ngram
listlengths 0
82k
|
|---|
[
"page_count = 0 page_fields[name] = part page_count += len(name) +",
"page in input: page_fields = dict() for name, content in",
"data[\"sender\"] == user or page_handlers[type][\"sender_only\"] is False: page_num = data[\"page\"]",
"def paginate_fields(input): pages = [] for page in input: page_fields",
"== \"PREV\": page_num -= 1 elif action == \"NEXT\": page_num",
"+ len(parts[0]) else: for i in range(len(parts)): part = parts[i]",
"len(suffix) lines = str(input).splitlines(keepends=True) pages = [] page = \"\"",
"page_count += len(name) + len(part) real_pages.append(page_fields) return real_pages def save_to_disc():",
"+= f\"{word} \" else: pages.append(f\"{prefix}{page}{suffix}\") page = line count =",
"if page_count + len(name) + len(parts[0]) > 4000: real_pages.append(page_fields) page_fields",
"= dict() for name, content in page.items(): page_fields[name] = paginate(content,",
"page = pages[page_num] return page, page_num def paginate(input, max_lines=20, max_chars=1900,",
"> 4000: real_pages.append(page_fields) page_fields = dict() page_count = 0 page_fields[name]",
"has_pages or len(emoji) > 0: data = { \"type\": type,",
"type = known_messages[message_id][\"type\"] if type in page_handlers.keys(): data = known_messages[message_id]",
"i in range(len(parts)): part = parts[i] name = f\"{base_name} ({i+1}/{len(parts)})\"",
"**kwargs): text, embed, has_pages, emoji = await page_handlers[type][\"init\"](ctx, **kwargs) message:",
"+ len(suffix) lines = str(input).splitlines(keepends=True) pages = [] page =",
"for name, parts in page.items(): base_name = name if len(parts)",
"count == max_lines: if page == \"\": # single 2k",
"pages.append(f\"{prefix}{page}{suffix}\") return pages def paginate_fields(input): pages = [] for page",
"def on_ready(bot): load_from_disc() def register(type, init, update, sender_only=False): page_handlers[type] =",
"page_handlers = dict() known_messages = dict() def on_ready(bot): load_from_disc() def",
"= dict() known_messages = dict() def on_ready(bot): load_from_disc() def register(type,",
"if len(page) + len(line) > max_chars or count == max_lines:",
"f\"{word} \" else: pages.append(f\"{prefix}{page}{suffix}\") page = line count = 1",
"= f\"{base_name} ({i+1}/{len(parts)})\" if page_count + len(name) + len(part) >",
"page_fields[name] = part page_count += len(name) + len(part) real_pages.append(page_fields) return",
"message: discord.Message = await ctx.channel.send(text, embed=embed) if has_pages or len(emoji)",
"word in words: if len(page) + len(word) > max_chars: pages.append(f\"{prefix}{page}{suffix}\")",
"\"NEXT\": page_num += 1 if page_num < 0: page_num =",
"for page in pages: page_count = 0 page_fields = dict()",
"name = f\"{base_name} ({i+1}/{len(parts)})\" if page_count + len(name) + len(part)",
"message.channel.get_message(data[\"trigger\"]) except discord.NotFound: trigger_message = None ctx = await bot.get_context(trigger_message)",
"= await message.channel.get_message(data[\"trigger\"]) except discord.NotFound: trigger_message = None ctx =",
"len(part) > 3000: real_pages.append(page_fields) page_fields = dict() page_count = 0",
"message, page_num, action, data) await message.edit(content=text, embed=embed) known_messages[message_id][\"page\"] = page",
"message_id in known_messages.keys(): type = known_messages[message_id][\"type\"] if type in page_handlers.keys():",
"from Util import Utils, Emoji, Translator page_handlers = dict() known_messages",
"0 page = pages[page_num] return page, page_num def paginate(input, max_lines=20,",
"page_count + len(name) + len(part) > 3000: real_pages.append(page_fields) page_fields =",
"1 else: page += line count += 1 pages.append(f\"{prefix}{page}{suffix}\") return",
"len(parts) is 1: if page_count + len(name) + len(parts[0]) >",
"= line.split(\" \") for word in words: if len(page) +",
"or count == max_lines: if page == \"\": # single",
"type_handler in page_handlers.keys(): del page_handlers[type_handler] async def create_new(type, ctx, **kwargs):",
"== \"\": # single 2k line, split smaller words =",
"known_messages[message_id] if data[\"sender\"] == user or page_handlers[type][\"sender_only\"] is False: page_num",
"words: if len(page) + len(word) > max_chars: pages.append(f\"{prefix}{page}{suffix}\") page =",
"**kwargs) message: discord.Message = await ctx.channel.send(text, embed=embed) if has_pages or",
"= len(pages) - 1 if page_num >= len(pages): page_num =",
"line count += 1 pages.append(f\"{prefix}{page}{suffix}\") return pages def paginate_fields(input): pages",
"else: page += f\"{word} \" else: pages.append(f\"{prefix}{page}{suffix}\") page = line",
"discord.Forbidden: await ctx.send( f\"{Emoji.get_chat_emoji('WARNING')} {Translator.translate('paginator_missing_perms', ctx, prev=Emoji.get_chat_emoji('LEFT'), next=Emoji.get_chat_emoji('RIGHT'))} {Emoji.get_chat_emoji('WARNING')}\") if",
"real_pages = [] for page in pages: page_count = 0",
"< 0: page_num = len(pages) - 1 if page_num >=",
"Util import Utils, Emoji, Translator page_handlers = dict() known_messages =",
"in page.items(): page_fields[name] = paginate(content, max_chars=1024) pages.append(page_fields) real_pages = []",
"if len(known_messages.keys()) > 500: del known_messages[list(known_messages.keys())[0]] save_to_disc() async def update(bot,",
"is not None else None text, embed, page = await",
"-= len(prefix) + len(suffix) lines = str(input).splitlines(keepends=True) pages = []",
"text, embed, page = await page_handlers[type][\"update\"](ctx, message, page_num, action, data)",
"del known_messages[list(known_messages.keys())[0]] save_to_disc() async def update(bot, message, action, user): message_id",
"parts[0] page_count += len(name) + len(parts[0]) else: for i in",
"page.items(): base_name = name if len(parts) is 1: if page_count",
"save_to_disc() return True return False def basic_pages(pages, page_num, action): if",
"type in page_handlers.keys(): data = known_messages[message_id] if data[\"sender\"] == user",
"\"page\": 0, \"trigger\": ctx.message.id, \"sender\": ctx.author.id } for k, v",
"Utils, Emoji, Translator page_handlers = dict() known_messages = dict() def",
"\" else: pages.append(f\"{prefix}{page}{suffix}\") page = line count = 1 else:",
"input: page_fields = dict() for name, content in page.items(): page_fields[name]",
"= dict() page_count = 0 page_fields[name] = parts[0] page_count +=",
"max_chars -= len(prefix) + len(suffix) lines = str(input).splitlines(keepends=True) pages =",
"len(line) > max_chars or count == max_lines: if page ==",
"pages.append(page_fields) real_pages = [] for page in pages: page_count =",
"page += f\"{word} \" else: pages.append(f\"{prefix}{page}{suffix}\") page = line count",
"count = 1 else: page += line count += 1",
"page_num < 0: page_num = len(pages) - 1 if page_num",
"ctx = await bot.get_context(trigger_message) if trigger_message is not None else",
"await page_handlers[type][\"init\"](ctx, **kwargs) message: discord.Message = await ctx.channel.send(text, embed=embed) if",
"str(message.id) if message_id in known_messages.keys(): type = known_messages[message_id][\"type\"] if type",
"return True return False def basic_pages(pages, page_num, action): if action",
"= await bot.get_context(trigger_message) if trigger_message is not None else None",
"def paginate(input, max_lines=20, max_chars=1900, prefix=\"\", suffix=\"\"): max_chars -= len(prefix) +",
"= data[\"page\"] try: trigger_message = await message.channel.get_message(data[\"trigger\"]) except discord.NotFound: trigger_message",
"in page_handlers.keys(): data = known_messages[message_id] if data[\"sender\"] == user or",
"page_fields = dict() page_count = 0 page_fields[name] = parts[0] page_count",
"in known_messages.keys(): type = known_messages[message_id][\"type\"] if type in page_handlers.keys(): data",
"= dict() for name, parts in page.items(): base_name = name",
"if page_num < 0: page_num = len(pages) - 1 if",
"data) await message.edit(content=text, embed=embed) known_messages[message_id][\"page\"] = page save_to_disc() return True",
"count += 1 pages.append(f\"{prefix}{page}{suffix}\") return pages def paginate_fields(input): pages =",
"= await page_handlers[type][\"init\"](ctx, **kwargs) message: discord.Message = await ctx.channel.send(text, embed=embed)",
"in words: if len(page) + len(word) > max_chars: pages.append(f\"{prefix}{page}{suffix}\") page",
"known_messages = dict() def on_ready(bot): load_from_disc() def register(type, init, update,",
"+= len(name) + len(parts[0]) else: for i in range(len(parts)): part",
"= 0 page_fields[name] = parts[0] page_count += len(name) + len(parts[0])",
"else: for i in range(len(parts)): part = parts[i] name =",
"Translator page_handlers = dict() known_messages = dict() def on_ready(bot): load_from_disc()",
"action, user): message_id = str(message.id) if message_id in known_messages.keys(): type",
"[] page = \"\" count = 0 for line in",
"smaller words = line.split(\" \") for word in words: if",
"split smaller words = line.split(\" \") for word in words:",
"await page_handlers[type][\"update\"](ctx, message, page_num, action, data) await message.edit(content=text, embed=embed) known_messages[message_id][\"page\"]",
"page = f\"{word} \" else: page += f\"{word} \" else:",
"= 0 page_fields[name] = part page_count += len(name) + len(part)",
"await message.add_reaction(Emoji.get_emoji('LEFT')) for e in emoji: await message.add_reaction(e) if has_pages:",
"ctx, **kwargs): text, embed, has_pages, emoji = await page_handlers[type][\"init\"](ctx, **kwargs)",
"page_count = 0 page_fields[name] = parts[0] page_count += len(name) +",
"-= 1 elif action == \"NEXT\": page_num += 1 if",
"message, action, user): message_id = str(message.id) if message_id in known_messages.keys():",
"await message.channel.get_message(data[\"trigger\"]) except discord.NotFound: trigger_message = None ctx = await",
"register(type, init, update, sender_only=False): page_handlers[type] = { \"init\": init, \"update\":",
"page == \"\": # single 2k line, split smaller words",
"== user or page_handlers[type][\"sender_only\"] is False: page_num = data[\"page\"] try:",
"return real_pages def save_to_disc(): Utils.saveToDisk(\"known_messages\", known_messages) def load_from_disc(): global known_messages",
"name, content in page.items(): page_fields[name] = paginate(content, max_chars=1024) pages.append(page_fields) real_pages",
"def update(bot, message, action, user): message_id = str(message.id) if message_id",
"e in emoji: await message.add_reaction(e) if has_pages: await message.add_reaction(Emoji.get_emoji('RIGHT')) except",
"if page_count + len(name) + len(part) > 3000: real_pages.append(page_fields) page_fields",
"len(name) + len(part) > 3000: real_pages.append(page_fields) page_fields = dict() page_count",
"True return False def basic_pages(pages, page_num, action): if action ==",
"dict() page_count = 0 page_fields[name] = parts[0] page_count += len(name)",
"page_handlers[type] = { \"init\": init, \"update\": update, \"sender_only\": sender_only }",
"create_new(type, ctx, **kwargs): text, embed, has_pages, emoji = await page_handlers[type][\"init\"](ctx,",
"try: if has_pages: await message.add_reaction(Emoji.get_emoji('LEFT')) for e in emoji: await",
"= \"\" count = 0 for line in lines: if",
"\" else: page += f\"{word} \" else: pages.append(f\"{prefix}{page}{suffix}\") page =",
"def basic_pages(pages, page_num, action): if action == \"PREV\": page_num -=",
"suffix=\"\"): max_chars -= len(prefix) + len(suffix) lines = str(input).splitlines(keepends=True) pages",
"lines: if len(page) + len(line) > max_chars or count ==",
"pages = [] page = \"\" count = 0 for",
"f\"{Emoji.get_chat_emoji('WARNING')} {Translator.translate('paginator_missing_perms', ctx, prev=Emoji.get_chat_emoji('LEFT'), next=Emoji.get_chat_emoji('RIGHT'))} {Emoji.get_chat_emoji('WARNING')}\") if len(known_messages.keys()) > 500:",
"v known_messages[str(message.id)] = data try: if has_pages: await message.add_reaction(Emoji.get_emoji('LEFT')) for",
"part page_count += len(name) + len(part) real_pages.append(page_fields) return real_pages def",
"len(pages) - 1 if page_num >= len(pages): page_num = 0",
"page_num -= 1 elif action == \"NEXT\": page_num += 1",
"line.split(\" \") for word in words: if len(page) + len(word)",
"= None ctx = await bot.get_context(trigger_message) if trigger_message is not",
"update(bot, message, action, user): message_id = str(message.id) if message_id in",
"paginate(content, max_chars=1024) pages.append(page_fields) real_pages = [] for page in pages:",
"await message.edit(content=text, embed=embed) known_messages[message_id][\"page\"] = page save_to_disc() return True return",
"try: trigger_message = await message.channel.get_message(data[\"trigger\"]) except discord.NotFound: trigger_message = None",
"= [] page = \"\" count = 0 for line",
"known_messages[message_id][\"page\"] = page save_to_disc() return True return False def basic_pages(pages,",
"discord.NotFound: trigger_message = None ctx = await bot.get_context(trigger_message) if trigger_message",
"1 if page_num < 0: page_num = len(pages) - 1",
"= known_messages[message_id][\"type\"] if type in page_handlers.keys(): data = known_messages[message_id] if",
"page_fields[name] = parts[0] page_count += len(name) + len(parts[0]) else: for",
"data = { \"type\": type, \"page\": 0, \"trigger\": ctx.message.id, \"sender\":",
"= dict() page_count = 0 page_fields[name] = part page_count +=",
"for line in lines: if len(page) + len(line) > max_chars",
"part = parts[i] name = f\"{base_name} ({i+1}/{len(parts)})\" if page_count +",
"embed=embed) known_messages[message_id][\"page\"] = page save_to_disc() return True return False def",
"return pages def paginate_fields(input): pages = [] for page in",
"return page, page_num def paginate(input, max_lines=20, max_chars=1900, prefix=\"\", suffix=\"\"): max_chars",
"== max_lines: if page == \"\": # single 2k line,",
"discord.Message = await ctx.channel.send(text, embed=embed) if has_pages or len(emoji) >",
"action == \"NEXT\": page_num += 1 if page_num < 0:",
"lines = str(input).splitlines(keepends=True) pages = [] page = \"\" count",
"page_num, action): if action == \"PREV\": page_num -= 1 elif",
"+= len(name) + len(part) real_pages.append(page_fields) return real_pages def save_to_disc(): Utils.saveToDisk(\"known_messages\",",
"trigger_message is not None else None text, embed, page =",
"1 if page_num >= len(pages): page_num = 0 page =",
"len(word) > max_chars: pages.append(f\"{prefix}{page}{suffix}\") page = f\"{word} \" else: page",
"len(pages): page_num = 0 page = pages[page_num] return page, page_num",
"page, page_num def paginate(input, max_lines=20, max_chars=1900, prefix=\"\", suffix=\"\"): max_chars -=",
"def register(type, init, update, sender_only=False): page_handlers[type] = { \"init\": init,",
"3000: real_pages.append(page_fields) page_fields = dict() page_count = 0 page_fields[name] =",
"pages.append(f\"{prefix}{page}{suffix}\") page = f\"{word} \" else: page += f\"{word} \"",
"async def create_new(type, ctx, **kwargs): text, embed, has_pages, emoji =",
"def save_to_disc(): Utils.saveToDisk(\"known_messages\", known_messages) def load_from_disc(): global known_messages known_messages =",
"known_messages[str(message.id)] = data try: if has_pages: await message.add_reaction(Emoji.get_emoji('LEFT')) for e",
"for word in words: if len(page) + len(word) > max_chars:",
"single 2k line, split smaller words = line.split(\" \") for",
"has_pages: await message.add_reaction(Emoji.get_emoji('RIGHT')) except discord.Forbidden: await ctx.send( f\"{Emoji.get_chat_emoji('WARNING')} {Translator.translate('paginator_missing_perms', ctx,",
"v in kwargs.items(): data[k] = v known_messages[str(message.id)] = data try:",
"emoji: await message.add_reaction(e) if has_pages: await message.add_reaction(Emoji.get_emoji('RIGHT')) except discord.Forbidden: await",
"message.add_reaction(Emoji.get_emoji('LEFT')) for e in emoji: await message.add_reaction(e) if has_pages: await",
"update, \"sender_only\": sender_only } def unregister(type_handler): if type_handler in page_handlers.keys():",
"line count = 1 else: page += line count +=",
"or page_handlers[type][\"sender_only\"] is False: page_num = data[\"page\"] try: trigger_message =",
"= v known_messages[str(message.id)] = data try: if has_pages: await message.add_reaction(Emoji.get_emoji('LEFT'))",
"+ len(part) > 3000: real_pages.append(page_fields) page_fields = dict() page_count =",
"bot.get_context(trigger_message) if trigger_message is not None else None text, embed,",
"del page_handlers[type_handler] async def create_new(type, ctx, **kwargs): text, embed, has_pages,",
"+ len(word) > max_chars: pages.append(f\"{prefix}{page}{suffix}\") page = f\"{word} \" else:",
"known_messages.keys(): type = known_messages[message_id][\"type\"] if type in page_handlers.keys(): data =",
"= str(input).splitlines(keepends=True) pages = [] page = \"\" count =",
"known_messages[message_id][\"type\"] if type in page_handlers.keys(): data = known_messages[message_id] if data[\"sender\"]",
"ctx, prev=Emoji.get_chat_emoji('LEFT'), next=Emoji.get_chat_emoji('RIGHT'))} {Emoji.get_chat_emoji('WARNING')}\") if len(known_messages.keys()) > 500: del known_messages[list(known_messages.keys())[0]]",
"user or page_handlers[type][\"sender_only\"] is False: page_num = data[\"page\"] try: trigger_message",
"+ len(name) + len(parts[0]) > 4000: real_pages.append(page_fields) page_fields = dict()",
"max_lines=20, max_chars=1900, prefix=\"\", suffix=\"\"): max_chars -= len(prefix) + len(suffix) lines",
"page_num = len(pages) - 1 if page_num >= len(pages): page_num",
"dict() known_messages = dict() def on_ready(bot): load_from_disc() def register(type, init,",
"> max_chars or count == max_lines: if page == \"\":",
"has_pages, emoji = await page_handlers[type][\"init\"](ctx, **kwargs) message: discord.Message = await",
"len(parts[0]) else: for i in range(len(parts)): part = parts[i] name",
"next=Emoji.get_chat_emoji('RIGHT'))} {Emoji.get_chat_emoji('WARNING')}\") if len(known_messages.keys()) > 500: del known_messages[list(known_messages.keys())[0]] save_to_disc() async",
"0 page_fields = dict() for name, parts in page.items(): base_name",
"\"PREV\": page_num -= 1 elif action == \"NEXT\": page_num +=",
"await bot.get_context(trigger_message) if trigger_message is not None else None text,",
"line in lines: if len(page) + len(line) > max_chars or",
"for k, v in kwargs.items(): data[k] = v known_messages[str(message.id)] =",
"} def unregister(type_handler): if type_handler in page_handlers.keys(): del page_handlers[type_handler] async",
"page_handlers.keys(): data = known_messages[message_id] if data[\"sender\"] == user or page_handlers[type][\"sender_only\"]",
"page = \"\" count = 0 for line in lines:",
"load_from_disc() def register(type, init, update, sender_only=False): page_handlers[type] = { \"init\":",
"embed, has_pages, emoji = await page_handlers[type][\"init\"](ctx, **kwargs) message: discord.Message =",
"= 1 else: page += line count += 1 pages.append(f\"{prefix}{page}{suffix}\")",
"None else None text, embed, page = await page_handlers[type][\"update\"](ctx, message,",
"action): if action == \"PREV\": page_num -= 1 elif action",
"= parts[0] page_count += len(name) + len(parts[0]) else: for i",
"f\"{base_name} ({i+1}/{len(parts)})\" if page_count + len(name) + len(part) > 3000:",
"> 3000: real_pages.append(page_fields) page_fields = dict() page_count = 0 page_fields[name]",
"basic_pages(pages, page_num, action): if action == \"PREV\": page_num -= 1",
"await ctx.channel.send(text, embed=embed) if has_pages or len(emoji) > 0: data",
"kwargs.items(): data[k] = v known_messages[str(message.id)] = data try: if has_pages:",
"= name if len(parts) is 1: if page_count + len(name)",
"known_messages[list(known_messages.keys())[0]] save_to_disc() async def update(bot, message, action, user): message_id =",
"on_ready(bot): load_from_disc() def register(type, init, update, sender_only=False): page_handlers[type] = {",
"page_count = 0 page_fields = dict() for name, parts in",
"sender_only=False): page_handlers[type] = { \"init\": init, \"update\": update, \"sender_only\": sender_only",
"page in pages: page_count = 0 page_fields = dict() for",
"len(name) + len(part) real_pages.append(page_fields) return real_pages def save_to_disc(): Utils.saveToDisk(\"known_messages\", known_messages)",
"{ \"type\": type, \"page\": 0, \"trigger\": ctx.message.id, \"sender\": ctx.author.id }",
"max_chars: pages.append(f\"{prefix}{page}{suffix}\") page = f\"{word} \" else: page += f\"{word}",
"page_handlers[type][\"init\"](ctx, **kwargs) message: discord.Message = await ctx.channel.send(text, embed=embed) if has_pages",
"{Emoji.get_chat_emoji('WARNING')}\") if len(known_messages.keys()) > 500: del known_messages[list(known_messages.keys())[0]] save_to_disc() async def",
"prefix=\"\", suffix=\"\"): max_chars -= len(prefix) + len(suffix) lines = str(input).splitlines(keepends=True)",
"in page.items(): base_name = name if len(parts) is 1: if",
"action, data) await message.edit(content=text, embed=embed) known_messages[message_id][\"page\"] = page save_to_disc() return",
"\"type\": type, \"page\": 0, \"trigger\": ctx.message.id, \"sender\": ctx.author.id } for",
"len(emoji) > 0: data = { \"type\": type, \"page\": 0,",
"len(known_messages.keys()) > 500: del known_messages[list(known_messages.keys())[0]] save_to_disc() async def update(bot, message,",
"data[\"page\"] try: trigger_message = await message.channel.get_message(data[\"trigger\"]) except discord.NotFound: trigger_message =",
"parts[i] name = f\"{base_name} ({i+1}/{len(parts)})\" if page_count + len(name) +",
"page_handlers[type_handler] async def create_new(type, ctx, **kwargs): text, embed, has_pages, emoji",
"save_to_disc(): Utils.saveToDisk(\"known_messages\", known_messages) def load_from_disc(): global known_messages known_messages = Utils.fetch_from_disk(\"known_messages\")",
"page_handlers[type][\"sender_only\"] is False: page_num = data[\"page\"] try: trigger_message = await",
"def unregister(type_handler): if type_handler in page_handlers.keys(): del page_handlers[type_handler] async def",
"f\"{word} \" else: page += f\"{word} \" else: pages.append(f\"{prefix}{page}{suffix}\") page",
"action == \"PREV\": page_num -= 1 elif action == \"NEXT\":",
"in range(len(parts)): part = parts[i] name = f\"{base_name} ({i+1}/{len(parts)})\" if",
"= part page_count += len(name) + len(part) real_pages.append(page_fields) return real_pages",
"= 0 for line in lines: if len(page) + len(line)",
"None ctx = await bot.get_context(trigger_message) if trigger_message is not None",
"if trigger_message is not None else None text, embed, page",
"init, \"update\": update, \"sender_only\": sender_only } def unregister(type_handler): if type_handler",
"0 page_fields[name] = part page_count += len(name) + len(part) real_pages.append(page_fields)",
"1 pages.append(f\"{prefix}{page}{suffix}\") return pages def paginate_fields(input): pages = [] for",
"False def basic_pages(pages, page_num, action): if action == \"PREV\": page_num",
"return False def basic_pages(pages, page_num, action): if action == \"PREV\":",
"\"sender\": ctx.author.id } for k, v in kwargs.items(): data[k] =",
"({i+1}/{len(parts)})\" if page_count + len(name) + len(part) > 3000: real_pages.append(page_fields)",
"dict() page_count = 0 page_fields[name] = part page_count += len(name)",
"if has_pages: await message.add_reaction(Emoji.get_emoji('LEFT')) for e in emoji: await message.add_reaction(e)",
"# single 2k line, split smaller words = line.split(\" \")",
"message_id = str(message.id) if message_id in known_messages.keys(): type = known_messages[message_id][\"type\"]",
"+= 1 if page_num < 0: page_num = len(pages) -",
"page_num += 1 if page_num < 0: page_num = len(pages)",
"+= 1 pages.append(f\"{prefix}{page}{suffix}\") return pages def paginate_fields(input): pages = []",
"max_lines: if page == \"\": # single 2k line, split",
"page_num = data[\"page\"] try: trigger_message = await message.channel.get_message(data[\"trigger\"]) except discord.NotFound:",
"page.items(): page_fields[name] = paginate(content, max_chars=1024) pages.append(page_fields) real_pages = [] for",
"if len(parts) is 1: if page_count + len(name) + len(parts[0])",
"len(name) + len(parts[0]) > 4000: real_pages.append(page_fields) page_fields = dict() page_count",
"} for k, v in kwargs.items(): data[k] = v known_messages[str(message.id)]",
"500: del known_messages[list(known_messages.keys())[0]] save_to_disc() async def update(bot, message, action, user):",
"{ \"init\": init, \"update\": update, \"sender_only\": sender_only } def unregister(type_handler):",
"sender_only } def unregister(type_handler): if type_handler in page_handlers.keys(): del page_handlers[type_handler]",
"in kwargs.items(): data[k] = v known_messages[str(message.id)] = data try: if",
"len(name) + len(parts[0]) else: for i in range(len(parts)): part =",
"= data try: if has_pages: await message.add_reaction(Emoji.get_emoji('LEFT')) for e in",
"= pages[page_num] return page, page_num def paginate(input, max_lines=20, max_chars=1900, prefix=\"\",",
"def create_new(type, ctx, **kwargs): text, embed, has_pages, emoji = await",
"0 for line in lines: if len(page) + len(line) >",
"\") for word in words: if len(page) + len(word) >",
"elif action == \"NEXT\": page_num += 1 if page_num <",
"await ctx.send( f\"{Emoji.get_chat_emoji('WARNING')} {Translator.translate('paginator_missing_perms', ctx, prev=Emoji.get_chat_emoji('LEFT'), next=Emoji.get_chat_emoji('RIGHT'))} {Emoji.get_chat_emoji('WARNING')}\") if len(known_messages.keys())",
"+ len(parts[0]) > 4000: real_pages.append(page_fields) page_fields = dict() page_count =",
"> 500: del known_messages[list(known_messages.keys())[0]] save_to_disc() async def update(bot, message, action,",
"is 1: if page_count + len(name) + len(parts[0]) > 4000:",
"trigger_message = await message.channel.get_message(data[\"trigger\"]) except discord.NotFound: trigger_message = None ctx",
"page_handlers.keys(): del page_handlers[type_handler] async def create_new(type, ctx, **kwargs): text, embed,",
"page_fields = dict() for name, content in page.items(): page_fields[name] =",
"in page_handlers.keys(): del page_handlers[type_handler] async def create_new(type, ctx, **kwargs): text,",
"== \"NEXT\": page_num += 1 if page_num < 0: page_num",
"if len(page) + len(word) > max_chars: pages.append(f\"{prefix}{page}{suffix}\") page = f\"{word}",
"if has_pages: await message.add_reaction(Emoji.get_emoji('RIGHT')) except discord.Forbidden: await ctx.send( f\"{Emoji.get_chat_emoji('WARNING')} {Translator.translate('paginator_missing_perms',",
"real_pages.append(page_fields) page_fields = dict() page_count = 0 page_fields[name] = parts[0]",
"k, v in kwargs.items(): data[k] = v known_messages[str(message.id)] = data",
"page += line count += 1 pages.append(f\"{prefix}{page}{suffix}\") return pages def",
"- 1 if page_num >= len(pages): page_num = 0 page",
"= line count = 1 else: page += line count",
"data try: if has_pages: await message.add_reaction(Emoji.get_emoji('LEFT')) for e in emoji:",
"pages[page_num] return page, page_num def paginate(input, max_lines=20, max_chars=1900, prefix=\"\", suffix=\"\"):",
"has_pages: await message.add_reaction(Emoji.get_emoji('LEFT')) for e in emoji: await message.add_reaction(e) if",
"page = await page_handlers[type][\"update\"](ctx, message, page_num, action, data) await message.edit(content=text,",
"max_chars=1024) pages.append(page_fields) real_pages = [] for page in pages: page_count",
"[] for page in input: page_fields = dict() for name,",
"except discord.Forbidden: await ctx.send( f\"{Emoji.get_chat_emoji('WARNING')} {Translator.translate('paginator_missing_perms', ctx, prev=Emoji.get_chat_emoji('LEFT'), next=Emoji.get_chat_emoji('RIGHT'))} {Emoji.get_chat_emoji('WARNING')}\")",
"[] for page in pages: page_count = 0 page_fields =",
"1: if page_count + len(name) + len(parts[0]) > 4000: real_pages.append(page_fields)",
"len(prefix) + len(suffix) lines = str(input).splitlines(keepends=True) pages = [] page",
"not None else None text, embed, page = await page_handlers[type][\"update\"](ctx,",
"user): message_id = str(message.id) if message_id in known_messages.keys(): type =",
"= dict() def on_ready(bot): load_from_disc() def register(type, init, update, sender_only=False):",
"if page == \"\": # single 2k line, split smaller",
"if message_id in known_messages.keys(): type = known_messages[message_id][\"type\"] if type in",
"page_count + len(name) + len(parts[0]) > 4000: real_pages.append(page_fields) page_fields =",
"page_num def paginate(input, max_lines=20, max_chars=1900, prefix=\"\", suffix=\"\"): max_chars -= len(prefix)",
"\"\": # single 2k line, split smaller words = line.split(\"",
"1 elif action == \"NEXT\": page_num += 1 if page_num",
"line, split smaller words = line.split(\" \") for word in",
"init, update, sender_only=False): page_handlers[type] = { \"init\": init, \"update\": update,",
"update, sender_only=False): page_handlers[type] = { \"init\": init, \"update\": update, \"sender_only\":",
"page_fields = dict() page_count = 0 page_fields[name] = part page_count",
"0 page_fields[name] = parts[0] page_count += len(name) + len(parts[0]) else:",
"max_chars or count == max_lines: if page == \"\": #",
"= { \"type\": type, \"page\": 0, \"trigger\": ctx.message.id, \"sender\": ctx.author.id",
"async def update(bot, message, action, user): message_id = str(message.id) if",
"page_handlers[type][\"update\"](ctx, message, page_num, action, data) await message.edit(content=text, embed=embed) known_messages[message_id][\"page\"] =",
"pages.append(f\"{prefix}{page}{suffix}\") page = line count = 1 else: page +=",
"else None text, embed, page = await page_handlers[type][\"update\"](ctx, message, page_num,",
"await message.add_reaction(Emoji.get_emoji('RIGHT')) except discord.Forbidden: await ctx.send( f\"{Emoji.get_chat_emoji('WARNING')} {Translator.translate('paginator_missing_perms', ctx, prev=Emoji.get_chat_emoji('LEFT'),",
"\"update\": update, \"sender_only\": sender_only } def unregister(type_handler): if type_handler in",
"for i in range(len(parts)): part = parts[i] name = f\"{base_name}",
"Emoji, Translator page_handlers = dict() known_messages = dict() def on_ready(bot):",
"dict() for name, content in page.items(): page_fields[name] = paginate(content, max_chars=1024)",
"real_pages def save_to_disc(): Utils.saveToDisk(\"known_messages\", known_messages) def load_from_disc(): global known_messages known_messages",
"> max_chars: pages.append(f\"{prefix}{page}{suffix}\") page = f\"{word} \" else: page +=",
"False: page_num = data[\"page\"] try: trigger_message = await message.channel.get_message(data[\"trigger\"]) except",
"page_fields[name] = paginate(content, max_chars=1024) pages.append(page_fields) real_pages = [] for page",
"dict() for name, parts in page.items(): base_name = name if",
"paginate_fields(input): pages = [] for page in input: page_fields =",
"= 0 page_fields = dict() for name, parts in page.items():",
"or len(emoji) > 0: data = { \"type\": type, \"page\":",
"if type_handler in page_handlers.keys(): del page_handlers[type_handler] async def create_new(type, ctx,",
"emoji = await page_handlers[type][\"init\"](ctx, **kwargs) message: discord.Message = await ctx.channel.send(text,",
"real_pages.append(page_fields) page_fields = dict() page_count = 0 page_fields[name] = part",
"else: page += line count += 1 pages.append(f\"{prefix}{page}{suffix}\") return pages",
"name, parts in page.items(): base_name = name if len(parts) is",
"pages = [] for page in input: page_fields = dict()",
"\"sender_only\": sender_only } def unregister(type_handler): if type_handler in page_handlers.keys(): del",
"= parts[i] name = f\"{base_name} ({i+1}/{len(parts)})\" if page_count + len(name)",
"data = known_messages[message_id] if data[\"sender\"] == user or page_handlers[type][\"sender_only\"] is",
"page save_to_disc() return True return False def basic_pages(pages, page_num, action):",
"range(len(parts)): part = parts[i] name = f\"{base_name} ({i+1}/{len(parts)})\" if page_count",
"pages def paginate_fields(input): pages = [] for page in input:",
"import Utils, Emoji, Translator page_handlers = dict() known_messages = dict()",
"page_count += len(name) + len(parts[0]) else: for i in range(len(parts)):",
"= [] for page in pages: page_count = 0 page_fields",
"type, \"page\": 0, \"trigger\": ctx.message.id, \"sender\": ctx.author.id } for k,",
"if has_pages or len(emoji) > 0: data = { \"type\":",
"discord from Util import Utils, Emoji, Translator page_handlers = dict()",
"= await page_handlers[type][\"update\"](ctx, message, page_num, action, data) await message.edit(content=text, embed=embed)",
"if page_num >= len(pages): page_num = 0 page = pages[page_num]",
"= 0 page = pages[page_num] return page, page_num def paginate(input,",
"is False: page_num = data[\"page\"] try: trigger_message = await message.channel.get_message(data[\"trigger\"])",
"message.add_reaction(e) if has_pages: await message.add_reaction(Emoji.get_emoji('RIGHT')) except discord.Forbidden: await ctx.send( f\"{Emoji.get_chat_emoji('WARNING')}",
"for name, content in page.items(): page_fields[name] = paginate(content, max_chars=1024) pages.append(page_fields)",
"page_num, action, data) await message.edit(content=text, embed=embed) known_messages[message_id][\"page\"] = page save_to_disc()",
"= page save_to_disc() return True return False def basic_pages(pages, page_num,",
"0: data = { \"type\": type, \"page\": 0, \"trigger\": ctx.message.id,",
"ctx.message.id, \"sender\": ctx.author.id } for k, v in kwargs.items(): data[k]",
"base_name = name if len(parts) is 1: if page_count +",
"words = line.split(\" \") for word in words: if len(page)",
"= await ctx.channel.send(text, embed=embed) if has_pages or len(emoji) > 0:",
"prev=Emoji.get_chat_emoji('LEFT'), next=Emoji.get_chat_emoji('RIGHT'))} {Emoji.get_chat_emoji('WARNING')}\") if len(known_messages.keys()) > 500: del known_messages[list(known_messages.keys())[0]] save_to_disc()",
"= paginate(content, max_chars=1024) pages.append(page_fields) real_pages = [] for page in",
"except discord.NotFound: trigger_message = None ctx = await bot.get_context(trigger_message) if",
"\"trigger\": ctx.message.id, \"sender\": ctx.author.id } for k, v in kwargs.items():",
"None text, embed, page = await page_handlers[type][\"update\"](ctx, message, page_num, action,",
"in input: page_fields = dict() for name, content in page.items():",
"= { \"init\": init, \"update\": update, \"sender_only\": sender_only } def",
"in pages: page_count = 0 page_fields = dict() for name,",
"else: pages.append(f\"{prefix}{page}{suffix}\") page = line count = 1 else: page",
"{Translator.translate('paginator_missing_perms', ctx, prev=Emoji.get_chat_emoji('LEFT'), next=Emoji.get_chat_emoji('RIGHT'))} {Emoji.get_chat_emoji('WARNING')}\") if len(known_messages.keys()) > 500: del",
"+ len(line) > max_chars or count == max_lines: if page",
"name if len(parts) is 1: if page_count + len(name) +",
"ctx.channel.send(text, embed=embed) if has_pages or len(emoji) > 0: data =",
"ctx.author.id } for k, v in kwargs.items(): data[k] = v",
"dict() def on_ready(bot): load_from_disc() def register(type, init, update, sender_only=False): page_handlers[type]",
"page_fields = dict() for name, parts in page.items(): base_name =",
"for e in emoji: await message.add_reaction(e) if has_pages: await message.add_reaction(Emoji.get_emoji('RIGHT'))",
"= [] for page in input: page_fields = dict() for",
"if data[\"sender\"] == user or page_handlers[type][\"sender_only\"] is False: page_num =",
"len(page) + len(word) > max_chars: pages.append(f\"{prefix}{page}{suffix}\") page = f\"{word} \"",
"real_pages.append(page_fields) return real_pages def save_to_disc(): Utils.saveToDisk(\"known_messages\", known_messages) def load_from_disc(): global",
"if type in page_handlers.keys(): data = known_messages[message_id] if data[\"sender\"] ==",
"await message.add_reaction(e) if has_pages: await message.add_reaction(Emoji.get_emoji('RIGHT')) except discord.Forbidden: await ctx.send(",
"4000: real_pages.append(page_fields) page_fields = dict() page_count = 0 page_fields[name] =",
"in emoji: await message.add_reaction(e) if has_pages: await message.add_reaction(Emoji.get_emoji('RIGHT')) except discord.Forbidden:",
"page_num >= len(pages): page_num = 0 page = pages[page_num] return",
"parts in page.items(): base_name = name if len(parts) is 1:",
"\"\" count = 0 for line in lines: if len(page)",
"len(page) + len(line) > max_chars or count == max_lines: if",
"= known_messages[message_id] if data[\"sender\"] == user or page_handlers[type][\"sender_only\"] is False:",
"import discord from Util import Utils, Emoji, Translator page_handlers =",
"+ len(part) real_pages.append(page_fields) return real_pages def save_to_disc(): Utils.saveToDisk(\"known_messages\", known_messages) def",
"max_chars=1900, prefix=\"\", suffix=\"\"): max_chars -= len(prefix) + len(suffix) lines =",
"if action == \"PREV\": page_num -= 1 elif action ==",
"= f\"{word} \" else: page += f\"{word} \" else: pages.append(f\"{prefix}{page}{suffix}\")",
"+= line count += 1 pages.append(f\"{prefix}{page}{suffix}\") return pages def paginate_fields(input):",
"unregister(type_handler): if type_handler in page_handlers.keys(): del page_handlers[type_handler] async def create_new(type,",
"\"init\": init, \"update\": update, \"sender_only\": sender_only } def unregister(type_handler): if",
"2k line, split smaller words = line.split(\" \") for word",
"save_to_disc() async def update(bot, message, action, user): message_id = str(message.id)",
"page = line count = 1 else: page += line",
"page_num = 0 page = pages[page_num] return page, page_num def",
"> 0: data = { \"type\": type, \"page\": 0, \"trigger\":",
"data[k] = v known_messages[str(message.id)] = data try: if has_pages: await",
"message.add_reaction(Emoji.get_emoji('RIGHT')) except discord.Forbidden: await ctx.send( f\"{Emoji.get_chat_emoji('WARNING')} {Translator.translate('paginator_missing_perms', ctx, prev=Emoji.get_chat_emoji('LEFT'), next=Emoji.get_chat_emoji('RIGHT'))}",
">= len(pages): page_num = 0 page = pages[page_num] return page,",
"message.edit(content=text, embed=embed) known_messages[message_id][\"page\"] = page save_to_disc() return True return False",
"count = 0 for line in lines: if len(page) +",
"embed=embed) if has_pages or len(emoji) > 0: data = {",
"content in page.items(): page_fields[name] = paginate(content, max_chars=1024) pages.append(page_fields) real_pages =",
"ctx.send( f\"{Emoji.get_chat_emoji('WARNING')} {Translator.translate('paginator_missing_perms', ctx, prev=Emoji.get_chat_emoji('LEFT'), next=Emoji.get_chat_emoji('RIGHT'))} {Emoji.get_chat_emoji('WARNING')}\") if len(known_messages.keys()) >",
"paginate(input, max_lines=20, max_chars=1900, prefix=\"\", suffix=\"\"): max_chars -= len(prefix) + len(suffix)",
"= str(message.id) if message_id in known_messages.keys(): type = known_messages[message_id][\"type\"] if",
"in lines: if len(page) + len(line) > max_chars or count",
"pages: page_count = 0 page_fields = dict() for name, parts",
"text, embed, has_pages, emoji = await page_handlers[type][\"init\"](ctx, **kwargs) message: discord.Message",
"0, \"trigger\": ctx.message.id, \"sender\": ctx.author.id } for k, v in",
"len(part) real_pages.append(page_fields) return real_pages def save_to_disc(): Utils.saveToDisk(\"known_messages\", known_messages) def load_from_disc():",
"+ len(name) + len(part) > 3000: real_pages.append(page_fields) page_fields = dict()",
"trigger_message = None ctx = await bot.get_context(trigger_message) if trigger_message is",
"embed, page = await page_handlers[type][\"update\"](ctx, message, page_num, action, data) await",
"len(parts[0]) > 4000: real_pages.append(page_fields) page_fields = dict() page_count = 0",
"for page in input: page_fields = dict() for name, content",
"str(input).splitlines(keepends=True) pages = [] page = \"\" count = 0",
"0: page_num = len(pages) - 1 if page_num >= len(pages):"
] |
[
"r.data def message_box(window, title, message): dialog = gtk.MessageDialog(window, 0, gtk.MESSAGE_INFO,",
"action == gtk.FILE_CHOOSER_ACTION_CREATE_FOLDER: buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_NEW,gtk.RESPONSE_OK) else: buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK) filew = gtk.FileChooserDialog(title=title, action=action,",
"def __init__(self, parent): self.goto_gui = gtk.glade.XML(parent.gladefile, root=\"GoToDialog\") self.dialog_box = self.goto_gui.get_widget(\"GoToDialog\")",
"is free software: you can redistribute it and/or modify #",
"gtk.RESPONSE_ACCEPT)) message_dialog.set_default_size(400, 300) message_dialog.connect(\"response\", close_dialog) scrolled_window = gtk.ScrolledWindow() message_dialog.vbox.add(scrolled_window) scrolled_window.show()",
"radio = gtk.RadioButton(prev_radio, choice) radio.connect(\"toggled\", self.radio_callback, choice) radio_box.pack_start(radio, False, False,",
"def message_box(window, title, message): dialog = gtk.MessageDialog(window, 0, gtk.MESSAGE_INFO, gtk.BUTTONS_OK,",
"self.window.show() #swindow = gtk.ScrolledWindow() #swindow.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) #self.window.add(swindow) #swindow.show() main_box =",
"within a scrolled window. \"\"\" message_dialog = gtk.Dialog(parent = parent,",
"import sys import traceback import gtk import pygtkconsole def prompt(parent,",
"for tbline in tb: tb_msg += tbline long_message(parent, tb_msg +",
"gtk.ScrolledWindow() message_dialog.vbox.add(scrolled_window) scrolled_window.show() scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS) text_view = gtk.TextView() scrolled_window.add(text_view) text_view.show()",
"response_id close_dialog(dialog, response_id) return def close_dialog(dialog, response_id = None): \"\"\"",
"gtk.MessageDialog(window, 0, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, message) dialog.set_title(title) dialog.connect(\"response\", close_dialog) dialog.run() class",
"WITHOUT ANY WARRANTY; without even the implied warranty of #",
"False, False, 0) radio.show() if prev_radio is None: radio.set_active(True) prev_radio",
"radio self.data = choices[0] gtk.main() def cleanup(self, widget, data=None): self.window.destroy()",
"main_box.pack_start(image, True, True, 0) image.show() label = gtk.Label(message) main_box.add(label) label.show()",
"is None: filew.set_current_folder_uri(\"file://\" + os.path.abspath(folder_uri)) for filtername in filter_names_and_patterns: filter",
"action=action, buttons=buttons) filew.set_default_response(gtk.RESPONSE_OK) if not folder_uri is None: filew.set_current_folder_uri(\"file://\" +",
"close_dialog(dialog, response_id) return def close_dialog(dialog, response_id = None): \"\"\" Signal",
"filter_names_and_patterns = {}, folder_uri = None): \"\"\" Utility function to",
"any later version. # # Diamond is distributed in the",
"self.key_press) self.window.set_title(title) self.window.set_position(gtk.WIN_POS_CENTER) if not logo is None: self.window.set_icon_from_file(logo) self.window.show()",
"return prompt_response.response def long_message(parent, message): \"\"\" Display a message prompt,",
"gtk.RESPONSE_CANCEL prompt_response.response = response_id close_dialog(dialog, response_id) return def close_dialog(dialog, response_id",
"#swindow.show() main_box = gtk.VBox(False, 0) self.window.add(main_box) main_box.show() if not logo",
"RadioDialog: def __init__(self, title, message, choices, logo): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)",
"under the terms of the GNU General Public License as",
"prompt_dialog = gtk.MessageDialog(parent, 0, type, gtk.BUTTONS_NONE, message) prompt_dialog.add_buttons(gtk.STOCK_YES, gtk.RESPONSE_YES, gtk.STOCK_NO,",
"text_view.set_property(\"editable\", False) text_view.set_property(\"height-request\", 180) text_view.set_property(\"width-request\", 240) message_dialog.run() return def error(parent,",
"parent, buttons = (gtk.STOCK_QUIT, gtk.RESPONSE_ACCEPT)) console_dialog.set_default_size(400, 300) console_dialog.connect(\"response\", close_dialog) stdout",
"def get_filename(title, action, filter_names_and_patterns = {}, folder_uri = None): \"\"\"",
"tbline in tb: tb_msg += tbline long_message(parent, tb_msg + \"\\n\"",
"warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.",
"text_view.show() text_view.get_buffer().set_text(message) text_view.set_cursor_visible(False) text_view.set_property(\"editable\", False) text_view.set_property(\"height-request\", 180) text_view.set_property(\"width-request\", 240) message_dialog.run()",
"True, 0) image.show() label = gtk.Label(message) main_box.add(label) label.show() radio_box =",
"def key_press(self, widget, event): if event.keyval == gtk.keysyms.Return: self.cleanup(None) def",
"with Diamond. If not, see <http://www.gnu.org/licenses/>. import os import sys",
"dialog. \"\"\" dialog.destroy() return def radio_dialog(title, message, choices, logo): r",
"filtername in filter_names_and_patterns: allfilter.add_pattern(filter_names_and_patterns[filtername]) filew.add_filter(allfilter) filter = gtk.FileFilter() filter.set_name(\"All files\")",
"or # (at your option) any later version. # #",
"console_dialog.run() sys.stdout = stdout sys.stderr = stderr return def prompt_response(dialog,",
"gtk import pygtkconsole def prompt(parent, message, type = gtk.MESSAGE_QUESTION, has_cancel",
"import os import sys import traceback import gtk import pygtkconsole",
"choice in choices: radio = gtk.RadioButton(prev_radio, choice) radio.connect(\"toggled\", self.radio_callback, choice)",
"contained within a scrolled window. \"\"\" message_dialog = gtk.Dialog(parent =",
"prompt_response) prompt_dialog.run() return prompt_response.response def long_message(parent, message): \"\"\" Display a",
"# GNU General Public License for more details. # #",
"Diamond. If not, see <http://www.gnu.org/licenses/>. import os import sys import",
"\"\"\" prompt_dialog = gtk.MessageDialog(parent, 0, type, gtk.BUTTONS_NONE, message) prompt_dialog.add_buttons(gtk.STOCK_YES, gtk.RESPONSE_YES,",
"prompt, with the message contained within a scrolled window. \"\"\"",
"gtk.RESPONSE_CANCEL) prompt_dialog.connect(\"response\", prompt_response) prompt_dialog.run() return prompt_response.response def long_message(parent, message): \"\"\"",
"key_press(self, widget, event): if event.keyval == gtk.keysyms.Return: self.cleanup(None) def radio_callback(self,",
"other functions. \"\"\" if response_id == gtk.RESPONSE_DELETE_EVENT: response_id = gtk.RESPONSE_CANCEL",
"title, message, choices, logo): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.connect(\"delete_event\", self.cleanup) self.window.connect(\"key_press_event\",",
"radio_box.pack_start(radio, False, False, 0) radio.show() if prev_radio is None: radio.set_active(True)",
"signals. Closes the dialog. \"\"\" dialog.destroy() return def radio_dialog(title, message,",
"Foundation, either version 3 of the License, or # (at",
"action, filter_names_and_patterns = {}, folder_uri = None): \"\"\" Utility function",
"return def close_dialog(dialog, response_id = None): \"\"\" Signal handler for",
"error_dialog.run() return def error_tb(parent, message): \"\"\" Display an error message,",
"message, type = gtk.MESSAGE_QUESTION, has_cancel = False): \"\"\" Display a",
"stderr = sys.stderr console_widget = pygtkconsole.GTKInterpreterConsole(locals) console_dialog.vbox.add(console_widget) console_widget.show() console_dialog.run() sys.stdout",
"class GoToDialog: def __init__(self, parent): self.goto_gui = gtk.glade.XML(parent.gladefile, root=\"GoToDialog\") self.dialog_box",
"= filew.get_filter().get_name() filew.destroy() return filename else: filew.destroy() return None def",
"tb = traceback.format_exception(sys.exc_info()[0] ,sys.exc_info()[1], sys.exc_info()[2]) tb_msg = \"\" for tbline",
"the last traceback. \"\"\" tb = traceback.format_exception(sys.exc_info()[0] ,sys.exc_info()[1], sys.exc_info()[2]) tb_msg",
"close = gtk.Button(stock=gtk.STOCK_OK) close.connect(\"clicked\", self.cleanup) main_box.pack_start(close, False, False, 0) close.show()",
"= gtk.HSeparator() main_box.pack_start(separator, False, True, 0) separator.show() close = gtk.Button(stock=gtk.STOCK_OK)",
"is part of Diamond. # # Diamond is free software:",
"filew = gtk.FileChooserDialog(title=title, action=action, buttons=buttons) filew.set_default_response(gtk.RESPONSE_OK) if not folder_uri is",
"filename else: filew.destroy() return None def console(parent, locals = None):",
"General Public License for more details. # # You should",
"gtk.MessageDialog(parent, 0, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK, message) error_dialog.connect(\"response\", close_dialog) error_dialog.run() return def",
"\"\"\" Utility function to get a filename. \"\"\" if action",
"A PARTICULAR PURPOSE. See the # GNU General Public License",
"the Free Software Foundation, either version 3 of the License,",
"\"\"\" dialog.destroy() return def radio_dialog(title, message, choices, logo): r =",
"gtk.BUTTONS_OK, message) error_dialog.connect(\"response\", close_dialog) error_dialog.run() return def error_tb(parent, message): \"\"\"",
"gtk.glade.XML(parent.gladefile, root=\"GoToDialog\") self.dialog_box = self.goto_gui.get_widget(\"GoToDialog\") self.dialog_box.set_modal(True) def run(self): signals =",
"choices[0] gtk.main() def cleanup(self, widget, data=None): self.window.destroy() gtk.main_quit() def key_press(self,",
"= \"\" for tbline in tb: tb_msg += tbline long_message(parent,",
"#!/usr/bin/env python # This file is part of Diamond. #",
"= {}, folder_uri = None): \"\"\" Utility function to get",
"root=\"GoToDialog\") self.dialog_box = self.goto_gui.get_widget(\"GoToDialog\") self.dialog_box.set_modal(True) def run(self): signals = {\"goto_activate\":",
"even the implied warranty of # MERCHANTABILITY or FITNESS FOR",
"os import sys import traceback import gtk import pygtkconsole def",
"free software: you can redistribute it and/or modify # it",
"or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU",
"the implied warranty of # MERCHANTABILITY or FITNESS FOR A",
"gtk.FILE_CHOOSER_ACTION_SAVE: buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK) elif action == gtk.FILE_CHOOSER_ACTION_CREATE_FOLDER: buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_NEW,gtk.RESPONSE_OK) else: buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK) filew",
"= sys.stdout stderr = sys.stderr console_widget = pygtkconsole.GTKInterpreterConsole(locals) console_dialog.vbox.add(console_widget) console_widget.show()",
"radio.set_active(True) prev_radio = radio self.data = choices[0] gtk.main() def cleanup(self,",
"widget, data=None): self.window.destroy() gtk.main_quit() def key_press(self, widget, event): if event.keyval",
"close_dialog) dialog.run() class RadioDialog: def __init__(self, title, message, choices, logo):",
"#self.window.add(swindow) #swindow.show() main_box = gtk.VBox(False, 0) self.window.add(main_box) main_box.show() if not",
"gtk.RESPONSE_DELETE_EVENT: response_id = gtk.RESPONSE_CANCEL prompt_response.response = response_id close_dialog(dialog, response_id) return",
"is None: radio.set_active(True) prev_radio = radio self.data = choices[0] gtk.main()",
"of the GNU General Public License as published by #",
"message_box(window, title, message): dialog = gtk.MessageDialog(window, 0, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, message)",
"filew.run() if result == gtk.RESPONSE_OK: filename = filew.get_filename() filtername =",
"can redistribute it and/or modify # it under the terms",
"Signal handler for dialog reponse or destroy signals. Closes the",
"by # the Free Software Foundation, either version 3 of",
"= response_id close_dialog(dialog, response_id) return def close_dialog(dialog, response_id = None):",
"along with Diamond. If not, see <http://www.gnu.org/licenses/>. import os import",
"error_dialog.connect(\"response\", close_dialog) error_dialog.run() return def error_tb(parent, message): \"\"\" Display an",
"main_box.pack_start(radio_box, True, True, 0) radio_box.show() separator = gtk.HSeparator() main_box.pack_start(separator, False,",
"= gtk.Image() image.set_from_file(logo) main_box.pack_start(image, True, True, 0) image.show() label =",
"self.goto_gui.get_widget(\"GoToDialog\") self.dialog_box.set_modal(True) def run(self): signals = {\"goto_activate\": self.on_goto_activate, \"cancel_activate\": self.on_cancel_activate}",
"def error(parent, message): \"\"\" Display an error message. \"\"\" error_dialog",
"filew.set_default_response(gtk.RESPONSE_OK) if not folder_uri is None: filew.set_current_folder_uri(\"file://\" + os.path.abspath(folder_uri)) for",
"dialog reponse or destroy signals. Closes the dialog. \"\"\" dialog.destroy()",
"radio.connect(\"toggled\", self.radio_callback, choice) radio_box.pack_start(radio, False, False, 0) radio.show() if prev_radio",
"= self.goto_gui.get_widget(\"GoToDialog\") self.dialog_box.set_modal(True) def run(self): signals = {\"goto_activate\": self.on_goto_activate, \"cancel_activate\":",
"== gtk.FILE_CHOOSER_ACTION_SAVE: buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK) elif action == gtk.FILE_CHOOSER_ACTION_CREATE_FOLDER: buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_NEW,gtk.RESPONSE_OK) else: buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK)",
"RadioDialog(title, message, choices, logo) return r.data def message_box(window, title, message):",
"buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK) filew = gtk.FileChooserDialog(title=title, action=action, buttons=buttons) filew.set_default_response(gtk.RESPONSE_OK) if not folder_uri",
"stdout = sys.stdout stderr = sys.stderr console_widget = pygtkconsole.GTKInterpreterConsole(locals) console_dialog.vbox.add(console_widget)",
"filename. \"\"\" if action == gtk.FILE_CHOOSER_ACTION_SAVE: buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK) elif action ==",
"License for more details. # # You should have received",
"Display an error message. \"\"\" error_dialog = gtk.MessageDialog(parent, 0, gtk.MESSAGE_WARNING,",
"close_dialog) stdout = sys.stdout stderr = sys.stderr console_widget = pygtkconsole.GTKInterpreterConsole(locals)",
"= gtk.Dialog(parent = parent, buttons = (gtk.STOCK_QUIT, gtk.RESPONSE_ACCEPT)) console_dialog.set_default_size(400, 300)",
"self.cleanup) main_box.pack_start(close, False, False, 0) close.show() prev_radio = None for",
"{}, folder_uri = None): \"\"\" Utility function to get a",
"filter.set_name(\"All files\") filter.add_pattern(\"*\") filew.add_filter(filter) result = filew.run() if result ==",
"for choice in choices: radio = gtk.RadioButton(prev_radio, choice) radio.connect(\"toggled\", self.radio_callback,",
"return None def console(parent, locals = None): \"\"\" Launch a",
"gtk.FileFilter() allfilter.set_name(\"All known files\") for filtername in filter_names_and_patterns: allfilter.add_pattern(filter_names_and_patterns[filtername]) filew.add_filter(allfilter)",
"buttons = (gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)) message_dialog.set_default_size(400, 300) message_dialog.connect(\"response\", close_dialog) scrolled_window =",
"the License, or # (at your option) any later version.",
"gtk.MESSAGE_WARNING, gtk.BUTTONS_OK, message) error_dialog.connect(\"response\", close_dialog) error_dialog.run() return def error_tb(parent, message):",
"Utility function to get a filename. \"\"\" if action ==",
"False): \"\"\" Display a simple Yes / No dialog. Returns",
"PARTICULAR PURPOSE. See the # GNU General Public License for",
"message, choices, logo): r = RadioDialog(title, message, choices, logo) return",
"filtername in filter_names_and_patterns: filter = gtk.FileFilter() filter.set_name(filtername) filter.add_pattern(filter_names_and_patterns[filtername]) filew.add_filter(filter) allfilter",
"filter.add_pattern(\"*\") filew.add_filter(filter) result = filew.run() if result == gtk.RESPONSE_OK: filename",
"General Public License # along with Diamond. If not, see",
"modify # it under the terms of the GNU General",
"terms of the GNU General Public License as published by",
"class RadioDialog: def __init__(self, title, message, choices, logo): self.window =",
"function to get a filename. \"\"\" if action == gtk.FILE_CHOOSER_ACTION_SAVE:",
"/ No dialog. Returns one of gtk.RESPONSE_{YES,NO,CANCEL}. \"\"\" prompt_dialog =",
"details. # # You should have received a copy of",
"0, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK, message) error_dialog.connect(\"response\", close_dialog) error_dialog.run() return def error_tb(parent,",
"return def radio_dialog(title, message, choices, logo): r = RadioDialog(title, message,",
"filter.add_pattern(filter_names_and_patterns[filtername]) filew.add_filter(filter) allfilter = gtk.FileFilter() allfilter.set_name(\"All known files\") for filtername",
"def __init__(self, title, message, choices, logo): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.connect(\"delete_event\",",
"prompt_response.response def long_message(parent, message): \"\"\" Display a message prompt, with",
",sys.exc_info()[1], sys.exc_info()[2]) tb_msg = \"\" for tbline in tb: tb_msg",
"return def get_filename(title, action, filter_names_and_patterns = {}, folder_uri = None):",
"def radio_dialog(title, message, choices, logo): r = RadioDialog(title, message, choices,",
"close_dialog) error_dialog.run() return def error_tb(parent, message): \"\"\" Display an error",
"Public License # along with Diamond. If not, see <http://www.gnu.org/licenses/>.",
"published by # the Free Software Foundation, either version 3",
"= gtk.FileChooserDialog(title=title, action=action, buttons=buttons) filew.set_default_response(gtk.RESPONSE_OK) if not folder_uri is None:",
"filew.destroy() return None def console(parent, locals = None): \"\"\" Launch",
"#swindow.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) #self.window.add(swindow) #swindow.show() main_box = gtk.VBox(False, 0) self.window.add(main_box) main_box.show()",
"main_box = gtk.VBox(False, 0) self.window.add(main_box) main_box.show() if not logo is",
"is None: self.window.set_icon_from_file(logo) self.window.show() #swindow = gtk.ScrolledWindow() #swindow.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) #self.window.add(swindow)",
"filter_names_and_patterns: filter = gtk.FileFilter() filter.set_name(filtername) filter.add_pattern(filter_names_and_patterns[filtername]) filew.add_filter(filter) allfilter = gtk.FileFilter()",
"Launch a python console. \"\"\" console_dialog = gtk.Dialog(parent = parent,",
"is None: image = gtk.Image() image.set_from_file(logo) main_box.pack_start(image, True, True, 0)",
"import pygtkconsole def prompt(parent, message, type = gtk.MESSAGE_QUESTION, has_cancel =",
"response_id = gtk.RESPONSE_CANCEL prompt_response.response = response_id close_dialog(dialog, response_id) return def",
"signals. Stores the dialog response in the function namespace, to",
"namespace, to allow response return in other functions. \"\"\" if",
"= gtk.FileFilter() filter.set_name(filtername) filter.add_pattern(filter_names_and_patterns[filtername]) filew.add_filter(filter) allfilter = gtk.FileFilter() allfilter.set_name(\"All known",
"= gtk.RadioButton(prev_radio, choice) radio.connect(\"toggled\", self.radio_callback, choice) radio_box.pack_start(radio, False, False, 0)",
"handler for dialog reponse or destroy signals. Closes the dialog.",
"= filew.get_filename() filtername = filew.get_filter().get_name() filew.destroy() return filename else: filew.destroy()",
"received a copy of the GNU General Public License #",
"not, see <http://www.gnu.org/licenses/>. import os import sys import traceback import",
"Display a simple Yes / No dialog. Returns one of",
"\"\\n\" + message) return def get_filename(title, action, filter_names_and_patterns = {},",
"None def console(parent, locals = None): \"\"\" Launch a python",
"return def prompt_response(dialog, response_id): \"\"\" Signal handler for dialog response",
"a filename. \"\"\" if action == gtk.FILE_CHOOSER_ACTION_SAVE: buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK) elif action",
"= False): \"\"\" Display a simple Yes / No dialog.",
"response return in other functions. \"\"\" if response_id == gtk.RESPONSE_DELETE_EVENT:",
"License as published by # the Free Software Foundation, either",
"buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_NEW,gtk.RESPONSE_OK) else: buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK) filew = gtk.FileChooserDialog(title=title, action=action, buttons=buttons) filew.set_default_response(gtk.RESPONSE_OK) if",
"message, together with the last traceback. \"\"\" tb = traceback.format_exception(sys.exc_info()[0]",
"See the # GNU General Public License for more details.",
"message): \"\"\" Display an error message, together with the last",
"self.goto_gui = gtk.glade.XML(parent.gladefile, root=\"GoToDialog\") self.dialog_box = self.goto_gui.get_widget(\"GoToDialog\") self.dialog_box.set_modal(True) def run(self):",
"text_view.set_property(\"width-request\", 240) message_dialog.run() return def error(parent, message): \"\"\" Display an",
"one of gtk.RESPONSE_{YES,NO,CANCEL}. \"\"\" prompt_dialog = gtk.MessageDialog(parent, 0, type, gtk.BUTTONS_NONE,",
"logo) return r.data def message_box(window, title, message): dialog = gtk.MessageDialog(window,",
"\"\"\" console_dialog = gtk.Dialog(parent = parent, buttons = (gtk.STOCK_QUIT, gtk.RESPONSE_ACCEPT))",
"if result == gtk.RESPONSE_OK: filename = filew.get_filename() filtername = filew.get_filter().get_name()",
"that it will be useful, # but WITHOUT ANY WARRANTY;",
"if action == gtk.FILE_CHOOSER_ACTION_SAVE: buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK) elif action == gtk.FILE_CHOOSER_ACTION_CREATE_FOLDER: buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_NEW,gtk.RESPONSE_OK)",
"dialog.set_title(title) dialog.connect(\"response\", close_dialog) dialog.run() class RadioDialog: def __init__(self, title, message,",
"0) radio.show() if prev_radio is None: radio.set_active(True) prev_radio = radio",
"\"\"\" if response_id == gtk.RESPONSE_DELETE_EVENT: response_id = gtk.RESPONSE_CANCEL prompt_response.response =",
"# # Diamond is free software: you can redistribute it",
"either version 3 of the License, or # (at your",
"self.window.set_title(title) self.window.set_position(gtk.WIN_POS_CENTER) if not logo is None: self.window.set_icon_from_file(logo) self.window.show() #swindow",
"gtk.MESSAGE_QUESTION, has_cancel = False): \"\"\" Display a simple Yes /",
"console_dialog = gtk.Dialog(parent = parent, buttons = (gtk.STOCK_QUIT, gtk.RESPONSE_ACCEPT)) console_dialog.set_default_size(400,",
"later version. # # Diamond is distributed in the hope",
"gtk.Dialog(parent = parent, buttons = (gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)) message_dialog.set_default_size(400, 300) message_dialog.connect(\"response\",",
"more details. # # You should have received a copy",
"self.window.destroy() gtk.main_quit() def key_press(self, widget, event): if event.keyval == gtk.keysyms.Return:",
"None): \"\"\" Signal handler for dialog reponse or destroy signals.",
"= sys.stderr console_widget = pygtkconsole.GTKInterpreterConsole(locals) console_dialog.vbox.add(console_widget) console_widget.show() console_dialog.run() sys.stdout =",
"be useful, # but WITHOUT ANY WARRANTY; without even the",
"handler for dialog response signals. Stores the dialog response in",
"gtk.MessageDialog(parent, 0, type, gtk.BUTTONS_NONE, message) prompt_dialog.add_buttons(gtk.STOCK_YES, gtk.RESPONSE_YES, gtk.STOCK_NO, gtk.RESPONSE_NO) if",
"= gtk.FileFilter() allfilter.set_name(\"All known files\") for filtername in filter_names_and_patterns: allfilter.add_pattern(filter_names_and_patterns[filtername])",
"event.keyval == gtk.keysyms.Return: self.cleanup(None) def radio_callback(self, widget, data): self.data =",
"gtk.POLICY_ALWAYS) text_view = gtk.TextView() scrolled_window.add(text_view) text_view.show() text_view.get_buffer().set_text(message) text_view.set_cursor_visible(False) text_view.set_property(\"editable\", False)",
"self.window.connect(\"key_press_event\", self.key_press) self.window.set_title(title) self.window.set_position(gtk.WIN_POS_CENTER) if not logo is None: self.window.set_icon_from_file(logo)",
"= None for choice in choices: radio = gtk.RadioButton(prev_radio, choice)",
"simple Yes / No dialog. Returns one of gtk.RESPONSE_{YES,NO,CANCEL}. \"\"\"",
"def prompt_response(dialog, response_id): \"\"\" Signal handler for dialog response signals.",
"Diamond. # # Diamond is free software: you can redistribute",
"last traceback. \"\"\" tb = traceback.format_exception(sys.exc_info()[0] ,sys.exc_info()[1], sys.exc_info()[2]) tb_msg =",
"text_view.set_cursor_visible(False) text_view.set_property(\"editable\", False) text_view.set_property(\"height-request\", 180) text_view.set_property(\"width-request\", 240) message_dialog.run() return def",
"# This file is part of Diamond. # # Diamond",
"Diamond is distributed in the hope that it will be",
"None): \"\"\" Launch a python console. \"\"\" console_dialog = gtk.Dialog(parent",
"False, 0) close.show() prev_radio = None for choice in choices:",
"10) main_box.pack_start(radio_box, True, True, 0) radio_box.show() separator = gtk.HSeparator() main_box.pack_start(separator,",
"__init__(self, parent): self.goto_gui = gtk.glade.XML(parent.gladefile, root=\"GoToDialog\") self.dialog_box = self.goto_gui.get_widget(\"GoToDialog\") self.dialog_box.set_modal(True)",
"\"\"\" Display an error message, together with the last traceback.",
"main_box.pack_start(separator, False, True, 0) separator.show() close = gtk.Button(stock=gtk.STOCK_OK) close.connect(\"clicked\", self.cleanup)",
"\"\" for tbline in tb: tb_msg += tbline long_message(parent, tb_msg",
"python # This file is part of Diamond. # #",
"label = gtk.Label(message) main_box.add(label) label.show() radio_box = gtk.VBox(False, 10) main_box.pack_start(radio_box,",
"Closes the dialog. \"\"\" dialog.destroy() return def radio_dialog(title, message, choices,",
"self.on_goto_activate, \"cancel_activate\": self.on_cancel_activate} self.goto_gui.signal_autoconnect(signals) self.dialog_box.show() return \"\" def on_goto_activate(self, widget=None):",
"GNU General Public License # along with Diamond. If not,",
"= choices[0] gtk.main() def cleanup(self, widget, data=None): self.window.destroy() gtk.main_quit() def",
"filter.set_name(filtername) filter.add_pattern(filter_names_and_patterns[filtername]) filew.add_filter(filter) allfilter = gtk.FileFilter() allfilter.set_name(\"All known files\") for",
"True, True, 0) image.show() label = gtk.Label(message) main_box.add(label) label.show() radio_box",
"gtk.FileFilter() filter.set_name(\"All files\") filter.add_pattern(\"*\") filew.add_filter(filter) result = filew.run() if result",
"= gtk.Label(message) main_box.add(label) label.show() radio_box = gtk.VBox(False, 10) main_box.pack_start(radio_box, True,",
"= parent, buttons = (gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)) message_dialog.set_default_size(400, 300) message_dialog.connect(\"response\", close_dialog)",
"gtk.MESSAGE_INFO, gtk.BUTTONS_OK, message) dialog.set_title(title) dialog.connect(\"response\", close_dialog) dialog.run() class RadioDialog: def",
"main_box.pack_start(close, False, False, 0) close.show() prev_radio = None for choice",
"long_message(parent, tb_msg + \"\\n\" + message) return def get_filename(title, action,",
"text_view.set_property(\"height-request\", 180) text_view.set_property(\"width-request\", 240) message_dialog.run() return def error(parent, message): \"\"\"",
"= data class GoToDialog: def __init__(self, parent): self.goto_gui = gtk.glade.XML(parent.gladefile,",
"== gtk.RESPONSE_OK: filename = filew.get_filename() filtername = filew.get_filter().get_name() filew.destroy() return",
"# but WITHOUT ANY WARRANTY; without even the implied warranty",
"def on_goto_activate(self, widget=None): print \"goto\" def on_cancel_activate(self, widget=None): print \"cancel\"",
"Free Software Foundation, either version 3 of the License, or",
"r = RadioDialog(title, message, choices, logo) return r.data def message_box(window,",
"if has_cancel: prompt_dialog.add_buttons(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL) prompt_dialog.connect(\"response\", prompt_response) prompt_dialog.run() return prompt_response.response def",
"= RadioDialog(title, message, choices, logo) return r.data def message_box(window, title,",
"response_id) return def close_dialog(dialog, response_id = None): \"\"\" Signal handler",
"and/or modify # it under the terms of the GNU",
"implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR",
"def run(self): signals = {\"goto_activate\": self.on_goto_activate, \"cancel_activate\": self.on_cancel_activate} self.goto_gui.signal_autoconnect(signals) self.dialog_box.show()",
"gtk.BUTTONS_NONE, message) prompt_dialog.add_buttons(gtk.STOCK_YES, gtk.RESPONSE_YES, gtk.STOCK_NO, gtk.RESPONSE_NO) if has_cancel: prompt_dialog.add_buttons(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)",
"action == gtk.FILE_CHOOSER_ACTION_SAVE: buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK) elif action == gtk.FILE_CHOOSER_ACTION_CREATE_FOLDER: buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_NEW,gtk.RESPONSE_OK) else:",
"dialog response in the function namespace, to allow response return",
"if prev_radio is None: radio.set_active(True) prev_radio = radio self.data =",
"it and/or modify # it under the terms of the",
"main_box.add(label) label.show() radio_box = gtk.VBox(False, 10) main_box.pack_start(radio_box, True, True, 0)",
"console_widget.show() console_dialog.run() sys.stdout = stdout sys.stderr = stderr return def",
"main_box.show() if not logo is None: image = gtk.Image() image.set_from_file(logo)",
"version. # # Diamond is distributed in the hope that",
"prompt_response(dialog, response_id): \"\"\" Signal handler for dialog response signals. Stores",
"it will be useful, # but WITHOUT ANY WARRANTY; without",
"return def error(parent, message): \"\"\" Display an error message. \"\"\"",
"logo is None: self.window.set_icon_from_file(logo) self.window.show() #swindow = gtk.ScrolledWindow() #swindow.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)",
"\"\"\" message_dialog = gtk.Dialog(parent = parent, buttons = (gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))",
"filew.get_filter().get_name() filew.destroy() return filename else: filew.destroy() return None def console(parent,",
"gtk.Image() image.set_from_file(logo) main_box.pack_start(image, True, True, 0) image.show() label = gtk.Label(message)",
"= filew.run() if result == gtk.RESPONSE_OK: filename = filew.get_filename() filtername",
"close.show() prev_radio = None for choice in choices: radio =",
"a python console. \"\"\" console_dialog = gtk.Dialog(parent = parent, buttons",
"# it under the terms of the GNU General Public",
"== gtk.FILE_CHOOSER_ACTION_CREATE_FOLDER: buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_NEW,gtk.RESPONSE_OK) else: buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK) filew = gtk.FileChooserDialog(title=title, action=action, buttons=buttons)",
"destroy signals. Closes the dialog. \"\"\" dialog.destroy() return def radio_dialog(title,",
"self.on_cancel_activate} self.goto_gui.signal_autoconnect(signals) self.dialog_box.show() return \"\" def on_goto_activate(self, widget=None): print \"goto\"",
"of the License, or # (at your option) any later",
"part of Diamond. # # Diamond is free software: you",
"Stores the dialog response in the function namespace, to allow",
"hope that it will be useful, # but WITHOUT ANY",
"it under the terms of the GNU General Public License",
"the function namespace, to allow response return in other functions.",
"gtk.Label(message) main_box.add(label) label.show() radio_box = gtk.VBox(False, 10) main_box.pack_start(radio_box, True, True,",
"= {\"goto_activate\": self.on_goto_activate, \"cancel_activate\": self.on_cancel_activate} self.goto_gui.signal_autoconnect(signals) self.dialog_box.show() return \"\" def",
"the GNU General Public License as published by # the",
"filter_names_and_patterns: allfilter.add_pattern(filter_names_and_patterns[filtername]) filew.add_filter(allfilter) filter = gtk.FileFilter() filter.set_name(\"All files\") filter.add_pattern(\"*\") filew.add_filter(filter)",
"prev_radio = None for choice in choices: radio = gtk.RadioButton(prev_radio,",
"gtk.main() def cleanup(self, widget, data=None): self.window.destroy() gtk.main_quit() def key_press(self, widget,",
"= gtk.MessageDialog(parent, 0, type, gtk.BUTTONS_NONE, message) prompt_dialog.add_buttons(gtk.STOCK_YES, gtk.RESPONSE_YES, gtk.STOCK_NO, gtk.RESPONSE_NO)",
"in choices: radio = gtk.RadioButton(prev_radio, choice) radio.connect(\"toggled\", self.radio_callback, choice) radio_box.pack_start(radio,",
"0) radio_box.show() separator = gtk.HSeparator() main_box.pack_start(separator, False, True, 0) separator.show()",
"= gtk.RESPONSE_CANCEL prompt_response.response = response_id close_dialog(dialog, response_id) return def close_dialog(dialog,",
"stdout sys.stderr = stderr return def prompt_response(dialog, response_id): \"\"\" Signal",
"FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General",
"traceback. \"\"\" tb = traceback.format_exception(sys.exc_info()[0] ,sys.exc_info()[1], sys.exc_info()[2]) tb_msg = \"\"",
"event): if event.keyval == gtk.keysyms.Return: self.cleanup(None) def radio_callback(self, widget, data):",
"your option) any later version. # # Diamond is distributed",
"General Public License as published by # the Free Software",
"option) any later version. # # Diamond is distributed in",
"a scrolled window. \"\"\" message_dialog = gtk.Dialog(parent = parent, buttons",
"# (at your option) any later version. # # Diamond",
"filew.add_filter(filter) allfilter = gtk.FileFilter() allfilter.set_name(\"All known files\") for filtername in",
"will be useful, # but WITHOUT ANY WARRANTY; without even",
"filter = gtk.FileFilter() filter.set_name(\"All files\") filter.add_pattern(\"*\") filew.add_filter(filter) result = filew.run()",
"logo): r = RadioDialog(title, message, choices, logo) return r.data def",
"data=None): self.window.destroy() gtk.main_quit() def key_press(self, widget, event): if event.keyval ==",
"or destroy signals. Closes the dialog. \"\"\" dialog.destroy() return def",
"image.set_from_file(logo) main_box.pack_start(image, True, True, 0) image.show() label = gtk.Label(message) main_box.add(label)",
"self.dialog_box.set_modal(True) def run(self): signals = {\"goto_activate\": self.on_goto_activate, \"cancel_activate\": self.on_cancel_activate} self.goto_gui.signal_autoconnect(signals)",
"stderr return def prompt_response(dialog, response_id): \"\"\" Signal handler for dialog",
"an error message, together with the last traceback. \"\"\" tb",
"error message. \"\"\" error_dialog = gtk.MessageDialog(parent, 0, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK, message)",
"scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS) text_view = gtk.TextView() scrolled_window.add(text_view) text_view.show() text_view.get_buffer().set_text(message) text_view.set_cursor_visible(False) text_view.set_property(\"editable\",",
"self.cleanup(None) def radio_callback(self, widget, data): self.data = data class GoToDialog:",
"0) separator.show() close = gtk.Button(stock=gtk.STOCK_OK) close.connect(\"clicked\", self.cleanup) main_box.pack_start(close, False, False,",
"= gtk.Button(stock=gtk.STOCK_OK) close.connect(\"clicked\", self.cleanup) main_box.pack_start(close, False, False, 0) close.show() prev_radio",
"message_dialog.set_default_size(400, 300) message_dialog.connect(\"response\", close_dialog) scrolled_window = gtk.ScrolledWindow() message_dialog.vbox.add(scrolled_window) scrolled_window.show() scrolled_window.set_policy(gtk.POLICY_AUTOMATIC,",
"sys.exc_info()[2]) tb_msg = \"\" for tbline in tb: tb_msg +=",
"files\") for filtername in filter_names_and_patterns: allfilter.add_pattern(filter_names_and_patterns[filtername]) filew.add_filter(allfilter) filter = gtk.FileFilter()",
"self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.connect(\"delete_event\", self.cleanup) self.window.connect(\"key_press_event\", self.key_press) self.window.set_title(title) self.window.set_position(gtk.WIN_POS_CENTER) if",
"filew.add_filter(filter) result = filew.run() if result == gtk.RESPONSE_OK: filename =",
"choices, logo) return r.data def message_box(window, title, message): dialog =",
"PURPOSE. See the # GNU General Public License for more",
"if not logo is None: image = gtk.Image() image.set_from_file(logo) main_box.pack_start(image,",
"allfilter.add_pattern(filter_names_and_patterns[filtername]) filew.add_filter(allfilter) filter = gtk.FileFilter() filter.set_name(\"All files\") filter.add_pattern(\"*\") filew.add_filter(filter) result",
"gtk.FileChooserDialog(title=title, action=action, buttons=buttons) filew.set_default_response(gtk.RESPONSE_OK) if not folder_uri is None: filew.set_current_folder_uri(\"file://\"",
"FOR A PARTICULAR PURPOSE. See the # GNU General Public",
"else: buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK) filew = gtk.FileChooserDialog(title=title, action=action, buttons=buttons) filew.set_default_response(gtk.RESPONSE_OK) if not",
"dialog.destroy() return def radio_dialog(title, message, choices, logo): r = RadioDialog(title,",
"the # GNU General Public License for more details. #",
"message_dialog.vbox.add(scrolled_window) scrolled_window.show() scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS) text_view = gtk.TextView() scrolled_window.add(text_view) text_view.show() text_view.get_buffer().set_text(message)",
"# Diamond is distributed in the hope that it will",
"\"\"\" Display an error message. \"\"\" error_dialog = gtk.MessageDialog(parent, 0,",
"+= tbline long_message(parent, tb_msg + \"\\n\" + message) return def",
"message. \"\"\" error_dialog = gtk.MessageDialog(parent, 0, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK, message) error_dialog.connect(\"response\",",
"def radio_callback(self, widget, data): self.data = data class GoToDialog: def",
"prompt_response.response = response_id close_dialog(dialog, response_id) return def close_dialog(dialog, response_id =",
"for more details. # # You should have received a",
"redistribute it and/or modify # it under the terms of",
"gtk.HSeparator() main_box.pack_start(separator, False, True, 0) separator.show() close = gtk.Button(stock=gtk.STOCK_OK) close.connect(\"clicked\",",
"console_widget = pygtkconsole.GTKInterpreterConsole(locals) console_dialog.vbox.add(console_widget) console_widget.show() console_dialog.run() sys.stdout = stdout sys.stderr",
"self.window.add(main_box) main_box.show() if not logo is None: image = gtk.Image()",
"self.data = choices[0] gtk.main() def cleanup(self, widget, data=None): self.window.destroy() gtk.main_quit()",
"elif action == gtk.FILE_CHOOSER_ACTION_CREATE_FOLDER: buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_NEW,gtk.RESPONSE_OK) else: buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK) filew = gtk.FileChooserDialog(title=title,",
"== gtk.RESPONSE_DELETE_EVENT: response_id = gtk.RESPONSE_CANCEL prompt_response.response = response_id close_dialog(dialog, response_id)",
"the GNU General Public License # along with Diamond. If",
"os.path.abspath(folder_uri)) for filtername in filter_names_and_patterns: filter = gtk.FileFilter() filter.set_name(filtername) filter.add_pattern(filter_names_and_patterns[filtername])",
"get a filename. \"\"\" if action == gtk.FILE_CHOOSER_ACTION_SAVE: buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK) elif",
"radio_callback(self, widget, data): self.data = data class GoToDialog: def __init__(self,",
"+ message) return def get_filename(title, action, filter_names_and_patterns = {}, folder_uri",
"message_dialog = gtk.Dialog(parent = parent, buttons = (gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)) message_dialog.set_default_size(400,",
"logo): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.connect(\"delete_event\", self.cleanup) self.window.connect(\"key_press_event\", self.key_press) self.window.set_title(title) self.window.set_position(gtk.WIN_POS_CENTER)",
"None for choice in choices: radio = gtk.RadioButton(prev_radio, choice) radio.connect(\"toggled\",",
"dialog = gtk.MessageDialog(window, 0, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, message) dialog.set_title(title) dialog.connect(\"response\", close_dialog)",
"ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY",
"\"\"\" error_dialog = gtk.MessageDialog(parent, 0, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK, message) error_dialog.connect(\"response\", close_dialog)",
"image = gtk.Image() image.set_from_file(logo) main_box.pack_start(image, True, True, 0) image.show() label",
"filew.add_filter(allfilter) filter = gtk.FileFilter() filter.set_name(\"All files\") filter.add_pattern(\"*\") filew.add_filter(filter) result =",
"console_dialog.connect(\"response\", close_dialog) stdout = sys.stdout stderr = sys.stderr console_widget =",
"allfilter = gtk.FileFilter() allfilter.set_name(\"All known files\") for filtername in filter_names_and_patterns:",
"prev_radio = radio self.data = choices[0] gtk.main() def cleanup(self, widget,",
"in tb: tb_msg += tbline long_message(parent, tb_msg + \"\\n\" +",
"prompt(parent, message, type = gtk.MESSAGE_QUESTION, has_cancel = False): \"\"\" Display",
"dialog.connect(\"response\", close_dialog) dialog.run() class RadioDialog: def __init__(self, title, message, choices,",
"= radio self.data = choices[0] gtk.main() def cleanup(self, widget, data=None):",
"def cleanup(self, widget, data=None): self.window.destroy() gtk.main_quit() def key_press(self, widget, event):",
"dialog.run() class RadioDialog: def __init__(self, title, message, choices, logo): self.window",
"__init__(self, title, message, choices, logo): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.connect(\"delete_event\", self.cleanup)",
"the hope that it will be useful, # but WITHOUT",
"gtk.main_quit() def key_press(self, widget, event): if event.keyval == gtk.keysyms.Return: self.cleanup(None)",
"pygtkconsole.GTKInterpreterConsole(locals) console_dialog.vbox.add(console_widget) console_widget.show() console_dialog.run() sys.stdout = stdout sys.stderr = stderr",
"True, 0) radio_box.show() separator = gtk.HSeparator() main_box.pack_start(separator, False, True, 0)",
"= parent, buttons = (gtk.STOCK_QUIT, gtk.RESPONSE_ACCEPT)) console_dialog.set_default_size(400, 300) console_dialog.connect(\"response\", close_dialog)",
"GoToDialog: def __init__(self, parent): self.goto_gui = gtk.glade.XML(parent.gladefile, root=\"GoToDialog\") self.dialog_box =",
"together with the last traceback. \"\"\" tb = traceback.format_exception(sys.exc_info()[0] ,sys.exc_info()[1],",
"+ \"\\n\" + message) return def get_filename(title, action, filter_names_and_patterns =",
"run(self): signals = {\"goto_activate\": self.on_goto_activate, \"cancel_activate\": self.on_cancel_activate} self.goto_gui.signal_autoconnect(signals) self.dialog_box.show() return",
"If not, see <http://www.gnu.org/licenses/>. import os import sys import traceback",
"radio.show() if prev_radio is None: radio.set_active(True) prev_radio = radio self.data",
"gtk.RESPONSE_ACCEPT)) console_dialog.set_default_size(400, 300) console_dialog.connect(\"response\", close_dialog) stdout = sys.stdout stderr =",
"message_dialog.run() return def error(parent, message): \"\"\" Display an error message.",
"None: image = gtk.Image() image.set_from_file(logo) main_box.pack_start(image, True, True, 0) image.show()",
"software: you can redistribute it and/or modify # it under",
"def console(parent, locals = None): \"\"\" Launch a python console.",
"for dialog reponse or destroy signals. Closes the dialog. \"\"\"",
"gtk.RESPONSE_NO) if has_cancel: prompt_dialog.add_buttons(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL) prompt_dialog.connect(\"response\", prompt_response) prompt_dialog.run() return prompt_response.response",
"gtk.BUTTONS_OK, message) dialog.set_title(title) dialog.connect(\"response\", close_dialog) dialog.run() class RadioDialog: def __init__(self,",
"else: filew.destroy() return None def console(parent, locals = None): \"\"\"",
"gtk.VBox(False, 0) self.window.add(main_box) main_box.show() if not logo is None: image",
"close.connect(\"clicked\", self.cleanup) main_box.pack_start(close, False, False, 0) close.show() prev_radio = None",
"240) message_dialog.run() return def error(parent, message): \"\"\" Display an error",
"text_view = gtk.TextView() scrolled_window.add(text_view) text_view.show() text_view.get_buffer().set_text(message) text_view.set_cursor_visible(False) text_view.set_property(\"editable\", False) text_view.set_property(\"height-request\",",
"scrolled_window.show() scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS) text_view = gtk.TextView() scrolled_window.add(text_view) text_view.show() text_view.get_buffer().set_text(message) text_view.set_cursor_visible(False)",
"gtk.Button(stock=gtk.STOCK_OK) close.connect(\"clicked\", self.cleanup) main_box.pack_start(close, False, False, 0) close.show() prev_radio =",
"False, False, 0) close.show() prev_radio = None for choice in",
"True, True, 0) radio_box.show() separator = gtk.HSeparator() main_box.pack_start(separator, False, True,",
"gtk.RadioButton(prev_radio, choice) radio.connect(\"toggled\", self.radio_callback, choice) radio_box.pack_start(radio, False, False, 0) radio.show()",
"= gtk.glade.XML(parent.gladefile, root=\"GoToDialog\") self.dialog_box = self.goto_gui.get_widget(\"GoToDialog\") self.dialog_box.set_modal(True) def run(self): signals",
"allfilter.set_name(\"All known files\") for filtername in filter_names_and_patterns: allfilter.add_pattern(filter_names_and_patterns[filtername]) filew.add_filter(allfilter) filter",
"in other functions. \"\"\" if response_id == gtk.RESPONSE_DELETE_EVENT: response_id =",
"Returns one of gtk.RESPONSE_{YES,NO,CANCEL}. \"\"\" prompt_dialog = gtk.MessageDialog(parent, 0, type,",
"0) self.window.add(main_box) main_box.show() if not logo is None: image =",
"copy of the GNU General Public License # along with",
"for filtername in filter_names_and_patterns: allfilter.add_pattern(filter_names_and_patterns[filtername]) filew.add_filter(allfilter) filter = gtk.FileFilter() filter.set_name(\"All",
"True, 0) separator.show() close = gtk.Button(stock=gtk.STOCK_OK) close.connect(\"clicked\", self.cleanup) main_box.pack_start(close, False,",
"gtk.RESPONSE_OK: filename = filew.get_filename() filtername = filew.get_filter().get_name() filew.destroy() return filename",
"tb_msg + \"\\n\" + message) return def get_filename(title, action, filter_names_and_patterns",
"Display an error message, together with the last traceback. \"\"\"",
"self.window.set_position(gtk.WIN_POS_CENTER) if not logo is None: self.window.set_icon_from_file(logo) self.window.show() #swindow =",
"tbline long_message(parent, tb_msg + \"\\n\" + message) return def get_filename(title,",
"self.radio_callback, choice) radio_box.pack_start(radio, False, False, 0) radio.show() if prev_radio is",
"sys.stdout = stdout sys.stderr = stderr return def prompt_response(dialog, response_id):",
"message) prompt_dialog.add_buttons(gtk.STOCK_YES, gtk.RESPONSE_YES, gtk.STOCK_NO, gtk.RESPONSE_NO) if has_cancel: prompt_dialog.add_buttons(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL) prompt_dialog.connect(\"response\",",
"filew.get_filename() filtername = filew.get_filter().get_name() filew.destroy() return filename else: filew.destroy() return",
"\"\"\" Launch a python console. \"\"\" console_dialog = gtk.Dialog(parent =",
"the message contained within a scrolled window. \"\"\" message_dialog =",
"message, choices, logo) return r.data def message_box(window, title, message): dialog",
"= pygtkconsole.GTKInterpreterConsole(locals) console_dialog.vbox.add(console_widget) console_widget.show() console_dialog.run() sys.stdout = stdout sys.stderr =",
"0) close.show() prev_radio = None for choice in choices: radio",
"self.goto_gui.signal_autoconnect(signals) self.dialog_box.show() return \"\" def on_goto_activate(self, widget=None): print \"goto\" def",
"distributed in the hope that it will be useful, #",
"tb_msg += tbline long_message(parent, tb_msg + \"\\n\" + message) return",
"message, choices, logo): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.connect(\"delete_event\", self.cleanup) self.window.connect(\"key_press_event\", self.key_press)",
"License, or # (at your option) any later version. #",
"error message, together with the last traceback. \"\"\" tb =",
"= None): \"\"\" Utility function to get a filename. \"\"\"",
"functions. \"\"\" if response_id == gtk.RESPONSE_DELETE_EVENT: response_id = gtk.RESPONSE_CANCEL prompt_response.response",
"return \"\" def on_goto_activate(self, widget=None): print \"goto\" def on_cancel_activate(self, widget=None):",
"error(parent, message): \"\"\" Display an error message. \"\"\" error_dialog =",
"logo is None: image = gtk.Image() image.set_from_file(logo) main_box.pack_start(image, True, True,",
"gtk.VBox(False, 10) main_box.pack_start(radio_box, True, True, 0) radio_box.show() separator = gtk.HSeparator()",
"allow response return in other functions. \"\"\" if response_id ==",
"# # Diamond is distributed in the hope that it",
"= gtk.ScrolledWindow() message_dialog.vbox.add(scrolled_window) scrolled_window.show() scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS) text_view = gtk.TextView() scrolled_window.add(text_view)",
"message) error_dialog.connect(\"response\", close_dialog) error_dialog.run() return def error_tb(parent, message): \"\"\" Display",
"has_cancel = False): \"\"\" Display a simple Yes / No",
"dialog response signals. Stores the dialog response in the function",
"traceback import gtk import pygtkconsole def prompt(parent, message, type =",
"tb: tb_msg += tbline long_message(parent, tb_msg + \"\\n\" + message)",
"You should have received a copy of the GNU General",
"parent): self.goto_gui = gtk.glade.XML(parent.gladefile, root=\"GoToDialog\") self.dialog_box = self.goto_gui.get_widget(\"GoToDialog\") self.dialog_box.set_modal(True) def",
"function namespace, to allow response return in other functions. \"\"\"",
"separator.show() close = gtk.Button(stock=gtk.STOCK_OK) close.connect(\"clicked\", self.cleanup) main_box.pack_start(close, False, False, 0)",
"\"cancel_activate\": self.on_cancel_activate} self.goto_gui.signal_autoconnect(signals) self.dialog_box.show() return \"\" def on_goto_activate(self, widget=None): print",
"This file is part of Diamond. # # Diamond is",
"self.dialog_box.show() return \"\" def on_goto_activate(self, widget=None): print \"goto\" def on_cancel_activate(self,",
"sys import traceback import gtk import pygtkconsole def prompt(parent, message,",
"radio_box.show() separator = gtk.HSeparator() main_box.pack_start(separator, False, True, 0) separator.show() close",
"def error_tb(parent, message): \"\"\" Display an error message, together with",
"folder_uri is None: filew.set_current_folder_uri(\"file://\" + os.path.abspath(folder_uri)) for filtername in filter_names_and_patterns:",
"message) return def get_filename(title, action, filter_names_and_patterns = {}, folder_uri =",
"sys.stdout stderr = sys.stderr console_widget = pygtkconsole.GTKInterpreterConsole(locals) console_dialog.vbox.add(console_widget) console_widget.show() console_dialog.run()",
"180) text_view.set_property(\"width-request\", 240) message_dialog.run() return def error(parent, message): \"\"\" Display",
"image.show() label = gtk.Label(message) main_box.add(label) label.show() radio_box = gtk.VBox(False, 10)",
"useful, # but WITHOUT ANY WARRANTY; without even the implied",
"= gtk.MESSAGE_QUESTION, has_cancel = False): \"\"\" Display a simple Yes",
"message): \"\"\" Display a message prompt, with the message contained",
"filew.destroy() return filename else: filew.destroy() return None def console(parent, locals",
"to allow response return in other functions. \"\"\" if response_id",
"sys.stderr console_widget = pygtkconsole.GTKInterpreterConsole(locals) console_dialog.vbox.add(console_widget) console_widget.show() console_dialog.run() sys.stdout = stdout",
"if event.keyval == gtk.keysyms.Return: self.cleanup(None) def radio_callback(self, widget, data): self.data",
"filename = filew.get_filename() filtername = filew.get_filter().get_name() filew.destroy() return filename else:",
"you can redistribute it and/or modify # it under the",
"response_id = None): \"\"\" Signal handler for dialog reponse or",
"filtername = filew.get_filter().get_name() filew.destroy() return filename else: filew.destroy() return None",
"scrolled window. \"\"\" message_dialog = gtk.Dialog(parent = parent, buttons =",
"= None): \"\"\" Signal handler for dialog reponse or destroy",
"console_dialog.vbox.add(console_widget) console_widget.show() console_dialog.run() sys.stdout = stdout sys.stderr = stderr return",
"prompt_dialog.run() return prompt_response.response def long_message(parent, message): \"\"\" Display a message",
"= traceback.format_exception(sys.exc_info()[0] ,sys.exc_info()[1], sys.exc_info()[2]) tb_msg = \"\" for tbline in",
"# You should have received a copy of the GNU",
"self.cleanup) self.window.connect(\"key_press_event\", self.key_press) self.window.set_title(title) self.window.set_position(gtk.WIN_POS_CENTER) if not logo is None:",
"text_view.get_buffer().set_text(message) text_view.set_cursor_visible(False) text_view.set_property(\"editable\", False) text_view.set_property(\"height-request\", 180) text_view.set_property(\"width-request\", 240) message_dialog.run() return",
"\"\"\" Display a message prompt, with the message contained within",
"return filename else: filew.destroy() return None def console(parent, locals =",
"= gtk.FileFilter() filter.set_name(\"All files\") filter.add_pattern(\"*\") filew.add_filter(filter) result = filew.run() if",
"(gtk.STOCK_QUIT, gtk.RESPONSE_ACCEPT)) console_dialog.set_default_size(400, 300) console_dialog.connect(\"response\", close_dialog) stdout = sys.stdout stderr",
"result = filew.run() if result == gtk.RESPONSE_OK: filename = filew.get_filename()",
"python console. \"\"\" console_dialog = gtk.Dialog(parent = parent, buttons =",
"of the GNU General Public License # along with Diamond.",
"pygtkconsole def prompt(parent, message, type = gtk.MESSAGE_QUESTION, has_cancel = False):",
"long_message(parent, message): \"\"\" Display a message prompt, with the message",
"locals = None): \"\"\" Launch a python console. \"\"\" console_dialog",
"console(parent, locals = None): \"\"\" Launch a python console. \"\"\"",
"300) console_dialog.connect(\"response\", close_dialog) stdout = sys.stdout stderr = sys.stderr console_widget",
"widget, event): if event.keyval == gtk.keysyms.Return: self.cleanup(None) def radio_callback(self, widget,",
"should have received a copy of the GNU General Public",
"tb_msg = \"\" for tbline in tb: tb_msg += tbline",
"gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.connect(\"delete_event\", self.cleanup) self.window.connect(\"key_press_event\", self.key_press) self.window.set_title(title) self.window.set_position(gtk.WIN_POS_CENTER) if not logo",
"if not folder_uri is None: filew.set_current_folder_uri(\"file://\" + os.path.abspath(folder_uri)) for filtername",
"type = gtk.MESSAGE_QUESTION, has_cancel = False): \"\"\" Display a simple",
"prev_radio is None: radio.set_active(True) prev_radio = radio self.data = choices[0]",
"window. \"\"\" message_dialog = gtk.Dialog(parent = parent, buttons = (gtk.STOCK_OK,",
"not folder_uri is None: filew.set_current_folder_uri(\"file://\" + os.path.abspath(folder_uri)) for filtername in",
"response in the function namespace, to allow response return in",
"gtk.RESPONSE_{YES,NO,CANCEL}. \"\"\" prompt_dialog = gtk.MessageDialog(parent, 0, type, gtk.BUTTONS_NONE, message) prompt_dialog.add_buttons(gtk.STOCK_YES,",
"gtk.Dialog(parent = parent, buttons = (gtk.STOCK_QUIT, gtk.RESPONSE_ACCEPT)) console_dialog.set_default_size(400, 300) console_dialog.connect(\"response\",",
"parent, buttons = (gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)) message_dialog.set_default_size(400, 300) message_dialog.connect(\"response\", close_dialog) scrolled_window",
"response_id == gtk.RESPONSE_DELETE_EVENT: response_id = gtk.RESPONSE_CANCEL prompt_response.response = response_id close_dialog(dialog,",
"type, gtk.BUTTONS_NONE, message) prompt_dialog.add_buttons(gtk.STOCK_YES, gtk.RESPONSE_YES, gtk.STOCK_NO, gtk.RESPONSE_NO) if has_cancel: prompt_dialog.add_buttons(gtk.STOCK_CANCEL,",
"a message prompt, with the message contained within a scrolled",
"data): self.data = data class GoToDialog: def __init__(self, parent): self.goto_gui",
"buttons = (gtk.STOCK_QUIT, gtk.RESPONSE_ACCEPT)) console_dialog.set_default_size(400, 300) console_dialog.connect(\"response\", close_dialog) stdout =",
"with the last traceback. \"\"\" tb = traceback.format_exception(sys.exc_info()[0] ,sys.exc_info()[1], sys.exc_info()[2])",
"error_tb(parent, message): \"\"\" Display an error message, together with the",
"300) message_dialog.connect(\"response\", close_dialog) scrolled_window = gtk.ScrolledWindow() message_dialog.vbox.add(scrolled_window) scrolled_window.show() scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS)",
"= None): \"\"\" Launch a python console. \"\"\" console_dialog =",
"\"\"\" Signal handler for dialog reponse or destroy signals. Closes",
"message): \"\"\" Display an error message. \"\"\" error_dialog = gtk.MessageDialog(parent,",
"for dialog response signals. Stores the dialog response in the",
"GNU General Public License as published by # the Free",
"def close_dialog(dialog, response_id = None): \"\"\" Signal handler for dialog",
"+ os.path.abspath(folder_uri)) for filtername in filter_names_and_patterns: filter = gtk.FileFilter() filter.set_name(filtername)",
"= stdout sys.stderr = stderr return def prompt_response(dialog, response_id): \"\"\"",
"{\"goto_activate\": self.on_goto_activate, \"cancel_activate\": self.on_cancel_activate} self.goto_gui.signal_autoconnect(signals) self.dialog_box.show() return \"\" def on_goto_activate(self,",
"prompt_dialog.connect(\"response\", prompt_response) prompt_dialog.run() return prompt_response.response def long_message(parent, message): \"\"\" Display",
"gtk.STOCK_NO, gtk.RESPONSE_NO) if has_cancel: prompt_dialog.add_buttons(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL) prompt_dialog.connect(\"response\", prompt_response) prompt_dialog.run() return",
"console. \"\"\" console_dialog = gtk.Dialog(parent = parent, buttons = (gtk.STOCK_QUIT,",
"close_dialog(dialog, response_id = None): \"\"\" Signal handler for dialog reponse",
"return in other functions. \"\"\" if response_id == gtk.RESPONSE_DELETE_EVENT: response_id",
"<http://www.gnu.org/licenses/>. import os import sys import traceback import gtk import",
"= stderr return def prompt_response(dialog, response_id): \"\"\" Signal handler for",
"gtk.FileFilter() filter.set_name(filtername) filter.add_pattern(filter_names_and_patterns[filtername]) filew.add_filter(filter) allfilter = gtk.FileFilter() allfilter.set_name(\"All known files\")",
"choice) radio.connect(\"toggled\", self.radio_callback, choice) radio_box.pack_start(radio, False, False, 0) radio.show() if",
"# the Free Software Foundation, either version 3 of the",
"#swindow = gtk.ScrolledWindow() #swindow.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) #self.window.add(swindow) #swindow.show() main_box = gtk.VBox(False,",
"of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See",
"of Diamond. # # Diamond is free software: you can",
"data class GoToDialog: def __init__(self, parent): self.goto_gui = gtk.glade.XML(parent.gladefile, root=\"GoToDialog\")",
"= gtk.Dialog(parent = parent, buttons = (gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)) message_dialog.set_default_size(400, 300)",
"console_dialog.set_default_size(400, 300) console_dialog.connect(\"response\", close_dialog) stdout = sys.stdout stderr = sys.stderr",
"signals = {\"goto_activate\": self.on_goto_activate, \"cancel_activate\": self.on_cancel_activate} self.goto_gui.signal_autoconnect(signals) self.dialog_box.show() return \"\"",
"radio_dialog(title, message, choices, logo): r = RadioDialog(title, message, choices, logo)",
"get_filename(title, action, filter_names_and_patterns = {}, folder_uri = None): \"\"\" Utility",
"choices: radio = gtk.RadioButton(prev_radio, choice) radio.connect(\"toggled\", self.radio_callback, choice) radio_box.pack_start(radio, False,",
"choices, logo): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.connect(\"delete_event\", self.cleanup) self.window.connect(\"key_press_event\", self.key_press) self.window.set_title(title)",
"but WITHOUT ANY WARRANTY; without even the implied warranty of",
"(at your option) any later version. # # Diamond is",
"Yes / No dialog. Returns one of gtk.RESPONSE_{YES,NO,CANCEL}. \"\"\" prompt_dialog",
"filter = gtk.FileFilter() filter.set_name(filtername) filter.add_pattern(filter_names_and_patterns[filtername]) filew.add_filter(filter) allfilter = gtk.FileFilter() allfilter.set_name(\"All",
"Public License for more details. # # You should have",
"0, type, gtk.BUTTONS_NONE, message) prompt_dialog.add_buttons(gtk.STOCK_YES, gtk.RESPONSE_YES, gtk.STOCK_NO, gtk.RESPONSE_NO) if has_cancel:",
"= gtk.MessageDialog(parent, 0, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK, message) error_dialog.connect(\"response\", close_dialog) error_dialog.run() return",
"self.dialog_box = self.goto_gui.get_widget(\"GoToDialog\") self.dialog_box.set_modal(True) def run(self): signals = {\"goto_activate\": self.on_goto_activate,",
"the terms of the GNU General Public License as published",
"= gtk.TextView() scrolled_window.add(text_view) text_view.show() text_view.get_buffer().set_text(message) text_view.set_cursor_visible(False) text_view.set_property(\"editable\", False) text_view.set_property(\"height-request\", 180)",
"gtk.RESPONSE_YES, gtk.STOCK_NO, gtk.RESPONSE_NO) if has_cancel: prompt_dialog.add_buttons(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL) prompt_dialog.connect(\"response\", prompt_response) prompt_dialog.run()",
"a simple Yes / No dialog. Returns one of gtk.RESPONSE_{YES,NO,CANCEL}.",
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #",
"scrolled_window.add(text_view) text_view.show() text_view.get_buffer().set_text(message) text_view.set_cursor_visible(False) text_view.set_property(\"editable\", False) text_view.set_property(\"height-request\", 180) text_view.set_property(\"width-request\", 240)",
"= gtk.VBox(False, 0) self.window.add(main_box) main_box.show() if not logo is None:",
"Software Foundation, either version 3 of the License, or #",
"close_dialog) scrolled_window = gtk.ScrolledWindow() message_dialog.vbox.add(scrolled_window) scrolled_window.show() scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS) text_view =",
"sys.stderr = stderr return def prompt_response(dialog, response_id): \"\"\" Signal handler",
"\"\" def on_goto_activate(self, widget=None): print \"goto\" def on_cancel_activate(self, widget=None): print",
"prompt_dialog.add_buttons(gtk.STOCK_YES, gtk.RESPONSE_YES, gtk.STOCK_NO, gtk.RESPONSE_NO) if has_cancel: prompt_dialog.add_buttons(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL) prompt_dialog.connect(\"response\", prompt_response)",
"def prompt(parent, message, type = gtk.MESSAGE_QUESTION, has_cancel = False): \"\"\"",
"title, message): dialog = gtk.MessageDialog(window, 0, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, message) dialog.set_title(title)",
"gtk.POLICY_AUTOMATIC) #self.window.add(swindow) #swindow.show() main_box = gtk.VBox(False, 0) self.window.add(main_box) main_box.show() if",
"== gtk.keysyms.Return: self.cleanup(None) def radio_callback(self, widget, data): self.data = data",
"def long_message(parent, message): \"\"\" Display a message prompt, with the",
"message_dialog.connect(\"response\", close_dialog) scrolled_window = gtk.ScrolledWindow() message_dialog.vbox.add(scrolled_window) scrolled_window.show() scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS) text_view",
"the dialog response in the function namespace, to allow response",
"\"\"\" Display a simple Yes / No dialog. Returns one",
"radio_box = gtk.VBox(False, 10) main_box.pack_start(radio_box, True, True, 0) radio_box.show() separator",
"import traceback import gtk import pygtkconsole def prompt(parent, message, type",
"as published by # the Free Software Foundation, either version",
"error_dialog = gtk.MessageDialog(parent, 0, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK, message) error_dialog.connect(\"response\", close_dialog) error_dialog.run()",
"No dialog. Returns one of gtk.RESPONSE_{YES,NO,CANCEL}. \"\"\" prompt_dialog = gtk.MessageDialog(parent,",
"version 3 of the License, or # (at your option)",
"buttons=buttons) filew.set_default_response(gtk.RESPONSE_OK) if not folder_uri is None: filew.set_current_folder_uri(\"file://\" + os.path.abspath(folder_uri))",
"for filtername in filter_names_and_patterns: filter = gtk.FileFilter() filter.set_name(filtername) filter.add_pattern(filter_names_and_patterns[filtername]) filew.add_filter(filter)",
"of gtk.RESPONSE_{YES,NO,CANCEL}. \"\"\" prompt_dialog = gtk.MessageDialog(parent, 0, type, gtk.BUTTONS_NONE, message)",
"file is part of Diamond. # # Diamond is free",
"0) image.show() label = gtk.Label(message) main_box.add(label) label.show() radio_box = gtk.VBox(False,",
"False, True, 0) separator.show() close = gtk.Button(stock=gtk.STOCK_OK) close.connect(\"clicked\", self.cleanup) main_box.pack_start(close,",
"if not logo is None: self.window.set_icon_from_file(logo) self.window.show() #swindow = gtk.ScrolledWindow()",
"prompt_dialog.add_buttons(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL) prompt_dialog.connect(\"response\", prompt_response) prompt_dialog.run() return prompt_response.response def long_message(parent, message):",
"response_id): \"\"\" Signal handler for dialog response signals. Stores the",
"False, 0) radio.show() if prev_radio is None: radio.set_active(True) prev_radio =",
"buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK) elif action == gtk.FILE_CHOOSER_ACTION_CREATE_FOLDER: buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_NEW,gtk.RESPONSE_OK) else: buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK) filew =",
"\"\"\" tb = traceback.format_exception(sys.exc_info()[0] ,sys.exc_info()[1], sys.exc_info()[2]) tb_msg = \"\" for",
"\"\"\" if action == gtk.FILE_CHOOSER_ACTION_SAVE: buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK) elif action == gtk.FILE_CHOOSER_ACTION_CREATE_FOLDER:",
"scrolled_window = gtk.ScrolledWindow() message_dialog.vbox.add(scrolled_window) scrolled_window.show() scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS) text_view = gtk.TextView()",
"has_cancel: prompt_dialog.add_buttons(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL) prompt_dialog.connect(\"response\", prompt_response) prompt_dialog.run() return prompt_response.response def long_message(parent,",
"an error message. \"\"\" error_dialog = gtk.MessageDialog(parent, 0, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK,",
"(gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)) message_dialog.set_default_size(400, 300) message_dialog.connect(\"response\", close_dialog) scrolled_window = gtk.ScrolledWindow() message_dialog.vbox.add(scrolled_window)",
"a copy of the GNU General Public License # along",
"choices, logo): r = RadioDialog(title, message, choices, logo) return r.data",
"Signal handler for dialog response signals. Stores the dialog response",
"message contained within a scrolled window. \"\"\" message_dialog = gtk.Dialog(parent",
"self.window.connect(\"delete_event\", self.cleanup) self.window.connect(\"key_press_event\", self.key_press) self.window.set_title(title) self.window.set_position(gtk.WIN_POS_CENTER) if not logo is",
"folder_uri = None): \"\"\" Utility function to get a filename.",
"dialog. Returns one of gtk.RESPONSE_{YES,NO,CANCEL}. \"\"\" prompt_dialog = gtk.MessageDialog(parent, 0,",
"None: radio.set_active(True) prev_radio = radio self.data = choices[0] gtk.main() def",
"= gtk.MessageDialog(window, 0, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, message) dialog.set_title(title) dialog.connect(\"response\", close_dialog) dialog.run()",
"Public License as published by # the Free Software Foundation,",
"None: self.window.set_icon_from_file(logo) self.window.show() #swindow = gtk.ScrolledWindow() #swindow.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) #self.window.add(swindow) #swindow.show()",
"self.data = data class GoToDialog: def __init__(self, parent): self.goto_gui =",
"the dialog. \"\"\" dialog.destroy() return def radio_dialog(title, message, choices, logo):",
"widget, data): self.data = data class GoToDialog: def __init__(self, parent):",
"with the message contained within a scrolled window. \"\"\" message_dialog",
"traceback.format_exception(sys.exc_info()[0] ,sys.exc_info()[1], sys.exc_info()[2]) tb_msg = \"\" for tbline in tb:",
"separator = gtk.HSeparator() main_box.pack_start(separator, False, True, 0) separator.show() close =",
"gtk.FILE_CHOOSER_ACTION_CREATE_FOLDER: buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_NEW,gtk.RESPONSE_OK) else: buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK) filew = gtk.FileChooserDialog(title=title, action=action, buttons=buttons) filew.set_default_response(gtk.RESPONSE_OK)",
"cleanup(self, widget, data=None): self.window.destroy() gtk.main_quit() def key_press(self, widget, event): if",
"False) text_view.set_property(\"height-request\", 180) text_view.set_property(\"width-request\", 240) message_dialog.run() return def error(parent, message):",
"have received a copy of the GNU General Public License",
"0, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, message) dialog.set_title(title) dialog.connect(\"response\", close_dialog) dialog.run() class RadioDialog:",
"message) dialog.set_title(title) dialog.connect(\"response\", close_dialog) dialog.run() class RadioDialog: def __init__(self, title,",
"gtk.TextView() scrolled_window.add(text_view) text_view.show() text_view.get_buffer().set_text(message) text_view.set_cursor_visible(False) text_view.set_property(\"editable\", False) text_view.set_property(\"height-request\", 180) text_view.set_property(\"width-request\",",
"in the hope that it will be useful, # but",
"= (gtk.STOCK_QUIT, gtk.RESPONSE_ACCEPT)) console_dialog.set_default_size(400, 300) console_dialog.connect(\"response\", close_dialog) stdout = sys.stdout",
"reponse or destroy signals. Closes the dialog. \"\"\" dialog.destroy() return",
"files\") filter.add_pattern(\"*\") filew.add_filter(filter) result = filew.run() if result == gtk.RESPONSE_OK:",
"response signals. Stores the dialog response in the function namespace,",
"return def error_tb(parent, message): \"\"\" Display an error message, together",
"if response_id == gtk.RESPONSE_DELETE_EVENT: response_id = gtk.RESPONSE_CANCEL prompt_response.response = response_id",
"see <http://www.gnu.org/licenses/>. import os import sys import traceback import gtk",
"message): dialog = gtk.MessageDialog(window, 0, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, message) dialog.set_title(title) dialog.connect(\"response\",",
"in the function namespace, to allow response return in other",
"License # along with Diamond. If not, see <http://www.gnu.org/licenses/>. import",
"None): \"\"\" Utility function to get a filename. \"\"\" if",
"to get a filename. \"\"\" if action == gtk.FILE_CHOOSER_ACTION_SAVE: buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK)",
"not logo is None: image = gtk.Image() image.set_from_file(logo) main_box.pack_start(image, True,",
"\"\"\" Signal handler for dialog response signals. Stores the dialog",
"known files\") for filtername in filter_names_and_patterns: allfilter.add_pattern(filter_names_and_patterns[filtername]) filew.add_filter(allfilter) filter =",
"not logo is None: self.window.set_icon_from_file(logo) self.window.show() #swindow = gtk.ScrolledWindow() #swindow.set_policy(gtk.POLICY_AUTOMATIC,",
"message prompt, with the message contained within a scrolled window.",
"None: filew.set_current_folder_uri(\"file://\" + os.path.abspath(folder_uri)) for filtername in filter_names_and_patterns: filter =",
"# Diamond is free software: you can redistribute it and/or",
"= (gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)) message_dialog.set_default_size(400, 300) message_dialog.connect(\"response\", close_dialog) scrolled_window = gtk.ScrolledWindow()",
"gtk.keysyms.Return: self.cleanup(None) def radio_callback(self, widget, data): self.data = data class",
"# along with Diamond. If not, see <http://www.gnu.org/licenses/>. import os",
"Display a message prompt, with the message contained within a",
"WARRANTY; without even the implied warranty of # MERCHANTABILITY or",
"in filter_names_and_patterns: filter = gtk.FileFilter() filter.set_name(filtername) filter.add_pattern(filter_names_and_patterns[filtername]) filew.add_filter(filter) allfilter =",
"self.window.set_icon_from_file(logo) self.window.show() #swindow = gtk.ScrolledWindow() #swindow.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) #self.window.add(swindow) #swindow.show() main_box",
"label.show() radio_box = gtk.VBox(False, 10) main_box.pack_start(radio_box, True, True, 0) radio_box.show()",
"in filter_names_and_patterns: allfilter.add_pattern(filter_names_and_patterns[filtername]) filew.add_filter(allfilter) filter = gtk.FileFilter() filter.set_name(\"All files\") filter.add_pattern(\"*\")",
"Diamond is free software: you can redistribute it and/or modify",
"GNU General Public License for more details. # # You",
"filew.set_current_folder_uri(\"file://\" + os.path.abspath(folder_uri)) for filtername in filter_names_and_patterns: filter = gtk.FileFilter()",
"import gtk import pygtkconsole def prompt(parent, message, type = gtk.MESSAGE_QUESTION,",
"result == gtk.RESPONSE_OK: filename = filew.get_filename() filtername = filew.get_filter().get_name() filew.destroy()",
"= gtk.VBox(False, 10) main_box.pack_start(radio_box, True, True, 0) radio_box.show() separator =",
"is distributed in the hope that it will be useful,",
"3 of the License, or # (at your option) any",
"choice) radio_box.pack_start(radio, False, False, 0) radio.show() if prev_radio is None:",
"= gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.connect(\"delete_event\", self.cleanup) self.window.connect(\"key_press_event\", self.key_press) self.window.set_title(title) self.window.set_position(gtk.WIN_POS_CENTER) if not",
"gtk.ScrolledWindow() #swindow.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) #self.window.add(swindow) #swindow.show() main_box = gtk.VBox(False, 0) self.window.add(main_box)",
"return r.data def message_box(window, title, message): dialog = gtk.MessageDialog(window, 0,",
"# # You should have received a copy of the",
"# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the",
"= gtk.ScrolledWindow() #swindow.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) #self.window.add(swindow) #swindow.show() main_box = gtk.VBox(False, 0)",
"without even the implied warranty of # MERCHANTABILITY or FITNESS"
] |
[
"default=(0, 0)) def run(self): pyxel.init( WINDOW_WIDTH, WINDOW_HEIGHT, scale=SCALE, caption=\"Mazes\", border_width=SCALE,",
"def draw(self): pyxel.cls(0) for i, cell in enumerate(self.maze): x, y",
"next_maze, pos, done = self.generator.step() if done: self.running = False",
"App: maze: Maze = field(init=False, default=tuple(0 for _ in range(N_CELLS)))",
"default_factory=list) _maze: List[int] = field(init=False) def __post_init__(self, start_pos: Optional[Tuple[int, int]]):",
"default=0) _stack: List[Tuple[int, int]] = field(init=False, default_factory=list) _maze: List[int] =",
"<< 0 LEFT = 1 << 1 DOWN = 1",
"WALL_SIZE, scr_y, CELL_SIZE, WALL_SIZE, CELL_COLOR ) if cell & LEFT:",
"Optional[Generator] = field(init=False, default=None) running: bool = field(init=False, default=False) pos:",
"+= 1 else: del self._stack[-1] return tuple(self._maze), self._stack[-1], False else:",
"is None: self.generator = Generator(BOARD_WIDTH, BOARD_HEIGHT, self.pos) if self.running: next_maze,",
"width: int height: int start_pos: InitVar[Optional[Tuple[int, int]]] = None _visited_cells:",
"= 32 BOARD_HEIGHT = 32 CELL_SIZE = 6 CELL_COLOR =",
"_get_neighbors(self, x: int, y: int) -> List[int]: return [ (i,",
"if self.running else 1 ) def update(self): if pyxel.btnp(pyxel.KEY_SPACE) or",
"= 1 self._maze = [0 for _ in range(self.width *",
"+ 2) % 4) | VISTED self._stack.append((x_, y_)) self._visited_cells +=",
"in range(self.width * self.height)] self._maze[y * self.width + x] |=",
"= BOARD_WIDTH * BOARD_HEIGHT BLOCK_SIZE = CELL_SIZE + WALL_SIZE *",
"CELL_SIZE, CELL_SIZE, WALL_SIZE, CELL_COLOR ) if cell & RIGHT: pyxel.rect(",
"= i % BOARD_WIDTH, i // BOARD_WIDTH scr_x, scr_y =",
"annotations from dataclasses import dataclass, field, InitVar from typing import",
"x] |= VISTED def _get_neighbors(self, x: int, y: int) ->",
"start_pos or (0, 0) self._stack.append(start_pos) self._visited_cells = 1 self._maze =",
"self._stack.append((x_, y_)) self._visited_cells += 1 else: del self._stack[-1] return tuple(self._maze),",
"RIGHT = 1 << 3 VISTED = 1 << 4",
"False self.generator = None self.maze = next_maze self.pos = pos",
"// BLOCK_SIZE)), max(0, min(BOARD_HEIGHT-1, pyxel.mouse_y // BLOCK_SIZE)) ) if __name__",
"------------------------------------------------------- @dataclass class Generator: width: int height: int start_pos: InitVar[Optional[Tuple[int,",
"Generator(BOARD_WIDTH, BOARD_HEIGHT, self.pos) if self.running: next_maze, pos, done = self.generator.step()",
"self.pos) if self.running: next_maze, pos, done = self.generator.step() if done:",
"False else: return tuple(self._maze), (0, 0), True # ------------------------------------------------------- #",
"Iterator, Iterable, Optional from random import choice import pyxel #",
"field(init=False, default=0) _stack: List[Tuple[int, int]] = field(init=False, default_factory=list) _maze: List[int]",
"self._visited_cells += 1 else: del self._stack[-1] return tuple(self._maze), self._stack[-1], False",
"dx)] & VISTED == 0 ) ] def step(self) ->",
"CELL_SIZE, CELL_SIZE, CELL_COLOR ) if cell & UP: pyxel.rect( scr_x",
"* BOARD_HEIGHT BLOCK_SIZE = CELL_SIZE + WALL_SIZE * 2 WINDOW_WIDTH",
"0)) # ------------------------------------------------------- # Maze # ------------------------------------------------------- @dataclass class Generator:",
"Generator: width: int height: int start_pos: InitVar[Optional[Tuple[int, int]]] = None",
"@dataclass class App: maze: Maze = field(init=False, default=tuple(0 for _",
"self._stack.append(start_pos) self._visited_cells = 1 self._maze = [0 for _ in",
"* self.height)] self._maze[y * self.width + x] |= VISTED def",
"cell & RIGHT: pyxel.rect( scr_x + WALL_SIZE + CELL_SIZE, scr_y",
"WALL_SIZE, CELL_COLOR ) if cell & RIGHT: pyxel.rect( scr_x +",
"x + dx < self.width and 0 <= y +",
"return tuple(self._maze), self._stack[-1], False else: return tuple(self._maze), (0, 0), True",
"BLOCK_SIZE WINDOW_HEIGHT = BOARD_HEIGHT * BLOCK_SIZE NEIGHBORS = ((0, -1),",
"del self._stack[-1] return tuple(self._maze), self._stack[-1], False else: return tuple(self._maze), (0,",
"generator: Optional[Generator] = field(init=False, default=None) running: bool = field(init=False, default=False)",
"or pyxel.btnp(pyxel.MOUSE_LEFT_BUTTON): self.running = not self.running if self.running and self.generator",
"__post_init__(self, start_pos: Optional[Tuple[int, int]]): x, y = start_pos = start_pos",
"BOARD_WIDTH scr_x, scr_y = x * BLOCK_SIZE, y * BLOCK_SIZE",
"in enumerate(NEIGHBORS) if ( 0 <= x + dx <",
"choice import pyxel # ------------------------------------------------------- # Types # ------------------------------------------------------- Maze",
"BOARD_WIDTH, i // BOARD_WIDTH scr_x, scr_y = x * BLOCK_SIZE,",
"= BOARD_WIDTH * BLOCK_SIZE WINDOW_HEIGHT = BOARD_HEIGHT * BLOCK_SIZE NEIGHBORS",
"x + dx, y + dy self._maze[y_ * self.width +",
"------------------------------------------------------- Maze = Tuple[int, ...] # ------------------------------------------------------- # Constants #",
"choice(neighbors) self._maze[y * self.width + x] |= 1 << d",
"if cell & DOWN: pyxel.rect( scr_x + WALL_SIZE, scr_y +",
"1 ) def update(self): if pyxel.btnp(pyxel.KEY_SPACE) or pyxel.btnp(pyxel.MOUSE_LEFT_BUTTON): self.running =",
"field(init=False) def __post_init__(self, start_pos: Optional[Tuple[int, int]]): x, y = start_pos",
"# Calculated N_CELLS = BOARD_WIDTH * BOARD_HEIGHT BLOCK_SIZE = CELL_SIZE",
"dy) * self.width + (x + dx)] & VISTED ==",
"= field(init=False, default=(0, 0)) def run(self): pyxel.init( WINDOW_WIDTH, WINDOW_HEIGHT, scale=SCALE,",
"self.width + x_] |= 1 << ((d + 2) %",
"import pyxel # ------------------------------------------------------- # Types # ------------------------------------------------------- Maze =",
"CELL_SIZE, CELL_COLOR ) if cell & DOWN: pyxel.rect( scr_x +",
"scr_x, scr_y = x * BLOCK_SIZE, y * BLOCK_SIZE pyxel.rect(",
"Maze = Tuple[int, ...] # ------------------------------------------------------- # Constants # -------------------------------------------------------",
"1 << 4 # Calculated N_CELLS = BOARD_WIDTH * BOARD_HEIGHT",
"List, Tuple, Iterator, Iterable, Optional from random import choice import",
"pyxel.mouse(True) pyxel.run(self.update, self.draw) def draw(self): pyxel.cls(0) for i, cell in",
"self.width and 0 <= y + dy < self.height and",
"scr_y + WALL_SIZE + CELL_SIZE, CELL_SIZE, WALL_SIZE, CELL_COLOR ) if",
"self.height)] self._maze[y * self.width + x] |= VISTED def _get_neighbors(self,",
"class App: maze: Maze = field(init=False, default=tuple(0 for _ in",
"in enumerate(self.maze): x, y = i % BOARD_WIDTH, i //",
"= 1 WALL_COLOR = 5 # Flags UP = 1",
"5 # Flags UP = 1 << 0 LEFT =",
"self.width + x] |= VISTED def _get_neighbors(self, x: int, y:",
"VISTED = 1 << 4 # Calculated N_CELLS = BOARD_WIDTH",
"y + dy self._maze[y_ * self.width + x_] |= 1",
"// BOARD_WIDTH scr_x, scr_y = x * BLOCK_SIZE, y *",
"y + dy < self.height and self._maze[(y + dy) *",
"self.draw) def draw(self): pyxel.cls(0) for i, cell in enumerate(self.maze): x,",
"pyxel.rect( scr_x + WALL_SIZE, scr_y, CELL_SIZE, WALL_SIZE, CELL_COLOR ) if",
"CELL_COLOR ) if cell & DOWN: pyxel.rect( scr_x + WALL_SIZE,",
"self.running = False self.generator = None self.maze = next_maze self.pos",
"y = start_pos = start_pos or (0, 0) self._stack.append(start_pos) self._visited_cells",
"int = field(init=False, default=0) _stack: List[Tuple[int, int]] = field(init=False, default_factory=list)",
"CELL_COLOR = 15 WALL_SIZE = 1 WALL_COLOR = 5 #",
"int]] = field(init=False, default_factory=list) _maze: List[int] = field(init=False) def __post_init__(self,",
"cell & UP: pyxel.rect( scr_x + WALL_SIZE, scr_y, CELL_SIZE, WALL_SIZE,",
"0), True # ------------------------------------------------------- # Application # ------------------------------------------------------- @dataclass class",
"CELL_SIZE, scr_y + WALL_SIZE, WALL_SIZE, CELL_SIZE, CELL_COLOR ) x, y",
"start_pos: Optional[Tuple[int, int]]): x, y = start_pos = start_pos or",
"None _visited_cells: int = field(init=False, default=0) _stack: List[Tuple[int, int]] =",
"dy = choice(neighbors) self._maze[y * self.width + x] |= 1",
"N_CELLS = BOARD_WIDTH * BOARD_HEIGHT BLOCK_SIZE = CELL_SIZE + WALL_SIZE",
"+ WALL_SIZE, y * BLOCK_SIZE + WALL_SIZE, CELL_SIZE, CELL_SIZE, 2",
"Types # ------------------------------------------------------- Maze = Tuple[int, ...] # ------------------------------------------------------- #",
"Tuple, Iterator, Iterable, Optional from random import choice import pyxel",
"neighbors = self._get_neighbors(x, y) if neighbors: d, dx, dy =",
"UP: pyxel.rect( scr_x + WALL_SIZE, scr_y, CELL_SIZE, WALL_SIZE, CELL_COLOR )",
"scr_x, scr_y + WALL_SIZE, WALL_SIZE, CELL_SIZE, CELL_COLOR ) if cell",
"1 else: del self._stack[-1] return tuple(self._maze), self._stack[-1], False else: return",
"< self.height and self._maze[(y + dy) * self.width + (x",
"None: self.generator = Generator(BOARD_WIDTH, BOARD_HEIGHT, self.pos) if self.running: next_maze, pos,",
"WALL_COLOR ) if cell & VISTED: pyxel.rect( scr_x + WALL_SIZE,",
"field(init=False, default=(0, 0)) def run(self): pyxel.init( WINDOW_WIDTH, WINDOW_HEIGHT, scale=SCALE, caption=\"Mazes\",",
"y * BLOCK_SIZE + WALL_SIZE, CELL_SIZE, CELL_SIZE, 2 if self.running",
"0 <= x + dx < self.width and 0 <=",
"scr_x + WALL_SIZE + CELL_SIZE, scr_y + WALL_SIZE, WALL_SIZE, CELL_SIZE,",
"neighbors: d, dx, dy = choice(neighbors) self._maze[y * self.width +",
"= CELL_SIZE + WALL_SIZE * 2 WINDOW_WIDTH = BOARD_WIDTH *",
"# ------------------------------------------------------- @dataclass class Generator: width: int height: int start_pos:",
"<= y + dy < self.height and self._maze[(y + dy)",
"BLOCK_SIZE, y * BLOCK_SIZE pyxel.rect( scr_x, scr_y, BLOCK_SIZE, BLOCK_SIZE, WALL_COLOR",
"<< ((d + 2) % 4) | VISTED self._stack.append((x_, y_))",
"& VISTED == 0 ) ] def step(self) -> Tuple[Maze,",
"WINDOW_WIDTH = BOARD_WIDTH * BLOCK_SIZE WINDOW_HEIGHT = BOARD_HEIGHT * BLOCK_SIZE",
"self.maze = next_maze self.pos = pos else: self.pos = (",
"Calculated N_CELLS = BOARD_WIDTH * BOARD_HEIGHT BLOCK_SIZE = CELL_SIZE +",
"< self.width and 0 <= y + dy < self.height",
"self.running = not self.running if self.running and self.generator is None:",
"2 WINDOW_WIDTH = BOARD_WIDTH * BLOCK_SIZE WINDOW_HEIGHT = BOARD_HEIGHT *",
"def _get_neighbors(self, x: int, y: int) -> List[int]: return [",
"== 0 ) ] def step(self) -> Tuple[Maze, Tuple[int, int],",
"= next_maze self.pos = pos else: self.pos = ( max(0,",
"self.pos pyxel.rectb( x * BLOCK_SIZE + WALL_SIZE, y * BLOCK_SIZE",
"+ WALL_SIZE, scr_y + WALL_SIZE + CELL_SIZE, CELL_SIZE, WALL_SIZE, CELL_COLOR",
"bool = field(init=False, default=False) pos: Tuple[int, int] = field(init=False, default=(0,",
") if cell & LEFT: pyxel.rect( scr_x, scr_y + WALL_SIZE,",
"# Application # ------------------------------------------------------- @dataclass class App: maze: Maze =",
"= x + dx, y + dy self._maze[y_ * self.width",
"_maze: List[int] = field(init=False) def __post_init__(self, start_pos: Optional[Tuple[int, int]]): x,",
"= field(init=False, default=None) running: bool = field(init=False, default=False) pos: Tuple[int,",
"+ WALL_SIZE, CELL_SIZE, CELL_SIZE, CELL_COLOR ) if cell & UP:",
"WALL_SIZE, CELL_SIZE, CELL_SIZE, 2 if self.running else 1 ) def",
"Iterable, Optional from random import choice import pyxel # -------------------------------------------------------",
"_ in range(self.width * self.height)] self._maze[y * self.width + x]",
"4 # Calculated N_CELLS = BOARD_WIDTH * BOARD_HEIGHT BLOCK_SIZE =",
"& LEFT: pyxel.rect( scr_x, scr_y + WALL_SIZE, WALL_SIZE, CELL_SIZE, CELL_COLOR",
"(-1, 0), (0, 1), (1, 0)) # ------------------------------------------------------- # Maze",
"maze: Maze = field(init=False, default=tuple(0 for _ in range(N_CELLS))) generator:",
"enumerate(self.maze): x, y = i % BOARD_WIDTH, i // BOARD_WIDTH",
"return tuple(self._maze), (0, 0), True # ------------------------------------------------------- # Application #",
"default=None) running: bool = field(init=False, default=False) pos: Tuple[int, int] =",
"BLOCK_SIZE + WALL_SIZE, y * BLOCK_SIZE + WALL_SIZE, CELL_SIZE, CELL_SIZE,",
"BOARD_HEIGHT * BLOCK_SIZE NEIGHBORS = ((0, -1), (-1, 0), (0,",
"WALL_SIZE, y * BLOCK_SIZE + WALL_SIZE, CELL_SIZE, CELL_SIZE, 2 if",
"+ WALL_SIZE + CELL_SIZE, scr_y + WALL_SIZE, WALL_SIZE, CELL_SIZE, CELL_COLOR",
"------------------------------------------------------- # Maze # ------------------------------------------------------- @dataclass class Generator: width: int",
"% 4) | VISTED self._stack.append((x_, y_)) self._visited_cells += 1 else:",
"WALL_SIZE * 2 WINDOW_WIDTH = BOARD_WIDTH * BLOCK_SIZE WINDOW_HEIGHT =",
"cell & VISTED: pyxel.rect( scr_x + WALL_SIZE, scr_y + WALL_SIZE,",
"# ------------------------------------------------------- Maze = Tuple[int, ...] # ------------------------------------------------------- # Constants",
"BLOCK_SIZE NEIGHBORS = ((0, -1), (-1, 0), (0, 1), (1,",
"pyxel.rect( scr_x + WALL_SIZE + CELL_SIZE, scr_y + WALL_SIZE, WALL_SIZE,",
"if done: self.running = False self.generator = None self.maze =",
"------------------------------------------------------- @dataclass class App: maze: Maze = field(init=False, default=tuple(0 for",
"< self.width * self.height: x, y = self._stack[-1] neighbors =",
"import choice import pyxel # ------------------------------------------------------- # Types # -------------------------------------------------------",
"Tuple[int, ...] # ------------------------------------------------------- # Constants # ------------------------------------------------------- SCALE =",
"Tuple[Maze, Tuple[int, int], bool]: if self._visited_cells < self.width * self.height:",
"List[int]: return [ (i, dx, dy) for i, (dx, dy)",
"self._stack[-1] return tuple(self._maze), self._stack[-1], False else: return tuple(self._maze), (0, 0),",
"if ( 0 <= x + dx < self.width and",
"------------------------------------------------------- # Constants # ------------------------------------------------------- SCALE = 3 BOARD_WIDTH =",
"1 self._maze = [0 for _ in range(self.width * self.height)]",
"WALL_SIZE, WALL_SIZE, CELL_SIZE, CELL_COLOR ) x, y = self.pos pyxel.rectb(",
"InitVar from typing import List, Tuple, Iterator, Iterable, Optional from",
"dy self._maze[y_ * self.width + x_] |= 1 << ((d",
"NEIGHBORS = ((0, -1), (-1, 0), (0, 1), (1, 0))",
"& DOWN: pyxel.rect( scr_x + WALL_SIZE, scr_y + WALL_SIZE +",
"32 BOARD_HEIGHT = 32 CELL_SIZE = 6 CELL_COLOR = 15",
"# ------------------------------------------------------- # Types # ------------------------------------------------------- Maze = Tuple[int, ...]",
"( max(0, min(BOARD_WIDTH-1, pyxel.mouse_x // BLOCK_SIZE)), max(0, min(BOARD_HEIGHT-1, pyxel.mouse_y //",
"y = self._stack[-1] neighbors = self._get_neighbors(x, y) if neighbors: d,",
") if cell & UP: pyxel.rect( scr_x + WALL_SIZE, scr_y,",
"int start_pos: InitVar[Optional[Tuple[int, int]]] = None _visited_cells: int = field(init=False,",
"List[int] = field(init=False) def __post_init__(self, start_pos: Optional[Tuple[int, int]]): x, y",
"* self.width + (x + dx)] & VISTED == 0",
"pos else: self.pos = ( max(0, min(BOARD_WIDTH-1, pyxel.mouse_x // BLOCK_SIZE)),",
"int height: int start_pos: InitVar[Optional[Tuple[int, int]]] = None _visited_cells: int",
"next_maze self.pos = pos else: self.pos = ( max(0, min(BOARD_WIDTH-1,",
"i, cell in enumerate(self.maze): x, y = i % BOARD_WIDTH,",
"y = self.pos pyxel.rectb( x * BLOCK_SIZE + WALL_SIZE, y",
"1), (1, 0)) # ------------------------------------------------------- # Maze # ------------------------------------------------------- @dataclass",
"* BLOCK_SIZE NEIGHBORS = ((0, -1), (-1, 0), (0, 1),",
"pyxel.mouse_x // BLOCK_SIZE)), max(0, min(BOARD_HEIGHT-1, pyxel.mouse_y // BLOCK_SIZE)) ) if",
"from random import choice import pyxel # ------------------------------------------------------- # Types",
"WALL_COLOR = 5 # Flags UP = 1 << 0",
"VISTED: pyxel.rect( scr_x + WALL_SIZE, scr_y + WALL_SIZE, CELL_SIZE, CELL_SIZE,",
"x_] |= 1 << ((d + 2) % 4) |",
"else: self.pos = ( max(0, min(BOARD_WIDTH-1, pyxel.mouse_x // BLOCK_SIZE)), max(0,",
"* 2 WINDOW_WIDTH = BOARD_WIDTH * BLOCK_SIZE WINDOW_HEIGHT = BOARD_HEIGHT",
"|= 1 << d x_, y_ = x + dx,",
"CELL_COLOR ) x, y = self.pos pyxel.rectb( x * BLOCK_SIZE",
"InitVar[Optional[Tuple[int, int]]] = None _visited_cells: int = field(init=False, default=0) _stack:",
"WINDOW_HEIGHT = BOARD_HEIGHT * BLOCK_SIZE NEIGHBORS = ((0, -1), (-1,",
"WALL_SIZE + CELL_SIZE, CELL_SIZE, WALL_SIZE, CELL_COLOR ) if cell &",
"= field(init=False, default=0) _stack: List[Tuple[int, int]] = field(init=False, default_factory=list) _maze:",
"<< d x_, y_ = x + dx, y +",
"x * BLOCK_SIZE, y * BLOCK_SIZE pyxel.rect( scr_x, scr_y, BLOCK_SIZE,",
"(1, 0)) # ------------------------------------------------------- # Maze # ------------------------------------------------------- @dataclass class",
"& VISTED: pyxel.rect( scr_x + WALL_SIZE, scr_y + WALL_SIZE, CELL_SIZE,",
"self._maze[(y + dy) * self.width + (x + dx)] &",
"((0, -1), (-1, 0), (0, 1), (1, 0)) # -------------------------------------------------------",
"x, y = self._stack[-1] neighbors = self._get_neighbors(x, y) if neighbors:",
"= start_pos or (0, 0) self._stack.append(start_pos) self._visited_cells = 1 self._maze",
"step(self) -> Tuple[Maze, Tuple[int, int], bool]: if self._visited_cells < self.width",
"for i, cell in enumerate(self.maze): x, y = i %",
"( 0 <= x + dx < self.width and 0",
"Maze = field(init=False, default=tuple(0 for _ in range(N_CELLS))) generator: Optional[Generator]",
"y) if neighbors: d, dx, dy = choice(neighbors) self._maze[y *",
"dx, dy) for i, (dx, dy) in enumerate(NEIGHBORS) if (",
"* self.width + x] |= 1 << d x_, y_",
"draw(self): pyxel.cls(0) for i, cell in enumerate(self.maze): x, y =",
"self.generator = Generator(BOARD_WIDTH, BOARD_HEIGHT, self.pos) if self.running: next_maze, pos, done",
"from dataclasses import dataclass, field, InitVar from typing import List,",
"else: del self._stack[-1] return tuple(self._maze), self._stack[-1], False else: return tuple(self._maze),",
"default=tuple(0 for _ in range(N_CELLS))) generator: Optional[Generator] = field(init=False, default=None)",
"= 1 << 0 LEFT = 1 << 1 DOWN",
"+ x] |= 1 << d x_, y_ = x",
"self.generator.step() if done: self.running = False self.generator = None self.maze",
"= self.pos pyxel.rectb( x * BLOCK_SIZE + WALL_SIZE, y *",
"y * BLOCK_SIZE pyxel.rect( scr_x, scr_y, BLOCK_SIZE, BLOCK_SIZE, WALL_COLOR )",
"# Maze # ------------------------------------------------------- @dataclass class Generator: width: int height:",
"Tuple[int, int], bool]: if self._visited_cells < self.width * self.height: x,",
"scr_y + WALL_SIZE, CELL_SIZE, CELL_SIZE, CELL_COLOR ) if cell &",
"def step(self) -> Tuple[Maze, Tuple[int, int], bool]: if self._visited_cells <",
"if self.running and self.generator is None: self.generator = Generator(BOARD_WIDTH, BOARD_HEIGHT,",
"VISTED == 0 ) ] def step(self) -> Tuple[Maze, Tuple[int,",
"def run(self): pyxel.init( WINDOW_WIDTH, WINDOW_HEIGHT, scale=SCALE, caption=\"Mazes\", border_width=SCALE, border_color=pyxel.DEFAULT_PALETTE[5], fps=100",
"if cell & LEFT: pyxel.rect( scr_x, scr_y + WALL_SIZE, WALL_SIZE,",
"scr_y + WALL_SIZE, WALL_SIZE, CELL_SIZE, CELL_COLOR ) if cell &",
"% BOARD_WIDTH, i // BOARD_WIDTH scr_x, scr_y = x *",
"if neighbors: d, dx, dy = choice(neighbors) self._maze[y * self.width",
"2) % 4) | VISTED self._stack.append((x_, y_)) self._visited_cells += 1",
"= field(init=False, default=False) pos: Tuple[int, int] = field(init=False, default=(0, 0))",
"------------------------------------------------------- # Types # ------------------------------------------------------- Maze = Tuple[int, ...] #",
"else: return tuple(self._maze), (0, 0), True # ------------------------------------------------------- # Application",
"= False self.generator = None self.maze = next_maze self.pos =",
"= self._get_neighbors(x, y) if neighbors: d, dx, dy = choice(neighbors)",
"self.pos = pos else: self.pos = ( max(0, min(BOARD_WIDTH-1, pyxel.mouse_x",
"= [0 for _ in range(self.width * self.height)] self._maze[y *",
"+ WALL_SIZE, WALL_SIZE, CELL_SIZE, CELL_COLOR ) x, y = self.pos",
"_visited_cells: int = field(init=False, default=0) _stack: List[Tuple[int, int]] = field(init=False,",
"running: bool = field(init=False, default=False) pos: Tuple[int, int] = field(init=False,",
"d x_, y_ = x + dx, y + dy",
"= field(init=False, default_factory=list) _maze: List[int] = field(init=False) def __post_init__(self, start_pos:",
"scr_x + WALL_SIZE, scr_y, CELL_SIZE, WALL_SIZE, CELL_COLOR ) if cell",
"field, InitVar from typing import List, Tuple, Iterator, Iterable, Optional",
"self._get_neighbors(x, y) if neighbors: d, dx, dy = choice(neighbors) self._maze[y",
"= Generator(BOARD_WIDTH, BOARD_HEIGHT, self.pos) if self.running: next_maze, pos, done =",
"& RIGHT: pyxel.rect( scr_x + WALL_SIZE + CELL_SIZE, scr_y +",
"self._visited_cells < self.width * self.height: x, y = self._stack[-1] neighbors",
"min(BOARD_WIDTH-1, pyxel.mouse_x // BLOCK_SIZE)), max(0, min(BOARD_HEIGHT-1, pyxel.mouse_y // BLOCK_SIZE)) )",
"scr_y, BLOCK_SIZE, BLOCK_SIZE, WALL_COLOR ) if cell & VISTED: pyxel.rect(",
"def update(self): if pyxel.btnp(pyxel.KEY_SPACE) or pyxel.btnp(pyxel.MOUSE_LEFT_BUTTON): self.running = not self.running",
"int, y: int) -> List[int]: return [ (i, dx, dy)",
"+ dy) * self.width + (x + dx)] & VISTED",
"Flags UP = 1 << 0 LEFT = 1 <<",
"i, (dx, dy) in enumerate(NEIGHBORS) if ( 0 <= x",
"cell in enumerate(self.maze): x, y = i % BOARD_WIDTH, i",
"+ CELL_SIZE, CELL_SIZE, WALL_SIZE, CELL_COLOR ) if cell & RIGHT:",
"WALL_SIZE = 1 WALL_COLOR = 5 # Flags UP =",
"y_ = x + dx, y + dy self._maze[y_ *",
"= start_pos = start_pos or (0, 0) self._stack.append(start_pos) self._visited_cells =",
"height: int start_pos: InitVar[Optional[Tuple[int, int]]] = None _visited_cells: int =",
"...] # ------------------------------------------------------- # Constants # ------------------------------------------------------- SCALE = 3",
"and self._maze[(y + dy) * self.width + (x + dx)]",
"= pos else: self.pos = ( max(0, min(BOARD_WIDTH-1, pyxel.mouse_x //",
"scr_y, CELL_SIZE, WALL_SIZE, CELL_COLOR ) if cell & LEFT: pyxel.rect(",
"x, y = i % BOARD_WIDTH, i // BOARD_WIDTH scr_x,",
"self.generator = None self.maze = next_maze self.pos = pos else:",
"if self.running: next_maze, pos, done = self.generator.step() if done: self.running",
"int) -> List[int]: return [ (i, dx, dy) for i,",
"[0 for _ in range(self.width * self.height)] self._maze[y * self.width",
"y_)) self._visited_cells += 1 else: del self._stack[-1] return tuple(self._maze), self._stack[-1],",
"CELL_SIZE, CELL_COLOR ) if cell & UP: pyxel.rect( scr_x +",
"VISTED self._stack.append((x_, y_)) self._visited_cells += 1 else: del self._stack[-1] return",
"1 << d x_, y_ = x + dx, y",
"BLOCK_SIZE, WALL_COLOR ) if cell & VISTED: pyxel.rect( scr_x +",
"from typing import List, Tuple, Iterator, Iterable, Optional from random",
"List[Tuple[int, int]] = field(init=False, default_factory=list) _maze: List[int] = field(init=False) def",
"pyxel.btnp(pyxel.MOUSE_LEFT_BUTTON): self.running = not self.running if self.running and self.generator is",
") x, y = self.pos pyxel.rectb( x * BLOCK_SIZE +",
"32 CELL_SIZE = 6 CELL_COLOR = 15 WALL_SIZE = 1",
"or (0, 0) self._stack.append(start_pos) self._visited_cells = 1 self._maze = [0",
"1 << 0 LEFT = 1 << 1 DOWN =",
"+ WALL_SIZE, scr_y + WALL_SIZE, CELL_SIZE, CELL_SIZE, CELL_COLOR ) if",
"= ( max(0, min(BOARD_WIDTH-1, pyxel.mouse_x // BLOCK_SIZE)), max(0, min(BOARD_HEIGHT-1, pyxel.mouse_y",
"(dx, dy) in enumerate(NEIGHBORS) if ( 0 <= x +",
"BOARD_WIDTH * BLOCK_SIZE WINDOW_HEIGHT = BOARD_HEIGHT * BLOCK_SIZE NEIGHBORS =",
"= x * BLOCK_SIZE, y * BLOCK_SIZE pyxel.rect( scr_x, scr_y,",
"WALL_SIZE + CELL_SIZE, scr_y + WALL_SIZE, WALL_SIZE, CELL_SIZE, CELL_COLOR )",
"= 15 WALL_SIZE = 1 WALL_COLOR = 5 # Flags",
"self._maze[y_ * self.width + x_] |= 1 << ((d +",
"* BLOCK_SIZE, y * BLOCK_SIZE pyxel.rect( scr_x, scr_y, BLOCK_SIZE, BLOCK_SIZE,",
"start_pos: InitVar[Optional[Tuple[int, int]]] = None _visited_cells: int = field(init=False, default=0)",
"self._stack[-1], False else: return tuple(self._maze), (0, 0), True # -------------------------------------------------------",
"# ------------------------------------------------------- SCALE = 3 BOARD_WIDTH = 32 BOARD_HEIGHT =",
"BOARD_WIDTH = 32 BOARD_HEIGHT = 32 CELL_SIZE = 6 CELL_COLOR",
"if cell & RIGHT: pyxel.rect( scr_x + WALL_SIZE + CELL_SIZE,",
"_stack: List[Tuple[int, int]] = field(init=False, default_factory=list) _maze: List[int] = field(init=False)",
"range(self.width * self.height)] self._maze[y * self.width + x] |= VISTED",
"[ (i, dx, dy) for i, (dx, dy) in enumerate(NEIGHBORS)",
"-1), (-1, 0), (0, 1), (1, 0)) # ------------------------------------------------------- #",
"cell & LEFT: pyxel.rect( scr_x, scr_y + WALL_SIZE, WALL_SIZE, CELL_SIZE,",
"Constants # ------------------------------------------------------- SCALE = 3 BOARD_WIDTH = 32 BOARD_HEIGHT",
"3 BOARD_WIDTH = 32 BOARD_HEIGHT = 32 CELL_SIZE = 6",
"UP = 1 << 0 LEFT = 1 << 1",
"1 << 1 DOWN = 1 << 2 RIGHT =",
"= 1 << 4 # Calculated N_CELLS = BOARD_WIDTH *",
"CELL_SIZE, WALL_SIZE, CELL_COLOR ) if cell & LEFT: pyxel.rect( scr_x,",
"typing import List, Tuple, Iterator, Iterable, Optional from random import",
"= 6 CELL_COLOR = 15 WALL_SIZE = 1 WALL_COLOR =",
"SCALE = 3 BOARD_WIDTH = 32 BOARD_HEIGHT = 32 CELL_SIZE",
"self.running and self.generator is None: self.generator = Generator(BOARD_WIDTH, BOARD_HEIGHT, self.pos)",
"default=False) pos: Tuple[int, int] = field(init=False, default=(0, 0)) def run(self):",
"# Types # ------------------------------------------------------- Maze = Tuple[int, ...] # -------------------------------------------------------",
"WALL_SIZE, CELL_SIZE, CELL_COLOR ) if cell & DOWN: pyxel.rect( scr_x",
"pyxel.rect( scr_x + WALL_SIZE, scr_y + WALL_SIZE + CELL_SIZE, CELL_SIZE,",
"def __post_init__(self, start_pos: Optional[Tuple[int, int]]): x, y = start_pos =",
"__future__ import annotations from dataclasses import dataclass, field, InitVar from",
"enumerate(NEIGHBORS) if ( 0 <= x + dx < self.width",
"border_color=pyxel.DEFAULT_PALETTE[5], fps=100 ) pyxel.mouse(True) pyxel.run(self.update, self.draw) def draw(self): pyxel.cls(0) for",
"= 32 CELL_SIZE = 6 CELL_COLOR = 15 WALL_SIZE =",
"scr_x + WALL_SIZE, scr_y + WALL_SIZE, CELL_SIZE, CELL_SIZE, CELL_COLOR )",
"cell & DOWN: pyxel.rect( scr_x + WALL_SIZE, scr_y + WALL_SIZE",
"= field(init=False, default=tuple(0 for _ in range(N_CELLS))) generator: Optional[Generator] =",
"y = i % BOARD_WIDTH, i // BOARD_WIDTH scr_x, scr_y",
"update(self): if pyxel.btnp(pyxel.KEY_SPACE) or pyxel.btnp(pyxel.MOUSE_LEFT_BUTTON): self.running = not self.running if",
"3 VISTED = 1 << 4 # Calculated N_CELLS =",
"BLOCK_SIZE = CELL_SIZE + WALL_SIZE * 2 WINDOW_WIDTH = BOARD_WIDTH",
"self.height and self._maze[(y + dy) * self.width + (x +",
"bool]: if self._visited_cells < self.width * self.height: x, y =",
"CELL_SIZE = 6 CELL_COLOR = 15 WALL_SIZE = 1 WALL_COLOR",
"# ------------------------------------------------------- # Maze # ------------------------------------------------------- @dataclass class Generator: width:",
"d, dx, dy = choice(neighbors) self._maze[y * self.width + x]",
"max(0, min(BOARD_WIDTH-1, pyxel.mouse_x // BLOCK_SIZE)), max(0, min(BOARD_HEIGHT-1, pyxel.mouse_y // BLOCK_SIZE))",
"WALL_SIZE, CELL_SIZE, CELL_SIZE, CELL_COLOR ) if cell & UP: pyxel.rect(",
"self._maze = [0 for _ in range(self.width * self.height)] self._maze[y",
") def update(self): if pyxel.btnp(pyxel.KEY_SPACE) or pyxel.btnp(pyxel.MOUSE_LEFT_BUTTON): self.running = not",
"CELL_SIZE + WALL_SIZE * 2 WINDOW_WIDTH = BOARD_WIDTH * BLOCK_SIZE",
"int] = field(init=False, default=(0, 0)) def run(self): pyxel.init( WINDOW_WIDTH, WINDOW_HEIGHT,",
"= None _visited_cells: int = field(init=False, default=0) _stack: List[Tuple[int, int]]",
"2 if self.running else 1 ) def update(self): if pyxel.btnp(pyxel.KEY_SPACE)",
"CELL_COLOR ) if cell & UP: pyxel.rect( scr_x + WALL_SIZE,",
"+ CELL_SIZE, scr_y + WALL_SIZE, WALL_SIZE, CELL_SIZE, CELL_COLOR ) x,",
"pos, done = self.generator.step() if done: self.running = False self.generator",
"self._stack[-1] neighbors = self._get_neighbors(x, y) if neighbors: d, dx, dy",
"BLOCK_SIZE + WALL_SIZE, CELL_SIZE, CELL_SIZE, 2 if self.running else 1",
"15 WALL_SIZE = 1 WALL_COLOR = 5 # Flags UP",
"dx, y + dy self._maze[y_ * self.width + x_] |=",
"pyxel.btnp(pyxel.KEY_SPACE) or pyxel.btnp(pyxel.MOUSE_LEFT_BUTTON): self.running = not self.running if self.running and",
"(0, 0) self._stack.append(start_pos) self._visited_cells = 1 self._maze = [0 for",
"2 RIGHT = 1 << 3 VISTED = 1 <<",
"CELL_COLOR ) if cell & RIGHT: pyxel.rect( scr_x + WALL_SIZE",
"------------------------------------------------------- # Application # ------------------------------------------------------- @dataclass class App: maze: Maze",
"self.generator is None: self.generator = Generator(BOARD_WIDTH, BOARD_HEIGHT, self.pos) if self.running:",
"<< 2 RIGHT = 1 << 3 VISTED = 1",
"* self.width + x_] |= 1 << ((d + 2)",
"import dataclass, field, InitVar from typing import List, Tuple, Iterator,",
"import annotations from dataclasses import dataclass, field, InitVar from typing",
"(i, dx, dy) for i, (dx, dy) in enumerate(NEIGHBORS) if",
"scr_x, scr_y, BLOCK_SIZE, BLOCK_SIZE, WALL_COLOR ) if cell & VISTED:",
"* BLOCK_SIZE + WALL_SIZE, y * BLOCK_SIZE + WALL_SIZE, CELL_SIZE,",
"_ in range(N_CELLS))) generator: Optional[Generator] = field(init=False, default=None) running: bool",
"|= VISTED def _get_neighbors(self, x: int, y: int) -> List[int]:",
"min(BOARD_HEIGHT-1, pyxel.mouse_y // BLOCK_SIZE)) ) if __name__ == '__main__': App().run()",
"self._visited_cells = 1 self._maze = [0 for _ in range(self.width",
"max(0, min(BOARD_HEIGHT-1, pyxel.mouse_y // BLOCK_SIZE)) ) if __name__ == '__main__':",
"dataclasses import dataclass, field, InitVar from typing import List, Tuple,",
"start_pos = start_pos or (0, 0) self._stack.append(start_pos) self._visited_cells = 1",
"dx < self.width and 0 <= y + dy <",
"CELL_SIZE, 2 if self.running else 1 ) def update(self): if",
"dataclass, field, InitVar from typing import List, Tuple, Iterator, Iterable,",
"None self.maze = next_maze self.pos = pos else: self.pos =",
"+ (x + dx)] & VISTED == 0 ) ]",
"-> List[int]: return [ (i, dx, dy) for i, (dx,",
"WALL_SIZE, WALL_SIZE, CELL_SIZE, CELL_COLOR ) if cell & DOWN: pyxel.rect(",
"= 1 << 3 VISTED = 1 << 4 #",
"+ dx)] & VISTED == 0 ) ] def step(self)",
"True # ------------------------------------------------------- # Application # ------------------------------------------------------- @dataclass class App:",
"] def step(self) -> Tuple[Maze, Tuple[int, int], bool]: if self._visited_cells",
"pyxel.init( WINDOW_WIDTH, WINDOW_HEIGHT, scale=SCALE, caption=\"Mazes\", border_width=SCALE, border_color=pyxel.DEFAULT_PALETTE[5], fps=100 ) pyxel.mouse(True)",
"BOARD_HEIGHT BLOCK_SIZE = CELL_SIZE + WALL_SIZE * 2 WINDOW_WIDTH =",
"0) self._stack.append(start_pos) self._visited_cells = 1 self._maze = [0 for _",
"+ x_] |= 1 << ((d + 2) % 4)",
"= 1 << 1 DOWN = 1 << 2 RIGHT",
"CELL_COLOR ) if cell & LEFT: pyxel.rect( scr_x, scr_y +",
"0), (0, 1), (1, 0)) # ------------------------------------------------------- # Maze #",
"= field(init=False) def __post_init__(self, start_pos: Optional[Tuple[int, int]]): x, y =",
"self._maze[y * self.width + x] |= VISTED def _get_neighbors(self, x:",
"1 DOWN = 1 << 2 RIGHT = 1 <<",
"* self.width + x] |= VISTED def _get_neighbors(self, x: int,",
"Maze # ------------------------------------------------------- @dataclass class Generator: width: int height: int",
"* BLOCK_SIZE pyxel.rect( scr_x, scr_y, BLOCK_SIZE, BLOCK_SIZE, WALL_COLOR ) if",
"if pyxel.btnp(pyxel.KEY_SPACE) or pyxel.btnp(pyxel.MOUSE_LEFT_BUTTON): self.running = not self.running if self.running",
"self.running if self.running and self.generator is None: self.generator = Generator(BOARD_WIDTH,",
"| VISTED self._stack.append((x_, y_)) self._visited_cells += 1 else: del self._stack[-1]",
"1 << ((d + 2) % 4) | VISTED self._stack.append((x_,",
"+ dy < self.height and self._maze[(y + dy) * self.width",
"= self._stack[-1] neighbors = self._get_neighbors(x, y) if neighbors: d, dx,",
"+ WALL_SIZE, WALL_SIZE, CELL_SIZE, CELL_COLOR ) if cell & DOWN:",
"(x + dx)] & VISTED == 0 ) ] def",
"pyxel # ------------------------------------------------------- # Types # ------------------------------------------------------- Maze = Tuple[int,",
"((d + 2) % 4) | VISTED self._stack.append((x_, y_)) self._visited_cells",
"# ------------------------------------------------------- @dataclass class App: maze: Maze = field(init=False, default=tuple(0",
"= 3 BOARD_WIDTH = 32 BOARD_HEIGHT = 32 CELL_SIZE =",
"range(N_CELLS))) generator: Optional[Generator] = field(init=False, default=None) running: bool = field(init=False,",
"------------------------------------------------------- SCALE = 3 BOARD_WIDTH = 32 BOARD_HEIGHT = 32",
"CELL_SIZE, WALL_SIZE, CELL_COLOR ) if cell & RIGHT: pyxel.rect( scr_x",
"x, y = self.pos pyxel.rectb( x * BLOCK_SIZE + WALL_SIZE,",
"Application # ------------------------------------------------------- @dataclass class App: maze: Maze = field(init=False,",
"self.width + x] |= 1 << d x_, y_ =",
"# ------------------------------------------------------- # Application # ------------------------------------------------------- @dataclass class App: maze:",
"= BOARD_HEIGHT * BLOCK_SIZE NEIGHBORS = ((0, -1), (-1, 0),",
"not self.running if self.running and self.generator is None: self.generator =",
"if self._visited_cells < self.width * self.height: x, y = self._stack[-1]",
"BOARD_HEIGHT, self.pos) if self.running: next_maze, pos, done = self.generator.step() if",
"# ------------------------------------------------------- # Constants # ------------------------------------------------------- SCALE = 3 BOARD_WIDTH",
"and self.generator is None: self.generator = Generator(BOARD_WIDTH, BOARD_HEIGHT, self.pos) if",
"0 LEFT = 1 << 1 DOWN = 1 <<",
"dx, dy = choice(neighbors) self._maze[y * self.width + x] |=",
"RIGHT: pyxel.rect( scr_x + WALL_SIZE + CELL_SIZE, scr_y + WALL_SIZE,",
"tuple(self._maze), self._stack[-1], False else: return tuple(self._maze), (0, 0), True #",
"i // BOARD_WIDTH scr_x, scr_y = x * BLOCK_SIZE, y",
"* BLOCK_SIZE + WALL_SIZE, CELL_SIZE, CELL_SIZE, 2 if self.running else",
"self.width * self.height: x, y = self._stack[-1] neighbors = self._get_neighbors(x,",
"# Constants # ------------------------------------------------------- SCALE = 3 BOARD_WIDTH = 32",
"DOWN: pyxel.rect( scr_x + WALL_SIZE, scr_y + WALL_SIZE + CELL_SIZE,",
"<< 3 VISTED = 1 << 4 # Calculated N_CELLS",
"BLOCK_SIZE pyxel.rect( scr_x, scr_y, BLOCK_SIZE, BLOCK_SIZE, WALL_COLOR ) if cell",
"x * BLOCK_SIZE + WALL_SIZE, y * BLOCK_SIZE + WALL_SIZE,",
"+ dx < self.width and 0 <= y + dy",
"int], bool]: if self._visited_cells < self.width * self.height: x, y",
"DOWN = 1 << 2 RIGHT = 1 << 3",
"else 1 ) def update(self): if pyxel.btnp(pyxel.KEY_SPACE) or pyxel.btnp(pyxel.MOUSE_LEFT_BUTTON): self.running",
"LEFT = 1 << 1 DOWN = 1 << 2",
"BOARD_WIDTH * BOARD_HEIGHT BLOCK_SIZE = CELL_SIZE + WALL_SIZE * 2",
"if cell & VISTED: pyxel.rect( scr_x + WALL_SIZE, scr_y +",
"Tuple[int, int] = field(init=False, default=(0, 0)) def run(self): pyxel.init( WINDOW_WIDTH,",
"i % BOARD_WIDTH, i // BOARD_WIDTH scr_x, scr_y = x",
"(0, 0), True # ------------------------------------------------------- # Application # ------------------------------------------------------- @dataclass",
"1 << 2 RIGHT = 1 << 3 VISTED =",
"= 1 << 2 RIGHT = 1 << 3 VISTED",
"# Flags UP = 1 << 0 LEFT = 1",
"import List, Tuple, Iterator, Iterable, Optional from random import choice",
"field(init=False, default=tuple(0 for _ in range(N_CELLS))) generator: Optional[Generator] = field(init=False,",
"pos: Tuple[int, int] = field(init=False, default=(0, 0)) def run(self): pyxel.init(",
"BOARD_HEIGHT = 32 CELL_SIZE = 6 CELL_COLOR = 15 WALL_SIZE",
"x_, y_ = x + dx, y + dy self._maze[y_",
") pyxel.mouse(True) pyxel.run(self.update, self.draw) def draw(self): pyxel.cls(0) for i, cell",
"* self.height: x, y = self._stack[-1] neighbors = self._get_neighbors(x, y)",
"<= x + dx < self.width and 0 <= y",
"caption=\"Mazes\", border_width=SCALE, border_color=pyxel.DEFAULT_PALETTE[5], fps=100 ) pyxel.mouse(True) pyxel.run(self.update, self.draw) def draw(self):",
"WALL_SIZE, scr_y + WALL_SIZE, CELL_SIZE, CELL_SIZE, CELL_COLOR ) if cell",
"self._maze[y * self.width + x] |= 1 << d x_,",
"-> Tuple[Maze, Tuple[int, int], bool]: if self._visited_cells < self.width *",
"BLOCK_SIZE, BLOCK_SIZE, WALL_COLOR ) if cell & VISTED: pyxel.rect( scr_x",
"+ WALL_SIZE, CELL_SIZE, CELL_SIZE, 2 if self.running else 1 )",
"<< 4 # Calculated N_CELLS = BOARD_WIDTH * BOARD_HEIGHT BLOCK_SIZE",
"scr_y = x * BLOCK_SIZE, y * BLOCK_SIZE pyxel.rect( scr_x,",
"VISTED def _get_neighbors(self, x: int, y: int) -> List[int]: return",
"self.running: next_maze, pos, done = self.generator.step() if done: self.running =",
"LEFT: pyxel.rect( scr_x, scr_y + WALL_SIZE, WALL_SIZE, CELL_SIZE, CELL_COLOR )",
"0 ) ] def step(self) -> Tuple[Maze, Tuple[int, int], bool]:",
"in range(N_CELLS))) generator: Optional[Generator] = field(init=False, default=None) running: bool =",
"tuple(self._maze), (0, 0), True # ------------------------------------------------------- # Application # -------------------------------------------------------",
"0)) def run(self): pyxel.init( WINDOW_WIDTH, WINDOW_HEIGHT, scale=SCALE, caption=\"Mazes\", border_width=SCALE, border_color=pyxel.DEFAULT_PALETTE[5],",
"field(init=False, default=False) pos: Tuple[int, int] = field(init=False, default=(0, 0)) def",
"border_width=SCALE, border_color=pyxel.DEFAULT_PALETTE[5], fps=100 ) pyxel.mouse(True) pyxel.run(self.update, self.draw) def draw(self): pyxel.cls(0)",
"done = self.generator.step() if done: self.running = False self.generator =",
"x, y = start_pos = start_pos or (0, 0) self._stack.append(start_pos)",
"= 5 # Flags UP = 1 << 0 LEFT",
"int]]): x, y = start_pos = start_pos or (0, 0)",
"from __future__ import annotations from dataclasses import dataclass, field, InitVar",
"= choice(neighbors) self._maze[y * self.width + x] |= 1 <<",
"+ WALL_SIZE, scr_y, CELL_SIZE, WALL_SIZE, CELL_COLOR ) if cell &",
"BLOCK_SIZE)), max(0, min(BOARD_HEIGHT-1, pyxel.mouse_y // BLOCK_SIZE)) ) if __name__ ==",
"dy < self.height and self._maze[(y + dy) * self.width +",
"= Tuple[int, ...] # ------------------------------------------------------- # Constants # ------------------------------------------------------- SCALE",
"= None self.maze = next_maze self.pos = pos else: self.pos",
"= ((0, -1), (-1, 0), (0, 1), (1, 0)) #",
"Optional from random import choice import pyxel # ------------------------------------------------------- #",
"random import choice import pyxel # ------------------------------------------------------- # Types #",
") ] def step(self) -> Tuple[Maze, Tuple[int, int], bool]: if",
"return [ (i, dx, dy) for i, (dx, dy) in",
"WINDOW_WIDTH, WINDOW_HEIGHT, scale=SCALE, caption=\"Mazes\", border_width=SCALE, border_color=pyxel.DEFAULT_PALETTE[5], fps=100 ) pyxel.mouse(True) pyxel.run(self.update,",
"for _ in range(self.width * self.height)] self._maze[y * self.width +",
"pyxel.rect( scr_x + WALL_SIZE, scr_y + WALL_SIZE, CELL_SIZE, CELL_SIZE, CELL_COLOR",
"@dataclass class Generator: width: int height: int start_pos: InitVar[Optional[Tuple[int, int]]]",
"(0, 1), (1, 0)) # ------------------------------------------------------- # Maze # -------------------------------------------------------",
"& UP: pyxel.rect( scr_x + WALL_SIZE, scr_y, CELL_SIZE, WALL_SIZE, CELL_COLOR",
"class Generator: width: int height: int start_pos: InitVar[Optional[Tuple[int, int]]] =",
"x: int, y: int) -> List[int]: return [ (i, dx,",
"pyxel.rect( scr_x, scr_y, BLOCK_SIZE, BLOCK_SIZE, WALL_COLOR ) if cell &",
"dy) in enumerate(NEIGHBORS) if ( 0 <= x + dx",
") if cell & RIGHT: pyxel.rect( scr_x + WALL_SIZE +",
"0 <= y + dy < self.height and self._maze[(y +",
"WINDOW_HEIGHT, scale=SCALE, caption=\"Mazes\", border_width=SCALE, border_color=pyxel.DEFAULT_PALETTE[5], fps=100 ) pyxel.mouse(True) pyxel.run(self.update, self.draw)",
"= self.generator.step() if done: self.running = False self.generator = None",
") if cell & DOWN: pyxel.rect( scr_x + WALL_SIZE, scr_y",
"CELL_SIZE, CELL_COLOR ) x, y = self.pos pyxel.rectb( x *",
"4) | VISTED self._stack.append((x_, y_)) self._visited_cells += 1 else: del",
"pyxel.rect( scr_x, scr_y + WALL_SIZE, WALL_SIZE, CELL_SIZE, CELL_COLOR ) if",
"pyxel.run(self.update, self.draw) def draw(self): pyxel.cls(0) for i, cell in enumerate(self.maze):",
"and 0 <= y + dy < self.height and self._maze[(y",
"CELL_SIZE, CELL_SIZE, 2 if self.running else 1 ) def update(self):",
"self.running else 1 ) def update(self): if pyxel.btnp(pyxel.KEY_SPACE) or pyxel.btnp(pyxel.MOUSE_LEFT_BUTTON):",
"y: int) -> List[int]: return [ (i, dx, dy) for",
"WALL_SIZE, CELL_COLOR ) if cell & LEFT: pyxel.rect( scr_x, scr_y",
"|= 1 << ((d + 2) % 4) | VISTED",
"+ x] |= VISTED def _get_neighbors(self, x: int, y: int)",
"1 << 3 VISTED = 1 << 4 # Calculated",
"field(init=False, default_factory=list) _maze: List[int] = field(init=False) def __post_init__(self, start_pos: Optional[Tuple[int,",
"Optional[Tuple[int, int]]): x, y = start_pos = start_pos or (0,",
"WALL_SIZE, scr_y + WALL_SIZE + CELL_SIZE, CELL_SIZE, WALL_SIZE, CELL_COLOR )",
"done: self.running = False self.generator = None self.maze = next_maze",
"6 CELL_COLOR = 15 WALL_SIZE = 1 WALL_COLOR = 5",
"for _ in range(N_CELLS))) generator: Optional[Generator] = field(init=False, default=None) running:",
"+ dy self._maze[y_ * self.width + x_] |= 1 <<",
"pyxel.cls(0) for i, cell in enumerate(self.maze): x, y = i",
"scr_x + WALL_SIZE, scr_y + WALL_SIZE + CELL_SIZE, CELL_SIZE, WALL_SIZE,",
") if cell & VISTED: pyxel.rect( scr_x + WALL_SIZE, scr_y",
"if cell & UP: pyxel.rect( scr_x + WALL_SIZE, scr_y, CELL_SIZE,",
"x] |= 1 << d x_, y_ = x +",
"+ dx, y + dy self._maze[y_ * self.width + x_]",
"1 WALL_COLOR = 5 # Flags UP = 1 <<",
"field(init=False, default=None) running: bool = field(init=False, default=False) pos: Tuple[int, int]",
"= not self.running if self.running and self.generator is None: self.generator",
"run(self): pyxel.init( WINDOW_WIDTH, WINDOW_HEIGHT, scale=SCALE, caption=\"Mazes\", border_width=SCALE, border_color=pyxel.DEFAULT_PALETTE[5], fps=100 )",
"pyxel.rectb( x * BLOCK_SIZE + WALL_SIZE, y * BLOCK_SIZE +",
"for i, (dx, dy) in enumerate(NEIGHBORS) if ( 0 <=",
"dy) for i, (dx, dy) in enumerate(NEIGHBORS) if ( 0",
"self.pos = ( max(0, min(BOARD_WIDTH-1, pyxel.mouse_x // BLOCK_SIZE)), max(0, min(BOARD_HEIGHT-1,",
"+ WALL_SIZE + CELL_SIZE, CELL_SIZE, WALL_SIZE, CELL_COLOR ) if cell",
"WALL_SIZE, CELL_SIZE, CELL_COLOR ) x, y = self.pos pyxel.rectb( x",
"<< 1 DOWN = 1 << 2 RIGHT = 1",
"scr_y + WALL_SIZE, WALL_SIZE, CELL_SIZE, CELL_COLOR ) x, y =",
"self.width + (x + dx)] & VISTED == 0 )",
"int]]] = None _visited_cells: int = field(init=False, default=0) _stack: List[Tuple[int,",
"fps=100 ) pyxel.mouse(True) pyxel.run(self.update, self.draw) def draw(self): pyxel.cls(0) for i,",
"scale=SCALE, caption=\"Mazes\", border_width=SCALE, border_color=pyxel.DEFAULT_PALETTE[5], fps=100 ) pyxel.mouse(True) pyxel.run(self.update, self.draw) def",
"* BLOCK_SIZE WINDOW_HEIGHT = BOARD_HEIGHT * BLOCK_SIZE NEIGHBORS = ((0,",
"self.height: x, y = self._stack[-1] neighbors = self._get_neighbors(x, y) if",
"+ WALL_SIZE * 2 WINDOW_WIDTH = BOARD_WIDTH * BLOCK_SIZE WINDOW_HEIGHT"
] |
[
"https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in",
"haystack HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'blog.whoosh_cn_backend.WhooshEngine', 'PATH': os.path.join(BASE_DIR,",
"for bobjiang project. Generated by 'django-admin startproject' using Django 2.0.6.",
"{ 'default': { 'ENGINE': 'blog.whoosh_cn_backend.WhooshEngine', 'PATH': os.path.join(BASE_DIR, 'whoosh_index'), }, }",
"# https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' #STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS",
"DEBUG = False RECORD_VISITOR = True # RECORD_VISITOR = False",
"# Application definition INSTALLED_APPS = [ 'haystack', 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth',",
"'HOST': '127.0.0.1', 'PORT': 3306, 'OPTIONS': { 'autocommit': True, }, }",
"# Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME':",
"os.path.join(BASE_DIR, 'whoosh_index'), }, } HAYSTACK_SEARCH_RESULTS_PER_PAGE = 5 HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'",
"False RECORD_VISITOR = True # RECORD_VISITOR = False ALLOWED_HOSTS =",
"paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR =",
"(CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' #STATIC_ROOT =",
"STORED['db_user'], 'PASSWORD': STORED['<PASSWORD>'], 'HOST': '127.0.0.1', 'PORT': 3306, 'OPTIONS': { 'autocommit':",
"}, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, {",
"inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))",
"'Format', 'Font', 'FontSize'], ['TextColor', 'BGColor'], ), 'extraPlugins': 'codesnippet', } }",
"'-', 'Templates'], ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-','Print','SpellChecker','Scayt'], ['Undo', 'Redo',",
"'default': { 'ENGINE': 'blog.whoosh_cn_backend.WhooshEngine', 'PATH': os.path.join(BASE_DIR, 'whoosh_index'), }, } HAYSTACK_SEARCH_RESULTS_PER_PAGE",
"DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': STORED['db_name'], 'USER':",
"{ 'ENGINE': 'blog.whoosh_cn_backend.WhooshEngine', 'PATH': os.path.join(BASE_DIR, 'whoosh_index'), }, } HAYSTACK_SEARCH_RESULTS_PER_PAGE =",
"key used in production secret! SECRET_KEY = STORED['secret_key'] # SECURITY",
"like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) with open(os.path.join(BASE_DIR, \"store.json\"),",
"True # RECORD_VISITOR = False ALLOWED_HOSTS = ['*',] APPEND_SLASH =",
"'Replace', '-', 'SelectAll', 'RemoveFormat','-','Maximize', 'ShowBlocks', '-',\"CodeSnippet\", 'Subscript', 'Superscript'], ['Form', 'Checkbox',",
"# Build paths inside the project like this: os.path.join(BASE_DIR, ...)",
"the secret key used in production secret! SECRET_KEY = STORED['secret_key']",
"= { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': STORED['db_name'], 'USER': STORED['db_user'],",
"'bobjiang.context_processors.device' ], }, }, ] WSGI_APPLICATION = 'bobjiang.wsgi.application' # Database",
"3306, 'OPTIONS': { 'autocommit': True, }, } } # Password",
"] ROOT_URLCONF = 'bobjiang.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates',",
"TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS':",
"STATICFILES_DIRS = [ os.path.join(BASE_DIR, \"static\"), ] #STATIC_ROOT = '/home/bob/djproject/bobjiang/blog/static/' MEDIA_ROOT",
"{ 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME':",
"os.path.join(BASE_DIR, \"static\"), ] #STATIC_ROOT = '/home/bob/djproject/bobjiang/blog/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')",
"on in production! # DEBUG = True DEBUG = False",
"{ 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] #",
"[ os.path.join(BASE_DIR, \"static\"), ] #STATIC_ROOT = '/home/bob/djproject/bobjiang/blog/static/' MEDIA_ROOT = os.path.join(BASE_DIR,",
"'django.contrib.staticfiles', 'main', 'comments', 'ckeditor', 'ckeditor_uploader', 'tool', 'accounting', #'xadmin', #'crispy_forms', ]",
"'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'comments', 'ckeditor', 'ckeditor_uploader', 'tool', 'accounting', #'xadmin',",
"full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ \"\"\"",
"JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' #STATIC_ROOT = os.path.join(BASE_DIR,",
"'default': { 'toolbar': (['div', 'Source', '-', 'Save', 'NewPage', 'Preview', '-',",
"['Bold', 'Italic', 'Underline', 'Strike', '-'], ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent',",
"'PageBreak'], ['Styles', 'Format', 'Font', 'FontSize'], ['TextColor', 'BGColor'], ), 'extraPlugins': 'codesnippet',",
"= True # Application definition INSTALLED_APPS = [ 'haystack', 'blog.apps.BlogConfig',",
"'127.0.0.1', 'PORT': 3306, 'OPTIONS': { 'autocommit': True, }, } }",
"with debug turned on in production! # DEBUG = True",
"\"store.json\"), \"r\") as store_file: STORED = json.load(store_file) # Quick-start development",
"ALLOWED_HOSTS = ['*',] APPEND_SLASH = True # Application definition INSTALLED_APPS",
"import os import json # Build paths inside the project",
"SECURITY WARNING: don't run with debug turned on in production!",
"= json.load(store_file) # Quick-start development settings - unsuitable for production",
"'Save', 'NewPage', 'Preview', '-', 'Templates'], ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord',",
"'-',\"CodeSnippet\", 'Subscript', 'Superscript'], ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button',",
"'NewPage', 'Preview', '-', 'Templates'], ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-','Print','SpellChecker','Scayt'],",
"'-', 'Save', 'NewPage', 'Preview', '-', 'Templates'], ['Cut', 'Copy', 'Paste', 'PasteText',",
"#STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, \"static\"), ]",
"#'xadmin', #'crispy_forms', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware',",
"'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug',",
"'JustifyBlock'], ['Link', 'Unlink', 'Anchor'], ['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar',",
"'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'comments', 'ckeditor', 'ckeditor_uploader', 'tool',",
"USE_TZ = False # Static files (CSS, JavaScript, Images) #",
"USE_L10N = True USE_TZ = False # Static files (CSS,",
"'django-admin startproject' using Django 2.0.6. For more information on this",
"'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', },",
"True DEBUG = False RECORD_VISITOR = True # RECORD_VISITOR =",
"[ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF",
"} # haystack HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'blog.whoosh_cn_backend.WhooshEngine',",
"}, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ #LANGUAGE_CODE = 'en-us' LANGUAGE_CODE",
"= { 'default': { 'ENGINE': 'blog.whoosh_cn_backend.WhooshEngine', 'PATH': os.path.join(BASE_DIR, 'whoosh_index'), },",
"'ENGINE': 'django.db.backends.mysql', 'NAME': STORED['db_name'], 'USER': STORED['db_user'], 'PASSWORD': STORED['<PASSWORD>'], 'HOST': '127.0.0.1',",
"{ 'autocommit': True, }, } } # Password validation #",
"'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',",
"= [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True,",
"'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'comments', 'ckeditor',",
"https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' #STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS =",
"'RemoveFormat','-','Maximize', 'ShowBlocks', '-',\"CodeSnippet\", 'Subscript', 'Superscript'], ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea',",
"CKEDITOR_CONFIGS = { 'default': { 'toolbar': (['div', 'Source', '-', 'Save',",
"{ 'default': { 'toolbar': (['div', 'Source', '-', 'Save', 'NewPage', 'Preview',",
"APPEND_SLASH = True # Application definition INSTALLED_APPS = [ 'haystack',",
"CKEDITOR_IMAGE_BACKEND = 'pillow' CKEDITOR_BROWSE_SHOW_DIRS = True CKEDITOR_RESTRICT_BY_USER = True CKEDITOR_CONFIGS",
"} # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ {",
"'-', 'Find', 'Replace', '-', 'SelectAll', 'RemoveFormat','-','Maximize', 'ShowBlocks', '-',\"CodeSnippet\", 'Subscript', 'Superscript'],",
"'Outdent', 'Indent', 'Blockquote'], ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ['Link', 'Unlink', 'Anchor'],",
"used in production secret! SECRET_KEY = STORED['secret_key'] # SECURITY WARNING:",
"True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'bobjiang.context_processors.device'",
"more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full",
"'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization #",
"information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list",
"False ALLOWED_HOSTS = ['*',] APPEND_SLASH = True # Application definition",
"] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ #LANGUAGE_CODE = 'en-us' LANGUAGE_CODE =",
"'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'bobjiang.urls' TEMPLATES",
"'BGColor'], ), 'extraPlugins': 'codesnippet', } } # haystack HAYSTACK_CONNECTIONS =",
"True, }, } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS",
"TIME_ZONE = 'Asia/Shanghai' USE_I18N = True USE_L10N = True USE_TZ",
"] WSGI_APPLICATION = 'bobjiang.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES =",
"'ShowBlocks', '-',\"CodeSnippet\", 'Subscript', 'Superscript'], ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select',",
"] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',",
"#'crispy_forms', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware',",
"}, }, ] WSGI_APPLICATION = 'bobjiang.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases",
"startproject' using Django 2.0.6. For more information on this file,",
"# Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL =",
"# RECORD_VISITOR = False ALLOWED_HOSTS = ['*',] APPEND_SLASH = True",
"= 'pillow' CKEDITOR_BROWSE_SHOW_DIRS = True CKEDITOR_RESTRICT_BY_USER = True CKEDITOR_CONFIGS =",
"= 'upload/' CKEDITOR_IMAGE_BACKEND = 'pillow' CKEDITOR_BROWSE_SHOW_DIRS = True CKEDITOR_RESTRICT_BY_USER =",
"'BulletedList', '-', 'Outdent', 'Indent', 'Blockquote'], ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ['Link',",
"'PATH': os.path.join(BASE_DIR, 'whoosh_index'), }, } HAYSTACK_SEARCH_RESULTS_PER_PAGE = 5 HAYSTACK_SIGNAL_PROCESSOR =",
"store_file: STORED = json.load(store_file) # Quick-start development settings - unsuitable",
"unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep",
"}, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ]",
"'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', },",
"definition INSTALLED_APPS = [ 'haystack', 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions',",
"for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the",
"'Asia/Shanghai' USE_I18N = True USE_L10N = True USE_TZ = False",
"Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/",
"'Source', '-', 'Save', 'NewPage', 'Preview', '-', 'Templates'], ['Cut', 'Copy', 'Paste',",
"'HiddenField'], ['Bold', 'Italic', 'Underline', 'Strike', '-'], ['NumberedList', 'BulletedList', '-', 'Outdent',",
"and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ \"\"\" import os import json",
"production! # DEBUG = True DEBUG = False RECORD_VISITOR =",
"True CKEDITOR_RESTRICT_BY_USER = True CKEDITOR_CONFIGS = { 'default': { 'toolbar':",
"'en-us' LANGUAGE_CODE = 'zh-hans' TIME_ZONE = 'Asia/Shanghai' USE_I18N = True",
"# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, {",
"= os.path.dirname(os.path.dirname(os.path.abspath(__file__))) with open(os.path.join(BASE_DIR, \"store.json\"), \"r\") as store_file: STORED =",
"= True USE_TZ = False # Static files (CSS, JavaScript,",
"} } # haystack HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE':",
"'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'bobjiang.context_processors.device' ], }, }, ] WSGI_APPLICATION",
"\"r\") as store_file: STORED = json.load(store_file) # Quick-start development settings",
"DEBUG = True DEBUG = False RECORD_VISITOR = True #",
"False # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL",
"'Paste', 'PasteText', 'PasteFromWord', '-','Print','SpellChecker','Scayt'], ['Undo', 'Redo', '-', 'Find', 'Replace', '-',",
"AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',",
"['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-','Print','SpellChecker','Scayt'], ['Undo', 'Redo', '-', 'Find',",
"'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'bobjiang.urls' TEMPLATES = [ {",
"= os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, \"static\"), ] #STATIC_ROOT",
"Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/'",
"'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization",
"'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'], ['Bold', 'Italic',",
"# SECURITY WARNING: don't run with debug turned on in",
"'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages',",
"'Font', 'FontSize'], ['TextColor', 'BGColor'], ), 'extraPlugins': 'codesnippet', } } #",
"['*',] APPEND_SLASH = True # Application definition INSTALLED_APPS = [",
"'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'bobjiang.urls'",
"= False ALLOWED_HOSTS = ['*',] APPEND_SLASH = True # Application",
"ROOT_URLCONF = 'bobjiang.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS':",
"# https://docs.djangoproject.com/en/2.0/topics/i18n/ #LANGUAGE_CODE = 'en-us' LANGUAGE_CODE = 'zh-hans' TIME_ZONE =",
"'Italic', 'Underline', 'Strike', '-'], ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', 'Blockquote'],",
"debug turned on in production! # DEBUG = True DEBUG",
"the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/",
"project. Generated by 'django-admin startproject' using Django 2.0.6. For more",
"'/home/bob/djproject/bobjiang/blog/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' CKEDITOR_UPLOAD_PATH =",
"'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'], ['Bold', 'Italic', 'Underline',",
"{ 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': STORED['db_name'], 'USER': STORED['db_user'], 'PASSWORD':",
"WSGI_APPLICATION = 'bobjiang.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = {",
"'Smiley', 'SpecialChar', 'PageBreak'], ['Styles', 'Format', 'Font', 'FontSize'], ['TextColor', 'BGColor'], ),",
"] #STATIC_ROOT = '/home/bob/djproject/bobjiang/blog/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL =",
"= True DEBUG = False RECORD_VISITOR = True # RECORD_VISITOR",
"2.0.6. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For",
"Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',",
"'Redo', '-', 'Find', 'Replace', '-', 'SelectAll', 'RemoveFormat','-','Maximize', 'ShowBlocks', '-',\"CodeSnippet\", 'Subscript',",
"settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ \"\"\" import os import",
"STORED['secret_key'] # SECURITY WARNING: don't run with debug turned on",
"WARNING: don't run with debug turned on in production! #",
"'toolbar': (['div', 'Source', '-', 'Save', 'NewPage', 'Preview', '-', 'Templates'], ['Cut',",
"see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their",
"['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', 'Blockquote'], ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],",
"For the full list of settings and their values, see",
"...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) with open(os.path.join(BASE_DIR, \"store.json\"), \"r\") as store_file:",
"https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME':",
"'PasteFromWord', '-','Print','SpellChecker','Scayt'], ['Undo', 'Redo', '-', 'Find', 'Replace', '-', 'SelectAll', 'RemoveFormat','-','Maximize',",
"INSTALLED_APPS = [ 'haystack', 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages',",
"see https://docs.djangoproject.com/en/2.0/ref/settings/ \"\"\" import os import json # Build paths",
"'-'], ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', 'Blockquote'], ['JustifyLeft', 'JustifyCenter', 'JustifyRight',",
"'Strike', '-'], ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', 'Blockquote'], ['JustifyLeft', 'JustifyCenter',",
"= '/static/' #STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR,",
"'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak'], ['Styles', 'Format', 'Font', 'FontSize'], ['TextColor',",
"SECRET_KEY = STORED['secret_key'] # SECURITY WARNING: don't run with debug",
"Django 2.0.6. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/",
"'main', 'comments', 'ckeditor', 'ckeditor_uploader', 'tool', 'accounting', #'xadmin', #'crispy_forms', ] MIDDLEWARE",
"don't run with debug turned on in production! # DEBUG",
"'tool', 'accounting', #'xadmin', #'crispy_forms', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware',",
"}, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/",
"True USE_TZ = False # Static files (CSS, JavaScript, Images)",
"= 'en-us' LANGUAGE_CODE = 'zh-hans' TIME_ZONE = 'Asia/Shanghai' USE_I18N =",
"BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) with open(os.path.join(BASE_DIR, \"store.json\"), \"r\") as store_file: STORED",
"'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors':",
"'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'comments', 'ckeditor', 'ckeditor_uploader', 'tool', 'accounting',",
"{ 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ #LANGUAGE_CODE",
"'USER': STORED['db_user'], 'PASSWORD': STORED['<PASSWORD>'], 'HOST': '127.0.0.1', 'PORT': 3306, 'OPTIONS': {",
"this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) with open(os.path.join(BASE_DIR, \"store.json\"), \"r\")",
"Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ #LANGUAGE_CODE = 'en-us' LANGUAGE_CODE = 'zh-hans' TIME_ZONE",
"WARNING: keep the secret key used in production secret! SECRET_KEY",
"https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': STORED['db_name'],",
"os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' CKEDITOR_UPLOAD_PATH = 'upload/' CKEDITOR_IMAGE_BACKEND =",
"True # Application definition INSTALLED_APPS = [ 'haystack', 'blog.apps.BlogConfig', 'django.contrib.admin',",
"= [ 'haystack', 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',",
"json # Build paths inside the project like this: os.path.join(BASE_DIR,",
"= True # RECORD_VISITOR = False ALLOWED_HOSTS = ['*',] APPEND_SLASH",
"'JustifyRight', 'JustifyBlock'], ['Link', 'Unlink', 'Anchor'], ['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley',",
"production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret",
"'PasteText', 'PasteFromWord', '-','Print','SpellChecker','Scayt'], ['Undo', 'Redo', '-', 'Find', 'Replace', '-', 'SelectAll',",
"# https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME':",
"'PORT': 3306, 'OPTIONS': { 'autocommit': True, }, } } #",
"['TextColor', 'BGColor'], ), 'extraPlugins': 'codesnippet', } } # haystack HAYSTACK_CONNECTIONS",
"STORED = json.load(store_file) # Quick-start development settings - unsuitable for",
"'-','Print','SpellChecker','Scayt'], ['Undo', 'Redo', '-', 'Find', 'Replace', '-', 'SelectAll', 'RemoveFormat','-','Maximize', 'ShowBlocks',",
"= STORED['secret_key'] # SECURITY WARNING: don't run with debug turned",
"# DEBUG = True DEBUG = False RECORD_VISITOR = True",
"= True CKEDITOR_RESTRICT_BY_USER = True CKEDITOR_CONFIGS = { 'default': {",
"= 'Asia/Shanghai' USE_I18N = True USE_L10N = True USE_TZ =",
"'/media/' CKEDITOR_UPLOAD_PATH = 'upload/' CKEDITOR_IMAGE_BACKEND = 'pillow' CKEDITOR_BROWSE_SHOW_DIRS = True",
"by 'django-admin startproject' using Django 2.0.6. For more information on",
"{ 'ENGINE': 'django.db.backends.mysql', 'NAME': STORED['db_name'], 'USER': STORED['db_user'], 'PASSWORD': STORED['<PASSWORD>'], 'HOST':",
"'haystack', 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'comments',",
"= [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]",
"secret key used in production secret! SECRET_KEY = STORED['secret_key'] #",
"'upload/' CKEDITOR_IMAGE_BACKEND = 'pillow' CKEDITOR_BROWSE_SHOW_DIRS = True CKEDITOR_RESTRICT_BY_USER = True",
"# haystack HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'blog.whoosh_cn_backend.WhooshEngine', 'PATH':",
"project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) with open(os.path.join(BASE_DIR,",
"Django settings for bobjiang project. Generated by 'django-admin startproject' using",
"CKEDITOR_RESTRICT_BY_USER = True CKEDITOR_CONFIGS = { 'default': { 'toolbar': (['div',",
"STATIC_URL = '/static/' #STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [",
"'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak'], ['Styles', 'Format', 'Font', 'FontSize'],",
"'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'bobjiang.urls' TEMPLATES =",
"the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) with",
"\"static\"), ] #STATIC_ROOT = '/home/bob/djproject/bobjiang/blog/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL",
"HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'blog.whoosh_cn_backend.WhooshEngine', 'PATH': os.path.join(BASE_DIR, 'whoosh_index'),",
"import json # Build paths inside the project like this:",
"'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'bobjiang.context_processors.device' ], }, }, ] WSGI_APPLICATION =",
"'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'bobjiang.urls' TEMPLATES = [ { 'BACKEND':",
"'Templates'], ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-','Print','SpellChecker','Scayt'], ['Undo', 'Redo', '-',",
"['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'], ['Bold',",
"'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',",
"file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and",
"}, } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS =",
"See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used",
"[ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, {",
"<reponame>bobjiangps/django-blog<filename>bobjiang/settings.py \"\"\" Django settings for bobjiang project. Generated by 'django-admin",
"'Superscript'], ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'],",
"USE_I18N = True USE_L10N = True USE_TZ = False #",
"os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, \"static\"), ] #STATIC_ROOT =",
"open(os.path.join(BASE_DIR, \"store.json\"), \"r\") as store_file: STORED = json.load(store_file) # Quick-start",
"using Django 2.0.6. For more information on this file, see",
"'ckeditor', 'ckeditor_uploader', 'tool', 'accounting', #'xadmin', #'crispy_forms', ] MIDDLEWARE = [",
"'FontSize'], ['TextColor', 'BGColor'], ), 'extraPlugins': 'codesnippet', } } # haystack",
"'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': STORED['db_name'], 'USER': STORED['db_user'], 'PASSWORD': STORED['<PASSWORD>'],",
"= '/home/bob/djproject/bobjiang/blog/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' CKEDITOR_UPLOAD_PATH",
"{ 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'bobjiang.context_processors.device' ], },",
"CKEDITOR_BROWSE_SHOW_DIRS = True CKEDITOR_RESTRICT_BY_USER = True CKEDITOR_CONFIGS = { 'default':",
"- unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING:",
"'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'bobjiang.context_processors.device' ], }, }, ] WSGI_APPLICATION = 'bobjiang.wsgi.application'",
"MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' CKEDITOR_UPLOAD_PATH = 'upload/'",
"[os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request',",
"'ENGINE': 'blog.whoosh_cn_backend.WhooshEngine', 'PATH': os.path.join(BASE_DIR, 'whoosh_index'), }, } HAYSTACK_SEARCH_RESULTS_PER_PAGE = 5",
"}, ] WSGI_APPLICATION = 'bobjiang.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES",
"['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ['Link', 'Unlink', 'Anchor'], ['Image', 'Flash', 'Table',",
"[ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS':",
"[ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'bobjiang.context_processors.device' ], }, }, ]",
"STORED['<PASSWORD>'], 'HOST': '127.0.0.1', 'PORT': 3306, 'OPTIONS': { 'autocommit': True, },",
"} } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [",
"= 'bobjiang.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default':",
"'codesnippet', } } # haystack HAYSTACK_CONNECTIONS = { 'default': {",
"= os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' CKEDITOR_UPLOAD_PATH = 'upload/' CKEDITOR_IMAGE_BACKEND",
"'NAME': STORED['db_name'], 'USER': STORED['db_user'], 'PASSWORD': STORED['<PASSWORD>'], 'HOST': '127.0.0.1', 'PORT': 3306,",
"'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [",
"'PASSWORD': STORED['<PASSWORD>'], 'HOST': '127.0.0.1', 'PORT': 3306, 'OPTIONS': { 'autocommit': True,",
"json.load(store_file) # Quick-start development settings - unsuitable for production #",
"'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ['Link', 'Unlink', 'Anchor'], ['Image', 'Flash', 'Table', 'HorizontalRule',",
"os import json # Build paths inside the project like",
"SECURITY WARNING: keep the secret key used in production secret!",
"['Link', 'Unlink', 'Anchor'], ['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak'],",
"'media') MEDIA_URL = '/media/' CKEDITOR_UPLOAD_PATH = 'upload/' CKEDITOR_IMAGE_BACKEND = 'pillow'",
"https://docs.djangoproject.com/en/2.0/topics/i18n/ #LANGUAGE_CODE = 'en-us' LANGUAGE_CODE = 'zh-hans' TIME_ZONE = 'Asia/Shanghai'",
"= False RECORD_VISITOR = True # RECORD_VISITOR = False ALLOWED_HOSTS",
"'comments', 'ckeditor', 'ckeditor_uploader', 'tool', 'accounting', #'xadmin', #'crispy_forms', ] MIDDLEWARE =",
"RECORD_VISITOR = True # RECORD_VISITOR = False ALLOWED_HOSTS = ['*',]",
"'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'comments', 'ckeditor', 'ckeditor_uploader', 'tool', 'accounting', #'xadmin', #'crispy_forms',",
"'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'bobjiang.context_processors.device' ], }, },",
"values, see https://docs.djangoproject.com/en/2.0/ref/settings/ \"\"\" import os import json # Build",
"'accounting', #'xadmin', #'crispy_forms', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware',",
"'Find', 'Replace', '-', 'SelectAll', 'RemoveFormat','-','Maximize', 'ShowBlocks', '-',\"CodeSnippet\", 'Subscript', 'Superscript'], ['Form',",
"LANGUAGE_CODE = 'zh-hans' TIME_ZONE = 'Asia/Shanghai' USE_I18N = True USE_L10N",
"bobjiang project. Generated by 'django-admin startproject' using Django 2.0.6. For",
"= 'zh-hans' TIME_ZONE = 'Asia/Shanghai' USE_I18N = True USE_L10N =",
"'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-','Print','SpellChecker','Scayt'], ['Undo', 'Redo', '-', 'Find', 'Replace',",
"settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY",
"'blog.whoosh_cn_backend.WhooshEngine', 'PATH': os.path.join(BASE_DIR, 'whoosh_index'), }, } HAYSTACK_SEARCH_RESULTS_PER_PAGE = 5 HAYSTACK_SIGNAL_PROCESSOR",
"'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ #LANGUAGE_CODE =",
"'zh-hans' TIME_ZONE = 'Asia/Shanghai' USE_I18N = True USE_L10N = True",
"'SpecialChar', 'PageBreak'], ['Styles', 'Format', 'Font', 'FontSize'], ['TextColor', 'BGColor'], ), 'extraPlugins':",
"'Button', 'ImageButton', 'HiddenField'], ['Bold', 'Italic', 'Underline', 'Strike', '-'], ['NumberedList', 'BulletedList',",
"'OPTIONS': { 'autocommit': True, }, } } # Password validation",
"'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF =",
"{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': {",
"True USE_L10N = True USE_TZ = False # Static files",
"= [ os.path.join(BASE_DIR, \"static\"), ] #STATIC_ROOT = '/home/bob/djproject/bobjiang/blog/static/' MEDIA_ROOT =",
"'bobjiang.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')],",
"{ 'toolbar': (['div', 'Source', '-', 'Save', 'NewPage', 'Preview', '-', 'Templates'],",
"os.path.dirname(os.path.dirname(os.path.abspath(__file__))) with open(os.path.join(BASE_DIR, \"store.json\"), \"r\") as store_file: STORED = json.load(store_file)",
"'Select', 'Button', 'ImageButton', 'HiddenField'], ['Bold', 'Italic', 'Underline', 'Strike', '-'], ['NumberedList',",
"['Styles', 'Format', 'Font', 'FontSize'], ['TextColor', 'BGColor'], ), 'extraPlugins': 'codesnippet', }",
"= [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', },",
"'Underline', 'Strike', '-'], ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', 'Blockquote'], ['JustifyLeft',",
"\"\"\" import os import json # Build paths inside the",
"their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ \"\"\" import os import json #",
"as store_file: STORED = json.load(store_file) # Quick-start development settings -",
"# Quick-start development settings - unsuitable for production # See",
"True CKEDITOR_CONFIGS = { 'default': { 'toolbar': (['div', 'Source', '-',",
"= True CKEDITOR_CONFIGS = { 'default': { 'toolbar': (['div', 'Source',",
"\"\"\" Django settings for bobjiang project. Generated by 'django-admin startproject'",
"settings for bobjiang project. Generated by 'django-admin startproject' using Django",
"'Anchor'], ['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak'], ['Styles', 'Format',",
"#STATIC_ROOT = '/home/bob/djproject/bobjiang/blog/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/'",
"os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) with open(os.path.join(BASE_DIR, \"store.json\"), \"r\") as",
"Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' #STATIC_ROOT = os.path.join(BASE_DIR, 'static')",
"'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'comments', 'ckeditor', 'ckeditor_uploader',",
"'pillow' CKEDITOR_BROWSE_SHOW_DIRS = True CKEDITOR_RESTRICT_BY_USER = True CKEDITOR_CONFIGS = {",
"'Blockquote'], ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ['Link', 'Unlink', 'Anchor'], ['Image', 'Flash',",
"For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the",
"(['div', 'Source', '-', 'Save', 'NewPage', 'Preview', '-', 'Templates'], ['Cut', 'Copy',",
"['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak'], ['Styles', 'Format', 'Font',",
"'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak'], ['Styles', 'Format', 'Font', 'FontSize'], ['TextColor', 'BGColor'],",
"= ['*',] APPEND_SLASH = True # Application definition INSTALLED_APPS =",
"['Undo', 'Redo', '-', 'Find', 'Replace', '-', 'SelectAll', 'RemoveFormat','-','Maximize', 'ShowBlocks', '-',\"CodeSnippet\",",
"in production! # DEBUG = True DEBUG = False RECORD_VISITOR",
"'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'bobjiang.context_processors.device' ],",
"MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',",
"#LANGUAGE_CODE = 'en-us' LANGUAGE_CODE = 'zh-hans' TIME_ZONE = 'Asia/Shanghai' USE_I18N",
"secret! SECRET_KEY = STORED['secret_key'] # SECURITY WARNING: don't run with",
"of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ \"\"\" import os",
"# Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE':",
"'Indent', 'Blockquote'], ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ['Link', 'Unlink', 'Anchor'], ['Image',",
"= False # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/",
"https://docs.djangoproject.com/en/2.0/ref/settings/ \"\"\" import os import json # Build paths inside",
"CKEDITOR_UPLOAD_PATH = 'upload/' CKEDITOR_IMAGE_BACKEND = 'pillow' CKEDITOR_BROWSE_SHOW_DIRS = True CKEDITOR_RESTRICT_BY_USER",
"with open(os.path.join(BASE_DIR, \"store.json\"), \"r\") as store_file: STORED = json.load(store_file) #",
"Application definition INSTALLED_APPS = [ 'haystack', 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes',",
"# SECURITY WARNING: keep the secret key used in production",
"= 'bobjiang.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,",
"'ImageButton', 'HiddenField'], ['Bold', 'Italic', 'Underline', 'Strike', '-'], ['NumberedList', 'BulletedList', '-',",
"production secret! SECRET_KEY = STORED['secret_key'] # SECURITY WARNING: don't run",
"https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values,",
"'ckeditor_uploader', 'tool', 'accounting', #'xadmin', #'crispy_forms', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware',",
"], }, }, ] WSGI_APPLICATION = 'bobjiang.wsgi.application' # Database #",
"'autocommit': True, }, } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators",
"list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ \"\"\" import",
"this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings",
"'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'bobjiang.urls' TEMPLATES = [",
"'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth',",
"run with debug turned on in production! # DEBUG =",
"RECORD_VISITOR = False ALLOWED_HOSTS = ['*',] APPEND_SLASH = True #",
"Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR",
"'django.contrib.messages.context_processors.messages', 'bobjiang.context_processors.device' ], }, }, ] WSGI_APPLICATION = 'bobjiang.wsgi.application' #",
"turned on in production! # DEBUG = True DEBUG =",
"'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ #LANGUAGE_CODE = 'en-us'",
"'extraPlugins': 'codesnippet', } } # haystack HAYSTACK_CONNECTIONS = { 'default':",
"STORED['db_name'], 'USER': STORED['db_user'], 'PASSWORD': STORED['<PASSWORD>'], 'HOST': '127.0.0.1', 'PORT': 3306, 'OPTIONS':",
"validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', },",
"'SelectAll', 'RemoveFormat','-','Maximize', 'ShowBlocks', '-',\"CodeSnippet\", 'Subscript', 'Superscript'], ['Form', 'Checkbox', 'Radio', 'TextField',",
"in production secret! SECRET_KEY = STORED['secret_key'] # SECURITY WARNING: don't",
"= { 'default': { 'toolbar': (['div', 'Source', '-', 'Save', 'NewPage',",
"{ 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME':",
"'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'], ['Bold', 'Italic', 'Underline', 'Strike',",
"development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ #",
"'Unlink', 'Anchor'], ['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak'], ['Styles',",
"on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of",
"), 'extraPlugins': 'codesnippet', } } # haystack HAYSTACK_CONNECTIONS = {",
"[ 'haystack', 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main',",
"= True USE_L10N = True USE_TZ = False # Static",
"'-', 'SelectAll', 'RemoveFormat','-','Maximize', 'ShowBlocks', '-',\"CodeSnippet\", 'Subscript', 'Superscript'], ['Form', 'Checkbox', 'Radio',",
"= '/media/' CKEDITOR_UPLOAD_PATH = 'upload/' CKEDITOR_IMAGE_BACKEND = 'pillow' CKEDITOR_BROWSE_SHOW_DIRS =",
"'Subscript', 'Superscript'], ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton',",
"'Preview', '-', 'Templates'], ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-','Print','SpellChecker','Scayt'], ['Undo',",
"'bobjiang.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': {",
"'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'], ['Bold', 'Italic', 'Underline', 'Strike', '-'],",
"'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, \"static\"), ] #STATIC_ROOT = '/home/bob/djproject/bobjiang/blog/static/'",
"keep the secret key used in production secret! SECRET_KEY =",
"files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' #STATIC_ROOT",
"'django.db.backends.mysql', 'NAME': STORED['db_name'], 'USER': STORED['db_user'], 'PASSWORD': STORED['<PASSWORD>'], 'HOST': '127.0.0.1', 'PORT':",
"# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key",
"Generated by 'django-admin startproject' using Django 2.0.6. For more information",
"MEDIA_URL = '/media/' CKEDITOR_UPLOAD_PATH = 'upload/' CKEDITOR_IMAGE_BACKEND = 'pillow' CKEDITOR_BROWSE_SHOW_DIRS",
"Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql',",
"# Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ #LANGUAGE_CODE = 'en-us' LANGUAGE_CODE = 'zh-hans'",
"'-', 'Outdent', 'Indent', 'Blockquote'], ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ['Link', 'Unlink',",
"'/static/' #STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, \"static\"),"
] |
[
"def __str__(self): return f'{self.user.username} Profile' def save(self,*args,**kwargs): super().save() img =",
"super().save() img = Image(self.prof_pic.path) if img.height > 300 and img.width",
"import User from PIL import Image class Profile(models.Model): user =",
"Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pic/') def",
"from django.db import models from django.contrib.auth.models import User from PIL",
"from PIL import Image class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE)",
"img = Image(self.prof_pic.path) if img.height > 300 and img.width >",
"Image class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg',",
"save(self,*args,**kwargs): super().save() img = Image(self.prof_pic.path) if img.height > 300 and",
"models.ImageField(default='default.jpg', upload_to='profile_pic/') def __str__(self): return f'{self.user.username} Profile' def save(self,*args,**kwargs): super().save()",
"PIL import Image class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) image",
"Image(self.prof_pic.path) if img.height > 300 and img.width > 300: output_size",
"import models from django.contrib.auth.models import User from PIL import Image",
"> 300 and img.width > 300: output_size = (300,300) img.thumbnail(output_size)",
"django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user",
"models from django.contrib.auth.models import User from PIL import Image class",
"from django.contrib.auth.models import User from PIL import Image class Profile(models.Model):",
"300 and img.width > 300: output_size = (300,300) img.thumbnail(output_size) img.save(self.prof_pic.path)",
"if img.height > 300 and img.width > 300: output_size =",
"def save(self,*args,**kwargs): super().save() img = Image(self.prof_pic.path) if img.height > 300",
"import Image class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) image =",
"upload_to='profile_pic/') def __str__(self): return f'{self.user.username} Profile' def save(self,*args,**kwargs): super().save() img",
"user = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pic/') def __str__(self):",
"f'{self.user.username} Profile' def save(self,*args,**kwargs): super().save() img = Image(self.prof_pic.path) if img.height",
"__str__(self): return f'{self.user.username} Profile' def save(self,*args,**kwargs): super().save() img = Image(self.prof_pic.path)",
"img.height > 300 and img.width > 300: output_size = (300,300)",
"= models.ImageField(default='default.jpg', upload_to='profile_pic/') def __str__(self): return f'{self.user.username} Profile' def save(self,*args,**kwargs):",
"return f'{self.user.username} Profile' def save(self,*args,**kwargs): super().save() img = Image(self.prof_pic.path) if",
"= Image(self.prof_pic.path) if img.height > 300 and img.width > 300:",
"on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pic/') def __str__(self): return f'{self.user.username} Profile'",
"Profile' def save(self,*args,**kwargs): super().save() img = Image(self.prof_pic.path) if img.height >",
"class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pic/')",
"image = models.ImageField(default='default.jpg', upload_to='profile_pic/') def __str__(self): return f'{self.user.username} Profile' def",
"User from PIL import Image class Profile(models.Model): user = models.ForeignKey(User,",
"django.db import models from django.contrib.auth.models import User from PIL import",
"= models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pic/') def __str__(self): return",
"models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pic/') def __str__(self): return f'{self.user.username}"
] |
[
"open(VERSIONPATH, 'w+') as fobj: fobj.write('# AUTOGENERATED by dvc/__init__.py\\n') fobj.write('version =",
"# auto-generated version.py to help us provide a true version",
"# and will provide a true version of the installed",
"or something. Hopefully we have our # auto-generated version.py to",
"installed with pip or something. Hopefully we have our #",
"# dvc is run directly from source without installation or",
"are benign and # we can simply ignore them so",
"---- Make your data science projects reproducible and shareable. \"\"\"",
"git.exc import InvalidGitRepositoryError try: repo = Repo(HOMEPATH) except InvalidGitRepositoryError: return",
"with the package # and will provide a true version",
"from git.exc import InvalidGitRepositoryError try: repo = Repo(HOMEPATH) except InvalidGitRepositoryError:",
"== '': __version__ = _update_version_file() else: # pragma: no cover",
"short_sha, dirty) # Write a helper file, that will be",
"from source without installation or # __version__ is called from",
"Write a helper file, that will be installed with the",
"a true version of the installed dvc with open(VERSIONPATH, 'w+')",
"can simply ignore them so that they don't show up",
"directly from source without installation or # __version__ is called",
"or # __version__ is called from setup.py if os.getenv('APPVEYOR_REPO_TAG', '').lower()",
"version from dvc.version import version __version__ = version VERSION =",
"that it doesn't get into the release.\"\"\" if os.path.exists(VERSIONPATH): os.unlink(VERSIONPATH)",
"without installation or # __version__ is called from setup.py if",
"= Repo(HOMEPATH) except InvalidGitRepositoryError: return __version__ sha = repo.head.object.hexsha short_sha",
"'' ver = '{}+{}{}'.format(__version__, short_sha, dirty) # Write a helper",
"os import warnings VERSION_BASE = '0.23.2' __version__ = VERSION_BASE PACKAGEPATH",
"Repo from git.exc import InvalidGitRepositoryError try: repo = Repo(HOMEPATH) except",
"when you are using dvc. warnings.filterwarnings(\"ignore\", message=\"numpy.dtype size changed\") warnings.filterwarnings(\"ignore\",",
"VERSION = __version__ # Ignore numpy's runtime warnings: https://github.com/numpy/numpy/pull/432. #",
"are using dvc. warnings.filterwarnings(\"ignore\", message=\"numpy.dtype size changed\") warnings.filterwarnings(\"ignore\", message=\"numpy.ufunc size",
"'': __version__ = _update_version_file() else: # pragma: no cover _remove_version_file()",
"that they don't show up when you are using dvc.",
"Repo(HOMEPATH) except InvalidGitRepositoryError: return __version__ sha = repo.head.object.hexsha short_sha =",
"'0.23.2' __version__ = VERSION_BASE PACKAGEPATH = os.path.abspath(os.path.dirname(__file__)) HOMEPATH = os.path.dirname(PACKAGEPATH)",
"version __version__ = version VERSION = __version__ # Ignore numpy's",
"dirty = '.mod' if repo.is_dirty() else '' ver = '{}+{}{}'.format(__version__,",
"pragma: no cover _remove_version_file() else: # pragma: no cover #",
"= '{}+{}{}'.format(__version__, short_sha, dirty) # Write a helper file, that",
"dependency networkx does, causing # these warnings in some environments.",
"dvc is run directly from source without installation or #",
"short=6) dirty = '.mod' if repo.is_dirty() else '' ver =",
"Luckily these warnings are benign and # we can simply",
"= repo.git.rev_parse(sha, short=6) dirty = '.mod' if repo.is_dirty() else ''",
"us provide a true version from dvc.version import version __version__",
"our dependency networkx does, causing # these warnings in some",
"dvc with open(VERSIONPATH, 'w+') as fobj: fobj.write('# AUTOGENERATED by dvc/__init__.py\\n')",
"help us provide a true version from dvc.version import version",
"repo.git.rev_parse(sha, short=6) dirty = '.mod' if repo.is_dirty() else '' ver",
"\"{}\"\\n'.format(ver)) return ver def _remove_version_file(): \"\"\"Remove version.py so that it",
"of the installed dvc with open(VERSIONPATH, 'w+') as fobj: fobj.write('#",
"fobj: fobj.write('# AUTOGENERATED by dvc/__init__.py\\n') fobj.write('version = \"{}\"\\n'.format(ver)) return ver",
"PACKAGEPATH = os.path.abspath(os.path.dirname(__file__)) HOMEPATH = os.path.dirname(PACKAGEPATH) VERSIONPATH = os.path.join(PACKAGEPATH, 'version.py')",
"else '' ver = '{}+{}{}'.format(__version__, short_sha, dirty) # Write a",
"git import Repo from git.exc import InvalidGitRepositoryError try: repo =",
"InvalidGitRepositoryError try: repo = Repo(HOMEPATH) except InvalidGitRepositoryError: return __version__ sha",
"no cover # dvc was installed with pip or something.",
"except InvalidGitRepositoryError: return __version__ sha = repo.head.object.hexsha short_sha = repo.git.rev_parse(sha,",
"os.path.exists(VERSIONPATH): os.unlink(VERSIONPATH) if os.path.exists(os.path.join(HOMEPATH, 'setup.py')): # dvc is run directly",
"provide a true version of the installed dvc with open(VERSIONPATH,",
"networkx does, causing # these warnings in some environments. Luckily",
"__version__ = VERSION_BASE PACKAGEPATH = os.path.abspath(os.path.dirname(__file__)) HOMEPATH = os.path.dirname(PACKAGEPATH) VERSIONPATH",
"'version.py') def _update_version_file(): \"\"\"Dynamically update version file.\"\"\" from git import",
"'setup.py')): # dvc is run directly from source without installation",
"__version__ # Ignore numpy's runtime warnings: https://github.com/numpy/numpy/pull/432. # We don't",
"os.path.exists(os.path.join(HOMEPATH, 'setup.py')): # dvc is run directly from source without",
"true version from dvc.version import version __version__ = version VERSION",
"dvc.version import version __version__ = version VERSION = __version__ #",
"'true' \\ and os.getenv('TRAVIS_TAG', '') == '': __version__ = _update_version_file()",
"pip or something. Hopefully we have our # auto-generated version.py",
"# we can simply ignore them so that they don't",
"os.path.join(PACKAGEPATH, 'version.py') def _update_version_file(): \"\"\"Dynamically update version file.\"\"\" from git",
"using dvc. warnings.filterwarnings(\"ignore\", message=\"numpy.dtype size changed\") warnings.filterwarnings(\"ignore\", message=\"numpy.ufunc size changed\")",
"# dvc was installed with pip or something. Hopefully we",
"def _remove_version_file(): \"\"\"Remove version.py so that it doesn't get into",
"something. Hopefully we have our # auto-generated version.py to help",
"if os.path.exists(os.path.join(HOMEPATH, 'setup.py')): # dvc is run directly from source",
"import os import warnings VERSION_BASE = '0.23.2' __version__ = VERSION_BASE",
"= \"{}\"\\n'.format(ver)) return ver def _remove_version_file(): \"\"\"Remove version.py so that",
"if repo.is_dirty() else '' ver = '{}+{}{}'.format(__version__, short_sha, dirty) #",
"= version VERSION = __version__ # Ignore numpy's runtime warnings:",
"numpy's runtime warnings: https://github.com/numpy/numpy/pull/432. # We don't directly import numpy,",
"_remove_version_file(): \"\"\"Remove version.py so that it doesn't get into the",
"repo.is_dirty() else '' ver = '{}+{}{}'.format(__version__, short_sha, dirty) # Write",
"fobj.write('version = \"{}\"\\n'.format(ver)) return ver def _remove_version_file(): \"\"\"Remove version.py so",
"'.mod' if repo.is_dirty() else '' ver = '{}+{}{}'.format(__version__, short_sha, dirty)",
"file, that will be installed with the package # and",
"_update_version_file(): \"\"\"Dynamically update version file.\"\"\" from git import Repo from",
"so that they don't show up when you are using",
"so that it doesn't get into the release.\"\"\" if os.path.exists(VERSIONPATH):",
"= VERSION_BASE PACKAGEPATH = os.path.abspath(os.path.dirname(__file__)) HOMEPATH = os.path.dirname(PACKAGEPATH) VERSIONPATH =",
"have our # auto-generated version.py to help us provide a",
"warnings in some environments. Luckily these warnings are benign and",
"reproducible and shareable. \"\"\" import os import warnings VERSION_BASE =",
"sha = repo.head.object.hexsha short_sha = repo.git.rev_parse(sha, short=6) dirty = '.mod'",
"_remove_version_file() else: # pragma: no cover # dvc was installed",
"__version__ is called from setup.py if os.getenv('APPVEYOR_REPO_TAG', '').lower() != 'true'",
"fobj.write('# AUTOGENERATED by dvc/__init__.py\\n') fobj.write('version = \"{}\"\\n'.format(ver)) return ver def",
"is called from setup.py if os.getenv('APPVEYOR_REPO_TAG', '').lower() != 'true' \\",
"your data science projects reproducible and shareable. \"\"\" import os",
"it doesn't get into the release.\"\"\" if os.path.exists(VERSIONPATH): os.unlink(VERSIONPATH) if",
"warnings are benign and # we can simply ignore them",
"dirty) # Write a helper file, that will be installed",
"they don't show up when you are using dvc. warnings.filterwarnings(\"ignore\",",
"as fobj: fobj.write('# AUTOGENERATED by dvc/__init__.py\\n') fobj.write('version = \"{}\"\\n'.format(ver)) return",
"AUTOGENERATED by dvc/__init__.py\\n') fobj.write('version = \"{}\"\\n'.format(ver)) return ver def _remove_version_file():",
"cover # dvc was installed with pip or something. Hopefully",
"version.py to help us provide a true version from dvc.version",
"version VERSION = __version__ # Ignore numpy's runtime warnings: https://github.com/numpy/numpy/pull/432.",
"= '.mod' if repo.is_dirty() else '' ver = '{}+{}{}'.format(__version__, short_sha,",
"import numpy, but our dependency networkx does, causing # these",
"our # auto-generated version.py to help us provide a true",
"# We don't directly import numpy, but our dependency networkx",
"# these warnings in some environments. Luckily these warnings are",
"'{}+{}{}'.format(__version__, short_sha, dirty) # Write a helper file, that will",
"to help us provide a true version from dvc.version import",
"dvc/__init__.py\\n') fobj.write('version = \"{}\"\\n'.format(ver)) return ver def _remove_version_file(): \"\"\"Remove version.py",
"Make your data science projects reproducible and shareable. \"\"\" import",
"no cover _remove_version_file() else: # pragma: no cover # dvc",
"# Ignore numpy's runtime warnings: https://github.com/numpy/numpy/pull/432. # We don't directly",
"data science projects reproducible and shareable. \"\"\" import os import",
"# Write a helper file, that will be installed with",
"__version__ sha = repo.head.object.hexsha short_sha = repo.git.rev_parse(sha, short=6) dirty =",
"os.getenv('TRAVIS_TAG', '') == '': __version__ = _update_version_file() else: # pragma:",
"try: repo = Repo(HOMEPATH) except InvalidGitRepositoryError: return __version__ sha =",
"import version __version__ = version VERSION = __version__ # Ignore",
"__version__ = version VERSION = __version__ # Ignore numpy's runtime",
"runtime warnings: https://github.com/numpy/numpy/pull/432. # We don't directly import numpy, but",
"package # and will provide a true version of the",
"be installed with the package # and will provide a",
"= os.path.join(PACKAGEPATH, 'version.py') def _update_version_file(): \"\"\"Dynamically update version file.\"\"\" from",
"<reponame>zjj2wry/dvc<filename>dvc/__init__.py \"\"\" DVC ---- Make your data science projects reproducible",
"these warnings are benign and # we can simply ignore",
"else: # pragma: no cover _remove_version_file() else: # pragma: no",
"doesn't get into the release.\"\"\" if os.path.exists(VERSIONPATH): os.unlink(VERSIONPATH) if os.path.exists(os.path.join(HOMEPATH,",
"science projects reproducible and shareable. \"\"\" import os import warnings",
"os.getenv('APPVEYOR_REPO_TAG', '').lower() != 'true' \\ and os.getenv('TRAVIS_TAG', '') == '':",
"and shareable. \"\"\" import os import warnings VERSION_BASE = '0.23.2'",
"return __version__ sha = repo.head.object.hexsha short_sha = repo.git.rev_parse(sha, short=6) dirty",
"get into the release.\"\"\" if os.path.exists(VERSIONPATH): os.unlink(VERSIONPATH) if os.path.exists(os.path.join(HOMEPATH, 'setup.py')):",
"causing # these warnings in some environments. Luckily these warnings",
"installed dvc with open(VERSIONPATH, 'w+') as fobj: fobj.write('# AUTOGENERATED by",
"ignore them so that they don't show up when you",
"and # we can simply ignore them so that they",
"repo = Repo(HOMEPATH) except InvalidGitRepositoryError: return __version__ sha = repo.head.object.hexsha",
"show up when you are using dvc. warnings.filterwarnings(\"ignore\", message=\"numpy.dtype size",
"__version__ = _update_version_file() else: # pragma: no cover _remove_version_file() else:",
"VERSIONPATH = os.path.join(PACKAGEPATH, 'version.py') def _update_version_file(): \"\"\"Dynamically update version file.\"\"\"",
"cover _remove_version_file() else: # pragma: no cover # dvc was",
"ver = '{}+{}{}'.format(__version__, short_sha, dirty) # Write a helper file,",
"simply ignore them so that they don't show up when",
"pragma: no cover # dvc was installed with pip or",
"We don't directly import numpy, but our dependency networkx does,",
"some environments. Luckily these warnings are benign and # we",
"the release.\"\"\" if os.path.exists(VERSIONPATH): os.unlink(VERSIONPATH) if os.path.exists(os.path.join(HOMEPATH, 'setup.py')): # dvc",
"os.path.abspath(os.path.dirname(__file__)) HOMEPATH = os.path.dirname(PACKAGEPATH) VERSIONPATH = os.path.join(PACKAGEPATH, 'version.py') def _update_version_file():",
"_update_version_file() else: # pragma: no cover _remove_version_file() else: # pragma:",
"environments. Luckily these warnings are benign and # we can",
"update version file.\"\"\" from git import Repo from git.exc import",
"auto-generated version.py to help us provide a true version from",
"projects reproducible and shareable. \"\"\" import os import warnings VERSION_BASE",
"don't directly import numpy, but our dependency networkx does, causing",
"import Repo from git.exc import InvalidGitRepositoryError try: repo = Repo(HOMEPATH)",
"os.unlink(VERSIONPATH) if os.path.exists(os.path.join(HOMEPATH, 'setup.py')): # dvc is run directly from",
"installed with the package # and will provide a true",
"the installed dvc with open(VERSIONPATH, 'w+') as fobj: fobj.write('# AUTOGENERATED",
"a true version from dvc.version import version __version__ = version",
"VERSION_BASE = '0.23.2' __version__ = VERSION_BASE PACKAGEPATH = os.path.abspath(os.path.dirname(__file__)) HOMEPATH",
"from dvc.version import version __version__ = version VERSION = __version__",
"if os.getenv('APPVEYOR_REPO_TAG', '').lower() != 'true' \\ and os.getenv('TRAVIS_TAG', '') ==",
"# pragma: no cover # dvc was installed with pip",
"a helper file, that will be installed with the package",
"return ver def _remove_version_file(): \"\"\"Remove version.py so that it doesn't",
"= '0.23.2' __version__ = VERSION_BASE PACKAGEPATH = os.path.abspath(os.path.dirname(__file__)) HOMEPATH =",
"HOMEPATH = os.path.dirname(PACKAGEPATH) VERSIONPATH = os.path.join(PACKAGEPATH, 'version.py') def _update_version_file(): \"\"\"Dynamically",
"Ignore numpy's runtime warnings: https://github.com/numpy/numpy/pull/432. # We don't directly import",
"import InvalidGitRepositoryError try: repo = Repo(HOMEPATH) except InvalidGitRepositoryError: return __version__",
"\"\"\"Dynamically update version file.\"\"\" from git import Repo from git.exc",
"'') == '': __version__ = _update_version_file() else: # pragma: no",
"don't show up when you are using dvc. warnings.filterwarnings(\"ignore\", message=\"numpy.dtype",
"that will be installed with the package # and will",
"version file.\"\"\" from git import Repo from git.exc import InvalidGitRepositoryError",
"from git import Repo from git.exc import InvalidGitRepositoryError try: repo",
"InvalidGitRepositoryError: return __version__ sha = repo.head.object.hexsha short_sha = repo.git.rev_parse(sha, short=6)",
"short_sha = repo.git.rev_parse(sha, short=6) dirty = '.mod' if repo.is_dirty() else",
"called from setup.py if os.getenv('APPVEYOR_REPO_TAG', '').lower() != 'true' \\ and",
"true version of the installed dvc with open(VERSIONPATH, 'w+') as",
"https://github.com/numpy/numpy/pull/432. # We don't directly import numpy, but our dependency",
"will provide a true version of the installed dvc with",
"directly import numpy, but our dependency networkx does, causing #",
"these warnings in some environments. Luckily these warnings are benign",
"\"\"\" import os import warnings VERSION_BASE = '0.23.2' __version__ =",
"else: # pragma: no cover # dvc was installed with",
"version.py so that it doesn't get into the release.\"\"\" if",
"ver def _remove_version_file(): \"\"\"Remove version.py so that it doesn't get",
"version of the installed dvc with open(VERSIONPATH, 'w+') as fobj:",
"\\ and os.getenv('TRAVIS_TAG', '') == '': __version__ = _update_version_file() else:",
"and will provide a true version of the installed dvc",
"helper file, that will be installed with the package #",
"the package # and will provide a true version of",
"you are using dvc. warnings.filterwarnings(\"ignore\", message=\"numpy.dtype size changed\") warnings.filterwarnings(\"ignore\", message=\"numpy.ufunc",
"is run directly from source without installation or # __version__",
"provide a true version from dvc.version import version __version__ =",
"\"\"\" DVC ---- Make your data science projects reproducible and",
"run directly from source without installation or # __version__ is",
"source without installation or # __version__ is called from setup.py",
"them so that they don't show up when you are",
"= os.path.abspath(os.path.dirname(__file__)) HOMEPATH = os.path.dirname(PACKAGEPATH) VERSIONPATH = os.path.join(PACKAGEPATH, 'version.py') def",
"warnings VERSION_BASE = '0.23.2' __version__ = VERSION_BASE PACKAGEPATH = os.path.abspath(os.path.dirname(__file__))",
"\"\"\"Remove version.py so that it doesn't get into the release.\"\"\"",
"by dvc/__init__.py\\n') fobj.write('version = \"{}\"\\n'.format(ver)) return ver def _remove_version_file(): \"\"\"Remove",
"we have our # auto-generated version.py to help us provide",
"'w+') as fobj: fobj.write('# AUTOGENERATED by dvc/__init__.py\\n') fobj.write('version = \"{}\"\\n'.format(ver))",
"and os.getenv('TRAVIS_TAG', '') == '': __version__ = _update_version_file() else: #",
"warnings: https://github.com/numpy/numpy/pull/432. # We don't directly import numpy, but our",
"DVC ---- Make your data science projects reproducible and shareable.",
"!= 'true' \\ and os.getenv('TRAVIS_TAG', '') == '': __version__ =",
"VERSION_BASE PACKAGEPATH = os.path.abspath(os.path.dirname(__file__)) HOMEPATH = os.path.dirname(PACKAGEPATH) VERSIONPATH = os.path.join(PACKAGEPATH,",
"shareable. \"\"\" import os import warnings VERSION_BASE = '0.23.2' __version__",
"with open(VERSIONPATH, 'w+') as fobj: fobj.write('# AUTOGENERATED by dvc/__init__.py\\n') fobj.write('version",
"'').lower() != 'true' \\ and os.getenv('TRAVIS_TAG', '') == '': __version__",
"= os.path.dirname(PACKAGEPATH) VERSIONPATH = os.path.join(PACKAGEPATH, 'version.py') def _update_version_file(): \"\"\"Dynamically update",
"= _update_version_file() else: # pragma: no cover _remove_version_file() else: #",
"up when you are using dvc. warnings.filterwarnings(\"ignore\", message=\"numpy.dtype size changed\")",
"into the release.\"\"\" if os.path.exists(VERSIONPATH): os.unlink(VERSIONPATH) if os.path.exists(os.path.join(HOMEPATH, 'setup.py')): #",
"numpy, but our dependency networkx does, causing # these warnings",
"if os.path.exists(VERSIONPATH): os.unlink(VERSIONPATH) if os.path.exists(os.path.join(HOMEPATH, 'setup.py')): # dvc is run",
"with pip or something. Hopefully we have our # auto-generated",
"Hopefully we have our # auto-generated version.py to help us",
"does, causing # these warnings in some environments. Luckily these",
"installation or # __version__ is called from setup.py if os.getenv('APPVEYOR_REPO_TAG',",
"release.\"\"\" if os.path.exists(VERSIONPATH): os.unlink(VERSIONPATH) if os.path.exists(os.path.join(HOMEPATH, 'setup.py')): # dvc is",
"in some environments. Luckily these warnings are benign and #",
"was installed with pip or something. Hopefully we have our",
"# __version__ is called from setup.py if os.getenv('APPVEYOR_REPO_TAG', '').lower() !=",
"we can simply ignore them so that they don't show",
"benign and # we can simply ignore them so that",
"but our dependency networkx does, causing # these warnings in",
"= repo.head.object.hexsha short_sha = repo.git.rev_parse(sha, short=6) dirty = '.mod' if",
"repo.head.object.hexsha short_sha = repo.git.rev_parse(sha, short=6) dirty = '.mod' if repo.is_dirty()",
"os.path.dirname(PACKAGEPATH) VERSIONPATH = os.path.join(PACKAGEPATH, 'version.py') def _update_version_file(): \"\"\"Dynamically update version",
"= __version__ # Ignore numpy's runtime warnings: https://github.com/numpy/numpy/pull/432. # We",
"import warnings VERSION_BASE = '0.23.2' __version__ = VERSION_BASE PACKAGEPATH =",
"setup.py if os.getenv('APPVEYOR_REPO_TAG', '').lower() != 'true' \\ and os.getenv('TRAVIS_TAG', '')",
"from setup.py if os.getenv('APPVEYOR_REPO_TAG', '').lower() != 'true' \\ and os.getenv('TRAVIS_TAG',",
"# pragma: no cover _remove_version_file() else: # pragma: no cover",
"file.\"\"\" from git import Repo from git.exc import InvalidGitRepositoryError try:",
"will be installed with the package # and will provide",
"def _update_version_file(): \"\"\"Dynamically update version file.\"\"\" from git import Repo",
"dvc was installed with pip or something. Hopefully we have"
] |
[
"blueprint dictionary for the dataframe (orient=index) :param db_json (json): json",
"properties :return db_schema (dictionary): schema of the table that includes",
"via Notion's API def get_notion_db_json(db_id): \"\"\" Calling a Notion database",
"by calling notion's api :param relevant_properties (list): list of string",
"= pd.DataFrame.from_dict(df_dict, orient=\"index\") #### Inserting the table's index as a",
"in [\"formula\"]: try: #### Applying conditions based on the type",
"try: #### Applying conditions based on the type of formula",
"over every relevant property in the table for col in",
"dataframe df_n = pd.DataFrame.from_dict(df_dict, orient=\"index\") #### Inserting the table's index",
"to identify the notion database :param relevant_properties (list): list of",
"Reading credentials from yaml file yaml_file = read_yaml(crds_loc) notion_version =",
"Notion database as a json via Notion's API :param db_id",
"Crating a schema of the notion database that was read",
"the table's base attributes #### All properties contained in the",
"the API req = requests.request( \"POST\", read_url, headers=headers ) ##",
"= row_props[index_prop][\"title\"][0][\"plain_text\"] #### Empty list to store all the row",
"orient=\"index\") #### Inserting the table's index as a column at",
"that includes the properties' data type \"\"\" ## Selecting a",
"dictionary for the dataframe (orient=index) :param db_json (json): json object",
"\"title\": continue #### Searching for data in specific locations for",
"table's base attributes #### All properties contained in the notion",
"\"\"\" Obtaining a Notion database as dataframe with the selected",
"import ( read_yaml, ) \"----------------------------------------------------------------------------------------------------------------------\" ####################################################### Functions ###################################################### \"----------------------------------------------------------------------------------------------------------------------\" ##",
"Adjusting column names df_n.columns = [col_n for col_n in db_schema]",
"= [] ## Iterating over every relevant property in the",
"via the API req = requests.request( \"POST\", read_url, headers=headers )",
"else: row_contents.append(row_props[col][db_schema[col][\"data_type\"]]) ## Saving the row contents gathered df_dict[row_name] =",
"\"\"\" ## Calling a Notion database as a json via",
"id of the database that will be read :param headers",
"elif data_type in [\"formula\"]: try: #### Applying conditions based on",
"with the names of the relevant properties :return df_n (dataframe):",
"for data in specific locations for special data types (1)",
"## Empty dictionary that will store all the results df_dict",
"General parameters needed to build the dataframe #### Database schema",
"[\"rich_text\"]: try: row_contents.append(row_props[col][data_type][0][\"text\"][\"content\"]) except: row_contents.append(\"No_data\") #### Searching for data in",
"be used as the dataframe's index index_prop = [prop for",
"as a column at the end of the df df_n.insert(",
"schema of the table that includes the properties' data type",
"the df df_n.insert( df_n.shape[1], index_prop, df_n.index ) #### Resetting index",
"library imports import requests ## Third party imports import pandas",
"Converting the api response to a json db_json = req.json()",
"Bulding dictionary (schema) of the relevant properties and their datatypes",
"a Notion database as a json via Notion's API def",
"object obtained by calling notion's api :param relevant_properties (list): list",
"with api :param db_api_url (string): base url provided by Notion",
"used to create a dataframe with the json contents \"\"\"",
"base attributes #### All properties contained in the notion db",
"notion database with api def notion_api_call(db_api_url, db_id, headers): \"\"\" Read",
"#### Crating dataframe df_n = pd.DataFrame.from_dict(df_dict, orient=\"index\") #### Inserting the",
"on the blueprint generated \"\"\" ## General parameters needed to",
"names of the relevant properties :return df_n (dataframe): resulting dataframe",
"= read_yaml(crds_loc) notion_version = yaml_file[\"notion_api\"][\"notion_version\"] db_api_url = yaml_file[\"notion_api\"][\"db_api_url\"] api_key =",
"contents row_contents = [] ## Iterating over every relevant property",
"the database that will be called :return db_json (json): json",
"notion's api req = notion_api_call(db_api_url, db_id, headers) ## Converting the",
"Applying conditions based on the type of formula result if",
"Saving the row contents gathered df_dict[row_name] = row_contents return df_dict",
"(dict): dictionary that will be used to create a dataframe",
"that will be called :return db_json (json): json with the",
"id to identify the notion database :param relevant_properties (list): list",
"def get_notion_db_json(db_id): \"\"\" Calling a Notion database as a json",
"## Standard library imports import requests ## Third party imports",
"= notion_json_to_df(db_json, relevant_properties) return df_n \"----------------------------------------------------------------------------------------------------------------------\" \"----------------------------------------------------------------------------------------------------------------------\" ## END OF",
"database that was read :param db_json (json): json object obtained",
"db_json (json): json object obtained by calling notion's api :return",
"with authorization and version info :return req (?): response after",
"URL read_url = db_api_url + db_id + \"/query\" ## Requesting",
"result if row_props[col][data_type][\"type\"] == \"string\": row_contents.append(row_props[col][data_type][\"string\"]) elif row_props[col][data_type][\"type\"] == \"number\":",
"row_contents.append(row_props[col][data_type][\"number\"]) except: row_contents.append(\"No_data\") #### General procedure to find data else:",
"status code: \", req.status_code) return req ## Calling a Notion",
"+ \"/query\" ## Requesting info via the API req =",
"(string): base url provided by Notion to make api calls",
"determine how the row will be treated #### Skipping the",
"was read :param db_json (json): json object obtained by calling",
"in the table for col in db_schema: ## Identifying the",
"dictionary for the dataframe (orient=index) def notion_db_blueprint_df(db_json, db_schema, index_prop): \"\"\"",
"will serve as the df's index :return df_dict (dict): dictionary",
"the dataframe for row in db_json[\"results\"]: ## Defining the table's",
"== \"title\"][0] ## Building a the blueprint dictionary for the",
"[\"formula\"]: try: #### Applying conditions based on the type of",
"\"\"\" ## Reading credentials from yaml file yaml_file = read_yaml(crds_loc)",
"row[\"properties\"] #### Name of the index; key attribute in the",
"data in specific locations for special data types (2) elif",
"Obtaining a dataframe from a notion database df_n = notion_json_to_df(db_json,",
"sample_entry if prop in relevant_properties } # print(db_schema) return db_schema",
"db_schema[prop][\"data_type\"] == \"title\"][0] ## Building a the blueprint dictionary for",
"the property data_type = db_schema[col][\"data_type\"] ## Set of conditions to",
"Notion's API :param db_id (string): unique id of the database",
"will be used as the dataframe's index index_prop = [prop",
"df_n ## Obtaining a Notion database as dataframe with the",
"relevant properties :return df_n (dataframe): resulting dataframe crated based on",
"index_prop) ## Creating dataframe with the resulting blueprint dictionary ####",
"the selected columns def notion_db_to_df(db_id, relevant_properties): \"\"\" Obtaining a Notion",
"if prop in relevant_properties } # print(db_schema) return db_schema ##",
"requests.request( \"POST\", read_url, headers=headers ) ## Verifying API call status",
":return db_json (json): json with the notion's db contents \"\"\"",
"that will be used to create a dataframe with the",
"imports import pandas as pd ## Local application imports from",
"dict with authorization and version info :return req (?): response",
"\"----------------------------------------------------------------------------------------------------------------------\" ## Read notion database with api def notion_api_call(db_api_url, db_id,",
"notion_version } ## Calling notion's api req = notion_api_call(db_api_url, db_id,",
"column names df_n.columns = [col_n for col_n in db_schema] return",
"dataframe (orient=index) def notion_db_blueprint_df(db_json, db_schema, index_prop): \"\"\" Building a the",
"notion_db_blueprint_df(db_json, db_schema, index_prop): \"\"\" Building a the blueprint dictionary for",
"of the database that will be called :return db_json (json):",
"df_n \"----------------------------------------------------------------------------------------------------------------------\" \"----------------------------------------------------------------------------------------------------------------------\" ## END OF FILE ## \"----------------------------------------------------------------------------------------------------------------------\" \"----------------------------------------------------------------------------------------------------------------------\"",
"notion_api_call(db_api_url, db_id, headers): \"\"\" Read notion database with api :param",
"row in db_json[\"results\"]: ## Defining the table's base attributes ####",
"of the database that will be read :param headers (dictionary):",
"of the df df_n.insert( df_n.shape[1], index_prop, df_n.index ) #### Resetting",
"a Notion database as a json via Notion's API :param",
"= req.json() return db_json ## Crating a schema of the",
"prop in relevant_properties } # print(db_schema) return db_schema ## Building",
"return df_n \"----------------------------------------------------------------------------------------------------------------------\" \"----------------------------------------------------------------------------------------------------------------------\" ## END OF FILE ## \"----------------------------------------------------------------------------------------------------------------------\"",
"notion_version = yaml_file[\"notion_api\"][\"notion_version\"] db_api_url = yaml_file[\"notion_api\"][\"db_api_url\"] api_key = yaml_file[\"notion_api\"][\"api_key\"] ##",
"(2) elif data_type in [\"rich_text\"]: try: row_contents.append(row_props[col][data_type][0][\"text\"][\"content\"]) except: row_contents.append(\"No_data\") ####",
"(string): unique id of the database that will be read",
"formula result if row_props[col][data_type][\"type\"] == \"string\": row_contents.append(row_props[col][data_type][\"string\"]) elif row_props[col][data_type][\"type\"] ==",
"as dataframe with the selected columns def notion_db_to_df(db_id, relevant_properties): \"\"\"",
"row will be treated #### Skipping the index row if",
"## Calling a Notion database as a json via Notion's",
"api req = notion_api_call(db_api_url, db_id, headers) ## Converting the api",
"Read notion database with api :param db_api_url (string): base url",
"json via Notion's API db_json = get_notion_db_json(db_id) ## Obtaining a",
"row contents gathered df_dict[row_name] = row_contents return df_dict ## Obtaining",
"pd.DataFrame.from_dict(df_dict, orient=\"index\") #### Inserting the table's index as a column",
"serve as the df's index :return df_dict (dict): dictionary that",
"for special data types (2) elif data_type in [\"formula\"]: try:",
"called :return db_json (json): json with the notion's db contents",
"treated #### Skipping the index row if data_type == \"title\":",
"Notion database as dataframe with the selected columns def notion_db_to_df(db_id,",
"conditions based on the type of formula result if row_props[col][data_type][\"type\"]",
"a notion database def notion_json_to_df(db_json, relevant_properties): \"\"\" Obtaining a dataframe",
"a json via Notion's API :param db_id (string): unique id",
"Selecting a sample entry to go over all of it's",
"req ## Calling a Notion database as a json via",
"types (2) elif data_type in [\"rich_text\"]: try: row_contents.append(row_props[col][data_type][0][\"text\"][\"content\"]) except: row_contents.append(\"No_data\")",
"\"created_by\"]: try: row_contents.append(row_props[col][data_type][\"name\"]) except: row_contents.append(\"No_data\") #### Searching for data in",
"db_schema ## Building a the blueprint dictionary for the dataframe",
"that will store all the results df_dict = {} ##",
":return req (?): response after calling notions api \"\"\" ##",
"Searching for data in specific locations for special data types",
"the df's index :return df_dict (dict): dictionary that will be",
"prop in db_schema if db_schema[prop][\"data_type\"] == \"title\"][0] ## Building a",
"table that includes the properties' data type \"\"\" ## Selecting",
"in [\"rich_text\"]: try: row_contents.append(row_props[col][data_type][0][\"text\"][\"content\"]) except: row_contents.append(\"No_data\") #### Searching for data",
"in specific locations for special data types (2) elif data_type",
"## Obtaining a dataframe from a notion database df_n =",
"dictionary (schema) of the relevant properties and their datatypes db_schema",
"API req = requests.request( \"POST\", read_url, headers=headers ) ## Verifying",
"that was read :param db_json (json): json object obtained by",
"generated \"\"\" ## General parameters needed to build the dataframe",
"the API call headers = { \"Authorization\": \"Bearer \" +",
"#### Applying conditions based on the type of formula result",
"WITH UTIL FUNCTIONS - NOTION \"----------------------------------------------------------------------------------------------------------------------\" ####################################################### Imports ######################################################## \"----------------------------------------------------------------------------------------------------------------------\"",
"attribute in the notion db row_name = row_props[index_prop][\"title\"][0][\"plain_text\"] #### Empty",
"headers for the API call headers = { \"Authorization\": \"Bearer",
"data type :param index_prop (string): name of the property that",
"(string): unique id to identify the notion database :param relevant_properties",
"special data types (1) elif data_type in [\"select\", \"person\", \"created_by\"]:",
"reading URL read_url = db_api_url + db_id + \"/query\" ##",
"df_n = pd.DataFrame.from_dict(df_dict, orient=\"index\") #### Inserting the table's index as",
"dataframe's index index_prop = [prop for prop in db_schema if",
"contained in the notion db row_props = row[\"properties\"] #### Name",
"to build the dataframe #### Database schema db_schema = create_notion_db_schema(db_json,",
"Notion database as a json via Notion's API def get_notion_db_json(db_id):",
"via Notion's API :param db_id (string): unique id of the",
"\"Bearer \" + api_key, \"Notion-Version\": notion_version } ## Calling notion's",
"notion's api :return db_schema (dictionary): schema of the table that",
"( read_yaml, ) \"----------------------------------------------------------------------------------------------------------------------\" ####################################################### Functions ###################################################### \"----------------------------------------------------------------------------------------------------------------------\" ## Read",
"a json via Notion's API def get_notion_db_json(db_id): \"\"\" Calling a",
"relevant property in the table for col in db_schema: ##",
"Notion's API db_json = get_notion_db_json(db_id) ## Obtaining a dataframe from",
"def create_notion_db_schema(db_json, relevant_properties): \"\"\" Crating a schema of the notion",
"relevant_properties): \"\"\" Crating a schema of the notion database that",
"with the selected columns :param db_id (string): unique id to",
"UTIL FUNCTIONS - NOTION \"----------------------------------------------------------------------------------------------------------------------\" ####################################################### Imports ######################################################## \"----------------------------------------------------------------------------------------------------------------------\" ##",
"## Set of conditions to determine how the row will",
"a schema of the notion database that was read :param",
"dictionary #### Crating dataframe df_n = pd.DataFrame.from_dict(df_dict, orient=\"index\") #### Inserting",
"pd ## Local application imports from pkg_dir.config.config import ( creds_file_path",
"} for prop in sample_entry if prop in relevant_properties }",
"api \"\"\" ## Configuring reading URL read_url = db_api_url +",
"make api calls :param db_id (string): unique id of the",
"notion_json_to_df(db_json, relevant_properties) return df_n \"----------------------------------------------------------------------------------------------------------------------\" \"----------------------------------------------------------------------------------------------------------------------\" ## END OF FILE",
"all of it's properties sample_entry = db_json[\"results\"][0][\"properties\"] ## Bulding dictionary",
"= { prop: { \"data_type\": sample_entry[prop][\"type\"] } for prop in",
"database that will be read :param headers (dictionary): dict with",
"the notion db row_name = row_props[index_prop][\"title\"][0][\"plain_text\"] #### Empty list to",
"\"\"\" Read notion database with api :param db_api_url (string): base",
"## Converting the api response to a json db_json =",
"relevant_properties) return df_n \"----------------------------------------------------------------------------------------------------------------------\" \"----------------------------------------------------------------------------------------------------------------------\" ## END OF FILE ##",
"(json): json with the notion's db contents \"\"\" ## Reading",
"authorization and version info :return req (?): response after calling",
"= requests.request( \"POST\", read_url, headers=headers ) ## Verifying API call",
"Empty dictionary that will store all the results df_dict =",
"the row contents row_contents = [] ## Iterating over every",
"a column at the end of the df df_n.insert( df_n.shape[1],",
"{ prop: { \"data_type\": sample_entry[prop][\"type\"] } for prop in sample_entry",
"crds_loc, ) from pkg_dir.src.utils.general_utils import ( read_yaml, ) \"----------------------------------------------------------------------------------------------------------------------\" #######################################################",
"the end of the df df_n.insert( df_n.shape[1], index_prop, df_n.index )",
"a json via Notion's API db_json = get_notion_db_json(db_id) ## Obtaining",
"attributes #### All properties contained in the notion db row_props",
"schema of the notion database that was read :param db_json",
"prop in sample_entry if prop in relevant_properties } # print(db_schema)",
"it's properties sample_entry = db_json[\"results\"][0][\"properties\"] ## Bulding dictionary (schema) of",
"get_notion_db_json(db_id) ## Obtaining a dataframe from a notion database df_n",
"\", req.status_code) return req ## Calling a Notion database as",
"Property that will be used as the dataframe's index index_prop",
"crated based on the blueprint generated \"\"\" ## Calling a",
"notion database df_n = notion_json_to_df(db_json, relevant_properties) return df_n \"----------------------------------------------------------------------------------------------------------------------\" \"----------------------------------------------------------------------------------------------------------------------\"",
"as a json via Notion's API :param db_id (string): unique",
"will be used to create a dataframe with the json",
"## General parameters needed to build the dataframe #### Database",
"headers): \"\"\" Read notion database with api :param db_api_url (string):",
"[col_n for col_n in db_schema] return df_n ## Obtaining a",
"api calls :param db_id (string): unique id of the database",
"results df_dict = {} ## Iterating over every row in",
"All properties contained in the notion db row_props = row[\"properties\"]",
"will be treated #### Skipping the index row if data_type",
"notion database that was read def create_notion_db_schema(db_json, relevant_properties): \"\"\" Crating",
"version info :return req (?): response after calling notions api",
"read_url, headers=headers ) ## Verifying API call status print(\"API interaction",
"= notion_db_blueprint_df(db_json, db_schema, index_prop) ## Creating dataframe with the resulting",
"json object obtained by calling notion's api :return db_schema (dictionary):",
"FUNCTIONS - NOTION \"----------------------------------------------------------------------------------------------------------------------\" ####################################################### Imports ######################################################## \"----------------------------------------------------------------------------------------------------------------------\" ## Standard",
"db_id + \"/query\" ## Requesting info via the API req",
"response to a json db_json = req.json() return db_json ##",
"blueprint generated \"\"\" ## General parameters needed to build the",
"resulting blueprint dictionary #### Crating dataframe df_n = pd.DataFrame.from_dict(df_dict, orient=\"index\")",
"parameters needed to build the dataframe #### Database schema db_schema",
"properties and their datatypes db_schema = { prop: { \"data_type\":",
"\"\"\" ## General parameters needed to build the dataframe ####",
"to a json db_json = req.json() return db_json ## Crating",
"blueprint generated \"\"\" ## Calling a Notion database as a",
"## Building headers for the API call headers = {",
"dataframe with the resulting blueprint dictionary #### Crating dataframe df_n",
"data types (1) elif data_type in [\"select\", \"person\", \"created_by\"]: try:",
"for col_n in db_schema] return df_n ## Obtaining a Notion",
"object obtained by calling notion's api :return db_schema (dictionary): schema",
"data types (2) elif data_type in [\"rich_text\"]: try: row_contents.append(row_props[col][data_type][0][\"text\"][\"content\"]) except:",
"calls :param db_id (string): unique id of the database that",
"= db_schema[col][\"data_type\"] ## Set of conditions to determine how the",
"table for col in db_schema: ## Identifying the datatype of",
"a Notion database as dataframe with the selected columns def",
"(string): name of the property that will serve as the",
"= create_notion_db_schema(db_json, relevant_properties) #### Property that will be used as",
"## Local application imports from pkg_dir.config.config import ( creds_file_path as",
"the notion db row_props = row[\"properties\"] #### Name of the",
"database df_n = notion_json_to_df(db_json, relevant_properties) return df_n \"----------------------------------------------------------------------------------------------------------------------\" \"----------------------------------------------------------------------------------------------------------------------\" ##",
"## Iterating over every relevant property in the table for",
"string with the names of the relevant properties :return df_n",
"create a dataframe with the json contents \"\"\" ## Empty",
"= notion_api_call(db_api_url, db_id, headers) ## Converting the api response to",
"includes the properties' data type :param index_prop (string): name of",
"(string): unique id of the database that will be called",
"the dataframe (orient=index) def notion_db_blueprint_df(db_json, db_schema, index_prop): \"\"\" Building a",
"row_props = row[\"properties\"] #### Name of the index; key attribute",
"the resulting blueprint dictionary #### Crating dataframe df_n = pd.DataFrame.from_dict(df_dict,",
"#### Name of the index; key attribute in the notion",
"\"----------------------------------------------------------------------------------------------------------------------\" ####################################################### Imports ######################################################## \"----------------------------------------------------------------------------------------------------------------------\" ## Standard library imports import",
"json via Notion's API def get_notion_db_json(db_id): \"\"\" Calling a Notion",
"in db_json[\"results\"]: ## Defining the table's base attributes #### All",
"on the type of formula result if row_props[col][data_type][\"type\"] == \"string\":",
"###################################################### \"----------------------------------------------------------------------------------------------------------------------\" ## Read notion database with api def notion_api_call(db_api_url,",
"for the dataframe (orient=index) df_dict = notion_db_blueprint_df(db_json, db_schema, index_prop) ##",
"will be called :return db_json (json): json with the notion's",
"with the json contents \"\"\" ## Empty dictionary that will",
"url provided by Notion to make api calls :param db_id",
"of the relevant properties :return df_n (dataframe): resulting dataframe crated",
"Building a the blueprint dictionary for the dataframe (orient=index) :param",
"based on the blueprint generated \"\"\" ## General parameters needed",
"the names of the relevant properties :return db_schema (dictionary): schema",
"dataframe from a notion database :param db_json (json): json object",
"df df_n.insert( df_n.shape[1], index_prop, df_n.index ) #### Resetting index df_n.reset_index(inplace=True,",
"pandas as pd ## Local application imports from pkg_dir.config.config import",
"dataframe (orient=index) :param db_json (json): json object obtained by calling",
"= { \"Authorization\": \"Bearer \" + api_key, \"Notion-Version\": notion_version }",
"db_schema: ## Identifying the datatype of the property data_type =",
"database as dataframe with the selected columns def notion_db_to_df(db_id, relevant_properties):",
"read def create_notion_db_schema(db_json, relevant_properties): \"\"\" Crating a schema of the",
"based on the blueprint generated \"\"\" ## Calling a Notion",
"api_key = yaml_file[\"notion_api\"][\"api_key\"] ## Building headers for the API call",
"Building headers for the API call headers = { \"Authorization\":",
"## Saving the row contents gathered df_dict[row_name] = row_contents return",
"sample_entry = db_json[\"results\"][0][\"properties\"] ## Bulding dictionary (schema) of the relevant",
"the table's index as a column at the end of",
"the api response to a json db_json = req.json() return",
"as a json via Notion's API def get_notion_db_json(db_id): \"\"\" Calling",
"#### Adjusting column names df_n.columns = [col_n for col_n in",
"db_schema] return df_n ## Obtaining a Notion database as dataframe",
"selected columns def notion_db_to_df(db_id, relevant_properties): \"\"\" Obtaining a Notion database",
"= [col_n for col_n in db_schema] return df_n ## Obtaining",
"calling notion's api :param relevant_properties (list): list of string with",
"return req ## Calling a Notion database as a json",
"notion's db contents \"\"\" ## Reading credentials from yaml file",
"as dataframe with the selected columns :param db_id (string): unique",
"try: row_contents.append(row_props[col][data_type][0][\"text\"][\"content\"]) except: row_contents.append(\"No_data\") #### Searching for data in specific",
"headers (dictionary): dict with authorization and version info :return req",
"was read def create_notion_db_schema(db_json, relevant_properties): \"\"\" Crating a schema of",
"\"\"\" ## Configuring reading URL read_url = db_api_url + db_id",
"## Defining the table's base attributes #### All properties contained",
"with the resulting blueprint dictionary #### Crating dataframe df_n =",
"store all the results df_dict = {} ## Iterating over",
"row_contents.append(row_props[col][data_type][0][\"text\"][\"content\"]) except: row_contents.append(\"No_data\") #### Searching for data in specific locations",
"database as a json via Notion's API :param db_id (string):",
"the notion's db contents \"\"\" ## Reading credentials from yaml",
"that was read def create_notion_db_schema(db_json, relevant_properties): \"\"\" Crating a schema",
"create_notion_db_schema(db_json, relevant_properties): \"\"\" Crating a schema of the notion database",
"\"number\": row_contents.append(row_props[col][data_type][\"number\"]) except: row_contents.append(\"No_data\") #### General procedure to find data",
"- NOTION \"----------------------------------------------------------------------------------------------------------------------\" ####################################################### Imports ######################################################## \"----------------------------------------------------------------------------------------------------------------------\" ## Standard library",
"in the dataframe for row in db_json[\"results\"]: ## Defining the",
"locations for special data types (2) elif data_type in [\"formula\"]:",
"db_schema = create_notion_db_schema(db_json, relevant_properties) #### Property that will be used",
"row_contents.append(row_props[col][data_type][\"string\"]) elif row_props[col][data_type][\"type\"] == \"number\": row_contents.append(row_props[col][data_type][\"number\"]) except: row_contents.append(\"No_data\") #### General",
"data else: row_contents.append(row_props[col][db_schema[col][\"data_type\"]]) ## Saving the row contents gathered df_dict[row_name]",
"relevant_properties } # print(db_schema) return db_schema ## Building a the",
"print(db_schema) return db_schema ## Building a the blueprint dictionary for",
"db_json (json): json object obtained by calling notion's api :param",
"database def notion_json_to_df(db_json, relevant_properties): \"\"\" Obtaining a dataframe from a",
"dictionary that will store all the results df_dict = {}",
"relevant properties :return db_schema (dictionary): schema of the table that",
":param relevant_properties (list): list of string with the names of",
"df_n.columns = [col_n for col_n in db_schema] return df_n ##",
"all the row contents row_contents = [] ## Iterating over",
"db_schema, index_prop): \"\"\" Building a the blueprint dictionary for the",
"Notion to make api calls :param db_id (string): unique id",
"df_n.index ) #### Resetting index df_n.reset_index(inplace=True, drop=True) #### Adjusting column",
"MODULE WITH UTIL FUNCTIONS - NOTION \"----------------------------------------------------------------------------------------------------------------------\" ####################################################### Imports ########################################################",
"the row contents gathered df_dict[row_name] = row_contents return df_dict ##",
"api def notion_api_call(db_api_url, db_id, headers): \"\"\" Read notion database with",
"obtained by calling notion's api :return db_schema (dictionary): schema of",
"database as dataframe with the selected columns :param db_id (string):",
"with the notion's db contents \"\"\" ## Reading credentials from",
"(dataframe): resulting dataframe crated based on the blueprint generated \"\"\"",
"create_notion_db_schema(db_json, relevant_properties) #### Property that will be used as the",
"as the dataframe's index index_prop = [prop for prop in",
"Empty list to store all the row contents row_contents =",
"db_schema[col][\"data_type\"] ## Set of conditions to determine how the row",
"\"\"\" ## Empty dictionary that will store all the results",
"db_id (string): unique id to identify the notion database :param",
"every relevant property in the table for col in db_schema:",
"properties :return df_n (dataframe): resulting dataframe crated based on the",
"with the selected columns def notion_db_to_df(db_id, relevant_properties): \"\"\" Obtaining a",
"json via Notion's API :param db_id (string): unique id of",
"database :param db_json (json): json object obtained by calling notion's",
"yaml_file[\"notion_api\"][\"notion_version\"] db_api_url = yaml_file[\"notion_api\"][\"db_api_url\"] api_key = yaml_file[\"notion_api\"][\"api_key\"] ## Building headers",
"## Iterating over every row in the dataframe for row",
"index :return df_dict (dict): dictionary that will be used to",
"Notion's API def get_notion_db_json(db_id): \"\"\" Calling a Notion database as",
"obtained by calling notion's api :param relevant_properties (list): list of",
"relevant_properties) #### Property that will be used as the dataframe's",
"col_n in db_schema] return df_n ## Obtaining a Notion database",
"selected columns :param db_id (string): unique id to identify the",
"Calling a Notion database as a json via Notion's API",
"row contents row_contents = [] ## Iterating over every relevant",
"datatypes db_schema = { prop: { \"data_type\": sample_entry[prop][\"type\"] } for",
") #### Resetting index df_n.reset_index(inplace=True, drop=True) #### Adjusting column names",
"interaction status code: \", req.status_code) return req ## Calling a",
"of the relevant properties and their datatypes db_schema = {",
"database that will be called :return db_json (json): json with",
"(orient=index) def notion_db_blueprint_df(db_json, db_schema, index_prop): \"\"\" Building a the blueprint",
"row_contents.append(\"No_data\") #### General procedure to find data else: row_contents.append(row_props[col][db_schema[col][\"data_type\"]]) ##",
"properties' data type \"\"\" ## Selecting a sample entry to",
"in the notion db row_props = row[\"properties\"] #### Name of",
":param db_id (string): unique id to identify the notion database",
"entry to go over all of it's properties sample_entry =",
"+ api_key, \"Notion-Version\": notion_version } ## Calling notion's api req",
"of the relevant properties :return db_schema (dictionary): schema of the",
"application imports from pkg_dir.config.config import ( creds_file_path as crds_loc, )",
"return df_n ## Obtaining a Notion database as dataframe with",
"relevant_properties (list): list of string with the names of the",
"Skipping the index row if data_type == \"title\": continue ####",
"the blueprint dictionary for the dataframe (orient=index) :param db_json (json):",
"df_n = notion_json_to_df(db_json, relevant_properties) return df_n \"----------------------------------------------------------------------------------------------------------------------\" \"----------------------------------------------------------------------------------------------------------------------\" ## END",
"headers=headers ) ## Verifying API call status print(\"API interaction status",
"[prop for prop in db_schema if db_schema[prop][\"data_type\"] == \"title\"][0] ##",
"the property that will serve as the df's index :return",
"the blueprint generated \"\"\" ## General parameters needed to build",
"row in the dataframe for row in db_json[\"results\"]: ## Defining",
"based on the type of formula result if row_props[col][data_type][\"type\"] ==",
"\"----------------------------------------------------------------------------------------------------------------------\" ####################################################### Functions ###################################################### \"----------------------------------------------------------------------------------------------------------------------\" ## Read notion database with",
"db_api_url = yaml_file[\"notion_api\"][\"db_api_url\"] api_key = yaml_file[\"notion_api\"][\"api_key\"] ## Building headers for",
"party imports import pandas as pd ## Local application imports",
"the relevant properties :return db_schema (dictionary): schema of the table",
") from pkg_dir.src.utils.general_utils import ( read_yaml, ) \"----------------------------------------------------------------------------------------------------------------------\" ####################################################### Functions",
"if data_type == \"title\": continue #### Searching for data in",
"####################################################### Imports ######################################################## \"----------------------------------------------------------------------------------------------------------------------\" ## Standard library imports import requests",
"a dataframe with the json contents \"\"\" ## Empty dictionary",
"API call headers = { \"Authorization\": \"Bearer \" + api_key,",
"that will be used as the dataframe's index index_prop =",
"## Configuring reading URL read_url = db_api_url + db_id +",
"index_prop (string): name of the property that will serve as",
"db_json = req.json() return db_json ## Crating a schema of",
"with api def notion_api_call(db_api_url, db_id, headers): \"\"\" Read notion database",
"\"string\": row_contents.append(row_props[col][data_type][\"string\"]) elif row_props[col][data_type][\"type\"] == \"number\": row_contents.append(row_props[col][data_type][\"number\"]) except: row_contents.append(\"No_data\") ####",
"## Read notion database with api def notion_api_call(db_api_url, db_id, headers):",
"calling notions api \"\"\" ## Configuring reading URL read_url =",
"= db_api_url + db_id + \"/query\" ## Requesting info via",
"the table that includes the properties' data type :param index_prop",
"from a notion database :param db_json (json): json object obtained",
"import pandas as pd ## Local application imports from pkg_dir.config.config",
"type \"\"\" ## Selecting a sample entry to go over",
"crated based on the blueprint generated \"\"\" ## General parameters",
"\"POST\", read_url, headers=headers ) ## Verifying API call status print(\"API",
"#### General procedure to find data else: row_contents.append(row_props[col][db_schema[col][\"data_type\"]]) ## Saving",
"Notion database as dataframe with the selected columns :param db_id",
"as a json via Notion's API db_json = get_notion_db_json(db_id) ##",
"to find data else: row_contents.append(row_props[col][db_schema[col][\"data_type\"]]) ## Saving the row contents",
"## Obtaining a dataframe from a notion database def notion_json_to_df(db_json,",
"#### Resetting index df_n.reset_index(inplace=True, drop=True) #### Adjusting column names df_n.columns",
"index df_n.reset_index(inplace=True, drop=True) #### Adjusting column names df_n.columns = [col_n",
"call headers = { \"Authorization\": \"Bearer \" + api_key, \"Notion-Version\":",
"= get_notion_db_json(db_id) ## Obtaining a dataframe from a notion database",
"prop: { \"data_type\": sample_entry[prop][\"type\"] } for prop in sample_entry if",
"req.status_code) return req ## Calling a Notion database as a",
"## Requesting info via the API req = requests.request( \"POST\",",
"== \"title\": continue #### Searching for data in specific locations",
"} ## Calling notion's api req = notion_api_call(db_api_url, db_id, headers)",
"columns :param db_id (string): unique id to identify the notion",
"Database schema db_schema = create_notion_db_schema(db_json, relevant_properties) #### Property that will",
"def notion_db_blueprint_df(db_json, db_schema, index_prop): \"\"\" Building a the blueprint dictionary",
"to make api calls :param db_id (string): unique id of",
":return db_schema (dictionary): schema of the table that includes the",
"Building a the blueprint dictionary for the dataframe (orient=index) def",
"row_name = row_props[index_prop][\"title\"][0][\"plain_text\"] #### Empty list to store all the",
"a notion database :param db_json (json): json object obtained by",
"the blueprint generated \"\"\" ## Calling a Notion database as",
"notion_db_blueprint_df(db_json, db_schema, index_prop) ## Creating dataframe with the resulting blueprint",
"db contents \"\"\" ## Reading credentials from yaml file yaml_file",
"return db_json ## Crating a schema of the notion database",
"be used to create a dataframe with the json contents",
"dataframe with the json contents \"\"\" ## Empty dictionary that",
"gathered df_dict[row_name] = row_contents return df_dict ## Obtaining a dataframe",
"key attribute in the notion db row_name = row_props[index_prop][\"title\"][0][\"plain_text\"] ####",
"a the blueprint dictionary for the dataframe (orient=index) def notion_db_blueprint_df(db_json,",
"notion database :param relevant_properties (list): list of string with the",
"creds_file_path as crds_loc, ) from pkg_dir.src.utils.general_utils import ( read_yaml, )",
"read :param headers (dictionary): dict with authorization and version info",
"Configuring reading URL read_url = db_api_url + db_id + \"/query\"",
"call status print(\"API interaction status code: \", req.status_code) return req",
") ## Verifying API call status print(\"API interaction status code:",
"## Crating a schema of the notion database that was",
"continue #### Searching for data in specific locations for special",
"every row in the dataframe for row in db_json[\"results\"]: ##",
"Read notion database with api def notion_api_call(db_api_url, db_id, headers): \"\"\"",
"a schema of the notion database that was read def",
"Defining the table's base attributes #### All properties contained in",
"how the row will be treated #### Skipping the index",
"table that includes the properties' data type :param index_prop (string):",
"index_prop = [prop for prop in db_schema if db_schema[prop][\"data_type\"] ==",
"info :return req (?): response after calling notions api \"\"\"",
"Standard library imports import requests ## Third party imports import",
"to go over all of it's properties sample_entry = db_json[\"results\"][0][\"properties\"]",
"properties contained in the notion db row_props = row[\"properties\"] ####",
"notion_json_to_df(db_json, relevant_properties): \"\"\" Obtaining a dataframe from a notion database",
"a Notion database as dataframe with the selected columns :param",
"\"\"\" ## Selecting a sample entry to go over all",
"names df_n.columns = [col_n for col_n in db_schema] return df_n",
"the notion database that was read :param db_json (json): json",
"\"\"\" Calling a Notion database as a json via Notion's",
"df_n (dataframe): resulting dataframe crated based on the blueprint generated",
"specific locations for special data types (1) elif data_type in",
"except: row_contents.append(\"No_data\") #### General procedure to find data else: row_contents.append(row_props[col][db_schema[col][\"data_type\"]])",
"the dataframe #### Database schema db_schema = create_notion_db_schema(db_json, relevant_properties) ####",
"db_schema = { prop: { \"data_type\": sample_entry[prop][\"type\"] } for prop",
"requests ## Third party imports import pandas as pd ##",
"name of the property that will serve as the df's",
"provided by Notion to make api calls :param db_id (string):",
"} # print(db_schema) return db_schema ## Building a the blueprint",
"db row_name = row_props[index_prop][\"title\"][0][\"plain_text\"] #### Empty list to store all",
"\"\"\" Obtaining a dataframe from a notion database :param db_json",
"#### Property that will be used as the dataframe's index",
"Imports ######################################################## \"----------------------------------------------------------------------------------------------------------------------\" ## Standard library imports import requests ##",
"Obtaining a dataframe from a notion database def notion_json_to_df(db_json, relevant_properties):",
"\"person\", \"created_by\"]: try: row_contents.append(row_props[col][data_type][\"name\"]) except: row_contents.append(\"No_data\") #### Searching for data",
"credentials from yaml file yaml_file = read_yaml(crds_loc) notion_version = yaml_file[\"notion_api\"][\"notion_version\"]",
"pkg_dir.config.config import ( creds_file_path as crds_loc, ) from pkg_dir.src.utils.general_utils import",
"return db_schema ## Building a the blueprint dictionary for the",
"{ \"data_type\": sample_entry[prop][\"type\"] } for prop in sample_entry if prop",
"response after calling notions api \"\"\" ## Configuring reading URL",
"\"\"\" Building a the blueprint dictionary for the dataframe (orient=index)",
"all the results df_dict = {} ## Iterating over every",
"for data in specific locations for special data types (2)",
"df_dict ## Obtaining a dataframe from a notion database def",
"dataframe (orient=index) df_dict = notion_db_blueprint_df(db_json, db_schema, index_prop) ## Creating dataframe",
"API :param db_id (string): unique id of the database that",
"sample_entry[prop][\"type\"] } for prop in sample_entry if prop in relevant_properties",
"NOTION \"----------------------------------------------------------------------------------------------------------------------\" ####################################################### Imports ######################################################## \"----------------------------------------------------------------------------------------------------------------------\" ## Standard library imports",
"database as a json via Notion's API db_json = get_notion_db_json(db_id)",
"print(\"API interaction status code: \", req.status_code) return req ## Calling",
"notion_api_call(db_api_url, db_id, headers) ## Converting the api response to a",
"of the table that includes the properties' data type \"\"\"",
"blueprint dictionary for the dataframe (orient=index) def notion_db_blueprint_df(db_json, db_schema, index_prop):",
"for the dataframe (orient=index) def notion_db_blueprint_df(db_json, db_schema, index_prop): \"\"\" Building",
"a notion database df_n = notion_json_to_df(db_json, relevant_properties) return df_n \"----------------------------------------------------------------------------------------------------------------------\"",
"that will be read :param headers (dictionary): dict with authorization",
"by calling notion's api :return db_schema (dictionary): schema of the",
":return df_n (dataframe): resulting dataframe crated based on the blueprint",
"Name of the index; key attribute in the notion db",
"#### Inserting the table's index as a column at the",
"the dataframe (orient=index) :param db_json (json): json object obtained by",
"the names of the relevant properties :return df_n (dataframe): resulting",
"code: \", req.status_code) return req ## Calling a Notion database",
"## Calling notion's api req = notion_api_call(db_api_url, db_id, headers) ##",
"== \"string\": row_contents.append(row_props[col][data_type][\"string\"]) elif row_props[col][data_type][\"type\"] == \"number\": row_contents.append(row_props[col][data_type][\"number\"]) except: row_contents.append(\"No_data\")",
"row_contents return df_dict ## Obtaining a dataframe from a notion",
"the properties' data type \"\"\" ## Selecting a sample entry",
"Building a the blueprint dictionary for the dataframe (orient=index) df_dict",
"database :param relevant_properties (list): list of string with the names",
"a sample entry to go over all of it's properties",
") \"----------------------------------------------------------------------------------------------------------------------\" ####################################################### Functions ###################################################### \"----------------------------------------------------------------------------------------------------------------------\" ## Read notion database",
"of the notion database that was read :param db_json (json):",
"and their datatypes db_schema = { prop: { \"data_type\": sample_entry[prop][\"type\"]",
"notion db row_props = row[\"properties\"] #### Name of the index;",
"the dataframe (orient=index) df_dict = notion_db_blueprint_df(db_json, db_schema, index_prop) ## Creating",
"json with the notion's db contents \"\"\" ## Reading credentials",
"json object obtained by calling notion's api :param relevant_properties (list):",
"db_json[\"results\"]: ## Defining the table's base attributes #### All properties",
"the table for col in db_schema: ## Identifying the datatype",
"the results df_dict = {} ## Iterating over every row",
"read_yaml, ) \"----------------------------------------------------------------------------------------------------------------------\" ####################################################### Functions ###################################################### \"----------------------------------------------------------------------------------------------------------------------\" ## Read notion",
"api :param db_api_url (string): base url provided by Notion to",
"notions api \"\"\" ## Configuring reading URL read_url = db_api_url",
"in db_schema: ## Identifying the datatype of the property data_type",
"#### Database schema db_schema = create_notion_db_schema(db_json, relevant_properties) #### Property that",
"from a notion database df_n = notion_json_to_df(db_json, relevant_properties) return df_n",
"the relevant properties and their datatypes db_schema = { prop:",
"db_api_url + db_id + \"/query\" ## Requesting info via the",
"elif data_type in [\"rich_text\"]: try: row_contents.append(row_props[col][data_type][0][\"text\"][\"content\"]) except: row_contents.append(\"No_data\") #### Searching",
"Functions ###################################################### \"----------------------------------------------------------------------------------------------------------------------\" ## Read notion database with api def",
"API def get_notion_db_json(db_id): \"\"\" Calling a Notion database as a",
"store all the row contents row_contents = [] ## Iterating",
"properties' data type :param index_prop (string): name of the property",
"db row_props = row[\"properties\"] #### Name of the index; key",
"the dataframe's index index_prop = [prop for prop in db_schema",
"property in the table for col in db_schema: ## Identifying",
"property that will serve as the df's index :return df_dict",
"contents \"\"\" ## Empty dictionary that will store all the",
"drop=True) #### Adjusting column names df_n.columns = [col_n for col_n",
"(dictionary): dict with authorization and version info :return req (?):",
"######################################################## \"----------------------------------------------------------------------------------------------------------------------\" ## Standard library imports import requests ## Third",
"for the dataframe (orient=index) :param db_json (json): json object obtained",
"for prop in db_schema if db_schema[prop][\"data_type\"] == \"title\"][0] ## Building",
"def notion_db_to_df(db_id, relevant_properties): \"\"\" Obtaining a Notion database as dataframe",
"to store all the row contents row_contents = [] ##",
"(orient=index) df_dict = notion_db_blueprint_df(db_json, db_schema, index_prop) ## Creating dataframe with",
"db_json = get_notion_db_json(db_id) ## Obtaining a dataframe from a notion",
"#### All properties contained in the notion db row_props =",
"Local application imports from pkg_dir.config.config import ( creds_file_path as crds_loc,",
"imports from pkg_dir.config.config import ( creds_file_path as crds_loc, ) from",
"db_schema (dictionary): schema of the table that includes the properties'",
":param db_api_url (string): base url provided by Notion to make",
"Verifying API call status print(\"API interaction status code: \", req.status_code)",
"sample entry to go over all of it's properties sample_entry",
"data in specific locations for special data types (1) elif",
"relevant_properties): \"\"\" Obtaining a dataframe from a notion database :param",
"\"Notion-Version\": notion_version } ## Calling notion's api req = notion_api_call(db_api_url,",
"schema db_schema = create_notion_db_schema(db_json, relevant_properties) #### Property that will be",
"on the blueprint generated \"\"\" ## Calling a Notion database",
"file yaml_file = read_yaml(crds_loc) notion_version = yaml_file[\"notion_api\"][\"notion_version\"] db_api_url = yaml_file[\"notion_api\"][\"db_api_url\"]",
"be called :return db_json (json): json with the notion's db",
"headers = { \"Authorization\": \"Bearer \" + api_key, \"Notion-Version\": notion_version",
"the relevant properties :return df_n (dataframe): resulting dataframe crated based",
"dataframe with the selected columns :param db_id (string): unique id",
"id of the database that will be called :return db_json",
"read :param db_json (json): json object obtained by calling notion's",
"for the API call headers = { \"Authorization\": \"Bearer \"",
"Calling notion's api req = notion_api_call(db_api_url, db_id, headers) ## Converting",
"dictionary that will be used to create a dataframe with",
"index row if data_type == \"title\": continue #### Searching for",
"schema of the notion database that was read def create_notion_db_schema(db_json,",
"import requests ## Third party imports import pandas as pd",
"as the df's index :return df_dict (dict): dictionary that will",
"that will serve as the df's index :return df_dict (dict):",
"data_type = db_schema[col][\"data_type\"] ## Set of conditions to determine how",
"table's index as a column at the end of the",
"+ db_id + \"/query\" ## Requesting info via the API",
"(2) elif data_type in [\"formula\"]: try: #### Applying conditions based",
"= [prop for prop in db_schema if db_schema[prop][\"data_type\"] == \"title\"][0]",
"notion's api :param relevant_properties (list): list of string with the",
"= db_json[\"results\"][0][\"properties\"] ## Bulding dictionary (schema) of the relevant properties",
"data types (2) elif data_type in [\"formula\"]: try: #### Applying",
"contents \"\"\" ## Reading credentials from yaml file yaml_file =",
"data_type in [\"rich_text\"]: try: row_contents.append(row_props[col][data_type][0][\"text\"][\"content\"]) except: row_contents.append(\"No_data\") #### Searching for",
"from yaml file yaml_file = read_yaml(crds_loc) notion_version = yaml_file[\"notion_api\"][\"notion_version\"] db_api_url",
":param db_json (json): json object obtained by calling notion's api",
"(1) elif data_type in [\"select\", \"person\", \"created_by\"]: try: row_contents.append(row_props[col][data_type][\"name\"]) except:",
"def notion_json_to_df(db_json, relevant_properties): \"\"\" Obtaining a dataframe from a notion",
"## Creating dataframe with the resulting blueprint dictionary #### Crating",
"#### Empty list to store all the row contents row_contents",
"of the property data_type = db_schema[col][\"data_type\"] ## Set of conditions",
"row_props[col][data_type][\"type\"] == \"number\": row_contents.append(row_props[col][data_type][\"number\"]) except: row_contents.append(\"No_data\") #### General procedure to",
"and version info :return req (?): response after calling notions",
"db_id, headers): \"\"\" Read notion database with api :param db_api_url",
"(list): list of string with the names of the relevant",
"json contents \"\"\" ## Empty dictionary that will store all",
"the notion database :param relevant_properties (list): list of string with",
"notion database with api :param db_api_url (string): base url provided",
"( creds_file_path as crds_loc, ) from pkg_dir.src.utils.general_utils import ( read_yaml,",
"used as the dataframe's index index_prop = [prop for prop",
"[] ## Iterating over every relevant property in the table",
"for col in db_schema: ## Identifying the datatype of the",
"the json contents \"\"\" ## Empty dictionary that will store",
"find data else: row_contents.append(row_props[col][db_schema[col][\"data_type\"]]) ## Saving the row contents gathered",
"the blueprint dictionary for the dataframe (orient=index) def notion_db_blueprint_df(db_json, db_schema,",
"req = notion_api_call(db_api_url, db_id, headers) ## Converting the api response",
"## Bulding dictionary (schema) of the relevant properties and their",
"api :return db_schema (dictionary): schema of the table that includes",
"\"----------------------------------------------------------------------------------------------------------------------\" ## Standard library imports import requests ## Third party",
"df_dict = {} ## Iterating over every row in the",
"that includes the properties' data type :param index_prop (string): name",
"= yaml_file[\"notion_api\"][\"db_api_url\"] api_key = yaml_file[\"notion_api\"][\"api_key\"] ## Building headers for the",
"index index_prop = [prop for prop in db_schema if db_schema[prop][\"data_type\"]",
"includes the properties' data type \"\"\" ## Selecting a sample",
"Crating dataframe df_n = pd.DataFrame.from_dict(df_dict, orient=\"index\") #### Inserting the table's",
"datatype of the property data_type = db_schema[col][\"data_type\"] ## Set of",
"from pkg_dir.config.config import ( creds_file_path as crds_loc, ) from pkg_dir.src.utils.general_utils",
"data type \"\"\" ## Selecting a sample entry to go",
"locations for special data types (1) elif data_type in [\"select\",",
"index_prop): \"\"\" Building a the blueprint dictionary for the dataframe",
"dataframe crated based on the blueprint generated \"\"\" ## General",
"## Third party imports import pandas as pd ## Local",
"a dataframe from a notion database def notion_json_to_df(db_json, relevant_properties): \"\"\"",
"from pkg_dir.src.utils.general_utils import ( read_yaml, ) \"----------------------------------------------------------------------------------------------------------------------\" ####################################################### Functions ######################################################",
"in relevant_properties } # print(db_schema) return db_schema ## Building a",
"elif row_props[col][data_type][\"type\"] == \"number\": row_contents.append(row_props[col][data_type][\"number\"]) except: row_contents.append(\"No_data\") #### General procedure",
"generated \"\"\" ## Calling a Notion database as a json",
"the row will be treated #### Skipping the index row",
"df_n.insert( df_n.shape[1], index_prop, df_n.index ) #### Resetting index df_n.reset_index(inplace=True, drop=True)",
"\"title\"][0] ## Building a the blueprint dictionary for the dataframe",
"Identifying the datatype of the property data_type = db_schema[col][\"data_type\"] ##",
"row_props[col][data_type][\"type\"] == \"string\": row_contents.append(row_props[col][data_type][\"string\"]) elif row_props[col][data_type][\"type\"] == \"number\": row_contents.append(row_props[col][data_type][\"number\"]) except:",
"columns def notion_db_to_df(db_id, relevant_properties): \"\"\" Obtaining a Notion database as",
"the type of formula result if row_props[col][data_type][\"type\"] == \"string\": row_contents.append(row_props[col][data_type][\"string\"])",
"at the end of the df df_n.insert( df_n.shape[1], index_prop, df_n.index",
"\"Authorization\": \"Bearer \" + api_key, \"Notion-Version\": notion_version } ## Calling",
"df_n.shape[1], index_prop, df_n.index ) #### Resetting index df_n.reset_index(inplace=True, drop=True) ####",
":param db_id (string): unique id of the database that will",
"import ( creds_file_path as crds_loc, ) from pkg_dir.src.utils.general_utils import (",
"blueprint dictionary #### Crating dataframe df_n = pd.DataFrame.from_dict(df_dict, orient=\"index\") ####",
"in sample_entry if prop in relevant_properties } # print(db_schema) return",
"the blueprint dictionary for the dataframe (orient=index) df_dict = notion_db_blueprint_df(db_json,",
":param headers (dictionary): dict with authorization and version info :return",
"notion database def notion_json_to_df(db_json, relevant_properties): \"\"\" Obtaining a dataframe from",
"df_dict (dict): dictionary that will be used to create a",
"headers) ## Converting the api response to a json db_json",
"= yaml_file[\"notion_api\"][\"api_key\"] ## Building headers for the API call headers",
"as pd ## Local application imports from pkg_dir.config.config import (",
"## Selecting a sample entry to go over all of",
"(json): json object obtained by calling notion's api :return db_schema",
"df_n.reset_index(inplace=True, drop=True) #### Adjusting column names df_n.columns = [col_n for",
"row_contents.append(\"No_data\") #### Searching for data in specific locations for special",
"db_schema, index_prop) ## Creating dataframe with the resulting blueprint dictionary",
"####################################################### Functions ###################################################### \"----------------------------------------------------------------------------------------------------------------------\" ## Read notion database with api",
"dataframe for row in db_json[\"results\"]: ## Defining the table's base",
"read_yaml(crds_loc) notion_version = yaml_file[\"notion_api\"][\"notion_version\"] db_api_url = yaml_file[\"notion_api\"][\"db_api_url\"] api_key = yaml_file[\"notion_api\"][\"api_key\"]",
"database with api def notion_api_call(db_api_url, db_id, headers): \"\"\" Read notion",
"dataframe with the selected columns def notion_db_to_df(db_id, relevant_properties): \"\"\" Obtaining",
"Iterating over every relevant property in the table for col",
"the table that includes the properties' data type \"\"\" ##",
"index; key attribute in the notion db row_name = row_props[index_prop][\"title\"][0][\"plain_text\"]",
"the database that will be read :param headers (dictionary): dict",
"special data types (2) elif data_type in [\"formula\"]: try: ####",
"= row[\"properties\"] #### Name of the index; key attribute in",
"# print(db_schema) return db_schema ## Building a the blueprint dictionary",
"dataframe from a notion database df_n = notion_json_to_df(db_json, relevant_properties) return",
"Obtaining a dataframe from a notion database :param db_json (json):",
"unique id to identify the notion database :param relevant_properties (list):",
"list to store all the row contents row_contents = []",
"row_contents.append(row_props[col][db_schema[col][\"data_type\"]]) ## Saving the row contents gathered df_dict[row_name] = row_contents",
"be read :param headers (dictionary): dict with authorization and version",
"if db_schema[prop][\"data_type\"] == \"title\"][0] ## Building a the blueprint dictionary",
"in db_schema] return df_n ## Obtaining a Notion database as",
"notion database that was read :param db_json (json): json object",
"yaml file yaml_file = read_yaml(crds_loc) notion_version = yaml_file[\"notion_api\"][\"notion_version\"] db_api_url =",
"via Notion's API db_json = get_notion_db_json(db_id) ## Obtaining a dataframe",
"dataframe #### Database schema db_schema = create_notion_db_schema(db_json, relevant_properties) #### Property",
"Inserting the table's index as a column at the end",
"req = requests.request( \"POST\", read_url, headers=headers ) ## Verifying API",
"Resetting index df_n.reset_index(inplace=True, drop=True) #### Adjusting column names df_n.columns =",
"row if data_type == \"title\": continue #### Searching for data",
"needed to build the dataframe #### Database schema db_schema =",
"type :param index_prop (string): name of the property that will",
"will store all the results df_dict = {} ## Iterating",
"db_api_url (string): base url provided by Notion to make api",
"= row_contents return df_dict ## Obtaining a dataframe from a",
"by Notion to make api calls :param db_id (string): unique",
"df's index :return df_dict (dict): dictionary that will be used",
"of string with the names of the relevant properties :return",
"row_props[index_prop][\"title\"][0][\"plain_text\"] #### Empty list to store all the row contents",
"== \"number\": row_contents.append(row_props[col][data_type][\"number\"]) except: row_contents.append(\"No_data\") #### General procedure to find",
"procedure to find data else: row_contents.append(row_props[col][db_schema[col][\"data_type\"]]) ## Saving the row",
"notion database :param db_json (json): json object obtained by calling",
"data_type == \"title\": continue #### Searching for data in specific",
"## Reading credentials from yaml file yaml_file = read_yaml(crds_loc) notion_version",
"API call status print(\"API interaction status code: \", req.status_code) return",
"(json): json object obtained by calling notion's api :param relevant_properties",
"df_dict[row_name] = row_contents return df_dict ## Obtaining a dataframe from",
"the selected columns :param db_id (string): unique id to identify",
"calling notion's api :return db_schema (dictionary): schema of the table",
"be treated #### Skipping the index row if data_type ==",
"of conditions to determine how the row will be treated",
"dataframe from a notion database def notion_json_to_df(db_json, relevant_properties): \"\"\" Obtaining",
"index as a column at the end of the df",
"db_id, headers) ## Converting the api response to a json",
"api :param relevant_properties (list): list of string with the names",
"resulting dataframe crated based on the blueprint generated \"\"\" ##",
"the index row if data_type == \"title\": continue #### Searching",
"as crds_loc, ) from pkg_dir.src.utils.general_utils import ( read_yaml, ) \"----------------------------------------------------------------------------------------------------------------------\"",
"to determine how the row will be treated #### Skipping",
"api response to a json db_json = req.json() return db_json",
"req.json() return db_json ## Crating a schema of the notion",
"will be read :param headers (dictionary): dict with authorization and",
"(dictionary): schema of the table that includes the properties' data",
"to create a dataframe with the json contents \"\"\" ##",
"locations for special data types (2) elif data_type in [\"rich_text\"]:",
"the datatype of the property data_type = db_schema[col][\"data_type\"] ## Set",
"over every row in the dataframe for row in db_json[\"results\"]:",
"a dataframe from a notion database df_n = notion_json_to_df(db_json, relevant_properties)",
"for row in db_json[\"results\"]: ## Defining the table's base attributes",
"read_url = db_api_url + db_id + \"/query\" ## Requesting info",
"db_id (string): unique id of the database that will be",
"db_json (json): json with the notion's db contents \"\"\" ##",
"\"\"\" Crating a schema of the notion database that was",
"build the dataframe #### Database schema db_schema = create_notion_db_schema(db_json, relevant_properties)",
"database with api :param db_api_url (string): base url provided by",
"of the notion database that was read def create_notion_db_schema(db_json, relevant_properties):",
"contents gathered df_dict[row_name] = row_contents return df_dict ## Obtaining a",
"notion_db_to_df(db_id, relevant_properties): \"\"\" Obtaining a Notion database as dataframe with",
"yaml_file[\"notion_api\"][\"db_api_url\"] api_key = yaml_file[\"notion_api\"][\"api_key\"] ## Building headers for the API",
"for special data types (1) elif data_type in [\"select\", \"person\",",
"row_contents = [] ## Iterating over every relevant property in",
"in [\"select\", \"person\", \"created_by\"]: try: row_contents.append(row_props[col][data_type][\"name\"]) except: row_contents.append(\"No_data\") #### Searching",
"index_prop, df_n.index ) #### Resetting index df_n.reset_index(inplace=True, drop=True) #### Adjusting",
"a Notion database as a json via Notion's API db_json",
":param index_prop (string): name of the property that will serve",
"special data types (2) elif data_type in [\"rich_text\"]: try: row_contents.append(row_props[col][data_type][0][\"text\"][\"content\"])",
"relevant properties and their datatypes db_schema = { prop: {",
"of the property that will serve as the df's index",
"in db_schema if db_schema[prop][\"data_type\"] == \"title\"][0] ## Building a the",
"\"data_type\": sample_entry[prop][\"type\"] } for prop in sample_entry if prop in",
"#### Searching for data in specific locations for special data",
"of formula result if row_props[col][data_type][\"type\"] == \"string\": row_contents.append(row_props[col][data_type][\"string\"]) elif row_props[col][data_type][\"type\"]",
"relevant_properties): \"\"\" Obtaining a Notion database as dataframe with the",
"database that was read def create_notion_db_schema(db_json, relevant_properties): \"\"\" Crating a",
"in specific locations for special data types (1) elif data_type",
"property data_type = db_schema[col][\"data_type\"] ## Set of conditions to determine",
"a the blueprint dictionary for the dataframe (orient=index) :param db_json",
"of the index; key attribute in the notion db row_name",
"{ \"Authorization\": \"Bearer \" + api_key, \"Notion-Version\": notion_version } ##",
"conditions to determine how the row will be treated ####",
"from a notion database def notion_json_to_df(db_json, relevant_properties): \"\"\" Obtaining a",
"of the table that includes the properties' data type :param",
"= {} ## Iterating over every row in the dataframe",
"row_contents.append(row_props[col][data_type][\"name\"]) except: row_contents.append(\"No_data\") #### Searching for data in specific locations",
"Creating dataframe with the resulting blueprint dictionary #### Crating dataframe",
"column at the end of the df df_n.insert( df_n.shape[1], index_prop,",
"(?): response after calling notions api \"\"\" ## Configuring reading",
"over all of it's properties sample_entry = db_json[\"results\"][0][\"properties\"] ## Bulding",
"identify the notion database :param relevant_properties (list): list of string",
"get_notion_db_json(db_id): \"\"\" Calling a Notion database as a json via",
"Set of conditions to determine how the row will be",
"db_json ## Crating a schema of the notion database that",
"their datatypes db_schema = { prop: { \"data_type\": sample_entry[prop][\"type\"] }",
"dictionary for the dataframe (orient=index) df_dict = notion_db_blueprint_df(db_json, db_schema, index_prop)",
"Iterating over every row in the dataframe for row in",
"end of the df df_n.insert( df_n.shape[1], index_prop, df_n.index ) ####",
"Third party imports import pandas as pd ## Local application",
"the properties' data type :param index_prop (string): name of the",
"unique id of the database that will be read :param",
":return df_dict (dict): dictionary that will be used to create",
"names of the relevant properties :return db_schema (dictionary): schema of",
"dataframe crated based on the blueprint generated \"\"\" ## Calling",
"pkg_dir.src.utils.general_utils import ( read_yaml, ) \"----------------------------------------------------------------------------------------------------------------------\" ####################################################### Functions ###################################################### \"----------------------------------------------------------------------------------------------------------------------\"",
"return df_dict ## Obtaining a dataframe from a notion database",
"with the names of the relevant properties :return db_schema (dictionary):",
"def notion_api_call(db_api_url, db_id, headers): \"\"\" Read notion database with api",
"df_dict = notion_db_blueprint_df(db_json, db_schema, index_prop) ## Creating dataframe with the",
"for prop in sample_entry if prop in relevant_properties } #",
"\" + api_key, \"Notion-Version\": notion_version } ## Calling notion's api",
"Notion database as a json via Notion's API db_json =",
"a json db_json = req.json() return db_json ## Crating a",
"#### Skipping the index row if data_type == \"title\": continue",
"blueprint dictionary for the dataframe (orient=index) df_dict = notion_db_blueprint_df(db_json, db_schema,",
"db_schema if db_schema[prop][\"data_type\"] == \"title\"][0] ## Building a the blueprint",
"Requesting info via the API req = requests.request( \"POST\", read_url,",
"try: row_contents.append(row_props[col][data_type][\"name\"]) except: row_contents.append(\"No_data\") #### Searching for data in specific",
"specific locations for special data types (2) elif data_type in",
"string with the names of the relevant properties :return db_schema",
"(orient=index) :param db_json (json): json object obtained by calling notion's",
"the index; key attribute in the notion db row_name =",
"## Identifying the datatype of the property data_type = db_schema[col][\"data_type\"]",
"elif data_type in [\"select\", \"person\", \"created_by\"]: try: row_contents.append(row_props[col][data_type][\"name\"]) except: row_contents.append(\"No_data\")",
"go over all of it's properties sample_entry = db_json[\"results\"][0][\"properties\"] ##",
"database as a json via Notion's API def get_notion_db_json(db_id): \"\"\"",
"types (1) elif data_type in [\"select\", \"person\", \"created_by\"]: try: row_contents.append(row_props[col][data_type][\"name\"])",
"## Obtaining a Notion database as dataframe with the selected",
"Obtaining a Notion database as dataframe with the selected columns",
"req (?): response after calling notions api \"\"\" ## Configuring",
"the notion database that was read def create_notion_db_schema(db_json, relevant_properties): \"\"\"",
"col in db_schema: ## Identifying the datatype of the property",
"(schema) of the relevant properties and their datatypes db_schema =",
"## MODULE WITH UTIL FUNCTIONS - NOTION \"----------------------------------------------------------------------------------------------------------------------\" ####################################################### Imports",
"properties sample_entry = db_json[\"results\"][0][\"properties\"] ## Bulding dictionary (schema) of the",
"list of string with the names of the relevant properties",
"after calling notions api \"\"\" ## Configuring reading URL read_url",
"data_type in [\"formula\"]: try: #### Applying conditions based on the",
"= yaml_file[\"notion_api\"][\"notion_version\"] db_api_url = yaml_file[\"notion_api\"][\"db_api_url\"] api_key = yaml_file[\"notion_api\"][\"api_key\"] ## Building",
"api_key, \"Notion-Version\": notion_version } ## Calling notion's api req =",
"unique id of the database that will be called :return",
"info via the API req = requests.request( \"POST\", read_url, headers=headers",
"json db_json = req.json() return db_json ## Crating a schema",
"types (2) elif data_type in [\"formula\"]: try: #### Applying conditions",
"type of formula result if row_props[col][data_type][\"type\"] == \"string\": row_contents.append(row_props[col][data_type][\"string\"]) elif",
"[\"select\", \"person\", \"created_by\"]: try: row_contents.append(row_props[col][data_type][\"name\"]) except: row_contents.append(\"No_data\") #### Searching for",
"of it's properties sample_entry = db_json[\"results\"][0][\"properties\"] ## Bulding dictionary (schema)",
"data_type in [\"select\", \"person\", \"created_by\"]: try: row_contents.append(row_props[col][data_type][\"name\"]) except: row_contents.append(\"No_data\") ####",
"if row_props[col][data_type][\"type\"] == \"string\": row_contents.append(row_props[col][data_type][\"string\"]) elif row_props[col][data_type][\"type\"] == \"number\": row_contents.append(row_props[col][data_type][\"number\"])",
"General procedure to find data else: row_contents.append(row_props[col][db_schema[col][\"data_type\"]]) ## Saving the",
"## Building a the blueprint dictionary for the dataframe (orient=index)",
"imports import requests ## Third party imports import pandas as",
"base url provided by Notion to make api calls :param",
"in the notion db row_name = row_props[index_prop][\"title\"][0][\"plain_text\"] #### Empty list",
"API db_json = get_notion_db_json(db_id) ## Obtaining a dataframe from a",
"for special data types (2) elif data_type in [\"rich_text\"]: try:",
"notion db row_name = row_props[index_prop][\"title\"][0][\"plain_text\"] #### Empty list to store",
"yaml_file[\"notion_api\"][\"api_key\"] ## Building headers for the API call headers =",
"except: row_contents.append(\"No_data\") #### Searching for data in specific locations for",
"\"/query\" ## Requesting info via the API req = requests.request(",
"## Verifying API call status print(\"API interaction status code: \",",
"db_json[\"results\"][0][\"properties\"] ## Bulding dictionary (schema) of the relevant properties and",
"{} ## Iterating over every row in the dataframe for",
"a dataframe from a notion database :param db_json (json): json",
"a the blueprint dictionary for the dataframe (orient=index) df_dict =",
"status print(\"API interaction status code: \", req.status_code) return req ##",
"yaml_file = read_yaml(crds_loc) notion_version = yaml_file[\"notion_api\"][\"notion_version\"] db_api_url = yaml_file[\"notion_api\"][\"db_api_url\"] api_key"
] |
[
"submit(self): LOGGER.info('submit was called') return super().submit() def make(self): LOGGER.info('make was",
"self.issue.uri) # TrackedResolvedIssue should behave the same way as TrackedUnresolvedIssue",
"'http://issuetracker.example.com/123') def test_str(self): self.assertEqual(str(self.issue), self.issue.uri) # TrackedResolvedIssue should behave the",
"cm: result1 = issue.submit() result2 = issue.submit() self.assertEqual(cm.output, [ \"INFO:test:submit",
"was called') return 'http://issuetracker.example.com/new_issue' def update(self): LOGGER.info('update was called') def",
"= self.assertSubmitCreate(self.new) self.assertTrue(self.new.new) self.assertTrue(self.new.tracked) self.assertEqual(result, 'http://issuetracker.example.com/new_issue') self.assertEqual(result, self.new.uri) # repeated",
"self.assertLogs('test', level='INFO') as cm: result = self.new.submit() self.assertEqual(cm.output, [ \"INFO:test:submit",
"with self.assertUnchanged(issue): with self.assertLogs('test', level='INFO') as cm: issue.submit() issue.submit() self.assertEqual(cm.output,",
"was called']) self.test_properties() def test_str(self): self.assertEqual(str(self.issue), self.issue.report_url) class TestTrackedUnresolvedIssue(TestNewIssue): def",
"'issueAnalyzer' : { 'create_issues': False, 'update_issues': False, 'create_issues_instead_of_update': False, }",
"class TestSubmitCreateOnlyNew(TestSubmitCreateUpdate): settings = Settings( { 'issueAnalyzer' : { 'create_issues':",
"@property def resolved(self): return False @property def report_url(self): return 'http://issuetracker.example.com/new/bar'",
"import IssueAnalyzerProxy from .base import BaseAnalyzer, BaseIssue from .issueset import",
"test lookup was called with self.assertLogs('test', level='INFO') as cm: self.issue.sync()",
"self.new.uri) # repeated submit doesn't do anything with self.assertUnchanged(self.new): with",
"def submit(self): LOGGER.info('submit was called') return super().submit() def make(self): LOGGER.info('make",
"]) self.assertEqual(result1, result2) return result1 def testNew(self): self.assertSubmitNoop(self.new) def testUnresolved(self):",
"TrackedUnresolvedIssue(self.settings) def test_properties(self): self.assertFalse(self.issue.new) self.assertTrue(self.issue.tracked) self.assertEqual(self.issue.uri, 'http://issuetracker.example.com/123') def test_str(self): self.assertEqual(str(self.issue),",
"self.assertTrue(self.issue.tracked) self.assertEqual(self.issue.uri, 'http://issuetracker.example.com/123') def test_str(self): self.assertEqual(str(self.issue), self.issue.uri) # TrackedResolvedIssue should",
"{}, [] ) def testUnresolved(self): self.assertSubmitNoop(self.unresolved) def testResolved(self): self.assertSubmitNoop(self.resolved) class",
"called') def _lookup(self): LOGGER.info('lookup was called') return None @property def",
"def assertUnchanged(self, issue): old_uri = issue.uri old_new = issue.new old_tracked",
"# TrackedResolvedIssue should behave the same way as TrackedUnresolvedIssue #",
"self.assertEqual(result1, result2) return result1 def testNew(self): self.assertSubmitNoop(self.new) def testUnresolved(self): self.assertSubmitNoop(self.unresolved)",
": { 'create_issues': False, 'update_issues': True, 'create_issues_instead_of_update': False, } },",
"self.assertNotEqual(result, old_uri) # The update_issue should have no effect when",
"test_str(self): self.assertEqual(str(self.issue), self.issue.uri) # TrackedResolvedIssue should behave the same way",
"def resolved(self): return True class TestNewIssue(unittest.TestCase): def setUp(self): self.settings =",
"old_tracked = issue.tracked yield issue self.assertEqual(issue.uri, old_uri) self.assertEqual(issue.new, old_new) self.assertEqual(issue.tracked,",
"[] ) def testNew(self): self.assertSubmitNoop(self.new) class TestSubmitCreateAlwaysWithUpdateOff(TestSubmitCreateUpdate): settings = Settings(",
"old_uri) # The update_issue should have no effect when create_issues_instead_of_update",
"{}, [] ) def testNew(self): self.assertSubmitNoop(self.new) class TestSubmitCreateAlwaysWithUpdateOff(TestSubmitCreateUpdate): settings =",
"called with self.assertLogs('test', level='INFO') as cm: self.issue.sync() self.assertEqual(cm.output, ['INFO:test:lookup was",
"False, } }, {}, [] ) def testUnresolved(self): self.assertSubmitNoop(self.unresolved) def",
"{ 'issueAnalyzer' : { 'create_issues': True, 'update_issues': True, 'create_issues_instead_of_update': False,",
"as cm: self.issue.sync() self.assertEqual(cm.output, ['INFO:test:lookup was called']) self.test_properties() def test_str(self):",
"return False @property def report_url(self): return 'http://issuetracker.example.com/new/bar' class TrackedResolvedIssue(TrackedUnresolvedIssue): @property",
"= Settings( { 'issueAnalyzer' : { 'create_issues': False, 'update_issues': True,",
"# sync the issues so that lookup is not called",
"called']) self.test_properties() def test_str(self): self.assertEqual(str(self.issue), self.issue.report_url) class TestTrackedUnresolvedIssue(TestNewIssue): def setUp(self):",
"BaseAnalyzer, BaseIssue from .issueset import IssueSet LOGGER = logging.getLogger('test') class",
"report_url(self): return 'http://issuetracker.example.com/new/foo' class TrackedUnresolvedIssue(NewIssue): def _lookup(self): LOGGER.info('lookup was called')",
"Settings({}, {}, []) self.issue = TrackedUnresolvedIssue(self.settings) def test_properties(self): self.assertFalse(self.issue.new) self.assertTrue(self.issue.tracked)",
"}, {}, [] ) def setUp(self): self.new = NewIssue(self.settings) self.unresolved",
"have no effect 'create_issues_instead_of_update': True, } }, {}, [] )",
"self.assertSubmitUpdate(self.resolved) class TestSubmitCreateOnlyNew(TestSubmitCreateUpdate): settings = Settings( { 'issueAnalyzer' : {",
"issue.submit() result2 = issue.submit() self.assertEqual(cm.output, [ \"INFO:test:submit was called\", \"INFO:test:update",
"as TrackedUnresolvedIssue # so just inherit the whole test case",
"lookup was called with self.assertLogs('test', level='INFO') as cm: self.issue.sync() self.assertEqual(cm.output,",
"import IssueSet LOGGER = logging.getLogger('test') class NewIssue(BaseIssue): def submit(self): LOGGER.info('submit",
"return super().submit() def make(self): LOGGER.info('make was called') return 'http://issuetracker.example.com/new_issue' def",
"TestSubmitCreateUpdate(TestSubmitDisabled): settings = Settings( { 'issueAnalyzer' : { 'create_issues': True,",
": { 'create_issues': True, 'update_issues': False, 'create_issues_instead_of_update': False, } },",
"return True class TestNewIssue(unittest.TestCase): def setUp(self): self.settings = Settings({}, {},",
"old_new) self.assertEqual(issue.tracked, old_tracked) def assertSubmitNoop(self, issue): with self.assertUnchanged(issue): with self.assertLogs('test',",
"'http://issuetracker.example.com/new_issue') self.assertEqual(self.resolved.uri, result) self.assertNotEqual(result, old_uri) # The update_issue should have",
"'http://issuetracker.example.com/new_issue') self.assertEqual(self.unresolved.uri, result) self.assertNotEqual(result, old_uri) def testResolved(self): old_uri = self.resolved.uri",
"was called with self.assertLogs('test', level='INFO') as cm: self.issue.sync() self.assertEqual(cm.output, ['INFO:test:lookup",
"'create_issues': True, 'update_issues': False, 'create_issues_instead_of_update': False, } }, {}, []",
"class TestSubmitDisabled(unittest.TestCase): settings = Settings( { 'issueAnalyzer' : { 'create_issues':",
"cm: result = self.new.submit() self.assertEqual(cm.output, [ \"INFO:test:submit was called\", ])",
"called\", \"INFO:test:update was called\", \"INFO:test:submit was called\", ]) self.assertEqual(result1, result2)",
"no effect 'create_issues_instead_of_update': True, } }, {}, [] ) def",
"TrackedResolvedIssue(self.settings) # sync the issues so that lookup is not",
"old_new = issue.new old_tracked = issue.tracked yield issue self.assertEqual(issue.uri, old_uri)",
"submit doesn't do anything with self.assertUnchanged(self.new): with self.assertLogs('test', level='INFO') as",
"\"INFO:test:submit was called\", \"INFO:test:update was called\", \"INFO:test:submit was called\", ])",
"just inherit the whole test case to run the very",
"return False @property def report_url(self): return 'http://issuetracker.example.com/new/foo' class TrackedUnresolvedIssue(NewIssue): def",
"testNew(self): self.assertSubmitNoop(self.new) def testUnresolved(self): self.assertSubmitNoop(self.unresolved) def testResolved(self): self.assertSubmitNoop(self.resolved) class TestSubmitCreateUpdate(TestSubmitDisabled):",
"True. class TestSubmitCreateAlwaysWithUpdateOn(TestSubmitCreateAlwaysWithUpdateOff): settings = Settings( { 'issueAnalyzer' : {",
"called') return 'http://issuetracker.example.com/new_issue' def update(self): LOGGER.info('update was called') def _lookup(self):",
"= TrackedUnresolvedIssue(self.settings) self.resolved = TrackedResolvedIssue(self.settings) # sync the issues so",
"called\", ]) self.assertEqual(result1, result2) return result1 def assertSubmitUpdate(self, issue): with",
"settings = Settings( { 'issueAnalyzer' : { 'create_issues': False, 'update_issues':",
"<filename>libpermian/issueanalyzer/test_baseissue.py import unittest import logging import contextlib from libpermian.settings import",
"self.assertLogs('test', level='INFO') as cm: issue.submit() issue.submit() self.assertEqual(cm.output, [ \"INFO:test:submit was",
"as cm: result = self.new.submit() self.assertEqual(cm.output, [ \"INFO:test:submit was called\",",
"{ 'create_issues': False, 'update_issues': True, 'create_issues_instead_of_update': False, } }, {},",
"level='INFO') as cm: result1 = issue.submit() result2 = issue.submit() self.assertEqual(cm.output,",
"} }, {}, [] ) def testNew(self): result = self.assertSubmitCreate(self.new)",
"class TestSubmitUpdateOnlyTracked(TestSubmitCreateUpdate): settings = Settings( { 'issueAnalyzer' : { 'create_issues':",
"def setUp(self): self.settings = Settings({}, {}, []) self.issue = TrackedResolvedIssue(self.settings)",
"return result1 def assertSubmitUpdate(self, issue): with self.assertUnchanged(issue): with self.assertLogs('test', level='INFO')",
"result = self.new.submit() self.assertEqual(cm.output, [ \"INFO:test:submit was called\", ]) def",
"self.assertEqual(self.resolved.uri, result) self.assertNotEqual(result, old_uri) # The update_issue should have no",
"]) def testUnresolved(self): self.assertSubmitUpdate(self.unresolved) def testResolved(self): self.assertSubmitUpdate(self.resolved) class TestSubmitCreateOnlyNew(TestSubmitCreateUpdate): settings",
"called') return super().submit() def make(self): LOGGER.info('make was called') return 'http://issuetracker.example.com/new_issue'",
") def testUnresolved(self): self.assertSubmitNoop(self.unresolved) def testResolved(self): self.assertSubmitNoop(self.resolved) class TestSubmitUpdateOnlyTracked(TestSubmitCreateUpdate): settings",
"'update_issues': True, # This should have no effect 'create_issues_instead_of_update': True,",
"import Settings from .proxy import IssueAnalyzerProxy from .base import BaseAnalyzer,",
"self.test_properties() def test_str(self): self.assertEqual(str(self.issue), self.issue.report_url) class TestTrackedUnresolvedIssue(TestNewIssue): def setUp(self): self.settings",
"'create_issues': True, 'update_issues': False, # This should have no effect",
"TestTrackedUnresolvedIssue(TestNewIssue): def setUp(self): self.settings = Settings({}, {}, []) self.issue =",
"[] ) def testUnresolved(self): old_uri = self.unresolved.uri result = self.assertSubmitCreate(self.unresolved)",
"def _lookup(self): LOGGER.info('lookup was called') return None @property def resolved(self):",
"issue.submit() result2 = issue.submit() self.assertEqual(cm.output, [ \"INFO:test:submit was called\", \"INFO:test:make",
"old_uri = issue.uri old_new = issue.new old_tracked = issue.tracked yield",
"issue self.assertEqual(issue.uri, old_uri) self.assertEqual(issue.new, old_new) self.assertEqual(issue.tracked, old_tracked) def assertSubmitNoop(self, issue):",
"case to run the very same test class TestTrackedResolvedIssue(TestTrackedUnresolvedIssue): def",
"issue.new old_tracked = issue.tracked yield issue self.assertEqual(issue.uri, old_uri) self.assertEqual(issue.new, old_new)",
"\"INFO:test:update was called\", \"INFO:test:submit was called\", ]) self.assertEqual(result1, result2) return",
"the same way as TrackedUnresolvedIssue # so just inherit the",
"settings = Settings( { 'issueAnalyzer' : { 'create_issues': True, 'update_issues':",
"whole test case to run the very same test class",
"issue.uri old_new = issue.new old_tracked = issue.tracked yield issue self.assertEqual(issue.uri,",
"update_issue should have no effect when create_issues_instead_of_update # is set",
"resolved(self): return False @property def report_url(self): return 'http://issuetracker.example.com/new/bar' class TrackedResolvedIssue(TrackedUnresolvedIssue):",
"'http://issuetracker.example.com/new/bar' class TrackedResolvedIssue(TrackedUnresolvedIssue): @property def resolved(self): return True class TestNewIssue(unittest.TestCase):",
"lookup is not called => logged during submit self.new.sync() self.unresolved.sync()",
"= Settings( { 'issueAnalyzer' : { 'create_issues': False, 'update_issues': False,",
"self.assertFalse(self.issue.new) self.assertTrue(self.issue.tracked) self.assertEqual(self.issue.uri, 'http://issuetracker.example.com/123') def test_str(self): self.assertEqual(str(self.issue), self.issue.uri) # TrackedResolvedIssue",
"TestSubmitCreateAlwaysWithUpdateOn(TestSubmitCreateAlwaysWithUpdateOff): settings = Settings( { 'issueAnalyzer' : { 'create_issues': True,",
"import BaseAnalyzer, BaseIssue from .issueset import IssueSet LOGGER = logging.getLogger('test')",
"self.assertSubmitCreate(self.new) self.assertTrue(self.new.new) self.assertTrue(self.new.tracked) self.assertEqual(result, 'http://issuetracker.example.com/new_issue') self.assertEqual(result, self.new.uri) # repeated submit",
"def assertSubmitNoop(self, issue): with self.assertUnchanged(issue): with self.assertLogs('test', level='INFO') as cm:",
"issue.tracked yield issue self.assertEqual(issue.uri, old_uri) self.assertEqual(issue.new, old_new) self.assertEqual(issue.tracked, old_tracked) def",
"self.settings = Settings({}, {}, []) self.issue = NewIssue(self.settings) def test_properties(self):",
"self.issue = NewIssue(self.settings) def test_properties(self): self.assertTrue(self.issue.new) self.assertFalse(self.issue.tracked) self.assertEqual(self.issue.uri, None) def",
"level='INFO') as cm: self.issue.sync() self.assertEqual(cm.output, ['INFO:test:lookup was called']) self.test_properties() def",
"= self.assertSubmitCreate(self.resolved) self.assertEqual(result, 'http://issuetracker.example.com/new_issue') self.assertEqual(self.resolved.uri, result) self.assertNotEqual(result, old_uri) # The",
"self.new.submit() self.assertEqual(cm.output, [ \"INFO:test:submit was called\", ]) def testUnresolved(self): self.assertSubmitUpdate(self.unresolved)",
"very same test class TestTrackedResolvedIssue(TestTrackedUnresolvedIssue): def setUp(self): self.settings = Settings({},",
"self.assertEqual(issue.new, old_new) self.assertEqual(issue.tracked, old_tracked) def assertSubmitNoop(self, issue): with self.assertUnchanged(issue): with",
"True, 'update_issues': True, 'create_issues_instead_of_update': False, } }, {}, [] )",
"run the very same test class TestTrackedResolvedIssue(TestTrackedUnresolvedIssue): def setUp(self): self.settings",
"self.settings = Settings({}, {}, []) self.issue = TrackedUnresolvedIssue(self.settings) def test_properties(self):",
"} }, {}, [] ) def testUnresolved(self): old_uri = self.unresolved.uri",
"True, 'update_issues': False, # This should have no effect 'create_issues_instead_of_update':",
"old_uri = self.resolved.uri result = self.assertSubmitCreate(self.resolved) self.assertEqual(result, 'http://issuetracker.example.com/new_issue') self.assertEqual(self.resolved.uri, result)",
"[ \"INFO:test:submit was called\", ]) def testUnresolved(self): self.assertSubmitUpdate(self.unresolved) def testResolved(self):",
"TestSubmitUpdateOnlyTracked(TestSubmitCreateUpdate): settings = Settings( { 'issueAnalyzer' : { 'create_issues': False,",
"self.assertEqual(self.issue.uri, 'http://issuetracker.example.com/123') def test_str(self): self.assertEqual(str(self.issue), self.issue.uri) # TrackedResolvedIssue should behave",
"= self.new.submit() self.assertEqual(cm.output, [ \"INFO:test:submit was called\", ]) def testUnresolved(self):",
"level='INFO') as cm: issue.submit() issue.submit() self.assertEqual(cm.output, [ \"INFO:test:submit was called\",",
"issue.submit() self.assertEqual(cm.output, [ \"INFO:test:submit was called\", \"INFO:test:update was called\", \"INFO:test:submit",
"= TrackedUnresolvedIssue(self.settings) def test_properties(self): self.assertFalse(self.issue.new) self.assertTrue(self.issue.tracked) self.assertEqual(self.issue.uri, 'http://issuetracker.example.com/123') def test_str(self):",
".issueset import IssueSet LOGGER = logging.getLogger('test') class NewIssue(BaseIssue): def submit(self):",
"['INFO:test:lookup was called']) self.test_properties() def test_str(self): self.assertEqual(str(self.issue), self.issue.report_url) class TestTrackedUnresolvedIssue(TestNewIssue):",
"self.assertEqual(str(self.issue), self.issue.uri) # TrackedResolvedIssue should behave the same way as",
"True class TestNewIssue(unittest.TestCase): def setUp(self): self.settings = Settings({}, {}, [])",
"self.new.sync() self.unresolved.sync() self.resolved.sync() @contextlib.contextmanager def assertUnchanged(self, issue): old_uri = issue.uri",
"def testNew(self): self.assertSubmitNoop(self.new) def testUnresolved(self): self.assertSubmitNoop(self.unresolved) def testResolved(self): self.assertSubmitNoop(self.resolved) class",
"This should have no effect 'create_issues_instead_of_update': True, } }, {},",
"class TestSubmitCreateUpdate(TestSubmitDisabled): settings = Settings( { 'issueAnalyzer' : { 'create_issues':",
"was called') def _lookup(self): LOGGER.info('lookup was called') return None @property",
"# The update_issue should have no effect when create_issues_instead_of_update #",
"def _lookup(self): LOGGER.info('lookup was called') return 'http://issuetracker.example.com/123' @property def resolved(self):",
"was called') return None @property def resolved(self): return False @property",
"submit self.new.sync() self.unresolved.sync() self.resolved.sync() @contextlib.contextmanager def assertUnchanged(self, issue): old_uri =",
"TestNewIssue(unittest.TestCase): def setUp(self): self.settings = Settings({}, {}, []) self.issue =",
"[] ) def setUp(self): self.new = NewIssue(self.settings) self.unresolved = TrackedUnresolvedIssue(self.settings)",
"super().submit() def make(self): LOGGER.info('make was called') return 'http://issuetracker.example.com/new_issue' def update(self):",
"behave the same way as TrackedUnresolvedIssue # so just inherit",
"update(self): LOGGER.info('update was called') def _lookup(self): LOGGER.info('lookup was called') return",
"= issue.submit() result2 = issue.submit() self.assertEqual(cm.output, [ \"INFO:test:submit was called\",",
"# so just inherit the whole test case to run",
"effect when create_issues_instead_of_update # is set to True. class TestSubmitCreateAlwaysWithUpdateOn(TestSubmitCreateAlwaysWithUpdateOff):",
"repeated submit doesn't do anything with self.assertUnchanged(self.new): with self.assertLogs('test', level='INFO')",
"{ 'create_issues': True, 'update_issues': True, # This should have no",
"import contextlib from libpermian.settings import Settings from .proxy import IssueAnalyzerProxy",
"test_str(self): self.assertEqual(str(self.issue), self.issue.report_url) class TestTrackedUnresolvedIssue(TestNewIssue): def setUp(self): self.settings = Settings({},",
"do anything with self.assertUnchanged(self.new): with self.assertLogs('test', level='INFO') as cm: result",
"'issueAnalyzer' : { 'create_issues': True, 'update_issues': False, 'create_issues_instead_of_update': False, }",
"make(self): LOGGER.info('make was called') return 'http://issuetracker.example.com/new_issue' def update(self): LOGGER.info('update was",
"}, {}, [] ) def testUnresolved(self): self.assertSubmitNoop(self.unresolved) def testResolved(self): self.assertSubmitNoop(self.resolved)",
"TrackedResolvedIssue(TrackedUnresolvedIssue): @property def resolved(self): return True class TestNewIssue(unittest.TestCase): def setUp(self):",
"def test_properties(self): self.assertFalse(self.issue.new) self.assertTrue(self.issue.tracked) self.assertEqual(self.issue.uri, 'http://issuetracker.example.com/123') def test_str(self): self.assertEqual(str(self.issue), self.issue.uri)",
"False, 'create_issues_instead_of_update': False, } }, {}, [] ) def setUp(self):",
"False, 'create_issues_instead_of_update': False, } }, {}, [] ) def testUnresolved(self):",
"have no effect when create_issues_instead_of_update # is set to True.",
"testResolved(self): self.assertSubmitNoop(self.resolved) class TestSubmitCreateUpdate(TestSubmitDisabled): settings = Settings( { 'issueAnalyzer' :",
"False, } }, {}, [] ) def testNew(self): self.assertSubmitNoop(self.new) class",
"{ 'create_issues': False, 'update_issues': False, 'create_issues_instead_of_update': False, } }, {},",
"logging import contextlib from libpermian.settings import Settings from .proxy import",
"issue.submit() self.assertEqual(cm.output, [ \"INFO:test:submit was called\", \"INFO:test:make was called\", \"INFO:test:submit",
"[]) self.issue = TrackedUnresolvedIssue(self.settings) def test_properties(self): self.assertFalse(self.issue.new) self.assertTrue(self.issue.tracked) self.assertEqual(self.issue.uri, 'http://issuetracker.example.com/123')",
"setUp(self): self.settings = Settings({}, {}, []) self.issue = TrackedUnresolvedIssue(self.settings) def",
"was called\", ]) self.assertEqual(result1, result2) return result1 def assertSubmitUpdate(self, issue):",
"testNew(self): self.assertSubmitNoop(self.new) class TestSubmitCreateAlwaysWithUpdateOff(TestSubmitCreateUpdate): settings = Settings( { 'issueAnalyzer' :",
"setUp(self): self.new = NewIssue(self.settings) self.unresolved = TrackedUnresolvedIssue(self.settings) self.resolved = TrackedResolvedIssue(self.settings)",
"def setUp(self): self.settings = Settings({}, {}, []) self.issue = TrackedUnresolvedIssue(self.settings)",
"self.assertTrue(self.issue.new) self.assertFalse(self.issue.tracked) self.assertEqual(self.issue.uri, None) def test_sync(self): # test lookup was",
"self.assertUnchanged(issue): with self.assertLogs('test', level='INFO') as cm: issue.submit() issue.submit() self.assertEqual(cm.output, [",
"False @property def report_url(self): return 'http://issuetracker.example.com/new/bar' class TrackedResolvedIssue(TrackedUnresolvedIssue): @property def",
"@property def report_url(self): return 'http://issuetracker.example.com/new/foo' class TrackedUnresolvedIssue(NewIssue): def _lookup(self): LOGGER.info('lookup",
"{ 'issueAnalyzer' : { 'create_issues': True, 'update_issues': True, # This",
"def test_sync(self): # test lookup was called with self.assertLogs('test', level='INFO')",
"with self.assertUnchanged(self.new): with self.assertLogs('test', level='INFO') as cm: result = self.new.submit()",
"no effect when create_issues_instead_of_update # is set to True. class",
"self.issue.sync() self.assertEqual(cm.output, ['INFO:test:lookup was called']) self.test_properties() def test_str(self): self.assertEqual(str(self.issue), self.issue.report_url)",
"[ \"INFO:test:submit was called\", \"INFO:test:submit was called\", ]) def assertSubmitCreate(self,",
"def testResolved(self): self.assertSubmitNoop(self.resolved) class TestSubmitCreateUpdate(TestSubmitDisabled): settings = Settings( { 'issueAnalyzer'",
"return 'http://issuetracker.example.com/123' @property def resolved(self): return False @property def report_url(self):",
"contextlib from libpermian.settings import Settings from .proxy import IssueAnalyzerProxy from",
"'issueAnalyzer' : { 'create_issues': True, 'update_issues': True, 'create_issues_instead_of_update': False, }",
"self.assertFalse(self.issue.tracked) self.assertEqual(self.issue.uri, None) def test_sync(self): # test lookup was called",
"# is set to True. class TestSubmitCreateAlwaysWithUpdateOn(TestSubmitCreateAlwaysWithUpdateOff): settings = Settings(",
"to True. class TestSubmitCreateAlwaysWithUpdateOn(TestSubmitCreateAlwaysWithUpdateOff): settings = Settings( { 'issueAnalyzer' :",
"self.unresolved.uri result = self.assertSubmitCreate(self.unresolved) self.assertEqual(result, 'http://issuetracker.example.com/new_issue') self.assertEqual(self.unresolved.uri, result) self.assertNotEqual(result, old_uri)",
"class TestSubmitCreateAlwaysWithUpdateOn(TestSubmitCreateAlwaysWithUpdateOff): settings = Settings( { 'issueAnalyzer' : { 'create_issues':",
"'create_issues_instead_of_update': False, } }, {}, [] ) def testNew(self): result",
"None) def test_sync(self): # test lookup was called with self.assertLogs('test',",
"[ \"INFO:test:submit was called\", \"INFO:test:update was called\", \"INFO:test:submit was called\",",
"LOGGER.info('lookup was called') return 'http://issuetracker.example.com/123' @property def resolved(self): return False",
"result2) return result1 def testNew(self): self.assertSubmitNoop(self.new) def testUnresolved(self): self.assertSubmitNoop(self.unresolved) def",
"'http://issuetracker.example.com/123' @property def resolved(self): return False @property def report_url(self): return",
"TrackedResolvedIssue(self.settings) class TestSubmitDisabled(unittest.TestCase): settings = Settings( { 'issueAnalyzer' : {",
"self.assertEqual(cm.output, [ \"INFO:test:submit was called\", \"INFO:test:make was called\", \"INFO:test:submit was",
"TrackedUnresolvedIssue(NewIssue): def _lookup(self): LOGGER.info('lookup was called') return 'http://issuetracker.example.com/123' @property def",
"{ 'create_issues': True, 'update_issues': True, 'create_issues_instead_of_update': False, } }, {},",
"TrackedUnresolvedIssue(self.settings) self.resolved = TrackedResolvedIssue(self.settings) # sync the issues so that",
"issue.submit() issue.submit() self.assertEqual(cm.output, [ \"INFO:test:submit was called\", \"INFO:test:submit was called\",",
"self.assertSubmitNoop(self.unresolved) def testResolved(self): self.assertSubmitNoop(self.resolved) class TestSubmitCreateUpdate(TestSubmitDisabled): settings = Settings( {",
"old_uri) def testResolved(self): old_uri = self.resolved.uri result = self.assertSubmitCreate(self.resolved) self.assertEqual(result,",
"{}, []) self.issue = TrackedUnresolvedIssue(self.settings) def test_properties(self): self.assertFalse(self.issue.new) self.assertTrue(self.issue.tracked) self.assertEqual(self.issue.uri,",
"setUp(self): self.settings = Settings({}, {}, []) self.issue = NewIssue(self.settings) def",
"is set to True. class TestSubmitCreateAlwaysWithUpdateOn(TestSubmitCreateAlwaysWithUpdateOff): settings = Settings( {",
"self.assertEqual(cm.output, ['INFO:test:lookup was called']) self.test_properties() def test_str(self): self.assertEqual(str(self.issue), self.issue.report_url) class",
"'create_issues_instead_of_update': False, } }, {}, [] ) def testUnresolved(self): self.assertSubmitNoop(self.unresolved)",
"True, # This should have no effect 'create_issues_instead_of_update': True, }",
"False, 'update_issues': False, 'create_issues_instead_of_update': False, } }, {}, [] )",
"was called') return super().submit() def make(self): LOGGER.info('make was called') return",
"{}, []) self.issue = TrackedResolvedIssue(self.settings) class TestSubmitDisabled(unittest.TestCase): settings = Settings(",
"self.assertEqual(result1, result2) return result1 def assertSubmitUpdate(self, issue): with self.assertUnchanged(issue): with",
"self.assertEqual(cm.output, [ \"INFO:test:submit was called\", ]) def testUnresolved(self): self.assertSubmitUpdate(self.unresolved) def",
"# repeated submit doesn't do anything with self.assertUnchanged(self.new): with self.assertLogs('test',",
"self.assertEqual(self.unresolved.uri, result) self.assertNotEqual(result, old_uri) def testResolved(self): old_uri = self.resolved.uri result",
"testUnresolved(self): self.assertSubmitNoop(self.unresolved) def testResolved(self): self.assertSubmitNoop(self.resolved) class TestSubmitCreateUpdate(TestSubmitDisabled): settings = Settings(",
"old_uri = self.unresolved.uri result = self.assertSubmitCreate(self.unresolved) self.assertEqual(result, 'http://issuetracker.example.com/new_issue') self.assertEqual(self.unresolved.uri, result)",
"anything with self.assertUnchanged(self.new): with self.assertLogs('test', level='INFO') as cm: result =",
"issue.submit() self.assertEqual(cm.output, [ \"INFO:test:submit was called\", \"INFO:test:submit was called\", ])",
"self.assertEqual(str(self.issue), self.issue.report_url) class TestTrackedUnresolvedIssue(TestNewIssue): def setUp(self): self.settings = Settings({}, {},",
"from .proxy import IssueAnalyzerProxy from .base import BaseAnalyzer, BaseIssue from",
"LOGGER.info('update was called') def _lookup(self): LOGGER.info('lookup was called') return None",
"self.issue = TrackedUnresolvedIssue(self.settings) def test_properties(self): self.assertFalse(self.issue.new) self.assertTrue(self.issue.tracked) self.assertEqual(self.issue.uri, 'http://issuetracker.example.com/123') def",
"return result1 def testNew(self): self.assertSubmitNoop(self.new) def testUnresolved(self): self.assertSubmitNoop(self.unresolved) def testResolved(self):",
"= NewIssue(self.settings) def test_properties(self): self.assertTrue(self.issue.new) self.assertFalse(self.issue.tracked) self.assertEqual(self.issue.uri, None) def test_sync(self):",
"was called\", ]) def assertSubmitCreate(self, issue): with self.assertLogs('test', level='INFO') as",
"= TrackedResolvedIssue(self.settings) class TestSubmitDisabled(unittest.TestCase): settings = Settings( { 'issueAnalyzer' :",
"IssueSet LOGGER = logging.getLogger('test') class NewIssue(BaseIssue): def submit(self): LOGGER.info('submit was",
"result) self.assertNotEqual(result, old_uri) # The update_issue should have no effect",
"False, 'update_issues': True, 'create_issues_instead_of_update': False, } }, {}, [] )",
"called\", ]) self.assertEqual(result1, result2) return result1 def testNew(self): self.assertSubmitNoop(self.new) def",
"LOGGER.info('submit was called') return super().submit() def make(self): LOGGER.info('make was called')",
"class TestTrackedUnresolvedIssue(TestNewIssue): def setUp(self): self.settings = Settings({}, {}, []) self.issue",
"BaseIssue from .issueset import IssueSet LOGGER = logging.getLogger('test') class NewIssue(BaseIssue):",
"def testResolved(self): self.assertSubmitUpdate(self.resolved) class TestSubmitCreateOnlyNew(TestSubmitCreateUpdate): settings = Settings( { 'issueAnalyzer'",
"testResolved(self): self.assertSubmitUpdate(self.resolved) class TestSubmitCreateOnlyNew(TestSubmitCreateUpdate): settings = Settings( { 'issueAnalyzer' :",
"Settings( { 'issueAnalyzer' : { 'create_issues': True, 'update_issues': True, 'create_issues_instead_of_update':",
"called') return None @property def resolved(self): return False @property def",
"is not called => logged during submit self.new.sync() self.unresolved.sync() self.resolved.sync()",
"that lookup is not called => logged during submit self.new.sync()",
"self.resolved.sync() @contextlib.contextmanager def assertUnchanged(self, issue): old_uri = issue.uri old_new =",
"self.assertSubmitNoop(self.new) class TestSubmitCreateAlwaysWithUpdateOff(TestSubmitCreateUpdate): settings = Settings( { 'issueAnalyzer' : {",
"= TrackedResolvedIssue(self.settings) # sync the issues so that lookup is",
"Settings({}, {}, []) self.issue = NewIssue(self.settings) def test_properties(self): self.assertTrue(self.issue.new) self.assertFalse(self.issue.tracked)",
"was called\", \"INFO:test:submit was called\", ]) self.assertEqual(result1, result2) return result1",
"self.assertEqual(result, 'http://issuetracker.example.com/new_issue') self.assertEqual(self.resolved.uri, result) self.assertNotEqual(result, old_uri) # The update_issue should",
"called\", \"INFO:test:submit was called\", ]) def assertSubmitCreate(self, issue): with self.assertLogs('test',",
"'update_issues': False, # This should have no effect 'create_issues_instead_of_update': True,",
"testUnresolved(self): self.assertSubmitUpdate(self.unresolved) def testResolved(self): self.assertSubmitUpdate(self.resolved) class TestSubmitCreateOnlyNew(TestSubmitCreateUpdate): settings = Settings(",
"[ \"INFO:test:submit was called\", \"INFO:test:make was called\", \"INFO:test:submit was called\",",
"@property def resolved(self): return False @property def report_url(self): return 'http://issuetracker.example.com/new/foo'",
"= issue.submit() self.assertEqual(cm.output, [ \"INFO:test:submit was called\", \"INFO:test:make was called\",",
"} }, {}, [] ) def testNew(self): self.assertSubmitNoop(self.new) class TestSubmitCreateAlwaysWithUpdateOff(TestSubmitCreateUpdate):",
"result2) return result1 def assertSubmitUpdate(self, issue): with self.assertUnchanged(issue): with self.assertLogs('test',",
"testUnresolved(self): old_uri = self.unresolved.uri result = self.assertSubmitCreate(self.unresolved) self.assertEqual(result, 'http://issuetracker.example.com/new_issue') self.assertEqual(self.unresolved.uri,",
"def setUp(self): self.settings = Settings({}, {}, []) self.issue = NewIssue(self.settings)",
"= logging.getLogger('test') class NewIssue(BaseIssue): def submit(self): LOGGER.info('submit was called') return",
"inherit the whole test case to run the very same",
"def assertSubmitCreate(self, issue): with self.assertLogs('test', level='INFO') as cm: result1 =",
"the very same test class TestTrackedResolvedIssue(TestTrackedUnresolvedIssue): def setUp(self): self.settings =",
".base import BaseAnalyzer, BaseIssue from .issueset import IssueSet LOGGER =",
"\"INFO:test:submit was called\", ]) def assertSubmitCreate(self, issue): with self.assertLogs('test', level='INFO')",
"so just inherit the whole test case to run the",
"{}, [] ) def testNew(self): result = self.assertSubmitCreate(self.new) self.assertTrue(self.new.new) self.assertTrue(self.new.tracked)",
"{}, []) self.issue = NewIssue(self.settings) def test_properties(self): self.assertTrue(self.issue.new) self.assertFalse(self.issue.tracked) self.assertEqual(self.issue.uri,",
"{ 'issueAnalyzer' : { 'create_issues': False, 'update_issues': True, 'create_issues_instead_of_update': False,",
"self.assertUnchanged(self.new): with self.assertLogs('test', level='INFO') as cm: result = self.new.submit() self.assertEqual(cm.output,",
"was called\", \"INFO:test:submit was called\", ]) def assertSubmitCreate(self, issue): with",
"unittest import logging import contextlib from libpermian.settings import Settings from",
"self.issue = TrackedResolvedIssue(self.settings) class TestSubmitDisabled(unittest.TestCase): settings = Settings( { 'issueAnalyzer'",
"class TrackedResolvedIssue(TrackedUnresolvedIssue): @property def resolved(self): return True class TestNewIssue(unittest.TestCase): def",
"= self.assertSubmitCreate(self.unresolved) self.assertEqual(result, 'http://issuetracker.example.com/new_issue') self.assertEqual(self.unresolved.uri, result) self.assertNotEqual(result, old_uri) def testResolved(self):",
"self.assertTrue(self.new.tracked) self.assertEqual(result, 'http://issuetracker.example.com/new_issue') self.assertEqual(result, self.new.uri) # repeated submit doesn't do",
"True, 'create_issues_instead_of_update': False, } }, {}, [] ) def testNew(self):",
"the whole test case to run the very same test",
"'http://issuetracker.example.com/new/foo' class TrackedUnresolvedIssue(NewIssue): def _lookup(self): LOGGER.info('lookup was called') return 'http://issuetracker.example.com/123'",
"TestSubmitCreateAlwaysWithUpdateOff(TestSubmitCreateUpdate): settings = Settings( { 'issueAnalyzer' : { 'create_issues': True,",
"NewIssue(self.settings) self.unresolved = TrackedUnresolvedIssue(self.settings) self.resolved = TrackedResolvedIssue(self.settings) # sync the",
"self.assertEqual(issue.tracked, old_tracked) def assertSubmitNoop(self, issue): with self.assertUnchanged(issue): with self.assertLogs('test', level='INFO')",
"} }, {}, [] ) def setUp(self): self.new = NewIssue(self.settings)",
"}, {}, [] ) def testNew(self): result = self.assertSubmitCreate(self.new) self.assertTrue(self.new.new)",
"False @property def report_url(self): return 'http://issuetracker.example.com/new/foo' class TrackedUnresolvedIssue(NewIssue): def _lookup(self):",
"@property def report_url(self): return 'http://issuetracker.example.com/new/bar' class TrackedResolvedIssue(TrackedUnresolvedIssue): @property def resolved(self):",
"self.assertSubmitNoop(self.unresolved) def testResolved(self): self.assertSubmitNoop(self.resolved) class TestSubmitUpdateOnlyTracked(TestSubmitCreateUpdate): settings = Settings( {",
"not called => logged during submit self.new.sync() self.unresolved.sync() self.resolved.sync() @contextlib.contextmanager",
"'issueAnalyzer' : { 'create_issues': True, 'update_issues': True, # This should",
"assertSubmitCreate(self, issue): with self.assertLogs('test', level='INFO') as cm: result1 = issue.submit()",
"to run the very same test class TestTrackedResolvedIssue(TestTrackedUnresolvedIssue): def setUp(self):",
"'http://issuetracker.example.com/new_issue' def update(self): LOGGER.info('update was called') def _lookup(self): LOGGER.info('lookup was",
"= self.unresolved.uri result = self.assertSubmitCreate(self.unresolved) self.assertEqual(result, 'http://issuetracker.example.com/new_issue') self.assertEqual(self.unresolved.uri, result) self.assertNotEqual(result,",
"called\", ]) def testUnresolved(self): self.assertSubmitUpdate(self.unresolved) def testResolved(self): self.assertSubmitUpdate(self.resolved) class TestSubmitCreateOnlyNew(TestSubmitCreateUpdate):",
"\"INFO:test:submit was called\", ]) self.assertEqual(result1, result2) return result1 def assertSubmitUpdate(self,",
"same way as TrackedUnresolvedIssue # so just inherit the whole",
"test_sync(self): # test lookup was called with self.assertLogs('test', level='INFO') as",
"self.assertEqual(result, 'http://issuetracker.example.com/new_issue') self.assertEqual(self.unresolved.uri, result) self.assertNotEqual(result, old_uri) def testResolved(self): old_uri =",
"TrackedResolvedIssue should behave the same way as TrackedUnresolvedIssue # so",
"level='INFO') as cm: result = self.new.submit() self.assertEqual(cm.output, [ \"INFO:test:submit was",
"LOGGER = logging.getLogger('test') class NewIssue(BaseIssue): def submit(self): LOGGER.info('submit was called')",
"'http://issuetracker.example.com/new_issue') self.assertEqual(result, self.new.uri) # repeated submit doesn't do anything with",
"old_uri) self.assertEqual(issue.new, old_new) self.assertEqual(issue.tracked, old_tracked) def assertSubmitNoop(self, issue): with self.assertUnchanged(issue):",
"\"INFO:test:submit was called\", \"INFO:test:make was called\", \"INFO:test:submit was called\", ])",
"[]) self.issue = NewIssue(self.settings) def test_properties(self): self.assertTrue(self.issue.new) self.assertFalse(self.issue.tracked) self.assertEqual(self.issue.uri, None)",
") def setUp(self): self.new = NewIssue(self.settings) self.unresolved = TrackedUnresolvedIssue(self.settings) self.resolved",
"self.assertTrue(self.new.new) self.assertTrue(self.new.tracked) self.assertEqual(result, 'http://issuetracker.example.com/new_issue') self.assertEqual(result, self.new.uri) # repeated submit doesn't",
"self.assertLogs('test', level='INFO') as cm: self.issue.sync() self.assertEqual(cm.output, ['INFO:test:lookup was called']) self.test_properties()",
"sync the issues so that lookup is not called =>",
"issue): with self.assertUnchanged(issue): with self.assertLogs('test', level='INFO') as cm: issue.submit() issue.submit()",
"setUp(self): self.settings = Settings({}, {}, []) self.issue = TrackedResolvedIssue(self.settings) class",
"class TestTrackedResolvedIssue(TestTrackedUnresolvedIssue): def setUp(self): self.settings = Settings({}, {}, []) self.issue",
"Settings( { 'issueAnalyzer' : { 'create_issues': False, 'update_issues': False, 'create_issues_instead_of_update':",
"= issue.uri old_new = issue.new old_tracked = issue.tracked yield issue",
"resolved(self): return False @property def report_url(self): return 'http://issuetracker.example.com/new/foo' class TrackedUnresolvedIssue(NewIssue):",
"as cm: result1 = issue.submit() result2 = issue.submit() self.assertEqual(cm.output, [",
"libpermian.settings import Settings from .proxy import IssueAnalyzerProxy from .base import",
"def make(self): LOGGER.info('make was called') return 'http://issuetracker.example.com/new_issue' def update(self): LOGGER.info('update",
": { 'create_issues': False, 'update_issues': False, 'create_issues_instead_of_update': False, } },",
"= issue.tracked yield issue self.assertEqual(issue.uri, old_uri) self.assertEqual(issue.new, old_new) self.assertEqual(issue.tracked, old_tracked)",
"}, {}, [] ) def testUnresolved(self): old_uri = self.unresolved.uri result",
"assertSubmitNoop(self, issue): with self.assertUnchanged(issue): with self.assertLogs('test', level='INFO') as cm: issue.submit()",
"= self.resolved.uri result = self.assertSubmitCreate(self.resolved) self.assertEqual(result, 'http://issuetracker.example.com/new_issue') self.assertEqual(self.resolved.uri, result) self.assertNotEqual(result,",
"old_tracked) def assertSubmitNoop(self, issue): with self.assertUnchanged(issue): with self.assertLogs('test', level='INFO') as",
"self.assertNotEqual(result, old_uri) def testResolved(self): old_uri = self.resolved.uri result = self.assertSubmitCreate(self.resolved)",
"should have no effect when create_issues_instead_of_update # is set to",
"False, } }, {}, [] ) def testNew(self): result =",
"cm: issue.submit() issue.submit() self.assertEqual(cm.output, [ \"INFO:test:submit was called\", \"INFO:test:submit was",
"\"INFO:test:submit was called\", ]) self.assertEqual(result1, result2) return result1 def testNew(self):",
"Settings( { 'issueAnalyzer' : { 'create_issues': True, 'update_issues': True, #",
"so that lookup is not called => logged during submit",
": { 'create_issues': True, 'update_issues': True, 'create_issues_instead_of_update': False, } },",
"test_properties(self): self.assertFalse(self.issue.new) self.assertTrue(self.issue.tracked) self.assertEqual(self.issue.uri, 'http://issuetracker.example.com/123') def test_str(self): self.assertEqual(str(self.issue), self.issue.uri) #",
"= Settings({}, {}, []) self.issue = NewIssue(self.settings) def test_properties(self): self.assertTrue(self.issue.new)",
"\"INFO:test:submit was called\", ]) def testUnresolved(self): self.assertSubmitUpdate(self.unresolved) def testResolved(self): self.assertSubmitUpdate(self.resolved)",
"{ 'issueAnalyzer' : { 'create_issues': False, 'update_issues': False, 'create_issues_instead_of_update': False,",
"testUnresolved(self): self.assertSubmitNoop(self.unresolved) def testResolved(self): self.assertSubmitNoop(self.resolved) class TestSubmitUpdateOnlyTracked(TestSubmitCreateUpdate): settings = Settings(",
"[]) self.issue = TrackedResolvedIssue(self.settings) class TestSubmitDisabled(unittest.TestCase): settings = Settings( {",
"return 'http://issuetracker.example.com/new/bar' class TrackedResolvedIssue(TrackedUnresolvedIssue): @property def resolved(self): return True class",
"with self.assertLogs('test', level='INFO') as cm: result = self.new.submit() self.assertEqual(cm.output, [",
"def update(self): LOGGER.info('update was called') def _lookup(self): LOGGER.info('lookup was called')",
"with self.assertLogs('test', level='INFO') as cm: result1 = issue.submit() result2 =",
"test case to run the very same test class TestTrackedResolvedIssue(TestTrackedUnresolvedIssue):",
"The update_issue should have no effect when create_issues_instead_of_update # is",
"{}, [] ) def setUp(self): self.new = NewIssue(self.settings) self.unresolved =",
"LOGGER.info('lookup was called') return None @property def resolved(self): return False",
"issue): with self.assertLogs('test', level='INFO') as cm: result1 = issue.submit() result2",
"with self.assertUnchanged(issue): with self.assertLogs('test', level='INFO') as cm: result1 = issue.submit()",
"was called\", ]) self.assertEqual(result1, result2) return result1 def testNew(self): self.assertSubmitNoop(self.new)",
"self.assertSubmitCreate(self.unresolved) self.assertEqual(result, 'http://issuetracker.example.com/new_issue') self.assertEqual(self.unresolved.uri, result) self.assertNotEqual(result, old_uri) def testResolved(self): old_uri",
"{ 'issueAnalyzer' : { 'create_issues': True, 'update_issues': False, 'create_issues_instead_of_update': False,",
"was called\", \"INFO:test:update was called\", \"INFO:test:submit was called\", ]) self.assertEqual(result1,",
"def testUnresolved(self): self.assertSubmitNoop(self.unresolved) def testResolved(self): self.assertSubmitNoop(self.resolved) class TestSubmitUpdateOnlyTracked(TestSubmitCreateUpdate): settings =",
"set to True. class TestSubmitCreateAlwaysWithUpdateOn(TestSubmitCreateAlwaysWithUpdateOff): settings = Settings( { 'issueAnalyzer'",
"called\", ]) def assertSubmitCreate(self, issue): with self.assertLogs('test', level='INFO') as cm:",
"'issueAnalyzer' : { 'create_issues': False, 'update_issues': True, 'create_issues_instead_of_update': False, }",
"TestSubmitCreateOnlyNew(TestSubmitCreateUpdate): settings = Settings( { 'issueAnalyzer' : { 'create_issues': True,",
"self.assertLogs('test', level='INFO') as cm: result1 = issue.submit() result2 = issue.submit()",
"called') return 'http://issuetracker.example.com/123' @property def resolved(self): return False @property def",
"= Settings({}, {}, []) self.issue = TrackedResolvedIssue(self.settings) class TestSubmitDisabled(unittest.TestCase): settings",
"[] ) def testUnresolved(self): self.assertSubmitNoop(self.unresolved) def testResolved(self): self.assertSubmitNoop(self.resolved) class TestSubmitUpdateOnlyTracked(TestSubmitCreateUpdate):",
"= issue.submit() self.assertEqual(cm.output, [ \"INFO:test:submit was called\", \"INFO:test:update was called\",",
"class TestNewIssue(unittest.TestCase): def setUp(self): self.settings = Settings({}, {}, []) self.issue",
"]) self.assertEqual(result1, result2) return result1 def assertSubmitUpdate(self, issue): with self.assertUnchanged(issue):",
"def testUnresolved(self): old_uri = self.unresolved.uri result = self.assertSubmitCreate(self.unresolved) self.assertEqual(result, 'http://issuetracker.example.com/new_issue')",
"result) self.assertNotEqual(result, old_uri) def testResolved(self): old_uri = self.resolved.uri result =",
"import logging import contextlib from libpermian.settings import Settings from .proxy",
"logging.getLogger('test') class NewIssue(BaseIssue): def submit(self): LOGGER.info('submit was called') return super().submit()",
"self.new = NewIssue(self.settings) self.unresolved = TrackedUnresolvedIssue(self.settings) self.resolved = TrackedResolvedIssue(self.settings) #",
"was called\", ]) def testUnresolved(self): self.assertSubmitUpdate(self.unresolved) def testResolved(self): self.assertSubmitUpdate(self.resolved) class",
"IssueAnalyzerProxy from .base import BaseAnalyzer, BaseIssue from .issueset import IssueSet",
"return 'http://issuetracker.example.com/new/foo' class TrackedUnresolvedIssue(NewIssue): def _lookup(self): LOGGER.info('lookup was called') return",
"as cm: issue.submit() issue.submit() self.assertEqual(cm.output, [ \"INFO:test:submit was called\", \"INFO:test:submit",
"from libpermian.settings import Settings from .proxy import IssueAnalyzerProxy from .base",
"'update_issues': True, 'create_issues_instead_of_update': False, } }, {}, [] ) def",
"self.issue.report_url) class TestTrackedUnresolvedIssue(TestNewIssue): def setUp(self): self.settings = Settings({}, {}, [])",
"TestTrackedResolvedIssue(TestTrackedUnresolvedIssue): def setUp(self): self.settings = Settings({}, {}, []) self.issue =",
"]) def assertSubmitCreate(self, issue): with self.assertLogs('test', level='INFO') as cm: result1",
"'create_issues': False, 'update_issues': True, 'create_issues_instead_of_update': False, } }, {}, []",
"class TestSubmitCreateAlwaysWithUpdateOff(TestSubmitCreateUpdate): settings = Settings( { 'issueAnalyzer' : { 'create_issues':",
"Settings from .proxy import IssueAnalyzerProxy from .base import BaseAnalyzer, BaseIssue",
"Settings( { 'issueAnalyzer' : { 'create_issues': True, 'update_issues': False, 'create_issues_instead_of_update':",
"None @property def resolved(self): return False @property def report_url(self): return",
"NewIssue(self.settings) def test_properties(self): self.assertTrue(self.issue.new) self.assertFalse(self.issue.tracked) self.assertEqual(self.issue.uri, None) def test_sync(self): #",
"@contextlib.contextmanager def assertUnchanged(self, issue): old_uri = issue.uri old_new = issue.new",
"def testResolved(self): old_uri = self.resolved.uri result = self.assertSubmitCreate(self.resolved) self.assertEqual(result, 'http://issuetracker.example.com/new_issue')",
"def testNew(self): self.assertSubmitNoop(self.new) class TestSubmitCreateAlwaysWithUpdateOff(TestSubmitCreateUpdate): settings = Settings( { 'issueAnalyzer'",
"during submit self.new.sync() self.unresolved.sync() self.resolved.sync() @contextlib.contextmanager def assertUnchanged(self, issue): old_uri",
"same test class TestTrackedResolvedIssue(TestTrackedUnresolvedIssue): def setUp(self): self.settings = Settings({}, {},",
"def resolved(self): return False @property def report_url(self): return 'http://issuetracker.example.com/new/foo' class",
"issue): old_uri = issue.uri old_new = issue.new old_tracked = issue.tracked",
"when create_issues_instead_of_update # is set to True. class TestSubmitCreateAlwaysWithUpdateOn(TestSubmitCreateAlwaysWithUpdateOff): settings",
"self.assertSubmitUpdate(self.unresolved) def testResolved(self): self.assertSubmitUpdate(self.resolved) class TestSubmitCreateOnlyNew(TestSubmitCreateUpdate): settings = Settings( {",
"Settings( { 'issueAnalyzer' : { 'create_issues': True, 'update_issues': False, #",
"assertSubmitUpdate(self, issue): with self.assertUnchanged(issue): with self.assertLogs('test', level='INFO') as cm: result1",
"True, 'update_issues': True, # This should have no effect 'create_issues_instead_of_update':",
"result1 = issue.submit() result2 = issue.submit() self.assertEqual(cm.output, [ \"INFO:test:submit was",
") def testNew(self): self.assertSubmitNoop(self.new) class TestSubmitCreateAlwaysWithUpdateOff(TestSubmitCreateUpdate): settings = Settings( {",
"from .base import BaseAnalyzer, BaseIssue from .issueset import IssueSet LOGGER",
"'create_issues_instead_of_update': False, } }, {}, [] ) def testNew(self): self.assertSubmitNoop(self.new)",
"self.unresolved = TrackedUnresolvedIssue(self.settings) self.resolved = TrackedResolvedIssue(self.settings) # sync the issues",
"testNew(self): result = self.assertSubmitCreate(self.new) self.assertTrue(self.new.new) self.assertTrue(self.new.tracked) self.assertEqual(result, 'http://issuetracker.example.com/new_issue') self.assertEqual(result, self.new.uri)",
"report_url(self): return 'http://issuetracker.example.com/new/bar' class TrackedResolvedIssue(TrackedUnresolvedIssue): @property def resolved(self): return True",
"{ 'issueAnalyzer' : { 'create_issues': True, 'update_issues': False, # This",
"= Settings({}, {}, []) self.issue = TrackedUnresolvedIssue(self.settings) def test_properties(self): self.assertFalse(self.issue.new)",
"result = self.assertSubmitCreate(self.unresolved) self.assertEqual(result, 'http://issuetracker.example.com/new_issue') self.assertEqual(self.unresolved.uri, result) self.assertNotEqual(result, old_uri) def",
"self.assertSubmitNoop(self.new) def testUnresolved(self): self.assertSubmitNoop(self.unresolved) def testResolved(self): self.assertSubmitNoop(self.resolved) class TestSubmitCreateUpdate(TestSubmitDisabled): settings",
"def testNew(self): result = self.assertSubmitCreate(self.new) self.assertTrue(self.new.new) self.assertTrue(self.new.tracked) self.assertEqual(result, 'http://issuetracker.example.com/new_issue') self.assertEqual(result,",
"\"INFO:test:make was called\", \"INFO:test:submit was called\", ]) self.assertEqual(result1, result2) return",
"def report_url(self): return 'http://issuetracker.example.com/new/bar' class TrackedResolvedIssue(TrackedUnresolvedIssue): @property def resolved(self): return",
"was called\", \"INFO:test:make was called\", \"INFO:test:submit was called\", ]) self.assertEqual(result1,",
"with self.assertLogs('test', level='INFO') as cm: issue.submit() issue.submit() self.assertEqual(cm.output, [ \"INFO:test:submit",
"result = self.assertSubmitCreate(self.resolved) self.assertEqual(result, 'http://issuetracker.example.com/new_issue') self.assertEqual(self.resolved.uri, result) self.assertNotEqual(result, old_uri) #",
"_lookup(self): LOGGER.info('lookup was called') return 'http://issuetracker.example.com/123' @property def resolved(self): return",
"TrackedUnresolvedIssue # so just inherit the whole test case to",
"self.assertSubmitNoop(self.resolved) class TestSubmitUpdateOnlyTracked(TestSubmitCreateUpdate): settings = Settings( { 'issueAnalyzer' : {",
"with self.assertLogs('test', level='INFO') as cm: self.issue.sync() self.assertEqual(cm.output, ['INFO:test:lookup was called'])",
"called\", \"INFO:test:submit was called\", ]) self.assertEqual(result1, result2) return result1 def",
"} }, {}, [] ) def testUnresolved(self): self.assertSubmitNoop(self.unresolved) def testResolved(self):",
"result1 def testNew(self): self.assertSubmitNoop(self.new) def testUnresolved(self): self.assertSubmitNoop(self.unresolved) def testResolved(self): self.assertSubmitNoop(self.resolved)",
"self.assertEqual(issue.uri, old_uri) self.assertEqual(issue.new, old_new) self.assertEqual(issue.tracked, old_tracked) def assertSubmitNoop(self, issue): with",
"\"INFO:test:submit was called\", \"INFO:test:submit was called\", ]) def assertSubmitCreate(self, issue):",
"'issueAnalyzer' : { 'create_issues': True, 'update_issues': False, # This should",
"self.resolved.uri result = self.assertSubmitCreate(self.resolved) self.assertEqual(result, 'http://issuetracker.example.com/new_issue') self.assertEqual(self.resolved.uri, result) self.assertNotEqual(result, old_uri)",
"testResolved(self): old_uri = self.resolved.uri result = self.assertSubmitCreate(self.resolved) self.assertEqual(result, 'http://issuetracker.example.com/new_issue') self.assertEqual(self.resolved.uri,",
"def test_str(self): self.assertEqual(str(self.issue), self.issue.uri) # TrackedResolvedIssue should behave the same",
"logged during submit self.new.sync() self.unresolved.sync() self.resolved.sync() @contextlib.contextmanager def assertUnchanged(self, issue):",
"NewIssue(BaseIssue): def submit(self): LOGGER.info('submit was called') return super().submit() def make(self):",
"def testResolved(self): self.assertSubmitNoop(self.resolved) class TestSubmitUpdateOnlyTracked(TestSubmitCreateUpdate): settings = Settings( { 'issueAnalyzer'",
"Settings({}, {}, []) self.issue = TrackedResolvedIssue(self.settings) class TestSubmitDisabled(unittest.TestCase): settings =",
"def assertSubmitUpdate(self, issue): with self.assertUnchanged(issue): with self.assertLogs('test', level='INFO') as cm:",
"the issues so that lookup is not called => logged",
"should behave the same way as TrackedUnresolvedIssue # so just",
"called\", \"INFO:test:make was called\", \"INFO:test:submit was called\", ]) self.assertEqual(result1, result2)",
"class TrackedUnresolvedIssue(NewIssue): def _lookup(self): LOGGER.info('lookup was called') return 'http://issuetracker.example.com/123' @property",
"import unittest import logging import contextlib from libpermian.settings import Settings",
"self.assertSubmitCreate(self.resolved) self.assertEqual(result, 'http://issuetracker.example.com/new_issue') self.assertEqual(self.resolved.uri, result) self.assertNotEqual(result, old_uri) # The update_issue",
"= NewIssue(self.settings) self.unresolved = TrackedUnresolvedIssue(self.settings) self.resolved = TrackedResolvedIssue(self.settings) # sync",
"called => logged during submit self.new.sync() self.unresolved.sync() self.resolved.sync() @contextlib.contextmanager def",
"create_issues_instead_of_update # is set to True. class TestSubmitCreateAlwaysWithUpdateOn(TestSubmitCreateAlwaysWithUpdateOff): settings =",
"cm: self.issue.sync() self.assertEqual(cm.output, ['INFO:test:lookup was called']) self.test_properties() def test_str(self): self.assertEqual(str(self.issue),",
"def testUnresolved(self): self.assertSubmitNoop(self.unresolved) def testResolved(self): self.assertSubmitNoop(self.resolved) class TestSubmitCreateUpdate(TestSubmitDisabled): settings =",
"effect 'create_issues_instead_of_update': True, } }, {}, [] ) def testUnresolved(self):",
"= Settings( { 'issueAnalyzer' : { 'create_issues': True, 'update_issues': False,",
".proxy import IssueAnalyzerProxy from .base import BaseAnalyzer, BaseIssue from .issueset",
"TestSubmitDisabled(unittest.TestCase): settings = Settings( { 'issueAnalyzer' : { 'create_issues': False,",
"self.assertEqual(result, self.new.uri) # repeated submit doesn't do anything with self.assertUnchanged(self.new):",
"issues so that lookup is not called => logged during",
"{ 'create_issues': True, 'update_issues': False, 'create_issues_instead_of_update': False, } }, {},",
"testResolved(self): self.assertSubmitNoop(self.resolved) class TestSubmitUpdateOnlyTracked(TestSubmitCreateUpdate): settings = Settings( { 'issueAnalyzer' :",
"self.resolved = TrackedResolvedIssue(self.settings) # sync the issues so that lookup",
"= issue.new old_tracked = issue.tracked yield issue self.assertEqual(issue.uri, old_uri) self.assertEqual(issue.new,",
"=> logged during submit self.new.sync() self.unresolved.sync() self.resolved.sync() @contextlib.contextmanager def assertUnchanged(self,",
"def resolved(self): return False @property def report_url(self): return 'http://issuetracker.example.com/new/bar' class",
"test_properties(self): self.assertTrue(self.issue.new) self.assertFalse(self.issue.tracked) self.assertEqual(self.issue.uri, None) def test_sync(self): # test lookup",
"# test lookup was called with self.assertLogs('test', level='INFO') as cm:",
"}, {}, [] ) def testNew(self): self.assertSubmitNoop(self.new) class TestSubmitCreateAlwaysWithUpdateOff(TestSubmitCreateUpdate): settings",
": { 'create_issues': True, 'update_issues': True, # This should have",
"_lookup(self): LOGGER.info('lookup was called') return None @property def resolved(self): return",
"[] ) def testNew(self): result = self.assertSubmitCreate(self.new) self.assertTrue(self.new.new) self.assertTrue(self.new.tracked) self.assertEqual(result,",
"from .issueset import IssueSet LOGGER = logging.getLogger('test') class NewIssue(BaseIssue): def",
"True, } }, {}, [] ) def testUnresolved(self): old_uri =",
"test class TestTrackedResolvedIssue(TestTrackedUnresolvedIssue): def setUp(self): self.settings = Settings({}, {}, [])",
"assertUnchanged(self, issue): old_uri = issue.uri old_new = issue.new old_tracked =",
"result2 = issue.submit() self.assertEqual(cm.output, [ \"INFO:test:submit was called\", \"INFO:test:update was",
"'create_issues': True, 'update_issues': True, # This should have no effect",
"'create_issues_instead_of_update': True, } }, {}, [] ) def testUnresolved(self): old_uri",
"{}, [] ) def testUnresolved(self): old_uri = self.unresolved.uri result =",
"{ 'create_issues': True, 'update_issues': False, # This should have no",
"self.assertEqual(result, 'http://issuetracker.example.com/new_issue') self.assertEqual(result, self.new.uri) # repeated submit doesn't do anything",
"Settings( { 'issueAnalyzer' : { 'create_issues': False, 'update_issues': True, 'create_issues_instead_of_update':",
"result1 def assertSubmitUpdate(self, issue): with self.assertUnchanged(issue): with self.assertLogs('test', level='INFO') as",
"'create_issues_instead_of_update': False, } }, {}, [] ) def setUp(self): self.new",
"self.assertEqual(cm.output, [ \"INFO:test:submit was called\", \"INFO:test:submit was called\", ]) def",
"way as TrackedUnresolvedIssue # so just inherit the whole test",
"False, # This should have no effect 'create_issues_instead_of_update': True, }",
"def test_str(self): self.assertEqual(str(self.issue), self.issue.report_url) class TestTrackedUnresolvedIssue(TestNewIssue): def setUp(self): self.settings =",
"was called') return 'http://issuetracker.example.com/123' @property def resolved(self): return False @property",
"# This should have no effect 'create_issues_instead_of_update': True, } },",
"issue): with self.assertUnchanged(issue): with self.assertLogs('test', level='INFO') as cm: result1 =",
": { 'create_issues': True, 'update_issues': False, # This should have",
"self.assertSubmitNoop(self.resolved) class TestSubmitCreateUpdate(TestSubmitDisabled): settings = Settings( { 'issueAnalyzer' : {",
"True, 'update_issues': False, 'create_issues_instead_of_update': False, } }, {}, [] )",
"result = self.assertSubmitCreate(self.new) self.assertTrue(self.new.new) self.assertTrue(self.new.tracked) self.assertEqual(result, 'http://issuetracker.example.com/new_issue') self.assertEqual(result, self.new.uri) #",
"self.assertUnchanged(issue): with self.assertLogs('test', level='INFO') as cm: result1 = issue.submit() result2",
"'update_issues': False, 'create_issues_instead_of_update': False, } }, {}, [] ) def",
") def testNew(self): result = self.assertSubmitCreate(self.new) self.assertTrue(self.new.new) self.assertTrue(self.new.tracked) self.assertEqual(result, 'http://issuetracker.example.com/new_issue')",
"return None @property def resolved(self): return False @property def report_url(self):",
"LOGGER.info('make was called') return 'http://issuetracker.example.com/new_issue' def update(self): LOGGER.info('update was called')",
"def setUp(self): self.new = NewIssue(self.settings) self.unresolved = TrackedUnresolvedIssue(self.settings) self.resolved =",
"return 'http://issuetracker.example.com/new_issue' def update(self): LOGGER.info('update was called') def _lookup(self): LOGGER.info('lookup",
"= Settings( { 'issueAnalyzer' : { 'create_issues': True, 'update_issues': True,",
"self.assertEqual(self.issue.uri, None) def test_sync(self): # test lookup was called with",
"def test_properties(self): self.assertTrue(self.issue.new) self.assertFalse(self.issue.tracked) self.assertEqual(self.issue.uri, None) def test_sync(self): # test",
"def report_url(self): return 'http://issuetracker.example.com/new/foo' class TrackedUnresolvedIssue(NewIssue): def _lookup(self): LOGGER.info('lookup was",
"result2 = issue.submit() self.assertEqual(cm.output, [ \"INFO:test:submit was called\", \"INFO:test:make was",
"class NewIssue(BaseIssue): def submit(self): LOGGER.info('submit was called') return super().submit() def",
"False, } }, {}, [] ) def setUp(self): self.new =",
") def testUnresolved(self): old_uri = self.unresolved.uri result = self.assertSubmitCreate(self.unresolved) self.assertEqual(result,",
"@property def resolved(self): return True class TestNewIssue(unittest.TestCase): def setUp(self): self.settings",
"self.unresolved.sync() self.resolved.sync() @contextlib.contextmanager def assertUnchanged(self, issue): old_uri = issue.uri old_new",
"resolved(self): return True class TestNewIssue(unittest.TestCase): def setUp(self): self.settings = Settings({},",
"'create_issues': False, 'update_issues': False, 'create_issues_instead_of_update': False, } }, {}, []",
"'create_issues': True, 'update_issues': True, 'create_issues_instead_of_update': False, } }, {}, []",
"doesn't do anything with self.assertUnchanged(self.new): with self.assertLogs('test', level='INFO') as cm:",
"self.settings = Settings({}, {}, []) self.issue = TrackedResolvedIssue(self.settings) class TestSubmitDisabled(unittest.TestCase):",
"def testUnresolved(self): self.assertSubmitUpdate(self.unresolved) def testResolved(self): self.assertSubmitUpdate(self.resolved) class TestSubmitCreateOnlyNew(TestSubmitCreateUpdate): settings =",
"self.assertEqual(cm.output, [ \"INFO:test:submit was called\", \"INFO:test:update was called\", \"INFO:test:submit was",
"should have no effect 'create_issues_instead_of_update': True, } }, {}, []",
"yield issue self.assertEqual(issue.uri, old_uri) self.assertEqual(issue.new, old_new) self.assertEqual(issue.tracked, old_tracked) def assertSubmitNoop(self,"
] |
[
"\"--write\", help=\"destination for computed acoustic model\") verbosity_group = argparser.add_mutually_exclusive_group() verbosity_group.add_argument(\"-v\",",
"# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN",
"Corpus from aligner import Aligner from archive import Archive from",
"= logging.WARNING if args.extra_verbose: loglevel = logging.DEBUG elif args.verbose: loglevel",
"corpus '{}'.\".format(args.align)) corpus = Corpus(args.align, opts) logging.info(\"Aligning corpus '{}'.\".format(args.align)) aligned",
"included # in all copies or substantial portions of the",
"containing data to align\") output_group.add_argument(\"-w\", \"--write\", help=\"destination for computed acoustic",
"WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT",
"_) = os.path.splitext(args.write) archive_path = os.path.relpath(archive.dump(basename)) logging.info(\"Wrote aligner to '{}'.\".format(archive_path))",
"not args.dictionary: args.dictionary = [DICTIONARY] # set up logging loglevel",
"EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE",
"yaml.dump(opts, sink) (basename, _) = os.path.splitext(args.write) archive_path = os.path.relpath(archive.dump(basename)) logging.info(\"Wrote",
"not going to work once you move the data if",
"pick one if args.align: # check to make sure we're",
"args.verbose: loglevel = logging.INFO logging.basicConfig(format=LOGGING_FMT, level=loglevel) # input: pick one",
"textgrid import MLF from corpus import Corpus from aligner import",
"archive.add(os.path.join(aligner.curdir, MACROS)) # whatever this is, it's not going to",
"# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION",
"if args.configuration: logging.warning(\"Ignoring config flag (-c/--configuration).\") args.configuration = None if",
"acoustic model\") input_group.add_argument(\"-t\", \"--train\", help=\"directory containing data for training\") output_group",
"else: if not args.read: args.read = MODEL logging.info(\"Reading aligner from",
"PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS #",
"logging.DEBUG elif args.verbose: loglevel = logging.INFO logging.basicConfig(format=LOGGING_FMT, level=loglevel) # input:",
"AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM,",
"free of charge, to any person obtaining a # copy",
"ARISING FROM, OUT OF OR IN CONNECTION WITH THE #",
"MLF(aligned).write(args.align) if not size: logging.error(\"No paths found!\") exit(1) logging.debug(\"Wrote {}",
"type=int, help=\"# of epochs of training per round\") input_group =",
"corpus '{}'.\".format(args.align)) aligned = os.path.join(args.align, ALIGNED) scores = os.path.join(args.align, SCORES)",
"corpus '{}'.\".format(args.train)) aligner.HTKbook_training_regime(corpus, opts[\"epochs\"], flatstart=(args.read is None)) else: if not",
"sell copies of the Software, and to # permit persons",
"logging.warning(\"Ignoring epochs flag (-e/--epochs).\") if args.samplerate: logging.warning(\"Ignoring samplerate flag (-s/--samplerate).\")",
"elif args.verbose: loglevel = logging.INFO logging.basicConfig(format=LOGGING_FMT, level=loglevel) # input: pick",
"portions of the Software. # # THE SOFTWARE IS PROVIDED",
"LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A",
"to point to the archive data aligner = Aligner(opts) aligner.curdir",
"for training\") output_group = argparser.add_mutually_exclusive_group(required=True) output_group.add_argument(\"-a\", \"--align\", help=\"directory containing data",
"up logging loglevel = logging.WARNING if args.extra_verbose: loglevel = logging.DEBUG",
"WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND",
"any person obtaining a # copy of this software and",
"# # The above copyright notice and this permission notice",
"help=\"Verbose output\") verbosity_group.add_argument(\"-V\", \"--extra-verbose\", action=\"store_true\", help=\"Even more verbose output\") args",
"flag (-c/--configuration).\") args.configuration = None if args.epochs: logging.warning(\"Ignoring epochs flag",
"publish, # distribute, sublicense, and/or sell copies of the Software,",
"training data if (not args.train) or (os.path.realpath(args.train) != os.path.realpath(args.align)): logging.info(\"Preparing",
"resolve options with it args.configuration = os.path.join(archive.dirname, CONFIG) opts =",
"logging.debug(\"Wrote likelihood scores to '{}'.\".format(scores)) logging.info(\"Writing TextGrids.\") size = MLF(aligned).write(args.align)",
"aligner.\") aligner = Aligner(opts) logging.info(\"Training aligner on corpus '{}'.\".format(args.train)) aligner.HTKbook_training_regime(corpus,",
"TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR",
"warn about irrelevant flags if args.configuration: logging.warning(\"Ignoring config flag (-c/--configuration).\")",
"resolve_opts, \\ ALIGNED, CONFIG, HMMDEFS, MACROS, SCORES from argparse import",
"# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE",
"use, copy, modify, merge, publish, # distribute, sublicense, and/or sell",
"THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE",
"train on persistent model.\") exit(1) logging.info(\"Preparing corpus '{}'.\".format(args.train)) opts =",
"argparse import ArgumentParser DICTIONARY = \"eng.dict\" MODEL = \"eng.zip\" LOGGING_FMT",
"= Aligner(opts) aligner.curdir = archive.dirname # output: pick one if",
"hereby granted, free of charge, to any person obtaining a",
"aligned, scores) logging.debug(\"Wrote MLF file to '{}'.\".format(aligned)) logging.debug(\"Wrote likelihood scores",
"AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR",
"and resolve options with it args.configuration = os.path.join(archive.dirname, CONFIG) opts",
"modify, merge, publish, # distribute, sublicense, and/or sell copies of",
"THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN",
"output\") verbosity_group.add_argument(\"-V\", \"--extra-verbose\", action=\"store_true\", help=\"Even more verbose output\") args =",
"create archive from -r argument archive = Archive(args.read) # read",
"flag (-e/--epochs).\") if args.samplerate: logging.warning(\"Ignoring samplerate flag (-s/--samplerate).\") args.samplerate =",
"opts) logging.info(\"Aligning corpus '{}'.\".format(args.align)) aligned = os.path.join(args.align, ALIGNED) scores =",
"opts = resolve_opts(args) # initialize aligner and set it to",
"to # the following conditions: # # The above copyright",
"if not args.read: args.read = MODEL logging.info(\"Reading aligner from '{}'.\".format(args.read))",
"without restriction, including # without limitation the rights to use,",
"the data if \"dictionary\" in opts: del opts[\"dictionary\"] with open(os.path.join(archive.dirname,",
"level=loglevel) # input: pick one if args.train: if args.read: logging.error(\"Cannot",
"opts) logging.info(\"Preparing aligner.\") aligner = Aligner(opts) logging.info(\"Training aligner on corpus",
"OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF",
"\"--dictionary\", metavar=\"DICT\", action=\"append\", help=\"dictionary file (default: {}) (can specify multiple)\".format(DICTIONARY))",
"sublicense, and/or sell copies of the Software, and to #",
"# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES",
"shall be included # in all copies or substantial portions",
"DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,",
"MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN",
"persistent model.\") exit(1) logging.info(\"Preparing corpus '{}'.\".format(args.train)) opts = resolve_opts(args) corpus",
"once you move the data if \"dictionary\" in opts: del",
"Archive from utilities import splitname, resolve_opts, \\ ALIGNED, CONFIG, HMMDEFS,",
"persons to whom the Software is furnished to do so,",
"{}) (can specify multiple)\".format(DICTIONARY)) argparser.add_argument(\"-s\", \"--samplerate\", type=int, help=\"analysis samplerate (in",
"OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH",
"logging.info(\"Training aligner on corpus '{}'.\".format(args.train)) aligner.HTKbook_training_regime(corpus, opts[\"epochs\"], flatstart=(args.read is None))",
"Aligner(opts) aligner.curdir = archive.dirname # output: pick one if args.align:",
"the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\",",
"bisect from shutil import copyfile from textgrid import MLF from",
"output_group.add_argument(\"-w\", \"--write\", help=\"destination for computed acoustic model\") verbosity_group = argparser.add_mutually_exclusive_group()",
"create and populate archive (_, basename, _) = splitname(args.write) archive",
"samplerate flag (-s/--samplerate).\") args.samplerate = None # create archive from",
"HMMDEFS, MACROS, SCORES from argparse import ArgumentParser DICTIONARY = \"eng.dict\"",
"Command-line driver for the module \"\"\" import logging import os",
"aligner.align_and_score(corpus, aligned, scores) logging.debug(\"Wrote MLF file to '{}'.\".format(aligned)) logging.debug(\"Wrote likelihood",
"args.extra_verbose: loglevel = logging.DEBUG elif args.verbose: loglevel = logging.INFO logging.basicConfig(format=LOGGING_FMT,",
"logging.debug(\"Wrote {} TextGrids.\".format(size)) elif args.write: # create and populate archive",
"with it args.configuration = os.path.join(archive.dirname, CONFIG) opts = resolve_opts(args) #",
"help=\"source for a precomputed acoustic model\") input_group.add_argument(\"-t\", \"--train\", help=\"directory containing",
"exit(1) logging.info(\"Preparing corpus '{}'.\".format(args.train)) opts = resolve_opts(args) corpus = Corpus(args.train,",
"OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT",
"FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT",
"all copies or substantial portions of the Software. # #",
"on corpus '{}'.\".format(args.train)) aligner.HTKbook_training_regime(corpus, opts[\"epochs\"], flatstart=(args.read is None)) else: if",
"BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY,",
"\\ ALIGNED, CONFIG, HMMDEFS, MACROS, SCORES from argparse import ArgumentParser",
"USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" Command-line driver",
"including # without limitation the rights to use, copy, modify,",
"if args.align: # check to make sure we're not aligning",
"# without limitation the rights to use, copy, modify, merge,",
"# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF",
"move the data if \"dictionary\" in opts: del opts[\"dictionary\"] with",
"(not args.train) or (os.path.realpath(args.train) != os.path.realpath(args.align)): logging.info(\"Preparing corpus '{}'.\".format(args.align)) corpus",
"aligner import Aligner from archive import Archive from utilities import",
"A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL",
"verbosity_group = argparser.add_mutually_exclusive_group() verbosity_group.add_argument(\"-v\", \"--verbose\", action=\"store_true\", help=\"Verbose output\") verbosity_group.add_argument(\"-V\", \"--extra-verbose\",",
"'{}'.\".format(args.train)) aligner.HTKbook_training_regime(corpus, opts[\"epochs\"], flatstart=(args.read is None)) else: if not args.read:",
"LOGGING_FMT = \"%(message)s\" # parse arguments argparser = ArgumentParser(prog=\"{} -m",
"HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER",
"MLF file to '{}'.\".format(aligned)) logging.debug(\"Wrote likelihood scores to '{}'.\".format(scores)) logging.info(\"Writing",
"to do so, subject to # the following conditions: #",
"# set up logging loglevel = logging.WARNING if args.extra_verbose: loglevel",
"Archive.empty(basename) archive.add(os.path.join(aligner.curdir, HMMDEFS)) archive.add(os.path.join(aligner.curdir, MACROS)) # whatever this is, it's",
"= argparser.add_mutually_exclusive_group() verbosity_group.add_argument(\"-v\", \"--verbose\", action=\"store_true\", help=\"Verbose output\") verbosity_group.add_argument(\"-V\", \"--extra-verbose\", action=\"store_true\",",
"args = argparser.parse_args() # hack to allow proper override of",
"# parse arguments argparser = ArgumentParser(prog=\"{} -m aligner\".format(sys.executable), description=\"Prosodylab-Aligner\") argparser.add_argument(\"-c\",",
"on the training data if (not args.train) or (os.path.realpath(args.train) !=",
"Software without restriction, including # without limitation the rights to",
"resolve_opts(args) corpus = Corpus(args.train, opts) logging.info(\"Preparing aligner.\") aligner = Aligner(opts)",
"paths found!\") exit(1) logging.debug(\"Wrote {} TextGrids.\".format(size)) elif args.write: # create",
"(the # \"Software\"), to deal in the Software without restriction,",
"# The above copyright notice and this permission notice shall",
"from utilities import splitname, resolve_opts, \\ ALIGNED, CONFIG, HMMDEFS, MACROS,",
"more verbose output\") args = argparser.parse_args() # hack to allow",
"module \"\"\" import logging import os import sys import yaml",
"therefrom, and resolve options with it args.configuration = os.path.join(archive.dirname, CONFIG)",
"and set it to point to the archive data aligner",
"from bisect import bisect from shutil import copyfile from textgrid",
"EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR",
"= Archive.empty(basename) archive.add(os.path.join(aligner.curdir, HMMDEFS)) archive.add(os.path.join(aligner.curdir, MACROS)) # whatever this is,",
"in the Software without restriction, including # without limitation the",
"THE SOFTWARE. \"\"\" Command-line driver for the module \"\"\" import",
"\"eng.zip\" LOGGING_FMT = \"%(message)s\" # parse arguments argparser = ArgumentParser(prog=\"{}",
"of this software and associated documentation files (the # \"Software\"),",
"subject to # the following conditions: # # The above",
"aligning on the training data if (not args.train) or (os.path.realpath(args.train)",
"# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS",
"IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS",
"file therefrom, and resolve options with it args.configuration = os.path.join(archive.dirname,",
"notice and this permission notice shall be included # in",
"of charge, to any person obtaining a # copy of",
"is, it's not going to work once you move the",
"archive = Archive(args.read) # read configuration file therefrom, and resolve",
"archive import Archive from utilities import splitname, resolve_opts, \\ ALIGNED,",
"to use, copy, modify, merge, publish, # distribute, sublicense, and/or",
"following conditions: # # The above copyright notice and this",
"(basename, _) = os.path.splitext(args.write) archive_path = os.path.relpath(archive.dump(basename)) logging.info(\"Wrote aligner to",
"to allow proper override of default dictionary if not args.dictionary:",
"of training per round\") input_group = argparser.add_argument_group() input_group.add_argument(\"-r\", \"--read\", help=\"source",
"acoustic model\") verbosity_group = argparser.add_mutually_exclusive_group() verbosity_group.add_argument(\"-v\", \"--verbose\", action=\"store_true\", help=\"Verbose output\")",
"conditions: # # The above copyright notice and this permission",
"opts[\"epochs\"], flatstart=(args.read is None)) else: if not args.read: args.read =",
"input_group.add_argument(\"-r\", \"--read\", help=\"source for a precomputed acoustic model\") input_group.add_argument(\"-t\", \"--train\",",
"epochs flag (-e/--epochs).\") if args.samplerate: logging.warning(\"Ignoring samplerate flag (-s/--samplerate).\") args.samplerate",
"= \"%(message)s\" # parse arguments argparser = ArgumentParser(prog=\"{} -m aligner\".format(sys.executable),",
"from textgrid import MLF from corpus import Corpus from aligner",
"one if args.align: # check to make sure we're not",
"scores = os.path.join(args.align, SCORES) aligner.align_and_score(corpus, aligned, scores) logging.debug(\"Wrote MLF file",
"likelihood scores to '{}'.\".format(scores)) logging.info(\"Writing TextGrids.\") size = MLF(aligned).write(args.align) if",
"ALIGNED) scores = os.path.join(args.align, SCORES) aligner.align_and_score(corpus, aligned, scores) logging.debug(\"Wrote MLF",
"size: logging.error(\"No paths found!\") exit(1) logging.debug(\"Wrote {} TextGrids.\".format(size)) elif args.write:",
"ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED",
"aligner from '{}'.\".format(args.read)) # warn about irrelevant flags if args.configuration:",
"set up logging loglevel = logging.WARNING if args.extra_verbose: loglevel =",
"# in all copies or substantial portions of the Software.",
"parse arguments argparser = ArgumentParser(prog=\"{} -m aligner\".format(sys.executable), description=\"Prosodylab-Aligner\") argparser.add_argument(\"-c\", \"--configuration\",",
"per round\") input_group = argparser.add_argument_group() input_group.add_argument(\"-r\", \"--read\", help=\"source for a",
"pick one if args.train: if args.read: logging.error(\"Cannot train on persistent",
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR",
"on persistent model.\") exit(1) logging.info(\"Preparing corpus '{}'.\".format(args.train)) opts = resolve_opts(args)",
"splitname(args.write) archive = Archive.empty(basename) archive.add(os.path.join(aligner.curdir, HMMDEFS)) archive.add(os.path.join(aligner.curdir, MACROS)) # whatever",
"!= os.path.realpath(args.align)): logging.info(\"Preparing corpus '{}'.\".format(args.align)) corpus = Corpus(args.align, opts) logging.info(\"Aligning",
"IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED,",
"containing data for training\") output_group = argparser.add_mutually_exclusive_group(required=True) output_group.add_argument(\"-a\", \"--align\", help=\"directory",
"= logging.INFO logging.basicConfig(format=LOGGING_FMT, level=loglevel) # input: pick one if args.train:",
"KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO",
"basename, _) = splitname(args.write) archive = Archive.empty(basename) archive.add(os.path.join(aligner.curdir, HMMDEFS)) archive.add(os.path.join(aligner.curdir,",
"\"--extra-verbose\", action=\"store_true\", help=\"Even more verbose output\") args = argparser.parse_args() #",
"it's not going to work once you move the data",
"WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING",
"2011-2014 <NAME> and <NAME> # # Permission is hereby granted,",
"corpus '{}'.\".format(args.train)) opts = resolve_opts(args) corpus = Corpus(args.train, opts) logging.info(\"Preparing",
"charge, to any person obtaining a # copy of this",
"= Corpus(args.train, opts) logging.info(\"Preparing aligner.\") aligner = Aligner(opts) logging.info(\"Training aligner",
"args.samplerate: logging.warning(\"Ignoring samplerate flag (-s/--samplerate).\") args.samplerate = None # create",
"copy of this software and associated documentation files (the #",
"set it to point to the archive data aligner =",
"about irrelevant flags if args.configuration: logging.warning(\"Ignoring config flag (-c/--configuration).\") args.configuration",
"ArgumentParser(prog=\"{} -m aligner\".format(sys.executable), description=\"Prosodylab-Aligner\") argparser.add_argument(\"-c\", \"--configuration\", help=\"config file\") argparser.add_argument(\"-d\", \"--dictionary\",",
"opts: del opts[\"dictionary\"] with open(os.path.join(archive.dirname, CONFIG), \"w\") as sink: yaml.dump(opts,",
"copy, modify, merge, publish, # distribute, sublicense, and/or sell copies",
"Copyright (c) 2011-2014 <NAME> and <NAME> # # Permission is",
"OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" Command-line driver for",
"a # copy of this software and associated documentation files",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF #",
"person obtaining a # copy of this software and associated",
"is hereby granted, free of charge, to any person obtaining",
"# read configuration file therefrom, and resolve options with it",
"and this permission notice shall be included # in all",
"logging.info(\"Preparing corpus '{}'.\".format(args.align)) corpus = Corpus(args.align, opts) logging.info(\"Aligning corpus '{}'.\".format(args.align))",
"if (not args.train) or (os.path.realpath(args.train) != os.path.realpath(args.align)): logging.info(\"Preparing corpus '{}'.\".format(args.align))",
"Corpus(args.align, opts) logging.info(\"Aligning corpus '{}'.\".format(args.align)) aligned = os.path.join(args.align, ALIGNED) scores",
"args.read: args.read = MODEL logging.info(\"Reading aligner from '{}'.\".format(args.read)) # warn",
"= Archive(args.read) # read configuration file therefrom, and resolve options",
"PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE",
"options with it args.configuration = os.path.join(archive.dirname, CONFIG) opts = resolve_opts(args)",
"from shutil import copyfile from textgrid import MLF from corpus",
"OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT",
"DEALINGS IN THE SOFTWARE. \"\"\" Command-line driver for the module",
"corpus import Corpus from aligner import Aligner from archive import",
"argparser.add_argument_group() input_group.add_argument(\"-r\", \"--read\", help=\"source for a precomputed acoustic model\") input_group.add_argument(\"-t\",",
"# # Permission is hereby granted, free of charge, to",
"data if (not args.train) or (os.path.realpath(args.train) != os.path.realpath(args.align)): logging.info(\"Preparing corpus",
"args.train) or (os.path.realpath(args.train) != os.path.realpath(args.align)): logging.info(\"Preparing corpus '{}'.\".format(args.align)) corpus =",
"model\") input_group.add_argument(\"-t\", \"--train\", help=\"directory containing data for training\") output_group =",
"it args.configuration = os.path.join(archive.dirname, CONFIG) opts = resolve_opts(args) # initialize",
"permit persons to whom the Software is furnished to do",
"read configuration file therefrom, and resolve options with it args.configuration",
"check to make sure we're not aligning on the training",
"copies of the Software, and to # permit persons to",
"flag (-s/--samplerate).\") args.samplerate = None # create archive from -r",
"CONFIG) opts = resolve_opts(args) # initialize aligner and set it",
"from '{}'.\".format(args.read)) # warn about irrelevant flags if args.configuration: logging.warning(\"Ignoring",
"verbosity_group.add_argument(\"-V\", \"--extra-verbose\", action=\"store_true\", help=\"Even more verbose output\") args = argparser.parse_args()",
"import os import sys import yaml from bisect import bisect",
"logging.error(\"Cannot train on persistent model.\") exit(1) logging.info(\"Preparing corpus '{}'.\".format(args.train)) opts",
"aligner on corpus '{}'.\".format(args.train)) aligner.HTKbook_training_regime(corpus, opts[\"epochs\"], flatstart=(args.read is None)) else:",
"argparser.add_argument(\"-s\", \"--samplerate\", type=int, help=\"analysis samplerate (in Hz)\") argparser.add_argument(\"-e\", \"--epochs\", type=int,",
"SOFTWARE. \"\"\" Command-line driver for the module \"\"\" import logging",
"data if \"dictionary\" in opts: del opts[\"dictionary\"] with open(os.path.join(archive.dirname, CONFIG),",
"logging.error(\"No paths found!\") exit(1) logging.debug(\"Wrote {} TextGrids.\".format(size)) elif args.write: #",
"aligner = Aligner(opts) aligner.curdir = archive.dirname # output: pick one",
"not aligning on the training data if (not args.train) or",
"PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS",
"logging.INFO logging.basicConfig(format=LOGGING_FMT, level=loglevel) # input: pick one if args.train: if",
"and associated documentation files (the # \"Software\"), to deal in",
"loglevel = logging.INFO logging.basicConfig(format=LOGGING_FMT, level=loglevel) # input: pick one if",
"or substantial portions of the Software. # # THE SOFTWARE",
"action=\"store_true\", help=\"Verbose output\") verbosity_group.add_argument(\"-V\", \"--extra-verbose\", action=\"store_true\", help=\"Even more verbose output\")",
"granted, free of charge, to any person obtaining a #",
"\"--epochs\", type=int, help=\"# of epochs of training per round\") input_group",
"logging.info(\"Aligning corpus '{}'.\".format(args.align)) aligned = os.path.join(args.align, ALIGNED) scores = os.path.join(args.align,",
"logging.info(\"Preparing corpus '{}'.\".format(args.train)) opts = resolve_opts(args) corpus = Corpus(args.train, opts)",
"MLF from corpus import Corpus from aligner import Aligner from",
"= os.path.join(archive.dirname, CONFIG) opts = resolve_opts(args) # initialize aligner and",
"from argparse import ArgumentParser DICTIONARY = \"eng.dict\" MODEL = \"eng.zip\"",
"import sys import yaml from bisect import bisect from shutil",
"= ArgumentParser(prog=\"{} -m aligner\".format(sys.executable), description=\"Prosodylab-Aligner\") argparser.add_argument(\"-c\", \"--configuration\", help=\"config file\") argparser.add_argument(\"-d\",",
"aligner.curdir = archive.dirname # output: pick one if args.align: #",
"we're not aligning on the training data if (not args.train)",
"# Permission is hereby granted, free of charge, to any",
"MODEL logging.info(\"Reading aligner from '{}'.\".format(args.read)) # warn about irrelevant flags",
"= None if args.epochs: logging.warning(\"Ignoring epochs flag (-e/--epochs).\") if args.samplerate:",
"_) = splitname(args.write) archive = Archive.empty(basename) archive.add(os.path.join(aligner.curdir, HMMDEFS)) archive.add(os.path.join(aligner.curdir, MACROS))",
"the Software is furnished to do so, subject to #",
"MACROS, SCORES from argparse import ArgumentParser DICTIONARY = \"eng.dict\" MODEL",
"help=\"Even more verbose output\") args = argparser.parse_args() # hack to",
"# # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY",
"from aligner import Aligner from archive import Archive from utilities",
"without limitation the rights to use, copy, modify, merge, publish,",
"input_group.add_argument(\"-t\", \"--train\", help=\"directory containing data for training\") output_group = argparser.add_mutually_exclusive_group(required=True)",
"corpus = Corpus(args.align, opts) logging.info(\"Aligning corpus '{}'.\".format(args.align)) aligned = os.path.join(args.align,",
"splitname, resolve_opts, \\ ALIGNED, CONFIG, HMMDEFS, MACROS, SCORES from argparse",
"output_group.add_argument(\"-a\", \"--align\", help=\"directory containing data to align\") output_group.add_argument(\"-w\", \"--write\", help=\"destination",
"merge, publish, # distribute, sublicense, and/or sell copies of the",
"obtaining a # copy of this software and associated documentation",
"limitation the rights to use, copy, modify, merge, publish, #",
"'{}'.\".format(args.read)) # warn about irrelevant flags if args.configuration: logging.warning(\"Ignoring config",
"= None # create archive from -r argument archive =",
"dictionary if not args.dictionary: args.dictionary = [DICTIONARY] # set up",
"# hack to allow proper override of default dictionary if",
"OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF",
"aligner.HTKbook_training_regime(corpus, opts[\"epochs\"], flatstart=(args.read is None)) else: if not args.read: args.read",
"so, subject to # the following conditions: # # The",
"IN CONNECTION WITH THE # SOFTWARE OR THE USE OR",
"file to '{}'.\".format(aligned)) logging.debug(\"Wrote likelihood scores to '{}'.\".format(scores)) logging.info(\"Writing TextGrids.\")",
"do so, subject to # the following conditions: # #",
"argparser.add_argument(\"-d\", \"--dictionary\", metavar=\"DICT\", action=\"append\", help=\"dictionary file (default: {}) (can specify",
"# check to make sure we're not aligning on the",
"(-c/--configuration).\") args.configuration = None if args.epochs: logging.warning(\"Ignoring epochs flag (-e/--epochs).\")",
"the rights to use, copy, modify, merge, publish, # distribute,",
"IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING",
"the module \"\"\" import logging import os import sys import",
"import yaml from bisect import bisect from shutil import copyfile",
"help=\"dictionary file (default: {}) (can specify multiple)\".format(DICTIONARY)) argparser.add_argument(\"-s\", \"--samplerate\", type=int,",
"logging.basicConfig(format=LOGGING_FMT, level=loglevel) # input: pick one if args.train: if args.read:",
"args.configuration: logging.warning(\"Ignoring config flag (-c/--configuration).\") args.configuration = None if args.epochs:",
"ALIGNED, CONFIG, HMMDEFS, MACROS, SCORES from argparse import ArgumentParser DICTIONARY",
"= os.path.relpath(archive.dump(basename)) logging.info(\"Wrote aligner to '{}'.\".format(archive_path)) # else unreachable logging.info(\"Success!\")",
"Software, and to # permit persons to whom the Software",
"= \"eng.dict\" MODEL = \"eng.zip\" LOGGING_FMT = \"%(message)s\" # parse",
"the following conditions: # # The above copyright notice and",
"irrelevant flags if args.configuration: logging.warning(\"Ignoring config flag (-c/--configuration).\") args.configuration =",
"distribute, sublicense, and/or sell copies of the Software, and to",
"loglevel = logging.WARNING if args.extra_verbose: loglevel = logging.DEBUG elif args.verbose:",
"to any person obtaining a # copy of this software",
"# \"Software\"), to deal in the Software without restriction, including",
"not args.read: args.read = MODEL logging.info(\"Reading aligner from '{}'.\".format(args.read)) #",
"make sure we're not aligning on the training data if",
"\"--read\", help=\"source for a precomputed acoustic model\") input_group.add_argument(\"-t\", \"--train\", help=\"directory",
"in opts: del opts[\"dictionary\"] with open(os.path.join(archive.dirname, CONFIG), \"w\") as sink:",
"# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. #",
"args.train: if args.read: logging.error(\"Cannot train on persistent model.\") exit(1) logging.info(\"Preparing",
"= MODEL logging.info(\"Reading aligner from '{}'.\".format(args.read)) # warn about irrelevant",
"# copy of this software and associated documentation files (the",
"ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT",
"initialize aligner and set it to point to the archive",
"of default dictionary if not args.dictionary: args.dictionary = [DICTIONARY] #",
"\"\"\" import logging import os import sys import yaml from",
"if args.train: if args.read: logging.error(\"Cannot train on persistent model.\") exit(1)",
"\"--verbose\", action=\"store_true\", help=\"Verbose output\") verbosity_group.add_argument(\"-V\", \"--extra-verbose\", action=\"store_true\", help=\"Even more verbose",
"from corpus import Corpus from aligner import Aligner from archive",
"to '{}'.\".format(scores)) logging.info(\"Writing TextGrids.\") size = MLF(aligned).write(args.align) if not size:",
"<filename>naplib/alignment/prosodylab_aligner/__main__.py # Copyright (c) 2011-2014 <NAME> and <NAME> # #",
"Corpus(args.train, opts) logging.info(\"Preparing aligner.\") aligner = Aligner(opts) logging.info(\"Training aligner on",
"= splitname(args.write) archive = Archive.empty(basename) archive.add(os.path.join(aligner.curdir, HMMDEFS)) archive.add(os.path.join(aligner.curdir, MACROS)) #",
"copyright notice and this permission notice shall be included #",
"logging import os import sys import yaml from bisect import",
"CONFIG, HMMDEFS, MACROS, SCORES from argparse import ArgumentParser DICTIONARY =",
"import copyfile from textgrid import MLF from corpus import Corpus",
"(can specify multiple)\".format(DICTIONARY)) argparser.add_argument(\"-s\", \"--samplerate\", type=int, help=\"analysis samplerate (in Hz)\")",
"argparser.add_mutually_exclusive_group() verbosity_group.add_argument(\"-v\", \"--verbose\", action=\"store_true\", help=\"Verbose output\") verbosity_group.add_argument(\"-V\", \"--extra-verbose\", action=\"store_true\", help=\"Even",
"to whom the Software is furnished to do so, subject",
"to work once you move the data if \"dictionary\" in",
"notice shall be included # in all copies or substantial",
"it to point to the archive data aligner = Aligner(opts)",
"SCORES from argparse import ArgumentParser DICTIONARY = \"eng.dict\" MODEL =",
"\"w\") as sink: yaml.dump(opts, sink) (basename, _) = os.path.splitext(args.write) archive_path",
"sure we're not aligning on the training data if (not",
"= os.path.splitext(args.write) archive_path = os.path.relpath(archive.dump(basename)) logging.info(\"Wrote aligner to '{}'.\".format(archive_path)) #",
"logging.warning(\"Ignoring samplerate flag (-s/--samplerate).\") args.samplerate = None # create archive",
"Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT",
"# whatever this is, it's not going to work once",
"# warn about irrelevant flags if args.configuration: logging.warning(\"Ignoring config flag",
"argparser.add_mutually_exclusive_group(required=True) output_group.add_argument(\"-a\", \"--align\", help=\"directory containing data to align\") output_group.add_argument(\"-w\", \"--write\",",
"{} TextGrids.\".format(size)) elif args.write: # create and populate archive (_,",
"Software is furnished to do so, subject to # the",
"\"dictionary\" in opts: del opts[\"dictionary\"] with open(os.path.join(archive.dirname, CONFIG), \"w\") as",
"args.epochs: logging.warning(\"Ignoring epochs flag (-e/--epochs).\") if args.samplerate: logging.warning(\"Ignoring samplerate flag",
"\"--train\", help=\"directory containing data for training\") output_group = argparser.add_mutually_exclusive_group(required=True) output_group.add_argument(\"-a\",",
"DICTIONARY = \"eng.dict\" MODEL = \"eng.zip\" LOGGING_FMT = \"%(message)s\" #",
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM,",
"to align\") output_group.add_argument(\"-w\", \"--write\", help=\"destination for computed acoustic model\") verbosity_group",
"os.path.splitext(args.write) archive_path = os.path.relpath(archive.dump(basename)) logging.info(\"Wrote aligner to '{}'.\".format(archive_path)) # else",
"argparser = ArgumentParser(prog=\"{} -m aligner\".format(sys.executable), description=\"Prosodylab-Aligner\") argparser.add_argument(\"-c\", \"--configuration\", help=\"config file\")",
"archive.dirname # output: pick one if args.align: # check to",
"flatstart=(args.read is None)) else: if not args.read: args.read = MODEL",
"going to work once you move the data if \"dictionary\"",
"aligned = os.path.join(args.align, ALIGNED) scores = os.path.join(args.align, SCORES) aligner.align_and_score(corpus, aligned,",
"# Copyright (c) 2011-2014 <NAME> and <NAME> # # Permission",
"epochs of training per round\") input_group = argparser.add_argument_group() input_group.add_argument(\"-r\", \"--read\",",
"args.write: # create and populate archive (_, basename, _) =",
"OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES",
"metavar=\"DICT\", action=\"append\", help=\"dictionary file (default: {}) (can specify multiple)\".format(DICTIONARY)) argparser.add_argument(\"-s\",",
"for a precomputed acoustic model\") input_group.add_argument(\"-t\", \"--train\", help=\"directory containing data",
"os import sys import yaml from bisect import bisect from",
"= Aligner(opts) logging.info(\"Training aligner on corpus '{}'.\".format(args.train)) aligner.HTKbook_training_regime(corpus, opts[\"epochs\"], flatstart=(args.read",
"NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR",
"Aligner from archive import Archive from utilities import splitname, resolve_opts,",
"action=\"append\", help=\"dictionary file (default: {}) (can specify multiple)\".format(DICTIONARY)) argparser.add_argument(\"-s\", \"--samplerate\",",
"if not args.dictionary: args.dictionary = [DICTIONARY] # set up logging",
"= argparser.parse_args() # hack to allow proper override of default",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY",
"NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT",
"substantial portions of the Software. # # THE SOFTWARE IS",
"logging.WARNING if args.extra_verbose: loglevel = logging.DEBUG elif args.verbose: loglevel =",
"to the archive data aligner = Aligner(opts) aligner.curdir = archive.dirname",
"proper override of default dictionary if not args.dictionary: args.dictionary =",
"this is, it's not going to work once you move",
"'{}'.\".format(args.train)) opts = resolve_opts(args) corpus = Corpus(args.train, opts) logging.info(\"Preparing aligner.\")",
"the Software, and to # permit persons to whom the",
"None if args.epochs: logging.warning(\"Ignoring epochs flag (-e/--epochs).\") if args.samplerate: logging.warning(\"Ignoring",
"Archive(args.read) # read configuration file therefrom, and resolve options with",
"help=\"directory containing data for training\") output_group = argparser.add_mutually_exclusive_group(required=True) output_group.add_argument(\"-a\", \"--align\",",
"verbose output\") args = argparser.parse_args() # hack to allow proper",
"argparser.add_argument(\"-e\", \"--epochs\", type=int, help=\"# of epochs of training per round\")",
"of the Software, and to # permit persons to whom",
"SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
"# create archive from -r argument archive = Archive(args.read) #",
"opts = resolve_opts(args) corpus = Corpus(args.train, opts) logging.info(\"Preparing aligner.\") aligner",
"to '{}'.\".format(aligned)) logging.debug(\"Wrote likelihood scores to '{}'.\".format(scores)) logging.info(\"Writing TextGrids.\") size",
"args.align: # check to make sure we're not aligning on",
"data to align\") output_group.add_argument(\"-w\", \"--write\", help=\"destination for computed acoustic model\")",
"training per round\") input_group = argparser.add_argument_group() input_group.add_argument(\"-r\", \"--read\", help=\"source for",
"# initialize aligner and set it to point to the",
"THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" Command-line",
"allow proper override of default dictionary if not args.dictionary: args.dictionary",
"rights to use, copy, modify, merge, publish, # distribute, sublicense,",
"action=\"store_true\", help=\"Even more verbose output\") args = argparser.parse_args() # hack",
"logging loglevel = logging.WARNING if args.extra_verbose: loglevel = logging.DEBUG elif",
"import Archive from utilities import splitname, resolve_opts, \\ ALIGNED, CONFIG,",
"computed acoustic model\") verbosity_group = argparser.add_mutually_exclusive_group() verbosity_group.add_argument(\"-v\", \"--verbose\", action=\"store_true\", help=\"Verbose",
"flags if args.configuration: logging.warning(\"Ignoring config flag (-c/--configuration).\") args.configuration = None",
"and/or sell copies of the Software, and to # permit",
"OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\"",
"import Corpus from aligner import Aligner from archive import Archive",
"# output: pick one if args.align: # check to make",
"logging.debug(\"Wrote MLF file to '{}'.\".format(aligned)) logging.debug(\"Wrote likelihood scores to '{}'.\".format(scores))",
"\"--align\", help=\"directory containing data to align\") output_group.add_argument(\"-w\", \"--write\", help=\"destination for",
"for the module \"\"\" import logging import os import sys",
"import splitname, resolve_opts, \\ ALIGNED, CONFIG, HMMDEFS, MACROS, SCORES from",
"to # permit persons to whom the Software is furnished",
"'{}'.\".format(args.align)) aligned = os.path.join(args.align, ALIGNED) scores = os.path.join(args.align, SCORES) aligner.align_and_score(corpus,",
"with open(os.path.join(archive.dirname, CONFIG), \"w\") as sink: yaml.dump(opts, sink) (basename, _)",
"description=\"Prosodylab-Aligner\") argparser.add_argument(\"-c\", \"--configuration\", help=\"config file\") argparser.add_argument(\"-d\", \"--dictionary\", metavar=\"DICT\", action=\"append\", help=\"dictionary",
"archive.add(os.path.join(aligner.curdir, HMMDEFS)) archive.add(os.path.join(aligner.curdir, MACROS)) # whatever this is, it's not",
"<NAME> # # Permission is hereby granted, free of charge,",
"OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.",
"this software and associated documentation files (the # \"Software\"), to",
"SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY",
"Aligner(opts) logging.info(\"Training aligner on corpus '{}'.\".format(args.train)) aligner.HTKbook_training_regime(corpus, opts[\"epochs\"], flatstart=(args.read is",
"data aligner = Aligner(opts) aligner.curdir = archive.dirname # output: pick",
"of the Software. # # THE SOFTWARE IS PROVIDED \"AS",
"is furnished to do so, subject to # the following",
"configuration file therefrom, and resolve options with it args.configuration =",
"loglevel = logging.DEBUG elif args.verbose: loglevel = logging.INFO logging.basicConfig(format=LOGGING_FMT, level=loglevel)",
"whom the Software is furnished to do so, subject to",
"= argparser.add_argument_group() input_group.add_argument(\"-r\", \"--read\", help=\"source for a precomputed acoustic model\")",
"# input: pick one if args.train: if args.read: logging.error(\"Cannot train",
"OR IN CONNECTION WITH THE # SOFTWARE OR THE USE",
"= resolve_opts(args) corpus = Corpus(args.train, opts) logging.info(\"Preparing aligner.\") aligner =",
"from -r argument archive = Archive(args.read) # read configuration file",
"OF OR IN CONNECTION WITH THE # SOFTWARE OR THE",
"= archive.dirname # output: pick one if args.align: # check",
"# permit persons to whom the Software is furnished to",
"import logging import os import sys import yaml from bisect",
"(-s/--samplerate).\") args.samplerate = None # create archive from -r argument",
"(_, basename, _) = splitname(args.write) archive = Archive.empty(basename) archive.add(os.path.join(aligner.curdir, HMMDEFS))",
"HMMDEFS)) archive.add(os.path.join(aligner.curdir, MACROS)) # whatever this is, it's not going",
"del opts[\"dictionary\"] with open(os.path.join(archive.dirname, CONFIG), \"w\") as sink: yaml.dump(opts, sink)",
"args.configuration = None if args.epochs: logging.warning(\"Ignoring epochs flag (-e/--epochs).\") if",
"import Aligner from archive import Archive from utilities import splitname,",
"logging.warning(\"Ignoring config flag (-c/--configuration).\") args.configuration = None if args.epochs: logging.warning(\"Ignoring",
"# create and populate archive (_, basename, _) = splitname(args.write)",
"\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR",
"# the following conditions: # # The above copyright notice",
"files (the # \"Software\"), to deal in the Software without",
"documentation files (the # \"Software\"), to deal in the Software",
"if not size: logging.error(\"No paths found!\") exit(1) logging.debug(\"Wrote {} TextGrids.\".format(size))",
"help=\"analysis samplerate (in Hz)\") argparser.add_argument(\"-e\", \"--epochs\", type=int, help=\"# of epochs",
"sys import yaml from bisect import bisect from shutil import",
"config flag (-c/--configuration).\") args.configuration = None if args.epochs: logging.warning(\"Ignoring epochs",
"type=int, help=\"analysis samplerate (in Hz)\") argparser.add_argument(\"-e\", \"--epochs\", type=int, help=\"# of",
"= os.path.join(args.align, SCORES) aligner.align_and_score(corpus, aligned, scores) logging.debug(\"Wrote MLF file to",
"WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE,",
"argparser.parse_args() # hack to allow proper override of default dictionary",
"= os.path.join(args.align, ALIGNED) scores = os.path.join(args.align, SCORES) aligner.align_and_score(corpus, aligned, scores)",
"aligner = Aligner(opts) logging.info(\"Training aligner on corpus '{}'.\".format(args.train)) aligner.HTKbook_training_regime(corpus, opts[\"epochs\"],",
"and to # permit persons to whom the Software is",
"BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS",
"CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER",
"(-e/--epochs).\") if args.samplerate: logging.warning(\"Ignoring samplerate flag (-s/--samplerate).\") args.samplerate = None",
"as sink: yaml.dump(opts, sink) (basename, _) = os.path.splitext(args.write) archive_path =",
"populate archive (_, basename, _) = splitname(args.write) archive = Archive.empty(basename)",
"of epochs of training per round\") input_group = argparser.add_argument_group() input_group.add_argument(\"-r\",",
"bisect import bisect from shutil import copyfile from textgrid import",
"input: pick one if args.train: if args.read: logging.error(\"Cannot train on",
"override of default dictionary if not args.dictionary: args.dictionary = [DICTIONARY]",
"default dictionary if not args.dictionary: args.dictionary = [DICTIONARY] # set",
"\"--configuration\", help=\"config file\") argparser.add_argument(\"-d\", \"--dictionary\", metavar=\"DICT\", action=\"append\", help=\"dictionary file (default:",
"be included # in all copies or substantial portions of",
"args.dictionary: args.dictionary = [DICTIONARY] # set up logging loglevel =",
"CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF",
"file\") argparser.add_argument(\"-d\", \"--dictionary\", metavar=\"DICT\", action=\"append\", help=\"dictionary file (default: {}) (can",
"arguments argparser = ArgumentParser(prog=\"{} -m aligner\".format(sys.executable), description=\"Prosodylab-Aligner\") argparser.add_argument(\"-c\", \"--configuration\", help=\"config",
"to make sure we're not aligning on the training data",
"logging.info(\"Preparing aligner.\") aligner = Aligner(opts) logging.info(\"Training aligner on corpus '{}'.\".format(args.train))",
"CONFIG), \"w\") as sink: yaml.dump(opts, sink) (basename, _) = os.path.splitext(args.write)",
"verbosity_group.add_argument(\"-v\", \"--verbose\", action=\"store_true\", help=\"Verbose output\") verbosity_group.add_argument(\"-V\", \"--extra-verbose\", action=\"store_true\", help=\"Even more",
"= Corpus(args.align, opts) logging.info(\"Aligning corpus '{}'.\".format(args.align)) aligned = os.path.join(args.align, ALIGNED)",
"import bisect from shutil import copyfile from textgrid import MLF",
"os.path.join(archive.dirname, CONFIG) opts = resolve_opts(args) # initialize aligner and set",
"model\") verbosity_group = argparser.add_mutually_exclusive_group() verbosity_group.add_argument(\"-v\", \"--verbose\", action=\"store_true\", help=\"Verbose output\") verbosity_group.add_argument(\"-V\",",
"= MLF(aligned).write(args.align) if not size: logging.error(\"No paths found!\") exit(1) logging.debug(\"Wrote",
"above copyright notice and this permission notice shall be included",
"\"--samplerate\", type=int, help=\"analysis samplerate (in Hz)\") argparser.add_argument(\"-e\", \"--epochs\", type=int, help=\"#",
"= \"eng.zip\" LOGGING_FMT = \"%(message)s\" # parse arguments argparser =",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO",
"elif args.write: # create and populate archive (_, basename, _)",
"WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS",
"help=\"destination for computed acoustic model\") verbosity_group = argparser.add_mutually_exclusive_group() verbosity_group.add_argument(\"-v\", \"--verbose\",",
"if args.read: logging.error(\"Cannot train on persistent model.\") exit(1) logging.info(\"Preparing corpus",
"scores to '{}'.\".format(scores)) logging.info(\"Writing TextGrids.\") size = MLF(aligned).write(args.align) if not",
"archive data aligner = Aligner(opts) aligner.curdir = archive.dirname # output:",
"one if args.train: if args.read: logging.error(\"Cannot train on persistent model.\")",
"\"%(message)s\" # parse arguments argparser = ArgumentParser(prog=\"{} -m aligner\".format(sys.executable), description=\"Prosodylab-Aligner\")",
"opts[\"dictionary\"] with open(os.path.join(archive.dirname, CONFIG), \"w\") as sink: yaml.dump(opts, sink) (basename,",
"'{}'.\".format(args.align)) corpus = Corpus(args.align, opts) logging.info(\"Aligning corpus '{}'.\".format(args.align)) aligned =",
"= [DICTIONARY] # set up logging loglevel = logging.WARNING if",
"associated documentation files (the # \"Software\"), to deal in the",
"if \"dictionary\" in opts: del opts[\"dictionary\"] with open(os.path.join(archive.dirname, CONFIG), \"w\")",
"in all copies or substantial portions of the Software. #",
"\"eng.dict\" MODEL = \"eng.zip\" LOGGING_FMT = \"%(message)s\" # parse arguments",
"-m aligner\".format(sys.executable), description=\"Prosodylab-Aligner\") argparser.add_argument(\"-c\", \"--configuration\", help=\"config file\") argparser.add_argument(\"-d\", \"--dictionary\", metavar=\"DICT\",",
"logging.info(\"Reading aligner from '{}'.\".format(args.read)) # warn about irrelevant flags if",
"data for training\") output_group = argparser.add_mutually_exclusive_group(required=True) output_group.add_argument(\"-a\", \"--align\", help=\"directory containing",
"copies or substantial portions of the Software. # # THE",
"logging.info(\"Writing TextGrids.\") size = MLF(aligned).write(args.align) if not size: logging.error(\"No paths",
"to deal in the Software without restriction, including # without",
"sink) (basename, _) = os.path.splitext(args.write) archive_path = os.path.relpath(archive.dump(basename)) logging.info(\"Wrote aligner",
"open(os.path.join(archive.dirname, CONFIG), \"w\") as sink: yaml.dump(opts, sink) (basename, _) =",
"= argparser.add_mutually_exclusive_group(required=True) output_group.add_argument(\"-a\", \"--align\", help=\"directory containing data to align\") output_group.add_argument(\"-w\",",
"output\") args = argparser.parse_args() # hack to allow proper override",
"multiple)\".format(DICTIONARY)) argparser.add_argument(\"-s\", \"--samplerate\", type=int, help=\"analysis samplerate (in Hz)\") argparser.add_argument(\"-e\", \"--epochs\",",
"FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN",
"LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER",
"exit(1) logging.debug(\"Wrote {} TextGrids.\".format(size)) elif args.write: # create and populate",
"resolve_opts(args) # initialize aligner and set it to point to",
"THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY #",
"input_group = argparser.add_argument_group() input_group.add_argument(\"-r\", \"--read\", help=\"source for a precomputed acoustic",
"specify multiple)\".format(DICTIONARY)) argparser.add_argument(\"-s\", \"--samplerate\", type=int, help=\"analysis samplerate (in Hz)\") argparser.add_argument(\"-e\",",
"os.path.join(args.align, ALIGNED) scores = os.path.join(args.align, SCORES) aligner.align_and_score(corpus, aligned, scores) logging.debug(\"Wrote",
"(os.path.realpath(args.train) != os.path.realpath(args.align)): logging.info(\"Preparing corpus '{}'.\".format(args.align)) corpus = Corpus(args.align, opts)",
"training\") output_group = argparser.add_mutually_exclusive_group(required=True) output_group.add_argument(\"-a\", \"--align\", help=\"directory containing data to",
"from archive import Archive from utilities import splitname, resolve_opts, \\",
"output: pick one if args.align: # check to make sure",
"file (default: {}) (can specify multiple)\".format(DICTIONARY)) argparser.add_argument(\"-s\", \"--samplerate\", type=int, help=\"analysis",
"is None)) else: if not args.read: args.read = MODEL logging.info(\"Reading",
"aligner\".format(sys.executable), description=\"Prosodylab-Aligner\") argparser.add_argument(\"-c\", \"--configuration\", help=\"config file\") argparser.add_argument(\"-d\", \"--dictionary\", metavar=\"DICT\", action=\"append\",",
"if args.extra_verbose: loglevel = logging.DEBUG elif args.verbose: loglevel = logging.INFO",
"yaml from bisect import bisect from shutil import copyfile from",
"args.read = MODEL logging.info(\"Reading aligner from '{}'.\".format(args.read)) # warn about",
"os.path.join(args.align, SCORES) aligner.align_and_score(corpus, aligned, scores) logging.debug(\"Wrote MLF file to '{}'.\".format(aligned))",
"MODEL = \"eng.zip\" LOGGING_FMT = \"%(message)s\" # parse arguments argparser",
"restriction, including # without limitation the rights to use, copy,",
"the Software without restriction, including # without limitation the rights",
"copyfile from textgrid import MLF from corpus import Corpus from",
"OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE",
"<NAME> and <NAME> # # Permission is hereby granted, free",
"model.\") exit(1) logging.info(\"Preparing corpus '{}'.\".format(args.train)) opts = resolve_opts(args) corpus =",
"IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE",
"os.path.realpath(args.align)): logging.info(\"Preparing corpus '{}'.\".format(args.align)) corpus = Corpus(args.align, opts) logging.info(\"Aligning corpus",
"furnished to do so, subject to # the following conditions:",
"TextGrids.\".format(size)) elif args.write: # create and populate archive (_, basename,",
"FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE",
"for computed acoustic model\") verbosity_group = argparser.add_mutually_exclusive_group() verbosity_group.add_argument(\"-v\", \"--verbose\", action=\"store_true\",",
"-r argument archive = Archive(args.read) # read configuration file therefrom,",
"MACROS)) # whatever this is, it's not going to work",
"SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.",
"ArgumentParser DICTIONARY = \"eng.dict\" MODEL = \"eng.zip\" LOGGING_FMT = \"%(message)s\"",
"precomputed acoustic model\") input_group.add_argument(\"-t\", \"--train\", help=\"directory containing data for training\")",
"work once you move the data if \"dictionary\" in opts:",
"None # create archive from -r argument archive = Archive(args.read)",
"archive = Archive.empty(basename) archive.add(os.path.join(aligner.curdir, HMMDEFS)) archive.add(os.path.join(aligner.curdir, MACROS)) # whatever this",
"'{}'.\".format(scores)) logging.info(\"Writing TextGrids.\") size = MLF(aligned).write(args.align) if not size: logging.error(\"No",
"archive from -r argument archive = Archive(args.read) # read configuration",
"'{}'.\".format(aligned)) logging.debug(\"Wrote likelihood scores to '{}'.\".format(scores)) logging.info(\"Writing TextGrids.\") size =",
"the archive data aligner = Aligner(opts) aligner.curdir = archive.dirname #",
"help=\"config file\") argparser.add_argument(\"-d\", \"--dictionary\", metavar=\"DICT\", action=\"append\", help=\"dictionary file (default: {})",
"argparser.add_argument(\"-c\", \"--configuration\", help=\"config file\") argparser.add_argument(\"-d\", \"--dictionary\", metavar=\"DICT\", action=\"append\", help=\"dictionary file",
"import ArgumentParser DICTIONARY = \"eng.dict\" MODEL = \"eng.zip\" LOGGING_FMT =",
"and populate archive (_, basename, _) = splitname(args.write) archive =",
"(c) 2011-2014 <NAME> and <NAME> # # Permission is hereby",
"driver for the module \"\"\" import logging import os import",
"TextGrids.\") size = MLF(aligned).write(args.align) if not size: logging.error(\"No paths found!\")",
"hack to allow proper override of default dictionary if not",
"TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION",
"you move the data if \"dictionary\" in opts: del opts[\"dictionary\"]",
"\"Software\"), to deal in the Software without restriction, including #",
"ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN",
"help=\"# of epochs of training per round\") input_group = argparser.add_argument_group()",
"software and associated documentation files (the # \"Software\"), to deal",
"COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR",
"\"\"\" Command-line driver for the module \"\"\" import logging import",
"= resolve_opts(args) # initialize aligner and set it to point",
"None)) else: if not args.read: args.read = MODEL logging.info(\"Reading aligner",
"permission notice shall be included # in all copies or",
"size = MLF(aligned).write(args.align) if not size: logging.error(\"No paths found!\") exit(1)",
"args.configuration = os.path.join(archive.dirname, CONFIG) opts = resolve_opts(args) # initialize aligner",
"or (os.path.realpath(args.train) != os.path.realpath(args.align)): logging.info(\"Preparing corpus '{}'.\".format(args.align)) corpus = Corpus(args.align,",
"args.samplerate = None # create archive from -r argument archive",
"the training data if (not args.train) or (os.path.realpath(args.train) != os.path.realpath(args.align)):",
"argument archive = Archive(args.read) # read configuration file therefrom, and",
"NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE",
"CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR",
"scores) logging.debug(\"Wrote MLF file to '{}'.\".format(aligned)) logging.debug(\"Wrote likelihood scores to",
"utilities import splitname, resolve_opts, \\ ALIGNED, CONFIG, HMMDEFS, MACROS, SCORES",
"args.read: logging.error(\"Cannot train on persistent model.\") exit(1) logging.info(\"Preparing corpus '{}'.\".format(args.train))",
"archive (_, basename, _) = splitname(args.write) archive = Archive.empty(basename) archive.add(os.path.join(aligner.curdir,",
"SCORES) aligner.align_and_score(corpus, aligned, scores) logging.debug(\"Wrote MLF file to '{}'.\".format(aligned)) logging.debug(\"Wrote",
"corpus = Corpus(args.train, opts) logging.info(\"Preparing aligner.\") aligner = Aligner(opts) logging.info(\"Training",
"found!\") exit(1) logging.debug(\"Wrote {} TextGrids.\".format(size)) elif args.write: # create and",
"whatever this is, it's not going to work once you",
"this permission notice shall be included # in all copies",
"deal in the Software without restriction, including # without limitation",
"IN THE SOFTWARE. \"\"\" Command-line driver for the module \"\"\"",
"round\") input_group = argparser.add_argument_group() input_group.add_argument(\"-r\", \"--read\", help=\"source for a precomputed",
"output_group = argparser.add_mutually_exclusive_group(required=True) output_group.add_argument(\"-a\", \"--align\", help=\"directory containing data to align\")",
"(default: {}) (can specify multiple)\".format(DICTIONARY)) argparser.add_argument(\"-s\", \"--samplerate\", type=int, help=\"analysis samplerate",
"not size: logging.error(\"No paths found!\") exit(1) logging.debug(\"Wrote {} TextGrids.\".format(size)) elif",
"align\") output_group.add_argument(\"-w\", \"--write\", help=\"destination for computed acoustic model\") verbosity_group =",
"Permission is hereby granted, free of charge, to any person",
"OTHER DEALINGS IN THE SOFTWARE. \"\"\" Command-line driver for the",
"sink: yaml.dump(opts, sink) (basename, _) = os.path.splitext(args.write) archive_path = os.path.relpath(archive.dump(basename))",
"archive_path = os.path.relpath(archive.dump(basename)) logging.info(\"Wrote aligner to '{}'.\".format(archive_path)) # else unreachable",
"(in Hz)\") argparser.add_argument(\"-e\", \"--epochs\", type=int, help=\"# of epochs of training",
"The above copyright notice and this permission notice shall be",
"INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY,",
"[DICTIONARY] # set up logging loglevel = logging.WARNING if args.extra_verbose:",
"a precomputed acoustic model\") input_group.add_argument(\"-t\", \"--train\", help=\"directory containing data for",
"import MLF from corpus import Corpus from aligner import Aligner",
"OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR",
"help=\"directory containing data to align\") output_group.add_argument(\"-w\", \"--write\", help=\"destination for computed",
"and <NAME> # # Permission is hereby granted, free of",
"= logging.DEBUG elif args.verbose: loglevel = logging.INFO logging.basicConfig(format=LOGGING_FMT, level=loglevel) #",
"if args.samplerate: logging.warning(\"Ignoring samplerate flag (-s/--samplerate).\") args.samplerate = None #",
"OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, #",
"aligner and set it to point to the archive data",
"# distribute, sublicense, and/or sell copies of the Software, and",
"Hz)\") argparser.add_argument(\"-e\", \"--epochs\", type=int, help=\"# of epochs of training per",
"args.dictionary = [DICTIONARY] # set up logging loglevel = logging.WARNING",
"shutil import copyfile from textgrid import MLF from corpus import",
"samplerate (in Hz)\") argparser.add_argument(\"-e\", \"--epochs\", type=int, help=\"# of epochs of",
"if args.epochs: logging.warning(\"Ignoring epochs flag (-e/--epochs).\") if args.samplerate: logging.warning(\"Ignoring samplerate",
"point to the archive data aligner = Aligner(opts) aligner.curdir ="
] |
[
"in init: if not line.strip(): continue line = line.strip().split('\\t') id_by_name[line[11]]",
"def memory_limit_from_int(ml): return str(ml // (1024 ** 2)) + '",
"\"\\\\begin{example}\" + samples +\"\\\\end{example}\\n\" + notes, problem_name + '.pdf', problem_name=problem_name)",
"logging import glob import json CONTEST_DIR = 'polygon-contest' INIT_FILE =",
"os.chdir(BUILD_DIR) logging.info('Compile problem %s' % problem_name) for _ in range(2):",
"name = properties['name'] legend = properties['legend'] input_file = properties['inputFile'] output_file",
"not line.strip(): continue line = line.strip().split('\\t') id_by_name[line[11]] = line[2] logging.basicConfig(level=logging.DEBUG,",
"properties['outputFile'] time_limit = time_limit_from_int(properties['timeLimit']) memory_limit = memory_limit_from_int(properties['memoryLimit']) input_format = properties['input']",
"file %s' % properties_file_name) with codecs.open(properties_file_name, 'r', 'utf-8') as properties_file:",
"as properties_file: properties = json.load(properties_file) name = properties['name'] legend =",
"properties['name'] legend = properties['legend'] input_file = properties['inputFile'] output_file = properties['outputFile']",
"data_file: data_file.write(text) cwd = os.getcwd() os.chdir(BUILD_DIR) logging.info('Compile problem %s' %",
"section='', problem_name=''): text = text.replace('%TEXT%', section + '\\n' + replace_data)",
"result, section='', problem_name=''): text = text.replace('%TEXT%', section + '\\n' +",
"= os.getcwd() os.chdir(BUILD_DIR) logging.info('Compile problem %s' % problem_name) for _",
"'utf-8') as properties_file: properties = json.load(properties_file) name = properties['name'] legend",
"= memory_limit_from_int(properties['memoryLimit']) input_format = properties['input'] output_format = properties['output'] samples =",
"= text.replace('%TEXT%', section + '\\n' + replace_data) with codecs.open(os.path.join(BUILD_DIR, 'data.tex'),",
"+ properties['notes'] shutil.copy('template.tex', os.path.join(BUILD_DIR, 'compile.tex')) shutil.copy('olymp.sty', os.path.join(BUILD_DIR, 'olymp.sty')) with codecs.open('data.tex',",
"= os.path.join(problem_dir, 'statements', LANGUAGE) properties_file_name = os.path.join(statement_dir, 'problem-properties.json') logging.info('Read problem",
"os.chdir(cwd) shutil.copy(os.path.join(BUILD_DIR, 'compile.pdf'), os.path.join(FILES_DIR, result)) def main(): id_by_name = {}",
"if not os.path.exists(FILES_DIR): logging.info('Create folder for output files: %s' %",
"enumerate(glob.glob(os.path.join(problems_dir, '*')), start=1): statement_dir = os.path.join(problem_dir, 'statements', LANGUAGE) properties_file_name =",
"problem properties file %s' % properties_file_name) with codecs.open(properties_file_name, 'r', 'utf-8')",
"folder for output files: %s' % FILES_DIR) os.mkdir(FILES_DIR) if not",
"+ \"\\\\begin{example}\" + samples +\"\\\\end{example}\\n\" + notes, problem_name + '.pdf',",
"= data_file.read() problem_name = os.path.basename(problem_dir) problem_id = id_by_name[problem_name] data =",
"+ LANGUAGE def time_limit_from_int(tl): tl //= 1000 return str(tl) +",
"'*')), start=1): statement_dir = os.path.join(problem_dir, 'statements', LANGUAGE) properties_file_name = os.path.join(statement_dir,",
"= data.replace('%NAME%', name).replace('%INPUT_FILE%', input_file).replace('%OUTPUT_FILE%', output_file).\\ replace('%TIME_LIMIT%', time_limit).replace('%MEMORY_LIMIT%', memory_limit).\\ replace('%ID%', problem_id).\\",
"'/') build_with_text(data, legend + '\\n\\\\InputFile\\n' + input_format + '\\n\\\\OutputFile\\n' +",
"shutil.copy('template.tex', os.path.join(BUILD_DIR, 'compile.tex')) shutil.copy('olymp.sty', os.path.join(BUILD_DIR, 'olymp.sty')) with codecs.open('data.tex', 'r', 'utf-8')",
"'' if len(properties.get('notes','')) > 0: notes = '\\\\Note\\n' + properties['notes']",
"output_file).\\ replace('%TIME_LIMIT%', time_limit).replace('%MEMORY_LIMIT%', memory_limit).\\ replace('%ID%', problem_id).\\ replace('%PROBLEM_COUNTER%', str(problem_counter)).\\ replace('%STATEMENT_DIR%', os.path.join('..',",
"= properties['input'] output_format = properties['output'] samples = \"\".join([\"\\exmp{%s}{%s}%%\\n\" % (sample['input'],",
"legend = properties['legend'] input_file = properties['inputFile'] output_file = properties['outputFile'] time_limit",
"os.path.join(problem_dir, 'statements', LANGUAGE) properties_file_name = os.path.join(statement_dir, 'problem-properties.json') logging.info('Read problem properties",
"data_file.write(text) cwd = os.getcwd() os.chdir(BUILD_DIR) logging.info('Compile problem %s' % problem_name)",
"+ '\\n\\\\InputFile\\n' + input_format + '\\n\\\\OutputFile\\n' + output_format + \"\\\\begin{example}\"",
"data.replace('%NAME%', name).replace('%INPUT_FILE%', input_file).replace('%OUTPUT_FILE%', output_file).\\ replace('%TIME_LIMIT%', time_limit).replace('%MEMORY_LIMIT%', memory_limit).\\ replace('%ID%', problem_id).\\ replace('%PROBLEM_COUNTER%',",
"legend + '\\n\\\\InputFile\\n' + input_format + '\\n\\\\OutputFile\\n' + output_format +",
"with codecs.open(properties_file_name, 'r', 'utf-8') as properties_file: properties = json.load(properties_file) name",
"glob import json CONTEST_DIR = 'polygon-contest' INIT_FILE = 'init.txt' BUILD_DIR",
"'utf-8') as data_file: data_file.write(text) cwd = os.getcwd() os.chdir(BUILD_DIR) logging.info('Compile problem",
"= '\\\\Note\\n' + properties['notes'] shutil.copy('template.tex', os.path.join(BUILD_DIR, 'compile.tex')) shutil.copy('olymp.sty', os.path.join(BUILD_DIR, 'olymp.sty'))",
"if not line.strip(): continue line = line.strip().split('\\t') id_by_name[line[11]] = line[2]",
"tl //= 1000 return str(tl) + ' секунд' + ('a'",
"codecs import os import os.path import shutil import subprocess import",
"= line.strip().split('\\t') id_by_name[line[11]] = line[2] logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(message)s') if",
"logging.info('Create folder for output files: %s' % FILES_DIR) os.mkdir(FILES_DIR) if",
"os.getcwd() os.chdir(BUILD_DIR) logging.info('Compile problem %s' % problem_name) for _ in",
"= 'russian' FILES_DIR = 'files-' + LANGUAGE def time_limit_from_int(tl): tl",
"os.path.exists(BUILD_DIR): logging.info('Create folder for build files: %s' % BUILD_DIR) os.mkdir(BUILD_DIR)",
"'statements', LANGUAGE) properties_file_name = os.path.join(statement_dir, 'problem-properties.json') logging.info('Read problem properties file",
"FILES_DIR) os.mkdir(FILES_DIR) if not os.path.exists(BUILD_DIR): logging.info('Create folder for build files:",
"def main(): id_by_name = {} with open(INIT_FILE, 'r', encoding='utf-8') as",
"= properties['inputFile'] output_file = properties['outputFile'] time_limit = time_limit_from_int(properties['timeLimit']) memory_limit =",
"= properties['legend'] input_file = properties['inputFile'] output_file = properties['outputFile'] time_limit =",
"properties_file_name = os.path.join(statement_dir, 'problem-properties.json') logging.info('Read problem properties file %s' %",
"1 else 'ы') def memory_limit_from_int(ml): return str(ml // (1024 **",
"\"\".join([\"\\exmp{%s}{%s}%%\\n\" % (sample['input'], sample['output']) for sample in properties['sampleTests']]) notes =",
"os.path.join(FILES_DIR, result)) def main(): id_by_name = {} with open(INIT_FILE, 'r',",
"INIT_FILE = 'init.txt' BUILD_DIR = 'build' LANGUAGE = 'russian' FILES_DIR",
"files: %s' % FILES_DIR) os.mkdir(FILES_DIR) if not os.path.exists(BUILD_DIR): logging.info('Create folder",
"for sample in properties['sampleTests']]) notes = '' if len(properties.get('notes','')) >",
"'problem-properties.json') logging.info('Read problem properties file %s' % properties_file_name) with codecs.open(properties_file_name,",
"import logging import glob import json CONTEST_DIR = 'polygon-contest' INIT_FILE",
"def time_limit_from_int(tl): tl //= 1000 return str(tl) + ' секунд'",
"init: for line in init: if not line.strip(): continue line",
"'build' LANGUAGE = 'russian' FILES_DIR = 'files-' + LANGUAGE def",
"for build files: %s' % BUILD_DIR) os.mkdir(BUILD_DIR) problems_dir = os.path.join(CONTEST_DIR,",
"os.path.join(statement_dir, 'problem-properties.json') logging.info('Read problem properties file %s' % properties_file_name) with",
"+ replace_data) with codecs.open(os.path.join(BUILD_DIR, 'data.tex'), 'w', 'utf-8') as data_file: data_file.write(text)",
"'r', 'utf-8') as properties_file: properties = json.load(properties_file) name = properties['name']",
"(sample['input'], sample['output']) for sample in properties['sampleTests']]) notes = '' if",
"name).replace('%INPUT_FILE%', input_file).replace('%OUTPUT_FILE%', output_file).\\ replace('%TIME_LIMIT%', time_limit).replace('%MEMORY_LIMIT%', memory_limit).\\ replace('%ID%', problem_id).\\ replace('%PROBLEM_COUNTER%', str(problem_counter)).\\",
"data_file: data = data_file.read() problem_name = os.path.basename(problem_dir) problem_id = id_by_name[problem_name]",
"+ '\\n' + replace_data) with codecs.open(os.path.join(BUILD_DIR, 'data.tex'), 'w', 'utf-8') as",
"+ '/') build_with_text(data, legend + '\\n\\\\InputFile\\n' + input_format + '\\n\\\\OutputFile\\n'",
"+ samples +\"\\\\end{example}\\n\" + notes, problem_name + '.pdf', problem_name=problem_name) if",
"+ notes, problem_name + '.pdf', problem_name=problem_name) if __name__ == '__main__':",
"problem_name = os.path.basename(problem_dir) problem_id = id_by_name[problem_name] data = data.replace('%NAME%', name).replace('%INPUT_FILE%',",
"in range(2): subprocess.check_output(['pdflatex', 'compile.tex']) os.chdir(cwd) shutil.copy(os.path.join(BUILD_DIR, 'compile.pdf'), os.path.join(FILES_DIR, result)) def",
"CONTEST_DIR = 'polygon-contest' INIT_FILE = 'init.txt' BUILD_DIR = 'build' LANGUAGE",
"def build_with_text(text, replace_data, result, section='', problem_name=''): text = text.replace('%TEXT%', section",
"= \"\".join([\"\\exmp{%s}{%s}%%\\n\" % (sample['input'], sample['output']) for sample in properties['sampleTests']]) notes",
"for problem_counter, problem_dir in enumerate(glob.glob(os.path.join(problems_dir, '*')), start=1): statement_dir = os.path.join(problem_dir,",
"import glob import json CONTEST_DIR = 'polygon-contest' INIT_FILE = 'init.txt'",
"as data_file: data = data_file.read() problem_name = os.path.basename(problem_dir) problem_id =",
"[%(levelname)s] %(message)s') if not os.path.exists(FILES_DIR): logging.info('Create folder for output files:",
"problem %s' % problem_name) for _ in range(2): subprocess.check_output(['pdflatex', 'compile.tex'])",
"properties['sampleTests']]) notes = '' if len(properties.get('notes','')) > 0: notes =",
"files: %s' % BUILD_DIR) os.mkdir(BUILD_DIR) problems_dir = os.path.join(CONTEST_DIR, 'problems') for",
"%s' % problem_name) for _ in range(2): subprocess.check_output(['pdflatex', 'compile.tex']) os.chdir(cwd)",
"id_by_name[line[11]] = line[2] logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(message)s') if not os.path.exists(FILES_DIR):",
"import os.path import shutil import subprocess import logging import glob",
"%s' % properties_file_name) with codecs.open(properties_file_name, 'r', 'utf-8') as properties_file: properties",
"'ы') def memory_limit_from_int(ml): return str(ml // (1024 ** 2)) +",
"str(ml // (1024 ** 2)) + ' мегабайт' def build_with_text(text,",
"replace('%STATEMENT_DIR%', os.path.join('..', statement_dir).replace('\\\\', '/') + '/') build_with_text(data, legend + '\\n\\\\InputFile\\n'",
"= 'build' LANGUAGE = 'russian' FILES_DIR = 'files-' + LANGUAGE",
"return str(tl) + ' секунд' + ('a' if tl ==",
"== 1 else 'ы') def memory_limit_from_int(ml): return str(ml // (1024",
"'\\n\\\\InputFile\\n' + input_format + '\\n\\\\OutputFile\\n' + output_format + \"\\\\begin{example}\" +",
"line in init: if not line.strip(): continue line = line.strip().split('\\t')",
"line.strip().split('\\t') id_by_name[line[11]] = line[2] logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(message)s') if not",
"'r', 'utf-8') as data_file: data = data_file.read() problem_name = os.path.basename(problem_dir)",
"BUILD_DIR = 'build' LANGUAGE = 'russian' FILES_DIR = 'files-' +",
"> 0: notes = '\\\\Note\\n' + properties['notes'] shutil.copy('template.tex', os.path.join(BUILD_DIR, 'compile.tex'))",
"= 'init.txt' BUILD_DIR = 'build' LANGUAGE = 'russian' FILES_DIR =",
"%s' % FILES_DIR) os.mkdir(FILES_DIR) if not os.path.exists(BUILD_DIR): logging.info('Create folder for",
"subprocess import logging import glob import json CONTEST_DIR = 'polygon-contest'",
"section + '\\n' + replace_data) with codecs.open(os.path.join(BUILD_DIR, 'data.tex'), 'w', 'utf-8')",
"replace('%TIME_LIMIT%', time_limit).replace('%MEMORY_LIMIT%', memory_limit).\\ replace('%ID%', problem_id).\\ replace('%PROBLEM_COUNTER%', str(problem_counter)).\\ replace('%STATEMENT_DIR%', os.path.join('..', statement_dir).replace('\\\\',",
"'olymp.sty')) with codecs.open('data.tex', 'r', 'utf-8') as data_file: data = data_file.read()",
"'problems') for problem_counter, problem_dir in enumerate(glob.glob(os.path.join(problems_dir, '*')), start=1): statement_dir =",
"//= 1000 return str(tl) + ' секунд' + ('a' if",
"+ ('a' if tl == 1 else 'ы') def memory_limit_from_int(ml):",
"if tl == 1 else 'ы') def memory_limit_from_int(ml): return str(ml",
"samples = \"\".join([\"\\exmp{%s}{%s}%%\\n\" % (sample['input'], sample['output']) for sample in properties['sampleTests']])",
"input_format + '\\n\\\\OutputFile\\n' + output_format + \"\\\\begin{example}\" + samples +\"\\\\end{example}\\n\"",
"+ output_format + \"\\\\begin{example}\" + samples +\"\\\\end{example}\\n\" + notes, problem_name",
"format='%(asctime)s [%(levelname)s] %(message)s') if not os.path.exists(FILES_DIR): logging.info('Create folder for output",
"output_format + \"\\\\begin{example}\" + samples +\"\\\\end{example}\\n\" + notes, problem_name +",
"1000 return str(tl) + ' секунд' + ('a' if tl",
"str(tl) + ' секунд' + ('a' if tl == 1",
"('a' if tl == 1 else 'ы') def memory_limit_from_int(ml): return",
"cwd = os.getcwd() os.chdir(BUILD_DIR) logging.info('Compile problem %s' % problem_name) for",
"range(2): subprocess.check_output(['pdflatex', 'compile.tex']) os.chdir(cwd) shutil.copy(os.path.join(BUILD_DIR, 'compile.pdf'), os.path.join(FILES_DIR, result)) def main():",
"'compile.pdf'), os.path.join(FILES_DIR, result)) def main(): id_by_name = {} with open(INIT_FILE,",
"for line in init: if not line.strip(): continue line =",
"str(problem_counter)).\\ replace('%STATEMENT_DIR%', os.path.join('..', statement_dir).replace('\\\\', '/') + '/') build_with_text(data, legend +",
"+ '\\n\\\\OutputFile\\n' + output_format + \"\\\\begin{example}\" + samples +\"\\\\end{example}\\n\" +",
"% problem_name) for _ in range(2): subprocess.check_output(['pdflatex', 'compile.tex']) os.chdir(cwd) shutil.copy(os.path.join(BUILD_DIR,",
"<reponame>andgein/sis-2017-winter-olymp<filename>init/build_statements.py #!/usr/bin/env python3 import codecs import os import os.path import",
"not os.path.exists(BUILD_DIR): logging.info('Create folder for build files: %s' % BUILD_DIR)",
"os.path.join(BUILD_DIR, 'olymp.sty')) with codecs.open('data.tex', 'r', 'utf-8') as data_file: data =",
"+\"\\\\end{example}\\n\" + notes, problem_name + '.pdf', problem_name=problem_name) if __name__ ==",
"'\\n' + replace_data) with codecs.open(os.path.join(BUILD_DIR, 'data.tex'), 'w', 'utf-8') as data_file:",
"os.mkdir(BUILD_DIR) problems_dir = os.path.join(CONTEST_DIR, 'problems') for problem_counter, problem_dir in enumerate(glob.glob(os.path.join(problems_dir,",
"logging.info('Compile problem %s' % problem_name) for _ in range(2): subprocess.check_output(['pdflatex',",
"'\\\\Note\\n' + properties['notes'] shutil.copy('template.tex', os.path.join(BUILD_DIR, 'compile.tex')) shutil.copy('olymp.sty', os.path.join(BUILD_DIR, 'olymp.sty')) with",
"% BUILD_DIR) os.mkdir(BUILD_DIR) problems_dir = os.path.join(CONTEST_DIR, 'problems') for problem_counter, problem_dir",
"= properties['outputFile'] time_limit = time_limit_from_int(properties['timeLimit']) memory_limit = memory_limit_from_int(properties['memoryLimit']) input_format =",
"' мегабайт' def build_with_text(text, replace_data, result, section='', problem_name=''): text =",
"input_file).replace('%OUTPUT_FILE%', output_file).\\ replace('%TIME_LIMIT%', time_limit).replace('%MEMORY_LIMIT%', memory_limit).\\ replace('%ID%', problem_id).\\ replace('%PROBLEM_COUNTER%', str(problem_counter)).\\ replace('%STATEMENT_DIR%',",
"memory_limit = memory_limit_from_int(properties['memoryLimit']) input_format = properties['input'] output_format = properties['output'] samples",
"{} with open(INIT_FILE, 'r', encoding='utf-8') as init: for line in",
"notes, problem_name + '.pdf', problem_name=problem_name) if __name__ == '__main__': main()",
"tl == 1 else 'ы') def memory_limit_from_int(ml): return str(ml //",
"not os.path.exists(FILES_DIR): logging.info('Create folder for output files: %s' % FILES_DIR)",
"memory_limit_from_int(properties['memoryLimit']) input_format = properties['input'] output_format = properties['output'] samples = \"\".join([\"\\exmp{%s}{%s}%%\\n\"",
"memory_limit).\\ replace('%ID%', problem_id).\\ replace('%PROBLEM_COUNTER%', str(problem_counter)).\\ replace('%STATEMENT_DIR%', os.path.join('..', statement_dir).replace('\\\\', '/') +",
"notes = '\\\\Note\\n' + properties['notes'] shutil.copy('template.tex', os.path.join(BUILD_DIR, 'compile.tex')) shutil.copy('olymp.sty', os.path.join(BUILD_DIR,",
"os.path.basename(problem_dir) problem_id = id_by_name[problem_name] data = data.replace('%NAME%', name).replace('%INPUT_FILE%', input_file).replace('%OUTPUT_FILE%', output_file).\\",
"line[2] logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(message)s') if not os.path.exists(FILES_DIR): logging.info('Create folder",
"replace_data, result, section='', problem_name=''): text = text.replace('%TEXT%', section + '\\n'",
"problem_counter, problem_dir in enumerate(glob.glob(os.path.join(problems_dir, '*')), start=1): statement_dir = os.path.join(problem_dir, 'statements',",
"properties['legend'] input_file = properties['inputFile'] output_file = properties['outputFile'] time_limit = time_limit_from_int(properties['timeLimit'])",
"notes = '' if len(properties.get('notes','')) > 0: notes = '\\\\Note\\n'",
"properties['input'] output_format = properties['output'] samples = \"\".join([\"\\exmp{%s}{%s}%%\\n\" % (sample['input'], sample['output'])",
"= id_by_name[problem_name] data = data.replace('%NAME%', name).replace('%INPUT_FILE%', input_file).replace('%OUTPUT_FILE%', output_file).\\ replace('%TIME_LIMIT%', time_limit).replace('%MEMORY_LIMIT%',",
"problem_name=''): text = text.replace('%TEXT%', section + '\\n' + replace_data) with",
"in enumerate(glob.glob(os.path.join(problems_dir, '*')), start=1): statement_dir = os.path.join(problem_dir, 'statements', LANGUAGE) properties_file_name",
"shutil import subprocess import logging import glob import json CONTEST_DIR",
"'utf-8') as data_file: data = data_file.read() problem_name = os.path.basename(problem_dir) problem_id",
"'/') + '/') build_with_text(data, legend + '\\n\\\\InputFile\\n' + input_format +",
"os import os.path import shutil import subprocess import logging import",
"codecs.open('data.tex', 'r', 'utf-8') as data_file: data = data_file.read() problem_name =",
"os.path import shutil import subprocess import logging import glob import",
"'files-' + LANGUAGE def time_limit_from_int(tl): tl //= 1000 return str(tl)",
"'r', encoding='utf-8') as init: for line in init: if not",
"data_file.read() problem_name = os.path.basename(problem_dir) problem_id = id_by_name[problem_name] data = data.replace('%NAME%',",
"id_by_name = {} with open(INIT_FILE, 'r', encoding='utf-8') as init: for",
"= 'polygon-contest' INIT_FILE = 'init.txt' BUILD_DIR = 'build' LANGUAGE =",
"+ ' мегабайт' def build_with_text(text, replace_data, result, section='', problem_name=''): text",
"%(message)s') if not os.path.exists(FILES_DIR): logging.info('Create folder for output files: %s'",
"start=1): statement_dir = os.path.join(problem_dir, 'statements', LANGUAGE) properties_file_name = os.path.join(statement_dir, 'problem-properties.json')",
"(1024 ** 2)) + ' мегабайт' def build_with_text(text, replace_data, result,",
"samples +\"\\\\end{example}\\n\" + notes, problem_name + '.pdf', problem_name=problem_name) if __name__",
"'data.tex'), 'w', 'utf-8') as data_file: data_file.write(text) cwd = os.getcwd() os.chdir(BUILD_DIR)",
"folder for build files: %s' % BUILD_DIR) os.mkdir(BUILD_DIR) problems_dir =",
"data = data_file.read() problem_name = os.path.basename(problem_dir) problem_id = id_by_name[problem_name] data",
"replace_data) with codecs.open(os.path.join(BUILD_DIR, 'data.tex'), 'w', 'utf-8') as data_file: data_file.write(text) cwd",
"properties_file_name) with codecs.open(properties_file_name, 'r', 'utf-8') as properties_file: properties = json.load(properties_file)",
"with codecs.open(os.path.join(BUILD_DIR, 'data.tex'), 'w', 'utf-8') as data_file: data_file.write(text) cwd =",
"continue line = line.strip().split('\\t') id_by_name[line[11]] = line[2] logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s]",
"= '' if len(properties.get('notes','')) > 0: notes = '\\\\Note\\n' +",
"shutil.copy('olymp.sty', os.path.join(BUILD_DIR, 'olymp.sty')) with codecs.open('data.tex', 'r', 'utf-8') as data_file: data",
"output files: %s' % FILES_DIR) os.mkdir(FILES_DIR) if not os.path.exists(BUILD_DIR): logging.info('Create",
"os.path.join(BUILD_DIR, 'compile.tex')) shutil.copy('olymp.sty', os.path.join(BUILD_DIR, 'olymp.sty')) with codecs.open('data.tex', 'r', 'utf-8') as",
"import subprocess import logging import glob import json CONTEST_DIR =",
"input_file = properties['inputFile'] output_file = properties['outputFile'] time_limit = time_limit_from_int(properties['timeLimit']) memory_limit",
"мегабайт' def build_with_text(text, replace_data, result, section='', problem_name=''): text = text.replace('%TEXT%',",
"memory_limit_from_int(ml): return str(ml // (1024 ** 2)) + ' мегабайт'",
"open(INIT_FILE, 'r', encoding='utf-8') as init: for line in init: if",
"'compile.tex')) shutil.copy('olymp.sty', os.path.join(BUILD_DIR, 'olymp.sty')) with codecs.open('data.tex', 'r', 'utf-8') as data_file:",
"time_limit = time_limit_from_int(properties['timeLimit']) memory_limit = memory_limit_from_int(properties['memoryLimit']) input_format = properties['input'] output_format",
"import shutil import subprocess import logging import glob import json",
"BUILD_DIR) os.mkdir(BUILD_DIR) problems_dir = os.path.join(CONTEST_DIR, 'problems') for problem_counter, problem_dir in",
"%s' % BUILD_DIR) os.mkdir(BUILD_DIR) problems_dir = os.path.join(CONTEST_DIR, 'problems') for problem_counter,",
"problem_id).\\ replace('%PROBLEM_COUNTER%', str(problem_counter)).\\ replace('%STATEMENT_DIR%', os.path.join('..', statement_dir).replace('\\\\', '/') + '/') build_with_text(data,",
"shutil.copy(os.path.join(BUILD_DIR, 'compile.pdf'), os.path.join(FILES_DIR, result)) def main(): id_by_name = {} with",
"'compile.tex']) os.chdir(cwd) shutil.copy(os.path.join(BUILD_DIR, 'compile.pdf'), os.path.join(FILES_DIR, result)) def main(): id_by_name =",
"= json.load(properties_file) name = properties['name'] legend = properties['legend'] input_file =",
"text.replace('%TEXT%', section + '\\n' + replace_data) with codecs.open(os.path.join(BUILD_DIR, 'data.tex'), 'w',",
"import json CONTEST_DIR = 'polygon-contest' INIT_FILE = 'init.txt' BUILD_DIR =",
"sample in properties['sampleTests']]) notes = '' if len(properties.get('notes','')) > 0:",
"codecs.open(os.path.join(BUILD_DIR, 'data.tex'), 'w', 'utf-8') as data_file: data_file.write(text) cwd = os.getcwd()",
"init: if not line.strip(): continue line = line.strip().split('\\t') id_by_name[line[11]] =",
"input_format = properties['input'] output_format = properties['output'] samples = \"\".join([\"\\exmp{%s}{%s}%%\\n\" %",
"os.path.join(CONTEST_DIR, 'problems') for problem_counter, problem_dir in enumerate(glob.glob(os.path.join(problems_dir, '*')), start=1): statement_dir",
"= time_limit_from_int(properties['timeLimit']) memory_limit = memory_limit_from_int(properties['memoryLimit']) input_format = properties['input'] output_format =",
"if len(properties.get('notes','')) > 0: notes = '\\\\Note\\n' + properties['notes'] shutil.copy('template.tex',",
"replace('%PROBLEM_COUNTER%', str(problem_counter)).\\ replace('%STATEMENT_DIR%', os.path.join('..', statement_dir).replace('\\\\', '/') + '/') build_with_text(data, legend",
"in properties['sampleTests']]) notes = '' if len(properties.get('notes','')) > 0: notes",
"output_file = properties['outputFile'] time_limit = time_limit_from_int(properties['timeLimit']) memory_limit = memory_limit_from_int(properties['memoryLimit']) input_format",
"data = data.replace('%NAME%', name).replace('%INPUT_FILE%', input_file).replace('%OUTPUT_FILE%', output_file).\\ replace('%TIME_LIMIT%', time_limit).replace('%MEMORY_LIMIT%', memory_limit).\\ replace('%ID%',",
"id_by_name[problem_name] data = data.replace('%NAME%', name).replace('%INPUT_FILE%', input_file).replace('%OUTPUT_FILE%', output_file).\\ replace('%TIME_LIMIT%', time_limit).replace('%MEMORY_LIMIT%', memory_limit).\\",
"sample['output']) for sample in properties['sampleTests']]) notes = '' if len(properties.get('notes',''))",
"% (sample['input'], sample['output']) for sample in properties['sampleTests']]) notes = ''",
"replace('%ID%', problem_id).\\ replace('%PROBLEM_COUNTER%', str(problem_counter)).\\ replace('%STATEMENT_DIR%', os.path.join('..', statement_dir).replace('\\\\', '/') + '/')",
"// (1024 ** 2)) + ' мегабайт' def build_with_text(text, replace_data,",
"text = text.replace('%TEXT%', section + '\\n' + replace_data) with codecs.open(os.path.join(BUILD_DIR,",
"subprocess.check_output(['pdflatex', 'compile.tex']) os.chdir(cwd) shutil.copy(os.path.join(BUILD_DIR, 'compile.pdf'), os.path.join(FILES_DIR, result)) def main(): id_by_name",
"properties_file: properties = json.load(properties_file) name = properties['name'] legend = properties['legend']",
"LANGUAGE = 'russian' FILES_DIR = 'files-' + LANGUAGE def time_limit_from_int(tl):",
"len(properties.get('notes','')) > 0: notes = '\\\\Note\\n' + properties['notes'] shutil.copy('template.tex', os.path.join(BUILD_DIR,",
"json.load(properties_file) name = properties['name'] legend = properties['legend'] input_file = properties['inputFile']",
"= os.path.basename(problem_dir) problem_id = id_by_name[problem_name] data = data.replace('%NAME%', name).replace('%INPUT_FILE%', input_file).replace('%OUTPUT_FILE%',",
"'w', 'utf-8') as data_file: data_file.write(text) cwd = os.getcwd() os.chdir(BUILD_DIR) logging.info('Compile",
"FILES_DIR = 'files-' + LANGUAGE def time_limit_from_int(tl): tl //= 1000",
"properties['output'] samples = \"\".join([\"\\exmp{%s}{%s}%%\\n\" % (sample['input'], sample['output']) for sample in",
"line = line.strip().split('\\t') id_by_name[line[11]] = line[2] logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(message)s')",
"problem_name) for _ in range(2): subprocess.check_output(['pdflatex', 'compile.tex']) os.chdir(cwd) shutil.copy(os.path.join(BUILD_DIR, 'compile.pdf'),",
"= os.path.join(statement_dir, 'problem-properties.json') logging.info('Read problem properties file %s' % properties_file_name)",
"% properties_file_name) with codecs.open(properties_file_name, 'r', 'utf-8') as properties_file: properties =",
"logging.info('Create folder for build files: %s' % BUILD_DIR) os.mkdir(BUILD_DIR) problems_dir",
"= properties['output'] samples = \"\".join([\"\\exmp{%s}{%s}%%\\n\" % (sample['input'], sample['output']) for sample",
"build_with_text(data, legend + '\\n\\\\InputFile\\n' + input_format + '\\n\\\\OutputFile\\n' + output_format",
"+ input_format + '\\n\\\\OutputFile\\n' + output_format + \"\\\\begin{example}\" + samples",
"секунд' + ('a' if tl == 1 else 'ы') def",
"with open(INIT_FILE, 'r', encoding='utf-8') as init: for line in init:",
"line.strip(): continue line = line.strip().split('\\t') id_by_name[line[11]] = line[2] logging.basicConfig(level=logging.DEBUG, format='%(asctime)s",
"'\\n\\\\OutputFile\\n' + output_format + \"\\\\begin{example}\" + samples +\"\\\\end{example}\\n\" + notes,",
"build_with_text(text, replace_data, result, section='', problem_name=''): text = text.replace('%TEXT%', section +",
"import os import os.path import shutil import subprocess import logging",
"time_limit_from_int(tl): tl //= 1000 return str(tl) + ' секунд' +",
"result)) def main(): id_by_name = {} with open(INIT_FILE, 'r', encoding='utf-8')",
"= 'files-' + LANGUAGE def time_limit_from_int(tl): tl //= 1000 return",
"main(): id_by_name = {} with open(INIT_FILE, 'r', encoding='utf-8') as init:",
"% FILES_DIR) os.mkdir(FILES_DIR) if not os.path.exists(BUILD_DIR): logging.info('Create folder for build",
"LANGUAGE) properties_file_name = os.path.join(statement_dir, 'problem-properties.json') logging.info('Read problem properties file %s'",
"logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(message)s') if not os.path.exists(FILES_DIR): logging.info('Create folder for",
"+ ' секунд' + ('a' if tl == 1 else",
"problems_dir = os.path.join(CONTEST_DIR, 'problems') for problem_counter, problem_dir in enumerate(glob.glob(os.path.join(problems_dir, '*')),",
"os.mkdir(FILES_DIR) if not os.path.exists(BUILD_DIR): logging.info('Create folder for build files: %s'",
"build files: %s' % BUILD_DIR) os.mkdir(BUILD_DIR) problems_dir = os.path.join(CONTEST_DIR, 'problems')",
"'init.txt' BUILD_DIR = 'build' LANGUAGE = 'russian' FILES_DIR = 'files-'",
"= {} with open(INIT_FILE, 'r', encoding='utf-8') as init: for line",
"as init: for line in init: if not line.strip(): continue",
"0: notes = '\\\\Note\\n' + properties['notes'] shutil.copy('template.tex', os.path.join(BUILD_DIR, 'compile.tex')) shutil.copy('olymp.sty',",
"properties['notes'] shutil.copy('template.tex', os.path.join(BUILD_DIR, 'compile.tex')) shutil.copy('olymp.sty', os.path.join(BUILD_DIR, 'olymp.sty')) with codecs.open('data.tex', 'r',",
"python3 import codecs import os import os.path import shutil import",
"for _ in range(2): subprocess.check_output(['pdflatex', 'compile.tex']) os.chdir(cwd) shutil.copy(os.path.join(BUILD_DIR, 'compile.pdf'), os.path.join(FILES_DIR,",
"properties file %s' % properties_file_name) with codecs.open(properties_file_name, 'r', 'utf-8') as",
"time_limit_from_int(properties['timeLimit']) memory_limit = memory_limit_from_int(properties['memoryLimit']) input_format = properties['input'] output_format = properties['output']",
"logging.info('Read problem properties file %s' % properties_file_name) with codecs.open(properties_file_name, 'r',",
"os.path.exists(FILES_DIR): logging.info('Create folder for output files: %s' % FILES_DIR) os.mkdir(FILES_DIR)",
"statement_dir = os.path.join(problem_dir, 'statements', LANGUAGE) properties_file_name = os.path.join(statement_dir, 'problem-properties.json') logging.info('Read",
"'russian' FILES_DIR = 'files-' + LANGUAGE def time_limit_from_int(tl): tl //=",
"if not os.path.exists(BUILD_DIR): logging.info('Create folder for build files: %s' %",
"= line[2] logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(message)s') if not os.path.exists(FILES_DIR): logging.info('Create",
"for output files: %s' % FILES_DIR) os.mkdir(FILES_DIR) if not os.path.exists(BUILD_DIR):",
"= os.path.join(CONTEST_DIR, 'problems') for problem_counter, problem_dir in enumerate(glob.glob(os.path.join(problems_dir, '*')), start=1):",
"'polygon-contest' INIT_FILE = 'init.txt' BUILD_DIR = 'build' LANGUAGE = 'russian'",
"problem_dir in enumerate(glob.glob(os.path.join(problems_dir, '*')), start=1): statement_dir = os.path.join(problem_dir, 'statements', LANGUAGE)",
"codecs.open(properties_file_name, 'r', 'utf-8') as properties_file: properties = json.load(properties_file) name =",
"return str(ml // (1024 ** 2)) + ' мегабайт' def",
"properties = json.load(properties_file) name = properties['name'] legend = properties['legend'] input_file",
"= properties['name'] legend = properties['legend'] input_file = properties['inputFile'] output_file =",
"#!/usr/bin/env python3 import codecs import os import os.path import shutil",
"else 'ы') def memory_limit_from_int(ml): return str(ml // (1024 ** 2))",
"** 2)) + ' мегабайт' def build_with_text(text, replace_data, result, section='',",
"2)) + ' мегабайт' def build_with_text(text, replace_data, result, section='', problem_name=''):",
"import codecs import os import os.path import shutil import subprocess",
"_ in range(2): subprocess.check_output(['pdflatex', 'compile.tex']) os.chdir(cwd) shutil.copy(os.path.join(BUILD_DIR, 'compile.pdf'), os.path.join(FILES_DIR, result))",
"encoding='utf-8') as init: for line in init: if not line.strip():",
"with codecs.open('data.tex', 'r', 'utf-8') as data_file: data = data_file.read() problem_name",
"json CONTEST_DIR = 'polygon-contest' INIT_FILE = 'init.txt' BUILD_DIR = 'build'",
"LANGUAGE def time_limit_from_int(tl): tl //= 1000 return str(tl) + '",
"problem_id = id_by_name[problem_name] data = data.replace('%NAME%', name).replace('%INPUT_FILE%', input_file).replace('%OUTPUT_FILE%', output_file).\\ replace('%TIME_LIMIT%',",
"properties['inputFile'] output_file = properties['outputFile'] time_limit = time_limit_from_int(properties['timeLimit']) memory_limit = memory_limit_from_int(properties['memoryLimit'])",
"os.path.join('..', statement_dir).replace('\\\\', '/') + '/') build_with_text(data, legend + '\\n\\\\InputFile\\n' +",
"statement_dir).replace('\\\\', '/') + '/') build_with_text(data, legend + '\\n\\\\InputFile\\n' + input_format",
"output_format = properties['output'] samples = \"\".join([\"\\exmp{%s}{%s}%%\\n\" % (sample['input'], sample['output']) for",
"time_limit).replace('%MEMORY_LIMIT%', memory_limit).\\ replace('%ID%', problem_id).\\ replace('%PROBLEM_COUNTER%', str(problem_counter)).\\ replace('%STATEMENT_DIR%', os.path.join('..', statement_dir).replace('\\\\', '/')",
"as data_file: data_file.write(text) cwd = os.getcwd() os.chdir(BUILD_DIR) logging.info('Compile problem %s'",
"' секунд' + ('a' if tl == 1 else 'ы')"
] |
[
"# from conans import python_requires import conans.tools as tools import",
"generators = \"cmake\" settings = \"os\", \"arch\" requires = ()",
"= () def config_options(self): del self.options.python2_version del self.options.python3_version def package_id(self):",
"\"https://github.com/jrl-umi3218/mc_rtc_data\" homepage = \"https://github.com/jrl-umi3218/mc_rtc_data\" author = \"<NAME> <<EMAIL>>\" license =",
"\"local_setup.bash\", \"setup.sh\", \"local_setup.sh\", \"setup.zsh\", \"local_setup.zsh\", \".rosinstall\"]: p = os.path.join(self.package_folder, f)",
"class MCRTCDataConan(base.Eigen3ToPythonConan): name = \"mc_rtc_data\" version = \"1.0.4\" description =",
"\"setup.bash\", \"local_setup.bash\", \"setup.sh\", \"local_setup.sh\", \"setup.zsh\", \"local_setup.zsh\", \".rosinstall\"]: p = os.path.join(self.package_folder,",
"name = \"mc_rtc_data\" version = \"1.0.4\" description = \"Environments/Robots description",
"= \"https://github.com/jrl-umi3218/mc_rtc_data\" author = \"<NAME> <<EMAIL>>\" license = \"BSD-2-Clause\" exports",
"\"pkgconfig\")) for f in [\".catkin\", \"_setup_util.py\", \"env.sh\", \"setup.bash\", \"local_setup.bash\", \"setup.sh\",",
"= \"mc_rtc_data\" version = \"1.0.4\" description = \"Environments/Robots description for",
"exports = [\"LICENSE\"] exports_sources = [\"CMakeLists.txt\", \"conan/CMakeLists.txt\", \"cmake/*\", \"jvrc_description/*\", \"mc_env_description/*\",",
"[\"LICENSE\"] exports_sources = [\"CMakeLists.txt\", \"conan/CMakeLists.txt\", \"cmake/*\", \"jvrc_description/*\", \"mc_env_description/*\", \"mc_int_obj_description/*\", \"mc_rtc_data/*\"]",
"tools.rmdir(os.path.join(self.package_folder, \"lib\", \"pkgconfig\")) for f in [\".catkin\", \"_setup_util.py\", \"env.sh\", \"setup.bash\",",
"\"<NAME> <<EMAIL>>\" license = \"BSD-2-Clause\" exports = [\"LICENSE\"] exports_sources =",
"\"mc_env_description/*\", \"mc_int_obj_description/*\", \"mc_rtc_data/*\"] generators = \"cmake\" settings = \"os\", \"arch\"",
"\"cmake\" settings = \"os\", \"arch\" requires = () def config_options(self):",
"= \"1.0.4\" description = \"Environments/Robots description for mc_rtc\" topics =",
"\"jvrc_description/*\", \"mc_env_description/*\", \"mc_int_obj_description/*\", \"mc_rtc_data/*\"] generators = \"cmake\" settings = \"os\",",
"= self._configure_cmake() cmake.install() tools.rmdir(os.path.join(self.package_folder, \"lib\", \"pkgconfig\")) for f in [\".catkin\",",
"in [\".catkin\", \"_setup_util.py\", \"env.sh\", \"setup.bash\", \"local_setup.bash\", \"setup.sh\", \"local_setup.sh\", \"setup.zsh\", \"local_setup.zsh\",",
"\"https://github.com/jrl-umi3218/mc_rtc_data\" author = \"<NAME> <<EMAIL>>\" license = \"BSD-2-Clause\" exports =",
"del self.options.python3_version def package_id(self): pass def package(self): cmake = self._configure_cmake()",
"def package_id(self): pass def package(self): cmake = self._configure_cmake() cmake.install() tools.rmdir(os.path.join(self.package_folder,",
"as tools import os base = python_requires(\"Eigen3ToPython/latest@multi-contact/dev\") class MCRTCDataConan(base.Eigen3ToPythonConan): name",
"package(self): cmake = self._configure_cmake() cmake.install() tools.rmdir(os.path.join(self.package_folder, \"lib\", \"pkgconfig\")) for f",
"self.options.python2_version del self.options.python3_version def package_id(self): pass def package(self): cmake =",
"import os base = python_requires(\"Eigen3ToPython/latest@multi-contact/dev\") class MCRTCDataConan(base.Eigen3ToPythonConan): name = \"mc_rtc_data\"",
"import conans.tools as tools import os base = python_requires(\"Eigen3ToPython/latest@multi-contact/dev\") class",
"() def config_options(self): del self.options.python2_version del self.options.python3_version def package_id(self): pass",
"os base = python_requires(\"Eigen3ToPython/latest@multi-contact/dev\") class MCRTCDataConan(base.Eigen3ToPythonConan): name = \"mc_rtc_data\" version",
"mc_rtc\" topics = (\"robotics\", \"data\") url = \"https://github.com/jrl-umi3218/mc_rtc_data\" homepage =",
"\"local_setup.sh\", \"setup.zsh\", \"local_setup.zsh\", \".rosinstall\"]: p = os.path.join(self.package_folder, f) if os.path.exists(p):",
"package_id(self): pass def package(self): cmake = self._configure_cmake() cmake.install() tools.rmdir(os.path.join(self.package_folder, \"lib\",",
"= [\"CMakeLists.txt\", \"conan/CMakeLists.txt\", \"cmake/*\", \"jvrc_description/*\", \"mc_env_description/*\", \"mc_int_obj_description/*\", \"mc_rtc_data/*\"] generators =",
"\"setup.zsh\", \"local_setup.zsh\", \".rosinstall\"]: p = os.path.join(self.package_folder, f) if os.path.exists(p): os.remove(p)",
"\"arch\" requires = () def config_options(self): del self.options.python2_version del self.options.python3_version",
"= \"os\", \"arch\" requires = () def config_options(self): del self.options.python2_version",
"= \"Environments/Robots description for mc_rtc\" topics = (\"robotics\", \"data\") url",
"# -*- coding: utf-8 -*- # from conans import python_requires",
"\"data\") url = \"https://github.com/jrl-umi3218/mc_rtc_data\" homepage = \"https://github.com/jrl-umi3218/mc_rtc_data\" author = \"<NAME>",
"description for mc_rtc\" topics = (\"robotics\", \"data\") url = \"https://github.com/jrl-umi3218/mc_rtc_data\"",
"= \"https://github.com/jrl-umi3218/mc_rtc_data\" homepage = \"https://github.com/jrl-umi3218/mc_rtc_data\" author = \"<NAME> <<EMAIL>>\" license",
"del self.options.python2_version del self.options.python3_version def package_id(self): pass def package(self): cmake",
"(\"robotics\", \"data\") url = \"https://github.com/jrl-umi3218/mc_rtc_data\" homepage = \"https://github.com/jrl-umi3218/mc_rtc_data\" author =",
"homepage = \"https://github.com/jrl-umi3218/mc_rtc_data\" author = \"<NAME> <<EMAIL>>\" license = \"BSD-2-Clause\"",
"author = \"<NAME> <<EMAIL>>\" license = \"BSD-2-Clause\" exports = [\"LICENSE\"]",
"\"env.sh\", \"setup.bash\", \"local_setup.bash\", \"setup.sh\", \"local_setup.sh\", \"setup.zsh\", \"local_setup.zsh\", \".rosinstall\"]: p =",
"description = \"Environments/Robots description for mc_rtc\" topics = (\"robotics\", \"data\")",
"coding: utf-8 -*- # from conans import python_requires import conans.tools",
"for mc_rtc\" topics = (\"robotics\", \"data\") url = \"https://github.com/jrl-umi3218/mc_rtc_data\" homepage",
"base = python_requires(\"Eigen3ToPython/latest@multi-contact/dev\") class MCRTCDataConan(base.Eigen3ToPythonConan): name = \"mc_rtc_data\" version =",
"cmake.install() tools.rmdir(os.path.join(self.package_folder, \"lib\", \"pkgconfig\")) for f in [\".catkin\", \"_setup_util.py\", \"env.sh\",",
"-*- # from conans import python_requires import conans.tools as tools",
"requires = () def config_options(self): del self.options.python2_version del self.options.python3_version def",
"\"mc_rtc_data\" version = \"1.0.4\" description = \"Environments/Robots description for mc_rtc\"",
"self.options.python3_version def package_id(self): pass def package(self): cmake = self._configure_cmake() cmake.install()",
"from conans import python_requires import conans.tools as tools import os",
"tools import os base = python_requires(\"Eigen3ToPython/latest@multi-contact/dev\") class MCRTCDataConan(base.Eigen3ToPythonConan): name =",
"topics = (\"robotics\", \"data\") url = \"https://github.com/jrl-umi3218/mc_rtc_data\" homepage = \"https://github.com/jrl-umi3218/mc_rtc_data\"",
"python_requires import conans.tools as tools import os base = python_requires(\"Eigen3ToPython/latest@multi-contact/dev\")",
"= [\"LICENSE\"] exports_sources = [\"CMakeLists.txt\", \"conan/CMakeLists.txt\", \"cmake/*\", \"jvrc_description/*\", \"mc_env_description/*\", \"mc_int_obj_description/*\",",
"= python_requires(\"Eigen3ToPython/latest@multi-contact/dev\") class MCRTCDataConan(base.Eigen3ToPythonConan): name = \"mc_rtc_data\" version = \"1.0.4\"",
"f in [\".catkin\", \"_setup_util.py\", \"env.sh\", \"setup.bash\", \"local_setup.bash\", \"setup.sh\", \"local_setup.sh\", \"setup.zsh\",",
"import python_requires import conans.tools as tools import os base =",
"self._configure_cmake() cmake.install() tools.rmdir(os.path.join(self.package_folder, \"lib\", \"pkgconfig\")) for f in [\".catkin\", \"_setup_util.py\",",
"\"1.0.4\" description = \"Environments/Robots description for mc_rtc\" topics = (\"robotics\",",
"cmake = self._configure_cmake() cmake.install() tools.rmdir(os.path.join(self.package_folder, \"lib\", \"pkgconfig\")) for f in",
"exports_sources = [\"CMakeLists.txt\", \"conan/CMakeLists.txt\", \"cmake/*\", \"jvrc_description/*\", \"mc_env_description/*\", \"mc_int_obj_description/*\", \"mc_rtc_data/*\"] generators",
"= \"BSD-2-Clause\" exports = [\"LICENSE\"] exports_sources = [\"CMakeLists.txt\", \"conan/CMakeLists.txt\", \"cmake/*\",",
"= (\"robotics\", \"data\") url = \"https://github.com/jrl-umi3218/mc_rtc_data\" homepage = \"https://github.com/jrl-umi3218/mc_rtc_data\" author",
"\"mc_rtc_data/*\"] generators = \"cmake\" settings = \"os\", \"arch\" requires =",
"license = \"BSD-2-Clause\" exports = [\"LICENSE\"] exports_sources = [\"CMakeLists.txt\", \"conan/CMakeLists.txt\",",
"\"_setup_util.py\", \"env.sh\", \"setup.bash\", \"local_setup.bash\", \"setup.sh\", \"local_setup.sh\", \"setup.zsh\", \"local_setup.zsh\", \".rosinstall\"]: p",
"version = \"1.0.4\" description = \"Environments/Robots description for mc_rtc\" topics",
"MCRTCDataConan(base.Eigen3ToPythonConan): name = \"mc_rtc_data\" version = \"1.0.4\" description = \"Environments/Robots",
"\"cmake/*\", \"jvrc_description/*\", \"mc_env_description/*\", \"mc_int_obj_description/*\", \"mc_rtc_data/*\"] generators = \"cmake\" settings =",
"config_options(self): del self.options.python2_version del self.options.python3_version def package_id(self): pass def package(self):",
"\"os\", \"arch\" requires = () def config_options(self): del self.options.python2_version del",
"= \"cmake\" settings = \"os\", \"arch\" requires = () def",
"\"BSD-2-Clause\" exports = [\"LICENSE\"] exports_sources = [\"CMakeLists.txt\", \"conan/CMakeLists.txt\", \"cmake/*\", \"jvrc_description/*\",",
"def package(self): cmake = self._configure_cmake() cmake.install() tools.rmdir(os.path.join(self.package_folder, \"lib\", \"pkgconfig\")) for",
"utf-8 -*- # from conans import python_requires import conans.tools as",
"pass def package(self): cmake = self._configure_cmake() cmake.install() tools.rmdir(os.path.join(self.package_folder, \"lib\", \"pkgconfig\"))",
"conans import python_requires import conans.tools as tools import os base",
"conans.tools as tools import os base = python_requires(\"Eigen3ToPython/latest@multi-contact/dev\") class MCRTCDataConan(base.Eigen3ToPythonConan):",
"settings = \"os\", \"arch\" requires = () def config_options(self): del",
"\"lib\", \"pkgconfig\")) for f in [\".catkin\", \"_setup_util.py\", \"env.sh\", \"setup.bash\", \"local_setup.bash\",",
"= \"<NAME> <<EMAIL>>\" license = \"BSD-2-Clause\" exports = [\"LICENSE\"] exports_sources",
"for f in [\".catkin\", \"_setup_util.py\", \"env.sh\", \"setup.bash\", \"local_setup.bash\", \"setup.sh\", \"local_setup.sh\",",
"[\".catkin\", \"_setup_util.py\", \"env.sh\", \"setup.bash\", \"local_setup.bash\", \"setup.sh\", \"local_setup.sh\", \"setup.zsh\", \"local_setup.zsh\", \".rosinstall\"]:",
"\"conan/CMakeLists.txt\", \"cmake/*\", \"jvrc_description/*\", \"mc_env_description/*\", \"mc_int_obj_description/*\", \"mc_rtc_data/*\"] generators = \"cmake\" settings",
"python_requires(\"Eigen3ToPython/latest@multi-contact/dev\") class MCRTCDataConan(base.Eigen3ToPythonConan): name = \"mc_rtc_data\" version = \"1.0.4\" description",
"<<EMAIL>>\" license = \"BSD-2-Clause\" exports = [\"LICENSE\"] exports_sources = [\"CMakeLists.txt\",",
"url = \"https://github.com/jrl-umi3218/mc_rtc_data\" homepage = \"https://github.com/jrl-umi3218/mc_rtc_data\" author = \"<NAME> <<EMAIL>>\"",
"\"mc_int_obj_description/*\", \"mc_rtc_data/*\"] generators = \"cmake\" settings = \"os\", \"arch\" requires",
"def config_options(self): del self.options.python2_version del self.options.python3_version def package_id(self): pass def",
"[\"CMakeLists.txt\", \"conan/CMakeLists.txt\", \"cmake/*\", \"jvrc_description/*\", \"mc_env_description/*\", \"mc_int_obj_description/*\", \"mc_rtc_data/*\"] generators = \"cmake\"",
"-*- coding: utf-8 -*- # from conans import python_requires import",
"\"Environments/Robots description for mc_rtc\" topics = (\"robotics\", \"data\") url =",
"\"setup.sh\", \"local_setup.sh\", \"setup.zsh\", \"local_setup.zsh\", \".rosinstall\"]: p = os.path.join(self.package_folder, f) if"
] |
[
"('hyperion', '0005_auto_20190212_2116'), ] operations = [ migrations.RenameField( model_name='post', old_name='visibleTo', new_name='visible_to',",
"from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies",
"dependencies = [ ('hyperion', '0005_auto_20190212_2116'), ] operations = [ migrations.RenameField(",
"model_name='post', name='content_type', field=models.CharField(choices=[('1', 'text/plain'), ('2', 'text/markdown'), ('3', 'image/png;base64'), ('4', 'image/jpeg;base64'),",
"max_length=1), ), migrations.AlterField( model_name='comment', name='author', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='hyperion.UserProfile'), ), ]",
"# Generated by Django 2.1.5 on 2019-02-18 22:51 from django.db",
"default='1', max_length=1), ), migrations.AddField( model_name='post', name='visibility', field=models.CharField(choices=[('1', 'PUBLIC'), ('2', 'FOAF'),",
"name='visibility', field=models.CharField(choices=[('1', 'PUBLIC'), ('2', 'FOAF'), ('3', 'FRIENDS'), ('4', 'PRIVATE'), ('5',",
"name='content_type', field=models.CharField(choices=[('1', 'text/plain'), ('2', 'text/markdown'), ('3', 'image/png;base64'), ('4', 'image/jpeg;base64'), ('5',",
"= [ migrations.RenameField( model_name='post', old_name='visibleTo', new_name='visible_to', ), migrations.AddField( model_name='post', name='content_type',",
"= [ ('hyperion', '0005_auto_20190212_2116'), ] operations = [ migrations.RenameField( model_name='post',",
"migrations.AddField( model_name='post', name='content_type', field=models.CharField(choices=[('1', 'text/plain'), ('2', 'text/markdown'), ('3', 'image/png;base64'), ('4',",
"'image/png;base64'), ('4', 'image/jpeg;base64'), ('5', 'application/base64')], default='1', max_length=1), ), migrations.AddField( model_name='post',",
"('4', 'image/jpeg;base64'), ('5', 'application/base64')], default='1', max_length=1), ), migrations.AddField( model_name='post', name='visibility',",
"field=models.CharField(choices=[('1', 'text/plain'), ('2', 'text/markdown'), ('3', 'image/png;base64'), ('4', 'image/jpeg;base64'), ('5', 'application/base64')],",
"'PRIVATE'), ('5', 'SERVERONLY')], default='1', max_length=1), ), migrations.AlterField( model_name='comment', name='author', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,",
"('5', 'application/base64')], default='1', max_length=1), ), migrations.AddField( model_name='post', name='visibility', field=models.CharField(choices=[('1', 'PUBLIC'),",
"22:51 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):",
"class Migration(migrations.Migration): dependencies = [ ('hyperion', '0005_auto_20190212_2116'), ] operations =",
"[ ('hyperion', '0005_auto_20190212_2116'), ] operations = [ migrations.RenameField( model_name='post', old_name='visibleTo',",
"('5', 'SERVERONLY')], default='1', max_length=1), ), migrations.AlterField( model_name='comment', name='author', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments',",
"), migrations.AddField( model_name='post', name='content_type', field=models.CharField(choices=[('1', 'text/plain'), ('2', 'text/markdown'), ('3', 'image/png;base64'),",
"'FOAF'), ('3', 'FRIENDS'), ('4', 'PRIVATE'), ('5', 'SERVERONLY')], default='1', max_length=1), ),",
"Django 2.1.5 on 2019-02-18 22:51 from django.db import migrations, models",
"django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('hyperion', '0005_auto_20190212_2116'), ] operations",
"import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('hyperion', '0005_auto_20190212_2116'), ]",
"('3', 'FRIENDS'), ('4', 'PRIVATE'), ('5', 'SERVERONLY')], default='1', max_length=1), ), migrations.AlterField(",
"'0005_auto_20190212_2116'), ] operations = [ migrations.RenameField( model_name='post', old_name='visibleTo', new_name='visible_to', ),",
"migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('hyperion',",
"), migrations.AddField( model_name='post', name='visibility', field=models.CharField(choices=[('1', 'PUBLIC'), ('2', 'FOAF'), ('3', 'FRIENDS'),",
"Generated by Django 2.1.5 on 2019-02-18 22:51 from django.db import",
"<filename>hyperion/migrations/0006_auto_20190218_2251.py # Generated by Django 2.1.5 on 2019-02-18 22:51 from",
"on 2019-02-18 22:51 from django.db import migrations, models import django.db.models.deletion",
"'application/base64')], default='1', max_length=1), ), migrations.AddField( model_name='post', name='visibility', field=models.CharField(choices=[('1', 'PUBLIC'), ('2',",
"'SERVERONLY')], default='1', max_length=1), ), migrations.AlterField( model_name='comment', name='author', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='hyperion.UserProfile'),",
"migrations.AddField( model_name='post', name='visibility', field=models.CharField(choices=[('1', 'PUBLIC'), ('2', 'FOAF'), ('3', 'FRIENDS'), ('4',",
"2019-02-18 22:51 from django.db import migrations, models import django.db.models.deletion class",
"models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('hyperion', '0005_auto_20190212_2116'),",
"new_name='visible_to', ), migrations.AddField( model_name='post', name='content_type', field=models.CharField(choices=[('1', 'text/plain'), ('2', 'text/markdown'), ('3',",
"django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies =",
"model_name='post', old_name='visibleTo', new_name='visible_to', ), migrations.AddField( model_name='post', name='content_type', field=models.CharField(choices=[('1', 'text/plain'), ('2',",
"max_length=1), ), migrations.AddField( model_name='post', name='visibility', field=models.CharField(choices=[('1', 'PUBLIC'), ('2', 'FOAF'), ('3',",
"import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [",
"Migration(migrations.Migration): dependencies = [ ('hyperion', '0005_auto_20190212_2116'), ] operations = [",
"field=models.CharField(choices=[('1', 'PUBLIC'), ('2', 'FOAF'), ('3', 'FRIENDS'), ('4', 'PRIVATE'), ('5', 'SERVERONLY')],",
"('4', 'PRIVATE'), ('5', 'SERVERONLY')], default='1', max_length=1), ), migrations.AlterField( model_name='comment', name='author',",
"('2', 'text/markdown'), ('3', 'image/png;base64'), ('4', 'image/jpeg;base64'), ('5', 'application/base64')], default='1', max_length=1),",
"default='1', max_length=1), ), migrations.AlterField( model_name='comment', name='author', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='hyperion.UserProfile'), ),",
"2.1.5 on 2019-02-18 22:51 from django.db import migrations, models import",
"'PUBLIC'), ('2', 'FOAF'), ('3', 'FRIENDS'), ('4', 'PRIVATE'), ('5', 'SERVERONLY')], default='1',",
"] operations = [ migrations.RenameField( model_name='post', old_name='visibleTo', new_name='visible_to', ), migrations.AddField(",
"migrations.RenameField( model_name='post', old_name='visibleTo', new_name='visible_to', ), migrations.AddField( model_name='post', name='content_type', field=models.CharField(choices=[('1', 'text/plain'),",
"'text/markdown'), ('3', 'image/png;base64'), ('4', 'image/jpeg;base64'), ('5', 'application/base64')], default='1', max_length=1), ),",
"('3', 'image/png;base64'), ('4', 'image/jpeg;base64'), ('5', 'application/base64')], default='1', max_length=1), ), migrations.AddField(",
"by Django 2.1.5 on 2019-02-18 22:51 from django.db import migrations,",
"'image/jpeg;base64'), ('5', 'application/base64')], default='1', max_length=1), ), migrations.AddField( model_name='post', name='visibility', field=models.CharField(choices=[('1',",
"model_name='post', name='visibility', field=models.CharField(choices=[('1', 'PUBLIC'), ('2', 'FOAF'), ('3', 'FRIENDS'), ('4', 'PRIVATE'),",
"('2', 'FOAF'), ('3', 'FRIENDS'), ('4', 'PRIVATE'), ('5', 'SERVERONLY')], default='1', max_length=1),",
"'FRIENDS'), ('4', 'PRIVATE'), ('5', 'SERVERONLY')], default='1', max_length=1), ), migrations.AlterField( model_name='comment',",
"operations = [ migrations.RenameField( model_name='post', old_name='visibleTo', new_name='visible_to', ), migrations.AddField( model_name='post',",
"old_name='visibleTo', new_name='visible_to', ), migrations.AddField( model_name='post', name='content_type', field=models.CharField(choices=[('1', 'text/plain'), ('2', 'text/markdown'),",
"[ migrations.RenameField( model_name='post', old_name='visibleTo', new_name='visible_to', ), migrations.AddField( model_name='post', name='content_type', field=models.CharField(choices=[('1',",
"'text/plain'), ('2', 'text/markdown'), ('3', 'image/png;base64'), ('4', 'image/jpeg;base64'), ('5', 'application/base64')], default='1',"
] |
[
"reset(self): self.n_count = 0 self.sum = 0 def val(self): res",
"% opt.crnn) if( opt.cuda ): stateDict = torch.load(opt.crnn ) else:",
"readYaml( fname ): with myOpen(fname, 'r') as fp: return yaml.load(",
"version. It will save the data as module.<xyz> . Handle",
"Handle it if( list( stateDict.keys() )[0][:7] == 'module.' ): for",
"+= v def reset(self): self.n_count = 0 self.sum = 0",
"= 0 if self.n_count != 0: res = self.sum /",
"some old torch version. It will save the data as",
"stateDict[ key[ 7:] ] = stateDict[key] del stateDict[ key ]",
"== '.gz' else ( open, 'r' ) with opener( fname,",
"key ] model.load_state_dict( stateDict ) print('Completed loading pre trained model')",
"== 'module.' ): for key in list(stateDict.keys()): stateDict[ key[ 7:]",
"fname, data ): with myOpen( fname, 'w') as outfile: json.dump(data,",
"the data as module.<xyz> . Handle it if( list( stateDict.keys()",
"as f: return json.load( f ) def writeFile( fname, contents",
"with myOpen( fname, 'w') as outfile: json.dump(data, outfile) def readYaml(",
"fname, mode, encoding=\"utf-8\" ) def readFile( fname ): opener, mode",
"opener( fname, mode ) as f: return f.read() def readLines(",
"return split('[\\r\\n]', readFile( fname ) ) def readJson( fname ):",
"data ): with myOpen( fname, 'w') as outfile: json.dump(data, outfile)",
"a pretrained model into given model\"\"\" print('loading pretrained model from",
"= ( gzip.open, 'rt' ) if fname[-3:] == '.gz' else",
"pyplot.imshow( im ) pyplot.show() def myOpen( fname, mode ): return",
"from %s' % opt.crnn) if( opt.cuda ): stateDict = torch.load(opt.crnn",
"as outfile: json.dump(data, outfile) def readYaml( fname ): with myOpen(fname,",
"'r' ) as f: return json.load( f ) def writeFile(",
"into given model\"\"\" print('loading pretrained model from %s' % opt.crnn)",
"\"\"\"Compute average for `torch.Variable` and `torch.Tensor`. \"\"\" def __init__(self): self.reset()",
"myOpen( fname, 'w' ) as f: f.write( contents ) def",
"fp: return yaml.load( fp ) config = readYaml('./config.yaml') class averager(object):",
"= v.data.sum() elif isinstance(v, torch.Tensor): count = v.numel() v =",
"def reset(self): self.n_count = 0 self.sum = 0 def val(self):",
"torch.load(opt.crnn, map_location={'cuda:0': 'cpu'} ) # Handle the case of some",
"gzip import yaml from re import split from matplotlib import",
"if( opt.cuda ): stateDict = torch.load(opt.crnn ) else: stateDict =",
"count self.sum += v def reset(self): self.n_count = 0 self.sum",
"isinstance(v, Variable): count = v.data.numel() v = v.data.sum() elif isinstance(v,",
"+= count self.sum += v def reset(self): self.n_count = 0",
"np from torch.autograd import Variable import gzip import yaml from",
"def loadTrainedModel( model, opt ): \"\"\"Load a pretrained model into",
"fname ): return split('[\\r\\n]', readFile( fname ) ) def readJson(",
"with myOpen(fname, 'r') as fp: return yaml.load( fp ) config",
"add(self, v): if isinstance(v, Variable): count = v.data.numel() v =",
")[0][:7] == 'module.' ): for key in list(stateDict.keys()): stateDict[ key[",
"as f: f.write( contents ) def writeJson( fname, data ):",
"contents ) def writeJson( fname, data ): with myOpen( fname,",
"old torch version. It will save the data as module.<xyz>",
"open, 'r' ) with opener( fname, mode ) as f:",
"'w') as outfile: json.dump(data, outfile) def readYaml( fname ): with",
"%s' % opt.crnn) if( opt.cuda ): stateDict = torch.load(opt.crnn )",
"self.n_count = 0 self.sum = 0 def val(self): res =",
"myOpen( fname, mode ): return open( fname, mode, encoding=\"utf-8\" )",
"if self.n_count != 0: res = self.sum / float(self.n_count) return",
"myOpen( fname, 'r' ) as f: return json.load( f )",
"opt.cuda ): stateDict = torch.load(opt.crnn ) else: stateDict = torch.load(opt.crnn,",
"contents ): with myOpen( fname, 'w' ) as f: f.write(",
"fname, 'w' ) as f: f.write( contents ) def writeJson(",
"from re import split from matplotlib import pyplot def showImg(",
"res def loadTrainedModel( model, opt ): \"\"\"Load a pretrained model",
"0 def val(self): res = 0 if self.n_count != 0:",
"torch import json import numpy as np from torch.autograd import",
"else: stateDict = torch.load(opt.crnn, map_location={'cuda:0': 'cpu'} ) # Handle the",
"def readFile( fname ): opener, mode = ( gzip.open, 'rt'",
"import Variable import gzip import yaml from re import split",
"open( fname, mode, encoding=\"utf-8\" ) def readFile( fname ): opener,",
"= stateDict[key] del stateDict[ key ] model.load_state_dict( stateDict ) print('Completed",
"= readYaml('./config.yaml') class averager(object): \"\"\"Compute average for `torch.Variable` and `torch.Tensor`.",
"import yaml from re import split from matplotlib import pyplot",
"config = readYaml('./config.yaml') class averager(object): \"\"\"Compute average for `torch.Variable` and",
"fp ) config = readYaml('./config.yaml') class averager(object): \"\"\"Compute average for",
") else: stateDict = torch.load(opt.crnn, map_location={'cuda:0': 'cpu'} ) # Handle",
"stateDict = torch.load(opt.crnn, map_location={'cuda:0': 'cpu'} ) # Handle the case",
"res = 0 if self.n_count != 0: res = self.sum",
"= torch.load(opt.crnn, map_location={'cuda:0': 'cpu'} ) # Handle the case of",
"): return open( fname, mode, encoding=\"utf-8\" ) def readFile( fname",
"v.sum() self.n_count += count self.sum += v def reset(self): self.n_count",
"it if( list( stateDict.keys() )[0][:7] == 'module.' ): for key",
"yaml.load( fp ) config = readYaml('./config.yaml') class averager(object): \"\"\"Compute average",
"!= 0: res = self.sum / float(self.n_count) return res def",
") ) def readJson( fname ): with myOpen( fname, 'r'",
"fname, 'w') as outfile: json.dump(data, outfile) def readYaml( fname ):",
"): with myOpen(fname, 'r') as fp: return yaml.load( fp )",
"return res def loadTrainedModel( model, opt ): \"\"\"Load a pretrained",
"else ( open, 'r' ) with opener( fname, mode )",
"0 self.sum = 0 def val(self): res = 0 if",
"import gzip import yaml from re import split from matplotlib",
"averager(object): \"\"\"Compute average for `torch.Variable` and `torch.Tensor`. \"\"\" def __init__(self):",
"float(self.n_count) return res def loadTrainedModel( model, opt ): \"\"\"Load a",
"torch.autograd import Variable import gzip import yaml from re import",
"torch version. It will save the data as module.<xyz> .",
"in list(stateDict.keys()): stateDict[ key[ 7:] ] = stateDict[key] del stateDict[",
"model, opt ): \"\"\"Load a pretrained model into given model\"\"\"",
") as f: f.write( contents ) def writeJson( fname, data",
"myOpen( fname, 'w') as outfile: json.dump(data, outfile) def readYaml( fname",
"as module.<xyz> . Handle it if( list( stateDict.keys() )[0][:7] ==",
"of some old torch version. It will save the data",
"= 0 def val(self): res = 0 if self.n_count !=",
"key[ 7:] ] = stateDict[key] del stateDict[ key ] model.load_state_dict(",
"v = v.data.sum() elif isinstance(v, torch.Tensor): count = v.numel() v",
"'cpu'} ) # Handle the case of some old torch",
"f: return json.load( f ) def writeFile( fname, contents ):",
"for key in list(stateDict.keys()): stateDict[ key[ 7:] ] = stateDict[key]",
"): return split('[\\r\\n]', readFile( fname ) ) def readJson( fname",
"import numpy as np from torch.autograd import Variable import gzip",
") pyplot.show() def myOpen( fname, mode ): return open( fname,",
"def writeFile( fname, contents ): with myOpen( fname, 'w' )",
"writeJson( fname, data ): with myOpen( fname, 'w') as outfile:",
"fname ): with myOpen(fname, 'r') as fp: return yaml.load( fp",
"Handle the case of some old torch version. It will",
"f.read() def readLines( fname ): return split('[\\r\\n]', readFile( fname )",
"): for key in list(stateDict.keys()): stateDict[ key[ 7:] ] =",
"0 if self.n_count != 0: res = self.sum / float(self.n_count)",
"f: f.write( contents ) def writeJson( fname, data ): with",
"readFile( fname ) ) def readJson( fname ): with myOpen(",
"stateDict[ key ] model.load_state_dict( stateDict ) print('Completed loading pre trained",
"outfile) def readYaml( fname ): with myOpen(fname, 'r') as fp:",
"'module.' ): for key in list(stateDict.keys()): stateDict[ key[ 7:] ]",
") # Handle the case of some old torch version.",
"case of some old torch version. It will save the",
"'w' ) as f: f.write( contents ) def writeJson( fname,",
") with opener( fname, mode ) as f: return f.read()",
"0: res = self.sum / float(self.n_count) return res def loadTrainedModel(",
"\"\"\" def __init__(self): self.reset() def add(self, v): if isinstance(v, Variable):",
"from torch.autograd import Variable import gzip import yaml from re",
"f ) def writeFile( fname, contents ): with myOpen( fname,",
"numpy as np from torch.autograd import Variable import gzip import",
") config = readYaml('./config.yaml') class averager(object): \"\"\"Compute average for `torch.Variable`",
"def add(self, v): if isinstance(v, Variable): count = v.data.numel() v",
"v def reset(self): self.n_count = 0 self.sum = 0 def",
"val(self): res = 0 if self.n_count != 0: res =",
"/ float(self.n_count) return res def loadTrainedModel( model, opt ): \"\"\"Load",
"from matplotlib import pyplot def showImg( im ): pyplot.imshow( im",
"pretrained model into given model\"\"\" print('loading pretrained model from %s'",
"stateDict[key] del stateDict[ key ] model.load_state_dict( stateDict ) print('Completed loading",
"return json.load( f ) def writeFile( fname, contents ): with",
"module.<xyz> . Handle it if( list( stateDict.keys() )[0][:7] == 'module.'",
"save the data as module.<xyz> . Handle it if( list(",
"im ): pyplot.imshow( im ) pyplot.show() def myOpen( fname, mode",
"): pyplot.imshow( im ) pyplot.show() def myOpen( fname, mode ):",
"def val(self): res = 0 if self.n_count != 0: res",
"encoding=\"utf-8\" ) def readFile( fname ): opener, mode = (",
"import split from matplotlib import pyplot def showImg( im ):",
"): with myOpen( fname, 'w' ) as f: f.write( contents",
"def readLines( fname ): return split('[\\r\\n]', readFile( fname ) )",
"self.sum / float(self.n_count) return res def loadTrainedModel( model, opt ):",
"f.write( contents ) def writeJson( fname, data ): with myOpen(",
"def __init__(self): self.reset() def add(self, v): if isinstance(v, Variable): count",
"): \"\"\"Load a pretrained model into given model\"\"\" print('loading pretrained",
"writeFile( fname, contents ): with myOpen( fname, 'w' ) as",
"v.data.numel() v = v.data.sum() elif isinstance(v, torch.Tensor): count = v.numel()",
"It will save the data as module.<xyz> . Handle it",
"v): if isinstance(v, Variable): count = v.data.numel() v = v.data.sum()",
"as np from torch.autograd import Variable import gzip import yaml",
"list(stateDict.keys()): stateDict[ key[ 7:] ] = stateDict[key] del stateDict[ key",
"): opener, mode = ( gzip.open, 'rt' ) if fname[-3:]",
"= self.sum / float(self.n_count) return res def loadTrainedModel( model, opt",
"showImg( im ): pyplot.imshow( im ) pyplot.show() def myOpen( fname,",
"readJson( fname ): with myOpen( fname, 'r' ) as f:",
"if isinstance(v, Variable): count = v.data.numel() v = v.data.sum() elif",
"fname ): with myOpen( fname, 'r' ) as f: return",
"self.n_count != 0: res = self.sum / float(self.n_count) return res",
"for `torch.Variable` and `torch.Tensor`. \"\"\" def __init__(self): self.reset() def add(self,",
"mode ) as f: return f.read() def readLines( fname ):",
"return f.read() def readLines( fname ): return split('[\\r\\n]', readFile( fname",
"opt.crnn) if( opt.cuda ): stateDict = torch.load(opt.crnn ) else: stateDict",
"print('loading pretrained model from %s' % opt.crnn) if( opt.cuda ):",
"return open( fname, mode, encoding=\"utf-8\" ) def readFile( fname ):",
"fname, mode ): return open( fname, mode, encoding=\"utf-8\" ) def",
"'.gz' else ( open, 'r' ) with opener( fname, mode",
"mode, encoding=\"utf-8\" ) def readFile( fname ): opener, mode =",
"f: return f.read() def readLines( fname ): return split('[\\r\\n]', readFile(",
"as f: return f.read() def readLines( fname ): return split('[\\r\\n]',",
"readLines( fname ): return split('[\\r\\n]', readFile( fname ) ) def",
"): with myOpen( fname, 'w') as outfile: json.dump(data, outfile) def",
"class averager(object): \"\"\"Compute average for `torch.Variable` and `torch.Tensor`. \"\"\" def",
"isinstance(v, torch.Tensor): count = v.numel() v = v.sum() self.n_count +=",
") as f: return json.load( f ) def writeFile( fname,",
"self.reset() def add(self, v): if isinstance(v, Variable): count = v.data.numel()",
"myOpen(fname, 'r') as fp: return yaml.load( fp ) config =",
"pyplot.show() def myOpen( fname, mode ): return open( fname, mode,",
"): stateDict = torch.load(opt.crnn ) else: stateDict = torch.load(opt.crnn, map_location={'cuda:0':",
"fname ) ) def readJson( fname ): with myOpen( fname,",
"stateDict = torch.load(opt.crnn ) else: stateDict = torch.load(opt.crnn, map_location={'cuda:0': 'cpu'}",
"7:] ] = stateDict[key] del stateDict[ key ] model.load_state_dict( stateDict",
"] = stateDict[key] del stateDict[ key ] model.load_state_dict( stateDict )",
") def readFile( fname ): opener, mode = ( gzip.open,",
"torch.load(opt.crnn ) else: stateDict = torch.load(opt.crnn, map_location={'cuda:0': 'cpu'} ) #",
"self.sum = 0 def val(self): res = 0 if self.n_count",
"`torch.Tensor`. \"\"\" def __init__(self): self.reset() def add(self, v): if isinstance(v,",
"opener, mode = ( gzip.open, 'rt' ) if fname[-3:] ==",
"matplotlib import pyplot def showImg( im ): pyplot.imshow( im )",
"map_location={'cuda:0': 'cpu'} ) # Handle the case of some old",
"the case of some old torch version. It will save",
"= torch.load(opt.crnn ) else: stateDict = torch.load(opt.crnn, map_location={'cuda:0': 'cpu'} )",
". Handle it if( list( stateDict.keys() )[0][:7] == 'module.' ):",
"will save the data as module.<xyz> . Handle it if(",
"stateDict.keys() )[0][:7] == 'module.' ): for key in list(stateDict.keys()): stateDict[",
"= 0 self.sum = 0 def val(self): res = 0",
"fname, mode ) as f: return f.read() def readLines( fname",
"del stateDict[ key ] model.load_state_dict( stateDict ) print('Completed loading pre",
") if fname[-3:] == '.gz' else ( open, 'r' )",
"def myOpen( fname, mode ): return open( fname, mode, encoding=\"utf-8\"",
") def writeJson( fname, data ): with myOpen( fname, 'w')",
"json import numpy as np from torch.autograd import Variable import",
"outfile: json.dump(data, outfile) def readYaml( fname ): with myOpen(fname, 'r')",
"import json import numpy as np from torch.autograd import Variable",
"with myOpen( fname, 'w' ) as f: f.write( contents )",
") def writeFile( fname, contents ): with myOpen( fname, 'w'",
"def writeJson( fname, data ): with myOpen( fname, 'w') as",
"self.sum += v def reset(self): self.n_count = 0 self.sum =",
"self.n_count += count self.sum += v def reset(self): self.n_count =",
"key in list(stateDict.keys()): stateDict[ key[ 7:] ] = stateDict[key] del",
"= v.sum() self.n_count += count self.sum += v def reset(self):",
"= v.numel() v = v.sum() self.n_count += count self.sum +=",
"data as module.<xyz> . Handle it if( list( stateDict.keys() )[0][:7]",
"Variable import gzip import yaml from re import split from",
"'rt' ) if fname[-3:] == '.gz' else ( open, 'r'",
"json.load( f ) def writeFile( fname, contents ): with myOpen(",
"): with myOpen( fname, 'r' ) as f: return json.load(",
"as fp: return yaml.load( fp ) config = readYaml('./config.yaml') class",
"given model\"\"\" print('loading pretrained model from %s' % opt.crnn) if(",
"# Handle the case of some old torch version. It",
"`torch.Variable` and `torch.Tensor`. \"\"\" def __init__(self): self.reset() def add(self, v):",
"model from %s' % opt.crnn) if( opt.cuda ): stateDict =",
"def showImg( im ): pyplot.imshow( im ) pyplot.show() def myOpen(",
"'r' ) with opener( fname, mode ) as f: return",
"list( stateDict.keys() )[0][:7] == 'module.' ): for key in list(stateDict.keys()):",
"average for `torch.Variable` and `torch.Tensor`. \"\"\" def __init__(self): self.reset() def",
"( gzip.open, 'rt' ) if fname[-3:] == '.gz' else (",
"mode ): return open( fname, mode, encoding=\"utf-8\" ) def readFile(",
"if fname[-3:] == '.gz' else ( open, 'r' ) with",
"with opener( fname, mode ) as f: return f.read() def",
"fname, 'r' ) as f: return json.load( f ) def",
"loadTrainedModel( model, opt ): \"\"\"Load a pretrained model into given",
"elif isinstance(v, torch.Tensor): count = v.numel() v = v.sum() self.n_count",
"im ) pyplot.show() def myOpen( fname, mode ): return open(",
"model into given model\"\"\" print('loading pretrained model from %s' %",
"model\"\"\" print('loading pretrained model from %s' % opt.crnn) if( opt.cuda",
"if( list( stateDict.keys() )[0][:7] == 'module.' ): for key in",
"def readJson( fname ): with myOpen( fname, 'r' ) as",
"__init__(self): self.reset() def add(self, v): if isinstance(v, Variable): count =",
") as f: return f.read() def readLines( fname ): return",
"yaml from re import split from matplotlib import pyplot def",
"split from matplotlib import pyplot def showImg( im ): pyplot.imshow(",
"v.data.sum() elif isinstance(v, torch.Tensor): count = v.numel() v = v.sum()",
"return yaml.load( fp ) config = readYaml('./config.yaml') class averager(object): \"\"\"Compute",
"gzip.open, 'rt' ) if fname[-3:] == '.gz' else ( open,",
"pretrained model from %s' % opt.crnn) if( opt.cuda ): stateDict",
"import pyplot def showImg( im ): pyplot.imshow( im ) pyplot.show()",
"split('[\\r\\n]', readFile( fname ) ) def readJson( fname ): with",
"res = self.sum / float(self.n_count) return res def loadTrainedModel( model,",
"import torch import json import numpy as np from torch.autograd",
"Variable): count = v.data.numel() v = v.data.sum() elif isinstance(v, torch.Tensor):",
"count = v.numel() v = v.sum() self.n_count += count self.sum",
"v = v.sum() self.n_count += count self.sum += v def",
"torch.Tensor): count = v.numel() v = v.sum() self.n_count += count",
"opt ): \"\"\"Load a pretrained model into given model\"\"\" print('loading",
"fname[-3:] == '.gz' else ( open, 'r' ) with opener(",
"fname ): opener, mode = ( gzip.open, 'rt' ) if",
"( open, 'r' ) with opener( fname, mode ) as",
"fname, contents ): with myOpen( fname, 'w' ) as f:",
"and `torch.Tensor`. \"\"\" def __init__(self): self.reset() def add(self, v): if",
"v.numel() v = v.sum() self.n_count += count self.sum += v",
"readFile( fname ): opener, mode = ( gzip.open, 'rt' )",
") def readJson( fname ): with myOpen( fname, 'r' )",
"re import split from matplotlib import pyplot def showImg( im",
"def readYaml( fname ): with myOpen(fname, 'r') as fp: return",
"readYaml('./config.yaml') class averager(object): \"\"\"Compute average for `torch.Variable` and `torch.Tensor`. \"\"\"",
"with myOpen( fname, 'r' ) as f: return json.load( f",
"json.dump(data, outfile) def readYaml( fname ): with myOpen(fname, 'r') as",
"count = v.data.numel() v = v.data.sum() elif isinstance(v, torch.Tensor): count",
"mode = ( gzip.open, 'rt' ) if fname[-3:] == '.gz'",
"\"\"\"Load a pretrained model into given model\"\"\" print('loading pretrained model",
"'r') as fp: return yaml.load( fp ) config = readYaml('./config.yaml')",
"pyplot def showImg( im ): pyplot.imshow( im ) pyplot.show() def",
"= v.data.numel() v = v.data.sum() elif isinstance(v, torch.Tensor): count ="
] |
[
"vips_error_clear (void); ''') def _to_bytes(x): \"\"\"Convert to a byte string.",
"if isinstance(x, text_type): x = x.encode() return x def _to_string(x):",
"_to_bytes(x): \"\"\"Convert to a byte string. Convert a Python unicode",
"is None or detail == \"\": detail = _to_string(ffi.string(vips_lib.vips_error_buffer())) vips_lib.vips_error_clear()",
"If x is a byte string, assume it is utf-8",
"this on strings you pass to libvips. \"\"\" if isinstance(x,",
"byte string. Convert a Python unicode string to a utf-8-encoded",
"of the error detail (str): a string with some detailed",
"detail is None or detail == \"\": detail = _to_string(ffi.string(vips_lib.vips_error_buffer()))",
"\"\"\"Convert to a byte string. Convert a Python unicode string",
"on strings you pass to libvips. \"\"\" if isinstance(x, text_type):",
"You must call this on strings you pass to libvips.",
"it is utf-8 and decode to a Python unicode string.",
"a byte string, assume it is utf-8 and decode to",
"self.detail) def __str__(self): return '{0}\\n {1}'.format(self.message, self.detail) __all__ = [",
"description of the error detail (str): a string with some",
"message (str): a high-level description of the error detail (str):",
"error detail (str): a string with some detailed diagnostics \"\"\"",
"_is_PY3 and isinstance(x, bytes): x = x.decode('utf-8') return x class",
"to a Python unicode string. You must call this on",
"pass to libvips. \"\"\" if isinstance(x, text_type): x = x.encode()",
"= message if detail is None or detail == \"\":",
"unicode string. If x is a byte string, assume it",
"to a byte string. Convert a Python unicode string to",
"You must call this on text strings you get back",
"self.detail = detail logger.debug('Error %s %s', self.message, self.detail) def __str__(self):",
"back from libvips. \"\"\" if _is_PY3 and isinstance(x, bytes): x",
"vips. Attributes: message (str): a high-level description of the error",
"_is_PY3 = sys.version_info[0] == 3 if _is_PY3: text_type = str",
"logging.getLogger(__name__) _is_PY3 = sys.version_info[0] == 3 if _is_PY3: text_type =",
"text_type = unicode ffi.cdef(''' const char* vips_error_buffer (void); void vips_error_clear",
"byte string. You must call this on strings you pass",
"None or detail == \"\": detail = _to_string(ffi.string(vips_lib.vips_error_buffer())) vips_lib.vips_error_clear() self.detail",
"== 3 if _is_PY3: text_type = str else: text_type =",
"you get back from libvips. \"\"\" if _is_PY3 and isinstance(x,",
"if _is_PY3: text_type = str else: text_type = unicode ffi.cdef('''",
"unicode ffi.cdef(''' const char* vips_error_buffer (void); void vips_error_clear (void); ''')",
"is a byte string, assume it is utf-8 and decode",
"__init__(self, message, detail=None): self.message = message if detail is None",
"= sys.version_info[0] == 3 if _is_PY3: text_type = str else:",
"= x.decode('utf-8') return x class Error(Exception): \"\"\"An error from vips.",
"import sys import logging from pyvips import ffi, vips_lib logger",
"is utf-8 and decode to a Python unicode string. You",
"vips_error_buffer (void); void vips_error_clear (void); ''') def _to_bytes(x): \"\"\"Convert to",
"from libvips import sys import logging from pyvips import ffi,",
"message if detail is None or detail == \"\": detail",
"or detail == \"\": detail = _to_string(ffi.string(vips_lib.vips_error_buffer())) vips_lib.vips_error_clear() self.detail =",
"strings you get back from libvips. \"\"\" if _is_PY3 and",
"= detail logger.debug('Error %s %s', self.message, self.detail) def __str__(self): return",
"const char* vips_error_buffer (void); void vips_error_clear (void); ''') def _to_bytes(x):",
"sys.version_info[0] == 3 if _is_PY3: text_type = str else: text_type",
"a high-level description of the error detail (str): a string",
"a Python unicode string. You must call this on text",
"if detail is None or detail == \"\": detail =",
"to a utf-8-encoded byte string. You must call this on",
"string. You must call this on strings you pass to",
"# errors from libvips import sys import logging from pyvips",
"= str else: text_type = unicode ffi.cdef(''' const char* vips_error_buffer",
"a string with some detailed diagnostics \"\"\" def __init__(self, message,",
"== \"\": detail = _to_string(ffi.string(vips_lib.vips_error_buffer())) vips_lib.vips_error_clear() self.detail = detail logger.debug('Error",
"unicode string to a utf-8-encoded byte string. You must call",
"def __init__(self, message, detail=None): self.message = message if detail is",
"detail (str): a string with some detailed diagnostics \"\"\" def",
"logger.debug('Error %s %s', self.message, self.detail) def __str__(self): return '{0}\\n {1}'.format(self.message,",
"class Error(Exception): \"\"\"An error from vips. Attributes: message (str): a",
"\"\"\" if _is_PY3 and isinstance(x, bytes): x = x.decode('utf-8') return",
"(void); void vips_error_clear (void); ''') def _to_bytes(x): \"\"\"Convert to a",
"high-level description of the error detail (str): a string with",
"x.decode('utf-8') return x class Error(Exception): \"\"\"An error from vips. Attributes:",
"logging from pyvips import ffi, vips_lib logger = logging.getLogger(__name__) _is_PY3",
"x = x.decode('utf-8') return x class Error(Exception): \"\"\"An error from",
"from pyvips import ffi, vips_lib logger = logging.getLogger(__name__) _is_PY3 =",
"utf-8 and decode to a Python unicode string. You must",
"= _to_string(ffi.string(vips_lib.vips_error_buffer())) vips_lib.vips_error_clear() self.detail = detail logger.debug('Error %s %s', self.message,",
"message, detail=None): self.message = message if detail is None or",
"x = x.encode() return x def _to_string(x): \"\"\"Convert to a",
"return x class Error(Exception): \"\"\"An error from vips. Attributes: message",
"byte string, assume it is utf-8 and decode to a",
"strings you pass to libvips. \"\"\" if isinstance(x, text_type): x",
"detail=None): self.message = message if detail is None or detail",
"_is_PY3: text_type = str else: text_type = unicode ffi.cdef(''' const",
"def _to_string(x): \"\"\"Convert to a unicode string. If x is",
"must call this on strings you pass to libvips. \"\"\"",
"unicode string. You must call this on text strings you",
"on text strings you get back from libvips. \"\"\" if",
"isinstance(x, bytes): x = x.decode('utf-8') return x class Error(Exception): \"\"\"An",
"error from vips. Attributes: message (str): a high-level description of",
"with some detailed diagnostics \"\"\" def __init__(self, message, detail=None): self.message",
"diagnostics \"\"\" def __init__(self, message, detail=None): self.message = message if",
"'{0}\\n {1}'.format(self.message, self.detail) __all__ = [ '_to_bytes', '_to_string', 'Error', ]",
"string. If x is a byte string, assume it is",
"sys import logging from pyvips import ffi, vips_lib logger =",
"(void); ''') def _to_bytes(x): \"\"\"Convert to a byte string. Convert",
"text strings you get back from libvips. \"\"\" if _is_PY3",
"<gh_stars>0 # errors from libvips import sys import logging from",
"char* vips_error_buffer (void); void vips_error_clear (void); ''') def _to_bytes(x): \"\"\"Convert",
"and isinstance(x, bytes): x = x.decode('utf-8') return x class Error(Exception):",
"bytes): x = x.decode('utf-8') return x class Error(Exception): \"\"\"An error",
"Attributes: message (str): a high-level description of the error detail",
"x def _to_string(x): \"\"\"Convert to a unicode string. If x",
"_to_string(x): \"\"\"Convert to a unicode string. If x is a",
"return '{0}\\n {1}'.format(self.message, self.detail) __all__ = [ '_to_bytes', '_to_string', 'Error',",
"a byte string. Convert a Python unicode string to a",
"\"\"\" if isinstance(x, text_type): x = x.encode() return x def",
"= x.encode() return x def _to_string(x): \"\"\"Convert to a unicode",
"to a unicode string. If x is a byte string,",
"\"\"\"Convert to a unicode string. If x is a byte",
"def _to_bytes(x): \"\"\"Convert to a byte string. Convert a Python",
"Convert a Python unicode string to a utf-8-encoded byte string.",
"from libvips. \"\"\" if _is_PY3 and isinstance(x, bytes): x =",
"__str__(self): return '{0}\\n {1}'.format(self.message, self.detail) __all__ = [ '_to_bytes', '_to_string',",
"text_type = str else: text_type = unicode ffi.cdef(''' const char*",
"= unicode ffi.cdef(''' const char* vips_error_buffer (void); void vips_error_clear (void);",
"if _is_PY3 and isinstance(x, bytes): x = x.decode('utf-8') return x",
"decode to a Python unicode string. You must call this",
"def __str__(self): return '{0}\\n {1}'.format(self.message, self.detail) __all__ = [ '_to_bytes',",
"isinstance(x, text_type): x = x.encode() return x def _to_string(x): \"\"\"Convert",
"errors from libvips import sys import logging from pyvips import",
"you pass to libvips. \"\"\" if isinstance(x, text_type): x =",
"_to_string(ffi.string(vips_lib.vips_error_buffer())) vips_lib.vips_error_clear() self.detail = detail logger.debug('Error %s %s', self.message, self.detail)",
"%s %s', self.message, self.detail) def __str__(self): return '{0}\\n {1}'.format(self.message, self.detail)",
"a utf-8-encoded byte string. You must call this on strings",
"\"\"\" def __init__(self, message, detail=None): self.message = message if detail",
"string with some detailed diagnostics \"\"\" def __init__(self, message, detail=None):",
"\"\": detail = _to_string(ffi.string(vips_lib.vips_error_buffer())) vips_lib.vips_error_clear() self.detail = detail logger.debug('Error %s",
"x class Error(Exception): \"\"\"An error from vips. Attributes: message (str):",
"libvips. \"\"\" if isinstance(x, text_type): x = x.encode() return x",
"return x def _to_string(x): \"\"\"Convert to a unicode string. If",
"detail logger.debug('Error %s %s', self.message, self.detail) def __str__(self): return '{0}\\n",
"Error(Exception): \"\"\"An error from vips. Attributes: message (str): a high-level",
"must call this on text strings you get back from",
"assume it is utf-8 and decode to a Python unicode",
"call this on strings you pass to libvips. \"\"\" if",
"this on text strings you get back from libvips. \"\"\"",
"utf-8-encoded byte string. You must call this on strings you",
"(str): a high-level description of the error detail (str): a",
"vips_lib logger = logging.getLogger(__name__) _is_PY3 = sys.version_info[0] == 3 if",
"the error detail (str): a string with some detailed diagnostics",
"detailed diagnostics \"\"\" def __init__(self, message, detail=None): self.message = message",
"from vips. Attributes: message (str): a high-level description of the",
"libvips. \"\"\" if _is_PY3 and isinstance(x, bytes): x = x.decode('utf-8')",
"void vips_error_clear (void); ''') def _to_bytes(x): \"\"\"Convert to a byte",
"string. You must call this on text strings you get",
"string. Convert a Python unicode string to a utf-8-encoded byte",
"ffi, vips_lib logger = logging.getLogger(__name__) _is_PY3 = sys.version_info[0] == 3",
"x is a byte string, assume it is utf-8 and",
"Python unicode string. You must call this on text strings",
"str else: text_type = unicode ffi.cdef(''' const char* vips_error_buffer (void);",
"string to a utf-8-encoded byte string. You must call this",
"''') def _to_bytes(x): \"\"\"Convert to a byte string. Convert a",
"string, assume it is utf-8 and decode to a Python",
"(str): a string with some detailed diagnostics \"\"\" def __init__(self,",
"and decode to a Python unicode string. You must call",
"libvips import sys import logging from pyvips import ffi, vips_lib",
"a Python unicode string to a utf-8-encoded byte string. You",
"vips_lib.vips_error_clear() self.detail = detail logger.debug('Error %s %s', self.message, self.detail) def",
"= logging.getLogger(__name__) _is_PY3 = sys.version_info[0] == 3 if _is_PY3: text_type",
"ffi.cdef(''' const char* vips_error_buffer (void); void vips_error_clear (void); ''') def",
"a unicode string. If x is a byte string, assume",
"self.message, self.detail) def __str__(self): return '{0}\\n {1}'.format(self.message, self.detail) __all__ =",
"\"\"\"An error from vips. Attributes: message (str): a high-level description",
"some detailed diagnostics \"\"\" def __init__(self, message, detail=None): self.message =",
"x.encode() return x def _to_string(x): \"\"\"Convert to a unicode string.",
"get back from libvips. \"\"\" if _is_PY3 and isinstance(x, bytes):",
"3 if _is_PY3: text_type = str else: text_type = unicode",
"detail == \"\": detail = _to_string(ffi.string(vips_lib.vips_error_buffer())) vips_lib.vips_error_clear() self.detail = detail",
"call this on text strings you get back from libvips.",
"self.message = message if detail is None or detail ==",
"import logging from pyvips import ffi, vips_lib logger = logging.getLogger(__name__)",
"detail = _to_string(ffi.string(vips_lib.vips_error_buffer())) vips_lib.vips_error_clear() self.detail = detail logger.debug('Error %s %s',",
"import ffi, vips_lib logger = logging.getLogger(__name__) _is_PY3 = sys.version_info[0] ==",
"Python unicode string to a utf-8-encoded byte string. You must",
"to libvips. \"\"\" if isinstance(x, text_type): x = x.encode() return",
"logger = logging.getLogger(__name__) _is_PY3 = sys.version_info[0] == 3 if _is_PY3:",
"%s', self.message, self.detail) def __str__(self): return '{0}\\n {1}'.format(self.message, self.detail) __all__",
"text_type): x = x.encode() return x def _to_string(x): \"\"\"Convert to",
"else: text_type = unicode ffi.cdef(''' const char* vips_error_buffer (void); void",
"pyvips import ffi, vips_lib logger = logging.getLogger(__name__) _is_PY3 = sys.version_info[0]"
] |
[
"+ 1) def display_list_items_with_prompt(screen, first_line_num, a_string, a_list, prompt): \"\"\"Paints a",
"window. first_line_num: An integer that represents the location along the",
"Please resize. ', width - 1)) return output_line def display_list_items(screen,",
"first_line_num, a_string, menu_items, prompt): \"\"\"Paints a string, a menu, and",
"too small for output! Please resize. ', width - 1))",
"first string that is painted on the terminal window. prompt:",
"of the terminal window as menu options. prompt: A string",
"and another string on a text-based terminal window. The menu",
"on its own line with the key and value separated",
"Returns: A string representation of the item in 'menu_items' that",
"window. Each item of the list is painted on its",
"dictionaries whose key, value pairs are painted on their own",
"order in which the item appears in the menu. The",
"Returns: A string that the user enters in as input.",
"a list, and each item is assigned its own number",
"another string on a text-based terminal window. Each key, value",
"item_key += 1 # Display the menu and prompt the",
"+= 1 output_line = display_string(screen, prompt, output_line) screen.refresh() return screen.getstr(output_line,",
"string that is painted on the terminal window. list_of_dicts: A",
"first_line_num, a_string, a_list, prompt): \"\"\"Paints a string, each item of",
"string that serves as a prompt for the user to",
"#!/usr/bin/env python \"\"\" Module for painting output on and obtaining",
"accepts input. Paints a string, a menu, and another string",
"a_list, output_line): # Paints each item of a list on",
"list, and accepts input. Paints a string, each item of",
"that the user selects. \"\"\" # Create a dictionary that",
"a list on a text-based terminal window. for item in",
"key, value pair of a dict on a text-based terminal",
"prompt): \"\"\"Paints a string, each item of each dict in",
"item_line, output_line) output_line += 1 output_line += 1 output_line =",
"a_list: output_line = display_string(screen, '%s' % (item), output_line) output_line +=",
"formatted_dict, output_line) output_line += 1 return output_line def display_string_with_prompt(screen, first_line_num,",
"items in 'menu_items'. Each item # is added as a",
"list of dictionaries whose key, value pairs are painted on",
"display_list_items(screen, a_list, output_line) output_line += 1 output_line = display_string(screen, prompt,",
"menu. Returns: A string representation of the item in 'menu_items'",
"terminal window. _, width = screen.getmaxyx() try: screen.addstr(output_line, 0, textwrap.fill(a_string,",
"of a list, and accepts input. Paints a string, each",
"on a text-based terminal window. Each key, value pair of",
"second string serves as a prompt for the user to",
"window too small for output! Please resize. ', width -",
"latter of the two strings serves as the prompt for",
"is assigned its own number that represents the order in",
"each line of the terminal window as menu options. prompt:",
"of a list, and another string on a text-based terminal",
"curses library. \"\"\" import curses import textwrap def display_string(screen, a_string,",
"1) if input not in selection_items.keys(): continue # Force the",
"prompt the user for a selection. while True: screen.clear() output_line",
"display_string(screen, '%s' % (item), output_line) output_line += 1 return output_line",
"an integer key that represents the order in which #",
"% (item), output_line) output_line += 1 return output_line def display_formatted_dict(screen,",
"the terminal window. list_of_dicts: A list of dictionaries whose key,",
"a_string, output_line) output_line += 3 for menu_num in sorted(selection_items.iterkeys()): item_line",
"of each dict is painted on its own line with",
"which the item appears in the menu. The second string",
"= display_string(screen, prompt, output_line) screen.refresh() input = screen.getstr(output_line, len(prompt) +",
"output_line) screen.refresh() return screen.getstr(output_line, len(prompt) + 1) def get_user_menu_selection(screen, first_line_num,",
"their own line of the terminal window. prompt: A string",
"serves as the prompt for the user to enter input.",
"output_line) output_line += 1 return output_line def display_string_with_prompt(screen, first_line_num, a_string,",
"display_string(screen, a_string, output_line) output_line += 3 output_line = display_string(screen, prompt,",
"a_string, menu_items, prompt): \"\"\"Paints a string, a menu, and accepts",
"is added as a value with an integer key that",
"a_string, output_line) output_line += 2 for dct in list_of_dicts: output_line",
"resize. ', width - 1)) return output_line def display_list_items(screen, a_list,",
"and value separated by a colon. The second string serves",
"of dictionaries whose key, value pairs are painted on their",
"on each line of the terminal window. prompt: A string",
"that represents the order in which the item appears in",
"return output_line def display_list_items(screen, a_list, output_line): # Paints each item",
"menu_items, prompt): \"\"\"Paints a string, a menu, and accepts input.",
"representation of the item in 'menu_items' that the user selects.",
"output_line = display_formatted_dict(screen, dct, output_line) output_line += 1 output_line +=",
"first_line_num: An integer that represents the location along the y-axis",
"for the user to enter a number from the menu.",
"on its own line. The second string serves as a",
"\"\"\" Module for painting output on and obtaining input from",
"1 output_line = display_string(screen, prompt, output_line) screen.refresh() return screen.getstr(output_line, len(prompt)",
"string, each item of a list, and accepts input. Paints",
"a string, a menu, and another string on a text-based",
"each item of a list on a text-based terminal window.",
"screen.refresh() input = screen.getstr(output_line, len(prompt) + 1) if input not",
"the user to enter a number from the menu. Returns:",
"window. The menu is composed of the items in a",
"and each item is assigned its own number that represents",
"%s' % (key, value) output_line = display_string(screen, formatted_dict, output_line) output_line",
"text-based terminal window. Each key, value pair of each dict",
"to enter a number from the menu. Args: screen: A",
"'menu_items'. Each item # is added as a value with",
"the user to enter a number from the menu. Args:",
"selection_items = {} for item in menu_items: selection_items['%s' % (item_key)]",
"return screen.getstr(output_line, len(prompt) + 1) def display_list_items_with_prompt(screen, first_line_num, a_string, a_list,",
"# is added as a value with an integer key",
"import curses import textwrap def display_string(screen, a_string, output_line): # Paints",
"line. The second string serves as a prompt for the",
"added as a value with an integer key that represents",
"terminal window. The latter of the two strings serves as",
"represents the location along the y-axis of the terminal window",
"the menu and prompt the user for a selection. while",
"item item_key += 1 # Display the menu and prompt",
"the order in which # the item will appear in",
"item in a_list: output_line = display_string(screen, '%s' % (item), output_line)",
"terminal window. The menu is composed of the items in",
"list, and each item is assigned its own number that",
"the curses library. \"\"\" import curses import textwrap def display_string(screen,",
"user to enter input. Returns: A string that the user",
"def display_string(screen, a_string, output_line): # Paints a string on a",
"first character of the first string is painted. a_string: The",
"the key and value separated by a colon. The second",
"serves as a prompt for the user to enter a",
"enter a number from the menu. Args: screen: A window",
"prompt, output_line) screen.refresh() return screen.getstr(output_line, len(prompt) + 1) def get_user_menu_selection(screen,",
"strings serves as the prompt for the user to enter",
"strings and accepts input. Paints two strings on a text-based",
"output_line) output_line += 1 output_line += 1 output_line = display_string(screen,",
"menu_num in sorted(selection_items.iterkeys()): item_line = '%s) %s' % (menu_num, selection_items[menu_num])",
"value = '{:,}'.format(value) formatted_dict = '%s: %s' % (key, value)",
"from the menu. Returns: A string representation of the item",
"a_string, a_list, prompt): \"\"\"Paints a string, each item of a",
"def display_list_items_with_prompt(screen, first_line_num, a_string, a_list, prompt): \"\"\"Paints a string, each",
"True: screen.clear() output_line = first_line_num output_line = display_string(screen, a_string, output_line)",
"item in menu_items: selection_items['%s' % (item_key)] = item item_key +=",
"y-axis of the terminal window where the first character of",
"terminal window. for item in a_list: output_line = display_string(screen, '%s'",
"the item appears in the menu. The second string serves",
"list is painted on its own line. The second string",
"integer that represents the location along the y-axis of the",
"in 'menu_items'. Each item # is added as a value",
"terminal window as menu options. prompt: A string that serves",
"dct, output_line) output_line += 1 output_line += 1 output_line =",
"screen.clear() output_line = first_line_num output_line = display_string(screen, a_string, output_line) output_line",
"are painted on their own line of the terminal window.",
"of the item in 'menu_items' that the user selects. \"\"\"",
"output_line += 1 return output_line def display_string_with_prompt(screen, first_line_num, a_string, prompt):",
"as a prompt for the user to enter a number",
"The latter of the two strings serves as the prompt",
"a list, and another string on a text-based terminal window.",
"the items in a list, and each item is assigned",
"value in dct.items(): if isinstance(value, int): value = '{:,}'.format(value) formatted_dict",
"# Force the user to enter a valid selection. else:",
"of the items in a list, and each item is",
"a dict on a text-based terminal window. for key, value",
"by a colon. The second string serves as a prompt",
"in a list, and each item is assigned its own",
"pairs are painted on their own line of the terminal",
"in selection_items.keys(): continue # Force the user to enter a",
"output_line def display_string_with_prompt(screen, first_line_num, a_string, prompt): \"\"\"Paints two strings and",
"selection. while True: screen.clear() output_line = first_line_num output_line = display_string(screen,",
"list_of_dicts: A list of dictionaries whose key, value pairs are",
"string on a text-based terminal window. _, width = screen.getmaxyx()",
"is painted on the terminal window. list_of_dicts: A list of",
"and another string on a text-based terminal window. Each item",
"curses import textwrap def display_string(screen, a_string, output_line): # Paints a",
"on the terminal window. list_of_dicts: A list of dictionaries whose",
"item is assigned its own number that represents the order",
"in as input. \"\"\" screen.clear() output_line = first_line_num output_line =",
"Module for painting output on and obtaining input from a",
"_, width = screen.getmaxyx() try: screen.addstr(output_line, 0, textwrap.fill(a_string, width -",
"Display the menu and prompt the user for a selection.",
"output_line) output_line += 1 output_line = display_string(screen, prompt, output_line) screen.refresh()",
"separated by a colon. The second string serves as a",
"two strings on a text-based terminal window. The latter of",
"the menu. item_key = 1 selection_items = {} for item",
"= 1 selection_items = {} for item in menu_items: selection_items['%s'",
"menu_items: A list whose items are painted on each line",
"screen.refresh() return screen.getstr(output_line, len(prompt) + 1) def display_list_items_with_prompt(screen, first_line_num, a_string,",
"output_line): # Paints a string on a text-based terminal window.",
"a_string, prompt): \"\"\"Paints two strings and accepts input. Paints two",
"items in a list, and each item is assigned its",
"# Create a dictionary that contains the items in 'menu_items'.",
"A string that serves as a prompt for the user",
"a text-based terminal window. The latter of the two strings",
"display_string(screen, a_string, output_line) output_line += 2 output_line = display_list_items(screen, a_list,",
"user to enter a number from the menu. Returns: A",
"output_line += 1 output_line = display_string(screen, prompt, output_line) screen.refresh() return",
"item_line = '%s) %s' % (menu_num, selection_items[menu_num]) output_line = display_string(screen,",
"1 # Display the menu and prompt the user for",
"each item of each dict in a list, and accepts",
"on a text-based terminal window. _, width = screen.getmaxyx() try:",
"painted on the terminal window. a_list: A list whose items",
"int): value = '{:,}'.format(value) formatted_dict = '%s: %s' % (key,",
"sorted(selection_items.iterkeys()): item_line = '%s) %s' % (menu_num, selection_items[menu_num]) output_line =",
"item of a list on a text-based terminal window. for",
"object that represents the text-based terminal window. first_line_num: An integer",
"The menu is composed of the items in a list,",
"selection_items['%s' % (item_key)] = item item_key += 1 # Display",
"window where the first character of the first string is",
"return output_line def display_formatted_dict(screen, dct, output_line): # Paints each key,",
"using the curses library. \"\"\" import curses import textwrap def",
"text-based terminal window. Each item of the list is painted",
"prompt for the user to enter a number from the",
"= first_line_num output_line = display_string(screen, a_string, output_line) output_line += 2",
"terminal window. prompt: A string that serves as a prompt",
"to enter input. Returns: A string that the user enters",
"from a text-based terminal window using the curses library. \"\"\"",
"display_string(screen, item_line, output_line) output_line += 1 output_line += 1 output_line",
"output_line += 2 for dct in list_of_dicts: output_line = display_formatted_dict(screen,",
"that represents the location along the y-axis of the terminal",
"terminal window. Each item of the list is painted on",
"return screen.getstr(output_line, len(prompt) + 1) def get_user_menu_selection(screen, first_line_num, a_string, menu_items,",
"that serves as a prompt for the user to enter",
"text-based terminal window. The menu is composed of the items",
"item of a list, and another string on a text-based",
"each dict is painted on its own line with the",
"that the user enters in as input. \"\"\" screen.clear() output_line",
"for item in menu_items: selection_items['%s' % (item_key)] = item item_key",
"(item_key)] = item item_key += 1 # Display the menu",
"whose key, value pairs are painted on their own line",
"of a dict on a text-based terminal window. for key,",
"list whose items are painted on each line of the",
"that is painted on the terminal window. list_of_dicts: A list",
"'{:,}'.format(value) formatted_dict = '%s: %s' % (key, value) output_line =",
"own number that represents the order in which the item",
"the user to enter input. Returns: A string that the",
"# Paints a string on a text-based terminal window. _,",
"list_of_dicts: output_line = display_formatted_dict(screen, dct, output_line) output_line += 1 output_line",
"len(prompt) + 1) def display_formatted_dicts_with_prompt(screen, first_line_num, a_string, list_of_dicts, prompt): \"\"\"Paints",
"% (key, value) output_line = display_string(screen, formatted_dict, output_line) output_line +=",
"that contains the items in 'menu_items'. Each item # is",
"isinstance(value, int): value = '{:,}'.format(value) formatted_dict = '%s: %s' %",
"3 output_line = display_string(screen, prompt, output_line) screen.refresh() return screen.getstr(output_line, len(prompt)",
"a text-based terminal window. Each item of the list is",
"string, each item of each dict in a list, and",
"value pairs are painted on their own line of the",
"two strings and accepts input. Paints two strings on a",
"prompt for the user to enter input. Args: screen: A",
"of each dict in a list, and another string on",
"len(prompt) + 1) def display_list_items_with_prompt(screen, first_line_num, a_string, a_list, prompt): \"\"\"Paints",
"on a text-based terminal window. for item in a_list: output_line",
"enter input. Returns: A string that the user enters in",
"A list of dictionaries whose key, value pairs are painted",
"input. Paints a string, each item of each dict in",
"menu. item_key = 1 selection_items = {} for item in",
"the menu. The second string serves as a prompt for",
"line with the key and value separated by a colon.",
"represents the order in which # the item will appear",
"Paints a string, each item of each dict in a",
"screen.getstr(output_line, len(prompt) + 1) if input not in selection_items.keys(): continue",
"of the list is painted on its own line. The",
"string that is painted on the terminal window. menu_items: A",
"def display_string_with_prompt(screen, first_line_num, a_string, prompt): \"\"\"Paints two strings and accepts",
"first_line_num output_line = display_string(screen, a_string, output_line) output_line += 2 output_line",
"string that is painted on the terminal window. prompt: A",
"'%s: %s' % (key, value) output_line = display_string(screen, formatted_dict, output_line)",
"window. _, width = screen.getmaxyx() try: screen.addstr(output_line, 0, textwrap.fill(a_string, width",
"output! Please resize. ', width - 1)) return output_line def",
"prompt: A string that serves as a prompt for the",
"+= 1 output_line = display_string(screen, prompt, output_line) screen.refresh() input =",
"text-based terminal window. for item in a_list: output_line = display_string(screen,",
"in the menu. item_key = 1 selection_items = {} for",
"the text-based terminal window. first_line_num: An integer that represents the",
"is painted on its own line. The second string serves",
"output_line def display_list_items(screen, a_list, output_line): # Paints each item of",
"output_line = display_string(screen, a_string, output_line) output_line += 2 output_line =",
"and obtaining input from a text-based terminal window using the",
"represents the text-based terminal window. first_line_num: An integer that represents",
"window. for key, value in dct.items(): if isinstance(value, int): value",
"= display_string(screen, a_string, output_line) output_line += 3 output_line = display_string(screen,",
"string on a text-based terminal window. Each key, value pair",
"return screen.getstr(output_line, len(prompt) + 1) def display_formatted_dicts_with_prompt(screen, first_line_num, a_string, list_of_dicts,",
"output_line) output_line += 2 output_line = display_list_items(screen, a_list, output_line) output_line",
"+ 1) def get_user_menu_selection(screen, first_line_num, a_string, menu_items, prompt): \"\"\"Paints a",
"display_string(screen, prompt, output_line) screen.refresh() input = screen.getstr(output_line, len(prompt) + 1)",
"first_line_num, a_string, prompt): \"\"\"Paints two strings and accepts input. Paints",
"a text-based terminal window. Each key, value pair of each",
"first string that is painted on the terminal window. a_list:",
"of the first string is painted. a_string: The first string",
"with the key and value separated by a colon. The",
"Create a dictionary that contains the items in 'menu_items'. Each",
"the user enters in as input. \"\"\" screen.clear() output_line =",
"a string, each item of a list, and another string",
"terminal window where the first character of the first string",
"enter input. Args: screen: A window object that represents the",
"selection_items[menu_num]) output_line = display_string(screen, item_line, output_line) output_line += 1 output_line",
"number that represents the order in which the item appears",
"item of the list is painted on its own line.",
"textwrap.fill( 'Terminal window too small for output! Please resize. ',",
"the y-axis of the terminal window where the first character",
"input. \"\"\" screen.clear() output_line = first_line_num output_line = display_string(screen, a_string,",
"+= 3 for menu_num in sorted(selection_items.iterkeys()): item_line = '%s) %s'",
"as the prompt for the user to enter input. Args:",
"the terminal window. menu_items: A list whose items are painted",
"of the terminal window where the first character of the",
"text-based terminal window. _, width = screen.getmaxyx() try: screen.addstr(output_line, 0,",
"output_line += 2 output_line = display_list_items(screen, a_list, output_line) output_line +=",
"of each dict in a list, and accepts input. Paints",
"are painted on each line of the terminal window as",
"on and obtaining input from a text-based terminal window using",
"painted on the terminal window. prompt: A string that serves",
"dct, output_line): # Paints each key, value pair of a",
"for output! Please resize. ', width - 1)) return output_line",
"display_string(screen, a_string, output_line) output_line += 2 for dct in list_of_dicts:",
"a string, each item of each dict in a list,",
"a text-based terminal window using the curses library. \"\"\" import",
"window. The latter of the two strings serves as the",
"Paints each key, value pair of a dict on a",
"a number from the menu. Returns: A string representation of",
"python \"\"\" Module for painting output on and obtaining input",
"textwrap.fill(a_string, width - 1)) except curses.error: screen.addstr(0, 0, textwrap.fill( 'Terminal",
"= display_string(screen, a_string, output_line) output_line += 2 output_line = display_list_items(screen,",
"+= 2 for dct in list_of_dicts: output_line = display_formatted_dict(screen, dct,",
"2 output_line = display_list_items(screen, a_list, output_line) output_line += 1 output_line",
"its own number that represents the order in which the",
"each item of a list, and accepts input. Paints a",
"in which # the item will appear in the menu.",
"for key, value in dct.items(): if isinstance(value, int): value =",
"in which the item appears in the menu. The second",
"a menu, and accepts input. Paints a string, a menu,",
"+= 1 # Display the menu and prompt the user",
"window object that represents the text-based terminal window. first_line_num: An",
"+= 3 output_line = display_string(screen, prompt, output_line) screen.refresh() return screen.getstr(output_line,",
"of the terminal window. prompt: A string that serves as",
"'Terminal window too small for output! Please resize. ', width",
"first string is painted. a_string: The first string that is",
"accepts input. Paints a string, each item of a list,",
"number from the menu. Args: screen: A window object that",
"key that represents the order in which # the item",
"first string that is painted on the terminal window. menu_items:",
"in a list, and accepts input. Paints a string, each",
"on the terminal window. a_list: A list whose items are",
"= {} for item in menu_items: selection_items['%s' % (item_key)] =",
"output_line = first_line_num output_line = display_string(screen, a_string, output_line) output_line +=",
"dict on a text-based terminal window. for key, value in",
"1) def get_user_menu_selection(screen, first_line_num, a_string, menu_items, prompt): \"\"\"Paints a string,",
"\"\"\" # Create a dictionary that contains the items in",
"a text-based terminal window. _, width = screen.getmaxyx() try: screen.addstr(output_line,",
"for a selection. while True: screen.clear() output_line = first_line_num output_line",
"each key, value pair of a dict on a text-based",
"+ 1) if input not in selection_items.keys(): continue # Force",
"is composed of the items in a list, and each",
"text-based terminal window using the curses library. \"\"\" import curses",
"in list_of_dicts: output_line = display_formatted_dict(screen, dct, output_line) output_line += 1",
"on the terminal window. prompt: A string that serves as",
"curses.error: screen.addstr(0, 0, textwrap.fill( 'Terminal window too small for output!",
"1) def display_formatted_dicts_with_prompt(screen, first_line_num, a_string, list_of_dicts, prompt): \"\"\"Paints a string,",
"item appears in the menu. The second string serves as",
"its own line with the key and value separated by",
"key and value separated by a colon. The second string",
"screen.addstr(output_line, 0, textwrap.fill(a_string, width - 1)) except curses.error: screen.addstr(0, 0,",
"A window object that represents the text-based terminal window. first_line_num:",
"0, textwrap.fill(a_string, width - 1)) except curses.error: screen.addstr(0, 0, textwrap.fill(",
"# the item will appear in the menu. item_key =",
"in 'menu_items' that the user selects. \"\"\" # Create a",
"for menu_num in sorted(selection_items.iterkeys()): item_line = '%s) %s' % (menu_num,",
"\"\"\"Paints a string, each item of a list, and accepts",
"own line. The second string serves as a prompt for",
"Paints a string, each item of a list, and another",
"output_line = display_string(screen, prompt, output_line) screen.refresh() return screen.getstr(output_line, len(prompt) +",
"a text-based terminal window. for key, value in dct.items(): if",
"character of the first string is painted. a_string: The first",
"each item of a list, and another string on a",
"a_string, output_line): # Paints a string on a text-based terminal",
"prompt, output_line) screen.refresh() return screen.getstr(output_line, len(prompt) + 1) def display_formatted_dicts_with_prompt(screen,",
"own line with the key and value separated by a",
"on a text-based terminal window. Each item of the list",
"a list, and accepts input. Paints a string, each item",
"and accepts input. Paints a string, each item of a",
"a colon. The second string serves as a prompt for",
"the menu. Returns: A string representation of the item in",
"', width - 1)) return output_line def display_list_items(screen, a_list, output_line):",
"output_line) output_line += 2 for dct in list_of_dicts: output_line =",
"painted on the terminal window. menu_items: A list whose items",
"a value with an integer key that represents the order",
"as a value with an integer key that represents the",
"small for output! Please resize. ', width - 1)) return",
"assigned its own number that represents the order in which",
"value pair of each dict is painted on its own",
"window. Each key, value pair of each dict is painted",
"user selects. \"\"\" # Create a dictionary that contains the",
"screen.refresh() return screen.getstr(output_line, len(prompt) + 1) def get_user_menu_selection(screen, first_line_num, a_string,",
"first_line_num output_line = display_string(screen, a_string, output_line) output_line += 3 for",
"dict is painted on its own line with the key",
"Force the user to enter a valid selection. else: return",
"user enters in as input. \"\"\" screen.clear() output_line = first_line_num",
"window using the curses library. \"\"\" import curses import textwrap",
"\"\"\" screen.clear() output_line = first_line_num output_line = display_string(screen, a_string, output_line)",
"obtaining input from a text-based terminal window using the curses",
"\"\"\"Paints a string, each item of each dict in a",
"while True: screen.clear() output_line = first_line_num output_line = display_string(screen, a_string,",
"order in which # the item will appear in the",
"and another string on a text-based terminal window. Each key,",
"menu, and accepts input. Paints a string, a menu, and",
"painted. a_string: The first string that is painted on the",
"screen: A window object that represents the text-based terminal window.",
"a prompt for the user to enter input. Args: screen:",
"item will appear in the menu. item_key = 1 selection_items",
"item of a list, and accepts input. Paints a string,",
"pair of a dict on a text-based terminal window. for",
"output_line) output_line += 1 return output_line def display_formatted_dict(screen, dct, output_line):",
"= display_list_items(screen, a_list, output_line) output_line += 1 output_line = display_string(screen,",
"menu and prompt the user for a selection. while True:",
"width - 1)) except curses.error: screen.addstr(0, 0, textwrap.fill( 'Terminal window",
"accepts input. Paints two strings on a text-based terminal window.",
"user for a selection. while True: screen.clear() output_line = first_line_num",
"display_string(screen, formatted_dict, output_line) output_line += 1 return output_line def display_string_with_prompt(screen,",
"item of each dict in a list, and another string",
"- 1)) return output_line def display_list_items(screen, a_list, output_line): # Paints",
"screen.refresh() return screen.getstr(output_line, len(prompt) + 1) def display_formatted_dicts_with_prompt(screen, first_line_num, a_string,",
"dct in list_of_dicts: output_line = display_formatted_dict(screen, dct, output_line) output_line +=",
"input. Paints a string, each item of a list, and",
"1)) return output_line def display_list_items(screen, a_list, output_line): # Paints each",
"output_line += 3 output_line = display_string(screen, prompt, output_line) screen.refresh() return",
"on the terminal window. menu_items: A list whose items are",
"a_string, output_line) output_line += 3 output_line = display_string(screen, prompt, output_line)",
"return output_line def display_string_with_prompt(screen, first_line_num, a_string, prompt): \"\"\"Paints two strings",
"output_line = display_string(screen, a_string, output_line) output_line += 3 output_line =",
"menu. The second string serves as a prompt for the",
"continue # Force the user to enter a valid selection.",
"items are painted on each line of the terminal window.",
"library. \"\"\" import curses import textwrap def display_string(screen, a_string, output_line):",
"a text-based terminal window. for item in a_list: output_line =",
"1 return output_line def display_string_with_prompt(screen, first_line_num, a_string, prompt): \"\"\"Paints two",
"for the user to enter input. Returns: A string that",
"on a text-based terminal window. for key, value in dct.items():",
"Args: screen: A window object that represents the text-based terminal",
"output_line += 1 output_line = display_string(screen, prompt, output_line) screen.refresh() input",
"a_string: The first string that is painted on the terminal",
"menu options. prompt: A string that serves as a prompt",
"pair of each dict is painted on its own line",
"the first character of the first string is painted. a_string:",
"string is painted. a_string: The first string that is painted",
"in a list, and another string on a text-based terminal",
"strings on a text-based terminal window. The latter of the",
"screen.getstr(output_line, len(prompt) + 1) def get_user_menu_selection(screen, first_line_num, a_string, menu_items, prompt):",
"a selection. while True: screen.clear() output_line = first_line_num output_line =",
"a prompt for the user to enter input. Returns: A",
"output on and obtaining input from a text-based terminal window",
"a dictionary that contains the items in 'menu_items'. Each item",
"enters in as input. \"\"\" screen.clear() output_line = first_line_num output_line",
"the first string is painted. a_string: The first string that",
"line of the terminal window as menu options. prompt: A",
"item # is added as a value with an integer",
"width - 1)) return output_line def display_list_items(screen, a_list, output_line): #",
"get_user_menu_selection(screen, first_line_num, a_string, menu_items, prompt): \"\"\"Paints a string, a menu,",
"user to enter a number from the menu. Args: screen:",
"terminal window. list_of_dicts: A list of dictionaries whose key, value",
"window as menu options. prompt: A string that serves as",
"the two strings serves as the prompt for the user",
"1) def display_list_items_with_prompt(screen, first_line_num, a_string, a_list, prompt): \"\"\"Paints a string,",
"(key, value) output_line = display_string(screen, formatted_dict, output_line) output_line += 1",
"the terminal window. prompt: A string that serves as a",
"screen.getmaxyx() try: screen.addstr(output_line, 0, textwrap.fill(a_string, width - 1)) except curses.error:",
"output_line = display_list_items(screen, a_list, output_line) output_line += 1 output_line =",
"Paints a string, a menu, and another string on a",
"the user to enter a valid selection. else: return selection_items[input]",
"string serves as a prompt for the user to enter",
"2 for dct in list_of_dicts: output_line = display_formatted_dict(screen, dct, output_line)",
"item of each dict in a list, and accepts input.",
"except curses.error: screen.addstr(0, 0, textwrap.fill( 'Terminal window too small for",
"each item is assigned its own number that represents the",
"contains the items in 'menu_items'. Each item # is added",
"on each line of the terminal window as menu options.",
"terminal window. menu_items: A list whose items are painted on",
"that is painted on the terminal window. menu_items: A list",
"output_line += 1 output_line += 1 output_line = display_string(screen, prompt,",
"two strings serves as the prompt for the user to",
"colon. The second string serves as a prompt for the",
"output_line = display_string(screen, item_line, output_line) output_line += 1 output_line +=",
"accepts input. Paints a string, each item of each dict",
"1 output_line += 1 output_line = display_string(screen, prompt, output_line) screen.refresh()",
"in a_list: output_line = display_string(screen, '%s' % (item), output_line) output_line",
"+= 1 return output_line def display_formatted_dict(screen, dct, output_line): # Paints",
"text-based terminal window. The latter of the two strings serves",
"formatted_dict = '%s: %s' % (key, value) output_line = display_string(screen,",
"window. prompt: A string that serves as a prompt for",
"line of the terminal window. prompt: A string that serves",
"prompt): \"\"\"Paints a string, a menu, and accepts input. Paints",
"width = screen.getmaxyx() try: screen.addstr(output_line, 0, textwrap.fill(a_string, width - 1))",
"string, a menu, and accepts input. Paints a string, a",
"if isinstance(value, int): value = '{:,}'.format(value) formatted_dict = '%s: %s'",
"and accepts input. Paints a string, a menu, and another",
"the terminal window where the first character of the first",
"An integer that represents the location along the y-axis of",
"each dict in a list, and another string on a",
"window. menu_items: A list whose items are painted on each",
"as menu options. prompt: A string that serves as a",
"painted on its own line. The second string serves as",
"a menu, and another string on a text-based terminal window.",
"which # the item will appear in the menu. item_key",
"prompt): \"\"\"Paints two strings and accepts input. Paints two strings",
"each line of the terminal window. prompt: A string that",
"enter a number from the menu. Returns: A string representation",
"in the menu. The second string serves as a prompt",
"% (menu_num, selection_items[menu_num]) output_line = display_string(screen, item_line, output_line) output_line +=",
"of a list on a text-based terminal window. for item",
"a number from the menu. Args: screen: A window object",
"for painting output on and obtaining input from a text-based",
"if input not in selection_items.keys(): continue # Force the user",
"Paints each item of a list on a text-based terminal",
"display_string_with_prompt(screen, first_line_num, a_string, prompt): \"\"\"Paints two strings and accepts input.",
"item_key = 1 selection_items = {} for item in menu_items:",
"string, each item of a list, and another string on",
"1 return output_line def display_formatted_dict(screen, dct, output_line): # Paints each",
"= item item_key += 1 # Display the menu and",
"= display_string(screen, a_string, output_line) output_line += 2 for dct in",
"number from the menu. Returns: A string representation of the",
"terminal window. for key, value in dct.items(): if isinstance(value, int):",
"from the menu. Args: screen: A window object that represents",
"screen.getstr(output_line, len(prompt) + 1) def display_formatted_dicts_with_prompt(screen, first_line_num, a_string, list_of_dicts, prompt):",
"serves as a prompt for the user to enter input.",
"= first_line_num output_line = display_string(screen, a_string, output_line) output_line += 3",
"terminal window. first_line_num: An integer that represents the location along",
"along the y-axis of the terminal window where the first",
"the item in 'menu_items' that the user selects. \"\"\" #",
"own line of the terminal window. prompt: A string that",
"menu, and another string on a text-based terminal window. The",
"is painted on the terminal window. menu_items: A list whose",
"# Paints each key, value pair of a dict on",
"0, textwrap.fill( 'Terminal window too small for output! Please resize.",
"string representation of the item in 'menu_items' that the user",
"len(prompt) + 1) def get_user_menu_selection(screen, first_line_num, a_string, menu_items, prompt): \"\"\"Paints",
"def get_user_menu_selection(screen, first_line_num, a_string, menu_items, prompt): \"\"\"Paints a string, a",
"items are painted on each line of the terminal window",
"list_of_dicts, prompt): \"\"\"Paints a string, each item of each dict",
"def display_formatted_dict(screen, dct, output_line): # Paints each key, value pair",
"in sorted(selection_items.iterkeys()): item_line = '%s) %s' % (menu_num, selection_items[menu_num]) output_line",
"len(prompt) + 1) if input not in selection_items.keys(): continue #",
"a string, a menu, and accepts input. Paints a string,",
"text-based terminal window. first_line_num: An integer that represents the location",
"1 output_line = display_string(screen, prompt, output_line) screen.refresh() input = screen.getstr(output_line,",
"each dict in a list, and accepts input. Paints a",
"a string, each item of a list, and accepts input.",
"menu is composed of the items in a list, and",
"as a prompt for the user to enter input. Returns:",
"input from a text-based terminal window using the curses library.",
"the menu. Args: screen: A window object that represents the",
"= screen.getstr(output_line, len(prompt) + 1) if input not in selection_items.keys():",
"string that is painted on the terminal window. a_list: A",
"1 selection_items = {} for item in menu_items: selection_items['%s' %",
"window. a_list: A list whose items are painted on each",
"the user for a selection. while True: screen.clear() output_line =",
"not in selection_items.keys(): continue # Force the user to enter",
"key, value pairs are painted on their own line of",
"= display_string(screen, formatted_dict, output_line) output_line += 1 return output_line def",
"The second string serves as a prompt for the user",
"display_list_items(screen, a_list, output_line): # Paints each item of a list",
"= screen.getmaxyx() try: screen.addstr(output_line, 0, textwrap.fill(a_string, width - 1)) except",
"represents the order in which the item appears in the",
"painted on the terminal window. list_of_dicts: A list of dictionaries",
"are painted on each line of the terminal window. prompt:",
"window. list_of_dicts: A list of dictionaries whose key, value pairs",
"input. Returns: A string that the user enters in as",
"<filename>population_estimator/curses_io.py #!/usr/bin/env python \"\"\" Module for painting output on and",
"terminal window using the curses library. \"\"\" import curses import",
"of the two strings serves as the prompt for the",
"output_line = display_string(screen, prompt, output_line) screen.refresh() input = screen.getstr(output_line, len(prompt)",
"display_formatted_dict(screen, dct, output_line): # Paints each key, value pair of",
"the user selects. \"\"\" # Create a dictionary that contains",
"A string that the user enters in as input. \"\"\"",
"import textwrap def display_string(screen, a_string, output_line): # Paints a string",
"menu_items: selection_items['%s' % (item_key)] = item item_key += 1 #",
"prompt): \"\"\"Paints a string, each item of a list, and",
"appear in the menu. item_key = 1 selection_items = {}",
"the location along the y-axis of the terminal window where",
"output_line) screen.refresh() return screen.getstr(output_line, len(prompt) + 1) def display_list_items_with_prompt(screen, first_line_num,",
"output_line) screen.refresh() return screen.getstr(output_line, len(prompt) + 1) def display_formatted_dicts_with_prompt(screen, first_line_num,",
"dict in a list, and another string on a text-based",
"prompt for the user to enter input. Returns: A string",
"value pair of a dict on a text-based terminal window.",
"%s' % (menu_num, selection_items[menu_num]) output_line = display_string(screen, item_line, output_line) output_line",
"= display_string(screen, '%s' % (item), output_line) output_line += 1 return",
"output_line): # Paints each key, value pair of a dict",
"on a text-based terminal window. The menu is composed of",
"painted on each line of the terminal window as menu",
"key, value in dct.items(): if isinstance(value, int): value = '{:,}'.format(value)",
"= display_string(screen, item_line, output_line) output_line += 1 output_line += 1",
"string on a text-based terminal window. Each item of the",
"for dct in list_of_dicts: output_line = display_formatted_dict(screen, dct, output_line) output_line",
"= display_formatted_dict(screen, dct, output_line) output_line += 1 output_line += 1",
"Paints two strings on a text-based terminal window. The latter",
"painting output on and obtaining input from a text-based terminal",
"Each item of the list is painted on its own",
"is painted on its own line with the key and",
"the prompt for the user to enter input. Args: screen:",
"dct.items(): if isinstance(value, int): value = '{:,}'.format(value) formatted_dict = '%s:",
"selects. \"\"\" # Create a dictionary that contains the items",
"= '%s) %s' % (menu_num, selection_items[menu_num]) output_line = display_string(screen, item_line,",
"for the user to enter input. Args: screen: A window",
"A list whose items are painted on each line of",
"Each item # is added as a value with an",
"composed of the items in a list, and each item",
"its own line. The second string serves as a prompt",
"output_line) output_line += 3 output_line = display_string(screen, prompt, output_line) screen.refresh()",
"user to enter input. Args: screen: A window object that",
"(menu_num, selection_items[menu_num]) output_line = display_string(screen, item_line, output_line) output_line += 1",
"a_list: A list whose items are painted on each line",
"that represents the text-based terminal window. first_line_num: An integer that",
"in menu_items: selection_items['%s' % (item_key)] = item item_key += 1",
"3 for menu_num in sorted(selection_items.iterkeys()): item_line = '%s) %s' %",
"output_line def display_formatted_dict(screen, dct, output_line): # Paints each key, value",
"that is painted on the terminal window. prompt: A string",
"value) output_line = display_string(screen, formatted_dict, output_line) output_line += 1 return",
"first_line_num, a_string, list_of_dicts, prompt): \"\"\"Paints a string, each item of",
"the terminal window. a_list: A list whose items are painted",
"a_list, prompt): \"\"\"Paints a string, each item of a list,",
"and prompt the user for a selection. while True: screen.clear()",
"whose items are painted on each line of the terminal",
"input. Paints two strings on a text-based terminal window. The",
"a_list, output_line) output_line += 1 output_line = display_string(screen, prompt, output_line)",
"the items in 'menu_items'. Each item # is added as",
"output_line): # Paints each item of a list on a",
"painted on its own line with the key and value",
"dictionary that contains the items in 'menu_items'. Each item #",
"a string on a text-based terminal window. _, width =",
"options. prompt: A string that serves as a prompt for",
"output_line += 3 for menu_num in sorted(selection_items.iterkeys()): item_line = '%s)",
"window. for item in a_list: output_line = display_string(screen, '%s' %",
"'%s) %s' % (menu_num, selection_items[menu_num]) output_line = display_string(screen, item_line, output_line)",
"input. Paints a string, a menu, and another string on",
"A string representation of the item in 'menu_items' that the",
"and accepts input. Paints a string, each item of each",
"The first string that is painted on the terminal window.",
"display_string(screen, prompt, output_line) screen.refresh() return screen.getstr(output_line, len(prompt) + 1) def",
"= '{:,}'.format(value) formatted_dict = '%s: %s' % (key, value) output_line",
"painted on each line of the terminal window. prompt: A",
"is painted. a_string: The first string that is painted on",
"'%s' % (item), output_line) output_line += 1 return output_line def",
"value with an integer key that represents the order in",
"as input. \"\"\" screen.clear() output_line = first_line_num output_line = display_string(screen,",
"+= 1 return output_line def display_string_with_prompt(screen, first_line_num, a_string, prompt): \"\"\"Paints",
"def display_formatted_dicts_with_prompt(screen, first_line_num, a_string, list_of_dicts, prompt): \"\"\"Paints a string, each",
"another string on a text-based terminal window. Each item of",
"output_line = display_string(screen, a_string, output_line) output_line += 3 for menu_num",
"1)) except curses.error: screen.addstr(0, 0, textwrap.fill( 'Terminal window too small",
"input. Args: screen: A window object that represents the text-based",
"to enter input. Args: screen: A window object that represents",
"textwrap def display_string(screen, a_string, output_line): # Paints a string on",
"will appear in the menu. item_key = 1 selection_items =",
"output_line += 1 return output_line def display_formatted_dict(screen, dct, output_line): #",
"painted on their own line of the terminal window. prompt:",
"Each key, value pair of each dict is painted on",
"terminal window. a_list: A list whose items are painted on",
"appears in the menu. The second string serves as a",
"item in 'menu_items' that the user selects. \"\"\" # Create",
"text-based terminal window. for key, value in dct.items(): if isinstance(value,",
"key, value pair of each dict is painted on its",
"the item will appear in the menu. item_key = 1",
"first_line_num output_line = display_string(screen, a_string, output_line) output_line += 2 for",
"\"\"\"Paints two strings and accepts input. Paints two strings on",
"+ 1) def display_formatted_dicts_with_prompt(screen, first_line_num, a_string, list_of_dicts, prompt): \"\"\"Paints a",
"screen.addstr(0, 0, textwrap.fill( 'Terminal window too small for output! Please",
"string on a text-based terminal window. The menu is composed",
"output_line) screen.refresh() input = screen.getstr(output_line, len(prompt) + 1) if input",
"= display_string(screen, prompt, output_line) screen.refresh() return screen.getstr(output_line, len(prompt) + 1)",
"prompt, output_line) screen.refresh() return screen.getstr(output_line, len(prompt) + 1) def display_list_items_with_prompt(screen,",
"display_list_items_with_prompt(screen, first_line_num, a_string, a_list, prompt): \"\"\"Paints a string, each item",
"is painted on the terminal window. a_list: A list whose",
"\"\"\" import curses import textwrap def display_string(screen, a_string, output_line): #",
"a_string, list_of_dicts, prompt): \"\"\"Paints a string, each item of each",
"on their own line of the terminal window. prompt: A",
"output_line) output_line += 3 for menu_num in sorted(selection_items.iterkeys()): item_line =",
"= display_string(screen, a_string, output_line) output_line += 3 for menu_num in",
"- 1)) except curses.error: screen.addstr(0, 0, textwrap.fill( 'Terminal window too",
"another string on a text-based terminal window. The menu is",
"input = screen.getstr(output_line, len(prompt) + 1) if input not in",
"and accepts input. Paints two strings on a text-based terminal",
"for item in a_list: output_line = display_string(screen, '%s' % (item),",
"string that the user enters in as input. \"\"\" screen.clear()",
"+= 1 output_line += 1 output_line = display_string(screen, prompt, output_line)",
"# Display the menu and prompt the user for a",
"input not in selection_items.keys(): continue # Force the user to",
"a text-based terminal window. The menu is composed of the",
"dict in a list, and accepts input. Paints a string,",
"prompt, output_line) screen.refresh() input = screen.getstr(output_line, len(prompt) + 1) if",
"(item), output_line) output_line += 1 return output_line def display_formatted_dict(screen, dct,",
"the list is painted on its own line. The second",
"screen.getstr(output_line, len(prompt) + 1) def display_list_items_with_prompt(screen, first_line_num, a_string, a_list, prompt):",
"a prompt for the user to enter a number from",
"terminal window. Each key, value pair of each dict is",
"the order in which the item appears in the menu.",
"that represents the order in which # the item will",
"location along the y-axis of the terminal window where the",
"menu. Args: screen: A window object that represents the text-based",
"\"\"\"Paints a string, a menu, and accepts input. Paints a",
"try: screen.addstr(output_line, 0, textwrap.fill(a_string, width - 1)) except curses.error: screen.addstr(0,",
"first_line_num output_line = display_string(screen, a_string, output_line) output_line += 3 output_line",
"integer key that represents the order in which # the",
"Paints a string on a text-based terminal window. _, width",
"+= 2 output_line = display_list_items(screen, a_list, output_line) output_line += 1",
"def display_list_items(screen, a_list, output_line): # Paints each item of a",
"on a text-based terminal window. The latter of the two",
"# Paints each item of a list on a text-based",
"= '%s: %s' % (key, value) output_line = display_string(screen, formatted_dict,",
"is painted on the terminal window. prompt: A string that",
"as a prompt for the user to enter input. Args:",
"the terminal window as menu options. prompt: A string that",
"output_line = display_string(screen, a_string, output_line) output_line += 2 for dct",
"display_formatted_dicts_with_prompt(screen, first_line_num, a_string, list_of_dicts, prompt): \"\"\"Paints a string, each item",
"list, and another string on a text-based terminal window. Each",
"list on a text-based terminal window. for item in a_list:",
"the user to enter input. Args: screen: A window object",
"'menu_items' that the user selects. \"\"\" # Create a dictionary",
"string, a menu, and another string on a text-based terminal",
"where the first character of the first string is painted.",
"{} for item in menu_items: selection_items['%s' % (item_key)] = item",
"each item of each dict in a list, and another",
"to enter a number from the menu. Returns: A string",
"first string that is painted on the terminal window. list_of_dicts:",
"with an integer key that represents the order in which",
"value separated by a colon. The second string serves as",
"output_line = display_string(screen, formatted_dict, output_line) output_line += 1 return output_line",
"display_formatted_dict(screen, dct, output_line) output_line += 1 output_line += 1 output_line",
"that is painted on the terminal window. a_list: A list",
"display_string(screen, a_string, output_line): # Paints a string on a text-based",
"a_string, output_line) output_line += 2 output_line = display_list_items(screen, a_list, output_line)",
"selection_items.keys(): continue # Force the user to enter a valid",
"% (item_key)] = item item_key += 1 # Display the",
"output_line = display_string(screen, '%s' % (item), output_line) output_line += 1",
"display_string(screen, a_string, output_line) output_line += 3 for menu_num in sorted(selection_items.iterkeys()):",
"in dct.items(): if isinstance(value, int): value = '{:,}'.format(value) formatted_dict ="
] |
[] |
[
"to send.\\n\\nPlease refresh the page.\" ) return None email_details =",
"self.tr_tree_view.get_children() self.tr_tree_view.selection_add(items) def get_selected_item_ids(self): return self.tr_tree_view.selection() def send_email(self): # get",
"self.tr_tree_view.insert('', 'end', values=no_data_information) def select_all(self): items = self.tr_tree_view.get_children() self.tr_tree_view.selection_add(items) def",
"Tk() self.window.title(\"Send email with import requests to TST\") self.window.config(padx=20, pady=20)",
"open(file=EXCEPTION_FILE, mode='r') as file: exception_list = set(json.load(file)['tr_numbers']) except FileNotFoundError: with",
"return None def prepare_email_details(self, selected_ids): transport_data = [self.tr_tree_view.item(id_tag, 'values') for",
"return email_details def load_exceptions(self): try: with open(file=EXCEPTION_FILE, mode='r') as file:",
"else: return exception_list def add_to_exceptions(self): selected_ids = self.get_selected_item_ids() if not",
"transport_data = [self.tr_tree_view.item(id_tag, 'values') for id_tag in selected_ids] # prepare",
"all TRs are in exceptions, insert only pre-defined information if",
"are in exceptions, insert only pre-defined information if all_are_in_exceptions: tr_number",
"file for number in transport_numbers: self.exceptions.add(number) updated_data= {'tr_numbers': list(self.exceptions)} with",
"column=0, rowspan=4) self.refresh_btn.grid(row=1, column=1, sticky=N+S+E+W, padx=2, pady=2) self.exceptions_btn.grid(row=2, column=1, sticky=E+W+S,",
"selected.\\n\\nPlease refresh the page.\" ) return None transport_numbers = [self.tr_tree_view.item(id_tag,",
"{', '.join(sorted(ticket_numbers)).rstrip(', ')}\", 'html_body': email_body_template.format(html_list_of_trs) } return email_details def load_exceptions(self):",
"pady=2) self.exceptions_btn.grid(row=2, column=1, sticky=E+W+S, padx=1, pady=2) self.select_all_btn.grid(row=3, column=1, sticky=E+W+N, padx=1,",
"data self.populate_tree_view_lines() #LAYOUT PLACEMENT self.title_lbl.grid(row=0, column=0, sticky=W) self.tr_tree_view.grid(row=1, column=0, rowspan=4)",
"nothing to send.\\n\\nPlease refresh the page.\" ) return None email_details",
"add trs into exceptions return self.add_to_exceptions() else: return None def",
"padx=1, pady=2) self.select_all_btn.grid(row=3, column=1, sticky=E+W+N, padx=1, pady=2) self.send_btn.grid(row=4, column=1, sticky=N+S+E+W,",
"if all_are_in_exceptions: tr_number = NO_DATA_MEETS_CRITERIA[0][0] description = NO_DATA_MEETS_CRITERIA[0][3] no_data_information =",
"refresh(self): # delete all rows in tree view for item",
"mode='w') as file: exception_dict = {'tr_numbers': []} json.dump(exception_dict, file, indent=4)",
"import json from tkinter import * from tkinter import ttk",
"tkinter import messagebox from tr_data import TRData, NO_DATA_MEETS_CRITERIA from email_text",
"self.window = Tk() self.window.title(\"Send email with import requests to TST\")",
"self.window.config(padx=20, pady=20) # TTILE LABEL self.title_lbl = Label( text=\"Please select",
"import requests to TST\") self.window.config(padx=20, pady=20) # TTILE LABEL self.title_lbl",
"export_timestamp, owner, description, ticket_number, sap_module, ticket_type) in self.transport_requests.data: # check",
"(\"Ticket Type\", 80), 'ticket_num': (\"Ticket Number\", 80), 'module': (\"SAP Module\",",
"pady=20) # TTILE LABEL self.title_lbl = Label( text=\"Please select TRs",
"\"\", \"\", \"\", \"\", \"\") self.tr_tree_view.insert('', 'end', values=no_data_information) def select_all(self):",
"in transport_data: html_list_of_trs += f\"<li>{tr_number} - {owner} - {description}</li>\" ticket_numbers.add(ticket_number)",
"Number\", 100), 'description': (\"Description\", 350), 'tkt_type': (\"Ticket Type\", 80), 'ticket_num':",
"= export_timestamp[4:6] day = export_timestamp[6:8] time = f\"{export_timestamp[8:10]}:{export_timestamp[10:12]}:{export_timestamp[12:]}\" export_date_time =",
"refresh the page.\" ) return None email_details = self.prepare_email_details(selected_ids) #",
"email body html_list_of_trs = \"\" ticket_numbers = set() for (tr_number,",
"open(file=EXCEPTION_FILE, mode='w') as file: exception_dict = {'tr_numbers': []} json.dump(exception_dict, file,",
"self.refresh_btn = Button(text=\"REFRESH\", command=self.refresh) self.exceptions_btn = Button(text=\"Add to exceptions\", command=self.add_to_exceptions)",
"in exceptions, insert only pre-defined information if all_are_in_exceptions: tr_number =",
"None def prepare_email_details(self, selected_ids): transport_data = [self.tr_tree_view.item(id_tag, 'values') for id_tag",
"350), 'tkt_type': (\"Ticket Type\", 80), 'ticket_num': (\"Ticket Number\", 80), 'module':",
"self.transport_requests = transport_requests self.exceptions = self.load_exceptions() # WINDOW CREATION self.window",
"'export_datetime': (\"Export Timestamp\", 150), 'owner': (\"Owner\", 80) } # TREE",
"'subject': f\"Transport requests for: {', '.join(sorted(ticket_numbers)).rstrip(', ')}\", 'html_body': email_body_template.format(html_list_of_trs) }",
"for id_tag in selected_ids] # add TR number of selected",
"# prepare email details email_details = { 'recipient': RECIPIENT, 'subject':",
"not selected_ids: messagebox.showinfo( title=\"Status Info\", message=\"Nothing has been selected.\\n\\nPlease refresh",
"in self.tr_tree_view.get_children(): self.tr_tree_view.delete(item) # update with new data self.transport_requests.refresh() self.exceptions",
"= Button(text=\"REFRESH\", command=self.refresh) self.exceptions_btn = Button(text=\"Add to exceptions\", command=self.add_to_exceptions) self.select_all_btn",
"for item in self.tr_tree_view.get_children(): self.tr_tree_view.delete(item) # update with new data",
"list display self.tr_tree_view = ttk.Treeview(columns=tuple(columns_labels.keys()), show='headings') # Update columns for",
"#LAYOUT PLACEMENT self.title_lbl.grid(row=0, column=0, sticky=W) self.tr_tree_view.grid(row=1, column=0, rowspan=4) self.refresh_btn.grid(row=1, column=1,",
"as file: exception_dict = {'tr_numbers': []} json.dump(exception_dict, file, indent=4) return",
"from helpers import send_email RECIPIENT = <email_address> EXCEPTION_FILE = \"tr_number_exceptions.json\"",
"if all TRs are in exceptions, insert only pre-defined information",
"self.title_lbl.grid(row=0, column=0, sticky=W) self.tr_tree_view.grid(row=1, column=0, rowspan=4) self.refresh_btn.grid(row=1, column=1, sticky=N+S+E+W, padx=2,",
"line_values = (tr_number, description, ticket_type, ticket_number, sap_module, export_date_time, owner) self.tr_tree_view.insert('',",
"self.tr_tree_view.insert('', 'end', values=line_values) all_are_in_exceptions = False # if all TRs",
"email with import requests to TST\") self.window.config(padx=20, pady=20) # TTILE",
"'values')[0] for id_tag in selected_ids] # add TR number of",
"VIEW for list display self.tr_tree_view = ttk.Treeview(columns=tuple(columns_labels.keys()), show='headings') # Update",
"(tr_number, description, ticket_type, ticket_number, sap_module, export_timestamp, owner) in transport_data: html_list_of_trs",
"self.exceptions: year = export_timestamp[:4] month = export_timestamp[4:6] day = export_timestamp[6:8]",
"anchor='w', stretch=False) self.tr_tree_view.heading(column, text=label) # insert data self.populate_tree_view_lines() #LAYOUT PLACEMENT",
"# list of TRs columns_labels = { 'tr_number': (\"TR Number\",",
"# TTILE LABEL self.title_lbl = Label( text=\"Please select TRs to",
"'values') for id_tag in selected_ids] # prepare list of transports",
"export_timestamp[:4] month = export_timestamp[4:6] day = export_timestamp[6:8] time = f\"{export_timestamp[8:10]}:{export_timestamp[10:12]}:{export_timestamp[12:]}\"",
"self.tr_tree_view.column(column, minwidth=80, width=field_length, anchor='w', stretch=False) self.tr_tree_view.heading(column, text=label) # insert data",
"self.tr_tree_view.heading(column, text=label) # insert data self.populate_tree_view_lines() #LAYOUT PLACEMENT self.title_lbl.grid(row=0, column=0,",
"__init__(self, transport_requests: TRData): self.transport_requests = transport_requests self.exceptions = self.load_exceptions() #",
"messagebox.showinfo( title=\"Status Info\", message=\"Email has been sent!\") # add trs",
"f\"<li>{tr_number} - {owner} - {description}</li>\" ticket_numbers.add(ticket_number) # prepare email details",
"} # TREE VIEW for list display self.tr_tree_view = ttk.Treeview(columns=tuple(columns_labels.keys()),",
"(\"Owner\", 80) } # TREE VIEW for list display self.tr_tree_view",
"= set(json.load(file)['tr_numbers']) except FileNotFoundError: with open(file=EXCEPTION_FILE, mode='w') as file: exception_dict",
"description = NO_DATA_MEETS_CRITERIA[0][3] no_data_information = (tr_number, description, \"\", \"\", \"\",",
"self.refresh_btn.grid(row=1, column=1, sticky=N+S+E+W, padx=2, pady=2) self.exceptions_btn.grid(row=2, column=1, sticky=E+W+S, padx=1, pady=2)",
"owner) in transport_data: html_list_of_trs += f\"<li>{tr_number} - {owner} - {description}</li>\"",
"columns for column, (label, field_length) in columns_labels.items(): self.tr_tree_view.column(column, minwidth=80, width=field_length,",
"Info\", message=\"Email has been sent!\") # add trs into exceptions",
"transport_data: html_list_of_trs += f\"<li>{tr_number} - {owner} - {description}</li>\" ticket_numbers.add(ticket_number) #",
"(\"Export Timestamp\", 150), 'owner': (\"Owner\", 80) } # TREE VIEW",
"for (tr_number, description, ticket_type, ticket_number, sap_module, export_timestamp, owner) in transport_data:",
"# DISPLAY WINDOW self.window.mainloop() def refresh(self): # delete all rows",
"self.prepare_email_details(selected_ids) # send email if send_email(**email_details): messagebox.showinfo( title=\"Status Info\", message=\"Email",
"prepare list of transports for email body html_list_of_trs = \"\"",
"number in transport_numbers: self.exceptions.add(number) updated_data= {'tr_numbers': list(self.exceptions)} with open(file=EXCEPTION_FILE, mode='w')",
"try: with open(file=EXCEPTION_FILE, mode='r') as file: exception_list = set(json.load(file)['tr_numbers']) except",
"command=self.select_all) self.send_btn = Button(text=\"SEND\", command=self.send_email) # list of TRs columns_labels",
"with open(file=EXCEPTION_FILE, mode='r') as file: exception_list = set(json.load(file)['tr_numbers']) except FileNotFoundError:",
"= \"tr_number_exceptions.json\" class TrEmailSender: def __init__(self, transport_requests: TRData): self.transport_requests =",
"<email_address> EXCEPTION_FILE = \"tr_number_exceptions.json\" class TrEmailSender: def __init__(self, transport_requests: TRData):",
"to TST\") self.window.config(padx=20, pady=20) # TTILE LABEL self.title_lbl = Label(",
"= self.tr_tree_view.get_children() self.tr_tree_view.selection_add(items) def get_selected_item_ids(self): return self.tr_tree_view.selection() def send_email(self): #",
"sticky=W) self.tr_tree_view.grid(row=1, column=0, rowspan=4) self.refresh_btn.grid(row=1, column=1, sticky=N+S+E+W, padx=2, pady=2) self.exceptions_btn.grid(row=2,",
"columns_labels = { 'tr_number': (\"TR Number\", 100), 'description': (\"Description\", 350),",
"with new data self.transport_requests.refresh() self.exceptions = self.load_exceptions() self.populate_tree_view_lines() def populate_tree_view_lines(self):",
"TTILE LABEL self.title_lbl = Label( text=\"Please select TRs to be",
"with open(file=EXCEPTION_FILE, mode='w') as file: exception_dict = {'tr_numbers': []} json.dump(exception_dict,",
"send_email RECIPIENT = <email_address> EXCEPTION_FILE = \"tr_number_exceptions.json\" class TrEmailSender: def",
"'description': (\"Description\", 350), 'tkt_type': (\"Ticket Type\", 80), 'ticket_num': (\"Ticket Number\",",
"# if all TRs are in exceptions, insert only pre-defined",
"= Tk() self.window.title(\"Send email with import requests to TST\") self.window.config(padx=20,",
") return None transport_numbers = [self.tr_tree_view.item(id_tag, 'values')[0] for id_tag in",
"transport_requests: TRData): self.transport_requests = transport_requests self.exceptions = self.load_exceptions() # WINDOW",
"selected_ids: messagebox.showinfo( title=\"Status Info\", message=\"Nothing has been selected.\\n\\nPlease refresh the",
"TRData): self.transport_requests = transport_requests self.exceptions = self.load_exceptions() # WINDOW CREATION",
"load_exceptions(self): try: with open(file=EXCEPTION_FILE, mode='r') as file: exception_list = set(json.load(file)['tr_numbers'])",
"indent=4) return set() else: return exception_list def add_to_exceptions(self): selected_ids =",
"into email: \", ) # BUTTONS self.refresh_btn = Button(text=\"REFRESH\", command=self.refresh)",
"selected_ids: messagebox.showinfo( title=\"Status Info\", message=\"There is nothing to send.\\n\\nPlease refresh",
"{time}\" line_values = (tr_number, description, ticket_type, ticket_number, sap_module, export_date_time, owner)",
"to exceptions\", command=self.add_to_exceptions) self.select_all_btn = Button(text=\"Select All\", command=self.select_all) self.send_btn =",
"if not tr_number in self.exceptions: year = export_timestamp[:4] month =",
"tr_number = NO_DATA_MEETS_CRITERIA[0][0] description = NO_DATA_MEETS_CRITERIA[0][3] no_data_information = (tr_number, description,",
"return None transport_numbers = [self.tr_tree_view.item(id_tag, 'values')[0] for id_tag in selected_ids]",
"requests for: {', '.join(sorted(ticket_numbers)).rstrip(', ')}\", 'html_body': email_body_template.format(html_list_of_trs) } return email_details",
"Module\", 80), 'export_datetime': (\"Export Timestamp\", 150), 'owner': (\"Owner\", 80) }",
"the page.\" ) return None email_details = self.prepare_email_details(selected_ids) # send",
"def select_all(self): items = self.tr_tree_view.get_children() self.tr_tree_view.selection_add(items) def get_selected_item_ids(self): return self.tr_tree_view.selection()",
"pady=2) # DISPLAY WINDOW self.window.mainloop() def refresh(self): # delete all",
"selected_ids = self.get_selected_item_ids() if not selected_ids: messagebox.showinfo( title=\"Status Info\", message=\"Nothing",
"Number\", 80), 'module': (\"SAP Module\", 80), 'export_datetime': (\"Export Timestamp\", 150),",
"= self.prepare_email_details(selected_ids) # send email if send_email(**email_details): messagebox.showinfo( title=\"Status Info\",",
"def get_selected_item_ids(self): return self.tr_tree_view.selection() def send_email(self): # get selected lines",
"title=\"Status Info\", message=\"Email has been sent!\") # add trs into",
"of each id if not selected_ids: messagebox.showinfo( title=\"Status Info\", message=\"There",
"in self.exceptions: year = export_timestamp[:4] month = export_timestamp[4:6] day =",
"file: exception_dict = {'tr_numbers': []} json.dump(exception_dict, file, indent=4) return set()",
"TST\") self.window.config(padx=20, pady=20) # TTILE LABEL self.title_lbl = Label( text=\"Please",
"owner) self.tr_tree_view.insert('', 'end', values=line_values) all_are_in_exceptions = False # if all",
"\"\", \"\") self.tr_tree_view.insert('', 'end', values=no_data_information) def select_all(self): items = self.tr_tree_view.get_children()",
"# BUTTONS self.refresh_btn = Button(text=\"REFRESH\", command=self.refresh) self.exceptions_btn = Button(text=\"Add to",
"self.exceptions.add(number) updated_data= {'tr_numbers': list(self.exceptions)} with open(file=EXCEPTION_FILE, mode='w') as file: json.dump(updated_data,",
"self.add_to_exceptions() else: return None def prepare_email_details(self, selected_ids): transport_data = [self.tr_tree_view.item(id_tag,",
"command=self.add_to_exceptions) self.select_all_btn = Button(text=\"Select All\", command=self.select_all) self.send_btn = Button(text=\"SEND\", command=self.send_email)",
"# update with new data self.transport_requests.refresh() self.exceptions = self.load_exceptions() self.populate_tree_view_lines()",
"NO_DATA_MEETS_CRITERIA from email_text import email_body_template from helpers import send_email RECIPIENT",
"all_are_in_exceptions = True for (tr_number, export_timestamp, owner, description, ticket_number, sap_module,",
"import messagebox from tr_data import TRData, NO_DATA_MEETS_CRITERIA from email_text import",
"exception_list def add_to_exceptions(self): selected_ids = self.get_selected_item_ids() if not selected_ids: messagebox.showinfo(",
"mode='r') as file: exception_list = set(json.load(file)['tr_numbers']) except FileNotFoundError: with open(file=EXCEPTION_FILE,",
"each id if not selected_ids: messagebox.showinfo( title=\"Status Info\", message=\"There is",
"\"\", \"\", \"\", \"\") self.tr_tree_view.insert('', 'end', values=no_data_information) def select_all(self): items",
"EXCEPTION_FILE = \"tr_number_exceptions.json\" class TrEmailSender: def __init__(self, transport_requests: TRData): self.transport_requests",
"list(self.exceptions)} with open(file=EXCEPTION_FILE, mode='w') as file: json.dump(updated_data, file, indent=4) return",
"data self.transport_requests.refresh() self.exceptions = self.load_exceptions() self.populate_tree_view_lines() def populate_tree_view_lines(self): all_are_in_exceptions =",
"column=1, sticky=E+W+S, padx=1, pady=2) self.select_all_btn.grid(row=3, column=1, sticky=E+W+N, padx=1, pady=2) self.send_btn.grid(row=4,",
"page.\" ) return None email_details = self.prepare_email_details(selected_ids) # send email",
"prepare_email_details(self, selected_ids): transport_data = [self.tr_tree_view.item(id_tag, 'values') for id_tag in selected_ids]",
"description, ticket_type, ticket_number, sap_module, export_date_time, owner) self.tr_tree_view.insert('', 'end', values=line_values) all_are_in_exceptions",
"export_timestamp[4:6] day = export_timestamp[6:8] time = f\"{export_timestamp[8:10]}:{export_timestamp[10:12]}:{export_timestamp[12:]}\" export_date_time = f\"{day}/{month}/{year}",
"# WINDOW CREATION self.window = Tk() self.window.title(\"Send email with import",
"id_tag in selected_ids] # add TR number of selected items",
"TREE VIEW for list display self.tr_tree_view = ttk.Treeview(columns=tuple(columns_labels.keys()), show='headings') #",
"self.title_lbl = Label( text=\"Please select TRs to be included into",
"id_tag in selected_ids] # prepare list of transports for email",
"# add TR number of selected items to exception json",
"to exception json file for number in transport_numbers: self.exceptions.add(number) updated_data=",
"= self.get_selected_item_ids() if not selected_ids: messagebox.showinfo( title=\"Status Info\", message=\"Nothing has",
"sticky=E+W+N, padx=1, pady=2) self.send_btn.grid(row=4, column=1, sticky=N+S+E+W, padx=1, pady=2) # DISPLAY",
"stretch=False) self.tr_tree_view.heading(column, text=label) # insert data self.populate_tree_view_lines() #LAYOUT PLACEMENT self.title_lbl.grid(row=0,",
"- {time}\" line_values = (tr_number, description, ticket_type, ticket_number, sap_module, export_date_time,",
"(\"TR Number\", 100), 'description': (\"Description\", 350), 'tkt_type': (\"Ticket Type\", 80),",
"tr_number in self.exceptions: year = export_timestamp[:4] month = export_timestamp[4:6] day",
"of TRs columns_labels = { 'tr_number': (\"TR Number\", 100), 'description':",
"RECIPIENT, 'subject': f\"Transport requests for: {', '.join(sorted(ticket_numbers)).rstrip(', ')}\", 'html_body': email_body_template.format(html_list_of_trs)",
"in exception if not tr_number in self.exceptions: year = export_timestamp[:4]",
"f\"{day}/{month}/{year} - {time}\" line_values = (tr_number, description, ticket_type, ticket_number, sap_module,",
"of selected items to exception json file for number in",
"be included into email: \", ) # BUTTONS self.refresh_btn =",
"= ttk.Treeview(columns=tuple(columns_labels.keys()), show='headings') # Update columns for column, (label, field_length)",
"= f\"{day}/{month}/{year} - {time}\" line_values = (tr_number, description, ticket_type, ticket_number,",
"NO_DATA_MEETS_CRITERIA[0][0] description = NO_DATA_MEETS_CRITERIA[0][3] no_data_information = (tr_number, description, \"\", \"\",",
"if not in exception if not tr_number in self.exceptions: year",
"has been selected.\\n\\nPlease refresh the page.\" ) return None transport_numbers",
"self.transport_requests.data: # check if not in exception if not tr_number",
"class TrEmailSender: def __init__(self, transport_requests: TRData): self.transport_requests = transport_requests self.exceptions",
"return exception_list def add_to_exceptions(self): selected_ids = self.get_selected_item_ids() if not selected_ids:",
"transport_requests self.exceptions = self.load_exceptions() # WINDOW CREATION self.window = Tk()",
"selected_ids] # add TR number of selected items to exception",
"return self.add_to_exceptions() else: return None def prepare_email_details(self, selected_ids): transport_data =",
"been selected.\\n\\nPlease refresh the page.\" ) return None transport_numbers =",
"\"\", \"\", \"\") self.tr_tree_view.insert('', 'end', values=no_data_information) def select_all(self): items =",
"* from tkinter import ttk from tkinter import messagebox from",
"(label, field_length) in columns_labels.items(): self.tr_tree_view.column(column, minwidth=80, width=field_length, anchor='w', stretch=False) self.tr_tree_view.heading(column,",
"export_timestamp[6:8] time = f\"{export_timestamp[8:10]}:{export_timestamp[10:12]}:{export_timestamp[12:]}\" export_date_time = f\"{day}/{month}/{year} - {time}\" line_values",
"get selected lines selected_ids = self.get_selected_item_ids() # get data of",
"column=0, sticky=W) self.tr_tree_view.grid(row=1, column=0, rowspan=4) self.refresh_btn.grid(row=1, column=1, sticky=N+S+E+W, padx=2, pady=2)",
"Button(text=\"Add to exceptions\", command=self.add_to_exceptions) self.select_all_btn = Button(text=\"Select All\", command=self.select_all) self.send_btn",
"'html_body': email_body_template.format(html_list_of_trs) } return email_details def load_exceptions(self): try: with open(file=EXCEPTION_FILE,",
"= f\"{export_timestamp[8:10]}:{export_timestamp[10:12]}:{export_timestamp[12:]}\" export_date_time = f\"{day}/{month}/{year} - {time}\" line_values = (tr_number,",
"All\", command=self.select_all) self.send_btn = Button(text=\"SEND\", command=self.send_email) # list of TRs",
"send.\\n\\nPlease refresh the page.\" ) return None email_details = self.prepare_email_details(selected_ids)",
"tkinter import ttk from tkinter import messagebox from tr_data import",
"message=\"There is nothing to send.\\n\\nPlease refresh the page.\" ) return",
"from tkinter import messagebox from tr_data import TRData, NO_DATA_MEETS_CRITERIA from",
"(\"SAP Module\", 80), 'export_datetime': (\"Export Timestamp\", 150), 'owner': (\"Owner\", 80)",
"Button(text=\"REFRESH\", command=self.refresh) self.exceptions_btn = Button(text=\"Add to exceptions\", command=self.add_to_exceptions) self.select_all_btn =",
"title=\"Status Info\", message=\"There is nothing to send.\\n\\nPlease refresh the page.\"",
"return None email_details = self.prepare_email_details(selected_ids) # send email if send_email(**email_details):",
"width=field_length, anchor='w', stretch=False) self.tr_tree_view.heading(column, text=label) # insert data self.populate_tree_view_lines() #LAYOUT",
"= NO_DATA_MEETS_CRITERIA[0][0] description = NO_DATA_MEETS_CRITERIA[0][3] no_data_information = (tr_number, description, \"\",",
"all rows in tree view for item in self.tr_tree_view.get_children(): self.tr_tree_view.delete(item)",
"not selected_ids: messagebox.showinfo( title=\"Status Info\", message=\"There is nothing to send.\\n\\nPlease",
"if not selected_ids: messagebox.showinfo( title=\"Status Info\", message=\"There is nothing to",
"# get selected lines selected_ids = self.get_selected_item_ids() # get data",
"TR number of selected items to exception json file for",
"self.tr_tree_view.selection() def send_email(self): # get selected lines selected_ids = self.get_selected_item_ids()",
"columns_labels.items(): self.tr_tree_view.column(column, minwidth=80, width=field_length, anchor='w', stretch=False) self.tr_tree_view.heading(column, text=label) # insert",
"self.tr_tree_view.selection_add(items) def get_selected_item_ids(self): return self.tr_tree_view.selection() def send_email(self): # get selected",
"text=label) # insert data self.populate_tree_view_lines() #LAYOUT PLACEMENT self.title_lbl.grid(row=0, column=0, sticky=W)",
"email_details = { 'recipient': RECIPIENT, 'subject': f\"Transport requests for: {',",
"# send email if send_email(**email_details): messagebox.showinfo( title=\"Status Info\", message=\"Email has",
"set() else: return exception_list def add_to_exceptions(self): selected_ids = self.get_selected_item_ids() if",
"# insert data self.populate_tree_view_lines() #LAYOUT PLACEMENT self.title_lbl.grid(row=0, column=0, sticky=W) self.tr_tree_view.grid(row=1,",
"for (tr_number, export_timestamp, owner, description, ticket_number, sap_module, ticket_type) in self.transport_requests.data:",
"+= f\"<li>{tr_number} - {owner} - {description}</li>\" ticket_numbers.add(ticket_number) # prepare email",
"return self.tr_tree_view.selection() def send_email(self): # get selected lines selected_ids =",
"self.tr_tree_view.grid(row=1, column=0, rowspan=4) self.refresh_btn.grid(row=1, column=1, sticky=N+S+E+W, padx=2, pady=2) self.exceptions_btn.grid(row=2, column=1,",
"self.exceptions = self.load_exceptions() # WINDOW CREATION self.window = Tk() self.window.title(\"Send",
"been sent!\") # add trs into exceptions return self.add_to_exceptions() else:",
"ticket_type) in self.transport_requests.data: # check if not in exception if",
"= export_timestamp[6:8] time = f\"{export_timestamp[8:10]}:{export_timestamp[10:12]}:{export_timestamp[12:]}\" export_date_time = f\"{day}/{month}/{year} - {time}\"",
"owner, description, ticket_number, sap_module, ticket_type) in self.transport_requests.data: # check if",
"exceptions return self.add_to_exceptions() else: return None def prepare_email_details(self, selected_ids): transport_data",
"NO_DATA_MEETS_CRITERIA[0][3] no_data_information = (tr_number, description, \"\", \"\", \"\", \"\", \"\")",
"description, ticket_type, ticket_number, sap_module, export_timestamp, owner) in transport_data: html_list_of_trs +=",
"for column, (label, field_length) in columns_labels.items(): self.tr_tree_view.column(column, minwidth=80, width=field_length, anchor='w',",
"is nothing to send.\\n\\nPlease refresh the page.\" ) return None",
"<gh_stars>0 import json from tkinter import * from tkinter import",
"# Update columns for column, (label, field_length) in columns_labels.items(): self.tr_tree_view.column(column,",
"TRs are in exceptions, insert only pre-defined information if all_are_in_exceptions:",
"80), 'export_datetime': (\"Export Timestamp\", 150), 'owner': (\"Owner\", 80) } #",
"data of each id if not selected_ids: messagebox.showinfo( title=\"Status Info\",",
"from email_text import email_body_template from helpers import send_email RECIPIENT =",
"(\"Ticket Number\", 80), 'module': (\"SAP Module\", 80), 'export_datetime': (\"Export Timestamp\",",
"def add_to_exceptions(self): selected_ids = self.get_selected_item_ids() if not selected_ids: messagebox.showinfo( title=\"Status",
"body html_list_of_trs = \"\" ticket_numbers = set() for (tr_number, description,",
"html_list_of_trs = \"\" ticket_numbers = set() for (tr_number, description, ticket_type,",
"def populate_tree_view_lines(self): all_are_in_exceptions = True for (tr_number, export_timestamp, owner, description,",
"new data self.transport_requests.refresh() self.exceptions = self.load_exceptions() self.populate_tree_view_lines() def populate_tree_view_lines(self): all_are_in_exceptions",
"into exceptions return self.add_to_exceptions() else: return None def prepare_email_details(self, selected_ids):",
"insert only pre-defined information if all_are_in_exceptions: tr_number = NO_DATA_MEETS_CRITERIA[0][0] description",
"for number in transport_numbers: self.exceptions.add(number) updated_data= {'tr_numbers': list(self.exceptions)} with open(file=EXCEPTION_FILE,",
"True for (tr_number, export_timestamp, owner, description, ticket_number, sap_module, ticket_type) in",
"day = export_timestamp[6:8] time = f\"{export_timestamp[8:10]}:{export_timestamp[10:12]}:{export_timestamp[12:]}\" export_date_time = f\"{day}/{month}/{year} -",
"transport_numbers = [self.tr_tree_view.item(id_tag, 'values')[0] for id_tag in selected_ids] # add",
"Info\", message=\"There is nothing to send.\\n\\nPlease refresh the page.\" )",
"self.tr_tree_view.delete(item) # update with new data self.transport_requests.refresh() self.exceptions = self.load_exceptions()",
"for id_tag in selected_ids] # prepare list of transports for",
"None transport_numbers = [self.tr_tree_view.item(id_tag, 'values')[0] for id_tag in selected_ids] #",
"= Button(text=\"Select All\", command=self.select_all) self.send_btn = Button(text=\"SEND\", command=self.send_email) # list",
"tkinter import * from tkinter import ttk from tkinter import",
"def refresh(self): # delete all rows in tree view for",
"self.load_exceptions() self.populate_tree_view_lines() def populate_tree_view_lines(self): all_are_in_exceptions = True for (tr_number, export_timestamp,",
"= export_timestamp[:4] month = export_timestamp[4:6] day = export_timestamp[6:8] time =",
") return None email_details = self.prepare_email_details(selected_ids) # send email if",
"tr_data import TRData, NO_DATA_MEETS_CRITERIA from email_text import email_body_template from helpers",
"in transport_numbers: self.exceptions.add(number) updated_data= {'tr_numbers': list(self.exceptions)} with open(file=EXCEPTION_FILE, mode='w') as",
"select_all(self): items = self.tr_tree_view.get_children() self.tr_tree_view.selection_add(items) def get_selected_item_ids(self): return self.tr_tree_view.selection() def",
"{'tr_numbers': list(self.exceptions)} with open(file=EXCEPTION_FILE, mode='w') as file: json.dump(updated_data, file, indent=4)",
"exceptions, insert only pre-defined information if all_are_in_exceptions: tr_number = NO_DATA_MEETS_CRITERIA[0][0]",
"transport_numbers: self.exceptions.add(number) updated_data= {'tr_numbers': list(self.exceptions)} with open(file=EXCEPTION_FILE, mode='w') as file:",
"f\"{export_timestamp[8:10]}:{export_timestamp[10:12]}:{export_timestamp[12:]}\" export_date_time = f\"{day}/{month}/{year} - {time}\" line_values = (tr_number, description,",
"def send_email(self): # get selected lines selected_ids = self.get_selected_item_ids() #",
"{owner} - {description}</li>\" ticket_numbers.add(ticket_number) # prepare email details email_details =",
"display self.tr_tree_view = ttk.Treeview(columns=tuple(columns_labels.keys()), show='headings') # Update columns for column,",
"- {description}</li>\" ticket_numbers.add(ticket_number) # prepare email details email_details = {",
"file: exception_list = set(json.load(file)['tr_numbers']) except FileNotFoundError: with open(file=EXCEPTION_FILE, mode='w') as",
"exception json file for number in transport_numbers: self.exceptions.add(number) updated_data= {'tr_numbers':",
"= <email_address> EXCEPTION_FILE = \"tr_number_exceptions.json\" class TrEmailSender: def __init__(self, transport_requests:",
"self.tr_tree_view.get_children(): self.tr_tree_view.delete(item) # update with new data self.transport_requests.refresh() self.exceptions =",
"exception if not tr_number in self.exceptions: year = export_timestamp[:4] month",
"from tkinter import ttk from tkinter import messagebox from tr_data",
"sticky=N+S+E+W, padx=1, pady=2) # DISPLAY WINDOW self.window.mainloop() def refresh(self): #",
"items = self.tr_tree_view.get_children() self.tr_tree_view.selection_add(items) def get_selected_item_ids(self): return self.tr_tree_view.selection() def send_email(self):",
"messagebox.showinfo( title=\"Status Info\", message=\"There is nothing to send.\\n\\nPlease refresh the",
"description, \"\", \"\", \"\", \"\", \"\") self.tr_tree_view.insert('', 'end', values=no_data_information) def",
"sap_module, export_timestamp, owner) in transport_data: html_list_of_trs += f\"<li>{tr_number} - {owner}",
"Update columns for column, (label, field_length) in columns_labels.items(): self.tr_tree_view.column(column, minwidth=80,",
"self.populate_tree_view_lines() def populate_tree_view_lines(self): all_are_in_exceptions = True for (tr_number, export_timestamp, owner,",
"not tr_number in self.exceptions: year = export_timestamp[:4] month = export_timestamp[4:6]",
"email_details def load_exceptions(self): try: with open(file=EXCEPTION_FILE, mode='r') as file: exception_list",
"padx=1, pady=2) self.send_btn.grid(row=4, column=1, sticky=N+S+E+W, padx=1, pady=2) # DISPLAY WINDOW",
"title=\"Status Info\", message=\"Nothing has been selected.\\n\\nPlease refresh the page.\" )",
"email_details = self.prepare_email_details(selected_ids) # send email if send_email(**email_details): messagebox.showinfo( title=\"Status",
"\"\") self.tr_tree_view.insert('', 'end', values=no_data_information) def select_all(self): items = self.tr_tree_view.get_children() self.tr_tree_view.selection_add(items)",
"'owner': (\"Owner\", 80) } # TREE VIEW for list display",
"None email_details = self.prepare_email_details(selected_ids) # send email if send_email(**email_details): messagebox.showinfo(",
"sent!\") # add trs into exceptions return self.add_to_exceptions() else: return",
"values=line_values) all_are_in_exceptions = False # if all TRs are in",
"'end', values=no_data_information) def select_all(self): items = self.tr_tree_view.get_children() self.tr_tree_view.selection_add(items) def get_selected_item_ids(self):",
"# delete all rows in tree view for item in",
"(tr_number, description, ticket_type, ticket_number, sap_module, export_date_time, owner) self.tr_tree_view.insert('', 'end', values=line_values)",
"= { 'tr_number': (\"TR Number\", 100), 'description': (\"Description\", 350), 'tkt_type':",
"ticket_type, ticket_number, sap_module, export_date_time, owner) self.tr_tree_view.insert('', 'end', values=line_values) all_are_in_exceptions =",
"trs into exceptions return self.add_to_exceptions() else: return None def prepare_email_details(self,",
"padx=2, pady=2) self.exceptions_btn.grid(row=2, column=1, sticky=E+W+S, padx=1, pady=2) self.select_all_btn.grid(row=3, column=1, sticky=E+W+N,",
"rows in tree view for item in self.tr_tree_view.get_children(): self.tr_tree_view.delete(item) #",
"Info\", message=\"Nothing has been selected.\\n\\nPlease refresh the page.\" ) return",
"item in self.tr_tree_view.get_children(): self.tr_tree_view.delete(item) # update with new data self.transport_requests.refresh()",
"= self.load_exceptions() # WINDOW CREATION self.window = Tk() self.window.title(\"Send email",
"= set() for (tr_number, description, ticket_type, ticket_number, sap_module, export_timestamp, owner)",
"prepare email details email_details = { 'recipient': RECIPIENT, 'subject': f\"Transport",
"export_timestamp, owner) in transport_data: html_list_of_trs += f\"<li>{tr_number} - {owner} -",
"# TREE VIEW for list display self.tr_tree_view = ttk.Treeview(columns=tuple(columns_labels.keys()), show='headings')",
"self.exceptions = self.load_exceptions() self.populate_tree_view_lines() def populate_tree_view_lines(self): all_are_in_exceptions = True for",
"[self.tr_tree_view.item(id_tag, 'values') for id_tag in selected_ids] # prepare list of",
"selected_ids] # prepare list of transports for email body html_list_of_trs",
"= (tr_number, description, ticket_type, ticket_number, sap_module, export_date_time, owner) self.tr_tree_view.insert('', 'end',",
"get data of each id if not selected_ids: messagebox.showinfo( title=\"Status",
"self.get_selected_item_ids() if not selected_ids: messagebox.showinfo( title=\"Status Info\", message=\"Nothing has been",
"= self.load_exceptions() self.populate_tree_view_lines() def populate_tree_view_lines(self): all_are_in_exceptions = True for (tr_number,",
"of transports for email body html_list_of_trs = \"\" ticket_numbers =",
"[self.tr_tree_view.item(id_tag, 'values')[0] for id_tag in selected_ids] # add TR number",
"column=1, sticky=N+S+E+W, padx=1, pady=2) # DISPLAY WINDOW self.window.mainloop() def refresh(self):",
"TrEmailSender: def __init__(self, transport_requests: TRData): self.transport_requests = transport_requests self.exceptions =",
"'tr_number': (\"TR Number\", 100), 'description': (\"Description\", 350), 'tkt_type': (\"Ticket Type\",",
"import TRData, NO_DATA_MEETS_CRITERIA from email_text import email_body_template from helpers import",
"pady=2) self.select_all_btn.grid(row=3, column=1, sticky=E+W+N, padx=1, pady=2) self.send_btn.grid(row=4, column=1, sticky=N+S+E+W, padx=1,",
"html_list_of_trs += f\"<li>{tr_number} - {owner} - {description}</li>\" ticket_numbers.add(ticket_number) # prepare",
"to be included into email: \", ) # BUTTONS self.refresh_btn",
"DISPLAY WINDOW self.window.mainloop() def refresh(self): # delete all rows in",
") # BUTTONS self.refresh_btn = Button(text=\"REFRESH\", command=self.refresh) self.exceptions_btn = Button(text=\"Add",
"information if all_are_in_exceptions: tr_number = NO_DATA_MEETS_CRITERIA[0][0] description = NO_DATA_MEETS_CRITERIA[0][3] no_data_information",
"has been sent!\") # add trs into exceptions return self.add_to_exceptions()",
"in columns_labels.items(): self.tr_tree_view.column(column, minwidth=80, width=field_length, anchor='w', stretch=False) self.tr_tree_view.heading(column, text=label) #",
"get_selected_item_ids(self): return self.tr_tree_view.selection() def send_email(self): # get selected lines selected_ids",
"(\"Description\", 350), 'tkt_type': (\"Ticket Type\", 80), 'ticket_num': (\"Ticket Number\", 80),",
"def __init__(self, transport_requests: TRData): self.transport_requests = transport_requests self.exceptions = self.load_exceptions()",
"'end', values=line_values) all_are_in_exceptions = False # if all TRs are",
"show='headings') # Update columns for column, (label, field_length) in columns_labels.items():",
"command=self.refresh) self.exceptions_btn = Button(text=\"Add to exceptions\", command=self.add_to_exceptions) self.select_all_btn = Button(text=\"Select",
"= Button(text=\"SEND\", command=self.send_email) # list of TRs columns_labels = {",
"{ 'recipient': RECIPIENT, 'subject': f\"Transport requests for: {', '.join(sorted(ticket_numbers)).rstrip(', ')}\",",
"page.\" ) return None transport_numbers = [self.tr_tree_view.item(id_tag, 'values')[0] for id_tag",
"add_to_exceptions(self): selected_ids = self.get_selected_item_ids() if not selected_ids: messagebox.showinfo( title=\"Status Info\",",
"details email_details = { 'recipient': RECIPIENT, 'subject': f\"Transport requests for:",
"included into email: \", ) # BUTTONS self.refresh_btn = Button(text=\"REFRESH\",",
"\"tr_number_exceptions.json\" class TrEmailSender: def __init__(self, transport_requests: TRData): self.transport_requests = transport_requests",
"from tkinter import * from tkinter import ttk from tkinter",
"json.dump(exception_dict, file, indent=4) return set() else: return exception_list def add_to_exceptions(self):",
"(tr_number, export_timestamp, owner, description, ticket_number, sap_module, ticket_type) in self.transport_requests.data: #",
"number of selected items to exception json file for number",
"# prepare list of transports for email body html_list_of_trs =",
"time = f\"{export_timestamp[8:10]}:{export_timestamp[10:12]}:{export_timestamp[12:]}\" export_date_time = f\"{day}/{month}/{year} - {time}\" line_values =",
"= \"\" ticket_numbers = set() for (tr_number, description, ticket_type, ticket_number,",
"ticket_numbers.add(ticket_number) # prepare email details email_details = { 'recipient': RECIPIENT,",
"self.load_exceptions() # WINDOW CREATION self.window = Tk() self.window.title(\"Send email with",
"export_date_time, owner) self.tr_tree_view.insert('', 'end', values=line_values) all_are_in_exceptions = False # if",
"Button(text=\"Select All\", command=self.select_all) self.send_btn = Button(text=\"SEND\", command=self.send_email) # list of",
"} return email_details def load_exceptions(self): try: with open(file=EXCEPTION_FILE, mode='r') as",
"description, ticket_number, sap_module, ticket_type) in self.transport_requests.data: # check if not",
"self.exceptions_btn = Button(text=\"Add to exceptions\", command=self.add_to_exceptions) self.select_all_btn = Button(text=\"Select All\",",
"[]} json.dump(exception_dict, file, indent=4) return set() else: return exception_list def",
"lines selected_ids = self.get_selected_item_ids() # get data of each id",
"= NO_DATA_MEETS_CRITERIA[0][3] no_data_information = (tr_number, description, \"\", \"\", \"\", \"\",",
"def load_exceptions(self): try: with open(file=EXCEPTION_FILE, mode='r') as file: exception_list =",
"email if send_email(**email_details): messagebox.showinfo( title=\"Status Info\", message=\"Email has been sent!\")",
"Timestamp\", 150), 'owner': (\"Owner\", 80) } # TREE VIEW for",
"selected_ids = self.get_selected_item_ids() # get data of each id if",
"all_are_in_exceptions = False # if all TRs are in exceptions,",
"items to exception json file for number in transport_numbers: self.exceptions.add(number)",
"self.select_all_btn = Button(text=\"Select All\", command=self.select_all) self.send_btn = Button(text=\"SEND\", command=self.send_email) #",
"pre-defined information if all_are_in_exceptions: tr_number = NO_DATA_MEETS_CRITERIA[0][0] description = NO_DATA_MEETS_CRITERIA[0][3]",
"except FileNotFoundError: with open(file=EXCEPTION_FILE, mode='w') as file: exception_dict = {'tr_numbers':",
"80), 'ticket_num': (\"Ticket Number\", 80), 'module': (\"SAP Module\", 80), 'export_datetime':",
"json file for number in transport_numbers: self.exceptions.add(number) updated_data= {'tr_numbers': list(self.exceptions)}",
"sticky=N+S+E+W, padx=2, pady=2) self.exceptions_btn.grid(row=2, column=1, sticky=E+W+S, padx=1, pady=2) self.select_all_btn.grid(row=3, column=1,",
"False # if all TRs are in exceptions, insert only",
"exception_list = set(json.load(file)['tr_numbers']) except FileNotFoundError: with open(file=EXCEPTION_FILE, mode='w') as file:",
"100), 'description': (\"Description\", 350), 'tkt_type': (\"Ticket Type\", 80), 'ticket_num': (\"Ticket",
"check if not in exception if not tr_number in self.exceptions:",
"helpers import send_email RECIPIENT = <email_address> EXCEPTION_FILE = \"tr_number_exceptions.json\" class",
"padx=1, pady=2) # DISPLAY WINDOW self.window.mainloop() def refresh(self): # delete",
"ticket_number, sap_module, ticket_type) in self.transport_requests.data: # check if not in",
"populate_tree_view_lines(self): all_are_in_exceptions = True for (tr_number, export_timestamp, owner, description, ticket_number,",
"sap_module, ticket_type) in self.transport_requests.data: # check if not in exception",
"insert data self.populate_tree_view_lines() #LAYOUT PLACEMENT self.title_lbl.grid(row=0, column=0, sticky=W) self.tr_tree_view.grid(row=1, column=0,",
"= transport_requests self.exceptions = self.load_exceptions() # WINDOW CREATION self.window =",
"ttk from tkinter import messagebox from tr_data import TRData, NO_DATA_MEETS_CRITERIA",
"= [self.tr_tree_view.item(id_tag, 'values') for id_tag in selected_ids] # prepare list",
"LABEL self.title_lbl = Label( text=\"Please select TRs to be included",
"send email if send_email(**email_details): messagebox.showinfo( title=\"Status Info\", message=\"Email has been",
"values=no_data_information) def select_all(self): items = self.tr_tree_view.get_children() self.tr_tree_view.selection_add(items) def get_selected_item_ids(self): return",
"# check if not in exception if not tr_number in",
"update with new data self.transport_requests.refresh() self.exceptions = self.load_exceptions() self.populate_tree_view_lines() def",
"self.get_selected_item_ids() # get data of each id if not selected_ids:",
"email details email_details = { 'recipient': RECIPIENT, 'subject': f\"Transport requests",
"messagebox.showinfo( title=\"Status Info\", message=\"Nothing has been selected.\\n\\nPlease refresh the page.\"",
"send_email(self): # get selected lines selected_ids = self.get_selected_item_ids() # get",
"if not selected_ids: messagebox.showinfo( title=\"Status Info\", message=\"Nothing has been selected.\\n\\nPlease",
"TRs to be included into email: \", ) # BUTTONS",
"select TRs to be included into email: \", ) #",
"self.send_btn = Button(text=\"SEND\", command=self.send_email) # list of TRs columns_labels =",
"import * from tkinter import ttk from tkinter import messagebox",
"id if not selected_ids: messagebox.showinfo( title=\"Status Info\", message=\"There is nothing",
"self.transport_requests.refresh() self.exceptions = self.load_exceptions() self.populate_tree_view_lines() def populate_tree_view_lines(self): all_are_in_exceptions = True",
"month = export_timestamp[4:6] day = export_timestamp[6:8] time = f\"{export_timestamp[8:10]}:{export_timestamp[10:12]}:{export_timestamp[12:]}\" export_date_time",
"# get data of each id if not selected_ids: messagebox.showinfo(",
"add TR number of selected items to exception json file",
"\"\" ticket_numbers = set() for (tr_number, description, ticket_type, ticket_number, sap_module,",
"requests to TST\") self.window.config(padx=20, pady=20) # TTILE LABEL self.title_lbl =",
"column=1, sticky=N+S+E+W, padx=2, pady=2) self.exceptions_btn.grid(row=2, column=1, sticky=E+W+S, padx=1, pady=2) self.select_all_btn.grid(row=3,",
"the page.\" ) return None transport_numbers = [self.tr_tree_view.item(id_tag, 'values')[0] for",
"= (tr_number, description, \"\", \"\", \"\", \"\", \"\") self.tr_tree_view.insert('', 'end',",
"'ticket_num': (\"Ticket Number\", 80), 'module': (\"SAP Module\", 80), 'export_datetime': (\"Export",
"list of transports for email body html_list_of_trs = \"\" ticket_numbers",
"= [self.tr_tree_view.item(id_tag, 'values')[0] for id_tag in selected_ids] # add TR",
"(tr_number, description, \"\", \"\", \"\", \"\", \"\") self.tr_tree_view.insert('', 'end', values=no_data_information)",
"field_length) in columns_labels.items(): self.tr_tree_view.column(column, minwidth=80, width=field_length, anchor='w', stretch=False) self.tr_tree_view.heading(column, text=label)",
"year = export_timestamp[:4] month = export_timestamp[4:6] day = export_timestamp[6:8] time",
"FileNotFoundError: with open(file=EXCEPTION_FILE, mode='w') as file: exception_dict = {'tr_numbers': []}",
"tree view for item in self.tr_tree_view.get_children(): self.tr_tree_view.delete(item) # update with",
"ticket_numbers = set() for (tr_number, description, ticket_type, ticket_number, sap_module, export_timestamp,",
"self.window.title(\"Send email with import requests to TST\") self.window.config(padx=20, pady=20) #",
"no_data_information = (tr_number, description, \"\", \"\", \"\", \"\", \"\") self.tr_tree_view.insert('',",
"updated_data= {'tr_numbers': list(self.exceptions)} with open(file=EXCEPTION_FILE, mode='w') as file: json.dump(updated_data, file,",
"import ttk from tkinter import messagebox from tr_data import TRData,",
"80) } # TREE VIEW for list display self.tr_tree_view =",
"\", ) # BUTTONS self.refresh_btn = Button(text=\"REFRESH\", command=self.refresh) self.exceptions_btn =",
"= Button(text=\"Add to exceptions\", command=self.add_to_exceptions) self.select_all_btn = Button(text=\"Select All\", command=self.select_all)",
"file, indent=4) return set() else: return exception_list def add_to_exceptions(self): selected_ids",
"self.tr_tree_view = ttk.Treeview(columns=tuple(columns_labels.keys()), show='headings') # Update columns for column, (label,",
"ticket_type, ticket_number, sap_module, export_timestamp, owner) in transport_data: html_list_of_trs += f\"<li>{tr_number}",
"delete all rows in tree view for item in self.tr_tree_view.get_children():",
"- {owner} - {description}</li>\" ticket_numbers.add(ticket_number) # prepare email details email_details",
"= False # if all TRs are in exceptions, insert",
"with import requests to TST\") self.window.config(padx=20, pady=20) # TTILE LABEL",
"RECIPIENT = <email_address> EXCEPTION_FILE = \"tr_number_exceptions.json\" class TrEmailSender: def __init__(self,",
"CREATION self.window = Tk() self.window.title(\"Send email with import requests to",
"transports for email body html_list_of_trs = \"\" ticket_numbers = set()",
"email_body_template from helpers import send_email RECIPIENT = <email_address> EXCEPTION_FILE =",
"')}\", 'html_body': email_body_template.format(html_list_of_trs) } return email_details def load_exceptions(self): try: with",
"Label( text=\"Please select TRs to be included into email: \",",
"selected items to exception json file for number in transport_numbers:",
"'.join(sorted(ticket_numbers)).rstrip(', ')}\", 'html_body': email_body_template.format(html_list_of_trs) } return email_details def load_exceptions(self): try:",
"TRs columns_labels = { 'tr_number': (\"TR Number\", 100), 'description': (\"Description\",",
"set() for (tr_number, description, ticket_type, ticket_number, sap_module, export_timestamp, owner) in",
"in selected_ids] # add TR number of selected items to",
"email: \", ) # BUTTONS self.refresh_btn = Button(text=\"REFRESH\", command=self.refresh) self.exceptions_btn",
"import send_email RECIPIENT = <email_address> EXCEPTION_FILE = \"tr_number_exceptions.json\" class TrEmailSender:",
"= True for (tr_number, export_timestamp, owner, description, ticket_number, sap_module, ticket_type)",
"command=self.send_email) # list of TRs columns_labels = { 'tr_number': (\"TR",
"all_are_in_exceptions: tr_number = NO_DATA_MEETS_CRITERIA[0][0] description = NO_DATA_MEETS_CRITERIA[0][3] no_data_information = (tr_number,",
"# add trs into exceptions return self.add_to_exceptions() else: return None",
"sticky=E+W+S, padx=1, pady=2) self.select_all_btn.grid(row=3, column=1, sticky=E+W+N, padx=1, pady=2) self.send_btn.grid(row=4, column=1,",
"rowspan=4) self.refresh_btn.grid(row=1, column=1, sticky=N+S+E+W, padx=2, pady=2) self.exceptions_btn.grid(row=2, column=1, sticky=E+W+S, padx=1,",
"list of TRs columns_labels = { 'tr_number': (\"TR Number\", 100),",
"messagebox from tr_data import TRData, NO_DATA_MEETS_CRITERIA from email_text import email_body_template",
"column, (label, field_length) in columns_labels.items(): self.tr_tree_view.column(column, minwidth=80, width=field_length, anchor='w', stretch=False)",
"column=1, sticky=E+W+N, padx=1, pady=2) self.send_btn.grid(row=4, column=1, sticky=N+S+E+W, padx=1, pady=2) #",
"ttk.Treeview(columns=tuple(columns_labels.keys()), show='headings') # Update columns for column, (label, field_length) in",
"{description}</li>\" ticket_numbers.add(ticket_number) # prepare email details email_details = { 'recipient':",
"email_body_template.format(html_list_of_trs) } return email_details def load_exceptions(self): try: with open(file=EXCEPTION_FILE, mode='r')",
"refresh the page.\" ) return None transport_numbers = [self.tr_tree_view.item(id_tag, 'values')[0]",
"= {'tr_numbers': []} json.dump(exception_dict, file, indent=4) return set() else: return",
"pady=2) self.send_btn.grid(row=4, column=1, sticky=N+S+E+W, padx=1, pady=2) # DISPLAY WINDOW self.window.mainloop()",
"sap_module, export_date_time, owner) self.tr_tree_view.insert('', 'end', values=line_values) all_are_in_exceptions = False #",
"{ 'tr_number': (\"TR Number\", 100), 'description': (\"Description\", 350), 'tkt_type': (\"Ticket",
"self.exceptions_btn.grid(row=2, column=1, sticky=E+W+S, padx=1, pady=2) self.select_all_btn.grid(row=3, column=1, sticky=E+W+N, padx=1, pady=2)",
"'recipient': RECIPIENT, 'subject': f\"Transport requests for: {', '.join(sorted(ticket_numbers)).rstrip(', ')}\", 'html_body':",
"self.window.mainloop() def refresh(self): # delete all rows in tree view",
"WINDOW CREATION self.window = Tk() self.window.title(\"Send email with import requests",
"only pre-defined information if all_are_in_exceptions: tr_number = NO_DATA_MEETS_CRITERIA[0][0] description =",
"set(json.load(file)['tr_numbers']) except FileNotFoundError: with open(file=EXCEPTION_FILE, mode='w') as file: exception_dict =",
"import email_body_template from helpers import send_email RECIPIENT = <email_address> EXCEPTION_FILE",
"export_date_time = f\"{day}/{month}/{year} - {time}\" line_values = (tr_number, description, ticket_type,",
"for list display self.tr_tree_view = ttk.Treeview(columns=tuple(columns_labels.keys()), show='headings') # Update columns",
"in self.transport_requests.data: # check if not in exception if not",
"in selected_ids] # prepare list of transports for email body",
"from tr_data import TRData, NO_DATA_MEETS_CRITERIA from email_text import email_body_template from",
"PLACEMENT self.title_lbl.grid(row=0, column=0, sticky=W) self.tr_tree_view.grid(row=1, column=0, rowspan=4) self.refresh_btn.grid(row=1, column=1, sticky=N+S+E+W,",
"= Label( text=\"Please select TRs to be included into email:",
"email_text import email_body_template from helpers import send_email RECIPIENT = <email_address>",
"for email body html_list_of_trs = \"\" ticket_numbers = set() for",
"BUTTONS self.refresh_btn = Button(text=\"REFRESH\", command=self.refresh) self.exceptions_btn = Button(text=\"Add to exceptions\",",
"{'tr_numbers': []} json.dump(exception_dict, file, indent=4) return set() else: return exception_list",
"send_email(**email_details): messagebox.showinfo( title=\"Status Info\", message=\"Email has been sent!\") # add",
"TRData, NO_DATA_MEETS_CRITERIA from email_text import email_body_template from helpers import send_email",
"ticket_number, sap_module, export_timestamp, owner) in transport_data: html_list_of_trs += f\"<li>{tr_number} -",
"self.populate_tree_view_lines() #LAYOUT PLACEMENT self.title_lbl.grid(row=0, column=0, sticky=W) self.tr_tree_view.grid(row=1, column=0, rowspan=4) self.refresh_btn.grid(row=1,",
"self.send_btn.grid(row=4, column=1, sticky=N+S+E+W, padx=1, pady=2) # DISPLAY WINDOW self.window.mainloop() def",
"message=\"Nothing has been selected.\\n\\nPlease refresh the page.\" ) return None",
"ticket_number, sap_module, export_date_time, owner) self.tr_tree_view.insert('', 'end', values=line_values) all_are_in_exceptions = False",
"in tree view for item in self.tr_tree_view.get_children(): self.tr_tree_view.delete(item) # update",
"f\"Transport requests for: {', '.join(sorted(ticket_numbers)).rstrip(', ')}\", 'html_body': email_body_template.format(html_list_of_trs) } return",
"150), 'owner': (\"Owner\", 80) } # TREE VIEW for list",
"= self.get_selected_item_ids() # get data of each id if not",
"else: return None def prepare_email_details(self, selected_ids): transport_data = [self.tr_tree_view.item(id_tag, 'values')",
"text=\"Please select TRs to be included into email: \", )",
"'tkt_type': (\"Ticket Type\", 80), 'ticket_num': (\"Ticket Number\", 80), 'module': (\"SAP",
"with open(file=EXCEPTION_FILE, mode='w') as file: json.dump(updated_data, file, indent=4) return self.refresh()",
"'module': (\"SAP Module\", 80), 'export_datetime': (\"Export Timestamp\", 150), 'owner': (\"Owner\",",
"Type\", 80), 'ticket_num': (\"Ticket Number\", 80), 'module': (\"SAP Module\", 80),",
"80), 'module': (\"SAP Module\", 80), 'export_datetime': (\"Export Timestamp\", 150), 'owner':",
"json from tkinter import * from tkinter import ttk from",
"selected_ids): transport_data = [self.tr_tree_view.item(id_tag, 'values') for id_tag in selected_ids] #",
"Button(text=\"SEND\", command=self.send_email) # list of TRs columns_labels = { 'tr_number':",
"not in exception if not tr_number in self.exceptions: year =",
"self.select_all_btn.grid(row=3, column=1, sticky=E+W+N, padx=1, pady=2) self.send_btn.grid(row=4, column=1, sticky=N+S+E+W, padx=1, pady=2)",
"minwidth=80, width=field_length, anchor='w', stretch=False) self.tr_tree_view.heading(column, text=label) # insert data self.populate_tree_view_lines()",
"exception_dict = {'tr_numbers': []} json.dump(exception_dict, file, indent=4) return set() else:",
"return set() else: return exception_list def add_to_exceptions(self): selected_ids = self.get_selected_item_ids()",
"exceptions\", command=self.add_to_exceptions) self.select_all_btn = Button(text=\"Select All\", command=self.select_all) self.send_btn = Button(text=\"SEND\",",
"WINDOW self.window.mainloop() def refresh(self): # delete all rows in tree",
"for: {', '.join(sorted(ticket_numbers)).rstrip(', ')}\", 'html_body': email_body_template.format(html_list_of_trs) } return email_details def",
"if send_email(**email_details): messagebox.showinfo( title=\"Status Info\", message=\"Email has been sent!\") #",
"view for item in self.tr_tree_view.get_children(): self.tr_tree_view.delete(item) # update with new",
"= { 'recipient': RECIPIENT, 'subject': f\"Transport requests for: {', '.join(sorted(ticket_numbers)).rstrip(',",
"def prepare_email_details(self, selected_ids): transport_data = [self.tr_tree_view.item(id_tag, 'values') for id_tag in",
"message=\"Email has been sent!\") # add trs into exceptions return",
"as file: exception_list = set(json.load(file)['tr_numbers']) except FileNotFoundError: with open(file=EXCEPTION_FILE, mode='w')",
"selected lines selected_ids = self.get_selected_item_ids() # get data of each"
] |
[
"np import matplotlib.pyplot as plt import opt4_8_generateds import opt4_8_forward STEPS",
"shape=(None, 1)) X, Y_, Y_c = opt4_8_generateds.generateds() y = opt4_8_forward.forward(x,",
"#定义损失函数 loss_mse = tf.reduce_mean(tf.square(y-y_)) loss_total = loss_mse + tf.add_n(tf.get_collection('losses')) #定义反向传播方法:包含正则化",
"as sess: init_op = tf.global_variables_initializer() sess.run(init_op) for i in range(STEPS):",
"opt4_8_generateds.generateds() y = opt4_8_forward.forward(x, REGULARIZER) global_step = tf.Variable(0,trainable=False) learning_rate =",
"= probs.reshape(xx.shape) plt.scatter(X[:,0], X[:,1], c=np.squeeze(Y_c)) plt.contour(xx, yy, probs, levels=[.5]) plt.show()",
"with tf.Session() as sess: init_op = tf.global_variables_initializer() sess.run(init_op) for i",
"probs.reshape(xx.shape) plt.scatter(X[:,0], X[:,1], c=np.squeeze(Y_c)) plt.contour(xx, yy, probs, levels=[.5]) plt.show() if",
"X[start:end], y_:Y_[start:end]}) if i % 2000 == 0: loss_v =",
"y_:Y_[start:end]}) if i % 2000 == 0: loss_v = sess.run(loss_total,",
"loss_v = sess.run(loss_total, feed_dict={x:X,y_:Y_}) print(\"After %d steps, loss is: %f\"",
"#coding:utf-8 #0导入模块 ,生成模拟数据集 import tensorflow as tf import numpy as",
"as tf import numpy as np import matplotlib.pyplot as plt",
"feed_dict={x:X,y_:Y_}) print(\"After %d steps, loss is: %f\" %(i, loss_v)) xx,",
"#定义反向传播方法:包含正则化 train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss_total) with tf.Session() as sess: init_op =",
"0.001 LEARNING_RATE_DECAY = 0.999 REGULARIZER = 0.01 def backward(): x",
"yy.ravel()] probs = sess.run(y, feed_dict={x:grid}) probs = probs.reshape(xx.shape) plt.scatter(X[:,0], X[:,1],",
"in range(STEPS): start = (i*BATCH_SIZE) % 300 end = start",
"BATCH_SIZE = 30 LEARNING_RATE_BASE = 0.001 LEARNING_RATE_DECAY = 0.999 REGULARIZER",
"is: %f\" %(i, loss_v)) xx, yy = np.mgrid[-3:3:.01, -3:3:.01] grid",
"% 2000 == 0: loss_v = sess.run(loss_total, feed_dict={x:X,y_:Y_}) print(\"After %d",
"REGULARIZER = 0.01 def backward(): x = tf.placeholder(tf.float32, shape=(None, 2))",
"LEARNING_RATE_BASE, global_step, 300/BATCH_SIZE, LEARNING_RATE_DECAY, staircase=True) #定义损失函数 loss_mse = tf.reduce_mean(tf.square(y-y_)) loss_total",
"plt.scatter(X[:,0], X[:,1], c=np.squeeze(Y_c)) plt.contour(xx, yy, probs, levels=[.5]) plt.show() if __name__=='__main__':",
"= 30 LEARNING_RATE_BASE = 0.001 LEARNING_RATE_DECAY = 0.999 REGULARIZER =",
"feed_dict={x: X[start:end], y_:Y_[start:end]}) if i % 2000 == 0: loss_v",
"loss_total = loss_mse + tf.add_n(tf.get_collection('losses')) #定义反向传播方法:包含正则化 train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss_total) with",
"loss_mse + tf.add_n(tf.get_collection('losses')) #定义反向传播方法:包含正则化 train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss_total) with tf.Session() as",
"300 end = start + BATCH_SIZE sess.run(train_step, feed_dict={x: X[start:end], y_:Y_[start:end]})",
"tf.global_variables_initializer() sess.run(init_op) for i in range(STEPS): start = (i*BATCH_SIZE) %",
"xx, yy = np.mgrid[-3:3:.01, -3:3:.01] grid = np.c_[xx.ravel(), yy.ravel()] probs",
"sess.run(loss_total, feed_dict={x:X,y_:Y_}) print(\"After %d steps, loss is: %f\" %(i, loss_v))",
"0: loss_v = sess.run(loss_total, feed_dict={x:X,y_:Y_}) print(\"After %d steps, loss is:",
"tf.Variable(0,trainable=False) learning_rate = tf.train.exponential_decay( LEARNING_RATE_BASE, global_step, 300/BATCH_SIZE, LEARNING_RATE_DECAY, staircase=True) #定义损失函数",
"tf.add_n(tf.get_collection('losses')) #定义反向传播方法:包含正则化 train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss_total) with tf.Session() as sess: init_op",
"tf.placeholder(tf.float32, shape=(None, 1)) X, Y_, Y_c = opt4_8_generateds.generateds() y =",
"start = (i*BATCH_SIZE) % 300 end = start + BATCH_SIZE",
"learning_rate = tf.train.exponential_decay( LEARNING_RATE_BASE, global_step, 300/BATCH_SIZE, LEARNING_RATE_DECAY, staircase=True) #定义损失函数 loss_mse",
"REGULARIZER) global_step = tf.Variable(0,trainable=False) learning_rate = tf.train.exponential_decay( LEARNING_RATE_BASE, global_step, 300/BATCH_SIZE,",
"tf.placeholder(tf.float32, shape=(None, 2)) y_ = tf.placeholder(tf.float32, shape=(None, 1)) X, Y_,",
"+ tf.add_n(tf.get_collection('losses')) #定义反向传播方法:包含正则化 train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss_total) with tf.Session() as sess:",
"y = opt4_8_forward.forward(x, REGULARIZER) global_step = tf.Variable(0,trainable=False) learning_rate = tf.train.exponential_decay(",
"for i in range(STEPS): start = (i*BATCH_SIZE) % 300 end",
"= 40000 BATCH_SIZE = 30 LEARNING_RATE_BASE = 0.001 LEARNING_RATE_DECAY =",
"np.mgrid[-3:3:.01, -3:3:.01] grid = np.c_[xx.ravel(), yy.ravel()] probs = sess.run(y, feed_dict={x:grid})",
"global_step = tf.Variable(0,trainable=False) learning_rate = tf.train.exponential_decay( LEARNING_RATE_BASE, global_step, 300/BATCH_SIZE, LEARNING_RATE_DECAY,",
"LEARNING_RATE_BASE = 0.001 LEARNING_RATE_DECAY = 0.999 REGULARIZER = 0.01 def",
"steps, loss is: %f\" %(i, loss_v)) xx, yy = np.mgrid[-3:3:.01,",
"print(\"After %d steps, loss is: %f\" %(i, loss_v)) xx, yy",
"probs = sess.run(y, feed_dict={x:grid}) probs = probs.reshape(xx.shape) plt.scatter(X[:,0], X[:,1], c=np.squeeze(Y_c))",
"start + BATCH_SIZE sess.run(train_step, feed_dict={x: X[start:end], y_:Y_[start:end]}) if i %",
"X, Y_, Y_c = opt4_8_generateds.generateds() y = opt4_8_forward.forward(x, REGULARIZER) global_step",
"loss is: %f\" %(i, loss_v)) xx, yy = np.mgrid[-3:3:.01, -3:3:.01]",
"%d steps, loss is: %f\" %(i, loss_v)) xx, yy =",
"train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss_total) with tf.Session() as sess: init_op = tf.global_variables_initializer()",
"== 0: loss_v = sess.run(loss_total, feed_dict={x:X,y_:Y_}) print(\"After %d steps, loss",
"= opt4_8_forward.forward(x, REGULARIZER) global_step = tf.Variable(0,trainable=False) learning_rate = tf.train.exponential_decay( LEARNING_RATE_BASE,",
"X[:,1], c=np.squeeze(Y_c)) plt.contour(xx, yy, probs, levels=[.5]) plt.show() if __name__=='__main__': backward()",
"x = tf.placeholder(tf.float32, shape=(None, 2)) y_ = tf.placeholder(tf.float32, shape=(None, 1))",
"-3:3:.01] grid = np.c_[xx.ravel(), yy.ravel()] probs = sess.run(y, feed_dict={x:grid}) probs",
"def backward(): x = tf.placeholder(tf.float32, shape=(None, 2)) y_ = tf.placeholder(tf.float32,",
"opt4_8_forward STEPS = 40000 BATCH_SIZE = 30 LEARNING_RATE_BASE = 0.001",
"feed_dict={x:grid}) probs = probs.reshape(xx.shape) plt.scatter(X[:,0], X[:,1], c=np.squeeze(Y_c)) plt.contour(xx, yy, probs,",
"tf.train.exponential_decay( LEARNING_RATE_BASE, global_step, 300/BATCH_SIZE, LEARNING_RATE_DECAY, staircase=True) #定义损失函数 loss_mse = tf.reduce_mean(tf.square(y-y_))",
"sess.run(train_step, feed_dict={x: X[start:end], y_:Y_[start:end]}) if i % 2000 == 0:",
"= 0.001 LEARNING_RATE_DECAY = 0.999 REGULARIZER = 0.01 def backward():",
"plt import opt4_8_generateds import opt4_8_forward STEPS = 40000 BATCH_SIZE =",
"= np.c_[xx.ravel(), yy.ravel()] probs = sess.run(y, feed_dict={x:grid}) probs = probs.reshape(xx.shape)",
"import tensorflow as tf import numpy as np import matplotlib.pyplot",
"%(i, loss_v)) xx, yy = np.mgrid[-3:3:.01, -3:3:.01] grid = np.c_[xx.ravel(),",
"sess.run(y, feed_dict={x:grid}) probs = probs.reshape(xx.shape) plt.scatter(X[:,0], X[:,1], c=np.squeeze(Y_c)) plt.contour(xx, yy,",
"30 LEARNING_RATE_BASE = 0.001 LEARNING_RATE_DECAY = 0.999 REGULARIZER = 0.01",
"staircase=True) #定义损失函数 loss_mse = tf.reduce_mean(tf.square(y-y_)) loss_total = loss_mse + tf.add_n(tf.get_collection('losses'))",
"= tf.train.exponential_decay( LEARNING_RATE_BASE, global_step, 300/BATCH_SIZE, LEARNING_RATE_DECAY, staircase=True) #定义损失函数 loss_mse =",
"backward(): x = tf.placeholder(tf.float32, shape=(None, 2)) y_ = tf.placeholder(tf.float32, shape=(None,",
"300/BATCH_SIZE, LEARNING_RATE_DECAY, staircase=True) #定义损失函数 loss_mse = tf.reduce_mean(tf.square(y-y_)) loss_total = loss_mse",
"tf.reduce_mean(tf.square(y-y_)) loss_total = loss_mse + tf.add_n(tf.get_collection('losses')) #定义反向传播方法:包含正则化 train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss_total)",
"= loss_mse + tf.add_n(tf.get_collection('losses')) #定义反向传播方法:包含正则化 train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss_total) with tf.Session()",
"sess.run(init_op) for i in range(STEPS): start = (i*BATCH_SIZE) % 300",
"(i*BATCH_SIZE) % 300 end = start + BATCH_SIZE sess.run(train_step, feed_dict={x:",
"opt4_8_forward.forward(x, REGULARIZER) global_step = tf.Variable(0,trainable=False) learning_rate = tf.train.exponential_decay( LEARNING_RATE_BASE, global_step,",
"1)) X, Y_, Y_c = opt4_8_generateds.generateds() y = opt4_8_forward.forward(x, REGULARIZER)",
"if i % 2000 == 0: loss_v = sess.run(loss_total, feed_dict={x:X,y_:Y_})",
"0.999 REGULARIZER = 0.01 def backward(): x = tf.placeholder(tf.float32, shape=(None,",
"Y_, Y_c = opt4_8_generateds.generateds() y = opt4_8_forward.forward(x, REGULARIZER) global_step =",
"= sess.run(loss_total, feed_dict={x:X,y_:Y_}) print(\"After %d steps, loss is: %f\" %(i,",
"y_ = tf.placeholder(tf.float32, shape=(None, 1)) X, Y_, Y_c = opt4_8_generateds.generateds()",
"2)) y_ = tf.placeholder(tf.float32, shape=(None, 1)) X, Y_, Y_c =",
"matplotlib.pyplot as plt import opt4_8_generateds import opt4_8_forward STEPS = 40000",
"= 0.01 def backward(): x = tf.placeholder(tf.float32, shape=(None, 2)) y_",
"= tf.global_variables_initializer() sess.run(init_op) for i in range(STEPS): start = (i*BATCH_SIZE)",
"= start + BATCH_SIZE sess.run(train_step, feed_dict={x: X[start:end], y_:Y_[start:end]}) if i",
"np.c_[xx.ravel(), yy.ravel()] probs = sess.run(y, feed_dict={x:grid}) probs = probs.reshape(xx.shape) plt.scatter(X[:,0],",
"STEPS = 40000 BATCH_SIZE = 30 LEARNING_RATE_BASE = 0.001 LEARNING_RATE_DECAY",
"= tf.train.AdamOptimizer(learning_rate).minimize(loss_total) with tf.Session() as sess: init_op = tf.global_variables_initializer() sess.run(init_op)",
"BATCH_SIZE sess.run(train_step, feed_dict={x: X[start:end], y_:Y_[start:end]}) if i % 2000 ==",
"= tf.placeholder(tf.float32, shape=(None, 1)) X, Y_, Y_c = opt4_8_generateds.generateds() y",
"global_step, 300/BATCH_SIZE, LEARNING_RATE_DECAY, staircase=True) #定义损失函数 loss_mse = tf.reduce_mean(tf.square(y-y_)) loss_total =",
"= (i*BATCH_SIZE) % 300 end = start + BATCH_SIZE sess.run(train_step,",
"= tf.reduce_mean(tf.square(y-y_)) loss_total = loss_mse + tf.add_n(tf.get_collection('losses')) #定义反向传播方法:包含正则化 train_step =",
"loss_v)) xx, yy = np.mgrid[-3:3:.01, -3:3:.01] grid = np.c_[xx.ravel(), yy.ravel()]",
"opt4_8_generateds import opt4_8_forward STEPS = 40000 BATCH_SIZE = 30 LEARNING_RATE_BASE",
"end = start + BATCH_SIZE sess.run(train_step, feed_dict={x: X[start:end], y_:Y_[start:end]}) if",
"shape=(None, 2)) y_ = tf.placeholder(tf.float32, shape=(None, 1)) X, Y_, Y_c",
"loss_mse = tf.reduce_mean(tf.square(y-y_)) loss_total = loss_mse + tf.add_n(tf.get_collection('losses')) #定义反向传播方法:包含正则化 train_step",
"yy = np.mgrid[-3:3:.01, -3:3:.01] grid = np.c_[xx.ravel(), yy.ravel()] probs =",
"LEARNING_RATE_DECAY, staircase=True) #定义损失函数 loss_mse = tf.reduce_mean(tf.square(y-y_)) loss_total = loss_mse +",
"init_op = tf.global_variables_initializer() sess.run(init_op) for i in range(STEPS): start =",
"as plt import opt4_8_generateds import opt4_8_forward STEPS = 40000 BATCH_SIZE",
"% 300 end = start + BATCH_SIZE sess.run(train_step, feed_dict={x: X[start:end],",
"+ BATCH_SIZE sess.run(train_step, feed_dict={x: X[start:end], y_:Y_[start:end]}) if i % 2000",
"#0导入模块 ,生成模拟数据集 import tensorflow as tf import numpy as np",
"= tf.placeholder(tf.float32, shape=(None, 2)) y_ = tf.placeholder(tf.float32, shape=(None, 1)) X,",
"= opt4_8_generateds.generateds() y = opt4_8_forward.forward(x, REGULARIZER) global_step = tf.Variable(0,trainable=False) learning_rate",
"import opt4_8_generateds import opt4_8_forward STEPS = 40000 BATCH_SIZE = 30",
"tensorflow as tf import numpy as np import matplotlib.pyplot as",
"0.01 def backward(): x = tf.placeholder(tf.float32, shape=(None, 2)) y_ =",
"sess: init_op = tf.global_variables_initializer() sess.run(init_op) for i in range(STEPS): start",
"= tf.Variable(0,trainable=False) learning_rate = tf.train.exponential_decay( LEARNING_RATE_BASE, global_step, 300/BATCH_SIZE, LEARNING_RATE_DECAY, staircase=True)",
"40000 BATCH_SIZE = 30 LEARNING_RATE_BASE = 0.001 LEARNING_RATE_DECAY = 0.999",
"= np.mgrid[-3:3:.01, -3:3:.01] grid = np.c_[xx.ravel(), yy.ravel()] probs = sess.run(y,",
"probs = probs.reshape(xx.shape) plt.scatter(X[:,0], X[:,1], c=np.squeeze(Y_c)) plt.contour(xx, yy, probs, levels=[.5])",
"tf import numpy as np import matplotlib.pyplot as plt import",
"%f\" %(i, loss_v)) xx, yy = np.mgrid[-3:3:.01, -3:3:.01] grid =",
"LEARNING_RATE_DECAY = 0.999 REGULARIZER = 0.01 def backward(): x =",
"2000 == 0: loss_v = sess.run(loss_total, feed_dict={x:X,y_:Y_}) print(\"After %d steps,",
"import opt4_8_forward STEPS = 40000 BATCH_SIZE = 30 LEARNING_RATE_BASE =",
"grid = np.c_[xx.ravel(), yy.ravel()] probs = sess.run(y, feed_dict={x:grid}) probs =",
"= 0.999 REGULARIZER = 0.01 def backward(): x = tf.placeholder(tf.float32,",
"numpy as np import matplotlib.pyplot as plt import opt4_8_generateds import",
"i in range(STEPS): start = (i*BATCH_SIZE) % 300 end =",
"i % 2000 == 0: loss_v = sess.run(loss_total, feed_dict={x:X,y_:Y_}) print(\"After",
"tf.train.AdamOptimizer(learning_rate).minimize(loss_total) with tf.Session() as sess: init_op = tf.global_variables_initializer() sess.run(init_op) for",
",生成模拟数据集 import tensorflow as tf import numpy as np import",
"= sess.run(y, feed_dict={x:grid}) probs = probs.reshape(xx.shape) plt.scatter(X[:,0], X[:,1], c=np.squeeze(Y_c)) plt.contour(xx,",
"range(STEPS): start = (i*BATCH_SIZE) % 300 end = start +",
"Y_c = opt4_8_generateds.generateds() y = opt4_8_forward.forward(x, REGULARIZER) global_step = tf.Variable(0,trainable=False)",
"tf.Session() as sess: init_op = tf.global_variables_initializer() sess.run(init_op) for i in",
"import numpy as np import matplotlib.pyplot as plt import opt4_8_generateds",
"import matplotlib.pyplot as plt import opt4_8_generateds import opt4_8_forward STEPS =",
"as np import matplotlib.pyplot as plt import opt4_8_generateds import opt4_8_forward"
] |
[
"use this file except in #// compliance with the License.",
"= [] if not UVMConfigDb.get(self, \"\", \"vif\", vif): uvm_fatal(\"VIP/AGT/NOVIF\", \"No",
"<NAME> (tpoikela) #// All Rights Reserved Worldwide #// #// Licensed",
"#// #// Unless required by applicable law or agreed to",
"BASIS, WITHOUT WARRANTIES OR #// CONDITIONS OF ANY KIND, either",
"cocotb.fork(self.rx_mon.reset_and_suspend()) ]) #join self.sqr.stop_sequences() async def suspend(self): await sv.fork_join([ #",
".vip_sequencer import vip_sequencer from .vip_driver import vip_driver from .vip_monitor import",
"writing, software distributed under the License is #// distributed on",
"self.rx_mon = vip_monitor.type_id.create(\"rx_mon\", self) self.rx_mon.hier_objection = self.hier_objection self.tx_mon.hier_objection = self.hier_objection",
"build_phase(self, phase): self.sqr = vip_sequencer.type_id.create(\"sqr\", self) self.drv = vip_driver.type_id.create(\"drv\", self)",
"an \"AS IS\" BASIS, WITHOUT WARRANTIES OR #// CONDITIONS OF",
"def connect_phase(self, phase): self.drv.seq_item_port.connect(self.sqr.seq_item_export) async def pre_reset_phase(self, phase): if self.hier_objection:",
"resume(self): # fork await sv.fork_join([ cocotb.fork(self.drv.resume()), cocotb.fork(self.tx_mon.resume()), cocotb.fork(self.rx_mon.resume()), ]) #",
"distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR #//",
"vip_monitor.type_id.create(\"tx_mon\", self) self.rx_mon = vip_monitor.type_id.create(\"rx_mon\", self) self.rx_mon.hier_objection = self.hier_objection self.tx_mon.hier_objection",
"not use this file except in #// compliance with the",
".vip_monitor import vip_monitor class vip_agent(UVMAgent): def __init__(self, name, parent=None): super().__init__(name,",
"for the specific language governing #// permissions and limitations under",
"import vip_monitor class vip_agent(UVMAgent): def __init__(self, name, parent=None): super().__init__(name, parent)",
"with the License. You may obtain a copy of #//",
"self.hier_objection: print(\"vip_agent dropping objection\") phase.drop_objection(self) async def reset_and_suspend(self): #fork await",
"from uvm import * from .vip_sequencer import vip_sequencer from .vip_driver",
"* from .vip_sequencer import vip_sequencer from .vip_driver import vip_driver from",
"pre_reset_phase(self, phase): if self.hier_objection: phase.raise_objection(self, \"Resetting agent\") await self.reset_and_suspend() if",
"print(\"vip_agent dropping objection\") phase.drop_objection(self) async def reset_and_suspend(self): #fork await sv.fork_join([",
"= self.hier_objection vif = [] if not UVMConfigDb.get(self, \"\", \"vif\",",
"WARRANTIES OR #// CONDITIONS OF ANY KIND, either express or",
"def resume(self): # fork await sv.fork_join([ cocotb.fork(self.drv.resume()), cocotb.fork(self.tx_mon.resume()), cocotb.fork(self.rx_mon.resume()), ])",
"#// distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR",
"join async def resume(self): # fork await sv.fork_join([ cocotb.fork(self.drv.resume()), cocotb.fork(self.tx_mon.resume()),",
"self.drv = vip_driver.type_id.create(\"drv\", self) self.tx_mon = vip_monitor.type_id.create(\"tx_mon\", self) self.rx_mon =",
"await sv.fork_join([ cocotb.fork(self.drv.reset_and_suspend()), cocotb.fork(self.tx_mon.reset_and_suspend()), cocotb.fork(self.rx_mon.reset_and_suspend()) ]) #join self.sqr.stop_sequences() async def",
"# join async def resume(self): # fork await sv.fork_join([ cocotb.fork(self.drv.resume()),",
"vip_monitor class vip_agent(UVMAgent): def __init__(self, name, parent=None): super().__init__(name, parent) self.hier_objection",
"\"License\"); you may not use this file except in #//",
"def reset_and_suspend(self): #fork await sv.fork_join([ cocotb.fork(self.drv.reset_and_suspend()), cocotb.fork(self.tx_mon.reset_and_suspend()), cocotb.fork(self.rx_mon.reset_and_suspend()) ]) #join",
"Inc. #// Copyright 2019-2020 <NAME> (tpoikela) #// All Rights Reserved",
"Reserved Worldwide #// #// Licensed under the Apache License, Version",
"(the #// \"License\"); you may not use this file except",
"Synopsys, Inc. #// Copyright 2019-2020 <NAME> (tpoikela) #// All Rights",
"required by applicable law or agreed to in #// writing,",
"vip_sequencer from .vip_driver import vip_driver from .vip_monitor import vip_monitor class",
"= vip_driver.type_id.create(\"drv\", self) self.tx_mon = vip_monitor.type_id.create(\"tx_mon\", self) self.rx_mon = vip_monitor.type_id.create(\"rx_mon\",",
"Copyright 2011 Synopsys, Inc. #// Copyright 2019-2020 <NAME> (tpoikela) #//",
"under the License. #// ------------------------------------------------------------- #// from uvm import *",
"------------------------------------------------------------- #// Copyright 2011 Synopsys, Inc. #// Copyright 2019-2020 <NAME>",
"#join self.sqr.stop_sequences() async def suspend(self): await sv.fork_join([ # fork cocotb.fork(self.drv.suspend()),",
"async def suspend(self): await sv.fork_join([ # fork cocotb.fork(self.drv.suspend()), cocotb.fork(self.tx_mon.suspend()), cocotb.fork(self.rx_mon.suspend()),",
"a copy of #// the License at #// #// http://www.apache.org/licenses/LICENSE-2.0",
"Rights Reserved Worldwide #// #// Licensed under the Apache License,",
"file except in #// compliance with the License. You may",
"the specific language governing #// permissions and limitations under the",
"vip_agent(UVMAgent): def __init__(self, name, parent=None): super().__init__(name, parent) self.hier_objection = False",
"License, Version 2.0 (the #// \"License\"); you may not use",
"the License. You may obtain a copy of #// the",
"See #// the License for the specific language governing #//",
"by applicable law or agreed to in #// writing, software",
"= self.hier_objection self.drv.hier_objection = self.hier_objection vif = [] if not",
"\"\", \"vif\", vif): uvm_fatal(\"VIP/AGT/NOVIF\", \"No virtual interface specified for self",
"# fork await sv.fork_join([ cocotb.fork(self.drv.resume()), cocotb.fork(self.tx_mon.resume()), cocotb.fork(self.rx_mon.resume()), ]) # join",
"self.tx_mon = vip_monitor.type_id.create(\"tx_mon\", self) self.rx_mon = vip_monitor.type_id.create(\"rx_mon\", self) self.rx_mon.hier_objection =",
"under the Apache License, Version 2.0 (the #// \"License\"); you",
"Apache License, Version 2.0 (the #// \"License\"); you may not",
"from .vip_sequencer import vip_sequencer from .vip_driver import vip_driver from .vip_monitor",
"2.0 (the #// \"License\"); you may not use this file",
"self.vif.rx) def connect_phase(self, phase): self.drv.seq_item_port.connect(self.sqr.seq_item_export) async def pre_reset_phase(self, phase): if",
"import vip_sequencer from .vip_driver import vip_driver from .vip_monitor import vip_monitor",
"self.drv.hier_objection = self.hier_objection vif = [] if not UVMConfigDb.get(self, \"\",",
"cocotb.fork(self.tx_mon.reset_and_suspend()), cocotb.fork(self.rx_mon.reset_and_suspend()) ]) #join self.sqr.stop_sequences() async def suspend(self): await sv.fork_join([",
"self.hier_objection self.tx_mon.hier_objection = self.hier_objection self.drv.hier_objection = self.hier_objection vif = []",
"#// All Rights Reserved Worldwide #// #// Licensed under the",
"Copyright 2019-2020 <NAME> (tpoikela) #// All Rights Reserved Worldwide #//",
"in #// writing, software distributed under the License is #//",
"express or implied. See #// the License for the specific",
"\"vif\", self.vif.rx) def connect_phase(self, phase): self.drv.seq_item_port.connect(self.sqr.seq_item_export) async def pre_reset_phase(self, phase):",
"distributed under the License is #// distributed on an \"AS",
"#fork await sv.fork_join([ cocotb.fork(self.drv.reset_and_suspend()), cocotb.fork(self.tx_mon.reset_and_suspend()), cocotb.fork(self.rx_mon.reset_and_suspend()) ]) #join self.sqr.stop_sequences() async",
"Worldwide #// #// Licensed under the Apache License, Version 2.0",
"IS\" BASIS, WITHOUT WARRANTIES OR #// CONDITIONS OF ANY KIND,",
"governing #// permissions and limitations under the License. #// -------------------------------------------------------------",
"the License is #// distributed on an \"AS IS\" BASIS,",
"#// #// http://www.apache.org/licenses/LICENSE-2.0 #// #// Unless required by applicable law",
"the License for the specific language governing #// permissions and",
"vip_driver from .vip_monitor import vip_monitor class vip_agent(UVMAgent): def __init__(self, name,",
"= vip_monitor.type_id.create(\"rx_mon\", self) self.rx_mon.hier_objection = self.hier_objection self.tx_mon.hier_objection = self.hier_objection self.drv.hier_objection",
"\"No virtual interface specified for self agent instance\") self.vif =",
"limitations under the License. #// ------------------------------------------------------------- #// from uvm import",
"= self.hier_objection self.tx_mon.hier_objection = self.hier_objection self.drv.hier_objection = self.hier_objection vif =",
"#// writing, software distributed under the License is #// distributed",
"vif): uvm_fatal(\"VIP/AGT/NOVIF\", \"No virtual interface specified for self agent instance\")",
"2011 Synopsys, Inc. #// Copyright 2019-2020 <NAME> (tpoikela) #// All",
"def __init__(self, name, parent=None): super().__init__(name, parent) self.hier_objection = False def",
"KIND, either express or implied. See #// the License for",
"async def reset_and_suspend(self): #fork await sv.fork_join([ cocotb.fork(self.drv.reset_and_suspend()), cocotb.fork(self.tx_mon.reset_and_suspend()), cocotb.fork(self.rx_mon.reset_and_suspend()) ])",
"#// from uvm import * from .vip_sequencer import vip_sequencer from",
"phase): self.sqr = vip_sequencer.type_id.create(\"sqr\", self) self.drv = vip_driver.type_id.create(\"drv\", self) self.tx_mon",
"#// Copyright 2019-2020 <NAME> (tpoikela) #// All Rights Reserved Worldwide",
"ANY KIND, either express or implied. See #// the License",
"uvm import * from .vip_sequencer import vip_sequencer from .vip_driver import",
"law or agreed to in #// writing, software distributed under",
"def pre_reset_phase(self, phase): if self.hier_objection: phase.raise_objection(self, \"Resetting agent\") await self.reset_and_suspend()",
"]) #join self.sqr.stop_sequences() async def suspend(self): await sv.fork_join([ # fork",
"#// #// ------------------------------------------------------------- #// Copyright 2011 Synopsys, Inc. #// Copyright",
"under the License is #// distributed on an \"AS IS\"",
"from .vip_monitor import vip_monitor class vip_agent(UVMAgent): def __init__(self, name, parent=None):",
"__init__(self, name, parent=None): super().__init__(name, parent) self.hier_objection = False def build_phase(self,",
"\"tx_mon\", \"vif\", self.vif.tx_mon) UVMConfigDb.set(self, \"rx_mon\", \"vif\", self.vif.rx) def connect_phase(self, phase):",
"if self.hier_objection: phase.raise_objection(self, \"Resetting agent\") await self.reset_and_suspend() if self.hier_objection: print(\"vip_agent",
"agent instance\") self.vif = vif[0] UVMConfigDb.set(self, \"tx_mon\", \"vif\", self.vif.tx_mon) UVMConfigDb.set(self,",
"self.hier_objection: phase.raise_objection(self, \"Resetting agent\") await self.reset_and_suspend() if self.hier_objection: print(\"vip_agent dropping",
"self.reset_and_suspend() if self.hier_objection: print(\"vip_agent dropping objection\") phase.drop_objection(self) async def reset_and_suspend(self):",
"not UVMConfigDb.get(self, \"\", \"vif\", vif): uvm_fatal(\"VIP/AGT/NOVIF\", \"No virtual interface specified",
"from .vip_driver import vip_driver from .vip_monitor import vip_monitor class vip_agent(UVMAgent):",
"uvm_fatal(\"VIP/AGT/NOVIF\", \"No virtual interface specified for self agent instance\") self.vif",
"]) # join async def resume(self): # fork await sv.fork_join([",
".vip_driver import vip_driver from .vip_monitor import vip_monitor class vip_agent(UVMAgent): def",
"#// compliance with the License. You may obtain a copy",
"vip_driver.type_id.create(\"drv\", self) self.tx_mon = vip_monitor.type_id.create(\"tx_mon\", self) self.rx_mon = vip_monitor.type_id.create(\"rx_mon\", self)",
"connect_phase(self, phase): self.drv.seq_item_port.connect(self.sqr.seq_item_export) async def pre_reset_phase(self, phase): if self.hier_objection: phase.raise_objection(self,",
"\"AS IS\" BASIS, WITHOUT WARRANTIES OR #// CONDITIONS OF ANY",
"UVMConfigDb.set(self, \"tx_mon\", \"vif\", self.vif.tx_mon) UVMConfigDb.set(self, \"rx_mon\", \"vif\", self.vif.rx) def connect_phase(self,",
"UVMConfigDb.set(self, \"rx_mon\", \"vif\", self.vif.rx) def connect_phase(self, phase): self.drv.seq_item_port.connect(self.sqr.seq_item_export) async def",
"the License at #// #// http://www.apache.org/licenses/LICENSE-2.0 #// #// Unless required",
"if self.hier_objection: print(\"vip_agent dropping objection\") phase.drop_objection(self) async def reset_and_suspend(self): #fork",
"def build_phase(self, phase): self.sqr = vip_sequencer.type_id.create(\"sqr\", self) self.drv = vip_driver.type_id.create(\"drv\",",
"suspend(self): await sv.fork_join([ # fork cocotb.fork(self.drv.suspend()), cocotb.fork(self.tx_mon.suspend()), cocotb.fork(self.rx_mon.suspend()), ]) #",
"self.hier_objection vif = [] if not UVMConfigDb.get(self, \"\", \"vif\", vif):",
"You may obtain a copy of #// the License at",
"except in #// compliance with the License. You may obtain",
"CONDITIONS OF ANY KIND, either express or implied. See #//",
"async def resume(self): # fork await sv.fork_join([ cocotb.fork(self.drv.resume()), cocotb.fork(self.tx_mon.resume()), cocotb.fork(self.rx_mon.resume()),",
"cocotb.fork(self.drv.reset_and_suspend()), cocotb.fork(self.tx_mon.reset_and_suspend()), cocotb.fork(self.rx_mon.reset_and_suspend()) ]) #join self.sqr.stop_sequences() async def suspend(self): await",
"on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR #// CONDITIONS",
"\"vif\", vif): uvm_fatal(\"VIP/AGT/NOVIF\", \"No virtual interface specified for self agent",
"objection\") phase.drop_objection(self) async def reset_and_suspend(self): #fork await sv.fork_join([ cocotb.fork(self.drv.reset_and_suspend()), cocotb.fork(self.tx_mon.reset_and_suspend()),",
"sv.fork_join([ # fork cocotb.fork(self.drv.suspend()), cocotb.fork(self.tx_mon.suspend()), cocotb.fork(self.rx_mon.suspend()), ]) # join async",
"to in #// writing, software distributed under the License is",
"\"vif\", self.vif.tx_mon) UVMConfigDb.set(self, \"rx_mon\", \"vif\", self.vif.rx) def connect_phase(self, phase): self.drv.seq_item_port.connect(self.sqr.seq_item_export)",
"self.vif.tx_mon) UVMConfigDb.set(self, \"rx_mon\", \"vif\", self.vif.rx) def connect_phase(self, phase): self.drv.seq_item_port.connect(self.sqr.seq_item_export) async",
"specified for self agent instance\") self.vif = vif[0] UVMConfigDb.set(self, \"tx_mon\",",
"fork cocotb.fork(self.drv.suspend()), cocotb.fork(self.tx_mon.suspend()), cocotb.fork(self.rx_mon.suspend()), ]) # join async def resume(self):",
"= vip_monitor.type_id.create(\"tx_mon\", self) self.rx_mon = vip_monitor.type_id.create(\"rx_mon\", self) self.rx_mon.hier_objection = self.hier_objection",
"License. You may obtain a copy of #// the License",
"import * from .vip_sequencer import vip_sequencer from .vip_driver import vip_driver",
"fork await sv.fork_join([ cocotb.fork(self.drv.resume()), cocotb.fork(self.tx_mon.resume()), cocotb.fork(self.rx_mon.resume()), ]) # join uvm_component_utils(vip_agent)",
"http://www.apache.org/licenses/LICENSE-2.0 #// #// Unless required by applicable law or agreed",
"instance\") self.vif = vif[0] UVMConfigDb.set(self, \"tx_mon\", \"vif\", self.vif.tx_mon) UVMConfigDb.set(self, \"rx_mon\",",
"applicable law or agreed to in #// writing, software distributed",
"interface specified for self agent instance\") self.vif = vif[0] UVMConfigDb.set(self,",
"self) self.rx_mon = vip_monitor.type_id.create(\"rx_mon\", self) self.rx_mon.hier_objection = self.hier_objection self.tx_mon.hier_objection =",
"may not use this file except in #// compliance with",
"self) self.rx_mon.hier_objection = self.hier_objection self.tx_mon.hier_objection = self.hier_objection self.drv.hier_objection = self.hier_objection",
"self.sqr = vip_sequencer.type_id.create(\"sqr\", self) self.drv = vip_driver.type_id.create(\"drv\", self) self.tx_mon =",
"await sv.fork_join([ # fork cocotb.fork(self.drv.suspend()), cocotb.fork(self.tx_mon.suspend()), cocotb.fork(self.rx_mon.suspend()), ]) # join",
"parent) self.hier_objection = False def build_phase(self, phase): self.sqr = vip_sequencer.type_id.create(\"sqr\",",
"License for the specific language governing #// permissions and limitations",
"\"rx_mon\", \"vif\", self.vif.rx) def connect_phase(self, phase): self.drv.seq_item_port.connect(self.sqr.seq_item_export) async def pre_reset_phase(self,",
"async def pre_reset_phase(self, phase): if self.hier_objection: phase.raise_objection(self, \"Resetting agent\") await",
"software distributed under the License is #// distributed on an",
"#// \"License\"); you may not use this file except in",
"for self agent instance\") self.vif = vif[0] UVMConfigDb.set(self, \"tx_mon\", \"vif\",",
"agreed to in #// writing, software distributed under the License",
"= vif[0] UVMConfigDb.set(self, \"tx_mon\", \"vif\", self.vif.tx_mon) UVMConfigDb.set(self, \"rx_mon\", \"vif\", self.vif.rx)",
"cocotb.fork(self.drv.suspend()), cocotb.fork(self.tx_mon.suspend()), cocotb.fork(self.rx_mon.suspend()), ]) # join async def resume(self): #",
"name, parent=None): super().__init__(name, parent) self.hier_objection = False def build_phase(self, phase):",
"import vip_driver from .vip_monitor import vip_monitor class vip_agent(UVMAgent): def __init__(self,",
"#// ------------------------------------------------------------- #// from uvm import * from .vip_sequencer import",
"await self.reset_and_suspend() if self.hier_objection: print(\"vip_agent dropping objection\") phase.drop_objection(self) async def",
"License at #// #// http://www.apache.org/licenses/LICENSE-2.0 #// #// Unless required by",
"#// Copyright 2011 Synopsys, Inc. #// Copyright 2019-2020 <NAME> (tpoikela)",
"#// ------------------------------------------------------------- #// Copyright 2011 Synopsys, Inc. #// Copyright 2019-2020",
"2019-2020 <NAME> (tpoikela) #// All Rights Reserved Worldwide #// #//",
"compliance with the License. You may obtain a copy of",
"virtual interface specified for self agent instance\") self.vif = vif[0]",
"vif[0] UVMConfigDb.set(self, \"tx_mon\", \"vif\", self.vif.tx_mon) UVMConfigDb.set(self, \"rx_mon\", \"vif\", self.vif.rx) def",
"this file except in #// compliance with the License. You",
"= vip_sequencer.type_id.create(\"sqr\", self) self.drv = vip_driver.type_id.create(\"drv\", self) self.tx_mon = vip_monitor.type_id.create(\"tx_mon\",",
"either express or implied. See #// the License for the",
"language governing #// permissions and limitations under the License. #//",
"False def build_phase(self, phase): self.sqr = vip_sequencer.type_id.create(\"sqr\", self) self.drv =",
"def suspend(self): await sv.fork_join([ # fork cocotb.fork(self.drv.suspend()), cocotb.fork(self.tx_mon.suspend()), cocotb.fork(self.rx_mon.suspend()), ])",
"#// the License at #// #// http://www.apache.org/licenses/LICENSE-2.0 #// #// Unless",
"Unless required by applicable law or agreed to in #//",
"the Apache License, Version 2.0 (the #// \"License\"); you may",
"may obtain a copy of #// the License at #//",
"agent\") await self.reset_and_suspend() if self.hier_objection: print(\"vip_agent dropping objection\") phase.drop_objection(self) async",
"self.hier_objection self.drv.hier_objection = self.hier_objection vif = [] if not UVMConfigDb.get(self,",
"vip_sequencer.type_id.create(\"sqr\", self) self.drv = vip_driver.type_id.create(\"drv\", self) self.tx_mon = vip_monitor.type_id.create(\"tx_mon\", self)",
"phase): if self.hier_objection: phase.raise_objection(self, \"Resetting agent\") await self.reset_and_suspend() if self.hier_objection:",
"All Rights Reserved Worldwide #// #// Licensed under the Apache",
"class vip_agent(UVMAgent): def __init__(self, name, parent=None): super().__init__(name, parent) self.hier_objection =",
"#// CONDITIONS OF ANY KIND, either express or implied. See",
"obtain a copy of #// the License at #// #//",
"License. #// ------------------------------------------------------------- #// from uvm import * from .vip_sequencer",
"or implied. See #// the License for the specific language",
"#// Unless required by applicable law or agreed to in",
"Licensed under the Apache License, Version 2.0 (the #// \"License\");",
"at #// #// http://www.apache.org/licenses/LICENSE-2.0 #// #// Unless required by applicable",
"reset_and_suspend(self): #fork await sv.fork_join([ cocotb.fork(self.drv.reset_and_suspend()), cocotb.fork(self.tx_mon.reset_and_suspend()), cocotb.fork(self.rx_mon.reset_and_suspend()) ]) #join self.sqr.stop_sequences()",
"self.rx_mon.hier_objection = self.hier_objection self.tx_mon.hier_objection = self.hier_objection self.drv.hier_objection = self.hier_objection vif",
"in #// compliance with the License. You may obtain a",
"self) self.tx_mon = vip_monitor.type_id.create(\"tx_mon\", self) self.rx_mon = vip_monitor.type_id.create(\"rx_mon\", self) self.rx_mon.hier_objection",
"UVMConfigDb.get(self, \"\", \"vif\", vif): uvm_fatal(\"VIP/AGT/NOVIF\", \"No virtual interface specified for",
"sv.fork_join([ cocotb.fork(self.drv.reset_and_suspend()), cocotb.fork(self.tx_mon.reset_and_suspend()), cocotb.fork(self.rx_mon.reset_and_suspend()) ]) #join self.sqr.stop_sequences() async def suspend(self):",
"OR #// CONDITIONS OF ANY KIND, either express or implied.",
"OF ANY KIND, either express or implied. See #// the",
"phase.drop_objection(self) async def reset_and_suspend(self): #fork await sv.fork_join([ cocotb.fork(self.drv.reset_and_suspend()), cocotb.fork(self.tx_mon.reset_and_suspend()), cocotb.fork(self.rx_mon.reset_and_suspend())",
"copy of #// the License at #// #// http://www.apache.org/licenses/LICENSE-2.0 #//",
"#// the License for the specific language governing #// permissions",
"[] if not UVMConfigDb.get(self, \"\", \"vif\", vif): uvm_fatal(\"VIP/AGT/NOVIF\", \"No virtual",
"and limitations under the License. #// ------------------------------------------------------------- #// from uvm",
"the License. #// ------------------------------------------------------------- #// from uvm import * from",
"self) self.drv = vip_driver.type_id.create(\"drv\", self) self.tx_mon = vip_monitor.type_id.create(\"tx_mon\", self) self.rx_mon",
"self.tx_mon.hier_objection = self.hier_objection self.drv.hier_objection = self.hier_objection vif = [] if",
"you may not use this file except in #// compliance",
"dropping objection\") phase.drop_objection(self) async def reset_and_suspend(self): #fork await sv.fork_join([ cocotb.fork(self.drv.reset_and_suspend()),",
"#// #// Licensed under the Apache License, Version 2.0 (the",
"implied. See #// the License for the specific language governing",
"of #// the License at #// #// http://www.apache.org/licenses/LICENSE-2.0 #// #//",
"License is #// distributed on an \"AS IS\" BASIS, WITHOUT",
"#// http://www.apache.org/licenses/LICENSE-2.0 #// #// Unless required by applicable law or",
"super().__init__(name, parent) self.hier_objection = False def build_phase(self, phase): self.sqr =",
"or agreed to in #// writing, software distributed under the",
"permissions and limitations under the License. #// ------------------------------------------------------------- #// from",
"vip_monitor.type_id.create(\"rx_mon\", self) self.rx_mon.hier_objection = self.hier_objection self.tx_mon.hier_objection = self.hier_objection self.drv.hier_objection =",
"vif = [] if not UVMConfigDb.get(self, \"\", \"vif\", vif): uvm_fatal(\"VIP/AGT/NOVIF\",",
"self agent instance\") self.vif = vif[0] UVMConfigDb.set(self, \"tx_mon\", \"vif\", self.vif.tx_mon)",
"phase): self.drv.seq_item_port.connect(self.sqr.seq_item_export) async def pre_reset_phase(self, phase): if self.hier_objection: phase.raise_objection(self, \"Resetting",
"self.hier_objection = False def build_phase(self, phase): self.sqr = vip_sequencer.type_id.create(\"sqr\", self)",
"<gh_stars>100-1000 #// #// ------------------------------------------------------------- #// Copyright 2011 Synopsys, Inc. #//",
"self.sqr.stop_sequences() async def suspend(self): await sv.fork_join([ # fork cocotb.fork(self.drv.suspend()), cocotb.fork(self.tx_mon.suspend()),",
"is #// distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES",
"#// Licensed under the Apache License, Version 2.0 (the #//",
"(tpoikela) #// All Rights Reserved Worldwide #// #// Licensed under",
"------------------------------------------------------------- #// from uvm import * from .vip_sequencer import vip_sequencer",
"WITHOUT WARRANTIES OR #// CONDITIONS OF ANY KIND, either express",
"\"Resetting agent\") await self.reset_and_suspend() if self.hier_objection: print(\"vip_agent dropping objection\") phase.drop_objection(self)",
"# fork cocotb.fork(self.drv.suspend()), cocotb.fork(self.tx_mon.suspend()), cocotb.fork(self.rx_mon.suspend()), ]) # join async def",
"phase.raise_objection(self, \"Resetting agent\") await self.reset_and_suspend() if self.hier_objection: print(\"vip_agent dropping objection\")",
"parent=None): super().__init__(name, parent) self.hier_objection = False def build_phase(self, phase): self.sqr",
"cocotb.fork(self.rx_mon.suspend()), ]) # join async def resume(self): # fork await",
"= False def build_phase(self, phase): self.sqr = vip_sequencer.type_id.create(\"sqr\", self) self.drv",
"specific language governing #// permissions and limitations under the License.",
"Version 2.0 (the #// \"License\"); you may not use this",
"cocotb.fork(self.tx_mon.suspend()), cocotb.fork(self.rx_mon.suspend()), ]) # join async def resume(self): # fork",
"if not UVMConfigDb.get(self, \"\", \"vif\", vif): uvm_fatal(\"VIP/AGT/NOVIF\", \"No virtual interface",
"#// permissions and limitations under the License. #// ------------------------------------------------------------- #//",
"self.vif = vif[0] UVMConfigDb.set(self, \"tx_mon\", \"vif\", self.vif.tx_mon) UVMConfigDb.set(self, \"rx_mon\", \"vif\",",
"self.drv.seq_item_port.connect(self.sqr.seq_item_export) async def pre_reset_phase(self, phase): if self.hier_objection: phase.raise_objection(self, \"Resetting agent\")"
] |
[
"u'a-z': u'x', } TEST_MAPPER = CharMapper(TEST_MAP, None) class TestTransliteratorInit(object): \"\"\"Test",
"init raises a TypeError when given a marker that is",
"LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A",
"invalid marker ( wgitespace in the middle). \"\"\" with pytest.raises(ValueError):",
"strip_markers is set to True. \"\"\" sent_orig = u'Hello @@World,",
"= Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig, True) == sent_out def test_trans_sent_ignore(self):",
"gets transliterated. \"\"\" sent_orig = u'Hello World, this is a",
"== sent_out def test_trans_sent_with_markers(self): \"\"\"Test that tokens with markers in",
"at the end). \"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER, '@@LAT@@ ') def",
"an invalid marker ( wgitespace in the middle). \"\"\" with",
"sent_out = u'Xxxxx Xxxxx, xxxx xx x xxxxxxxx!' trans =",
"License # # Copyright 2018-2020 New York University A<NAME> #",
"with markers in a sentence do not get transliterated. \"\"\"",
"raises a ValueError when given an invalid marker ( whitespace",
"sentence get transliterated with markers stripped when both strip_markers and",
"markers gets transliterated when ignore markers is set to True.",
"that translates lower-case English characters to a lower-case x and",
"CharMapper(TEST_MAP, None) class TestTransliteratorInit(object): \"\"\"Test class for Transliterator.__init__. \"\"\" def",
"= Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig, False, True) == sent_out def",
"English characters to a lower-case x and # upper-case English",
"'@@') assert trans.transliterate(u'Hello') == u'Xxxxx' def test_trans_single_with_markers(self): \"\"\"Test that a",
"transliterated. \"\"\" sent_orig = u'Hello World, this is a sentence!'",
"TEST_MAPPER = CharMapper(TEST_MAP, None) class TestTransliteratorInit(object): \"\"\"Test class for Transliterator.__init__.",
"TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR",
"an empty string. \"\"\" trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'')",
"get transliterated. \"\"\" trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'@@Hello') ==",
"markers stripped when both strip_markers and ignore_markers are set to",
"rights # to use, copy, modify, merge, publish, distribute, sublicense,",
"u'X', u'a-z': u'x', } TEST_MAPPER = CharMapper(TEST_MAP, None) class TestTransliteratorInit(object):",
"[]) def test_init_empty_marker(self): \"\"\"Test that init raises a ValueError when",
"test_trans_single_ignore(self): \"\"\"Test that a single word with markers gets transliterated",
"permission notice shall be included in # all copies or",
"raises a TypeError when given a marker that is None.",
"def test_trans_single_no_markers(self): \"\"\"Test that a single word with no markers",
"single word with markers gets transliterated when ignore markers is",
"True) == u'Xxxxx' def test_trans_sent_no_markers(self): \"\"\"Test that a sentence with",
"'@@') assert trans.transliterate(sent_orig) == sent_out def test_trans_sent_strip(self): \"\"\"Test that tokens",
"a mapper that is None. \"\"\" with pytest.raises(TypeError): Transliterator(None) def",
"\"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER, '@@LAT@@ ') def test_init_invalid_marker3(self): \"\"\"Test that",
"portions of the Software. # # THE SOFTWARE IS PROVIDED",
"def test_init_invalid_type_marker(self): \"\"\"Test that init raises a TypeError when given",
"is set to True. \"\"\" sent_orig = u'Hello @@World, this",
"-*- # MIT License # # Copyright 2018-2020 New York",
"def test_init_invalid_type_mapper(self): \"\"\"Test that init raises a TypeError when given",
"error when given a valid mapper. \"\"\" assert Transliterator(TEST_MAPPER) def",
"coding: utf-8 -*- # MIT License # # Copyright 2018-2020",
"# # The above copyright notice and this permission notice",
"wgitespace in the middle). \"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER, '@@LAT @@')",
"assert trans.transliterate(sent_orig) == sent_out def test_trans_sent_strip(self): \"\"\"Test that tokens with",
"u'Xxxxx @@Xxxxx, xxxx xx x @@xxxxxxxx!' trans = Transliterator(TEST_MAPPER, '@@')",
"sent_out def test_trans_sent_ignore_strip(self): \"\"\"Test that tokens with markers in a",
"trans.transliterate(sent_orig) == sent_out def test_trans_sent_strip(self): \"\"\"Test that tokens with markers",
"pytest.raises(TypeError): Transliterator(TEST_MAPPER, None) def test_init_invalid_type_marker(self): \"\"\"Test that init raises a",
"that tokens with markers in a sentence get transliterated when",
"TypeError when given a mapper that is None. \"\"\" with",
"and associated documentation files (the \"Software\"), to deal # in",
"Software without restriction, including without limitation the rights # to",
"from __future__ import absolute_import import pytest from camel_tools.utils.charmap import CharMapper",
"and to permit persons to whom the Software is #",
"gets transliterated. \"\"\" trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'Hello') ==",
"markers in a sentence get transliterated when ignore markers is",
"when given an invalid marker ( wgitespace in the middle).",
"copies of the Software, and to permit persons to whom",
"hereby granted, free of charge, to any person obtaining a",
"Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'@@Hello', True, True) == u'Xxxxx' def test_trans_sent_no_markers(self):",
"xxxx xx x @@sentence!' trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig)",
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE",
"distribute, sublicense, and/or sell # copies of the Software, and",
"\"\"\" assert Transliterator(TEST_MAPPER, '@@LAT@@') def test_init_valid_marker2(self): \"\"\"Test that init doesn't",
"= Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'@@Hello', True, True) == u'Xxxxx' def",
"this is a sentence!' sent_out = u'Xxxxx Xxxxx, xxxx xx",
"is an empty string. \"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER, '') def",
"# all copies or substantial portions of the Software. #",
"OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.",
"for Transliterator.__init__. \"\"\" def test_init_none_mapper(self): \"\"\"Test that init raises a",
"stripped when strip_markers is set to True. \"\"\" trans =",
"assert trans.transliterate(u'@@Hello', True) == u'Hello' def test_trans_single_ignore(self): \"\"\"Test that a",
"HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #",
"x @@sentence!' trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig) == sent_out",
"\"\"\" from __future__ import absolute_import import pytest from camel_tools.utils.charmap import",
"given an invalid marker ( wgitespace in the middle). \"\"\"",
"World, xxxx xx x sentence!' trans = Transliterator(TEST_MAPPER, '@@') assert",
"test_trans_sent_strip(self): \"\"\"Test that tokens with markers in a sentence do",
"included in # all copies or substantial portions of the",
"== u'' def test_trans_single_no_markers(self): \"\"\"Test that a single word with",
"Xxxxx, xxxx xx x xxxxxxxx!' trans = Transliterator(TEST_MAPPER, '@@') assert",
"it easy to # predict what the transliteration should be.",
"an empty string returns an empty string. \"\"\" trans =",
"'@@LAT@@ ') def test_init_invalid_marker3(self): \"\"\"Test that init raises a ValueError",
"invalid marker ( whitespace at the end). \"\"\" with pytest.raises(ValueError):",
"string returns an empty string. \"\"\" trans = Transliterator(TEST_MAPPER, '@@')",
"x @@xxxxxxxx!' trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig, False, True)",
"{ u'A-Z': u'X', u'a-z': u'x', } TEST_MAPPER = CharMapper(TEST_MAP, None)",
"strip_markers is set to True. \"\"\" trans = Transliterator(TEST_MAPPER, '@@')",
"characters to a lower-case x and # upper-case English characters",
"CharMapper from camel_tools.utils.transliterate import Transliterator # A mapper that translates",
"a single word with markers gets transliterated when ignore markers",
"stripped when strip_markers is set to True. \"\"\" sent_orig =",
"when given a mapper that is None. \"\"\" with pytest.raises(TypeError):",
"OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH",
"deal # in the Software without restriction, including without limitation",
"test_init_empty_marker(self): \"\"\"Test that init raises a ValueError when given a",
"use, copy, modify, merge, publish, distribute, sublicense, and/or sell #",
"Transliterator.__init__. \"\"\" def test_init_none_mapper(self): \"\"\"Test that init raises a TypeError",
"get transliterated when ignore markers is set to True. \"\"\"",
"xxxxxxxx!' trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig, True, True) ==",
"init doesn't raise an error when given a valid mapper.",
"notice and this permission notice shall be included in #",
"test_trans_single_with_markers(self): \"\"\"Test that a single word with markers does not",
"None. \"\"\" with pytest.raises(TypeError): Transliterator(TEST_MAPPER, None) def test_init_invalid_type_marker(self): \"\"\"Test that",
"def test_init_valid_marker2(self): \"\"\"Test that init doesn't raise an error when",
"markers gets transliterated. \"\"\" trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'Hello')",
"but markers do get stripped when strip_markers is set to",
"the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\",",
"with no markers gets transliterated. \"\"\" trans = Transliterator(TEST_MAPPER, '@@')",
"copy, modify, merge, publish, distribute, sublicense, and/or sell # copies",
"# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR",
"when given a marker that is an empty string. \"\"\"",
"test_trans_sent_with_markers(self): \"\"\"Test that tokens with markers in a sentence do",
"init raises a TypeError when given a mapper that is",
"\"\"\"Test that a sentence with no markers gets transliterated. \"\"\"",
"x xxxxxxxx!' trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig) == sent_out",
"camel_tools.utils.charmap import CharMapper from camel_tools.utils.transliterate import Transliterator # A mapper",
"that init raises a TypeError when given a mapper that",
"when ignore markers is set to True. \"\"\" sent_orig =",
"camel_tools.utils.transliterate import Transliterator # A mapper that translates lower-case English",
"a TypeError when given a mapper that is None. \"\"\"",
"all copies or substantial portions of the Software. # #",
"that a sentence with no markers gets transliterated. \"\"\" sent_orig",
"init doesn't raise an error when given a valid marker.",
"empty string. \"\"\" trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'') ==",
"software and associated documentation files (the \"Software\"), to deal #",
"ValueError when given an invalid marker ( whitespace at the",
"@@sentence!' sent_out = u'Xxxxx @@World, xxxx xx x @@sentence!' trans",
"sent_out def test_trans_sent_ignore(self): \"\"\"Test that tokens with markers in a",
"ignore_markers are set to True. \"\"\" trans = Transliterator(TEST_MAPPER, '@@')",
"def test_init_empty_marker(self): \"\"\"Test that init raises a ValueError when given",
"init raises a ValueError when given a marker that is",
"# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF",
"AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR",
"the Software without restriction, including without limitation the rights #",
"with pytest.raises(TypeError): Transliterator(None) def test_init_invalid_type_mapper(self): \"\"\"Test that init raises a",
"# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF",
"are set to True. \"\"\" trans = Transliterator(TEST_MAPPER, '@@') assert",
"DEALINGS IN THE # SOFTWARE. \"\"\" Tests for camel_tools.transliterate. \"\"\"",
"the beginning). \"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER, ' @@LAT@@') def test_init_valid_marker1(self):",
"'@@') assert trans.transliterate(u'@@Hello', True, True) == u'Xxxxx' def test_trans_sent_no_markers(self): \"\"\"Test",
"trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig, False, True) == sent_out",
"THE USE OR OTHER DEALINGS IN THE # SOFTWARE. \"\"\"",
"\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #",
"valid mapper. \"\"\" assert Transliterator(TEST_MAPPER) def test_init_none_marker(self): \"\"\"Test that init",
"assert trans.transliterate(u'@@Hello') == u'@@Hello' def test_trans_single_strip(self): \"\"\"Test that a single",
"do not get transliterated but markers do get stripped when",
"marker that is not a string. \"\"\" with pytest.raises(TypeError): Transliterator(TEST_MAPPER,",
"the end). \"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER, '@@LAT@@ ') def test_init_invalid_marker3(self):",
"TypeError when given a marker that is not a string.",
"Transliterator(TEST_MAPPER, '') def test_init_invalid_marker1(self): \"\"\"Test that init raises a ValueError",
"get stripped when strip_markers is set to True. \"\"\" sent_orig",
"TEST_MAP = { u'A-Z': u'X', u'a-z': u'x', } TEST_MAPPER =",
"given a marker that is None. \"\"\" with pytest.raises(TypeError): Transliterator(TEST_MAPPER,",
"\"\"\" def test_init_none_mapper(self): \"\"\"Test that init raises a TypeError when",
"@@World, this is a @@sentence!' sent_out = u'Xxxxx Xxxxx, xxxx",
"transliterated when ignore markers is set to True. \"\"\" trans",
"when given a valid marker. \"\"\" assert Transliterator(TEST_MAPPER, u'@@LAT@@') class",
"\"\"\"Test that init doesn't raise an error when given a",
"when both strip_markers and ignore_markers are set to True. \"\"\"",
"test_init_invalid_marker1(self): \"\"\"Test that init raises a ValueError when given an",
"xx x sentence!' trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig, True)",
"sent_orig = u'Hello @@World, this is a @@sentence!' sent_out =",
"marker ( wgitespace in the middle). \"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER,",
"-*- coding: utf-8 -*- # MIT License # # Copyright",
"# of this software and associated documentation files (the \"Software\"),",
"def test_init_none_mapper(self): \"\"\"Test that init raises a TypeError when given",
"furnished to do so, subject to the following conditions: #",
"to do so, subject to the following conditions: # #",
"# The above copyright notice and this permission notice shall",
"mapper. \"\"\" assert Transliterator(TEST_MAPPER) def test_init_none_marker(self): \"\"\"Test that init raises",
"SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR",
"pytest from camel_tools.utils.charmap import CharMapper from camel_tools.utils.transliterate import Transliterator #",
"an upper-case X. This makes it easy to # predict",
"no markers gets transliterated. \"\"\" trans = Transliterator(TEST_MAPPER, '@@') assert",
"get transliterated but markers do get stripped when strip_markers is",
"\"\"\" def test_trans_empty(self): \"\"\"Test that transliterating an empty string returns",
"a copy # of this software and associated documentation files",
"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF",
"middle). \"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER, '@@LAT @@') def test_init_invalid_marker2(self): \"\"\"Test",
"class for Transliterator.__init__. \"\"\" def test_init_none_mapper(self): \"\"\"Test that init raises",
"@@sentence!' trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig) == sent_out def",
"notice shall be included in # all copies or substantial",
"given a valid marker. \"\"\" assert Transliterator(TEST_MAPPER, '@@LAT@@') def test_init_valid_marker2(self):",
"empty string. \"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER, '') def test_init_invalid_marker1(self): \"\"\"Test",
"u'Xxxxx World, xxxx xx x sentence!' trans = Transliterator(TEST_MAPPER, '@@')",
"characters to an upper-case X. This makes it easy to",
"xx x @@sentence!' trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig) ==",
"assert trans.transliterate(sent_orig) == sent_out def test_trans_sent_with_markers(self): \"\"\"Test that tokens with",
"not get transliterated. \"\"\" sent_orig = u'Hello @@World, this is",
"# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO",
"@@') def test_init_invalid_marker2(self): \"\"\"Test that init raises a ValueError when",
"pytest.raises(ValueError): Transliterator(TEST_MAPPER, '@@LAT @@') def test_init_invalid_marker2(self): \"\"\"Test that init raises",
"= { u'A-Z': u'X', u'a-z': u'x', } TEST_MAPPER = CharMapper(TEST_MAP,",
"and this permission notice shall be included in # all",
"that transliterating an empty string returns an empty string. \"\"\"",
"\"\"\" with pytest.raises(TypeError): Transliterator(None) def test_init_invalid_type_mapper(self): \"\"\"Test that init raises",
"raises a TypeError when given a marker that is not",
"IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS",
"u'Xxxxx Xxxxx, xxxx xx x xxxxxxxx!' trans = Transliterator(TEST_MAPPER, '@@')",
"York University A<NAME> # # Permission is hereby granted, free",
"given an invalid marker ( whitespace at the end). \"\"\"",
"NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE",
"this is a @@sentence!' sent_out = u'Xxxxx @@Xxxxx, xxxx xx",
"is a @@sentence!' sent_out = u'Xxxxx @@World, xxxx xx x",
"strip_markers and ignore_markers are set to True. \"\"\" sent_orig =",
"# -*- coding: utf-8 -*- # MIT License # #",
"# MIT License # # Copyright 2018-2020 New York University",
"following conditions: # # The above copyright notice and this",
"pytest.raises(TypeError): Transliterator({}) def test_init_valid_mapper(self): \"\"\"Test that init doesn't raise an",
"marker. \"\"\" assert Transliterator(TEST_MAPPER, u'@@LAT@@') class TestTransliteratorTranslate(object): \"\"\"Test class for",
"to deal # in the Software without restriction, including without",
"\"\"\"Test that tokens with markers in a sentence do not",
"is None. \"\"\" with pytest.raises(TypeError): Transliterator(None) def test_init_invalid_type_mapper(self): \"\"\"Test that",
"# SOFTWARE. \"\"\" Tests for camel_tools.transliterate. \"\"\" from __future__ import",
"conditions: # # The above copyright notice and this permission",
"\"\"\" trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'') == u'' def",
"trans.transliterate(u'') == u'' def test_trans_single_no_markers(self): \"\"\"Test that a single word",
"= Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'@@Hello', True) == u'Hello' def test_trans_single_ignore(self):",
"is a @@sentence!' sent_out = u'Xxxxx Xxxxx, xxxx xx x",
"SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #",
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell",
"a TypeError when given a mapper that is not a",
"u'A-Z': u'X', u'a-z': u'x', } TEST_MAPPER = CharMapper(TEST_MAP, None) class",
"IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS",
"at the beginning). \"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER, ' @@LAT@@') def",
"a sentence get transliterated when ignore markers is set to",
"not get transliterated. \"\"\" trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'@@Hello')",
"FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN",
"that tokens with markers in a sentence get transliterated with",
"trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'@@Hello') == u'@@Hello' def test_trans_single_strip(self):",
"given a valid marker. \"\"\" assert Transliterator(TEST_MAPPER, u'@@LAT@@') class TestTransliteratorTranslate(object):",
"def test_init_invalid_marker3(self): \"\"\"Test that init raises a ValueError when given",
"trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'Hello') == u'Xxxxx' def test_trans_single_with_markers(self):",
"transliterated with markers stripped when both strip_markers and ignore_markers are",
"raise an error when given a valid mapper. \"\"\" assert",
"u'@@LAT@@') class TestTransliteratorTranslate(object): \"\"\"Test class for Transliterator.translate. \"\"\" def test_trans_empty(self):",
"True. \"\"\" trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'@@Hello', True, True)",
"a TypeError when given a marker that is None. \"\"\"",
"def test_trans_sent_no_markers(self): \"\"\"Test that a sentence with no markers gets",
"CharMapper instance. \"\"\" with pytest.raises(TypeError): Transliterator({}) def test_init_valid_mapper(self): \"\"\"Test that",
"mapper that is None. \"\"\" with pytest.raises(TypeError): Transliterator(None) def test_init_invalid_type_mapper(self):",
"def test_trans_sent_ignore_strip(self): \"\"\"Test that tokens with markers in a sentence",
"== sent_out def test_trans_sent_ignore(self): \"\"\"Test that tokens with markers in",
"this is a @@sentence!' sent_out = u'Xxxxx Xxxxx, xxxx xx",
"with pytest.raises(TypeError): Transliterator({}) def test_init_valid_mapper(self): \"\"\"Test that init doesn't raise",
"whitespace at the end). \"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER, '@@LAT@@ ')",
"== sent_out def test_trans_sent_strip(self): \"\"\"Test that tokens with markers in",
"and/or sell # copies of the Software, and to permit",
"a marker that is None. \"\"\" with pytest.raises(TypeError): Transliterator(TEST_MAPPER, None)",
"test_init_invalid_type_mapper(self): \"\"\"Test that init raises a TypeError when given a",
"the rights # to use, copy, modify, merge, publish, distribute,",
"\"\"\"Test that tokens with markers in a sentence get transliterated",
"\"\"\"Test that a single word with markers does not get",
"'@@LAT @@') def test_init_invalid_marker2(self): \"\"\"Test that init raises a ValueError",
"u'Xxxxx' def test_trans_sent_no_markers(self): \"\"\"Test that a sentence with no markers",
"= u'Hello @@World, this is a @@sentence!' sent_out = u'Xxxxx",
"English characters to an upper-case X. This makes it easy",
"X. This makes it easy to # predict what the",
"World, this is a sentence!' sent_out = u'Xxxxx Xxxxx, xxxx",
"test_init_invalid_marker3(self): \"\"\"Test that init raises a ValueError when given an",
"be included in # all copies or substantial portions of",
"with pytest.raises(ValueError): Transliterator(TEST_MAPPER, '@@LAT@@ ') def test_init_invalid_marker3(self): \"\"\"Test that init",
"True) == u'Hello' def test_trans_single_ignore(self): \"\"\"Test that a single word",
"is hereby granted, free of charge, to any person obtaining",
"@@LAT@@') def test_init_valid_marker1(self): \"\"\"Test that init doesn't raise an error",
"transliterated. \"\"\" trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'Hello') == u'Xxxxx'",
"get transliterated. \"\"\" sent_orig = u'Hello @@World, this is a",
"sentence do not get transliterated. \"\"\" sent_orig = u'Hello @@World,",
"TypeError when given a marker that is None. \"\"\" with",
"xxxx xx x xxxxxxxx!' trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig)",
"both strip_markers and ignore_markers are set to True. \"\"\" sent_orig",
"transliterated. \"\"\" trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'@@Hello') == u'@@Hello'",
"xxxxxxxx!' trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig) == sent_out def",
"A<NAME> # # Permission is hereby granted, free of charge,",
"CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR",
"Transliterator({}) def test_init_valid_mapper(self): \"\"\"Test that init doesn't raise an error",
"lower-case x and # upper-case English characters to an upper-case",
"markers does not get transliterated but markers do get stripped",
"person obtaining a copy # of this software and associated",
"# # Permission is hereby granted, free of charge, to",
"without restriction, including without limitation the rights # to use,",
"pytest.raises(ValueError): Transliterator(TEST_MAPPER, ' @@LAT@@') def test_init_valid_marker1(self): \"\"\"Test that init doesn't",
"that a single word with markers gets transliterated with markers",
"gets transliterated with markers stripped when both strip_markers and ignore_markers",
"when strip_markers is set to True. \"\"\" sent_orig = u'Hello",
"not a CharMapper instance. \"\"\" with pytest.raises(TypeError): Transliterator({}) def test_init_valid_mapper(self):",
"u'Hello World, this is a sentence!' sent_out = u'Xxxxx Xxxxx,",
"subject to the following conditions: # # The above copyright",
"test_init_none_marker(self): \"\"\"Test that init raises a TypeError when given a",
"the middle). \"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER, '@@LAT @@') def test_init_invalid_marker2(self):",
"x sentence!' trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig, True) ==",
"= Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'@@Hello') == u'@@Hello' def test_trans_single_strip(self): \"\"\"Test",
"sent_orig = u'Hello World, this is a sentence!' sent_out =",
"init raises a ValueError when given an invalid marker (",
"set to True. \"\"\" sent_orig = u'Hello @@World, this is",
"@@Xxxxx, xxxx xx x @@xxxxxxxx!' trans = Transliterator(TEST_MAPPER, '@@') assert",
"') def test_init_invalid_marker3(self): \"\"\"Test that init raises a ValueError when",
"= Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'@@Hello', False, True) == u'@@Xxxxx' def",
"does not get transliterated but markers do get stripped when",
"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN",
"# # Copyright 2018-2020 New York University A<NAME> # #",
"word with no markers gets transliterated. \"\"\" trans = Transliterator(TEST_MAPPER,",
"def test_trans_single_ignore(self): \"\"\"Test that a single word with markers gets",
"doesn't raise an error when given a valid marker. \"\"\"",
"a sentence do not get transliterated but markers do get",
"u'Hello @@World, this is a @@sentence!' sent_out = u'Xxxxx @@Xxxxx,",
"a @@sentence!' sent_out = u'Xxxxx @@World, xxxx xx x @@sentence!'",
"True. \"\"\" trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'@@Hello', True) ==",
"\"\"\" with pytest.raises(TypeError): Transliterator({}) def test_init_valid_mapper(self): \"\"\"Test that init doesn't",
"Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig) == sent_out def test_trans_sent_with_markers(self): \"\"\"Test that",
"THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE",
"Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig) == sent_out def test_trans_sent_strip(self): \"\"\"Test that",
"assert Transliterator(TEST_MAPPER, '@@LAT@@') def test_init_valid_marker2(self): \"\"\"Test that init doesn't raise",
"word with markers gets transliterated when ignore markers is set",
"markers gets transliterated with markers stripped when both strip_markers and",
"to True. \"\"\" trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'@@Hello', True,",
"an error when given a valid mapper. \"\"\" assert Transliterator(TEST_MAPPER)",
"that init doesn't raise an error when given a valid",
"or substantial portions of the Software. # # THE SOFTWARE",
"= Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'Hello') == u'Xxxxx' def test_trans_single_with_markers(self): \"\"\"Test",
"\"\"\"Test that a single word with markers gets transliterated when",
"BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS",
"FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL",
"tokens with markers in a sentence do not get transliterated.",
"gets transliterated when ignore markers is set to True. \"\"\"",
"valid marker. \"\"\" assert Transliterator(TEST_MAPPER, u'@@LAT@@') class TestTransliteratorTranslate(object): \"\"\"Test class",
"OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR",
"= Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig) == sent_out def test_trans_sent_with_markers(self): \"\"\"Test",
"\"\"\"Test that a single word with no markers gets transliterated.",
"is a @@sentence!' sent_out = u'Xxxxx World, xxxx xx x",
"OR OTHER DEALINGS IN THE # SOFTWARE. \"\"\" Tests for",
"import Transliterator # A mapper that translates lower-case English characters",
"given a marker that is not a string. \"\"\" with",
"CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS",
"IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER",
"University A<NAME> # # Permission is hereby granted, free of",
"CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION",
"transliterated. \"\"\" sent_orig = u'Hello @@World, this is a @@sentence!'",
"# Permission is hereby granted, free of charge, to any",
"of charge, to any person obtaining a copy # of",
"INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #",
"merge, publish, distribute, sublicense, and/or sell # copies of the",
"does not get transliterated. \"\"\" trans = Transliterator(TEST_MAPPER, '@@') assert",
"that a single word with no markers gets transliterated. \"\"\"",
"# upper-case English characters to an upper-case X. This makes",
"# # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY",
"is set to True. \"\"\" trans = Transliterator(TEST_MAPPER, '@@') assert",
"TestTransliteratorTranslate(object): \"\"\"Test class for Transliterator.translate. \"\"\" def test_trans_empty(self): \"\"\"Test that",
"with markers does not get transliterated. \"\"\" trans = Transliterator(TEST_MAPPER,",
"NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT",
"a valid mapper. \"\"\" assert Transliterator(TEST_MAPPER) def test_init_none_marker(self): \"\"\"Test that",
"class TestTransliteratorTranslate(object): \"\"\"Test class for Transliterator.translate. \"\"\" def test_trans_empty(self): \"\"\"Test",
"that init raises a TypeError when given a marker that",
"transliterated when ignore markers is set to True. \"\"\" sent_orig",
"when strip_markers is set to True. \"\"\" trans = Transliterator(TEST_MAPPER,",
"sentence!' trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig, True) == sent_out",
"sent_out def test_trans_sent_with_markers(self): \"\"\"Test that tokens with markers in a",
"NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR",
"given an invalid marker ( whitespace at the beginning). \"\"\"",
"== u'Xxxxx' def test_trans_sent_no_markers(self): \"\"\"Test that a sentence with no",
"# A mapper that translates lower-case English characters to a",
"to True. \"\"\" trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'@@Hello', True)",
"\"\"\" trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'@@Hello') == u'@@Hello' def",
"True, True) == u'Xxxxx' def test_trans_sent_no_markers(self): \"\"\"Test that a sentence",
"for Transliterator.translate. \"\"\" def test_trans_empty(self): \"\"\"Test that transliterating an empty",
"OTHER DEALINGS IN THE # SOFTWARE. \"\"\" Tests for camel_tools.transliterate.",
"'@@LAT@@') def test_init_valid_marker2(self): \"\"\"Test that init doesn't raise an error",
"with markers does not get transliterated but markers do get",
"do not get transliterated. \"\"\" sent_orig = u'Hello @@World, this",
"a ValueError when given an invalid marker ( whitespace at",
"\"\"\"Test that init raises a TypeError when given a mapper",
"markers in a sentence get transliterated with markers stripped when",
"to permit persons to whom the Software is # furnished",
"True. \"\"\" trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'@@Hello', False, True)",
"a lower-case x and # upper-case English characters to an",
"Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'@@Hello', True) == u'Hello' def test_trans_single_ignore(self): \"\"\"Test",
"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER",
"with no markers gets transliterated. \"\"\" sent_orig = u'Hello World,",
"tokens with markers in a sentence do not get transliterated",
"test_trans_sent_no_markers(self): \"\"\"Test that a sentence with no markers gets transliterated.",
"a @@sentence!' sent_out = u'Xxxxx Xxxxx, xxxx xx x xxxxxxxx!'",
"= u'Xxxxx World, xxxx xx x sentence!' trans = Transliterator(TEST_MAPPER,",
"tokens with markers in a sentence get transliterated when ignore",
"string. \"\"\" with pytest.raises(TypeError): Transliterator(TEST_MAPPER, []) def test_init_empty_marker(self): \"\"\"Test that",
"so, subject to the following conditions: # # The above",
"absolute_import import pytest from camel_tools.utils.charmap import CharMapper from camel_tools.utils.transliterate import",
"that a single word with markers does not get transliterated.",
"do get stripped when strip_markers is set to True. \"\"\"",
"AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #",
"be. TEST_MAP = { u'A-Z': u'X', u'a-z': u'x', } TEST_MAPPER",
"DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF",
"def test_trans_sent_with_markers(self): \"\"\"Test that tokens with markers in a sentence",
"and ignore_markers are set to True. \"\"\" sent_orig = u'Hello",
"Transliterator(TEST_MAPPER, []) def test_init_empty_marker(self): \"\"\"Test that init raises a ValueError",
"utf-8 -*- # MIT License # # Copyright 2018-2020 New",
"what the transliteration should be. TEST_MAP = { u'A-Z': u'X',",
"assert trans.transliterate(sent_orig, True) == sent_out def test_trans_sent_ignore(self): \"\"\"Test that tokens",
"is a @@sentence!' sent_out = u'Xxxxx @@Xxxxx, xxxx xx x",
"sent_out = u'Xxxxx @@World, xxxx xx x @@sentence!' trans =",
"the transliteration should be. TEST_MAP = { u'A-Z': u'X', u'a-z':",
"'') def test_init_invalid_marker1(self): \"\"\"Test that init raises a ValueError when",
"the following conditions: # # The above copyright notice and",
"FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE",
"Transliterator(TEST_MAPPER, u'@@LAT@@') class TestTransliteratorTranslate(object): \"\"\"Test class for Transliterator.translate. \"\"\" def",
"== u'@@Xxxxx' def test_trans_single_ignore_strip(self): \"\"\"Test that a single word with",
"end). \"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER, '@@LAT@@ ') def test_init_invalid_marker3(self): \"\"\"Test",
"are set to True. \"\"\" sent_orig = u'Hello @@World, this",
"in a sentence do not get transliterated. \"\"\" sent_orig =",
"markers do get stripped when strip_markers is set to True.",
"u'Hello @@World, this is a @@sentence!' sent_out = u'Xxxxx @@World,",
"markers gets transliterated. \"\"\" sent_orig = u'Hello World, this is",
"MIT License # # Copyright 2018-2020 New York University A<NAME>",
"this is a @@sentence!' sent_out = u'Xxxxx @@World, xxxx xx",
"with pytest.raises(ValueError): Transliterator(TEST_MAPPER, ' @@LAT@@') def test_init_valid_marker1(self): \"\"\"Test that init",
"the Software, and to permit persons to whom the Software",
"x and # upper-case English characters to an upper-case X.",
"translates lower-case English characters to a lower-case x and #",
"easy to # predict what the transliteration should be. TEST_MAP",
"in # all copies or substantial portions of the Software.",
"a single word with no markers gets transliterated. \"\"\" trans",
"@@sentence!' sent_out = u'Xxxxx @@Xxxxx, xxxx xx x @@xxxxxxxx!' trans",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT",
"persons to whom the Software is # furnished to do",
"a sentence get transliterated with markers stripped when both strip_markers",
"when given an invalid marker ( whitespace at the end).",
"associated documentation files (the \"Software\"), to deal # in the",
"test_init_invalid_type_marker(self): \"\"\"Test that init raises a TypeError when given a",
"@@World, xxxx xx x @@sentence!' trans = Transliterator(TEST_MAPPER, '@@') assert",
"== u'Xxxxx' def test_trans_single_with_markers(self): \"\"\"Test that a single word with",
"def test_init_valid_mapper(self): \"\"\"Test that init doesn't raise an error when",
"from camel_tools.utils.charmap import CharMapper from camel_tools.utils.transliterate import Transliterator # A",
"to a lower-case x and # upper-case English characters to",
"MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN",
"== sent_out def test_trans_sent_ignore_strip(self): \"\"\"Test that tokens with markers in",
"None) class TestTransliteratorInit(object): \"\"\"Test class for Transliterator.__init__. \"\"\" def test_init_none_mapper(self):",
"u'Hello' def test_trans_single_ignore(self): \"\"\"Test that a single word with markers",
"xx x xxxxxxxx!' trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig, True,",
"Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT",
"== u'Hello' def test_trans_single_ignore(self): \"\"\"Test that a single word with",
"to any person obtaining a copy # of this software",
"an invalid marker ( whitespace at the beginning). \"\"\" with",
"in a sentence do not get transliterated but markers do",
"raise an error when given a valid marker. \"\"\" assert",
"a single word with markers gets transliterated with markers stripped",
"a TypeError when given a marker that is not a",
"'@@') assert trans.transliterate(u'@@Hello') == u'@@Hello' def test_trans_single_strip(self): \"\"\"Test that a",
"= u'Hello World, this is a sentence!' sent_out = u'Xxxxx",
"of the Software, and to permit persons to whom the",
"this software and associated documentation files (the \"Software\"), to deal",
"ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN",
"that is not a CharMapper instance. \"\"\" with pytest.raises(TypeError): Transliterator({})",
"import absolute_import import pytest from camel_tools.utils.charmap import CharMapper from camel_tools.utils.transliterate",
"' @@LAT@@') def test_init_valid_marker1(self): \"\"\"Test that init doesn't raise an",
"ignore markers is set to True. \"\"\" sent_orig = u'Hello",
"BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY,",
"\"\"\"Test class for Transliterator.translate. \"\"\" def test_trans_empty(self): \"\"\"Test that transliterating",
"pytest.raises(TypeError): Transliterator(TEST_MAPPER, []) def test_init_empty_marker(self): \"\"\"Test that init raises a",
"trans.transliterate(sent_orig, True) == sent_out def test_trans_sent_ignore(self): \"\"\"Test that tokens with",
"when given an invalid marker ( whitespace at the beginning).",
"u'x', } TEST_MAPPER = CharMapper(TEST_MAP, None) class TestTransliteratorInit(object): \"\"\"Test class",
"sentence get transliterated when ignore markers is set to True.",
"makes it easy to # predict what the transliteration should",
"Software is # furnished to do so, subject to the",
"test_trans_sent_ignore(self): \"\"\"Test that tokens with markers in a sentence get",
"markers does not get transliterated. \"\"\" trans = Transliterator(TEST_MAPPER, '@@')",
"Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'@@Hello', False, True) == u'@@Xxxxx' def test_trans_single_ignore_strip(self):",
"PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",
"get stripped when strip_markers is set to True. \"\"\" trans",
"trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'@@Hello', True) == u'Hello' def",
"for camel_tools.transliterate. \"\"\" from __future__ import absolute_import import pytest from",
"whom the Software is # furnished to do so, subject",
"Copyright 2018-2020 New York University A<NAME> # # Permission is",
"sublicense, and/or sell # copies of the Software, and to",
"\"\"\"Test that init raises a ValueError when given a marker",
"Transliterator.translate. \"\"\" def test_trans_empty(self): \"\"\"Test that transliterating an empty string",
"@@sentence!' sent_out = u'Xxxxx Xxxxx, xxxx xx x xxxxxxxx!' trans",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY",
"@@World, this is a @@sentence!' sent_out = u'Xxxxx @@World, xxxx",
"given a marker that is an empty string. \"\"\" with",
"substantial portions of the Software. # # THE SOFTWARE IS",
"USE OR OTHER DEALINGS IN THE # SOFTWARE. \"\"\" Tests",
"test_init_none_mapper(self): \"\"\"Test that init raises a TypeError when given a",
"def test_trans_sent_strip(self): \"\"\"Test that tokens with markers in a sentence",
"when given a marker that is not a string. \"\"\"",
"do so, subject to the following conditions: # # The",
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,",
"WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING",
"is not a CharMapper instance. \"\"\" with pytest.raises(TypeError): Transliterator({}) def",
"pytest.raises(ValueError): Transliterator(TEST_MAPPER, '') def test_init_invalid_marker1(self): \"\"\"Test that init raises a",
"with pytest.raises(ValueError): Transliterator(TEST_MAPPER, '@@LAT @@') def test_init_invalid_marker2(self): \"\"\"Test that init",
"in the Software without restriction, including without limitation the rights",
"# furnished to do so, subject to the following conditions:",
"stripped when both strip_markers and ignore_markers are set to True.",
"any person obtaining a copy # of this software and",
"ARISING FROM, # OUT OF OR IN CONNECTION WITH THE",
"SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
"New York University A<NAME> # # Permission is hereby granted,",
"shall be included in # all copies or substantial portions",
"pytest.raises(TypeError): Transliterator(None) def test_init_invalid_type_mapper(self): \"\"\"Test that init raises a TypeError",
"KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO",
"False, True) == sent_out def test_trans_sent_ignore_strip(self): \"\"\"Test that tokens with",
"OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES",
"( wgitespace in the middle). \"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER, '@@LAT",
"restriction, including without limitation the rights # to use, copy,",
"that is None. \"\"\" with pytest.raises(TypeError): Transliterator(None) def test_init_invalid_type_mapper(self): \"\"\"Test",
"Transliterator(TEST_MAPPER, '@@LAT@@') def test_init_valid_marker2(self): \"\"\"Test that init doesn't raise an",
"single word with markers gets transliterated with markers stripped when",
"when given a marker that is None. \"\"\" with pytest.raises(TypeError):",
"IN THE # SOFTWARE. \"\"\" Tests for camel_tools.transliterate. \"\"\" from",
"with pytest.raises(TypeError): Transliterator(TEST_MAPPER, []) def test_init_empty_marker(self): \"\"\"Test that init raises",
"string. \"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER, '') def test_init_invalid_marker1(self): \"\"\"Test that",
"\"\"\"Test that a single word with markers gets transliterated with",
"ignore markers is set to True. \"\"\" trans = Transliterator(TEST_MAPPER,",
"SOFTWARE. \"\"\" Tests for camel_tools.transliterate. \"\"\" from __future__ import absolute_import",
"error when given a valid marker. \"\"\" assert Transliterator(TEST_MAPPER, '@@LAT@@')",
"including without limitation the rights # to use, copy, modify,",
"when given a valid mapper. \"\"\" assert Transliterator(TEST_MAPPER) def test_init_none_marker(self):",
"raises a ValueError when given a marker that is an",
"copyright notice and this permission notice shall be included in",
"a single word with markers does not get transliterated but",
"u'@@Xxxxx' def test_trans_single_ignore_strip(self): \"\"\"Test that a single word with markers",
"Transliterator(TEST_MAPPER, '@@LAT @@') def test_init_invalid_marker2(self): \"\"\"Test that init raises a",
"xxxx xx x xxxxxxxx!' trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig,",
"doesn't raise an error when given a valid mapper. \"\"\"",
"predict what the transliteration should be. TEST_MAP = { u'A-Z':",
"a sentence!' sent_out = u'Xxxxx Xxxxx, xxxx xx x xxxxxxxx!'",
"True) == sent_out def test_trans_sent_ignore_strip(self): \"\"\"Test that tokens with markers",
"ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED",
"free of charge, to any person obtaining a copy #",
"files (the \"Software\"), to deal # in the Software without",
"Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig, True) == sent_out def test_trans_sent_ignore(self): \"\"\"Test",
"markers in a sentence do not get transliterated. \"\"\" sent_orig",
"sent_out def test_trans_sent_strip(self): \"\"\"Test that tokens with markers in a",
"test_init_valid_marker1(self): \"\"\"Test that init doesn't raise an error when given",
"a marker that is an empty string. \"\"\" with pytest.raises(ValueError):",
"test_trans_sent_ignore_strip(self): \"\"\"Test that tokens with markers in a sentence get",
"sentence with no markers gets transliterated. \"\"\" sent_orig = u'Hello",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",
"'@@') assert trans.transliterate(u'@@Hello', False, True) == u'@@Xxxxx' def test_trans_single_ignore_strip(self): \"\"\"Test",
"instance. \"\"\" with pytest.raises(TypeError): Transliterator({}) def test_init_valid_mapper(self): \"\"\"Test that init",
"error when given a valid marker. \"\"\" assert Transliterator(TEST_MAPPER, u'@@LAT@@')",
"that is None. \"\"\" with pytest.raises(TypeError): Transliterator(TEST_MAPPER, None) def test_init_invalid_type_marker(self):",
"is None. \"\"\" with pytest.raises(TypeError): Transliterator(TEST_MAPPER, None) def test_init_invalid_type_marker(self): \"\"\"Test",
"marker that is an empty string. \"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER,",
"of the Software. # # THE SOFTWARE IS PROVIDED \"AS",
"empty string returns an empty string. \"\"\" trans = Transliterator(TEST_MAPPER,",
"( whitespace at the beginning). \"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER, '",
"xxxx xx x @@xxxxxxxx!' trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig,",
"a ValueError when given a marker that is an empty",
"\"\"\" Tests for camel_tools.transliterate. \"\"\" from __future__ import absolute_import import",
"@@sentence!' sent_out = u'Xxxxx World, xxxx xx x sentence!' trans",
"not get transliterated but markers do get stripped when strip_markers",
"= u'Xxxxx @@Xxxxx, xxxx xx x @@xxxxxxxx!' trans = Transliterator(TEST_MAPPER,",
"trans.transliterate(u'@@Hello', False, True) == u'@@Xxxxx' def test_trans_single_ignore_strip(self): \"\"\"Test that a",
"a sentence do not get transliterated. \"\"\" sent_orig = u'Hello",
"trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig) == sent_out def test_trans_sent_strip(self):",
"upper-case English characters to an upper-case X. This makes it",
"assert trans.transliterate(u'@@Hello', False, True) == u'@@Xxxxx' def test_trans_single_ignore_strip(self): \"\"\"Test that",
"TestTransliteratorInit(object): \"\"\"Test class for Transliterator.__init__. \"\"\" def test_init_none_mapper(self): \"\"\"Test that",
"trans.transliterate(sent_orig, False, True) == sent_out def test_trans_sent_ignore_strip(self): \"\"\"Test that tokens",
"ValueError when given a marker that is an empty string.",
"__future__ import absolute_import import pytest from camel_tools.utils.charmap import CharMapper from",
"markers is set to True. \"\"\" sent_orig = u'Hello @@World,",
"\"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER, '') def test_init_invalid_marker1(self): \"\"\"Test that init",
"a valid marker. \"\"\" assert Transliterator(TEST_MAPPER, '@@LAT@@') def test_init_valid_marker2(self): \"\"\"Test",
"Transliterator(TEST_MAPPER, None) def test_init_invalid_type_marker(self): \"\"\"Test that init raises a TypeError",
"Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'@@Hello') == u'@@Hello' def test_trans_single_strip(self): \"\"\"Test that",
"not a string. \"\"\" with pytest.raises(TypeError): Transliterator(TEST_MAPPER, []) def test_init_empty_marker(self):",
"Transliterator(TEST_MAPPER, '@@LAT@@ ') def test_init_invalid_marker3(self): \"\"\"Test that init raises a",
"that a single word with markers does not get transliterated",
"False, True) == u'@@Xxxxx' def test_trans_single_ignore_strip(self): \"\"\"Test that a single",
"u'Hello @@World, this is a @@sentence!' sent_out = u'Xxxxx Xxxxx,",
"a valid marker. \"\"\" assert Transliterator(TEST_MAPPER, u'@@LAT@@') class TestTransliteratorTranslate(object): \"\"\"Test",
"def test_trans_empty(self): \"\"\"Test that transliterating an empty string returns an",
"None. \"\"\" with pytest.raises(TypeError): Transliterator(None) def test_init_invalid_type_mapper(self): \"\"\"Test that init",
"of this software and associated documentation files (the \"Software\"), to",
"OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR",
"OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE",
"in the middle). \"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER, '@@LAT @@') def",
"'@@') assert trans.transliterate(sent_orig, False, True) == sent_out def test_trans_sent_ignore_strip(self): \"\"\"Test",
"a mapper that is not a CharMapper instance. \"\"\" with",
"EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE",
"def test_trans_single_with_markers(self): \"\"\"Test that a single word with markers does",
"and ignore_markers are set to True. \"\"\" trans = Transliterator(TEST_MAPPER,",
"\"\"\" trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'@@Hello', True, True) ==",
"with markers gets transliterated when ignore markers is set to",
"should be. TEST_MAP = { u'A-Z': u'X', u'a-z': u'x', }",
"returns an empty string. \"\"\" trans = Transliterator(TEST_MAPPER, '@@') assert",
"u'Hello @@World, this is a @@sentence!' sent_out = u'Xxxxx World,",
"= Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'') == u'' def test_trans_single_no_markers(self): \"\"\"Test",
"xx x @@xxxxxxxx!' trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig, False,",
"to an upper-case X. This makes it easy to #",
"# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,",
"PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS",
"\"\"\" trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'@@Hello', True) == u'Hello'",
"trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig, True, True) == sent_out",
"\"\"\"Test class for Transliterator.__init__. \"\"\" def test_init_none_mapper(self): \"\"\"Test that init",
"ValueError when given an invalid marker ( wgitespace in the",
"is a sentence!' sent_out = u'Xxxxx Xxxxx, xxxx xx x",
"(the \"Software\"), to deal # in the Software without restriction,",
"trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'') == u'' def test_trans_single_no_markers(self):",
"when given a mapper that is not a CharMapper instance.",
"single word with markers does not get transliterated. \"\"\" trans",
"an empty string. \"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER, '') def test_init_invalid_marker1(self):",
"\"\"\" trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'Hello') == u'Xxxxx' def",
"single word with markers does not get transliterated but markers",
"A mapper that translates lower-case English characters to a lower-case",
"valid marker. \"\"\" assert Transliterator(TEST_MAPPER, '@@LAT@@') def test_init_valid_marker2(self): \"\"\"Test that",
"a @@sentence!' sent_out = u'Xxxxx World, xxxx xx x sentence!'",
"= u'Xxxxx @@World, xxxx xx x @@sentence!' trans = Transliterator(TEST_MAPPER,",
"WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND",
"charge, to any person obtaining a copy # of this",
"permit persons to whom the Software is # furnished to",
"test_init_valid_marker2(self): \"\"\"Test that init doesn't raise an error when given",
"THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE",
"upper-case X. This makes it easy to # predict what",
"== u'@@Hello' def test_trans_single_strip(self): \"\"\"Test that a single word with",
"the Software is # furnished to do so, subject to",
"( whitespace at the end). \"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER, '@@LAT@@",
"@@World, this is a @@sentence!' sent_out = u'Xxxxx @@Xxxxx, xxxx",
"above copyright notice and this permission notice shall be included",
"IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED,",
"A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE",
"limitation the rights # to use, copy, modify, merge, publish,",
"this permission notice shall be included in # all copies",
"given a valid mapper. \"\"\" assert Transliterator(TEST_MAPPER) def test_init_none_marker(self): \"\"\"Test",
"Transliterator(TEST_MAPPER) def test_init_none_marker(self): \"\"\"Test that init raises a TypeError when",
"test_trans_single_no_markers(self): \"\"\"Test that a single word with no markers gets",
"word with markers does not get transliterated. \"\"\" trans =",
"a @@sentence!' sent_out = u'Xxxxx @@Xxxxx, xxxx xx x @@xxxxxxxx!'",
"True. \"\"\" sent_orig = u'Hello @@World, this is a @@sentence!'",
"= u'Xxxxx Xxxxx, xxxx xx x xxxxxxxx!' trans = Transliterator(TEST_MAPPER,",
"PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #",
"strip_markers and ignore_markers are set to True. \"\"\" trans =",
"def test_trans_sent_ignore(self): \"\"\"Test that tokens with markers in a sentence",
"without limitation the rights # to use, copy, modify, merge,",
"def test_trans_single_strip(self): \"\"\"Test that a single word with markers does",
"that init raises a ValueError when given an invalid marker",
"trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'@@Hello', False, True) == u'@@Xxxxx'",
"test_init_valid_mapper(self): \"\"\"Test that init doesn't raise an error when given",
"with markers in a sentence do not get transliterated but",
"in a sentence get transliterated with markers stripped when both",
"x xxxxxxxx!' trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig, True, True)",
"EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE",
"\"\"\" with pytest.raises(TypeError): Transliterator(TEST_MAPPER, []) def test_init_empty_marker(self): \"\"\"Test that init",
"\"\"\" sent_orig = u'Hello @@World, this is a @@sentence!' sent_out",
"def test_trans_single_ignore_strip(self): \"\"\"Test that a single word with markers gets",
"# in the Software without restriction, including without limitation the",
"pytest.raises(ValueError): Transliterator(TEST_MAPPER, '@@LAT@@ ') def test_init_invalid_marker3(self): \"\"\"Test that init raises",
"documentation files (the \"Software\"), to deal # in the Software",
"set to True. \"\"\" trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'@@Hello',",
"markers is set to True. \"\"\" trans = Transliterator(TEST_MAPPER, '@@')",
"'@@') assert trans.transliterate(sent_orig, True) == sent_out def test_trans_sent_ignore(self): \"\"\"Test that",
"\"\"\" with pytest.raises(TypeError): Transliterator(TEST_MAPPER, None) def test_init_invalid_type_marker(self): \"\"\"Test that init",
"copies or substantial portions of the Software. # # THE",
"that init raises a ValueError when given a marker that",
"assert Transliterator(TEST_MAPPER, u'@@LAT@@') class TestTransliteratorTranslate(object): \"\"\"Test class for Transliterator.translate. \"\"\"",
"sentence!' sent_out = u'Xxxxx Xxxxx, xxxx xx x xxxxxxxx!' trans",
"assert trans.transliterate(u'') == u'' def test_trans_single_no_markers(self): \"\"\"Test that a single",
"to # predict what the transliteration should be. TEST_MAP =",
"\"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER, '@@LAT @@') def test_init_invalid_marker2(self): \"\"\"Test that",
"with markers gets transliterated with markers stripped when both strip_markers",
"from camel_tools.utils.transliterate import Transliterator # A mapper that translates lower-case",
"a single word with markers does not get transliterated. \"\"\"",
"given a mapper that is not a CharMapper instance. \"\"\"",
"ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT",
"sell # copies of the Software, and to permit persons",
"OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT",
"trans.transliterate(u'@@Hello') == u'@@Hello' def test_trans_single_strip(self): \"\"\"Test that a single word",
"with pytest.raises(ValueError): Transliterator(TEST_MAPPER, '') def test_init_invalid_marker1(self): \"\"\"Test that init raises",
"transliterated but markers do get stripped when strip_markers is set",
"word with markers does not get transliterated but markers do",
"Transliterator(TEST_MAPPER, ' @@LAT@@') def test_init_valid_marker1(self): \"\"\"Test that init doesn't raise",
"OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT,",
"\"\"\" assert Transliterator(TEST_MAPPER) def test_init_none_marker(self): \"\"\"Test that init raises a",
"publish, distribute, sublicense, and/or sell # copies of the Software,",
"trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'@@Hello', True, True) == u'Xxxxx'",
"to the following conditions: # # The above copyright notice",
"def test_init_none_marker(self): \"\"\"Test that init raises a TypeError when given",
"a string. \"\"\" with pytest.raises(TypeError): Transliterator(TEST_MAPPER, []) def test_init_empty_marker(self): \"\"\"Test",
"class for Transliterator.translate. \"\"\" def test_trans_empty(self): \"\"\"Test that transliterating an",
"u'@@Hello' def test_trans_single_strip(self): \"\"\"Test that a single word with markers",
"lower-case English characters to a lower-case x and # upper-case",
"\"\"\" assert Transliterator(TEST_MAPPER, u'@@LAT@@') class TestTransliteratorTranslate(object): \"\"\"Test class for Transliterator.translate.",
"\"\"\"Test that transliterating an empty string returns an empty string.",
"when ignore markers is set to True. \"\"\" trans =",
"word with markers gets transliterated with markers stripped when both",
"assert trans.transliterate(u'Hello') == u'Xxxxx' def test_trans_single_with_markers(self): \"\"\"Test that a single",
"transliterating an empty string returns an empty string. \"\"\" trans",
"ignore_markers are set to True. \"\"\" sent_orig = u'Hello @@World,",
"def test_init_valid_marker1(self): \"\"\"Test that init doesn't raise an error when",
"modify, merge, publish, distribute, sublicense, and/or sell # copies of",
"to True. \"\"\" sent_orig = u'Hello @@World, this is a",
"trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig, True) == sent_out def",
"sent_out = u'Xxxxx @@Xxxxx, xxxx xx x @@xxxxxxxx!' trans =",
"OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION",
"\"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER, ' @@LAT@@') def test_init_valid_marker1(self): \"\"\"Test that",
"raises a TypeError when given a mapper that is None.",
"test_trans_single_ignore_strip(self): \"\"\"Test that a single word with markers gets transliterated",
"assert trans.transliterate(u'@@Hello', True, True) == u'Xxxxx' def test_trans_sent_no_markers(self): \"\"\"Test that",
"IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
"a CharMapper instance. \"\"\" with pytest.raises(TypeError): Transliterator({}) def test_init_valid_mapper(self): \"\"\"Test",
"Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'Hello') == u'Xxxxx' def test_trans_single_with_markers(self): \"\"\"Test that",
"Software, and to permit persons to whom the Software is",
"2018-2020 New York University A<NAME> # # Permission is hereby",
"# predict what the transliteration should be. TEST_MAP = {",
"None) def test_init_invalid_type_marker(self): \"\"\"Test that init raises a TypeError when",
"string. \"\"\" trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'') == u''",
"raises a ValueError when given an invalid marker ( wgitespace",
"import CharMapper from camel_tools.utils.transliterate import Transliterator # A mapper that",
"# to use, copy, modify, merge, publish, distribute, sublicense, and/or",
"and # upper-case English characters to an upper-case X. This",
"is not a string. \"\"\" with pytest.raises(TypeError): Transliterator(TEST_MAPPER, []) def",
"trans.transliterate(u'@@Hello', True) == u'Hello' def test_trans_single_ignore(self): \"\"\"Test that a single",
"OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT",
"xxxx xx x sentence!' trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig,",
"invalid marker ( whitespace at the beginning). \"\"\" with pytest.raises(ValueError):",
"a marker that is not a string. \"\"\" with pytest.raises(TypeError):",
"marker that is None. \"\"\" with pytest.raises(TypeError): Transliterator(TEST_MAPPER, None) def",
"assert Transliterator(TEST_MAPPER) def test_init_none_marker(self): \"\"\"Test that init raises a TypeError",
"raises a TypeError when given a mapper that is not",
"\"\"\" trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'@@Hello', False, True) ==",
"\"Software\"), to deal # in the Software without restriction, including",
"that tokens with markers in a sentence do not get",
"mapper that is not a CharMapper instance. \"\"\" with pytest.raises(TypeError):",
"assert trans.transliterate(sent_orig, False, True) == sent_out def test_trans_sent_ignore_strip(self): \"\"\"Test that",
"that is an empty string. \"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER, '')",
"whitespace at the beginning). \"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER, ' @@LAT@@')",
"True) == sent_out def test_trans_sent_ignore(self): \"\"\"Test that tokens with markers",
"tokens with markers in a sentence get transliterated with markers",
"# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR",
"transliteration should be. TEST_MAP = { u'A-Z': u'X', u'a-z': u'x',",
"THE # SOFTWARE. \"\"\" Tests for camel_tools.transliterate. \"\"\" from __future__",
"marker ( whitespace at the beginning). \"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER,",
"that is not a string. \"\"\" with pytest.raises(TypeError): Transliterator(TEST_MAPPER, [])",
"sentence do not get transliterated but markers do get stripped",
"this is a @@sentence!' sent_out = u'Xxxxx World, xxxx xx",
"class TestTransliteratorInit(object): \"\"\"Test class for Transliterator.__init__. \"\"\" def test_init_none_mapper(self): \"\"\"Test",
"= Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig) == sent_out def test_trans_sent_strip(self): \"\"\"Test",
"COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
"marker. \"\"\" assert Transliterator(TEST_MAPPER, '@@LAT@@') def test_init_valid_marker2(self): \"\"\"Test that init",
"in a sentence get transliterated when ignore markers is set",
"@@xxxxxxxx!' trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig, False, True) ==",
"u'Xxxxx @@World, xxxx xx x @@sentence!' trans = Transliterator(TEST_MAPPER, '@@')",
"\"\"\"Test that init raises a TypeError when given a marker",
"an error when given a valid marker. \"\"\" assert Transliterator(TEST_MAPPER,",
"marker ( whitespace at the end). \"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER,",
"= CharMapper(TEST_MAP, None) class TestTransliteratorInit(object): \"\"\"Test class for Transliterator.__init__. \"\"\"",
"# copies of the Software, and to permit persons to",
"} TEST_MAPPER = CharMapper(TEST_MAP, None) class TestTransliteratorInit(object): \"\"\"Test class for",
"an invalid marker ( whitespace at the end). \"\"\" with",
"camel_tools.transliterate. \"\"\" from __future__ import absolute_import import pytest from camel_tools.utils.charmap",
"'@@') assert trans.transliterate(u'@@Hello', True) == u'Hello' def test_trans_single_ignore(self): \"\"\"Test that",
"'@@') assert trans.transliterate(sent_orig) == sent_out def test_trans_sent_with_markers(self): \"\"\"Test that tokens",
"granted, free of charge, to any person obtaining a copy",
"xx x xxxxxxxx!' trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig) ==",
"with markers stripped when both strip_markers and ignore_markers are set",
"obtaining a copy # of this software and associated documentation",
"@@World, this is a @@sentence!' sent_out = u'Xxxxx World, xxxx",
"TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN",
"is # furnished to do so, subject to the following",
"to whom the Software is # furnished to do so,",
"a ValueError when given an invalid marker ( wgitespace in",
"with markers in a sentence get transliterated with markers stripped",
"copy # of this software and associated documentation files (the",
"trans.transliterate(u'Hello') == u'Xxxxx' def test_trans_single_with_markers(self): \"\"\"Test that a single word",
"THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY",
"OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE.",
"Permission is hereby granted, free of charge, to any person",
"def test_init_invalid_marker2(self): \"\"\"Test that init raises a ValueError when given",
"'@@') assert trans.transliterate(u'') == u'' def test_trans_single_no_markers(self): \"\"\"Test that a",
"test_trans_single_strip(self): \"\"\"Test that a single word with markers does not",
"This makes it easy to # predict what the transliteration",
"test_init_invalid_marker2(self): \"\"\"Test that init raises a ValueError when given an",
"Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig, False, True) == sent_out def test_trans_sent_ignore_strip(self):",
"beginning). \"\"\" with pytest.raises(ValueError): Transliterator(TEST_MAPPER, ' @@LAT@@') def test_init_valid_marker1(self): \"\"\"Test",
"# Copyright 2018-2020 New York University A<NAME> # # Permission",
"single word with no markers gets transliterated. \"\"\" trans =",
"that a single word with markers gets transliterated when ignore",
"Tests for camel_tools.transliterate. \"\"\" from __future__ import absolute_import import pytest",
"with markers in a sentence get transliterated when ignore markers",
"The above copyright notice and this permission notice shall be",
"True) == u'@@Xxxxx' def test_trans_single_ignore_strip(self): \"\"\"Test that a single word",
"get transliterated with markers stripped when both strip_markers and ignore_markers",
"TypeError when given a mapper that is not a CharMapper",
"\"\"\"Test that init raises a ValueError when given an invalid",
"sent_out = u'Xxxxx World, xxxx xx x sentence!' trans =",
"Transliterator # A mapper that translates lower-case English characters to",
"u'Xxxxx' def test_trans_single_with_markers(self): \"\"\"Test that a single word with markers",
"when given a valid marker. \"\"\" assert Transliterator(TEST_MAPPER, '@@LAT@@') def",
"u'' def test_trans_single_no_markers(self): \"\"\"Test that a single word with no",
"trans.transliterate(sent_orig) == sent_out def test_trans_sent_with_markers(self): \"\"\"Test that tokens with markers",
"Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'') == u'' def test_trans_single_no_markers(self): \"\"\"Test that",
"to True. \"\"\" trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(u'@@Hello', False,",
"markers in a sentence do not get transliterated but markers",
"given a mapper that is None. \"\"\" with pytest.raises(TypeError): Transliterator(None)",
"WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT",
"both strip_markers and ignore_markers are set to True. \"\"\" trans",
"Transliterator(None) def test_init_invalid_type_mapper(self): \"\"\"Test that init raises a TypeError when",
"no markers gets transliterated. \"\"\" sent_orig = u'Hello World, this",
"import pytest from camel_tools.utils.charmap import CharMapper from camel_tools.utils.transliterate import Transliterator",
"test_trans_empty(self): \"\"\"Test that transliterating an empty string returns an empty",
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES",
"trans.transliterate(u'@@Hello', True, True) == u'Xxxxx' def test_trans_sent_no_markers(self): \"\"\"Test that a",
"def test_init_invalid_marker1(self): \"\"\"Test that init raises a ValueError when given",
"a sentence with no markers gets transliterated. \"\"\" sent_orig =",
"\"\"\" sent_orig = u'Hello World, this is a sentence!' sent_out",
"trans = Transliterator(TEST_MAPPER, '@@') assert trans.transliterate(sent_orig) == sent_out def test_trans_sent_with_markers(self):",
"mapper that translates lower-case English characters to a lower-case x",
"WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING",
"with pytest.raises(TypeError): Transliterator(TEST_MAPPER, None) def test_init_invalid_type_marker(self): \"\"\"Test that init raises"
] |
[
"import sys from collections import OrderedDict def get_versioned_template(template_filename, bucket, solution,",
"# # # # or in the \"license\" file accompanying",
"WITHOUT WARRANTIES # # OR CONDITIONS OF ANY KIND, express",
"the License for the specific language governing permissions # #",
"OrderedDict def get_versioned_template(template_filename, bucket, solution, version, region): with open(template_filename, \"rt\")",
"'cn-northwest-1': arn_prefix = \"arn:aws-cn\" else: arn_prefix = \"arn:aws\" template_text =",
"2.0 (the \"License\"). You may not use this file except",
"template = get_versioned_template(template_file, bucket, solution, version, region) print(json.dumps(template, indent=4)) main(template_file=sys.argv[1],",
"License. A copy of the License is located at #",
"# with the License. A copy of the License is",
"located at # # # # http://www.apache.org/licenses/ # # #",
"get_versioned_template(template_filename, bucket, solution, version, region): with open(template_filename, \"rt\") as f:",
"version, region): with open(template_filename, \"rt\") as f: template_text = \"\".join(f.readlines())",
"in compliance # # with the License. A copy of",
"file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES",
"on an \"AS IS\" BASIS, WITHOUT WARRANTIES # # OR",
"return json.loads(template_text, object_pairs_hook=OrderedDict) def main(template_file, bucket, solution, version, region): template",
"OR CONDITIONS OF ANY KIND, express or implied. See the",
"# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights",
"or its affiliates. All Rights Reserved. # # # #",
"Version 2.0 (the \"License\"). You may not use this file",
"express or implied. See the License for the specific language",
"region == 'cn-north-1' or region == 'cn-northwest-1': arn_prefix = \"arn:aws-cn\"",
"an \"AS IS\" BASIS, WITHOUT WARRANTIES # # OR CONDITIONS",
"bucket, solution, version, region): template = get_versioned_template(template_file, bucket, solution, version,",
"Apache License Version 2.0 (the \"License\"). You may not use",
"governing permissions # # and limitations under the License. #",
"version, region): template = get_versioned_template(template_file, bucket, solution, version, region) print(json.dumps(template,",
"the specific language governing permissions # # and limitations under",
"== 'cn-north-1' or region == 'cn-northwest-1': arn_prefix = \"arn:aws-cn\" else:",
"the License is located at # # # # http://www.apache.org/licenses/",
"solution, version, region): template = get_versioned_template(template_file, bucket, solution, version, region)",
"template_text.replace(\"%bucket%\", bucket) template_text = template_text.replace(\"%solution%\", solution) template_text = template_text.replace(\"%version%\", version)",
"arn_prefix = \"arn:aws\" template_text = template_text.replace(\"%arn_prefix%\", arn_prefix) return json.loads(template_text, object_pairs_hook=OrderedDict)",
"def main(template_file, bucket, solution, version, region): template = get_versioned_template(template_file, bucket,",
"= get_versioned_template(template_file, bucket, solution, version, region) print(json.dumps(template, indent=4)) main(template_file=sys.argv[1], bucket=sys.argv[2],",
"# Licensed under the Apache License Version 2.0 (the \"License\").",
"# # and limitations under the License. # ###################################################################################################################### import",
"# # or in the \"license\" file accompanying this file.",
"2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. #",
"else: arn_prefix = \"arn:aws\" template_text = template_text.replace(\"%arn_prefix%\", arn_prefix) return json.loads(template_text,",
"# # # or in the \"license\" file accompanying this",
"This file is distributed on an \"AS IS\" BASIS, WITHOUT",
"\"\".join(f.readlines()) template_text = template_text.replace(\"%bucket%\", bucket) template_text = template_text.replace(\"%solution%\", solution) template_text",
"Reserved. # # # # Licensed under the Apache License",
"template_text = template_text.replace(\"%solution%\", solution) template_text = template_text.replace(\"%version%\", version) if region",
"under the License. # ###################################################################################################################### import json import sys from",
"# OR CONDITIONS OF ANY KIND, express or implied. See",
"\"license\" file accompanying this file. This file is distributed on",
"this file. This file is distributed on an \"AS IS\"",
"for the specific language governing permissions # # and limitations",
"Rights Reserved. # # # # Licensed under the Apache",
"# or in the \"license\" file accompanying this file. This",
"template_text.replace(\"%solution%\", solution) template_text = template_text.replace(\"%version%\", version) if region == 'cn-north-1'",
"with open(template_filename, \"rt\") as f: template_text = \"\".join(f.readlines()) template_text =",
"Inc. or its affiliates. All Rights Reserved. # # #",
"See the License for the specific language governing permissions #",
"License. # ###################################################################################################################### import json import sys from collections import",
"# # with the License. A copy of the License",
"bucket, solution, version, region) print(json.dumps(template, indent=4)) main(template_file=sys.argv[1], bucket=sys.argv[2], solution=sys.argv[3], version=sys.argv[4],",
"# # # http://www.apache.org/licenses/ # # # # or in",
"solution) template_text = template_text.replace(\"%version%\", version) if region == 'cn-north-1' or",
"# ###################################################################################################################### import json import sys from collections import OrderedDict",
"def get_versioned_template(template_filename, bucket, solution, version, region): with open(template_filename, \"rt\") as",
"http://www.apache.org/licenses/ # # # # or in the \"license\" file",
"# http://www.apache.org/licenses/ # # # # or in the \"license\"",
"is located at # # # # http://www.apache.org/licenses/ # #",
"KIND, express or implied. See the License for the specific",
"collections import OrderedDict def get_versioned_template(template_filename, bucket, solution, version, region): with",
"License Version 2.0 (the \"License\"). You may not use this",
"= template_text.replace(\"%version%\", version) if region == 'cn-north-1' or region ==",
"= \"\".join(f.readlines()) template_text = template_text.replace(\"%bucket%\", bucket) template_text = template_text.replace(\"%solution%\", solution)",
"# # # # http://www.apache.org/licenses/ # # # # or",
"BASIS, WITHOUT WARRANTIES # # OR CONDITIONS OF ANY KIND,",
"or in the \"license\" file accompanying this file. This file",
"CONDITIONS OF ANY KIND, express or implied. See the License",
"json.loads(template_text, object_pairs_hook=OrderedDict) def main(template_file, bucket, solution, version, region): template =",
"limitations under the License. # ###################################################################################################################### import json import sys",
"if region == 'cn-north-1' or region == 'cn-northwest-1': arn_prefix =",
"with the License. A copy of the License is located",
"from collections import OrderedDict def get_versioned_template(template_filename, bucket, solution, version, region):",
"= template_text.replace(\"%bucket%\", bucket) template_text = template_text.replace(\"%solution%\", solution) template_text = template_text.replace(\"%version%\",",
"main(template_file, bucket, solution, version, region): template = get_versioned_template(template_file, bucket, solution,",
"# and limitations under the License. # ###################################################################################################################### import json",
"template_text.replace(\"%arn_prefix%\", arn_prefix) return json.loads(template_text, object_pairs_hook=OrderedDict) def main(template_file, bucket, solution, version,",
"file accompanying this file. This file is distributed on an",
"the License. A copy of the License is located at",
"Amazon.com, Inc. or its affiliates. All Rights Reserved. # #",
"permissions # # and limitations under the License. # ######################################################################################################################",
"Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.",
"template_text = template_text.replace(\"%arn_prefix%\", arn_prefix) return json.loads(template_text, object_pairs_hook=OrderedDict) def main(template_file, bucket,",
"its affiliates. All Rights Reserved. # # # # Licensed",
"All Rights Reserved. # # # # Licensed under the",
"ANY KIND, express or implied. See the License for the",
"You may not use this file except in compliance #",
"# # OR CONDITIONS OF ANY KIND, express or implied.",
"\"AS IS\" BASIS, WITHOUT WARRANTIES # # OR CONDITIONS OF",
"= template_text.replace(\"%arn_prefix%\", arn_prefix) return json.loads(template_text, object_pairs_hook=OrderedDict) def main(template_file, bucket, solution,",
"file except in compliance # # with the License. A",
"version, region) print(json.dumps(template, indent=4)) main(template_file=sys.argv[1], bucket=sys.argv[2], solution=sys.argv[3], version=sys.argv[4], region=sys.argv[5]) exit(0)",
"this file except in compliance # # with the License.",
"\"arn:aws\" template_text = template_text.replace(\"%arn_prefix%\", arn_prefix) return json.loads(template_text, object_pairs_hook=OrderedDict) def main(template_file,",
"use this file except in compliance # # with the",
"arn_prefix = \"arn:aws-cn\" else: arn_prefix = \"arn:aws\" template_text = template_text.replace(\"%arn_prefix%\",",
"or implied. See the License for the specific language governing",
"object_pairs_hook=OrderedDict) def main(template_file, bucket, solution, version, region): template = get_versioned_template(template_file,",
"of the License is located at # # # #",
"the License. # ###################################################################################################################### import json import sys from collections",
"import json import sys from collections import OrderedDict def get_versioned_template(template_filename,",
"json import sys from collections import OrderedDict def get_versioned_template(template_filename, bucket,",
"language governing permissions # # and limitations under the License.",
"WARRANTIES # # OR CONDITIONS OF ANY KIND, express or",
"\"arn:aws-cn\" else: arn_prefix = \"arn:aws\" template_text = template_text.replace(\"%arn_prefix%\", arn_prefix) return",
"not use this file except in compliance # # with",
"the \"license\" file accompanying this file. This file is distributed",
"= template_text.replace(\"%solution%\", solution) template_text = template_text.replace(\"%version%\", version) if region ==",
"or region == 'cn-northwest-1': arn_prefix = \"arn:aws-cn\" else: arn_prefix =",
"f: template_text = \"\".join(f.readlines()) template_text = template_text.replace(\"%bucket%\", bucket) template_text =",
"(the \"License\"). You may not use this file except in",
"\"License\"). You may not use this file except in compliance",
"'cn-north-1' or region == 'cn-northwest-1': arn_prefix = \"arn:aws-cn\" else: arn_prefix",
"Licensed under the Apache License Version 2.0 (the \"License\"). You",
"get_versioned_template(template_file, bucket, solution, version, region) print(json.dumps(template, indent=4)) main(template_file=sys.argv[1], bucket=sys.argv[2], solution=sys.argv[3],",
"solution, version, region): with open(template_filename, \"rt\") as f: template_text =",
"as f: template_text = \"\".join(f.readlines()) template_text = template_text.replace(\"%bucket%\", bucket) template_text",
"at # # # # http://www.apache.org/licenses/ # # # #",
"except in compliance # # with the License. A copy",
"distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES # #",
"is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES #",
"# # # Licensed under the Apache License Version 2.0",
"OF ANY KIND, express or implied. See the License for",
"accompanying this file. This file is distributed on an \"AS",
"template_text = template_text.replace(\"%bucket%\", bucket) template_text = template_text.replace(\"%solution%\", solution) template_text =",
"version) if region == 'cn-north-1' or region == 'cn-northwest-1': arn_prefix",
"the Apache License Version 2.0 (the \"License\"). You may not",
"bucket, solution, version, region): with open(template_filename, \"rt\") as f: template_text",
"and limitations under the License. # ###################################################################################################################### import json import",
"= \"arn:aws-cn\" else: arn_prefix = \"arn:aws\" template_text = template_text.replace(\"%arn_prefix%\", arn_prefix)",
"region): template = get_versioned_template(template_file, bucket, solution, version, region) print(json.dumps(template, indent=4))",
"import OrderedDict def get_versioned_template(template_filename, bucket, solution, version, region): with open(template_filename,",
"bucket) template_text = template_text.replace(\"%solution%\", solution) template_text = template_text.replace(\"%version%\", version) if",
"solution, version, region) print(json.dumps(template, indent=4)) main(template_file=sys.argv[1], bucket=sys.argv[2], solution=sys.argv[3], version=sys.argv[4], region=sys.argv[5])",
"License is located at # # # # http://www.apache.org/licenses/ #",
"may not use this file except in compliance # #",
"# # Licensed under the Apache License Version 2.0 (the",
"copy of the License is located at # # #",
"# # http://www.apache.org/licenses/ # # # # or in the",
"specific language governing permissions # # and limitations under the",
"template_text = \"\".join(f.readlines()) template_text = template_text.replace(\"%bucket%\", bucket) template_text = template_text.replace(\"%solution%\",",
"compliance # # with the License. A copy of the",
"in the \"license\" file accompanying this file. This file is",
"implied. See the License for the specific language governing permissions",
"sys from collections import OrderedDict def get_versioned_template(template_filename, bucket, solution, version,",
"affiliates. All Rights Reserved. # # # # Licensed under",
"== 'cn-northwest-1': arn_prefix = \"arn:aws-cn\" else: arn_prefix = \"arn:aws\" template_text",
"# # # # Licensed under the Apache License Version",
"\"rt\") as f: template_text = \"\".join(f.readlines()) template_text = template_text.replace(\"%bucket%\", bucket)",
"A copy of the License is located at # #",
"License for the specific language governing permissions # # and",
"file. This file is distributed on an \"AS IS\" BASIS,",
"template_text.replace(\"%version%\", version) if region == 'cn-north-1' or region == 'cn-northwest-1':",
"region): with open(template_filename, \"rt\") as f: template_text = \"\".join(f.readlines()) template_text",
"arn_prefix) return json.loads(template_text, object_pairs_hook=OrderedDict) def main(template_file, bucket, solution, version, region):",
"= \"arn:aws\" template_text = template_text.replace(\"%arn_prefix%\", arn_prefix) return json.loads(template_text, object_pairs_hook=OrderedDict) def",
"###################################################################################################################### import json import sys from collections import OrderedDict def",
"open(template_filename, \"rt\") as f: template_text = \"\".join(f.readlines()) template_text = template_text.replace(\"%bucket%\",",
"template_text = template_text.replace(\"%version%\", version) if region == 'cn-north-1' or region",
"###################################################################################################################### # Copyright 2019 Amazon.com, Inc. or its affiliates. All",
"IS\" BASIS, WITHOUT WARRANTIES # # OR CONDITIONS OF ANY",
"under the Apache License Version 2.0 (the \"License\"). You may",
"region == 'cn-northwest-1': arn_prefix = \"arn:aws-cn\" else: arn_prefix = \"arn:aws\""
] |
[
"dim = int(cvars[2][1:cvars[2].find(':')],0) for i in range(dim+1): self.config_names.append(cvars[-2]+'['+str(i)+']') else: self.config_names.append(cvars[-2])",
"ind_end = signal[signal.find(':')+1:signal.find(']')] symb_end = False if ind_end in self.vars:",
"sequence, and config_name variables as they appear in btor2 for",
"affiliations. # All rights reserved. See the file LICENSE in",
"cvars[0] and 'SOLVE' != cvars[1]: self.constr2terms.append(cvars) elif 'if' == cvars[0]:",
"self.seq_out.append(cvars[-2]) elif 'SOLVE' == cvars[-1] and ('input' == cvars[0] or",
"annot_file = args.hwpath+\"agg_lake_top_annotation.txt\" elif tb_set: annot_file = args.hwpath+\"tb_lake_top_annotation.txt\" elif sram_set:",
"symb_start = True ind_end = signal[signal.find(':')+1:signal.find(']')] symb_end = False if",
"0 j -= 1 gen[j] += 1 else: if cvars[-1][-1:]",
"args.hwpath+\"tb_lake_top_annotation.txt\" elif sram_set: annot_file = args.hwpath+\"sram_lake_top_annotation.txt\" else: annot_file = args.hwpath+\"lake_top_annotation.txt\"",
"!= cvars[1]: self.constr2terms.append(cvars) elif 'if' == cvars[0]: self.constr2terms.append(cvars) elif 'SOLVE'",
"an annotation file if args.annotation == None: if agg_set: annot_file",
"sram_set: annot_file = args.hwpath+\"sram_lake_top_annotation.txt\" else: annot_file = args.hwpath+\"lake_top_annotation.txt\" else: annot_file",
"# Collect the Set0, Set1, I/O sequence, and config_name variables",
"1 else: if cvars[0] == 'input': self.seq_in.append(cvars[-2]) else: self.seq_out.append(cvars[-2]) elif",
"self.seq_in.append(cvars[-2]) else: self.seq_out.append(cvars[-2]) elif 'SOLVE' == cvars[-1] and ('input' ==",
"else: #implement later when suport for universal quantifiers is added",
"constr2terms = [] data_in_size = [] data_out_size = [] clk_name",
"cvars[0] and 'var' != cvars[0] and 'if' != cvars[0] and",
"<= 3 assert len(self.data_out_size) <= 3 gen = [0]*len(dims) j",
"and 'if' != cvars[0] and 'SOLVE' != cvars[1]: self.constr2terms.append(cvars) elif",
"annot_file = args.annotation cfo = open(annot_file, \"r+\") clines = cfo.readlines()",
"= False if ind_end in self.vars: ind_end = int(self.vars[ind_end],0) elif",
"i in gen: build_dims = build_dims + '['+str(i)+']' if cvars[0]",
"(rem_dims != ''): dims.append(int(rem_dims[1:rem_dims.find(':')],0)) rem_dims = rem_dims[rem_dims.find(']')+1:] gen = [0]*len(dims)",
"# <NAME> # This file is part of the configuration",
"symbolic symb_end = True if not symb_start and not symb_end:",
"cfo = open(annot_file, \"r+\") clines = cfo.readlines() # Close opend",
"symb_start and not symb_end: if signal[:signal.find('[')] not in self.var_array_inds: self.var_array_inds[signal[:signal.find('[')]]",
"if len(cvars) == 6: rem_dims = cvars[2] dims = []",
"# continue if len(cvars) == 6: dim = int(cvars[2][1:cvars[2].find(':')],0) for",
"== None: if agg_set: annot_file = args.hwpath+\"agg_lake_top_annotation.txt\" elif tb_set: annot_file",
"be anything, e.g. 0 signal = cvars[0] if ':' in",
"else: self.seq_out.append(build_dims) while (j < len(dims)-1 and gen[j+1] == 0):",
"else: annot_file = args.annotation cfo = open(annot_file, \"r+\") clines =",
"= cvars[0] if ':' in signal: signal_name = signal[:signal.find('[')] ind_start",
"cfo.close() # Collect the Set0, Set1, I/O sequence, and config_name",
"import sys import re import time import copy import io",
"rem_dims = rem_dims[rem_dims.find(']')+1:] if cvars[0] == 'input': self.data_in_size = dims",
"2021 by the authors listed in the file AUTHORS #",
"annot_file = args.hwpath+\"lake_top_annotation.txt\" else: annot_file = args.annotation cfo = open(annot_file,",
"= args.hwpath+\"agg_lake_top_annotation.txt\" elif tb_set: annot_file = args.hwpath+\"tb_lake_top_annotation.txt\" elif sram_set: annot_file",
"gen: build_dims = build_dims + '['+str(i)+']' if cvars[0] == 'input':",
"version): # <NAME> # This file is part of the",
"not in self.var_array_inds: self.var_array_inds[signal[:signal.find('[')]] = [] for i in range(ind_start,ind_end+1):",
"tb_set, sram_set, symbols, solver): global dim_names # open an annotation",
"= int(ind_start,0) else: symb_start = True ind_end = signal[signal.find(':')+1:signal.find(']')] symb_end",
"for cln in clines: cln = cln.strip() cln = cln.replace(',',",
"annot_file = args.hwpath+\"tb_lake_top_annotation.txt\" elif sram_set: annot_file = args.hwpath+\"sram_lake_top_annotation.txt\" else: annot_file",
"self.seq_out.append(build_dims) while (j < len(dims)-1 and gen[j+1] == 0): j",
"in gen: build_dims = build_dims + '['+str(i)+']' if cvars[0] ==",
"# # Handles parsing of all input files. ############################################################################### import",
"import io #import timeit class stream: set0 = [] set1",
"io #import timeit class stream: set0 = [] set1 =",
"cvars = cln.split() if 'var' == cvars[0]: self.vars[cvars[1]] = cvars[3]",
"project. # Copyright (c) 2021 by the authors listed in",
"while (rem_dims != ''): dims.append(int(rem_dims[1:rem_dims.find(':')],0)) rem_dims = rem_dims[rem_dims.find(']')+1:] if cvars[0]",
"as ss import smt_switch.primops as po import smt_switch.sortkinds as sk",
"!= ''): dims.append(int(rem_dims[1:rem_dims.find(':')],0)) rem_dims = rem_dims[rem_dims.find(']')+1:] gen = [0]*len(dims) j",
"file -- parse.py -- # Top contributors (to current version):",
"= True ind_end = signal[signal.find(':')+1:signal.find(']')] symb_end = False if ind_end",
"-= 1 gen[j] += 1 else: if cvars[0] == 'input':",
"part of the configuration finder for the Stanford AHA project.",
"signal_name = signal[:signal.find('[')] ind_start = signal[signal.find('[')+1:signal.find(':')] symb_start = False if",
"3 gen = [0]*len(dims) j = len(dims)-1 while j >=",
"cln in clines: cln = cln.strip() cln = cln.replace(',', '')",
"continue if len(cvars) == 6: dim = int(cvars[2][1:cvars[2].find(':')],0) for i",
"self.var_array_inds: self.var_array_inds[signal[:signal.find('[')]] = [] for i in range(ind_start,ind_end+1): self.var_array_inds[signal_name].append(i) else:",
"global dim_names # open an annotation file if args.annotation ==",
"top-level source # directory for licensing information. # # Handles",
"else: annot_file = args.hwpath+\"lake_top_annotation.txt\" else: annot_file = args.annotation cfo =",
"config_names = [] def read_stream(self, args, fout, agg_set, tb_set, sram_set,",
"elif 'SET' == cvars[-1][:-1]: if len(cvars) == 6: rem_dims =",
"= [] set1 = [] seq_in = [] seq_out =",
"j += 1 else: gen[j] = 0 j -= 1",
"licensing information. # # Handles parsing of all input files.",
"#implement later when suport for universal quantifiers is added self.constr2terms.append(cvars)",
"and config_name variables as they appear in btor2 for cln",
"the top-level source # directory for licensing information. # #",
"int(ind_start,0) else: symb_start = True ind_end = signal[signal.find(':')+1:signal.find(']')] symb_end =",
"signal[signal.find(':')+1:signal.find(']')] symb_end = False if ind_end in self.vars: ind_end =",
"= args.hwpath+\"tb_lake_top_annotation.txt\" elif sram_set: annot_file = args.hwpath+\"sram_lake_top_annotation.txt\" else: annot_file =",
"'SEQUENCE' == cvars[-1]: if len(cvars) == 6: rem_dims = cvars[2]",
"import pono as c import sys import re import time",
"= cvars[-2] elif 'RSTN' == cvars[-1]: self.rst_n_name = cvars[-2] else:",
"(rem_dims != ''): dims.append(int(rem_dims[1:rem_dims.find(':')],0)) rem_dims = rem_dims[rem_dims.find(']')+1:] if cvars[0] ==",
"if ':' in signal: signal_name = signal[:signal.find('[')] ind_start = signal[signal.find('[')+1:signal.find(':')]",
"= [] vars = {} var_array_inds = {} constr2terms =",
"[0]*len(dims) j = len(dims)-1 while j >= 0: if gen[j]",
"in signal: signal_name = signal[:signal.find('[')] ind_start = signal[signal.find('[')+1:signal.find(':')] symb_start =",
"#if cvars[3] == 'strg_ub_pre_fetch_0_input_latency': # continue if len(cvars) == 6:",
"None config_names = [] def read_stream(self, args, fout, agg_set, tb_set,",
"'0': self.set0.append(build_dims) else: self.set1.append(build_dims) while (j < len(dims)-1 and gen[j+1]",
"while (j < len(dims)-1 and gen[j+1] == 0): j +=",
"time import copy import io #import timeit class stream: set0",
"= [] seq_in = [] seq_out = [] vars =",
"'RSTN' == cvars[-1]: self.rst_n_name = cvars[-2] else: assert 'X' ==",
"elif tb_set: annot_file = args.hwpath+\"tb_lake_top_annotation.txt\" elif sram_set: annot_file = args.hwpath+\"sram_lake_top_annotation.txt\"",
"gen[j] <= dims[j]: build_dims = cvars[-2] for i in gen:",
"+= 1 else: if cvars[-1][-1:] == '0': self.set0.append(cvars[-2]) else: self.set1.append(cvars[-2])",
"directory for licensing information. # # Handles parsing of all",
"j = len(dims)-1 while j >= 0: if gen[j] <=",
"= build_dims + '['+str(i)+']' if cvars[-1][-1:] == '0': self.set0.append(build_dims) else:",
"len(dims)-1 and gen[j+1] == 0): j += 1 else: gen[j]",
"''): dims.append(int(rem_dims[1:rem_dims.find(':')],0)) rem_dims = rem_dims[rem_dims.find(']')+1:] gen = [0]*len(dims) j =",
"clines: cln = cln.strip() cln = cln.replace(',', '') cvars =",
"parse.py -- # Top contributors (to current version): # <NAME>",
"i in range(dim+1): self.config_names.append(cvars[-2]+'['+str(i)+']') else: self.config_names.append(cvars[-2]) elif 'CLK' == cvars[-1]:",
"AHA project. # Copyright (c) 2021 by the authors listed",
"args.annotation == None: if agg_set: annot_file = args.hwpath+\"agg_lake_top_annotation.txt\" elif tb_set:",
"<= 3 gen = [0]*len(dims) j = len(dims)-1 while j",
"and their institutional affiliations. # All rights reserved. See the",
"to be solved. Others can be anything, e.g. 0 signal",
"i in range(ind_start,ind_end+1): self.var_array_inds[signal_name].append(i) else: #implement later when suport for",
"= dims assert len(self.data_in_size) <= 3 assert len(self.data_out_size) <= 3",
"1 gen[j] += 1 else: if cvars[0] == 'input': self.seq_in.append(cvars[-2])",
"False if ind_end in self.vars: ind_end = int(self.vars[ind_end],0) elif ind_end.isdigit():",
"< len(dims)-1 and gen[j+1] == 0): j += 1 else:",
"cln.strip() cln = cln.replace(',', '') cvars = cln.split() if 'var'",
"'var' == cvars[0]: self.vars[cvars[1]] = cvars[3] elif 'input' != cvars[0]",
"= signal[:signal.find('[')] ind_start = signal[signal.find('[')+1:signal.find(':')] symb_start = False if ind_start",
"Set0, Set1, I/O sequence, and config_name variables as they appear",
"len(cvars) == 6: rem_dims = cvars[2] dims = [] while",
"= cfo.readlines() # Close opend file cfo.close() # Collect the",
"= int(ind_end,0) else: #case of symbolic symb_end = True if",
"+ '['+str(i)+']' if cvars[-1][-1:] == '0': self.set0.append(build_dims) else: self.set1.append(build_dims) while",
"cvars[0]: self.vars[cvars[1]] = cvars[3] elif 'input' != cvars[0] and 'output'",
"#case of symbolic symb_end = True if not symb_start and",
"== cvars[-1]: self.clk_name = cvars[-2] elif 'RSTN' == cvars[-1]: self.rst_n_name",
"= [0]*len(dims) j = len(dims)-1 while j >= 0: if",
"cvars[0] == 'input': self.data_in_size = dims else: self.data_out_size = dims",
"gen[j] += 1 else: if cvars[0] == 'input': self.seq_in.append(cvars[-2]) else:",
"Top contributors (to current version): # <NAME> # This file",
"# Handles parsing of all input files. ############################################################################### import smt_switch",
"'var' != cvars[0] and 'if' != cvars[0] and 'SOLVE' !=",
"= build_dims + '['+str(i)+']' if cvars[0] == 'input': self.seq_in.append(build_dims) else:",
"6: dim = int(cvars[2][1:cvars[2].find(':')],0) for i in range(dim+1): self.config_names.append(cvars[-2]+'['+str(i)+']') else:",
"set only to be solved. Others can be anything, e.g.",
"dims assert len(self.data_in_size) <= 3 assert len(self.data_out_size) <= 3 gen",
"if ind_start in self.vars: ind_start = int(self.vars[ind_start],0) elif ind_start.isdigit(): ind_start",
"cfo.readlines() # Close opend file cfo.close() # Collect the Set0,",
"signal[:signal.find('[')] not in self.var_array_inds: self.var_array_inds[signal[:signal.find('[')]] = [] for i in",
"0): j += 1 else: gen[j] = 0 j -=",
"= open(annot_file, \"r+\") clines = cfo.readlines() # Close opend file",
"self.constr2terms.append(cvars) elif 'SOLVE' == cvars[1]:#specific bits are set only to",
"for i in range(dim+1): self.config_names.append(cvars[-2]+'['+str(i)+']') else: self.config_names.append(cvars[-2]) elif 'CLK' ==",
"elif 'SOLVE' == cvars[1]:#specific bits are set only to be",
"Close opend file cfo.close() # Collect the Set0, Set1, I/O",
"'SET' == cvars[-1][:-1]: if len(cvars) == 6: rem_dims = cvars[2]",
"annot_file = args.hwpath+\"sram_lake_top_annotation.txt\" else: annot_file = args.hwpath+\"lake_top_annotation.txt\" else: annot_file =",
"class stream: set0 = [] set1 = [] seq_in =",
"== cvars[0]: self.vars[cvars[1]] = cvars[3] elif 'input' != cvars[0] and",
"only to be solved. Others can be anything, e.g. 0",
"'SOLVE' == cvars[1]:#specific bits are set only to be solved.",
"finder for the Stanford AHA project. # Copyright (c) 2021",
"Stanford AHA project. # Copyright (c) 2021 by the authors",
"later when suport for universal quantifiers is added self.constr2terms.append(cvars) else:",
"in self.vars: ind_start = int(self.vars[ind_start],0) elif ind_start.isdigit(): ind_start = int(ind_start,0)",
"args.hwpath+\"lake_top_annotation.txt\" else: annot_file = args.annotation cfo = open(annot_file, \"r+\") clines",
"= [] for i in range(ind_start,ind_end+1): self.var_array_inds[signal_name].append(i) else: #implement later",
"def read_stream(self, args, fout, agg_set, tb_set, sram_set, symbols, solver): global",
"== 'strg_ub_pre_fetch_0_input_latency': # continue if len(cvars) == 6: dim =",
"gen[j] += 1 else: if cvars[-1][-1:] == '0': self.set0.append(cvars[-2]) else:",
"= cln.strip() cln = cln.replace(',', '') cvars = cln.split() if",
"== '0': self.set0.append(build_dims) else: self.set1.append(build_dims) while (j < len(dims)-1 and",
"True if not symb_start and not symb_end: if signal[:signal.find('[')] not",
"'SOLVE' != cvars[1]: self.constr2terms.append(cvars) elif 'if' == cvars[0]: self.constr2terms.append(cvars) elif",
"== 6: dim = int(cvars[2][1:cvars[2].find(':')],0) for i in range(dim+1): self.config_names.append(cvars[-2]+'['+str(i)+']')",
"''): dims.append(int(rem_dims[1:rem_dims.find(':')],0)) rem_dims = rem_dims[rem_dims.find(']')+1:] if cvars[0] == 'input': self.data_in_size",
"<= dims[j]: build_dims = cvars[-2] for i in gen: build_dims",
"solved. Others can be anything, e.g. 0 signal = cvars[0]",
"if signal[:signal.find('[')] not in self.var_array_inds: self.var_array_inds[signal[:signal.find('[')]] = [] for i",
"all input files. ############################################################################### import smt_switch as ss import smt_switch.primops",
"[] for i in range(ind_start,ind_end+1): self.var_array_inds[signal_name].append(i) else: #implement later when",
"dims.append(int(rem_dims[1:rem_dims.find(':')],0)) rem_dims = rem_dims[rem_dims.find(']')+1:] if cvars[0] == 'input': self.data_in_size =",
"stream: set0 = [] set1 = [] seq_in = []",
"= None config_names = [] def read_stream(self, args, fout, agg_set,",
"are set only to be solved. Others can be anything,",
"input files. ############################################################################### import smt_switch as ss import smt_switch.primops as",
"rem_dims = cvars[2] dims = [] while (rem_dims != ''):",
"cvars[-2] for i in gen: build_dims = build_dims + '['+str(i)+']'",
"else: self.data_out_size = dims assert len(self.data_in_size) <= 3 assert len(self.data_out_size)",
"assert len(self.data_out_size) <= 3 gen = [0]*len(dims) j = len(dims)-1",
"args, fout, agg_set, tb_set, sram_set, symbols, solver): global dim_names #",
"= [] data_in_size = [] data_out_size = [] clk_name =",
"self.set0.append(build_dims) else: self.set1.append(build_dims) while (j < len(dims)-1 and gen[j+1] ==",
"= args.hwpath+\"sram_lake_top_annotation.txt\" else: annot_file = args.hwpath+\"lake_top_annotation.txt\" else: annot_file = args.annotation",
"annotation file if args.annotation == None: if agg_set: annot_file =",
"files. ############################################################################### import smt_switch as ss import smt_switch.primops as po",
"is part of the configuration finder for the Stanford AHA",
"directory) and their institutional affiliations. # All rights reserved. See",
"import time import copy import io #import timeit class stream:",
"file cfo.close() # Collect the Set0, Set1, I/O sequence, and",
"[] self.var_array_inds[signal[:signal.find('[')]].append(signal[signal.find('[')+1:signal.find(']')]) elif 'SET' == cvars[-1][:-1]: if len(cvars) == 6:",
"= None rst_n_name = None config_names = [] def read_stream(self,",
"source # directory for licensing information. # # Handles parsing",
"import re import time import copy import io #import timeit",
"self.constr2terms.append(cvars) elif 'if' == cvars[0]: self.constr2terms.append(cvars) elif 'SOLVE' == cvars[1]:#specific",
"self.data_in_size = dims else: self.data_out_size = dims assert len(self.data_in_size) <=",
"rem_dims = rem_dims[rem_dims.find(']')+1:] gen = [0]*len(dims) j = len(dims)-1 while",
"symb_start = False if ind_start in self.vars: ind_start = int(self.vars[ind_start],0)",
"for i in gen: build_dims = build_dims + '['+str(i)+']' if",
"1 else: gen[j] = 0 j -= 1 gen[j] +=",
"else: gen[j] = 0 j -= 1 gen[j] += 1",
"= [] data_out_size = [] clk_name = None rst_n_name =",
"cvars[-1]: if len(cvars) == 6: rem_dims = cvars[2] dims =",
"!= cvars[0] and 'SOLVE' != cvars[1]: self.constr2terms.append(cvars) elif 'if' ==",
"in self.vars: ind_end = int(self.vars[ind_end],0) elif ind_end.isdigit(): ind_end = int(ind_end,0)",
"in clines: cln = cln.strip() cln = cln.replace(',', '') cvars",
"= len(dims)-1 while j >= 0: if gen[j] <= dims[j]:",
"range(dim+1): self.config_names.append(cvars[-2]+'['+str(i)+']') else: self.config_names.append(cvars[-2]) elif 'CLK' == cvars[-1]: self.clk_name =",
"if cvars[-1][-1:] == '0': self.set0.append(build_dims) else: self.set1.append(build_dims) while (j <",
"if gen[j] <= dims[j]: build_dims = cvars[-2] for i in",
"contributors (to current version): # <NAME> # This file is",
"institutional affiliations. # All rights reserved. See the file LICENSE",
"not symb_end: if signal[:signal.find('[')] not in self.var_array_inds: self.var_array_inds[signal[:signal.find('[')]] = []",
"set1 = [] seq_in = [] seq_out = [] vars",
"not in self.var_array_inds: self.var_array_inds[signal[:signal.find('[')]] = [] self.var_array_inds[signal[:signal.find('[')]].append(signal[signal.find('[')+1:signal.find(']')]) elif 'SET' ==",
"while j >= 0: if gen[j] <= dims[j]: build_dims =",
"build_dims = build_dims + '['+str(i)+']' if cvars[-1][-1:] == '0': self.set0.append(build_dims)",
"[] set1 = [] seq_in = [] seq_out = []",
"self.set1.append(build_dims) while (j < len(dims)-1 and gen[j+1] == 0): j",
"for universal quantifiers is added self.constr2terms.append(cvars) else: if signal[:signal.find('[')] not",
"rem_dims[rem_dims.find(']')+1:] if cvars[0] == 'input': self.data_in_size = dims else: self.data_out_size",
"int(self.vars[ind_start],0) elif ind_start.isdigit(): ind_start = int(ind_start,0) else: symb_start = True",
"dims[j]: build_dims = cvars[-2] for i in gen: build_dims =",
"cln = cln.replace(',', '') cvars = cln.split() if 'var' ==",
"self.var_array_inds[signal_name].append(i) else: #implement later when suport for universal quantifiers is",
"of all input files. ############################################################################### import smt_switch as ss import",
"in btor2 for cln in clines: cln = cln.strip() cln",
"ind_end.isdigit(): ind_end = int(ind_end,0) else: #case of symbolic symb_end =",
"-= 1 gen[j] += 1 else: if cvars[-1][-1:] == '0':",
"1 gen[j] += 1 else: if cvars[-1][-1:] == '0': self.set0.append(cvars[-2])",
"data_out_size = [] clk_name = None rst_n_name = None config_names",
"if cvars[-1][-1:] == '0': self.set0.append(cvars[-2]) else: self.set1.append(cvars[-2]) elif 'SEQUENCE' ==",
"symb_end = True if not symb_start and not symb_end: if",
"gen: build_dims = build_dims + '['+str(i)+']' if cvars[-1][-1:] == '0':",
"'input' != cvars[0] and 'output' != cvars[0] and 'var' !=",
"= {} var_array_inds = {} constr2terms = [] data_in_size =",
"ind_start in self.vars: ind_start = int(self.vars[ind_start],0) elif ind_start.isdigit(): ind_start =",
"'input': self.data_in_size = dims else: self.data_out_size = dims assert len(self.data_in_size)",
"'strg_ub_pre_fetch_0_input_latency': # continue if len(cvars) == 6: dim = int(cvars[2][1:cvars[2].find(':')],0)",
"be solved. Others can be anything, e.g. 0 signal =",
"anything, e.g. 0 signal = cvars[0] if ':' in signal:",
"file is part of the configuration finder for the Stanford",
"while (rem_dims != ''): dims.append(int(rem_dims[1:rem_dims.find(':')],0)) rem_dims = rem_dims[rem_dims.find(']')+1:] gen =",
">= 0: if gen[j] <= dims[j]: build_dims = cvars[-2] for",
"= [] clk_name = None rst_n_name = None config_names =",
"when suport for universal quantifiers is added self.constr2terms.append(cvars) else: if",
"the file AUTHORS # in the top-level source directory) and",
"cln.replace(',', '') cvars = cln.split() if 'var' == cvars[0]: self.vars[cvars[1]]",
"and 'output' != cvars[0] and 'var' != cvars[0] and 'if'",
"self.var_array_inds: self.var_array_inds[signal[:signal.find('[')]] = [] self.var_array_inds[signal[:signal.find('[')]].append(signal[signal.find('[')+1:signal.find(']')]) elif 'SET' == cvars[-1][:-1]: if",
"# file -- parse.py -- # Top contributors (to current",
"= int(self.vars[ind_start],0) elif ind_start.isdigit(): ind_start = int(ind_start,0) else: symb_start =",
"listed in the file AUTHORS # in the top-level source",
"Set1, I/O sequence, and config_name variables as they appear in",
"== 'input': self.data_in_size = dims else: self.data_out_size = dims assert",
"elif 'if' == cvars[0]: self.constr2terms.append(cvars) elif 'SOLVE' == cvars[1]:#specific bits",
"self.set0.append(cvars[-2]) else: self.set1.append(cvars[-2]) elif 'SEQUENCE' == cvars[-1]: if len(cvars) ==",
"elif 'RSTN' == cvars[-1]: self.rst_n_name = cvars[-2] else: assert 'X'",
"rights reserved. See the file LICENSE in the top-level source",
"= [] while (rem_dims != ''): dims.append(int(rem_dims[1:rem_dims.find(':')],0)) rem_dims = rem_dims[rem_dims.find(']')+1:]",
"== cvars[-1]: self.rst_n_name = cvars[-2] else: assert 'X' == cvars[-1]",
"len(self.data_in_size) <= 3 assert len(self.data_out_size) <= 3 gen = [0]*len(dims)",
"for licensing information. # # Handles parsing of all input",
"args.hwpath+\"agg_lake_top_annotation.txt\" elif tb_set: annot_file = args.hwpath+\"tb_lake_top_annotation.txt\" elif sram_set: annot_file =",
"if args.annotation == None: if agg_set: annot_file = args.hwpath+\"agg_lake_top_annotation.txt\" elif",
"e.g. 0 signal = cvars[0] if ':' in signal: signal_name",
"elif ind_end.isdigit(): ind_end = int(ind_end,0) else: #case of symbolic symb_end",
"6: rem_dims = cvars[2] dims = [] while (rem_dims !=",
"self.var_array_inds[signal[:signal.find('[')]].append(signal[signal.find('[')+1:signal.find(']')]) elif 'SET' == cvars[-1][:-1]: if len(cvars) == 6: rem_dims",
"self.vars: ind_start = int(self.vars[ind_start],0) elif ind_start.isdigit(): ind_start = int(ind_start,0) else:",
"cvars[0]): #if cvars[3] == 'strg_ub_pre_fetch_0_input_latency': # continue if len(cvars) ==",
"c import sys import re import time import copy import",
"configuration finder for the Stanford AHA project. # Copyright (c)",
"'if' == cvars[0]: self.constr2terms.append(cvars) elif 'SOLVE' == cvars[1]:#specific bits are",
"bits are set only to be solved. Others can be",
"+= 1 else: if cvars[0] == 'input': self.seq_in.append(cvars[-2]) else: self.seq_out.append(cvars[-2])",
"dim_names # open an annotation file if args.annotation == None:",
"config_name variables as they appear in btor2 for cln in",
"'output' == cvars[0]): #if cvars[3] == 'strg_ub_pre_fetch_0_input_latency': # continue if",
"len(cvars) == 6: dim = int(cvars[2][1:cvars[2].find(':')],0) for i in range(dim+1):",
"\"r+\") clines = cfo.readlines() # Close opend file cfo.close() #",
"the file LICENSE in the top-level source # directory for",
"in the file AUTHORS # in the top-level source directory)",
"!= cvars[0] and 'output' != cvars[0] and 'var' != cvars[0]",
"See the file LICENSE in the top-level source # directory",
"I/O sequence, and config_name variables as they appear in btor2",
"self.config_names.append(cvars[-2]+'['+str(i)+']') else: self.config_names.append(cvars[-2]) elif 'CLK' == cvars[-1]: self.clk_name = cvars[-2]",
"cvars[0] and 'if' != cvars[0] and 'SOLVE' != cvars[1]: self.constr2terms.append(cvars)",
"cvars[3] == 'strg_ub_pre_fetch_0_input_latency': # continue if len(cvars) == 6: dim",
"by the authors listed in the file AUTHORS # in",
"cvars[1]:#specific bits are set only to be solved. Others can",
"btor2 for cln in clines: cln = cln.strip() cln =",
"or 'output' == cvars[0]): #if cvars[3] == 'strg_ub_pre_fetch_0_input_latency': # continue",
"'output' != cvars[0] and 'var' != cvars[0] and 'if' !=",
"cln = cln.strip() cln = cln.replace(',', '') cvars = cln.split()",
"len(dims)-1 while j >= 0: if gen[j] <= dims[j]: build_dims",
"(j < len(dims)-1 and gen[j+1] == 0): j += 1",
"= args.hwpath+\"lake_top_annotation.txt\" else: annot_file = args.annotation cfo = open(annot_file, \"r+\")",
"[] vars = {} var_array_inds = {} constr2terms = []",
"= cln.replace(',', '') cvars = cln.split() if 'var' == cvars[0]:",
"else: self.config_names.append(cvars[-2]) elif 'CLK' == cvars[-1]: self.clk_name = cvars[-2] elif",
"rst_n_name = None config_names = [] def read_stream(self, args, fout,",
"(to current version): # <NAME> # This file is part",
"= signal[signal.find(':')+1:signal.find(']')] symb_end = False if ind_end in self.vars: ind_end",
"# This file is part of the configuration finder for",
"AUTHORS # in the top-level source directory) and their institutional",
"is added self.constr2terms.append(cvars) else: if signal[:signal.find('[')] not in self.var_array_inds: self.var_array_inds[signal[:signal.find('[')]]",
"the Set0, Set1, I/O sequence, and config_name variables as they",
"<NAME> # This file is part of the configuration finder",
"as sk import argparse import pono as c import sys",
"smt_switch.sortkinds as sk import argparse import pono as c import",
"!= cvars[0] and 'var' != cvars[0] and 'if' != cvars[0]",
"# Copyright (c) 2021 by the authors listed in the",
"timeit class stream: set0 = [] set1 = [] seq_in",
"j -= 1 gen[j] += 1 else: if cvars[-1][-1:] ==",
"added self.constr2terms.append(cvars) else: if signal[:signal.find('[')] not in self.var_array_inds: self.var_array_inds[signal[:signal.find('[')]] =",
"parsing of all input files. ############################################################################### import smt_switch as ss",
"read_stream(self, args, fout, agg_set, tb_set, sram_set, symbols, solver): global dim_names",
"self.set1.append(cvars[-2]) elif 'SEQUENCE' == cvars[-1]: if len(cvars) == 6: rem_dims",
"{} constr2terms = [] data_in_size = [] data_out_size = []",
"1 else: if cvars[-1][-1:] == '0': self.set0.append(cvars[-2]) else: self.set1.append(cvars[-2]) elif",
"== cvars[-1]: if len(cvars) == 6: rem_dims = cvars[2] dims",
"'CLK' == cvars[-1]: self.clk_name = cvars[-2] elif 'RSTN' == cvars[-1]:",
"'input': self.seq_in.append(cvars[-2]) else: self.seq_out.append(cvars[-2]) elif 'SOLVE' == cvars[-1] and ('input'",
"import smt_switch.sortkinds as sk import argparse import pono as c",
"the Stanford AHA project. # Copyright (c) 2021 by the",
"import argparse import pono as c import sys import re",
"self.data_out_size = dims assert len(self.data_in_size) <= 3 assert len(self.data_out_size) <=",
"cvars[0] == 'input': self.seq_in.append(cvars[-2]) else: self.seq_out.append(cvars[-2]) elif 'SOLVE' == cvars[-1]",
"in range(dim+1): self.config_names.append(cvars[-2]+'['+str(i)+']') else: self.config_names.append(cvars[-2]) elif 'CLK' == cvars[-1]: self.clk_name",
"if 'var' == cvars[0]: self.vars[cvars[1]] = cvars[3] elif 'input' !=",
"None: if agg_set: annot_file = args.hwpath+\"agg_lake_top_annotation.txt\" elif tb_set: annot_file =",
"not symb_start and not symb_end: if signal[:signal.find('[')] not in self.var_array_inds:",
"(c) 2021 by the authors listed in the file AUTHORS",
"sram_set, symbols, solver): global dim_names # open an annotation file",
"== 'input': self.seq_in.append(cvars[-2]) else: self.seq_out.append(cvars[-2]) elif 'SOLVE' == cvars[-1] and",
"= int(self.vars[ind_end],0) elif ind_end.isdigit(): ind_end = int(ind_end,0) else: #case of",
"assert len(self.data_in_size) <= 3 assert len(self.data_out_size) <= 3 gen =",
"self.seq_in.append(build_dims) else: self.seq_out.append(build_dims) while (j < len(dims)-1 and gen[j+1] ==",
"('input' == cvars[0] or 'output' == cvars[0]): #if cvars[3] ==",
"copy import io #import timeit class stream: set0 = []",
"symb_end: if signal[:signal.find('[')] not in self.var_array_inds: self.var_array_inds[signal[:signal.find('[')]] = [] for",
"self.clk_name = cvars[-2] elif 'RSTN' == cvars[-1]: self.rst_n_name = cvars[-2]",
"as po import smt_switch.sortkinds as sk import argparse import pono",
"== '0': self.set0.append(cvars[-2]) else: self.set1.append(cvars[-2]) elif 'SEQUENCE' == cvars[-1]: if",
"as c import sys import re import time import copy",
"[] seq_out = [] vars = {} var_array_inds = {}",
"[] data_in_size = [] data_out_size = [] clk_name = None",
"in self.var_array_inds: self.var_array_inds[signal[:signal.find('[')]] = [] for i in range(ind_start,ind_end+1): self.var_array_inds[signal_name].append(i)",
"re import time import copy import io #import timeit class",
"cvars[-1] and ('input' == cvars[0] or 'output' == cvars[0]): #if",
"[] while (rem_dims != ''): dims.append(int(rem_dims[1:rem_dims.find(':')],0)) rem_dims = rem_dims[rem_dims.find(']')+1:] if",
"cvars[0] == 'input': self.seq_in.append(build_dims) else: self.seq_out.append(build_dims) while (j < len(dims)-1",
"fout, agg_set, tb_set, sram_set, symbols, solver): global dim_names # open",
"self.config_names.append(cvars[-2]) elif 'CLK' == cvars[-1]: self.clk_name = cvars[-2] elif 'RSTN'",
"and 'var' != cvars[0] and 'if' != cvars[0] and 'SOLVE'",
"gen[j] = 0 j -= 1 gen[j] += 1 else:",
"of symbolic symb_end = True if not symb_start and not",
"reserved. See the file LICENSE in the top-level source #",
"top-level source directory) and their institutional affiliations. # All rights",
"cvars[3] elif 'input' != cvars[0] and 'output' != cvars[0] and",
"if len(cvars) == 6: dim = int(cvars[2][1:cvars[2].find(':')],0) for i in",
"current version): # <NAME> # This file is part of",
"open an annotation file if args.annotation == None: if agg_set:",
"else: if signal[:signal.find('[')] not in self.var_array_inds: self.var_array_inds[signal[:signal.find('[')]] = [] self.var_array_inds[signal[:signal.find('[')]].append(signal[signal.find('[')+1:signal.find(']')])",
"and ('input' == cvars[0] or 'output' == cvars[0]): #if cvars[3]",
"import copy import io #import timeit class stream: set0 =",
"seq_in = [] seq_out = [] vars = {} var_array_inds",
"# in the top-level source directory) and their institutional affiliations.",
"int(ind_end,0) else: #case of symbolic symb_end = True if not",
"suport for universal quantifiers is added self.constr2terms.append(cvars) else: if signal[:signal.find('[')]",
"== cvars[0]): #if cvars[3] == 'strg_ub_pre_fetch_0_input_latency': # continue if len(cvars)",
"gen = [0]*len(dims) j = len(dims)-1 while j >= 0:",
"set0 = [] set1 = [] seq_in = [] seq_out",
"argparse import pono as c import sys import re import",
"cvars[-2] elif 'RSTN' == cvars[-1]: self.rst_n_name = cvars[-2] else: assert",
"LICENSE in the top-level source # directory for licensing information.",
"############################################################################### import smt_switch as ss import smt_switch.primops as po import",
"dims.append(int(rem_dims[1:rem_dims.find(':')],0)) rem_dims = rem_dims[rem_dims.find(']')+1:] gen = [0]*len(dims) j = len(dims)-1",
"if signal[:signal.find('[')] not in self.var_array_inds: self.var_array_inds[signal[:signal.find('[')]] = [] self.var_array_inds[signal[:signal.find('[')]].append(signal[signal.find('[')+1:signal.find(']')]) elif",
"ind_end = int(ind_end,0) else: #case of symbolic symb_end = True",
"agg_set, tb_set, sram_set, symbols, solver): global dim_names # open an",
"file if args.annotation == None: if agg_set: annot_file = args.hwpath+\"agg_lake_top_annotation.txt\"",
"= cln.split() if 'var' == cvars[0]: self.vars[cvars[1]] = cvars[3] elif",
"len(self.data_out_size) <= 3 gen = [0]*len(dims) j = len(dims)-1 while",
"elif ind_start.isdigit(): ind_start = int(ind_start,0) else: symb_start = True ind_end",
"0: if gen[j] <= dims[j]: build_dims = cvars[-2] for i",
"False if ind_start in self.vars: ind_start = int(self.vars[ind_start],0) elif ind_start.isdigit():",
"ss import smt_switch.primops as po import smt_switch.sortkinds as sk import",
"'if' != cvars[0] and 'SOLVE' != cvars[1]: self.constr2terms.append(cvars) elif 'if'",
"elif 'SOLVE' == cvars[-1] and ('input' == cvars[0] or 'output'",
"else: self.set1.append(build_dims) while (j < len(dims)-1 and gen[j+1] == 0):",
"# open an annotation file if args.annotation == None: if",
"they appear in btor2 for cln in clines: cln =",
"for i in range(ind_start,ind_end+1): self.var_array_inds[signal_name].append(i) else: #implement later when suport",
"dims = [] while (rem_dims != ''): dims.append(int(rem_dims[1:rem_dims.find(':')],0)) rem_dims =",
"[] while (rem_dims != ''): dims.append(int(rem_dims[1:rem_dims.find(':')],0)) rem_dims = rem_dims[rem_dims.find(']')+1:] gen",
"elif 'CLK' == cvars[-1]: self.clk_name = cvars[-2] elif 'RSTN' ==",
"j -= 1 gen[j] += 1 else: if cvars[0] ==",
"cvars[1]: self.constr2terms.append(cvars) elif 'if' == cvars[0]: self.constr2terms.append(cvars) elif 'SOLVE' ==",
"import smt_switch as ss import smt_switch.primops as po import smt_switch.sortkinds",
"vars = {} var_array_inds = {} constr2terms = [] data_in_size",
"signal[:signal.find('[')] ind_start = signal[signal.find('[')+1:signal.find(':')] symb_start = False if ind_start in",
"== 6: rem_dims = cvars[2] dims = [] while (rem_dims",
"'SOLVE' == cvars[-1] and ('input' == cvars[0] or 'output' ==",
"cvars[2] dims = [] while (rem_dims != ''): dims.append(int(rem_dims[1:rem_dims.find(':')],0)) rem_dims",
"in the top-level source directory) and their institutional affiliations. #",
"build_dims + '['+str(i)+']' if cvars[-1][-1:] == '0': self.set0.append(build_dims) else: self.set1.append(build_dims)",
"= [] seq_out = [] vars = {} var_array_inds =",
"ind_start.isdigit(): ind_start = int(ind_start,0) else: symb_start = True ind_end =",
"the configuration finder for the Stanford AHA project. # Copyright",
"self.constr2terms.append(cvars) else: if signal[:signal.find('[')] not in self.var_array_inds: self.var_array_inds[signal[:signal.find('[')]] = []",
"in gen: build_dims = build_dims + '['+str(i)+']' if cvars[-1][-1:] ==",
"# directory for licensing information. # # Handles parsing of",
"else: self.set1.append(cvars[-2]) elif 'SEQUENCE' == cvars[-1]: if len(cvars) == 6:",
"symbols, solver): global dim_names # open an annotation file if",
"open(annot_file, \"r+\") clines = cfo.readlines() # Close opend file cfo.close()",
"= args.annotation cfo = open(annot_file, \"r+\") clines = cfo.readlines() #",
"symb_end = False if ind_end in self.vars: ind_end = int(self.vars[ind_end],0)",
"== 'input': self.seq_in.append(build_dims) else: self.seq_out.append(build_dims) while (j < len(dims)-1 and",
"information. # # Handles parsing of all input files. ###############################################################################",
"cvars[-1]: self.clk_name = cvars[-2] elif 'RSTN' == cvars[-1]: self.rst_n_name =",
"if cvars[0] == 'input': self.seq_in.append(cvars[-2]) else: self.seq_out.append(cvars[-2]) elif 'SOLVE' ==",
"== cvars[0]: self.constr2terms.append(cvars) elif 'SOLVE' == cvars[1]:#specific bits are set",
"Collect the Set0, Set1, I/O sequence, and config_name variables as",
"universal quantifiers is added self.constr2terms.append(cvars) else: if signal[:signal.find('[')] not in",
"= cvars[3] elif 'input' != cvars[0] and 'output' != cvars[0]",
"cvars[0] or 'output' == cvars[0]): #if cvars[3] == 'strg_ub_pre_fetch_0_input_latency': #",
"i in gen: build_dims = build_dims + '['+str(i)+']' if cvars[-1][-1:]",
"build_dims + '['+str(i)+']' if cvars[0] == 'input': self.seq_in.append(build_dims) else: self.seq_out.append(build_dims)",
"cvars[0] if ':' in signal: signal_name = signal[:signal.find('[')] ind_start =",
"= int(cvars[2][1:cvars[2].find(':')],0) for i in range(dim+1): self.config_names.append(cvars[-2]+'['+str(i)+']') else: self.config_names.append(cvars[-2]) elif",
"in range(ind_start,ind_end+1): self.var_array_inds[signal_name].append(i) else: #implement later when suport for universal",
"range(ind_start,ind_end+1): self.var_array_inds[signal_name].append(i) else: #implement later when suport for universal quantifiers",
"= {} constr2terms = [] data_in_size = [] data_out_size =",
"the top-level source directory) and their institutional affiliations. # All",
"+ '['+str(i)+']' if cvars[0] == 'input': self.seq_in.append(build_dims) else: self.seq_out.append(build_dims) while",
"if ind_end in self.vars: ind_end = int(self.vars[ind_end],0) elif ind_end.isdigit(): ind_end",
"gen[j+1] == 0): j += 1 else: gen[j] = 0",
"= dims else: self.data_out_size = dims assert len(self.data_in_size) <= 3",
"== cvars[0] or 'output' == cvars[0]): #if cvars[3] == 'strg_ub_pre_fetch_0_input_latency':",
"their institutional affiliations. # All rights reserved. See the file",
"'['+str(i)+']' if cvars[0] == 'input': self.seq_in.append(build_dims) else: self.seq_out.append(build_dims) while (j",
"else: #case of symbolic symb_end = True if not symb_start",
"authors listed in the file AUTHORS # in the top-level",
"[] data_out_size = [] clk_name = None rst_n_name = None",
"var_array_inds = {} constr2terms = [] data_in_size = [] data_out_size",
"cvars[-1][-1:] == '0': self.set0.append(cvars[-2]) else: self.set1.append(cvars[-2]) elif 'SEQUENCE' == cvars[-1]:",
"sys import re import time import copy import io #import",
"cvars[0]: self.constr2terms.append(cvars) elif 'SOLVE' == cvars[1]:#specific bits are set only",
"if not symb_start and not symb_end: if signal[:signal.find('[')] not in",
"data_in_size = [] data_out_size = [] clk_name = None rst_n_name",
"quantifiers is added self.constr2terms.append(cvars) else: if signal[:signal.find('[')] not in self.var_array_inds:",
"'['+str(i)+']' if cvars[-1][-1:] == '0': self.set0.append(build_dims) else: self.set1.append(build_dims) while (j",
"else: self.seq_out.append(cvars[-2]) elif 'SOLVE' == cvars[-1] and ('input' == cvars[0]",
"# Close opend file cfo.close() # Collect the Set0, Set1,",
"+= 1 else: gen[j] = 0 j -= 1 gen[j]",
"== cvars[-1] and ('input' == cvars[0] or 'output' == cvars[0]):",
"elif sram_set: annot_file = args.hwpath+\"sram_lake_top_annotation.txt\" else: annot_file = args.hwpath+\"lake_top_annotation.txt\" else:",
"int(self.vars[ind_end],0) elif ind_end.isdigit(): ind_end = int(ind_end,0) else: #case of symbolic",
"#import timeit class stream: set0 = [] set1 = []",
"= True if not symb_start and not symb_end: if signal[:signal.find('[')]",
"j >= 0: if gen[j] <= dims[j]: build_dims = cvars[-2]",
"{} var_array_inds = {} constr2terms = [] data_in_size = []",
"in the top-level source # directory for licensing information. #",
"smt_switch as ss import smt_switch.primops as po import smt_switch.sortkinds as",
"signal: signal_name = signal[:signal.find('[')] ind_start = signal[signal.find('[')+1:signal.find(':')] symb_start = False",
"!= cvars[0] and 'if' != cvars[0] and 'SOLVE' != cvars[1]:",
"signal[signal.find('[')+1:signal.find(':')] symb_start = False if ind_start in self.vars: ind_start =",
"of the configuration finder for the Stanford AHA project. #",
"sk import argparse import pono as c import sys import",
"== cvars[-1][:-1]: if len(cvars) == 6: rem_dims = cvars[2] dims",
"[] seq_in = [] seq_out = [] vars = {}",
"cln.split() if 'var' == cvars[0]: self.vars[cvars[1]] = cvars[3] elif 'input'",
"':' in signal: signal_name = signal[:signal.find('[')] ind_start = signal[signal.find('[')+1:signal.find(':')] symb_start",
"opend file cfo.close() # Collect the Set0, Set1, I/O sequence,",
"############################################################################### # file -- parse.py -- # Top contributors (to",
"= cvars[2] dims = [] while (rem_dims != ''): dims.append(int(rem_dims[1:rem_dims.find(':')],0))",
"ind_end in self.vars: ind_end = int(self.vars[ind_end],0) elif ind_end.isdigit(): ind_end =",
"self.vars[cvars[1]] = cvars[3] elif 'input' != cvars[0] and 'output' !=",
"'input': self.seq_in.append(build_dims) else: self.seq_out.append(build_dims) while (j < len(dims)-1 and gen[j+1]",
"= [] self.var_array_inds[signal[:signal.find('[')]].append(signal[signal.find('[')+1:signal.find(']')]) elif 'SET' == cvars[-1][:-1]: if len(cvars) ==",
"[] def read_stream(self, args, fout, agg_set, tb_set, sram_set, symbols, solver):",
"source directory) and their institutional affiliations. # All rights reserved.",
"pono as c import sys import re import time import",
"All rights reserved. See the file LICENSE in the top-level",
"else: symb_start = True ind_end = signal[signal.find(':')+1:signal.find(']')] symb_end = False",
"for the Stanford AHA project. # Copyright (c) 2021 by",
"# Top contributors (to current version): # <NAME> # This",
"= rem_dims[rem_dims.find(']')+1:] if cvars[0] == 'input': self.data_in_size = dims else:",
"po import smt_switch.sortkinds as sk import argparse import pono as",
"= signal[signal.find('[')+1:signal.find(':')] symb_start = False if ind_start in self.vars: ind_start",
"if cvars[0] == 'input': self.data_in_size = dims else: self.data_out_size =",
"!= ''): dims.append(int(rem_dims[1:rem_dims.find(':')],0)) rem_dims = rem_dims[rem_dims.find(']')+1:] if cvars[0] == 'input':",
"can be anything, e.g. 0 signal = cvars[0] if ':'",
"solver): global dim_names # open an annotation file if args.annotation",
"args.annotation cfo = open(annot_file, \"r+\") clines = cfo.readlines() # Close",
"True ind_end = signal[signal.find(':')+1:signal.find(']')] symb_end = False if ind_end in",
"clines = cfo.readlines() # Close opend file cfo.close() # Collect",
"= 0 j -= 1 gen[j] += 1 else: if",
"file LICENSE in the top-level source # directory for licensing",
"and 'SOLVE' != cvars[1]: self.constr2terms.append(cvars) elif 'if' == cvars[0]: self.constr2terms.append(cvars)",
"self.var_array_inds[signal[:signal.find('[')]] = [] for i in range(ind_start,ind_end+1): self.var_array_inds[signal_name].append(i) else: #implement",
"dims else: self.data_out_size = dims assert len(self.data_in_size) <= 3 assert",
"== 0): j += 1 else: gen[j] = 0 j",
"in self.var_array_inds: self.var_array_inds[signal[:signal.find('[')]] = [] self.var_array_inds[signal[:signal.find('[')]].append(signal[signal.find('[')+1:signal.find(']')]) elif 'SET' == cvars[-1][:-1]:",
"if cvars[0] == 'input': self.seq_in.append(build_dims) else: self.seq_out.append(build_dims) while (j <",
"'') cvars = cln.split() if 'var' == cvars[0]: self.vars[cvars[1]] =",
"signal = cvars[0] if ':' in signal: signal_name = signal[:signal.find('[')]",
"else: if cvars[-1][-1:] == '0': self.set0.append(cvars[-2]) else: self.set1.append(cvars[-2]) elif 'SEQUENCE'",
"variables as they appear in btor2 for cln in clines:",
"file AUTHORS # in the top-level source directory) and their",
"rem_dims[rem_dims.find(']')+1:] gen = [0]*len(dims) j = len(dims)-1 while j >=",
"Copyright (c) 2021 by the authors listed in the file",
"tb_set: annot_file = args.hwpath+\"tb_lake_top_annotation.txt\" elif sram_set: annot_file = args.hwpath+\"sram_lake_top_annotation.txt\" else:",
"-- # Top contributors (to current version): # <NAME> #",
"# All rights reserved. See the file LICENSE in the",
"== cvars[1]:#specific bits are set only to be solved. Others",
"else: if cvars[0] == 'input': self.seq_in.append(cvars[-2]) else: self.seq_out.append(cvars[-2]) elif 'SOLVE'",
"signal[:signal.find('[')] not in self.var_array_inds: self.var_array_inds[signal[:signal.find('[')]] = [] self.var_array_inds[signal[:signal.find('[')]].append(signal[signal.find('[')+1:signal.find(']')]) elif 'SET'",
"Handles parsing of all input files. ############################################################################### import smt_switch as",
"[] clk_name = None rst_n_name = None config_names = []",
"elif 'SEQUENCE' == cvars[-1]: if len(cvars) == 6: rem_dims =",
"build_dims = cvars[-2] for i in gen: build_dims = build_dims",
"agg_set: annot_file = args.hwpath+\"agg_lake_top_annotation.txt\" elif tb_set: annot_file = args.hwpath+\"tb_lake_top_annotation.txt\" elif",
"as they appear in btor2 for cln in clines: cln",
"0 j -= 1 gen[j] += 1 else: if cvars[0]",
"clk_name = None rst_n_name = None config_names = [] def",
"if agg_set: annot_file = args.hwpath+\"agg_lake_top_annotation.txt\" elif tb_set: annot_file = args.hwpath+\"tb_lake_top_annotation.txt\"",
"self.vars: ind_end = int(self.vars[ind_end],0) elif ind_end.isdigit(): ind_end = int(ind_end,0) else:",
"self.var_array_inds[signal[:signal.find('[')]] = [] self.var_array_inds[signal[:signal.find('[')]].append(signal[signal.find('[')+1:signal.find(']')]) elif 'SET' == cvars[-1][:-1]: if len(cvars)",
"and gen[j+1] == 0): j += 1 else: gen[j] =",
"'0': self.set0.append(cvars[-2]) else: self.set1.append(cvars[-2]) elif 'SEQUENCE' == cvars[-1]: if len(cvars)",
"smt_switch.primops as po import smt_switch.sortkinds as sk import argparse import",
"None rst_n_name = None config_names = [] def read_stream(self, args,",
"int(cvars[2][1:cvars[2].find(':')],0) for i in range(dim+1): self.config_names.append(cvars[-2]+'['+str(i)+']') else: self.config_names.append(cvars[-2]) elif 'CLK'",
"seq_out = [] vars = {} var_array_inds = {} constr2terms",
"args.hwpath+\"sram_lake_top_annotation.txt\" else: annot_file = args.hwpath+\"lake_top_annotation.txt\" else: annot_file = args.annotation cfo",
"cvars[-1][-1:] == '0': self.set0.append(build_dims) else: self.set1.append(build_dims) while (j < len(dims)-1",
"3 assert len(self.data_out_size) <= 3 gen = [0]*len(dims) j =",
"cvars[-1][:-1]: if len(cvars) == 6: rem_dims = cvars[2] dims =",
"= False if ind_start in self.vars: ind_start = int(self.vars[ind_start],0) elif",
"appear in btor2 for cln in clines: cln = cln.strip()",
"-- parse.py -- # Top contributors (to current version): #",
"import smt_switch.primops as po import smt_switch.sortkinds as sk import argparse",
"Others can be anything, e.g. 0 signal = cvars[0] if",
"the authors listed in the file AUTHORS # in the",
"This file is part of the configuration finder for the",
"= [] def read_stream(self, args, fout, agg_set, tb_set, sram_set, symbols,",
"ind_end = int(self.vars[ind_end],0) elif ind_end.isdigit(): ind_end = int(ind_end,0) else: #case",
"build_dims = build_dims + '['+str(i)+']' if cvars[0] == 'input': self.seq_in.append(build_dims)",
"cvars[0] and 'output' != cvars[0] and 'var' != cvars[0] and",
"and not symb_end: if signal[:signal.find('[')] not in self.var_array_inds: self.var_array_inds[signal[:signal.find('[')]] =",
"ind_start = int(ind_start,0) else: symb_start = True ind_end = signal[signal.find(':')+1:signal.find(']')]",
"ind_start = int(self.vars[ind_start],0) elif ind_start.isdigit(): ind_start = int(ind_start,0) else: symb_start",
"elif 'input' != cvars[0] and 'output' != cvars[0] and 'var'",
"= cvars[-2] for i in gen: build_dims = build_dims +",
"ind_start = signal[signal.find('[')+1:signal.find(':')] symb_start = False if ind_start in self.vars:",
"0 signal = cvars[0] if ':' in signal: signal_name =",
"= rem_dims[rem_dims.find(']')+1:] gen = [0]*len(dims) j = len(dims)-1 while j"
] |
[
"request, flash, make_response from werkzeug.security import generate_password_hash from flask_login import",
"#visit=True pass else: resp = make_response(render_template('index.html')) resp.set_cookie('isvisited', 'yess') return resp",
"= visited_time db.session.commit() else: new_visitor = Visitor(ip=visitor_ip,last_visit=visited_time) db.session.add(new_visitor) db.session.commit() return",
"already exists') return redirect(url_for('auth.signup')) # create a new user with",
"Visitor.query.all() visited = Visitor.query.filter_by(ip=visitor_ip).first() visit = False if visited: difference",
"visited.last_visit).seconds) if difference > 60: visit = True visited.last_visit =",
"main = Blueprint('main', __name__) @main.route('/') def index(): #control visitor with",
"request.form.get('name') password = request.form.get('password') user = User.query.filter_by(email=email).first() # if this",
"login_required, current_user from . import db import datetime from .models",
"visited.last_visit = visited_time db.session.commit() else: new_visitor = Visitor(ip=visitor_ip,last_visit=visited_time) db.session.add(new_visitor) db.session.commit()",
"from flask_login import login_required, current_user from . import db import",
"= make_response(render_template('index.html')) resp.set_cookie('isvisited', 'yess') return resp visitor_ip = request.remote_addr visited_time",
"False if visited: difference = abs((visited_time - visited.last_visit).seconds) if difference",
"= False if visited: difference = abs((visited_time - visited.last_visit).seconds) if",
"db.session.commit() return redirect(url_for('auth.login')) @main.route('/profile') @login_required def profile(): return render_template('profile.html', name=current_user.name)",
"User main = Blueprint('main', __name__) @main.route('/') def index(): #control visitor",
"resp visitor_ip = request.remote_addr visited_time = datetime.datetime.now() visitors = Visitor.query.all()",
"plaintext version isn't saved. new_user = User(email=email, name=name, password=generate_password_hash(password, method='sha256'))",
"request.form.get('password') user = User.query.filter_by(email=email).first() # if this returns a user,",
"page so user can try again flash('Email address already exists')",
"a user is found, we want to redirect back to",
"import generate_password_hash from flask_login import login_required, current_user from . import",
"difference = abs((visited_time - visited.last_visit).seconds) if difference > 60: visit",
"return render_template('index.html',visitors=visitors,visit=visit) @main.route('/', methods=['POST']) def index_post(): email = request.form.get('email') name",
"visitor_ip = request.remote_addr visited_time = datetime.datetime.now() visitors = Visitor.query.all() visited",
"new user to the database db.session.add(new_user) db.session.commit() return redirect(url_for('auth.login')) @main.route('/profile')",
"again flash('Email address already exists') return redirect(url_for('auth.signup')) # create a",
"pass else: resp = make_response(render_template('index.html')) resp.set_cookie('isvisited', 'yess') return resp visitor_ip",
"abs((visited_time - visited.last_visit).seconds) if difference > 60: visit = True",
"werkzeug.security import generate_password_hash from flask_login import login_required, current_user from .",
"import login_required, current_user from . import db import datetime from",
"resp.set_cookie('isvisited', 'yess') return resp visitor_ip = request.remote_addr visited_time = datetime.datetime.now()",
"= abs((visited_time - visited.last_visit).seconds) if difference > 60: visit =",
"request.cookies.get('isvisited') if cookie: #visit=True pass else: resp = make_response(render_template('index.html')) resp.set_cookie('isvisited',",
"= User(email=email, name=name, password=generate_password_hash(password, method='sha256')) # add the new user",
"def index_post(): email = request.form.get('email') name = request.form.get('name') password =",
"database if user: # if a user is found, we",
"with the form data. Hash the password so the plaintext",
"the database db.session.add(new_user) db.session.commit() return redirect(url_for('auth.login')) @main.route('/profile') @login_required def profile():",
"db import datetime from .models import Visitor, User main =",
".models import Visitor, User main = Blueprint('main', __name__) @main.route('/') def",
"datetime.datetime.now() visitors = Visitor.query.all() visited = Visitor.query.filter_by(ip=visitor_ip).first() visit = False",
"import datetime from .models import Visitor, User main = Blueprint('main',",
"datetime from .models import Visitor, User main = Blueprint('main', __name__)",
"a user, then the email already exists in database if",
"user is found, we want to redirect back to signup",
"name=name, password=generate_password_hash(password, method='sha256')) # add the new user to the",
"cookie: #visit=True pass else: resp = make_response(render_template('index.html')) resp.set_cookie('isvisited', 'yess') return",
"if visited: difference = abs((visited_time - visited.last_visit).seconds) if difference >",
"render_template('index.html',visitors=visitors,visit=visit) @main.route('/', methods=['POST']) def index_post(): email = request.form.get('email') name =",
"db.session.add(new_user) db.session.commit() return redirect(url_for('auth.login')) @main.route('/profile') @login_required def profile(): return render_template('profile.html',",
"visited_time = datetime.datetime.now() visitors = Visitor.query.all() visited = Visitor.query.filter_by(ip=visitor_ip).first() visit",
"data. Hash the password so the plaintext version isn't saved.",
"current_user from . import db import datetime from .models import",
"= Blueprint('main', __name__) @main.route('/') def index(): #control visitor with cookies",
"'yess') return resp visitor_ip = request.remote_addr visited_time = datetime.datetime.now() visitors",
"db.session.commit() return render_template('index.html',visitors=visitors,visit=visit) @main.route('/', methods=['POST']) def index_post(): email = request.form.get('email')",
"else: resp = make_response(render_template('index.html')) resp.set_cookie('isvisited', 'yess') return resp visitor_ip =",
"make_response(render_template('index.html')) resp.set_cookie('isvisited', 'yess') return resp visitor_ip = request.remote_addr visited_time =",
"Visitor, User main = Blueprint('main', __name__) @main.route('/') def index(): #control",
"user to the database db.session.add(new_user) db.session.commit() return redirect(url_for('auth.login')) @main.route('/profile') @login_required",
"to redirect back to signup page so user can try",
"redirect, url_for, request, flash, make_response from werkzeug.security import generate_password_hash from",
"User.query.filter_by(email=email).first() # if this returns a user, then the email",
". import db import datetime from .models import Visitor, User",
"can try again flash('Email address already exists') return redirect(url_for('auth.signup')) #",
"flash, make_response from werkzeug.security import generate_password_hash from flask_login import login_required,",
"visitor with cookies cookie = request.cookies.get('isvisited') if cookie: #visit=True pass",
"method='sha256')) # add the new user to the database db.session.add(new_user)",
"new_visitor = Visitor(ip=visitor_ip,last_visit=visited_time) db.session.add(new_visitor) db.session.commit() return render_template('index.html',visitors=visitors,visit=visit) @main.route('/', methods=['POST']) def",
"= request.form.get('email') name = request.form.get('name') password = request.form.get('password') user =",
"try again flash('Email address already exists') return redirect(url_for('auth.signup')) # create",
"the plaintext version isn't saved. new_user = User(email=email, name=name, password=generate_password_hash(password,",
"from .models import Visitor, User main = Blueprint('main', __name__) @main.route('/')",
"return resp visitor_ip = request.remote_addr visited_time = datetime.datetime.now() visitors =",
"to the database db.session.add(new_user) db.session.commit() return redirect(url_for('auth.login')) @main.route('/profile') @login_required def",
"generate_password_hash from flask_login import login_required, current_user from . import db",
"password=generate_password_hash(password, method='sha256')) # add the new user to the database",
"= Visitor(ip=visitor_ip,last_visit=visited_time) db.session.add(new_visitor) db.session.commit() return render_template('index.html',visitors=visitors,visit=visit) @main.route('/', methods=['POST']) def index_post():",
"from flask import Blueprint, render_template, redirect, url_for, request, flash, make_response",
"found, we want to redirect back to signup page so",
"new user with the form data. Hash the password so",
"else: new_visitor = Visitor(ip=visitor_ip,last_visit=visited_time) db.session.add(new_visitor) db.session.commit() return render_template('index.html',visitors=visitors,visit=visit) @main.route('/', methods=['POST'])",
"if difference > 60: visit = True visited.last_visit = visited_time",
"__name__) @main.route('/') def index(): #control visitor with cookies cookie =",
"cookies cookie = request.cookies.get('isvisited') if cookie: #visit=True pass else: resp",
"from . import db import datetime from .models import Visitor,",
"flask import Blueprint, render_template, redirect, url_for, request, flash, make_response from",
"<reponame>omerfarukbaysal/neyesem<gh_stars>0 from flask import Blueprint, render_template, redirect, url_for, request, flash,",
"if a user is found, we want to redirect back",
"difference > 60: visit = True visited.last_visit = visited_time db.session.commit()",
"returns a user, then the email already exists in database",
"then the email already exists in database if user: #",
"redirect(url_for('auth.signup')) # create a new user with the form data.",
"email = request.form.get('email') name = request.form.get('name') password = request.form.get('password') user",
"email already exists in database if user: # if a",
"Visitor(ip=visitor_ip,last_visit=visited_time) db.session.add(new_visitor) db.session.commit() return render_template('index.html',visitors=visitors,visit=visit) @main.route('/', methods=['POST']) def index_post(): email",
"= Visitor.query.all() visited = Visitor.query.filter_by(ip=visitor_ip).first() visit = False if visited:",
"Blueprint, render_template, redirect, url_for, request, flash, make_response from werkzeug.security import",
"60: visit = True visited.last_visit = visited_time db.session.commit() else: new_visitor",
"# add the new user to the database db.session.add(new_user) db.session.commit()",
"flash('Email address already exists') return redirect(url_for('auth.signup')) # create a new",
"visit = False if visited: difference = abs((visited_time - visited.last_visit).seconds)",
"@main.route('/') def index(): #control visitor with cookies cookie = request.cookies.get('isvisited')",
"= User.query.filter_by(email=email).first() # if this returns a user, then the",
"in database if user: # if a user is found,",
"> 60: visit = True visited.last_visit = visited_time db.session.commit() else:",
"create a new user with the form data. Hash the",
"redirect back to signup page so user can try again",
"if this returns a user, then the email already exists",
"the email already exists in database if user: # if",
"password = request.form.get('password') user = User.query.filter_by(email=email).first() # if this returns",
"= request.form.get('name') password = request.form.get('password') user = User.query.filter_by(email=email).first() # if",
"database db.session.add(new_user) db.session.commit() return redirect(url_for('auth.login')) @main.route('/profile') @login_required def profile(): return",
"user, then the email already exists in database if user:",
"exists') return redirect(url_for('auth.signup')) # create a new user with the",
"= request.form.get('password') user = User.query.filter_by(email=email).first() # if this returns a",
"already exists in database if user: # if a user",
"form data. Hash the password so the plaintext version isn't",
"visited_time db.session.commit() else: new_visitor = Visitor(ip=visitor_ip,last_visit=visited_time) db.session.add(new_visitor) db.session.commit() return render_template('index.html',visitors=visitors,visit=visit)",
"if cookie: #visit=True pass else: resp = make_response(render_template('index.html')) resp.set_cookie('isvisited', 'yess')",
"True visited.last_visit = visited_time db.session.commit() else: new_visitor = Visitor(ip=visitor_ip,last_visit=visited_time) db.session.add(new_visitor)",
"Visitor.query.filter_by(ip=visitor_ip).first() visit = False if visited: difference = abs((visited_time -",
"is found, we want to redirect back to signup page",
"Blueprint('main', __name__) @main.route('/') def index(): #control visitor with cookies cookie",
"import Visitor, User main = Blueprint('main', __name__) @main.route('/') def index():",
"index_post(): email = request.form.get('email') name = request.form.get('name') password = request.form.get('password')",
"the form data. Hash the password so the plaintext version",
"so the plaintext version isn't saved. new_user = User(email=email, name=name,",
"import Blueprint, render_template, redirect, url_for, request, flash, make_response from werkzeug.security",
"# if this returns a user, then the email already",
"want to redirect back to signup page so user can",
"exists in database if user: # if a user is",
"user: # if a user is found, we want to",
"Hash the password so the plaintext version isn't saved. new_user",
"index(): #control visitor with cookies cookie = request.cookies.get('isvisited') if cookie:",
"#control visitor with cookies cookie = request.cookies.get('isvisited') if cookie: #visit=True",
"add the new user to the database db.session.add(new_user) db.session.commit() return",
"request.form.get('email') name = request.form.get('name') password = request.form.get('password') user = User.query.filter_by(email=email).first()",
"= datetime.datetime.now() visitors = Visitor.query.all() visited = Visitor.query.filter_by(ip=visitor_ip).first() visit =",
"= request.remote_addr visited_time = datetime.datetime.now() visitors = Visitor.query.all() visited =",
"make_response from werkzeug.security import generate_password_hash from flask_login import login_required, current_user",
"user can try again flash('Email address already exists') return redirect(url_for('auth.signup'))",
"the new user to the database db.session.add(new_user) db.session.commit() return redirect(url_for('auth.login'))",
"= request.cookies.get('isvisited') if cookie: #visit=True pass else: resp = make_response(render_template('index.html'))",
"@main.route('/', methods=['POST']) def index_post(): email = request.form.get('email') name = request.form.get('name')",
"= True visited.last_visit = visited_time db.session.commit() else: new_visitor = Visitor(ip=visitor_ip,last_visit=visited_time)",
"User(email=email, name=name, password=generate_password_hash(password, method='sha256')) # add the new user to",
"isn't saved. new_user = User(email=email, name=name, password=generate_password_hash(password, method='sha256')) # add",
"# if a user is found, we want to redirect",
"visit = True visited.last_visit = visited_time db.session.commit() else: new_visitor =",
"methods=['POST']) def index_post(): email = request.form.get('email') name = request.form.get('name') password",
"to signup page so user can try again flash('Email address",
"new_user = User(email=email, name=name, password=generate_password_hash(password, method='sha256')) # add the new",
"visited: difference = abs((visited_time - visited.last_visit).seconds) if difference > 60:",
"the password so the plaintext version isn't saved. new_user =",
"def index(): #control visitor with cookies cookie = request.cookies.get('isvisited') if",
"so user can try again flash('Email address already exists') return",
"- visited.last_visit).seconds) if difference > 60: visit = True visited.last_visit",
"db.session.commit() else: new_visitor = Visitor(ip=visitor_ip,last_visit=visited_time) db.session.add(new_visitor) db.session.commit() return render_template('index.html',visitors=visitors,visit=visit) @main.route('/',",
"a new user with the form data. Hash the password",
"this returns a user, then the email already exists in",
"render_template, redirect, url_for, request, flash, make_response from werkzeug.security import generate_password_hash",
"we want to redirect back to signup page so user",
"visited = Visitor.query.filter_by(ip=visitor_ip).first() visit = False if visited: difference =",
"flask_login import login_required, current_user from . import db import datetime",
"resp = make_response(render_template('index.html')) resp.set_cookie('isvisited', 'yess') return resp visitor_ip = request.remote_addr",
"cookie = request.cookies.get('isvisited') if cookie: #visit=True pass else: resp =",
"import db import datetime from .models import Visitor, User main",
"name = request.form.get('name') password = request.form.get('password') user = User.query.filter_by(email=email).first() #",
"request.remote_addr visited_time = datetime.datetime.now() visitors = Visitor.query.all() visited = Visitor.query.filter_by(ip=visitor_ip).first()",
"user = User.query.filter_by(email=email).first() # if this returns a user, then",
"user with the form data. Hash the password so the",
"saved. new_user = User(email=email, name=name, password=generate_password_hash(password, method='sha256')) # add the",
"url_for, request, flash, make_response from werkzeug.security import generate_password_hash from flask_login",
"if user: # if a user is found, we want",
"from werkzeug.security import generate_password_hash from flask_login import login_required, current_user from",
"address already exists') return redirect(url_for('auth.signup')) # create a new user",
"# create a new user with the form data. Hash",
"back to signup page so user can try again flash('Email",
"password so the plaintext version isn't saved. new_user = User(email=email,",
"visitors = Visitor.query.all() visited = Visitor.query.filter_by(ip=visitor_ip).first() visit = False if",
"signup page so user can try again flash('Email address already",
"version isn't saved. new_user = User(email=email, name=name, password=generate_password_hash(password, method='sha256')) #",
"db.session.add(new_visitor) db.session.commit() return render_template('index.html',visitors=visitors,visit=visit) @main.route('/', methods=['POST']) def index_post(): email =",
"with cookies cookie = request.cookies.get('isvisited') if cookie: #visit=True pass else:",
"= Visitor.query.filter_by(ip=visitor_ip).first() visit = False if visited: difference = abs((visited_time",
"return redirect(url_for('auth.signup')) # create a new user with the form"
] |
[
"print(conteudo) print(rodape) def ler_opcoes(): opcao = int(input(\"Insira a opção: \"))",
"== 1: imprimir_tela(\"A opção escolhida foi 'Cadastrar funcionário'\") elif opcao",
"foi 'Cadastrar funcionário'\") elif opcao == 2: imprimir_tela(\"A opção escolhida",
"funcionário'\") elif opcao == 5: imprimir_tela(\"A opção escolhida foi 'Sair'\")",
"DE CADASTRO DE FUNCIONARIO\\n\\n\\n\" rodape = \"\\n\\n\\n Obrigada pela preferencia\"",
"opcao == 2: imprimir_tela(\"A opção escolhida foi 'Listar funcionários'\") elif",
"preferencia\" def imprimir_tela(conteudo): print(cabecalho) #print(opcao_menu) print(conteudo) print(rodape) def ler_opcoes(): opcao",
"elif opcao == 2: imprimir_tela(\"A opção escolhida foi 'Listar funcionários'\")",
"rodape = \"\\n\\n\\n Obrigada pela preferencia\" def imprimir_tela(conteudo): print(cabecalho) #print(opcao_menu)",
"int(input(\"Insira a opção: \")) return opcao def carregar_opcoes(opcao): if opcao",
"opcao def carregar_opcoes(opcao): if opcao == 1: imprimir_tela(\"A opção escolhida",
"= \"SISTEMA DE CADASTRO DE FUNCIONARIO\\n\\n\\n\" rodape = \"\\n\\n\\n Obrigada",
"print(rodape) def ler_opcoes(): opcao = int(input(\"Insira a opção: \")) return",
"ler_opcoes(): opcao = int(input(\"Insira a opção: \")) return opcao def",
"opcao == 1: imprimir_tela(\"A opção escolhida foi 'Cadastrar funcionário'\") elif",
"escolhida foi 'Editar funcionário'\") elif opcao == 4: imprimir_tela(\"A opção",
"DE FUNCIONARIO\\n\\n\\n\" rodape = \"\\n\\n\\n Obrigada pela preferencia\" def imprimir_tela(conteudo):",
"def carregar_opcoes(opcao): if opcao == 1: imprimir_tela(\"A opção escolhida foi",
"opção escolhida foi 'Editar funcionário'\") elif opcao == 4: imprimir_tela(\"A",
"opção: \")) return opcao def carregar_opcoes(opcao): if opcao == 1:",
"# Funções cabecalho = \"SISTEMA DE CADASTRO DE FUNCIONARIO\\n\\n\\n\" rodape",
"opcao == 3: imprimir_tela(\"A opção escolhida foi 'Editar funcionário'\") elif",
"def imprimir_tela(conteudo): print(cabecalho) #print(opcao_menu) print(conteudo) print(rodape) def ler_opcoes(): opcao =",
"escolhida foi 'Listar funcionários'\") elif opcao == 3: imprimir_tela(\"A opção",
"4: imprimir_tela(\"A opção escolhida foi 'Deletar funcionário'\") elif opcao ==",
"cabecalho = \"SISTEMA DE CADASTRO DE FUNCIONARIO\\n\\n\\n\" rodape = \"\\n\\n\\n",
"imprimir_tela(\"A opção escolhida foi 'Listar funcionários'\") elif opcao == 3:",
"= \"\\n\\n\\n Obrigada pela preferencia\" def imprimir_tela(conteudo): print(cabecalho) #print(opcao_menu) print(conteudo)",
"pela preferencia\" def imprimir_tela(conteudo): print(cabecalho) #print(opcao_menu) print(conteudo) print(rodape) def ler_opcoes():",
"#print(opcao_menu) print(conteudo) print(rodape) def ler_opcoes(): opcao = int(input(\"Insira a opção:",
"elif opcao == 5: imprimir_tela(\"A opção escolhida foi 'Sair'\") else:",
"Obrigada pela preferencia\" def imprimir_tela(conteudo): print(cabecalho) #print(opcao_menu) print(conteudo) print(rodape) def",
"return opcao def carregar_opcoes(opcao): if opcao == 1: imprimir_tela(\"A opção",
"opção escolhida foi 'Listar funcionários'\") elif opcao == 3: imprimir_tela(\"A",
"elif opcao == 4: imprimir_tela(\"A opção escolhida foi 'Deletar funcionário'\")",
"opcao == 4: imprimir_tela(\"A opção escolhida foi 'Deletar funcionário'\") elif",
"opção escolhida foi 'Deletar funcionário'\") elif opcao == 5: imprimir_tela(\"A",
"imprimir_tela(\"A opção escolhida foi 'Editar funcionário'\") elif opcao == 4:",
"\"SISTEMA DE CADASTRO DE FUNCIONARIO\\n\\n\\n\" rodape = \"\\n\\n\\n Obrigada pela",
"funcionário'\") elif opcao == 4: imprimir_tela(\"A opção escolhida foi 'Deletar",
"foi 'Listar funcionários'\") elif opcao == 3: imprimir_tela(\"A opção escolhida",
"funcionários'\") elif opcao == 3: imprimir_tela(\"A opção escolhida foi 'Editar",
"imprimir_tela(\"A opção escolhida foi 'Cadastrar funcionário'\") elif opcao == 2:",
"opcao == 5: imprimir_tela(\"A opção escolhida foi 'Sair'\") else: pass",
"CADASTRO DE FUNCIONARIO\\n\\n\\n\" rodape = \"\\n\\n\\n Obrigada pela preferencia\" def",
"Funções cabecalho = \"SISTEMA DE CADASTRO DE FUNCIONARIO\\n\\n\\n\" rodape =",
"\"\\n\\n\\n Obrigada pela preferencia\" def imprimir_tela(conteudo): print(cabecalho) #print(opcao_menu) print(conteudo) print(rodape)",
"1: imprimir_tela(\"A opção escolhida foi 'Cadastrar funcionário'\") elif opcao ==",
"imprimir_tela(\"A opção escolhida foi 'Deletar funcionário'\") elif opcao == 5:",
"print(cabecalho) #print(opcao_menu) print(conteudo) print(rodape) def ler_opcoes(): opcao = int(input(\"Insira a",
"escolhida foi 'Cadastrar funcionário'\") elif opcao == 2: imprimir_tela(\"A opção",
"carregar_opcoes(opcao): if opcao == 1: imprimir_tela(\"A opção escolhida foi 'Cadastrar",
"= int(input(\"Insira a opção: \")) return opcao def carregar_opcoes(opcao): if",
"foi 'Editar funcionário'\") elif opcao == 4: imprimir_tela(\"A opção escolhida",
"opcao = int(input(\"Insira a opção: \")) return opcao def carregar_opcoes(opcao):",
"'Cadastrar funcionário'\") elif opcao == 2: imprimir_tela(\"A opção escolhida foi",
"== 3: imprimir_tela(\"A opção escolhida foi 'Editar funcionário'\") elif opcao",
"if opcao == 1: imprimir_tela(\"A opção escolhida foi 'Cadastrar funcionário'\")",
"elif opcao == 3: imprimir_tela(\"A opção escolhida foi 'Editar funcionário'\")",
"3: imprimir_tela(\"A opção escolhida foi 'Editar funcionário'\") elif opcao ==",
"imprimir_tela(conteudo): print(cabecalho) #print(opcao_menu) print(conteudo) print(rodape) def ler_opcoes(): opcao = int(input(\"Insira",
"'Listar funcionários'\") elif opcao == 3: imprimir_tela(\"A opção escolhida foi",
"2: imprimir_tela(\"A opção escolhida foi 'Listar funcionários'\") elif opcao ==",
"\")) return opcao def carregar_opcoes(opcao): if opcao == 1: imprimir_tela(\"A",
"funcionário'\") elif opcao == 2: imprimir_tela(\"A opção escolhida foi 'Listar",
"== 2: imprimir_tela(\"A opção escolhida foi 'Listar funcionários'\") elif opcao",
"foi 'Deletar funcionário'\") elif opcao == 5: imprimir_tela(\"A opção escolhida",
"'Deletar funcionário'\") elif opcao == 5: imprimir_tela(\"A opção escolhida foi",
"a opção: \")) return opcao def carregar_opcoes(opcao): if opcao ==",
"== 4: imprimir_tela(\"A opção escolhida foi 'Deletar funcionário'\") elif opcao",
"'Editar funcionário'\") elif opcao == 4: imprimir_tela(\"A opção escolhida foi",
"FUNCIONARIO\\n\\n\\n\" rodape = \"\\n\\n\\n Obrigada pela preferencia\" def imprimir_tela(conteudo): print(cabecalho)",
"def ler_opcoes(): opcao = int(input(\"Insira a opção: \")) return opcao",
"escolhida foi 'Deletar funcionário'\") elif opcao == 5: imprimir_tela(\"A opção",
"opção escolhida foi 'Cadastrar funcionário'\") elif opcao == 2: imprimir_tela(\"A"
] |
[
"self.value == \"DIV\": return a // b elif self.value ==",
"\"MULT\": return a * b elif self.value == \"DIV\": return",
"elif self.value == \"LE\": return a <= b elif self.value",
"self.value == \"GREATER\": return a > b elif self.value ==",
"a - b elif self.value == \"PLUS\": return a +",
"< b elif self.value == \"GE\": return a >= b",
"\"PLUS\": return a + b elif self.value == \"MULT\": return",
"and b elif self.value == \"OR\": return a or b",
"= self.children[0].eval(st) b = self.children[1].eval(st) if self.value == \"MINUS\": return",
"\"GREATER\": return a > b elif self.value == \"LESS\": return",
"<= b elif self.value == \"EQUALS\": return a == b",
"import Node class BinOp(Node): def eval(self, st): a = self.children[0].eval(st)",
"a = self.children[0].eval(st) b = self.children[1].eval(st) if self.value == \"MINUS\":",
"self.value == \"LESS\": return a < b elif self.value ==",
"self.value == \"PLUS\": return a + b elif self.value ==",
"BinOp(Node): def eval(self, st): a = self.children[0].eval(st) b = self.children[1].eval(st)",
"b = self.children[1].eval(st) if self.value == \"MINUS\": return a -",
"eval(self, st): a = self.children[0].eval(st) b = self.children[1].eval(st) if self.value",
"self.children[1].eval(st) if self.value == \"MINUS\": return a - b elif",
"node import Node class BinOp(Node): def eval(self, st): a =",
"== \"GREATER\": return a > b elif self.value == \"LESS\":",
"b elif self.value == \"LE\": return a <= b elif",
"== \"DIV\": return a // b elif self.value == \"GREATER\":",
"b elif self.value == \"GE\": return a >= b elif",
"== \"MINUS\": return a - b elif self.value == \"PLUS\":",
"\"GE\": return a >= b elif self.value == \"LE\": return",
"class BinOp(Node): def eval(self, st): a = self.children[0].eval(st) b =",
"<reponame>lucassa3/CCompiler<filename>ast_version/src/binop.py from node import Node class BinOp(Node): def eval(self, st):",
"self.value == \"GE\": return a >= b elif self.value ==",
"elif self.value == \"AND\": return a and b elif self.value",
"return a * b elif self.value == \"DIV\": return a",
"return a - b elif self.value == \"PLUS\": return a",
"\"AND\": return a and b elif self.value == \"OR\": return",
"self.children[0].eval(st) b = self.children[1].eval(st) if self.value == \"MINUS\": return a",
"== \"AND\": return a and b elif self.value == \"OR\":",
"if self.value == \"MINUS\": return a - b elif self.value",
"b elif self.value == \"AND\": return a and b elif",
"a < b elif self.value == \"GE\": return a >=",
"self.value == \"EQUALS\": return a == b elif self.value ==",
"\"LE\": return a <= b elif self.value == \"EQUALS\": return",
"a > b elif self.value == \"LESS\": return a <",
"Node class BinOp(Node): def eval(self, st): a = self.children[0].eval(st) b",
"self.value == \"LE\": return a <= b elif self.value ==",
"== \"LESS\": return a < b elif self.value == \"GE\":",
"b elif self.value == \"LESS\": return a < b elif",
"elif self.value == \"PLUS\": return a + b elif self.value",
"elif self.value == \"EQUALS\": return a == b elif self.value",
"def eval(self, st): a = self.children[0].eval(st) b = self.children[1].eval(st) if",
"b elif self.value == \"DIV\": return a // b elif",
"return a > b elif self.value == \"LESS\": return a",
"return a <= b elif self.value == \"EQUALS\": return a",
"\"DIV\": return a // b elif self.value == \"GREATER\": return",
"a >= b elif self.value == \"LE\": return a <=",
"b elif self.value == \"GREATER\": return a > b elif",
"\"EQUALS\": return a == b elif self.value == \"AND\": return",
"b elif self.value == \"MULT\": return a * b elif",
"== b elif self.value == \"AND\": return a and b",
"== \"LE\": return a <= b elif self.value == \"EQUALS\":",
"// b elif self.value == \"GREATER\": return a > b",
"b elif self.value == \"EQUALS\": return a == b elif",
"elif self.value == \"GREATER\": return a > b elif self.value",
"return a >= b elif self.value == \"LE\": return a",
"a and b elif self.value == \"OR\": return a or",
"st): a = self.children[0].eval(st) b = self.children[1].eval(st) if self.value ==",
"return a and b elif self.value == \"OR\": return a",
"a * b elif self.value == \"DIV\": return a //",
"elif self.value == \"LESS\": return a < b elif self.value",
">= b elif self.value == \"LE\": return a <= b",
"* b elif self.value == \"DIV\": return a // b",
"a == b elif self.value == \"AND\": return a and",
"== \"EQUALS\": return a == b elif self.value == \"AND\":",
"self.value == \"AND\": return a and b elif self.value ==",
"return a < b elif self.value == \"GE\": return a",
"elif self.value == \"DIV\": return a // b elif self.value",
"a <= b elif self.value == \"EQUALS\": return a ==",
"b elif self.value == \"PLUS\": return a + b elif",
"a + b elif self.value == \"MULT\": return a *",
"== \"PLUS\": return a + b elif self.value == \"MULT\":",
"elif self.value == \"GE\": return a >= b elif self.value",
"\"MINUS\": return a - b elif self.value == \"PLUS\": return",
"> b elif self.value == \"LESS\": return a < b",
"= self.children[1].eval(st) if self.value == \"MINUS\": return a - b",
"return a == b elif self.value == \"AND\": return a",
"self.value == \"MULT\": return a * b elif self.value ==",
"a // b elif self.value == \"GREATER\": return a >",
"== \"GE\": return a >= b elif self.value == \"LE\":",
"\"LESS\": return a < b elif self.value == \"GE\": return",
"elif self.value == \"MULT\": return a * b elif self.value",
"from node import Node class BinOp(Node): def eval(self, st): a",
"return a + b elif self.value == \"MULT\": return a",
"return a // b elif self.value == \"GREATER\": return a",
"== \"MULT\": return a * b elif self.value == \"DIV\":",
"- b elif self.value == \"PLUS\": return a + b",
"+ b elif self.value == \"MULT\": return a * b",
"self.value == \"MINUS\": return a - b elif self.value =="
] |
[
"(C) 2019,2020 <NAME> <<EMAIL>> # Copyright (C) 2020, <NAME> #",
"name = package.name start_time = time.perf_counter() self.logger.info(\"Downloading {}...\".format(name)) self.logger.debug(\"Download URL:",
"command_args = [self.command, 'x', '-aoa', '-bd', '-y', '-o{}'.format(self.base_dir), archive] else:",
"ar in self.qt_archives.get_archives()] done, not_done = concurrent.futures.wait(futures, return_when=concurrent.futures.FIRST_EXCEPTION) if len(not_done)",
"in self.qt_archives.get_archives()] done, not_done = concurrent.futures.wait(futures, return_when=concurrent.futures.FIRST_EXCEPTION) if len(not_done) >",
"lines: if line.startswith('QT_EDITION ='): line = 'QT_EDITION = OpenSource\\n' if",
"proc = subprocess.run(command_args, stdout=subprocess.PIPE, check=True) self.logger.debug(proc.stdout) except subprocess.CalledProcessError as cpe:",
"with open(os.path.join(self.base_dir, qt_version, arch_dir, 'bin', 'qt.conf'), 'w') as f: f.write(\"[Paths]\\n\")",
"self.qt_archives.get_archives()] done, not_done = concurrent.futures.wait(futures, return_when=concurrent.futures.FIRST_EXCEPTION) if len(not_done) > 0:",
"# Copyright (C) 2019,2020 <NAME> <<EMAIL>> # Copyright (C) 2020,",
"OR IN # CONNECTION WITH THE SOFTWARE OR THE USE",
"target_dir self.settings = Settings() def retrieve_archive(self, package: QtPackage): archive =",
"retrieve_archive(self, package: QtPackage): archive = package.archive url = package.url name",
"as f: f.write(\"[Paths]\\n\") f.write(\"Prefix=..\\n\") # update qtconfig.pri only as OpenSource",
"szf = py7zr.SevenZipFile(archive) szf.extractall(path=self.base_dir) szf.close() def extract_archive_ext(self, archive): if self.base_dir",
"pathlib import subprocess import sys import time from logging import",
"= subprocess.run(command_args, stdout=subprocess.PIPE, check=True) self.logger.debug(proc.stdout) except subprocess.CalledProcessError as cpe: self.logger.error(\"Extraction",
"self.logger.error(\"Configuration file generation error: %s\\n\", e.args, exc_info=True) raise e def",
"do so, # subject to the following conditions: # #",
"f.truncate() for line in lines: if line.startswith('QT_EDITION ='): line =",
"deal in # the Software without restriction, including without limitation",
"self.command = command if target_dir is None: self.base_dir = os.getcwd()",
"subprocess.run(command_args, stdout=subprocess.PIPE, check=True) self.logger.debug(proc.stdout) except subprocess.CalledProcessError as cpe: self.logger.error(\"Extraction error:",
"r = session.get(newurl, stream=True) except requests.exceptions.ConnectionError as e: self.logger.error(\"Connection error:",
"package.url name = package.name start_time = time.perf_counter() self.logger.info(\"Downloading {}...\".format(name)) self.logger.debug(\"Download",
"def extract_archive(self, archive): szf = py7zr.SevenZipFile(archive) szf.extractall(path=self.base_dir) szf.close() def extract_archive_ext(self,",
"if line.startswith('QT_LICHECK ='): line = 'QT_LICHECK =\\n' f.write(line) except IOError",
"import Updater from aqt.settings import Settings class ExtractionError(Exception): pass class",
"%d\" % cpe.returncode) if cpe.stdout is not None: self.logger.error(cpe.stdout) if",
"self.base_dir is not None: command_args = [self.command, 'x', '-aoa', '-bd',",
"update qtconfig.pri only as OpenSource with open(os.path.join(self.base_dir, qt_version, arch_dir, 'mkspecs',",
"distribute, sublicense, and/or sell copies of # the Software, and",
"from aqt.settings import Settings class ExtractionError(Exception): pass class QtInstaller: \"\"\"",
"FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER # IN",
"if self.command is None: with open(archive, 'rb') as fd: self.extract_archive(fd)",
"self.logger.error(\"Connection error: %s\" % e.args) raise e else: try: with",
"python3 # # Copyright (C) 2018 <NAME> <<EMAIL>> # Copyright",
"ARISING FROM, OUT OF OR IN # CONNECTION WITH THE",
"portions of the Software. # # THE SOFTWARE IS PROVIDED",
"% cpe.returncode) if cpe.stdout is not None: self.logger.error(cpe.stdout) if cpe.stderr",
"self.logger.debug(\"Download URL: {}\".format(url)) session = requests.Session() retry = Retry(connect=5, backoff_factor=0.5)",
"SOFTWARE. import concurrent.futures import os import pathlib import subprocess import",
"from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry from aqt.archives",
"arch[6:] + '_64' elif arch.startswith('win32_mingw'): arch_dir = arch[6:] + '_32'",
"# prepare qt.conf with open(os.path.join(self.base_dir, qt_version, arch_dir, 'bin', 'qt.conf'), 'w')",
"<<EMAIL>> # Copyright (C) 2019,2020 <NAME> <<EMAIL>> # Copyright (C)",
"import Retry from aqt.archives import QtPackage from aqt.helper import altlink,",
"requests.exceptions.ConnectionError as e: self.logger.error(\"Connection error: %s\" % e.args) raise e",
"# # The above copyright notice and this permission notice",
"TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR",
"DAMAGES OR OTHER LIABILITY, WHETHER # IN AN ACTION OF",
"URL: {}\".format(url)) session = requests.Session() retry = Retry(connect=5, backoff_factor=0.5) adapter",
"arch_dir def make_conf_files(self, qt_version, arch): \"\"\"Make Qt configuration files, qt.conf",
"as executor: futures = [executor.submit(self.retrieve_archive, ar) for ar in self.qt_archives.get_archives()]",
"Copyright (C) 2019,2020 <NAME> <<EMAIL>> # Copyright (C) 2020, <NAME>",
"requests.Session() retry = Retry(connect=5, backoff_factor=0.5) adapter = HTTPAdapter(max_retries=retry) session.mount('http://', adapter)",
"'QT_LICHECK =\\n' f.write(line) except IOError as e: self.logger.error(\"Configuration file generation",
"error detected.\") exit(1) try: for feature in done: feature.result() except",
"szf.close() def extract_archive_ext(self, archive): if self.base_dir is not None: command_args",
"arch_dir = arch[6:] else: arch_dir = arch return arch_dir def",
"f.write(\"[Paths]\\n\") f.write(\"Prefix=..\\n\") # update qtconfig.pri only as OpenSource with open(os.path.join(self.base_dir,",
"get_arch_dir(self, arch): if arch.startswith('win64_mingw'): arch_dir = arch[6:] + '_64' elif",
"error: %s\" % exc[1]) raise e else: if self.command is",
"limitation the rights to # use, copy, modify, merge, publish,",
"the rights to # use, copy, modify, merge, publish, distribute,",
"[self.command, 'x', '-aoa', '-bd', '-y', '-o{}'.format(self.base_dir), archive] else: command_args =",
"# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR",
"hereby granted, free of charge, to any person obtaining a",
"='): line = 'QT_EDITION = OpenSource\\n' if line.startswith('QT_LICHECK ='): line",
"this permission notice shall be included in all # copies",
"qt.conf with open(os.path.join(self.base_dir, qt_version, arch_dir, 'bin', 'qt.conf'), 'w') as f:",
"py7zr.SevenZipFile(archive) szf.extractall(path=self.base_dir) szf.close() def extract_archive_ext(self, archive): if self.base_dir is not",
"'w') as f: f.write(\"[Paths]\\n\") f.write(\"Prefix=..\\n\") # update qtconfig.pri only as",
"self.logger.error(cpe.stdout) if cpe.stderr is not None: self.logger.error(cpe.stderr) raise cpe def",
"ar) for ar in self.qt_archives.get_archives()] done, not_done = concurrent.futures.wait(futures, return_when=concurrent.futures.FIRST_EXCEPTION)",
"as fd: for chunk in r.iter_content(chunk_size=8196): fd.write(chunk) fd.flush() if self.command",
"class QtInstaller: \"\"\" Installer class to download packages and extract",
"ExtractionError(Exception): pass class QtInstaller: \"\"\" Installer class to download packages",
"else: command_args = [self.command, 'x', '-aoa', '-bd', '-y', archive] try:",
"'-bd', '-y', archive] try: proc = subprocess.run(command_args, stdout=subprocess.PIPE, check=True) self.logger.debug(proc.stdout)",
"concurrent.futures.ThreadPoolExecutor(self.settings.concurrency) as executor: futures = [executor.submit(self.retrieve_archive, ar) for ar in",
"if logging: self.logger = logging else: self.logger = getLogger('aqt') self.command",
"= arch[6:] else: arch_dir = arch return arch_dir def make_conf_files(self,",
"== 302: newurl = altlink(r.url, r.headers['Location'], logger=self.logger) self.logger.info('Redirected URL: {}'.format(newurl))",
"f.write(line) except IOError as e: self.logger.error(\"Configuration file generation error: %s\\n\",",
"HTTPAdapter from urllib3.util.retry import Retry from aqt.archives import QtPackage from",
"{}...\".format(name)) self.logger.debug(\"Download URL: {}\".format(url)) session = requests.Session() retry = Retry(connect=5,",
"requests from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry from",
"'-bd', '-y', '-o{}'.format(self.base_dir), archive] else: command_args = [self.command, 'x', '-aoa',",
"error: %s\\n\", e.args, exc_info=True) raise e def install(self): with concurrent.futures.ThreadPoolExecutor(self.settings.concurrency)",
"arch.startswith('win64_mingw'): arch_dir = arch[6:] + '_64' elif arch.startswith('win32_mingw'): arch_dir =",
"arch): if arch.startswith('win64_mingw'): arch_dir = arch[6:] + '_64' elif arch.startswith('win32_mingw'):",
"Updater from aqt.settings import Settings class ExtractionError(Exception): pass class QtInstaller:",
"documentation files (the \"Software\"), to deal in # the Software",
"self.get_arch_dir(arch) try: # prepare qt.conf with open(os.path.join(self.base_dir, qt_version, arch_dir, 'bin',",
"logger=self.logger) self.logger.info('Redirected URL: {}'.format(newurl)) r = session.get(newurl, stream=True) except requests.exceptions.ConnectionError",
"including without limitation the rights to # use, copy, modify,",
"= [self.command, 'x', '-aoa', '-bd', '-y', '-o{}'.format(self.base_dir), archive] else: command_args",
"persons to whom the Software is furnished to do so,",
"cpe.returncode) if cpe.stdout is not None: self.logger.error(cpe.stdout) if cpe.stderr is",
"class to download packages and extract it. \"\"\" def __init__(self,",
"be included in all # copies or substantial portions of",
"OpenSource with open(os.path.join(self.base_dir, qt_version, arch_dir, 'mkspecs', 'qconfig.pri'), 'r+') as f:",
"the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\",",
"= 'QT_LICHECK =\\n' f.write(line) except IOError as e: self.logger.error(\"Configuration file",
"except Exception: exit(1) def finalize(self): target = self.qt_archives.get_target_config() self.make_conf_files(target.version, target.arch)",
"exit(1) def finalize(self): target = self.qt_archives.get_target_config() self.make_conf_files(target.version, target.arch) prefix =",
"aqt.qtpatch import Updater from aqt.settings import Settings class ExtractionError(Exception): pass",
"(C) 2018 <NAME> <<EMAIL>> # Copyright (C) 2019,2020 <NAME> <<EMAIL>>",
"# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING",
"in lines: if line.startswith('QT_EDITION ='): line = 'QT_EDITION = OpenSource\\n'",
"= Settings() def retrieve_archive(self, package: QtPackage): archive = package.archive url",
"to do so, # subject to the following conditions: #",
"2019,2020 <NAME> <<EMAIL>> # Copyright (C) 2020, <NAME> # #",
"Software without restriction, including without limitation the rights to #",
"Retry(connect=5, backoff_factor=0.5) adapter = HTTPAdapter(max_retries=retry) session.mount('http://', adapter) session.mount('https://', adapter) try:",
"copy of # this software and associated documentation files (the",
"self.logger.error(\"Download error: %s\" % exc[1]) raise e else: if self.command",
"is not None: self.logger.error(cpe.stderr) raise cpe def get_arch_dir(self, arch): if",
"open(archive, 'rb') as fd: self.extract_archive(fd) except Exception as e: exc",
"as cpe: self.logger.error(\"Extraction error: %d\" % cpe.returncode) if cpe.stdout is",
"None: self.base_dir = os.getcwd() else: self.base_dir = target_dir self.settings =",
"# # Copyright (C) 2018 <NAME> <<EMAIL>> # Copyright (C)",
"OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR",
"IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS",
"self.logger.error(\"Installation error detected.\") exit(1) try: for feature in done: feature.result()",
"a copy of # this software and associated documentation files",
"self.logger.debug(proc.stdout) except subprocess.CalledProcessError as cpe: self.logger.error(\"Extraction error: %d\" % cpe.returncode)",
"# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF",
"as OpenSource with open(os.path.join(self.base_dir, qt_version, arch_dir, 'mkspecs', 'qconfig.pri'), 'r+') as",
"if self.command is not None: self.extract_archive_ext(archive) os.unlink(archive) self.logger.info(\"Finish installation of",
"# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF",
"OTHER LIABILITY, WHETHER # IN AN ACTION OF CONTRACT, TORT",
"class ExtractionError(Exception): pass class QtInstaller: \"\"\" Installer class to download",
"\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #",
"from urllib3.util.retry import Retry from aqt.archives import QtPackage from aqt.helper",
"{}\".format(url)) session = requests.Session() retry = Retry(connect=5, backoff_factor=0.5) adapter =",
"'qconfig.pri'), 'r+') as f: lines = f.readlines() f.seek(0) f.truncate() for",
"# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER",
"configuration files, qt.conf and qtconfig.pri\"\"\" arch_dir = self.get_arch_dir(arch) try: #",
"feature in done: feature.result() except Exception: exit(1) def finalize(self): target",
"so, # subject to the following conditions: # # The",
"LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A",
"self.make_conf_files(target.version, target.arch) prefix = pathlib.Path(self.base_dir) / target.version / target.arch updater",
"copy, modify, merge, publish, distribute, sublicense, and/or sell copies of",
"of {} in {}\".format(archive, time.perf_counter() - start_time)) def extract_archive(self, archive):",
"qt_archives if logging: self.logger = logging else: self.logger = getLogger('aqt')",
"included in all # copies or substantial portions of the",
"/ target.arch updater = Updater(prefix, self.logger) if versiontuple(target.version) < (5,",
"# The above copyright notice and this permission notice shall",
"try: with open(archive, 'wb') as fd: for chunk in r.iter_content(chunk_size=8196):",
"TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN #",
"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER #",
"without restriction, including without limitation the rights to # use,",
"qtconfig.pri\"\"\" arch_dir = self.get_arch_dir(arch) try: # prepare qt.conf with open(os.path.join(self.base_dir,",
"else: self.logger = getLogger('aqt') self.command = command if target_dir is",
"for line in lines: if line.startswith('QT_EDITION ='): line = 'QT_EDITION",
"{}'.format(newurl)) r = session.get(newurl, stream=True) except requests.exceptions.ConnectionError as e: self.logger.error(\"Connection",
"self.settings = Settings() def retrieve_archive(self, package: QtPackage): archive = package.archive",
"furnished to do so, # subject to the following conditions:",
"permission notice shall be included in all # copies or",
"and extract it. \"\"\" def __init__(self, qt_archives, logging=None, command=None, target_dir=None):",
"not None: command_args = [self.command, 'x', '-aoa', '-bd', '-y', '-o{}'.format(self.base_dir),",
"r.iter_content(chunk_size=8196): fd.write(chunk) fd.flush() if self.command is None: with open(archive, 'rb')",
"import py7zr import requests from requests.adapters import HTTPAdapter from urllib3.util.retry",
"try: for feature in done: feature.result() except Exception: exit(1) def",
"IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS",
"OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES",
"aqt.helper import altlink, versiontuple from aqt.qtpatch import Updater from aqt.settings",
"download packages and extract it. \"\"\" def __init__(self, qt_archives, logging=None,",
"raise e def install(self): with concurrent.futures.ThreadPoolExecutor(self.settings.concurrency) as executor: futures =",
"# subject to the following conditions: # # The above",
"def finalize(self): target = self.qt_archives.get_target_config() self.make_conf_files(target.version, target.arch) prefix = pathlib.Path(self.base_dir)",
"= Retry(connect=5, backoff_factor=0.5) adapter = HTTPAdapter(max_retries=retry) session.mount('http://', adapter) session.mount('https://', adapter)",
"time.perf_counter() - start_time)) def extract_archive(self, archive): szf = py7zr.SevenZipFile(archive) szf.extractall(path=self.base_dir)",
"import HTTPAdapter from urllib3.util.retry import Retry from aqt.archives import QtPackage",
"'-aoa', '-bd', '-y', archive] try: proc = subprocess.run(command_args, stdout=subprocess.PIPE, check=True)",
"following conditions: # # The above copyright notice and this",
"self.qt_archives = qt_archives if logging: self.logger = logging else: self.logger",
"OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH",
"QtInstaller: \"\"\" Installer class to download packages and extract it.",
"rights to # use, copy, modify, merge, publish, distribute, sublicense,",
"conditions: # # The above copyright notice and this permission",
"> 0: self.logger.error(\"Installation error detected.\") exit(1) try: for feature in",
"pass class QtInstaller: \"\"\" Installer class to download packages and",
"from aqt.helper import altlink, versiontuple from aqt.qtpatch import Updater from",
"command if target_dir is None: self.base_dir = os.getcwd() else: self.base_dir",
"szf.extractall(path=self.base_dir) szf.close() def extract_archive_ext(self, archive): if self.base_dir is not None:",
"qt.conf and qtconfig.pri\"\"\" arch_dir = self.get_arch_dir(arch) try: # prepare qt.conf",
"start_time = time.perf_counter() self.logger.info(\"Downloading {}...\".format(name)) self.logger.debug(\"Download URL: {}\".format(url)) session =",
"arch_dir = arch return arch_dir def make_conf_files(self, qt_version, arch): \"\"\"Make",
"except subprocess.CalledProcessError as cpe: self.logger.error(\"Extraction error: %d\" % cpe.returncode) if",
"files (the \"Software\"), to deal in # the Software without",
"command=None, target_dir=None): self.qt_archives = qt_archives if logging: self.logger = logging",
"= 'QT_EDITION = OpenSource\\n' if line.startswith('QT_LICHECK ='): line = 'QT_LICHECK",
"= requests.Session() retry = Retry(connect=5, backoff_factor=0.5) adapter = HTTPAdapter(max_retries=retry) session.mount('http://',",
"f.seek(0) f.truncate() for line in lines: if line.startswith('QT_EDITION ='): line",
"e: self.logger.error(\"Connection error: %s\" % e.args) raise e else: try:",
"cpe: self.logger.error(\"Extraction error: %d\" % cpe.returncode) if cpe.stdout is not",
"OTHER DEALINGS IN THE SOFTWARE. import concurrent.futures import os import",
"urllib3.util.retry import Retry from aqt.archives import QtPackage from aqt.helper import",
"ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF",
"it. \"\"\" def __init__(self, qt_archives, logging=None, command=None, target_dir=None): self.qt_archives =",
"= concurrent.futures.wait(futures, return_when=concurrent.futures.FIRST_EXCEPTION) if len(not_done) > 0: self.logger.error(\"Installation error detected.\")",
"error: %s\" % e.args) raise e else: try: with open(archive,",
"<<EMAIL>> # Copyright (C) 2020, <NAME> # # Permission is",
"generation error: %s\\n\", e.args, exc_info=True) raise e def install(self): with",
"all # copies or substantial portions of the Software. #",
"stdout=subprocess.PIPE, check=True) self.logger.debug(proc.stdout) except subprocess.CalledProcessError as cpe: self.logger.error(\"Extraction error: %d\"",
"logging: self.logger = logging else: self.logger = getLogger('aqt') self.command =",
"software and associated documentation files (the \"Software\"), to deal in",
"whom the Software is furnished to do so, # subject",
"extract_archive(self, archive): szf = py7zr.SevenZipFile(archive) szf.extractall(path=self.base_dir) szf.close() def extract_archive_ext(self, archive):",
"with open(archive, 'wb') as fd: for chunk in r.iter_content(chunk_size=8196): fd.write(chunk)",
"stream=True) except requests.exceptions.ConnectionError as e: self.logger.error(\"Connection error: %s\" % e.args)",
"# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT",
"Exception as e: exc = sys.exc_info() self.logger.error(\"Download error: %s\" %",
"notice and this permission notice shall be included in all",
"def make_conf_files(self, qt_version, arch): \"\"\"Make Qt configuration files, qt.conf and",
"is hereby granted, free of charge, to any person obtaining",
"Settings() def retrieve_archive(self, package: QtPackage): archive = package.archive url =",
"to download packages and extract it. \"\"\" def __init__(self, qt_archives,",
"exc = sys.exc_info() self.logger.error(\"Download error: %s\" % exc[1]) raise e",
"= py7zr.SevenZipFile(archive) szf.extractall(path=self.base_dir) szf.close() def extract_archive_ext(self, archive): if self.base_dir is",
"arch[6:] else: arch_dir = arch return arch_dir def make_conf_files(self, qt_version,",
"= pathlib.Path(self.base_dir) / target.version / target.arch updater = Updater(prefix, self.logger)",
"fd.write(chunk) fd.flush() if self.command is None: with open(archive, 'rb') as",
"is None: with open(archive, 'rb') as fd: self.extract_archive(fd) except Exception",
"the Software without restriction, including without limitation the rights to",
"# # Permission is hereby granted, free of charge, to",
"OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION",
"exc[1]) raise e else: if self.command is not None: self.extract_archive_ext(archive)",
"and/or sell copies of # the Software, and to permit",
"subject to the following conditions: # # The above copyright",
"e: exc = sys.exc_info() self.logger.error(\"Download error: %s\" % exc[1]) raise",
"permit persons to whom the Software is furnished to do",
"not_done = concurrent.futures.wait(futures, return_when=concurrent.futures.FIRST_EXCEPTION) if len(not_done) > 0: self.logger.error(\"Installation error",
"archive] try: proc = subprocess.run(command_args, stdout=subprocess.PIPE, check=True) self.logger.debug(proc.stdout) except subprocess.CalledProcessError",
"feature.result() except Exception: exit(1) def finalize(self): target = self.qt_archives.get_target_config() self.make_conf_files(target.version,",
"to whom the Software is furnished to do so, #",
"of # the Software, and to permit persons to whom",
"as fd: self.extract_archive(fd) except Exception as e: exc = sys.exc_info()",
"return arch_dir def make_conf_files(self, qt_version, arch): \"\"\"Make Qt configuration files,",
"(C) 2020, <NAME> # # Permission is hereby granted, free",
"sell copies of # the Software, and to permit persons",
"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN",
"chunk in r.iter_content(chunk_size=8196): fd.write(chunk) fd.flush() if self.command is None: with",
"Software is furnished to do so, # subject to the",
"= qt_archives if logging: self.logger = logging else: self.logger =",
"qt_version, arch_dir, 'bin', 'qt.conf'), 'w') as f: f.write(\"[Paths]\\n\") f.write(\"Prefix=..\\n\") #",
"IN # CONNECTION WITH THE SOFTWARE OR THE USE OR",
"QtPackage from aqt.helper import altlink, versiontuple from aqt.qtpatch import Updater",
"THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE",
"[executor.submit(self.retrieve_archive, ar) for ar in self.qt_archives.get_archives()] done, not_done = concurrent.futures.wait(futures,",
"OR OTHER LIABILITY, WHETHER # IN AN ACTION OF CONTRACT,",
"target.arch) prefix = pathlib.Path(self.base_dir) / target.version / target.arch updater =",
"session.mount('http://', adapter) session.mount('https://', adapter) try: r = session.get(url, allow_redirects=False, stream=True)",
"backoff_factor=0.5) adapter = HTTPAdapter(max_retries=retry) session.mount('http://', adapter) session.mount('https://', adapter) try: r",
"BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS #",
"or substantial portions of the Software. # # THE SOFTWARE",
"archive): if self.base_dir is not None: command_args = [self.command, 'x',",
"FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL",
"is not None: self.logger.error(cpe.stdout) if cpe.stderr is not None: self.logger.error(cpe.stderr)",
"py7zr import requests from requests.adapters import HTTPAdapter from urllib3.util.retry import",
"url = package.url name = package.name start_time = time.perf_counter() self.logger.info(\"Downloading",
"arch.startswith('win32_mingw'): arch_dir = arch[6:] + '_32' elif arch.startswith('win'): arch_dir =",
"= arch return arch_dir def make_conf_files(self, qt_version, arch): \"\"\"Make Qt",
"Installer class to download packages and extract it. \"\"\" def",
"THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY",
"\"Software\"), to deal in # the Software without restriction, including",
"'r+') as f: lines = f.readlines() f.seek(0) f.truncate() for line",
"%s\\n\", e.args, exc_info=True) raise e def install(self): with concurrent.futures.ThreadPoolExecutor(self.settings.concurrency) as",
"= OpenSource\\n' if line.startswith('QT_LICHECK ='): line = 'QT_LICHECK =\\n' f.write(line)",
"CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS",
"WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND",
"if r.status_code == 302: newurl = altlink(r.url, r.headers['Location'], logger=self.logger) self.logger.info('Redirected",
"command_args = [self.command, 'x', '-aoa', '-bd', '-y', archive] try: proc",
"packages and extract it. \"\"\" def __init__(self, qt_archives, logging=None, command=None,",
"getLogger('aqt') self.command = command if target_dir is None: self.base_dir =",
"'rb') as fd: self.extract_archive(fd) except Exception as e: exc =",
"target.version / target.arch updater = Updater(prefix, self.logger) if versiontuple(target.version) <",
"# Permission is hereby granted, free of charge, to any",
"self.command is None: with open(archive, 'rb') as fd: self.extract_archive(fd) except",
"cpe def get_arch_dir(self, arch): if arch.startswith('win64_mingw'): arch_dir = arch[6:] +",
"elif arch.startswith('win'): arch_dir = arch[6:] else: arch_dir = arch return",
"for feature in done: feature.result() except Exception: exit(1) def finalize(self):",
"# # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY",
"executor: futures = [executor.submit(self.retrieve_archive, ar) for ar in self.qt_archives.get_archives()] done,",
"return_when=concurrent.futures.FIRST_EXCEPTION) if len(not_done) > 0: self.logger.error(\"Installation error detected.\") exit(1) try:",
"else: try: with open(archive, 'wb') as fd: for chunk in",
"check=True) self.logger.debug(proc.stdout) except subprocess.CalledProcessError as cpe: self.logger.error(\"Extraction error: %d\" %",
"'QT_EDITION = OpenSource\\n' if line.startswith('QT_LICHECK ='): line = 'QT_LICHECK =\\n'",
"= package.name start_time = time.perf_counter() self.logger.info(\"Downloading {}...\".format(name)) self.logger.debug(\"Download URL: {}\".format(url))",
"try: r = session.get(url, allow_redirects=False, stream=True) if r.status_code == 302:",
"<NAME> <<EMAIL>> # Copyright (C) 2020, <NAME> # # Permission",
"retry = Retry(connect=5, backoff_factor=0.5) adapter = HTTPAdapter(max_retries=retry) session.mount('http://', adapter) session.mount('https://',",
"2018 <NAME> <<EMAIL>> # Copyright (C) 2019,2020 <NAME> <<EMAIL>> #",
"to any person obtaining a copy of # this software",
"self.logger = logging else: self.logger = getLogger('aqt') self.command = command",
"open(archive, 'wb') as fd: for chunk in r.iter_content(chunk_size=8196): fd.write(chunk) fd.flush()",
"to permit persons to whom the Software is furnished to",
"package.archive url = package.url name = package.name start_time = time.perf_counter()",
"not None: self.logger.error(cpe.stderr) raise cpe def get_arch_dir(self, arch): if arch.startswith('win64_mingw'):",
"aqt.settings import Settings class ExtractionError(Exception): pass class QtInstaller: \"\"\" Installer",
"raise e else: try: with open(archive, 'wb') as fd: for",
"None: command_args = [self.command, 'x', '-aoa', '-bd', '-y', '-o{}'.format(self.base_dir), archive]",
"= HTTPAdapter(max_retries=retry) session.mount('http://', adapter) session.mount('https://', adapter) try: r = session.get(url,",
"def get_arch_dir(self, arch): if arch.startswith('win64_mingw'): arch_dir = arch[6:] + '_64'",
"adapter) try: r = session.get(url, allow_redirects=False, stream=True) if r.status_code ==",
"{} in {}\".format(archive, time.perf_counter() - start_time)) def extract_archive(self, archive): szf",
"\"\"\" Installer class to download packages and extract it. \"\"\"",
"package: QtPackage): archive = package.archive url = package.url name =",
"= session.get(url, allow_redirects=False, stream=True) if r.status_code == 302: newurl =",
"self.command is not None: self.extract_archive_ext(archive) os.unlink(archive) self.logger.info(\"Finish installation of {}",
"for chunk in r.iter_content(chunk_size=8196): fd.write(chunk) fd.flush() if self.command is None:",
"AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,",
"raise cpe def get_arch_dir(self, arch): if arch.startswith('win64_mingw'): arch_dir = arch[6:]",
"'-y', '-o{}'.format(self.base_dir), archive] else: command_args = [self.command, 'x', '-aoa', '-bd',",
"= os.getcwd() else: self.base_dir = target_dir self.settings = Settings() def",
"self.extract_archive(fd) except Exception as e: exc = sys.exc_info() self.logger.error(\"Download error:",
"make_conf_files(self, qt_version, arch): \"\"\"Make Qt configuration files, qt.conf and qtconfig.pri\"\"\"",
"import Settings class ExtractionError(Exception): pass class QtInstaller: \"\"\" Installer class",
"versiontuple from aqt.qtpatch import Updater from aqt.settings import Settings class",
"in done: feature.result() except Exception: exit(1) def finalize(self): target =",
"the following conditions: # # The above copyright notice and",
"r.headers['Location'], logger=self.logger) self.logger.info('Redirected URL: {}'.format(newurl)) r = session.get(newurl, stream=True) except",
"% e.args) raise e else: try: with open(archive, 'wb') as",
"in # the Software without restriction, including without limitation the",
"try: # prepare qt.conf with open(os.path.join(self.base_dir, qt_version, arch_dir, 'bin', 'qt.conf'),",
"arch_dir, 'bin', 'qt.conf'), 'w') as f: f.write(\"[Paths]\\n\") f.write(\"Prefix=..\\n\") # update",
"PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR",
"logging import getLogger import py7zr import requests from requests.adapters import",
"if target_dir is None: self.base_dir = os.getcwd() else: self.base_dir =",
"aqt.archives import QtPackage from aqt.helper import altlink, versiontuple from aqt.qtpatch",
"extract_archive_ext(self, archive): if self.base_dir is not None: command_args = [self.command,",
"+ '_32' elif arch.startswith('win'): arch_dir = arch[6:] else: arch_dir =",
"is not None: self.extract_archive_ext(archive) os.unlink(archive) self.logger.info(\"Finish installation of {} in",
"f.readlines() f.seek(0) f.truncate() for line in lines: if line.startswith('QT_EDITION ='):",
"detected.\") exit(1) try: for feature in done: feature.result() except Exception:",
"obtaining a copy of # this software and associated documentation",
"exc_info=True) raise e def install(self): with concurrent.futures.ThreadPoolExecutor(self.settings.concurrency) as executor: futures",
"stream=True) if r.status_code == 302: newurl = altlink(r.url, r.headers['Location'], logger=self.logger)",
"archive] else: command_args = [self.command, 'x', '-aoa', '-bd', '-y', archive]",
"any person obtaining a copy of # this software and",
"the Software, and to permit persons to whom the Software",
"'-y', archive] try: proc = subprocess.run(command_args, stdout=subprocess.PIPE, check=True) self.logger.debug(proc.stdout) except",
"sys.exc_info() self.logger.error(\"Download error: %s\" % exc[1]) raise e else: if",
"session.get(url, allow_redirects=False, stream=True) if r.status_code == 302: newurl = altlink(r.url,",
"= self.qt_archives.get_target_config() self.make_conf_files(target.version, target.arch) prefix = pathlib.Path(self.base_dir) / target.version /",
"Exception: exit(1) def finalize(self): target = self.qt_archives.get_target_config() self.make_conf_files(target.version, target.arch) prefix",
"import os import pathlib import subprocess import sys import time",
"futures = [executor.submit(self.retrieve_archive, ar) for ar in self.qt_archives.get_archives()] done, not_done",
"#!/usr/bin/env python3 # # Copyright (C) 2018 <NAME> <<EMAIL>> #",
"else: self.base_dir = target_dir self.settings = Settings() def retrieve_archive(self, package:",
"self.logger.info(\"Downloading {}...\".format(name)) self.logger.debug(\"Download URL: {}\".format(url)) session = requests.Session() retry =",
"='): line = 'QT_LICHECK =\\n' f.write(line) except IOError as e:",
"and associated documentation files (the \"Software\"), to deal in #",
"def extract_archive_ext(self, archive): if self.base_dir is not None: command_args =",
"file generation error: %s\\n\", e.args, exc_info=True) raise e def install(self):",
"if self.base_dir is not None: command_args = [self.command, 'x', '-aoa',",
"'wb') as fd: for chunk in r.iter_content(chunk_size=8196): fd.write(chunk) fd.flush() if",
"Settings class ExtractionError(Exception): pass class QtInstaller: \"\"\" Installer class to",
"except Exception as e: exc = sys.exc_info() self.logger.error(\"Download error: %s\"",
"% exc[1]) raise e else: if self.command is not None:",
"if cpe.stderr is not None: self.logger.error(cpe.stderr) raise cpe def get_arch_dir(self,",
"line = 'QT_LICHECK =\\n' f.write(line) except IOError as e: self.logger.error(\"Configuration",
"fd.flush() if self.command is None: with open(archive, 'rb') as fd:",
"# Copyright (C) 2018 <NAME> <<EMAIL>> # Copyright (C) 2019,2020",
"package.name start_time = time.perf_counter() self.logger.info(\"Downloading {}...\".format(name)) self.logger.debug(\"Download URL: {}\".format(url)) session",
"arch[6:] + '_32' elif arch.startswith('win'): arch_dir = arch[6:] else: arch_dir",
"# update qtconfig.pri only as OpenSource with open(os.path.join(self.base_dir, qt_version, arch_dir,",
"extract it. \"\"\" def __init__(self, qt_archives, logging=None, command=None, target_dir=None): self.qt_archives",
"cpe.stderr is not None: self.logger.error(cpe.stderr) raise cpe def get_arch_dir(self, arch):",
"files, qt.conf and qtconfig.pri\"\"\" arch_dir = self.get_arch_dir(arch) try: # prepare",
"OpenSource\\n' if line.startswith('QT_LICHECK ='): line = 'QT_LICHECK =\\n' f.write(line) except",
"Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT",
"line in lines: if line.startswith('QT_EDITION ='): line = 'QT_EDITION =",
"archive = package.archive url = package.url name = package.name start_time",
"os.unlink(archive) self.logger.info(\"Finish installation of {} in {}\".format(archive, time.perf_counter() - start_time))",
"e.args, exc_info=True) raise e def install(self): with concurrent.futures.ThreadPoolExecutor(self.settings.concurrency) as executor:",
"e def install(self): with concurrent.futures.ThreadPoolExecutor(self.settings.concurrency) as executor: futures = [executor.submit(self.retrieve_archive,",
"None: self.logger.error(cpe.stderr) raise cpe def get_arch_dir(self, arch): if arch.startswith('win64_mingw'): arch_dir",
"f.write(\"Prefix=..\\n\") # update qtconfig.pri only as OpenSource with open(os.path.join(self.base_dir, qt_version,",
"in all # copies or substantial portions of the Software.",
"this software and associated documentation files (the \"Software\"), to deal",
"subprocess.CalledProcessError as cpe: self.logger.error(\"Extraction error: %d\" % cpe.returncode) if cpe.stdout",
"'mkspecs', 'qconfig.pri'), 'r+') as f: lines = f.readlines() f.seek(0) f.truncate()",
"= target_dir self.settings = Settings() def retrieve_archive(self, package: QtPackage): archive",
"r.status_code == 302: newurl = altlink(r.url, r.headers['Location'], logger=self.logger) self.logger.info('Redirected URL:",
"not None: self.logger.error(cpe.stdout) if cpe.stderr is not None: self.logger.error(cpe.stderr) raise",
"= command if target_dir is None: self.base_dir = os.getcwd() else:",
"= [self.command, 'x', '-aoa', '-bd', '-y', archive] try: proc =",
"subprocess import sys import time from logging import getLogger import",
"sys import time from logging import getLogger import py7zr import",
"shall be included in all # copies or substantial portions",
"(the \"Software\"), to deal in # the Software without restriction,",
"adapter = HTTPAdapter(max_retries=retry) session.mount('http://', adapter) session.mount('https://', adapter) try: r =",
"PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",
"= self.get_arch_dir(arch) try: # prepare qt.conf with open(os.path.join(self.base_dir, qt_version, arch_dir,",
"= [executor.submit(self.retrieve_archive, ar) for ar in self.qt_archives.get_archives()] done, not_done =",
"'_64' elif arch.startswith('win32_mingw'): arch_dir = arch[6:] + '_32' elif arch.startswith('win'):",
"self.base_dir = os.getcwd() else: self.base_dir = target_dir self.settings = Settings()",
"= logging else: self.logger = getLogger('aqt') self.command = command if",
"import subprocess import sys import time from logging import getLogger",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY",
"= arch[6:] + '_32' elif arch.startswith('win'): arch_dir = arch[6:] else:",
"substantial portions of the Software. # # THE SOFTWARE IS",
"notice shall be included in all # copies or substantial",
"os.getcwd() else: self.base_dir = target_dir self.settings = Settings() def retrieve_archive(self,",
"= package.archive url = package.url name = package.name start_time =",
"session.mount('https://', adapter) try: r = session.get(url, allow_redirects=False, stream=True) if r.status_code",
"2020, <NAME> # # Permission is hereby granted, free of",
"WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING",
"exit(1) try: for feature in done: feature.result() except Exception: exit(1)",
"= time.perf_counter() self.logger.info(\"Downloading {}...\".format(name)) self.logger.debug(\"Download URL: {}\".format(url)) session = requests.Session()",
"import altlink, versiontuple from aqt.qtpatch import Updater from aqt.settings import",
"len(not_done) > 0: self.logger.error(\"Installation error detected.\") exit(1) try: for feature",
"requests.adapters import HTTPAdapter from urllib3.util.retry import Retry from aqt.archives import",
"prefix = pathlib.Path(self.base_dir) / target.version / target.arch updater = Updater(prefix,",
"SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
"pathlib.Path(self.base_dir) / target.version / target.arch updater = Updater(prefix, self.logger) if",
"self.logger.error(cpe.stderr) raise cpe def get_arch_dir(self, arch): if arch.startswith('win64_mingw'): arch_dir =",
"BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER",
"e.args) raise e else: try: with open(archive, 'wb') as fd:",
"HTTPAdapter(max_retries=retry) session.mount('http://', adapter) session.mount('https://', adapter) try: r = session.get(url, allow_redirects=False,",
"KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO",
"of # this software and associated documentation files (the \"Software\"),",
"if cpe.stdout is not None: self.logger.error(cpe.stdout) if cpe.stderr is not",
"OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES",
"getLogger import py7zr import requests from requests.adapters import HTTPAdapter from",
"logging else: self.logger = getLogger('aqt') self.command = command if target_dir",
"prepare qt.conf with open(os.path.join(self.base_dir, qt_version, arch_dir, 'bin', 'qt.conf'), 'w') as",
"lines = f.readlines() f.seek(0) f.truncate() for line in lines: if",
"INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS",
"LIABILITY, WHETHER # IN AN ACTION OF CONTRACT, TORT OR",
"from aqt.qtpatch import Updater from aqt.settings import Settings class ExtractionError(Exception):",
"%s\" % exc[1]) raise e else: if self.command is not",
"self.logger = getLogger('aqt') self.command = command if target_dir is None:",
"HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,",
"line.startswith('QT_LICHECK ='): line = 'QT_LICHECK =\\n' f.write(line) except IOError as",
"Copyright (C) 2020, <NAME> # # Permission is hereby granted,",
"copyright notice and this permission notice shall be included in",
"from logging import getLogger import py7zr import requests from requests.adapters",
"os import pathlib import subprocess import sys import time from",
"and qtconfig.pri\"\"\" arch_dir = self.get_arch_dir(arch) try: # prepare qt.conf with",
"ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED",
"OR OTHER DEALINGS IN THE SOFTWARE. import concurrent.futures import os",
"=\\n' f.write(line) except IOError as e: self.logger.error(\"Configuration file generation error:",
"done: feature.result() except Exception: exit(1) def finalize(self): target = self.qt_archives.get_target_config()",
"import concurrent.futures import os import pathlib import subprocess import sys",
"target_dir=None): self.qt_archives = qt_archives if logging: self.logger = logging else:",
"and to permit persons to whom the Software is furnished",
"FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE",
"newurl = altlink(r.url, r.headers['Location'], logger=self.logger) self.logger.info('Redirected URL: {}'.format(newurl)) r =",
"to deal in # the Software without restriction, including without",
"only as OpenSource with open(os.path.join(self.base_dir, qt_version, arch_dir, 'mkspecs', 'qconfig.pri'), 'r+')",
"associated documentation files (the \"Software\"), to deal in # the",
"allow_redirects=False, stream=True) if r.status_code == 302: newurl = altlink(r.url, r.headers['Location'],",
"= getLogger('aqt') self.command = command if target_dir is None: self.base_dir",
"{}\".format(archive, time.perf_counter() - start_time)) def extract_archive(self, archive): szf = py7zr.SevenZipFile(archive)",
"<NAME> # # Permission is hereby granted, free of charge,",
"f: f.write(\"[Paths]\\n\") f.write(\"Prefix=..\\n\") # update qtconfig.pri only as OpenSource with",
"/ target.version / target.arch updater = Updater(prefix, self.logger) if versiontuple(target.version)",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",
"# Copyright (C) 2020, <NAME> # # Permission is hereby",
"altlink(r.url, r.headers['Location'], logger=self.logger) self.logger.info('Redirected URL: {}'.format(newurl)) r = session.get(newurl, stream=True)",
"with open(archive, 'rb') as fd: self.extract_archive(fd) except Exception as e:",
"None: self.logger.error(cpe.stdout) if cpe.stderr is not None: self.logger.error(cpe.stderr) raise cpe",
"restriction, including without limitation the rights to # use, copy,",
"of the Software. # # THE SOFTWARE IS PROVIDED \"AS",
"= session.get(newurl, stream=True) except requests.exceptions.ConnectionError as e: self.logger.error(\"Connection error: %s\"",
"in r.iter_content(chunk_size=8196): fd.write(chunk) fd.flush() if self.command is None: with open(archive,",
"if len(not_done) > 0: self.logger.error(\"Installation error detected.\") exit(1) try: for",
"OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import",
"- start_time)) def extract_archive(self, archive): szf = py7zr.SevenZipFile(archive) szf.extractall(path=self.base_dir) szf.close()",
"qtconfig.pri only as OpenSource with open(os.path.join(self.base_dir, qt_version, arch_dir, 'mkspecs', 'qconfig.pri'),",
"e: self.logger.error(\"Configuration file generation error: %s\\n\", e.args, exc_info=True) raise e",
"session.get(newurl, stream=True) except requests.exceptions.ConnectionError as e: self.logger.error(\"Connection error: %s\" %",
"+ '_64' elif arch.startswith('win32_mingw'): arch_dir = arch[6:] + '_32' elif",
"import getLogger import py7zr import requests from requests.adapters import HTTPAdapter",
"__init__(self, qt_archives, logging=None, command=None, target_dir=None): self.qt_archives = qt_archives if logging:",
"def retrieve_archive(self, package: QtPackage): archive = package.archive url = package.url",
"= sys.exc_info() self.logger.error(\"Download error: %s\" % exc[1]) raise e else:",
"e else: try: with open(archive, 'wb') as fd: for chunk",
"from aqt.archives import QtPackage from aqt.helper import altlink, versiontuple from",
"None: with open(archive, 'rb') as fd: self.extract_archive(fd) except Exception as",
"EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE",
"target = self.qt_archives.get_target_config() self.make_conf_files(target.version, target.arch) prefix = pathlib.Path(self.base_dir) / target.version",
"if line.startswith('QT_EDITION ='): line = 'QT_EDITION = OpenSource\\n' if line.startswith('QT_LICHECK",
"OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.",
"URL: {}'.format(newurl)) r = session.get(newurl, stream=True) except requests.exceptions.ConnectionError as e:",
"'bin', 'qt.conf'), 'w') as f: f.write(\"[Paths]\\n\") f.write(\"Prefix=..\\n\") # update qtconfig.pri",
"self.qt_archives.get_target_config() self.make_conf_files(target.version, target.arch) prefix = pathlib.Path(self.base_dir) / target.version / target.arch",
"without limitation the rights to # use, copy, modify, merge,",
"CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER # IN AN ACTION",
"arch_dir = self.get_arch_dir(arch) try: # prepare qt.conf with open(os.path.join(self.base_dir, qt_version,",
"in {}\".format(archive, time.perf_counter() - start_time)) def extract_archive(self, archive): szf =",
"copies of # the Software, and to permit persons to",
"'_32' elif arch.startswith('win'): arch_dir = arch[6:] else: arch_dir = arch",
"as e: self.logger.error(\"Connection error: %s\" % e.args) raise e else:",
"is not None: command_args = [self.command, 'x', '-aoa', '-bd', '-y',",
"import sys import time from logging import getLogger import py7zr",
"publish, distribute, sublicense, and/or sell copies of # the Software,",
"target.arch updater = Updater(prefix, self.logger) if versiontuple(target.version) < (5, 14,",
"CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN",
"raise e else: if self.command is not None: self.extract_archive_ext(archive) os.unlink(archive)",
"logging=None, command=None, target_dir=None): self.qt_archives = qt_archives if logging: self.logger =",
"= f.readlines() f.seek(0) f.truncate() for line in lines: if line.startswith('QT_EDITION",
"FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO",
"above copyright notice and this permission notice shall be included",
"IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED,",
"A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE",
"MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN",
"for ar in self.qt_archives.get_archives()] done, not_done = concurrent.futures.wait(futures, return_when=concurrent.futures.FIRST_EXCEPTION) if",
"to # use, copy, modify, merge, publish, distribute, sublicense, and/or",
"target_dir is None: self.base_dir = os.getcwd() else: self.base_dir = target_dir",
"is furnished to do so, # subject to the following",
"line.startswith('QT_EDITION ='): line = 'QT_EDITION = OpenSource\\n' if line.startswith('QT_LICHECK ='):",
"'-aoa', '-bd', '-y', '-o{}'.format(self.base_dir), archive] else: command_args = [self.command, 'x',",
"e else: if self.command is not None: self.extract_archive_ext(archive) os.unlink(archive) self.logger.info(\"Finish",
"# copies or substantial portions of the Software. # #",
"Copyright (C) 2018 <NAME> <<EMAIL>> # Copyright (C) 2019,2020 <NAME>",
"NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT",
"self.logger.info(\"Finish installation of {} in {}\".format(archive, time.perf_counter() - start_time)) def",
"copies or substantial portions of the Software. # # THE",
"finalize(self): target = self.qt_archives.get_target_config() self.make_conf_files(target.version, target.arch) prefix = pathlib.Path(self.base_dir) /",
"r = session.get(url, allow_redirects=False, stream=True) if r.status_code == 302: newurl",
"time from logging import getLogger import py7zr import requests from",
"%s\" % e.args) raise e else: try: with open(archive, 'wb')",
"as e: exc = sys.exc_info() self.logger.error(\"Download error: %s\" % exc[1])",
"line = 'QT_EDITION = OpenSource\\n' if line.startswith('QT_LICHECK ='): line =",
"self.base_dir = target_dir self.settings = Settings() def retrieve_archive(self, package: QtPackage):",
"archive): szf = py7zr.SevenZipFile(archive) szf.extractall(path=self.base_dir) szf.close() def extract_archive_ext(self, archive): if",
"except requests.exceptions.ConnectionError as e: self.logger.error(\"Connection error: %s\" % e.args) raise",
"OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT",
"open(os.path.join(self.base_dir, qt_version, arch_dir, 'mkspecs', 'qconfig.pri'), 'r+') as f: lines =",
"self.logger.info('Redirected URL: {}'.format(newurl)) r = session.get(newurl, stream=True) except requests.exceptions.ConnectionError as",
"self.extract_archive_ext(archive) os.unlink(archive) self.logger.info(\"Finish installation of {} in {}\".format(archive, time.perf_counter() -",
"concurrent.futures import os import pathlib import subprocess import sys import",
"qt_version, arch): \"\"\"Make Qt configuration files, qt.conf and qtconfig.pri\"\"\" arch_dir",
"arch): \"\"\"Make Qt configuration files, qt.conf and qtconfig.pri\"\"\" arch_dir =",
"Retry from aqt.archives import QtPackage from aqt.helper import altlink, versiontuple",
"DEALINGS IN THE SOFTWARE. import concurrent.futures import os import pathlib",
"= altlink(r.url, r.headers['Location'], logger=self.logger) self.logger.info('Redirected URL: {}'.format(newurl)) r = session.get(newurl,",
"'qt.conf'), 'w') as f: f.write(\"[Paths]\\n\") f.write(\"Prefix=..\\n\") # update qtconfig.pri only",
"to the following conditions: # # The above copyright notice",
"concurrent.futures.wait(futures, return_when=concurrent.futures.FIRST_EXCEPTION) if len(not_done) > 0: self.logger.error(\"Installation error detected.\") exit(1)",
"as f: lines = f.readlines() f.seek(0) f.truncate() for line in",
"QtPackage): archive = package.archive url = package.url name = package.name",
"AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT",
"adapter) session.mount('https://', adapter) try: r = session.get(url, allow_redirects=False, stream=True) if",
"open(os.path.join(self.base_dir, qt_version, arch_dir, 'bin', 'qt.conf'), 'w') as f: f.write(\"[Paths]\\n\") f.write(\"Prefix=..\\n\")",
"and this permission notice shall be included in all #",
"WHETHER # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,",
"THE SOFTWARE. import concurrent.futures import os import pathlib import subprocess",
"fd: for chunk in r.iter_content(chunk_size=8196): fd.write(chunk) fd.flush() if self.command is",
"except IOError as e: self.logger.error(\"Configuration file generation error: %s\\n\", e.args,",
"start_time)) def extract_archive(self, archive): szf = py7zr.SevenZipFile(archive) szf.extractall(path=self.base_dir) szf.close() def",
"arch_dir = arch[6:] + '_64' elif arch.startswith('win32_mingw'): arch_dir = arch[6:]",
"try: proc = subprocess.run(command_args, stdout=subprocess.PIPE, check=True) self.logger.debug(proc.stdout) except subprocess.CalledProcessError as",
"free of charge, to any person obtaining a copy of",
"NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR",
"SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR",
"not None: self.extract_archive_ext(archive) os.unlink(archive) self.logger.info(\"Finish installation of {} in {}\".format(archive,",
"IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
"charge, to any person obtaining a copy of # this",
"the Software is furnished to do so, # subject to",
"Software, and to permit persons to whom the Software is",
"def __init__(self, qt_archives, logging=None, command=None, target_dir=None): self.qt_archives = qt_archives if",
"SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.",
"USE OR OTHER DEALINGS IN THE SOFTWARE. import concurrent.futures import",
"qt_archives, logging=None, command=None, target_dir=None): self.qt_archives = qt_archives if logging: self.logger",
"is None: self.base_dir = os.getcwd() else: self.base_dir = target_dir self.settings",
"# this software and associated documentation files (the \"Software\"), to",
"THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE",
"IOError as e: self.logger.error(\"Configuration file generation error: %s\\n\", e.args, exc_info=True)",
"# use, copy, modify, merge, publish, distribute, sublicense, and/or sell",
"modify, merge, publish, distribute, sublicense, and/or sell copies of #",
"import requests from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry",
"arch.startswith('win'): arch_dir = arch[6:] else: arch_dir = arch return arch_dir",
"# the Software, and to permit persons to whom the",
"EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE",
"time.perf_counter() self.logger.info(\"Downloading {}...\".format(name)) self.logger.debug(\"Download URL: {}\".format(url)) session = requests.Session() retry",
"'-o{}'.format(self.base_dir), archive] else: command_args = [self.command, 'x', '-aoa', '-bd', '-y',",
"COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
"self.logger.error(\"Extraction error: %d\" % cpe.returncode) if cpe.stdout is not None:",
"[self.command, 'x', '-aoa', '-bd', '-y', archive] try: proc = subprocess.run(command_args,",
"Qt configuration files, qt.conf and qtconfig.pri\"\"\" arch_dir = self.get_arch_dir(arch) try:",
"as e: self.logger.error(\"Configuration file generation error: %s\\n\", e.args, exc_info=True) raise",
"arch return arch_dir def make_conf_files(self, qt_version, arch): \"\"\"Make Qt configuration",
"use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies",
"merge, publish, distribute, sublicense, and/or sell copies of # the",
"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR",
"None: self.extract_archive_ext(archive) os.unlink(archive) self.logger.info(\"Finish installation of {} in {}\".format(archive, time.perf_counter()",
"if arch.startswith('win64_mingw'): arch_dir = arch[6:] + '_64' elif arch.startswith('win32_mingw'): arch_dir",
"f: lines = f.readlines() f.seek(0) f.truncate() for line in lines:",
"arch_dir, 'mkspecs', 'qconfig.pri'), 'r+') as f: lines = f.readlines() f.seek(0)",
"NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE",
"granted, free of charge, to any person obtaining a copy",
"= package.url name = package.name start_time = time.perf_counter() self.logger.info(\"Downloading {}...\".format(name))",
"\"\"\" def __init__(self, qt_archives, logging=None, command=None, target_dir=None): self.qt_archives = qt_archives",
"302: newurl = altlink(r.url, r.headers['Location'], logger=self.logger) self.logger.info('Redirected URL: {}'.format(newurl)) r",
"OF OR IN # CONNECTION WITH THE SOFTWARE OR THE",
"# the Software without restriction, including without limitation the rights",
"PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS",
"def install(self): with concurrent.futures.ThreadPoolExecutor(self.settings.concurrency) as executor: futures = [executor.submit(self.retrieve_archive, ar)",
"Permission is hereby granted, free of charge, to any person",
"import QtPackage from aqt.helper import altlink, versiontuple from aqt.qtpatch import",
"0: self.logger.error(\"Installation error detected.\") exit(1) try: for feature in done:",
"AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR #",
"cpe.stdout is not None: self.logger.error(cpe.stdout) if cpe.stderr is not None:",
"else: arch_dir = arch return arch_dir def make_conf_files(self, qt_version, arch):",
"of charge, to any person obtaining a copy of #",
"with concurrent.futures.ThreadPoolExecutor(self.settings.concurrency) as executor: futures = [executor.submit(self.retrieve_archive, ar) for ar",
"The above copyright notice and this permission notice shall be",
"elif arch.startswith('win32_mingw'): arch_dir = arch[6:] + '_32' elif arch.startswith('win'): arch_dir",
"ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER # IN AN",
"installation of {} in {}\".format(archive, time.perf_counter() - start_time)) def extract_archive(self,",
"= arch[6:] + '_64' elif arch.startswith('win32_mingw'): arch_dir = arch[6:] +",
"arch_dir = arch[6:] + '_32' elif arch.startswith('win'): arch_dir = arch[6:]",
"with open(os.path.join(self.base_dir, qt_version, arch_dir, 'mkspecs', 'qconfig.pri'), 'r+') as f: lines",
"session = requests.Session() retry = Retry(connect=5, backoff_factor=0.5) adapter = HTTPAdapter(max_retries=retry)",
"qt_version, arch_dir, 'mkspecs', 'qconfig.pri'), 'r+') as f: lines = f.readlines()",
"sublicense, and/or sell copies of # the Software, and to",
"altlink, versiontuple from aqt.qtpatch import Updater from aqt.settings import Settings",
"fd: self.extract_archive(fd) except Exception as e: exc = sys.exc_info() self.logger.error(\"Download",
"import pathlib import subprocess import sys import time from logging",
"error: %d\" % cpe.returncode) if cpe.stdout is not None: self.logger.error(cpe.stdout)",
"WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT",
"else: if self.command is not None: self.extract_archive_ext(archive) os.unlink(archive) self.logger.info(\"Finish installation",
"'x', '-aoa', '-bd', '-y', archive] try: proc = subprocess.run(command_args, stdout=subprocess.PIPE,",
"\"\"\"Make Qt configuration files, qt.conf and qtconfig.pri\"\"\" arch_dir = self.get_arch_dir(arch)",
"install(self): with concurrent.futures.ThreadPoolExecutor(self.settings.concurrency) as executor: futures = [executor.submit(self.retrieve_archive, ar) for",
"person obtaining a copy of # this software and associated",
"import time from logging import getLogger import py7zr import requests",
"done, not_done = concurrent.futures.wait(futures, return_when=concurrent.futures.FIRST_EXCEPTION) if len(not_done) > 0: self.logger.error(\"Installation",
"<NAME> <<EMAIL>> # Copyright (C) 2019,2020 <NAME> <<EMAIL>> # Copyright",
"'x', '-aoa', '-bd', '-y', '-o{}'.format(self.base_dir), archive] else: command_args = [self.command,",
"= Updater(prefix, self.logger) if versiontuple(target.version) < (5, 14, 2): updater.patch_qt(target)",
"IN THE SOFTWARE. import concurrent.futures import os import pathlib import",
"THE USE OR OTHER DEALINGS IN THE SOFTWARE. import concurrent.futures",
"updater = Updater(prefix, self.logger) if versiontuple(target.version) < (5, 14, 2):"
] |
[
"the result number of the last of object in the",
"[] else: raise Http404 c = RequestContext(request, { '%s_list' %",
"else: c[key] = value response = HttpResponse(t.render(c), mimetype=mimetype) populate_xheaders(request, response,",
"django.http import Http404, HttpResponse from django.core.xheaders import populate_xheaders from django.core.paginator",
"% template_object_name: object_list, 'is_paginated': paginator.pages > 1, 'results_per_page': paginate_by, 'has_next':",
"t = template_loader.select_template(template_name_list) else: t = template_loader.get_template(template_name) c = RequestContext(request,",
"if callable(value): c[key] = value() else: c[key] = value response",
"paginate_by, 'has_next': paginator.has_next_page(page - 1), 'has_previous': paginator.has_previous_page(page - 1), 'page':",
"context_processors=None, template_object_name='object', mimetype=None): \"\"\" Generic detail of an object. Templates:",
"\"\"\" if extra_context is None: extra_context = {} queryset =",
"model._meta.object_name.lower()) t = template_loader.get_template(template_name) return HttpResponse(t.render(c), mimetype=mimetype) def object_detail(request, queryset,",
"last of object in the object_list (1-indexed) first_on_page the result",
"'%s_list' % template_object_name: object_list, 'is_paginated': paginator.pages > 1, 'results_per_page': paginate_by,",
"import ObjectPaginator, InvalidPage from django.core.exceptions import ObjectDoesNotExist def object_list(request, queryset,",
"AttributeError, \"Generic detail view must be called with either an",
"\"%s/%s_detail.html\" % (model._meta.app_label, model._meta.object_name.lower()) if template_name_field: template_name_list = [getattr(obj, template_name_field),",
"list of objects is_paginated are the results paginated? results_per_page number",
"object. Templates: ``<app_label>/<model_name>_detail.html`` Context: object the object \"\"\" if extra_context",
"page the current page next the next page previous the",
"template_name_list = [getattr(obj, template_name_field), template_name] t = template_loader.select_template(template_name_list) else: t",
"= request.GET.get('page', 1) try: page = int(page) object_list = paginator.get_page(page",
"= paginator.get_page(page - 1) except (InvalidPage, ValueError): if page ==",
"extra_context is None: extra_context = {} queryset = queryset._clone() if",
"extra_context = {} model = queryset.model if object_id: queryset =",
"extra_context is None: extra_context = {} model = queryset.model if",
"object_detail(request, queryset, object_id=None, slug=None, slug_field=None, template_name=None, template_name_field=None, template_loader=loader, extra_context=None, context_processors=None,",
"value() else: c[key] = value response = HttpResponse(t.render(c), mimetype=mimetype) populate_xheaders(request,",
"object_list list of objects is_paginated are the results paginated? results_per_page",
"page=None, allow_empty=False, template_name=None, template_loader=loader, extra_context=None, context_processors=None, template_object_name='object', mimetype=None): \"\"\" Generic",
"last_on_page the result number of the last of object in",
"the last of object in the object_list (1-indexed) first_on_page the",
"paginated) has_next is there a next page? has_previous is there",
"= RequestContext(request, { template_object_name: obj, }, context_processors) for key, value",
"pages, total hits number of objects, total last_on_page the result",
"object_id or a slug/slug_field.\" try: obj = queryset.get() except ObjectDoesNotExist:",
"page - 1, 'last_on_page': paginator.last_on_page(page - 1), 'first_on_page': paginator.first_on_page(page -",
"object_list, 'is_paginated': paginator.pages > 1, 'results_per_page': paginate_by, 'has_next': paginator.has_next_page(page -",
"not allow_empty and len(queryset) == 0: raise Http404 for key,",
"1), 'has_previous': paginator.has_previous_page(page - 1), 'page': page, 'next': page +",
"= \"%s/%s_detail.html\" % (model._meta.app_label, model._meta.object_name.lower()) if template_name_field: template_name_list = [getattr(obj,",
"{ template_object_name: obj, }, context_processors) for key, value in extra_context.items():",
"(1-indexed) first_on_page the result number of the first object in",
"number of pages, total hits number of objects, total last_on_page",
"1, 'last_on_page': paginator.last_on_page(page - 1), 'first_on_page': paginator.first_on_page(page - 1), 'pages':",
"page = request.GET.get('page', 1) try: page = int(page) object_list =",
"= value() else: c[key] = value if not template_name: model",
"1, 'previous': page - 1, 'last_on_page': paginator.last_on_page(page - 1), 'first_on_page':",
"(if paginated) has_next is there a next page? has_previous is",
"next page previous the previous page pages number of pages,",
"\"Generic detail view must be called with either an object_id",
"import loader, RequestContext from django.http import Http404, HttpResponse from django.core.xheaders",
"a slug/slug_field.\" try: obj = queryset.get() except ObjectDoesNotExist: raise Http404,",
"page? page the current page next the next page previous",
"if not page: page = request.GET.get('page', 1) try: page =",
"ValueError): if page == 1 and allow_empty: object_list = []",
"1) except (InvalidPage, ValueError): if page == 1 and allow_empty:",
"the previous page pages number of pages, total hits number",
"queryset, object_id=None, slug=None, slug_field=None, template_name=None, template_name_field=None, template_loader=loader, extra_context=None, context_processors=None, template_object_name='object',",
"Generic list of objects. Templates: ``<app_label>/<model_name>_list.html`` Context: object_list list of",
"'is_paginated': paginator.pages > 1, 'results_per_page': paginate_by, 'has_next': paginator.has_next_page(page - 1),",
"raise Http404, \"No %s found matching the query\" % (model._meta.verbose_name)",
"queryset.get() except ObjectDoesNotExist: raise Http404, \"No %s found matching the",
"{} queryset = queryset._clone() if paginate_by: paginator = ObjectPaginator(queryset, paginate_by)",
"per page (if paginated) has_next is there a next page?",
"int(page) object_list = paginator.get_page(page - 1) except (InvalidPage, ValueError): if",
"slug/slug_field.\" try: obj = queryset.get() except ObjectDoesNotExist: raise Http404, \"No",
"== 0: raise Http404 for key, value in extra_context.items(): if",
"page + 1, 'previous': page - 1, 'last_on_page': paginator.last_on_page(page -",
"first_on_page the result number of the first object in the",
"Http404 for key, value in extra_context.items(): if callable(value): c[key] =",
"(model._meta.verbose_name) if not template_name: template_name = \"%s/%s_detail.html\" % (model._meta.app_label, model._meta.object_name.lower())",
"either an object_id or a slug/slug_field.\" try: obj = queryset.get()",
"value in extra_context.items(): if callable(value): c[key] = value() else: c[key]",
"if callable(value): c[key] = value() else: c[key] = value if",
"called with either an object_id or a slug/slug_field.\" try: obj",
"InvalidPage from django.core.exceptions import ObjectDoesNotExist def object_list(request, queryset, paginate_by=None, page=None,",
"matching the query\" % (model._meta.verbose_name) if not template_name: template_name =",
"and slug_field: queryset = queryset.filter(**{slug_field: slug}) else: raise AttributeError, \"Generic",
"'last_on_page': paginator.last_on_page(page - 1), 'first_on_page': paginator.first_on_page(page - 1), 'pages': paginator.pages,",
"django.core.xheaders import populate_xheaders from django.core.paginator import ObjectPaginator, InvalidPage from django.core.exceptions",
"is None: extra_context = {} model = queryset.model if object_id:",
"model = queryset.model template_name = \"%s/%s_list.html\" % (model._meta.app_label, model._meta.object_name.lower()) t",
"value if not template_name: model = queryset.model template_name = \"%s/%s_list.html\"",
"hits number of objects, total last_on_page the result number of",
"= value() else: c[key] = value response = HttpResponse(t.render(c), mimetype=mimetype)",
"template_name_field), template_name] t = template_loader.select_template(template_name_list) else: t = template_loader.get_template(template_name) c",
"= queryset.model if object_id: queryset = queryset.filter(pk=object_id) elif slug and",
"number of the last of object in the object_list (1-indexed)",
"detail view must be called with either an object_id or",
"% template_object_name: queryset, 'is_paginated': False }, context_processors) if not allow_empty",
"paginator.pages > 1, 'results_per_page': paginate_by, 'has_next': paginator.has_next_page(page - 1), 'has_previous':",
"object_list = paginator.get_page(page - 1) except (InvalidPage, ValueError): if page",
"queryset, paginate_by=None, page=None, allow_empty=False, template_name=None, template_loader=loader, extra_context=None, context_processors=None, template_object_name='object', mimetype=None):",
"has_next is there a next page? has_previous is there a",
"number of objects per page (if paginated) has_next is there",
"and len(queryset) == 0: raise Http404 for key, value in",
"of objects is_paginated are the results paginated? results_per_page number of",
"extra_context=None, context_processors=None, template_object_name='object', mimetype=None): \"\"\" Generic detail of an object.",
"next page? has_previous is there a prev page? page the",
"def object_detail(request, queryset, object_id=None, slug=None, slug_field=None, template_name=None, template_name_field=None, template_loader=loader, extra_context=None,",
"= queryset.get() except ObjectDoesNotExist: raise Http404, \"No %s found matching",
"pages number of pages, total hits number of objects, total",
"page (if paginated) has_next is there a next page? has_previous",
"'results_per_page': paginate_by, 'has_next': paginator.has_next_page(page - 1), 'has_previous': paginator.has_previous_page(page - 1),",
"previous page pages number of pages, total hits number of",
"if paginate_by: paginator = ObjectPaginator(queryset, paginate_by) if not page: page",
"try: obj = queryset.get() except ObjectDoesNotExist: raise Http404, \"No %s",
"template_name_field=None, template_loader=loader, extra_context=None, context_processors=None, template_object_name='object', mimetype=None): \"\"\" Generic detail of",
"import populate_xheaders from django.core.paginator import ObjectPaginator, InvalidPage from django.core.exceptions import",
"page next the next page previous the previous page pages",
"slug and slug_field: queryset = queryset.filter(**{slug_field: slug}) else: raise AttributeError,",
"= [getattr(obj, template_name_field), template_name] t = template_loader.select_template(template_name_list) else: t =",
"c[key] = value() else: c[key] = value if not template_name:",
"extra_context = {} queryset = queryset._clone() if paginate_by: paginator =",
"if not template_name: template_name = \"%s/%s_detail.html\" % (model._meta.app_label, model._meta.object_name.lower()) if",
"page? has_previous is there a prev page? page the current",
"the next page previous the previous page pages number of",
"object_id: queryset = queryset.filter(pk=object_id) elif slug and slug_field: queryset =",
"if not allow_empty and len(queryset) == 0: raise Http404 for",
"Templates: ``<app_label>/<model_name>_detail.html`` Context: object the object \"\"\" if extra_context is",
"== 1 and allow_empty: object_list = [] else: raise Http404",
"number of the first object in the object_list (1-indexed) \"\"\"",
"'pages': paginator.pages, 'hits' : paginator.hits, }, context_processors) else: c =",
"in extra_context.items(): if callable(value): c[key] = value() else: c[key] =",
"template_loader.get_template(template_name) return HttpResponse(t.render(c), mimetype=mimetype) def object_detail(request, queryset, object_id=None, slug=None, slug_field=None,",
"template_object_name: object_list, 'is_paginated': paginator.pages > 1, 'results_per_page': paginate_by, 'has_next': paginator.has_next_page(page",
"callable(value): c[key] = value() else: c[key] = value if not",
"objects per page (if paginated) has_next is there a next",
"template_name: template_name = \"%s/%s_detail.html\" % (model._meta.app_label, model._meta.object_name.lower()) if template_name_field: template_name_list",
"mimetype=None): \"\"\" Generic list of objects. Templates: ``<app_label>/<model_name>_list.html`` Context: object_list",
"'previous': page - 1, 'last_on_page': paginator.last_on_page(page - 1), 'first_on_page': paginator.first_on_page(page",
"template_object_name: obj, }, context_processors) for key, value in extra_context.items(): if",
"template_loader=loader, extra_context=None, context_processors=None, template_object_name='object', mimetype=None): \"\"\" Generic list of objects.",
"}, context_processors) else: c = RequestContext(request, { '%s_list' % template_object_name:",
"raise Http404 c = RequestContext(request, { '%s_list' % template_object_name: object_list,",
"first object in the object_list (1-indexed) \"\"\" if extra_context is",
"objects is_paginated are the results paginated? results_per_page number of objects",
"queryset._clone() if paginate_by: paginator = ObjectPaginator(queryset, paginate_by) if not page:",
"the query\" % (model._meta.verbose_name) if not template_name: template_name = \"%s/%s_detail.html\"",
"template_name_field: template_name_list = [getattr(obj, template_name_field), template_name] t = template_loader.select_template(template_name_list) else:",
"(model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) return HttpResponse(t.render(c), mimetype=mimetype) def object_detail(request,",
"else: c = RequestContext(request, { '%s_list' % template_object_name: queryset, 'is_paginated':",
"RequestContext(request, { '%s_list' % template_object_name: queryset, 'is_paginated': False }, context_processors)",
"paginator.get_page(page - 1) except (InvalidPage, ValueError): if page == 1",
"t = template_loader.get_template(template_name) c = RequestContext(request, { template_object_name: obj, },",
"queryset.filter(pk=object_id) elif slug and slug_field: queryset = queryset.filter(**{slug_field: slug}) else:",
"= template_loader.select_template(template_name_list) else: t = template_loader.get_template(template_name) c = RequestContext(request, {",
"return HttpResponse(t.render(c), mimetype=mimetype) def object_detail(request, queryset, object_id=None, slug=None, slug_field=None, template_name=None,",
"paginator.has_previous_page(page - 1), 'page': page, 'next': page + 1, 'previous':",
"in the object_list (1-indexed) \"\"\" if extra_context is None: extra_context",
"{ '%s_list' % template_object_name: queryset, 'is_paginated': False }, context_processors) if",
"= value response = HttpResponse(t.render(c), mimetype=mimetype) populate_xheaders(request, response, model, getattr(obj,",
"queryset, 'is_paginated': False }, context_processors) if not allow_empty and len(queryset)",
"paginated? results_per_page number of objects per page (if paginated) has_next",
"= value if not template_name: model = queryset.model template_name =",
"obj = queryset.get() except ObjectDoesNotExist: raise Http404, \"No %s found",
"1), 'page': page, 'next': page + 1, 'previous': page -",
"object in the object_list (1-indexed) \"\"\" if extra_context is None:",
"paginator.has_next_page(page - 1), 'has_previous': paginator.has_previous_page(page - 1), 'page': page, 'next':",
"context_processors) if not allow_empty and len(queryset) == 0: raise Http404",
"``<app_label>/<model_name>_detail.html`` Context: object the object \"\"\" if extra_context is None:",
"\"\"\" Generic detail of an object. Templates: ``<app_label>/<model_name>_detail.html`` Context: object",
"try: page = int(page) object_list = paginator.get_page(page - 1) except",
"page, 'next': page + 1, 'previous': page - 1, 'last_on_page':",
"object_list(request, queryset, paginate_by=None, page=None, allow_empty=False, template_name=None, template_loader=loader, extra_context=None, context_processors=None, template_object_name='object',",
"'hits' : paginator.hits, }, context_processors) else: c = RequestContext(request, {",
"\"\"\" Generic list of objects. Templates: ``<app_label>/<model_name>_list.html`` Context: object_list list",
"django.core.paginator import ObjectPaginator, InvalidPage from django.core.exceptions import ObjectDoesNotExist def object_list(request,",
"False }, context_processors) if not allow_empty and len(queryset) == 0:",
"objects. Templates: ``<app_label>/<model_name>_list.html`` Context: object_list list of objects is_paginated are",
"paginate_by) if not page: page = request.GET.get('page', 1) try: page",
"raise Http404 for key, value in extra_context.items(): if callable(value): c[key]",
"slug_field: queryset = queryset.filter(**{slug_field: slug}) else: raise AttributeError, \"Generic detail",
"django.core.exceptions import ObjectDoesNotExist def object_list(request, queryset, paginate_by=None, page=None, allow_empty=False, template_name=None,",
"of the first object in the object_list (1-indexed) \"\"\" if",
"[getattr(obj, template_name_field), template_name] t = template_loader.select_template(template_name_list) else: t = template_loader.get_template(template_name)",
"1), 'pages': paginator.pages, 'hits' : paginator.hits, }, context_processors) else: c",
"an object. Templates: ``<app_label>/<model_name>_detail.html`` Context: object the object \"\"\" if",
"of the last of object in the object_list (1-indexed) first_on_page",
"None: extra_context = {} queryset = queryset._clone() if paginate_by: paginator",
"1 and allow_empty: object_list = [] else: raise Http404 c",
"value() else: c[key] = value if not template_name: model =",
"len(queryset) == 0: raise Http404 for key, value in extra_context.items():",
"None: extra_context = {} model = queryset.model if object_id: queryset",
"the object_list (1-indexed) \"\"\" if extra_context is None: extra_context =",
"queryset = queryset.filter(pk=object_id) elif slug and slug_field: queryset = queryset.filter(**{slug_field:",
"Http404, HttpResponse from django.core.xheaders import populate_xheaders from django.core.paginator import ObjectPaginator,",
"current page next the next page previous the previous page",
"paginator.pages, 'hits' : paginator.hits, }, context_processors) else: c = RequestContext(request,",
"HttpResponse(t.render(c), mimetype=mimetype) def object_detail(request, queryset, object_id=None, slug=None, slug_field=None, template_name=None, template_name_field=None,",
"object_list (1-indexed) first_on_page the result number of the first object",
"c = RequestContext(request, { '%s_list' % template_object_name: queryset, 'is_paginated': False",
"page pages number of pages, total hits number of objects,",
"are the results paginated? results_per_page number of objects per page",
"django.template import loader, RequestContext from django.http import Http404, HttpResponse from",
"ObjectPaginator(queryset, paginate_by) if not page: page = request.GET.get('page', 1) try:",
"not template_name: model = queryset.model template_name = \"%s/%s_list.html\" % (model._meta.app_label,",
"next the next page previous the previous page pages number",
"+ 1, 'previous': page - 1, 'last_on_page': paginator.last_on_page(page - 1),",
"from django.core.exceptions import ObjectDoesNotExist def object_list(request, queryset, paginate_by=None, page=None, allow_empty=False,",
"import ObjectDoesNotExist def object_list(request, queryset, paginate_by=None, page=None, allow_empty=False, template_name=None, template_loader=loader,",
"{} model = queryset.model if object_id: queryset = queryset.filter(pk=object_id) elif",
"obj, }, context_processors) for key, value in extra_context.items(): if callable(value):",
"= queryset.filter(pk=object_id) elif slug and slug_field: queryset = queryset.filter(**{slug_field: slug})",
"c[key] = value if not template_name: model = queryset.model template_name",
"= RequestContext(request, { '%s_list' % template_object_name: object_list, 'is_paginated': paginator.pages >",
"= {} queryset = queryset._clone() if paginate_by: paginator = ObjectPaginator(queryset,",
"\"\"\" if extra_context is None: extra_context = {} model =",
"template_name] t = template_loader.select_template(template_name_list) else: t = template_loader.get_template(template_name) c =",
"= queryset._clone() if paginate_by: paginator = ObjectPaginator(queryset, paginate_by) if not",
"elif slug and slug_field: queryset = queryset.filter(**{slug_field: slug}) else: raise",
"% (model._meta.verbose_name) if not template_name: template_name = \"%s/%s_detail.html\" % (model._meta.app_label,",
"prev page? page the current page next the next page",
"= int(page) object_list = paginator.get_page(page - 1) except (InvalidPage, ValueError):",
"%s found matching the query\" % (model._meta.verbose_name) if not template_name:",
"results paginated? results_per_page number of objects per page (if paginated)",
"template_name=None, template_loader=loader, extra_context=None, context_processors=None, template_object_name='object', mimetype=None): \"\"\" Generic list of",
"- 1), 'first_on_page': paginator.first_on_page(page - 1), 'pages': paginator.pages, 'hits' :",
"(InvalidPage, ValueError): if page == 1 and allow_empty: object_list =",
"- 1, 'last_on_page': paginator.last_on_page(page - 1), 'first_on_page': paginator.first_on_page(page - 1),",
"= template_loader.get_template(template_name) c = RequestContext(request, { template_object_name: obj, }, context_processors)",
"% (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) return HttpResponse(t.render(c), mimetype=mimetype) def",
"template_name=None, template_name_field=None, template_loader=loader, extra_context=None, context_processors=None, template_object_name='object', mimetype=None): \"\"\" Generic detail",
"HttpResponse from django.core.xheaders import populate_xheaders from django.core.paginator import ObjectPaginator, InvalidPage",
"extra_context.items(): if callable(value): c[key] = value() else: c[key] = value",
"model = queryset.model if object_id: queryset = queryset.filter(pk=object_id) elif slug",
"total hits number of objects, total last_on_page the result number",
"if extra_context is None: extra_context = {} model = queryset.model",
"of objects, total last_on_page the result number of the last",
"0: raise Http404 for key, value in extra_context.items(): if callable(value):",
"template_loader.get_template(template_name) c = RequestContext(request, { template_object_name: obj, }, context_processors) for",
"and allow_empty: object_list = [] else: raise Http404 c =",
"'%s_list' % template_object_name: queryset, 'is_paginated': False }, context_processors) if not",
"if template_name_field: template_name_list = [getattr(obj, template_name_field), template_name] t = template_loader.select_template(template_name_list)",
"1), 'first_on_page': paginator.first_on_page(page - 1), 'pages': paginator.pages, 'hits' : paginator.hits,",
"or a slug/slug_field.\" try: obj = queryset.get() except ObjectDoesNotExist: raise",
"query\" % (model._meta.verbose_name) if not template_name: template_name = \"%s/%s_detail.html\" %",
"context_processors) else: c = RequestContext(request, { '%s_list' % template_object_name: queryset,",
"- 1) except (InvalidPage, ValueError): if page == 1 and",
"slug_field=None, template_name=None, template_name_field=None, template_loader=loader, extra_context=None, context_processors=None, template_object_name='object', mimetype=None): \"\"\" Generic",
"is there a prev page? page the current page next",
"from django.core.paginator import ObjectPaginator, InvalidPage from django.core.exceptions import ObjectDoesNotExist def",
"\"%s/%s_list.html\" % (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) return HttpResponse(t.render(c), mimetype=mimetype)",
"request.GET.get('page', 1) try: page = int(page) object_list = paginator.get_page(page -",
"'has_next': paginator.has_next_page(page - 1), 'has_previous': paginator.has_previous_page(page - 1), 'page': page,",
"ObjectPaginator, InvalidPage from django.core.exceptions import ObjectDoesNotExist def object_list(request, queryset, paginate_by=None,",
"is_paginated are the results paginated? results_per_page number of objects per",
"import Http404, HttpResponse from django.core.xheaders import populate_xheaders from django.core.paginator import",
"object_id=None, slug=None, slug_field=None, template_name=None, template_name_field=None, template_loader=loader, extra_context=None, context_processors=None, template_object_name='object', mimetype=None):",
"template_object_name: queryset, 'is_paginated': False }, context_processors) if not allow_empty and",
"from django.core.xheaders import populate_xheaders from django.core.paginator import ObjectPaginator, InvalidPage from",
"for key, value in extra_context.items(): if callable(value): c[key] = value()",
"Generic detail of an object. Templates: ``<app_label>/<model_name>_detail.html`` Context: object the",
"paginate_by: paginator = ObjectPaginator(queryset, paginate_by) if not page: page =",
": paginator.hits, }, context_processors) else: c = RequestContext(request, { '%s_list'",
"the results paginated? results_per_page number of objects per page (if",
"(1-indexed) \"\"\" if extra_context is None: extra_context = {} queryset",
"c[key] = value() else: c[key] = value response = HttpResponse(t.render(c),",
"= queryset.filter(**{slug_field: slug}) else: raise AttributeError, \"Generic detail view must",
"slug}) else: raise AttributeError, \"Generic detail view must be called",
"template_loader.select_template(template_name_list) else: t = template_loader.get_template(template_name) c = RequestContext(request, { template_object_name:",
"queryset.filter(**{slug_field: slug}) else: raise AttributeError, \"Generic detail view must be",
"else: raise Http404 c = RequestContext(request, { '%s_list' % template_object_name:",
"queryset.model if object_id: queryset = queryset.filter(pk=object_id) elif slug and slug_field:",
"the result number of the first object in the object_list",
"'page': page, 'next': page + 1, 'previous': page - 1,",
"page = int(page) object_list = paginator.get_page(page - 1) except (InvalidPage,",
"}, context_processors) for key, value in extra_context.items(): if callable(value): c[key]",
"ObjectDoesNotExist: raise Http404, \"No %s found matching the query\" %",
"has_previous is there a prev page? page the current page",
"'next': page + 1, 'previous': page - 1, 'last_on_page': paginator.last_on_page(page",
"template_name = \"%s/%s_detail.html\" % (model._meta.app_label, model._meta.object_name.lower()) if template_name_field: template_name_list =",
"template_name = \"%s/%s_list.html\" % (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) return",
"found matching the query\" % (model._meta.verbose_name) if not template_name: template_name",
"Templates: ``<app_label>/<model_name>_list.html`` Context: object_list list of objects is_paginated are the",
"c[key] = value response = HttpResponse(t.render(c), mimetype=mimetype) populate_xheaders(request, response, model,",
"model._meta.object_name.lower()) if template_name_field: template_name_list = [getattr(obj, template_name_field), template_name] t =",
"extra_context=None, context_processors=None, template_object_name='object', mimetype=None): \"\"\" Generic list of objects. Templates:",
"not page: page = request.GET.get('page', 1) try: page = int(page)",
"with either an object_id or a slug/slug_field.\" try: obj =",
"template_name: model = queryset.model template_name = \"%s/%s_list.html\" % (model._meta.app_label, model._meta.object_name.lower())",
"1, 'results_per_page': paginate_by, 'has_next': paginator.has_next_page(page - 1), 'has_previous': paginator.has_previous_page(page -",
"result number of the last of object in the object_list",
"Http404, \"No %s found matching the query\" % (model._meta.verbose_name) if",
"mimetype=None): \"\"\" Generic detail of an object. Templates: ``<app_label>/<model_name>_detail.html`` Context:",
"allow_empty: object_list = [] else: raise Http404 c = RequestContext(request,",
"must be called with either an object_id or a slug/slug_field.\"",
"the object \"\"\" if extra_context is None: extra_context = {}",
"else: c[key] = value if not template_name: model = queryset.model",
"c = RequestContext(request, { template_object_name: obj, }, context_processors) for key,",
"Context: object the object \"\"\" if extra_context is None: extra_context",
"Http404 c = RequestContext(request, { '%s_list' % template_object_name: object_list, 'is_paginated':",
"detail of an object. Templates: ``<app_label>/<model_name>_detail.html`` Context: object the object",
"results_per_page number of objects per page (if paginated) has_next is",
"queryset = queryset._clone() if paginate_by: paginator = ObjectPaginator(queryset, paginate_by) if",
"previous the previous page pages number of pages, total hits",
"template_object_name='object', mimetype=None): \"\"\" Generic list of objects. Templates: ``<app_label>/<model_name>_list.html`` Context:",
"there a next page? has_previous is there a prev page?",
"the object_list (1-indexed) first_on_page the result number of the first",
"page == 1 and allow_empty: object_list = [] else: raise",
"template_loader=loader, extra_context=None, context_processors=None, template_object_name='object', mimetype=None): \"\"\" Generic detail of an",
"of objects. Templates: ``<app_label>/<model_name>_list.html`` Context: object_list list of objects is_paginated",
"if extra_context is None: extra_context = {} queryset = queryset._clone()",
"in the object_list (1-indexed) first_on_page the result number of the",
"total last_on_page the result number of the last of object",
"a next page? has_previous is there a prev page? page",
"of objects per page (if paginated) has_next is there a",
"object_list = [] else: raise Http404 c = RequestContext(request, {",
"not template_name: template_name = \"%s/%s_detail.html\" % (model._meta.app_label, model._meta.object_name.lower()) if template_name_field:",
"c = RequestContext(request, { '%s_list' % template_object_name: object_list, 'is_paginated': paginator.pages",
"= RequestContext(request, { '%s_list' % template_object_name: queryset, 'is_paginated': False },",
"= HttpResponse(t.render(c), mimetype=mimetype) populate_xheaders(request, response, model, getattr(obj, obj._meta.pk.name)) return response",
"- 1), 'pages': paginator.pages, 'hits' : paginator.hits, }, context_processors) else:",
"raise AttributeError, \"Generic detail view must be called with either",
"number of objects, total last_on_page the result number of the",
"object_list (1-indexed) \"\"\" if extra_context is None: extra_context = {}",
"context_processors) for key, value in extra_context.items(): if callable(value): c[key] =",
"objects, total last_on_page the result number of the last of",
"{ '%s_list' % template_object_name: object_list, 'is_paginated': paginator.pages > 1, 'results_per_page':",
"= \"%s/%s_list.html\" % (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) return HttpResponse(t.render(c),",
"result number of the first object in the object_list (1-indexed)",
"object the object \"\"\" if extra_context is None: extra_context =",
"allow_empty and len(queryset) == 0: raise Http404 for key, value",
"paginator.first_on_page(page - 1), 'pages': paginator.pages, 'hits' : paginator.hits, }, context_processors)",
"paginator.hits, }, context_processors) else: c = RequestContext(request, { '%s_list' %",
"value response = HttpResponse(t.render(c), mimetype=mimetype) populate_xheaders(request, response, model, getattr(obj, obj._meta.pk.name))",
"paginate_by=None, page=None, allow_empty=False, template_name=None, template_loader=loader, extra_context=None, context_processors=None, template_object_name='object', mimetype=None): \"\"\"",
"list of objects. Templates: ``<app_label>/<model_name>_list.html`` Context: object_list list of objects",
"> 1, 'results_per_page': paginate_by, 'has_next': paginator.has_next_page(page - 1), 'has_previous': paginator.has_previous_page(page",
"the first object in the object_list (1-indexed) \"\"\" if extra_context",
"``<app_label>/<model_name>_list.html`` Context: object_list list of objects is_paginated are the results",
"t = template_loader.get_template(template_name) return HttpResponse(t.render(c), mimetype=mimetype) def object_detail(request, queryset, object_id=None,",
"paginator.last_on_page(page - 1), 'first_on_page': paginator.first_on_page(page - 1), 'pages': paginator.pages, 'hits'",
"= ObjectPaginator(queryset, paginate_by) if not page: page = request.GET.get('page', 1)",
"object \"\"\" if extra_context is None: extra_context = {} model",
"(model._meta.app_label, model._meta.object_name.lower()) if template_name_field: template_name_list = [getattr(obj, template_name_field), template_name] t",
"= queryset.model template_name = \"%s/%s_list.html\" % (model._meta.app_label, model._meta.object_name.lower()) t =",
"ObjectDoesNotExist def object_list(request, queryset, paginate_by=None, page=None, allow_empty=False, template_name=None, template_loader=loader, extra_context=None,",
"if not template_name: model = queryset.model template_name = \"%s/%s_list.html\" %",
"from django.template import loader, RequestContext from django.http import Http404, HttpResponse",
"except ObjectDoesNotExist: raise Http404, \"No %s found matching the query\"",
"be called with either an object_id or a slug/slug_field.\" try:",
"}, context_processors) if not allow_empty and len(queryset) == 0: raise",
"callable(value): c[key] = value() else: c[key] = value response =",
"if object_id: queryset = queryset.filter(pk=object_id) elif slug and slug_field: queryset",
"'is_paginated': False }, context_processors) if not allow_empty and len(queryset) ==",
"response = HttpResponse(t.render(c), mimetype=mimetype) populate_xheaders(request, response, model, getattr(obj, obj._meta.pk.name)) return",
"from django.http import Http404, HttpResponse from django.core.xheaders import populate_xheaders from",
"queryset = queryset.filter(**{slug_field: slug}) else: raise AttributeError, \"Generic detail view",
"mimetype=mimetype) def object_detail(request, queryset, object_id=None, slug=None, slug_field=None, template_name=None, template_name_field=None, template_loader=loader,",
"is there a next page? has_previous is there a prev",
"of object in the object_list (1-indexed) first_on_page the result number",
"else: raise AttributeError, \"Generic detail view must be called with",
"RequestContext(request, { template_object_name: obj, }, context_processors) for key, value in",
"the current page next the next page previous the previous",
"of an object. Templates: ``<app_label>/<model_name>_detail.html`` Context: object the object \"\"\"",
"template_object_name='object', mimetype=None): \"\"\" Generic detail of an object. Templates: ``<app_label>/<model_name>_detail.html``",
"is None: extra_context = {} queryset = queryset._clone() if paginate_by:",
"an object_id or a slug/slug_field.\" try: obj = queryset.get() except",
"= template_loader.get_template(template_name) return HttpResponse(t.render(c), mimetype=mimetype) def object_detail(request, queryset, object_id=None, slug=None,",
"- 1), 'page': page, 'next': page + 1, 'previous': page",
"\"No %s found matching the query\" % (model._meta.verbose_name) if not",
"populate_xheaders from django.core.paginator import ObjectPaginator, InvalidPage from django.core.exceptions import ObjectDoesNotExist",
"= [] else: raise Http404 c = RequestContext(request, { '%s_list'",
"allow_empty=False, template_name=None, template_loader=loader, extra_context=None, context_processors=None, template_object_name='object', mimetype=None): \"\"\" Generic list",
"1) try: page = int(page) object_list = paginator.get_page(page - 1)",
"= {} model = queryset.model if object_id: queryset = queryset.filter(pk=object_id)",
"queryset.model template_name = \"%s/%s_list.html\" % (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name)",
"paginator = ObjectPaginator(queryset, paginate_by) if not page: page = request.GET.get('page',",
"object in the object_list (1-indexed) first_on_page the result number of",
"loader, RequestContext from django.http import Http404, HttpResponse from django.core.xheaders import",
"a prev page? page the current page next the next",
"'first_on_page': paginator.first_on_page(page - 1), 'pages': paginator.pages, 'hits' : paginator.hits, },",
"context_processors=None, template_object_name='object', mimetype=None): \"\"\" Generic list of objects. Templates: ``<app_label>/<model_name>_list.html``",
"% (model._meta.app_label, model._meta.object_name.lower()) if template_name_field: template_name_list = [getattr(obj, template_name_field), template_name]",
"RequestContext(request, { '%s_list' % template_object_name: object_list, 'is_paginated': paginator.pages > 1,",
"Context: object_list list of objects is_paginated are the results paginated?",
"except (InvalidPage, ValueError): if page == 1 and allow_empty: object_list",
"'has_previous': paginator.has_previous_page(page - 1), 'page': page, 'next': page + 1,",
"view must be called with either an object_id or a",
"- 1), 'has_previous': paginator.has_previous_page(page - 1), 'page': page, 'next': page",
"def object_list(request, queryset, paginate_by=None, page=None, allow_empty=False, template_name=None, template_loader=loader, extra_context=None, context_processors=None,",
"if page == 1 and allow_empty: object_list = [] else:",
"else: t = template_loader.get_template(template_name) c = RequestContext(request, { template_object_name: obj,",
"slug=None, slug_field=None, template_name=None, template_name_field=None, template_loader=loader, extra_context=None, context_processors=None, template_object_name='object', mimetype=None): \"\"\"",
"there a prev page? page the current page next the",
"RequestContext from django.http import Http404, HttpResponse from django.core.xheaders import populate_xheaders",
"page previous the previous page pages number of pages, total",
"page: page = request.GET.get('page', 1) try: page = int(page) object_list",
"of pages, total hits number of objects, total last_on_page the",
"key, value in extra_context.items(): if callable(value): c[key] = value() else:"
] |
[
"name) else: assert callable(create_fn), \"Expect a callable function\" value =",
"treedef = jax.tree_flatten(value) self.treedef_dict[name] = treedef self.leaves_dict[name] = leaves def",
"AttributeError() def update(self: T, **kwargs) -> T: \"\"\"Update the flattener.",
"-> T: \"\"\"Raise an error. Need to reconstruct the original",
"zip(self.features[:-1], self.features[1:]) ... for i, (in_dim, out_dim) in enumerate(sizes): ...",
"└── Linear(in_dim=2, out_dim=3, with_bias=True) \"\"\" def get_or_create(self, name, create_fn: Callable[[],",
"module. Example: >>> net = pax.Lambda(jax.nn.relu) >>> print(net.summary()) x =>",
"**kwargs): return self.func(*args, **kwargs) def __repr__(self) -> str: if self.name",
"it is not exist. Return the attribute. \"\"\" if hasattr(self,",
"O = TypeVar(\"O\") class ParameterModule(Module): \"\"\"A PAX module that registers",
"func def __call__(self, *args, **kwargs): return self.func(*args, **kwargs) def __repr__(self)",
"error. Need to reconstruct the original module before getting parameters.",
"Module, parameters_method T = TypeVar(\"T\", bound=Module) O = TypeVar(\"O\") class",
"else: return f\"{self.__class__.__qualname__}({self.func.__name__})\" def summary(self, return_list: bool = False) ->",
"for better performance. Example: >>> net = pax.Linear(3, 3) >>>",
"opax.adam(1e-3)(net.parameters()) >>> flat_mods = pax.experimental.Flattener(model=net, optimizer=opt) >>> net, opt =",
"module that registers attributes as parameters by default.\"\"\" def parameters(self):",
"= pax.Linear(3, 3) >>> flats = pax.experimental.Flattener(net=net) >>> flats =",
"name, value in kwargs.items(): leaves, treedef = jax.tree_flatten(value) new_self.treedef_dict[name] =",
"= jax.tree_flatten(value) new_self.treedef_dict[name] = treedef new_self.leaves_dict[name] = leaves return new_self",
"\"\"\" raise ValueError( \"A flattener only stores ndarray leaves as",
">>> @dataclass ... class MLP(pax.experimental.LazyModule): ... features: list ... ...",
"original module before getting parameters. \"\"\" raise ValueError( \"A flattener",
"pax.Linear(in_dim, out_dim)) ... x = jax.nn.relu(fc(x)) ... return x ...",
"not None: name = self.name elif isinstance(self.func, jax.custom_jvp) and hasattr(self.func,",
"attributes as parameters by default.\"\"\" def parameters(self): return self.apply_submodules(lambda x:",
"\"\"\"Raise an error. Need to reconstruct the original module before",
"for i, (in_dim, out_dim) in enumerate(sizes): ... fc = self.get_or_create(f\"fc_{i}\",",
"with_bias=True) \"\"\" new_self = self.copy() for name, value in kwargs.items():",
"better performance. Example: >>> net = pax.Linear(3, 3) >>> opt",
"new_self.leaves_dict[name] = leaves return new_self def parameters(self: T) -> T:",
"= func def __call__(self, *args, **kwargs): return self.func(*args, **kwargs) def",
"flats.update(net=pax.Linear(4, 4)) >>> print(flats.net.summary()) Linear(in_dim=4, out_dim=4, with_bias=True) \"\"\" new_self =",
"Linear(in_dim=2, out_dim=3, with_bias=True) \"\"\" def get_or_create(self, name, create_fn: Callable[[], T])",
"for name, value in kwargs.items(): leaves, treedef = jax.tree_flatten(value) new_self.treedef_dict[name]",
"List[str]]: if self.name is not None: name = self.name elif",
"stores ndarray leaves as non-trainable states.\\n\" \"Reconstruct the original module",
"module that registers attributes as states by default.\"\"\" parameters =",
"treedef = jax.tree_flatten(value) new_self.treedef_dict[name] = treedef new_self.leaves_dict[name] = leaves return",
"= {} self.leaves_dict = {} for name, value in kwargs.items():",
"net, opt = flat_mods.model, flat_mods.optimizer >>> print(net.summary()) Linear(in_dim=3, out_dim=3, with_bias=True)",
"return value else: raise AttributeError() def update(self: T, **kwargs) ->",
"flat_mods = pax.experimental.Flattener(model=net, optimizer=opt) >>> net, opt = flat_mods.model, flat_mods.optimizer",
"and register a new attribute when it is not exist.",
"treedef_dict: Dict[str, Any] leaves_dict: Dict[str, Sequence[jnp.ndarray]] def __init__(self, **kwargs): \"\"\"Create",
"and hasattr(self.func, \"fun\"): if hasattr(self.func.fun, \"__name__\"): name = self.func.fun.__name__ else:",
"jax.tree_flatten(value) self.treedef_dict[name] = treedef self.leaves_dict[name] = leaves def __getattr__(self, name:",
"raise AttributeError() def update(self: T, **kwargs) -> T: \"\"\"Update the",
">>> flats = pax.experimental.Flattener(net=net) >>> flats = flats.update(net=pax.Linear(4, 4)) >>>",
">>> y = net(jnp.array(-1)) >>> y DeviceArray(0, dtype=int32, weak_type=True) \"\"\"",
"jax.tree_unflatten(treedef, leaves) return value else: raise AttributeError() def update(self: T,",
"MLP(features=[1, 2, 3]) ├── Linear(in_dim=1, out_dim=2, with_bias=True) └── Linear(in_dim=2, out_dim=3,",
"assert callable(create_fn), \"Expect a callable function\" value = create_fn() setattr(self,",
"as states by default.\"\"\" parameters = parameters_method() class LazyModule(Module): \"\"\"A",
"{name}(x)\" return [output] if return_list else output class Flattener(Module): \"\"\"Flatten",
"ParameterModule(Module): \"\"\"A PAX module that registers attributes as parameters by",
"None): super().__init__(name=name) self.func = func def __call__(self, *args, **kwargs): return",
"name = self.func.fun.__name__ else: name = f\"{self.func.fun}\" elif hasattr(self.func, \"__name__\"):",
"in kwargs.items(): leaves, treedef = jax.tree_flatten(value) self.treedef_dict[name] = treedef self.leaves_dict[name]",
"to reconstruct the original module before getting parameters. \"\"\" raise",
"scale_by_adam.<locals>.ScaleByAdam │ ├── Linear(in_dim=3, out_dim=3, with_bias=True) │ └── Linear(in_dim=3, out_dim=3,",
"a callable function\" value = create_fn() setattr(self, name, value) return",
"mlp, _ = MLP([1, 2, 3]) % jnp.ones((1, 1)) >>>",
"elif hasattr(self.func, \"__name__\"): name = self.func.__name__ else: name = f\"{self.func}\"",
"optimizer=opt) >>> net, opt = flat_mods.model, flat_mods.optimizer >>> print(net.summary()) Linear(in_dim=3,",
"def parameters(self: T) -> T: \"\"\"Raise an error. Need to",
"def __repr__(self) -> str: if self.name is not None: return",
"name in self.treedef_dict: treedef = self.treedef_dict[name] leaves = self.leaves_dict[name] value",
">>> print(net.summary()) Linear(in_dim=3, out_dim=3, with_bias=True) >>> print(opt.summary()) chain.<locals>.Chain ├── scale_by_adam.<locals>.ScaleByAdam",
"if name in self.treedef_dict: treedef = self.treedef_dict[name] leaves = self.leaves_dict[name]",
"name: Optional[str] = None): super().__init__(name=name) self.func = func def __call__(self,",
"before getting parameters. \"\"\" raise ValueError( \"A flattener only stores",
"Example: >>> net = pax.Linear(3, 3) >>> flats = pax.experimental.Flattener(net=net)",
"MLP(pax.experimental.LazyModule): ... features: list ... ... def __call__(self, x): ...",
"│ ├── Linear(in_dim=3, out_dim=3, with_bias=True) │ └── Linear(in_dim=3, out_dim=3, with_bias=True)",
"StateModule(Module): \"\"\"A PAX module that registers attributes as states by",
"\"\"\"Utility Modules.\"\"\" from typing import Any, Callable, Dict, List, Optional,",
"chain.<locals>.Chain ├── scale_by_adam.<locals>.ScaleByAdam │ ├── Linear(in_dim=3, out_dim=3, with_bias=True) │ └──",
"creates submodules when needed. Example: >>> from dataclasses import dataclass",
"False) -> Union[str, List[str]]: if self.name is not None: name",
"\"A flattener only stores ndarray leaves as non-trainable states.\\n\" \"Reconstruct",
"new_self def parameters(self: T) -> T: \"\"\"Raise an error. Need",
"3]) % jnp.ones((1, 1)) >>> print(mlp.summary()) MLP(features=[1, 2, 3]) ├──",
"parameters_method() class LazyModule(Module): \"\"\"A lazy module is a module that",
"self.name is not None: name = self.name elif isinstance(self.func, jax.custom_jvp)",
"elif isinstance(self.func, jax.custom_jvp) and hasattr(self.func, \"fun\"): if hasattr(self.func.fun, \"__name__\"): name",
"else: raise AttributeError() def update(self: T, **kwargs) -> T: \"\"\"Update",
"leaves_dict: Dict[str, Sequence[jnp.ndarray]] def __init__(self, **kwargs): \"\"\"Create a new flattener.\"\"\"",
"{} for name, value in kwargs.items(): leaves, treedef = jax.tree_flatten(value)",
"return x ... ... >>> mlp, _ = MLP([1, 2,",
"= treedef self.leaves_dict[name] = leaves def __getattr__(self, name: str) ->",
"attributes as states by default.\"\"\" parameters = parameters_method() class LazyModule(Module):",
"value else: raise AttributeError() def update(self: T, **kwargs) -> T:",
"print(net.summary()) x => relu(x) >>> y = net(jnp.array(-1)) >>> y",
"a new flattener.\"\"\" super().__init__() self.treedef_dict = {} self.leaves_dict = {}",
"= jax.tree_flatten(value) self.treedef_dict[name] = treedef self.leaves_dict[name] = leaves def __getattr__(self,",
"-> str: if self.name is not None: return super().__repr__() else:",
"create_fn() setattr(self, name, value) return value class Lambda(Module): \"\"\"Convert a",
"Lambda(Module): \"\"\"Convert a function to a module. Example: >>> net",
"leaves = self.leaves_dict[name] value = jax.tree_unflatten(treedef, leaves) return value else:",
"[output] if return_list else output class Flattener(Module): \"\"\"Flatten PAX modules",
"out_dim=3, with_bias=True) │ └── Linear(in_dim=3, out_dim=3, with_bias=True) └── scale.<locals>.Scale \"\"\"",
"func: Callable def __init__(self, func: Callable, name: Optional[str] = None):",
"T: \"\"\"Update the flattener. Example: >>> net = pax.Linear(3, 3)",
"flattener.\"\"\" super().__init__() self.treedef_dict = {} self.leaves_dict = {} for name,",
"return f\"{self.__class__.__qualname__}({self.func.__name__})\" def summary(self, return_list: bool = False) -> Union[str,",
"= pax.Lambda(jax.nn.relu) >>> print(net.summary()) x => relu(x) >>> y =",
"List, Optional, Sequence, TypeVar, Union import jax import jax.numpy as",
"jax.custom_jvp) and hasattr(self.func, \"fun\"): if hasattr(self.func.fun, \"__name__\"): name = self.func.fun.__name__",
"T, **kwargs) -> T: \"\"\"Update the flattener. Example: >>> net",
"net = pax.Linear(3, 3) >>> flats = pax.experimental.Flattener(net=net) >>> flats",
"self.copy() for name, value in kwargs.items(): leaves, treedef = jax.tree_flatten(value)",
"self.treedef_dict[name] leaves = self.leaves_dict[name] value = jax.tree_unflatten(treedef, leaves) return value",
"x = jax.nn.relu(fc(x)) ... return x ... ... >>> mlp,",
"leaves, treedef = jax.tree_flatten(value) self.treedef_dict[name] = treedef self.leaves_dict[name] = leaves",
"out_dim=3, with_bias=True) \"\"\" def get_or_create(self, name, create_fn: Callable[[], T]) ->",
"= self.func.fun.__name__ else: name = f\"{self.func.fun}\" elif hasattr(self.func, \"__name__\"): name",
"self.name is not None: return super().__repr__() else: return f\"{self.__class__.__qualname__}({self.func.__name__})\" def",
"self.func = func def __call__(self, *args, **kwargs): return self.func(*args, **kwargs)",
"Optional, Sequence, TypeVar, Union import jax import jax.numpy as jnp",
"= flats.update(net=pax.Linear(4, 4)) >>> print(flats.net.summary()) Linear(in_dim=4, out_dim=4, with_bias=True) \"\"\" new_self",
"pax.Linear(3, 3) >>> opt = opax.adam(1e-3)(net.parameters()) >>> flat_mods = pax.experimental.Flattener(model=net,",
"Callable, Dict, List, Optional, Sequence, TypeVar, Union import jax import",
"else: name = f\"{self.func}\" output = f\"x => {name}(x)\" return",
"the flattener. Example: >>> net = pax.Linear(3, 3) >>> flats",
"net = pax.Lambda(jax.nn.relu) >>> print(net.summary()) x => relu(x) >>> y",
"raise ValueError( \"A flattener only stores ndarray leaves as non-trainable",
"jax import jax.numpy as jnp from .module import Module, parameters_method",
"is a module that only creates submodules when needed. Example:",
"from .module import Module, parameters_method T = TypeVar(\"T\", bound=Module) O",
"i, (in_dim, out_dim) in enumerate(sizes): ... fc = self.get_or_create(f\"fc_{i}\", lambda:",
"import jax import jax.numpy as jnp from .module import Module,",
"\"\"\"Convert a function to a module. Example: >>> net =",
"Callable, name: Optional[str] = None): super().__init__(name=name) self.func = func def",
"self.leaves_dict = {} for name, value in kwargs.items(): leaves, treedef",
"update(self: T, **kwargs) -> T: \"\"\"Update the flattener. Example: >>>",
"2, 3]) % jnp.ones((1, 1)) >>> print(mlp.summary()) MLP(features=[1, 2, 3])",
"__init__(self, func: Callable, name: Optional[str] = None): super().__init__(name=name) self.func =",
"├── scale_by_adam.<locals>.ScaleByAdam │ ├── Linear(in_dim=3, out_dim=3, with_bias=True) │ └── Linear(in_dim=3,",
"= pax.Linear(3, 3) >>> opt = opax.adam(1e-3)(net.parameters()) >>> flat_mods =",
"return self.apply_submodules(lambda x: x.parameters()) class StateModule(Module): \"\"\"A PAX module that",
"setattr(self, name, value) return value class Lambda(Module): \"\"\"Convert a function",
"name = f\"{self.func}\" output = f\"x => {name}(x)\" return [output]",
"Example: >>> net = pax.Linear(3, 3) >>> opt = opax.adam(1e-3)(net.parameters())",
"pax.experimental.Flattener(net=net) >>> flats = flats.update(net=pax.Linear(4, 4)) >>> print(flats.net.summary()) Linear(in_dim=4, out_dim=4,",
"\"fun\"): if hasattr(self.func.fun, \"__name__\"): name = self.func.fun.__name__ else: name =",
"with_bias=True) >>> print(opt.summary()) chain.<locals>.Chain ├── scale_by_adam.<locals>.ScaleByAdam │ ├── Linear(in_dim=3, out_dim=3,",
"... for i, (in_dim, out_dim) in enumerate(sizes): ... fc =",
"= leaves def __getattr__(self, name: str) -> Any: if name",
"(in_dim, out_dim) in enumerate(sizes): ... fc = self.get_or_create(f\"fc_{i}\", lambda: pax.Linear(in_dim,",
"= f\"{self.func}\" output = f\"x => {name}(x)\" return [output] if",
"= self.leaves_dict[name] value = jax.tree_unflatten(treedef, leaves) return value else: raise",
"dataclasses import dataclass >>> @dataclass ... class MLP(pax.experimental.LazyModule): ... features:",
"Any, Callable, Dict, List, Optional, Sequence, TypeVar, Union import jax",
"... class MLP(pax.experimental.LazyModule): ... features: list ... ... def __call__(self,",
"create_fn: Callable[[], T]) -> T: \"\"\"Create and register a new",
"if self.name is not None: name = self.name elif isinstance(self.func,",
"value in kwargs.items(): leaves, treedef = jax.tree_flatten(value) new_self.treedef_dict[name] = treedef",
"dataclass >>> @dataclass ... class MLP(pax.experimental.LazyModule): ... features: list ...",
"=> {name}(x)\" return [output] if return_list else output class Flattener(Module):",
"value = jax.tree_unflatten(treedef, leaves) return value else: raise AttributeError() def",
"self.func.__name__ else: name = f\"{self.func}\" output = f\"x => {name}(x)\"",
"Union[str, List[str]]: if self.name is not None: name = self.name",
"Example: >>> from dataclasses import dataclass >>> @dataclass ... class",
"= f\"{self.func.fun}\" elif hasattr(self.func, \"__name__\"): name = self.func.__name__ else: name",
"Any: if name in self.treedef_dict: treedef = self.treedef_dict[name] leaves =",
"\"\"\"Flatten PAX modules for better performance. Example: >>> net =",
"Optional[str] = None): super().__init__(name=name) self.func = func def __call__(self, *args,",
"that registers attributes as states by default.\"\"\" parameters = parameters_method()",
"Example: >>> net = pax.Lambda(jax.nn.relu) >>> print(net.summary()) x => relu(x)",
"... >>> mlp, _ = MLP([1, 2, 3]) % jnp.ones((1,",
"... features: list ... ... def __call__(self, x): ... sizes",
"lambda: pax.Linear(in_dim, out_dim)) ... x = jax.nn.relu(fc(x)) ... return x",
"MLP([1, 2, 3]) % jnp.ones((1, 1)) >>> print(mlp.summary()) MLP(features=[1, 2,",
"out_dim=2, with_bias=True) └── Linear(in_dim=2, out_dim=3, with_bias=True) \"\"\" def get_or_create(self, name,",
"def __call__(self, *args, **kwargs): return self.func(*args, **kwargs) def __repr__(self) ->",
"def update(self: T, **kwargs) -> T: \"\"\"Update the flattener. Example:",
"net(jnp.array(-1)) >>> y DeviceArray(0, dtype=int32, weak_type=True) \"\"\" func: Callable def",
"name, value in kwargs.items(): leaves, treedef = jax.tree_flatten(value) self.treedef_dict[name] =",
">>> net = pax.Lambda(jax.nn.relu) >>> print(net.summary()) x => relu(x) >>>",
"3) >>> flats = pax.experimental.Flattener(net=net) >>> flats = flats.update(net=pax.Linear(4, 4))",
"TypeVar, Union import jax import jax.numpy as jnp from .module",
"needed. Example: >>> from dataclasses import dataclass >>> @dataclass ...",
"parameters(self): return self.apply_submodules(lambda x: x.parameters()) class StateModule(Module): \"\"\"A PAX module",
"y = net(jnp.array(-1)) >>> y DeviceArray(0, dtype=int32, weak_type=True) \"\"\" func:",
"def __call__(self, x): ... sizes = zip(self.features[:-1], self.features[1:]) ... for",
"flats = pax.experimental.Flattener(net=net) >>> flats = flats.update(net=pax.Linear(4, 4)) >>> print(flats.net.summary())",
"f\"{self.func.fun}\" elif hasattr(self.func, \"__name__\"): name = self.func.__name__ else: name =",
"Dict, List, Optional, Sequence, TypeVar, Union import jax import jax.numpy",
"from dataclasses import dataclass >>> @dataclass ... class MLP(pax.experimental.LazyModule): ...",
"pax.Linear(3, 3) >>> flats = pax.experimental.Flattener(net=net) >>> flats = flats.update(net=pax.Linear(4,",
"states by default.\"\"\" parameters = parameters_method() class LazyModule(Module): \"\"\"A lazy",
"module is a module that only creates submodules when needed.",
"value in kwargs.items(): leaves, treedef = jax.tree_flatten(value) self.treedef_dict[name] = treedef",
"= self.copy() for name, value in kwargs.items(): leaves, treedef =",
"= opax.adam(1e-3)(net.parameters()) >>> flat_mods = pax.experimental.Flattener(model=net, optimizer=opt) >>> net, opt",
"class LazyModule(Module): \"\"\"A lazy module is a module that only",
"*args, **kwargs): return self.func(*args, **kwargs) def __repr__(self) -> str: if",
"3]) ├── Linear(in_dim=1, out_dim=2, with_bias=True) └── Linear(in_dim=2, out_dim=3, with_bias=True) \"\"\"",
"PAX modules for better performance. Example: >>> net = pax.Linear(3,",
"def __getattr__(self, name: str) -> Any: if name in self.treedef_dict:",
">>> flat_mods = pax.experimental.Flattener(model=net, optimizer=opt) >>> net, opt = flat_mods.model,",
"... x = jax.nn.relu(fc(x)) ... return x ... ... >>>",
"if hasattr(self.func.fun, \"__name__\"): name = self.func.fun.__name__ else: name = f\"{self.func.fun}\"",
"when needed. Example: >>> from dataclasses import dataclass >>> @dataclass",
"jax.nn.relu(fc(x)) ... return x ... ... >>> mlp, _ =",
"self.treedef_dict[name] = treedef self.leaves_dict[name] = leaves def __getattr__(self, name: str)",
"a module that only creates submodules when needed. Example: >>>",
"parameters_method T = TypeVar(\"T\", bound=Module) O = TypeVar(\"O\") class ParameterModule(Module):",
"\"\"\" func: Callable def __init__(self, func: Callable, name: Optional[str] =",
"new flattener.\"\"\" super().__init__() self.treedef_dict = {} self.leaves_dict = {} for",
"= None): super().__init__(name=name) self.func = func def __call__(self, *args, **kwargs):",
"get_or_create(self, name, create_fn: Callable[[], T]) -> T: \"\"\"Create and register",
"flattener only stores ndarray leaves as non-trainable states.\\n\" \"Reconstruct the",
"\"\"\" new_self = self.copy() for name, value in kwargs.items(): leaves,",
"Linear(in_dim=3, out_dim=3, with_bias=True) └── scale.<locals>.Scale \"\"\" treedef_dict: Dict[str, Any] leaves_dict:",
"return super().__repr__() else: return f\"{self.__class__.__qualname__}({self.func.__name__})\" def summary(self, return_list: bool =",
"self.get_or_create(f\"fc_{i}\", lambda: pax.Linear(in_dim, out_dim)) ... x = jax.nn.relu(fc(x)) ... return",
"Union import jax import jax.numpy as jnp from .module import",
">>> print(mlp.summary()) MLP(features=[1, 2, 3]) ├── Linear(in_dim=1, out_dim=2, with_bias=True) └──",
"│ └── Linear(in_dim=3, out_dim=3, with_bias=True) └── scale.<locals>.Scale \"\"\" treedef_dict: Dict[str,",
"T = TypeVar(\"T\", bound=Module) O = TypeVar(\"O\") class ParameterModule(Module): \"\"\"A",
"registers attributes as parameters by default.\"\"\" def parameters(self): return self.apply_submodules(lambda",
">>> from dataclasses import dataclass >>> @dataclass ... class MLP(pax.experimental.LazyModule):",
"print(mlp.summary()) MLP(features=[1, 2, 3]) ├── Linear(in_dim=1, out_dim=2, with_bias=True) └── Linear(in_dim=2,",
"= treedef new_self.leaves_dict[name] = leaves return new_self def parameters(self: T)",
"not None: return super().__repr__() else: return f\"{self.__class__.__qualname__}({self.func.__name__})\" def summary(self, return_list:",
"= pax.experimental.Flattener(model=net, optimizer=opt) >>> net, opt = flat_mods.model, flat_mods.optimizer >>>",
"module before getting parameters. \"\"\" raise ValueError( \"A flattener only",
"x: x.parameters()) class StateModule(Module): \"\"\"A PAX module that registers attributes",
"parameters by default.\"\"\" def parameters(self): return self.apply_submodules(lambda x: x.parameters()) class",
"default.\"\"\" parameters = parameters_method() class LazyModule(Module): \"\"\"A lazy module is",
"callable(create_fn), \"Expect a callable function\" value = create_fn() setattr(self, name,",
"__init__(self, **kwargs): \"\"\"Create a new flattener.\"\"\" super().__init__() self.treedef_dict = {}",
"is not None: return super().__repr__() else: return f\"{self.__class__.__qualname__}({self.func.__name__})\" def summary(self,",
"kwargs.items(): leaves, treedef = jax.tree_flatten(value) self.treedef_dict[name] = treedef self.leaves_dict[name] =",
"value = getattr(self, name) else: assert callable(create_fn), \"Expect a callable",
"features: list ... ... def __call__(self, x): ... sizes =",
"print(net.summary()) Linear(in_dim=3, out_dim=3, with_bias=True) >>> print(opt.summary()) chain.<locals>.Chain ├── scale_by_adam.<locals>.ScaleByAdam │",
"leaves as non-trainable states.\\n\" \"Reconstruct the original module before getting",
"self.treedef_dict: treedef = self.treedef_dict[name] leaves = self.leaves_dict[name] value = jax.tree_unflatten(treedef,",
"Dict[str, Any] leaves_dict: Dict[str, Sequence[jnp.ndarray]] def __init__(self, **kwargs): \"\"\"Create a",
"self.name elif isinstance(self.func, jax.custom_jvp) and hasattr(self.func, \"fun\"): if hasattr(self.func.fun, \"__name__\"):",
"import jax.numpy as jnp from .module import Module, parameters_method T",
"\"__name__\"): name = self.func.__name__ else: name = f\"{self.func}\" output =",
"import dataclass >>> @dataclass ... class MLP(pax.experimental.LazyModule): ... features: list",
"... return x ... ... >>> mlp, _ = MLP([1,",
"typing import Any, Callable, Dict, List, Optional, Sequence, TypeVar, Union",
"in enumerate(sizes): ... fc = self.get_or_create(f\"fc_{i}\", lambda: pax.Linear(in_dim, out_dim)) ...",
"flat_mods.model, flat_mods.optimizer >>> print(net.summary()) Linear(in_dim=3, out_dim=3, with_bias=True) >>> print(opt.summary()) chain.<locals>.Chain",
"└── scale.<locals>.Scale \"\"\" treedef_dict: Dict[str, Any] leaves_dict: Dict[str, Sequence[jnp.ndarray]] def",
"super().__init__() self.treedef_dict = {} self.leaves_dict = {} for name, value",
"\"Expect a callable function\" value = create_fn() setattr(self, name, value)",
"name = self.name elif isinstance(self.func, jax.custom_jvp) and hasattr(self.func, \"fun\"): if",
"an error. Need to reconstruct the original module before getting",
"... ... def __call__(self, x): ... sizes = zip(self.features[:-1], self.features[1:])",
"\"\"\"A PAX module that registers attributes as states by default.\"\"\"",
"when it is not exist. Return the attribute. \"\"\" if",
"a new attribute when it is not exist. Return the",
"Callable def __init__(self, func: Callable, name: Optional[str] = None): super().__init__(name=name)",
"print(flats.net.summary()) Linear(in_dim=4, out_dim=4, with_bias=True) \"\"\" new_self = self.copy() for name,",
"... fc = self.get_or_create(f\"fc_{i}\", lambda: pax.Linear(in_dim, out_dim)) ... x =",
"with_bias=True) └── Linear(in_dim=2, out_dim=3, with_bias=True) \"\"\" def get_or_create(self, name, create_fn:",
"= net(jnp.array(-1)) >>> y DeviceArray(0, dtype=int32, weak_type=True) \"\"\" func: Callable",
"flats = flats.update(net=pax.Linear(4, 4)) >>> print(flats.net.summary()) Linear(in_dim=4, out_dim=4, with_bias=True) \"\"\"",
"name, value) return value class Lambda(Module): \"\"\"Convert a function to",
"jax.tree_flatten(value) new_self.treedef_dict[name] = treedef new_self.leaves_dict[name] = leaves return new_self def",
"fc = self.get_or_create(f\"fc_{i}\", lambda: pax.Linear(in_dim, out_dim)) ... x = jax.nn.relu(fc(x))",
"= jax.tree_unflatten(treedef, leaves) return value else: raise AttributeError() def update(self:",
"= {} for name, value in kwargs.items(): leaves, treedef =",
"ValueError( \"A flattener only stores ndarray leaves as non-trainable states.\\n\"",
"jnp.ones((1, 1)) >>> print(mlp.summary()) MLP(features=[1, 2, 3]) ├── Linear(in_dim=1, out_dim=2,",
"def parameters(self): return self.apply_submodules(lambda x: x.parameters()) class StateModule(Module): \"\"\"A PAX",
"... def __call__(self, x): ... sizes = zip(self.features[:-1], self.features[1:]) ...",
">>> opt = opax.adam(1e-3)(net.parameters()) >>> flat_mods = pax.experimental.Flattener(model=net, optimizer=opt) >>>",
"name): value = getattr(self, name) else: assert callable(create_fn), \"Expect a",
"= self.get_or_create(f\"fc_{i}\", lambda: pax.Linear(in_dim, out_dim)) ... x = jax.nn.relu(fc(x)) ...",
"**kwargs) def __repr__(self) -> str: if self.name is not None:",
"getting parameters. \"\"\" raise ValueError( \"A flattener only stores ndarray",
"DeviceArray(0, dtype=int32, weak_type=True) \"\"\" func: Callable def __init__(self, func: Callable,",
">>> mlp, _ = MLP([1, 2, 3]) % jnp.ones((1, 1))",
"T]) -> T: \"\"\"Create and register a new attribute when",
"opt = flat_mods.model, flat_mods.optimizer >>> print(net.summary()) Linear(in_dim=3, out_dim=3, with_bias=True) >>>",
"with_bias=True) └── scale.<locals>.Scale \"\"\" treedef_dict: Dict[str, Any] leaves_dict: Dict[str, Sequence[jnp.ndarray]]",
"name: str) -> Any: if name in self.treedef_dict: treedef =",
".module import Module, parameters_method T = TypeVar(\"T\", bound=Module) O =",
"a module. Example: >>> net = pax.Lambda(jax.nn.relu) >>> print(net.summary()) x",
"Flattener(Module): \"\"\"Flatten PAX modules for better performance. Example: >>> net",
"def __init__(self, **kwargs): \"\"\"Create a new flattener.\"\"\" super().__init__() self.treedef_dict =",
"enumerate(sizes): ... fc = self.get_or_create(f\"fc_{i}\", lambda: pax.Linear(in_dim, out_dim)) ... x",
"f\"x => {name}(x)\" return [output] if return_list else output class",
"Linear(in_dim=3, out_dim=3, with_bias=True) │ └── Linear(in_dim=3, out_dim=3, with_bias=True) └── scale.<locals>.Scale",
"\"\"\" treedef_dict: Dict[str, Any] leaves_dict: Dict[str, Sequence[jnp.ndarray]] def __init__(self, **kwargs):",
"= getattr(self, name) else: assert callable(create_fn), \"Expect a callable function\"",
"attribute. \"\"\" if hasattr(self, name): value = getattr(self, name) else:",
"a function to a module. Example: >>> net = pax.Lambda(jax.nn.relu)",
"str) -> Any: if name in self.treedef_dict: treedef = self.treedef_dict[name]",
">>> print(net.summary()) x => relu(x) >>> y = net(jnp.array(-1)) >>>",
"f\"{self.func}\" output = f\"x => {name}(x)\" return [output] if return_list",
"None: name = self.name elif isinstance(self.func, jax.custom_jvp) and hasattr(self.func, \"fun\"):",
"Any] leaves_dict: Dict[str, Sequence[jnp.ndarray]] def __init__(self, **kwargs): \"\"\"Create a new",
"self.func.fun.__name__ else: name = f\"{self.func.fun}\" elif hasattr(self.func, \"__name__\"): name =",
"out_dim=4, with_bias=True) \"\"\" new_self = self.copy() for name, value in",
"hasattr(self.func, \"fun\"): if hasattr(self.func.fun, \"__name__\"): name = self.func.fun.__name__ else: name",
"weak_type=True) \"\"\" func: Callable def __init__(self, func: Callable, name: Optional[str]",
"f\"{self.__class__.__qualname__}({self.func.__name__})\" def summary(self, return_list: bool = False) -> Union[str, List[str]]:",
"not exist. Return the attribute. \"\"\" if hasattr(self, name): value",
"class Flattener(Module): \"\"\"Flatten PAX modules for better performance. Example: >>>",
">>> print(opt.summary()) chain.<locals>.Chain ├── scale_by_adam.<locals>.ScaleByAdam │ ├── Linear(in_dim=3, out_dim=3, with_bias=True)",
"from typing import Any, Callable, Dict, List, Optional, Sequence, TypeVar,",
"is not None: name = self.name elif isinstance(self.func, jax.custom_jvp) and",
"TypeVar(\"O\") class ParameterModule(Module): \"\"\"A PAX module that registers attributes as",
"Sequence[jnp.ndarray]] def __init__(self, **kwargs): \"\"\"Create a new flattener.\"\"\" super().__init__() self.treedef_dict",
"function to a module. Example: >>> net = pax.Lambda(jax.nn.relu) >>>",
"Linear(in_dim=1, out_dim=2, with_bias=True) └── Linear(in_dim=2, out_dim=3, with_bias=True) \"\"\" def get_or_create(self,",
"parameters = parameters_method() class LazyModule(Module): \"\"\"A lazy module is a",
"out_dim) in enumerate(sizes): ... fc = self.get_or_create(f\"fc_{i}\", lambda: pax.Linear(in_dim, out_dim))",
"relu(x) >>> y = net(jnp.array(-1)) >>> y DeviceArray(0, dtype=int32, weak_type=True)",
"= self.func.__name__ else: name = f\"{self.func}\" output = f\"x =>",
"= jax.nn.relu(fc(x)) ... return x ... ... >>> mlp, _",
"T) -> T: \"\"\"Raise an error. Need to reconstruct the",
"\"\"\" def get_or_create(self, name, create_fn: Callable[[], T]) -> T: \"\"\"Create",
"that only creates submodules when needed. Example: >>> from dataclasses",
"self.apply_submodules(lambda x: x.parameters()) class StateModule(Module): \"\"\"A PAX module that registers",
"def get_or_create(self, name, create_fn: Callable[[], T]) -> T: \"\"\"Create and",
"print(opt.summary()) chain.<locals>.Chain ├── scale_by_adam.<locals>.ScaleByAdam │ ├── Linear(in_dim=3, out_dim=3, with_bias=True) │",
"only creates submodules when needed. Example: >>> from dataclasses import",
"2, 3]) ├── Linear(in_dim=1, out_dim=2, with_bias=True) └── Linear(in_dim=2, out_dim=3, with_bias=True)",
"jnp from .module import Module, parameters_method T = TypeVar(\"T\", bound=Module)",
"by default.\"\"\" def parameters(self): return self.apply_submodules(lambda x: x.parameters()) class StateModule(Module):",
"reconstruct the original module before getting parameters. \"\"\" raise ValueError(",
"return_list else output class Flattener(Module): \"\"\"Flatten PAX modules for better",
"return [output] if return_list else output class Flattener(Module): \"\"\"Flatten PAX",
"flat_mods.optimizer >>> print(net.summary()) Linear(in_dim=3, out_dim=3, with_bias=True) >>> print(opt.summary()) chain.<locals>.Chain ├──",
"**kwargs) -> T: \"\"\"Update the flattener. Example: >>> net =",
"Linear(in_dim=3, out_dim=3, with_bias=True) >>> print(opt.summary()) chain.<locals>.Chain ├── scale_by_adam.<locals>.ScaleByAdam │ ├──",
"leaves def __getattr__(self, name: str) -> Any: if name in",
"└── Linear(in_dim=3, out_dim=3, with_bias=True) └── scale.<locals>.Scale \"\"\" treedef_dict: Dict[str, Any]",
"kwargs.items(): leaves, treedef = jax.tree_flatten(value) new_self.treedef_dict[name] = treedef new_self.leaves_dict[name] =",
"value) return value class Lambda(Module): \"\"\"Convert a function to a",
"out_dim=3, with_bias=True) >>> print(opt.summary()) chain.<locals>.Chain ├── scale_by_adam.<locals>.ScaleByAdam │ ├── Linear(in_dim=3,",
"registers attributes as states by default.\"\"\" parameters = parameters_method() class",
"in kwargs.items(): leaves, treedef = jax.tree_flatten(value) new_self.treedef_dict[name] = treedef new_self.leaves_dict[name]",
"= TypeVar(\"O\") class ParameterModule(Module): \"\"\"A PAX module that registers attributes",
"= self.treedef_dict[name] leaves = self.leaves_dict[name] value = jax.tree_unflatten(treedef, leaves) return",
"import Module, parameters_method T = TypeVar(\"T\", bound=Module) O = TypeVar(\"O\")",
"name, create_fn: Callable[[], T]) -> T: \"\"\"Create and register a",
"Need to reconstruct the original module before getting parameters. \"\"\"",
"as parameters by default.\"\"\" def parameters(self): return self.apply_submodules(lambda x: x.parameters())",
"if hasattr(self, name): value = getattr(self, name) else: assert callable(create_fn),",
"the attribute. \"\"\" if hasattr(self, name): value = getattr(self, name)",
"\"\"\"A PAX module that registers attributes as parameters by default.\"\"\"",
"the original module before getting parameters. \"\"\" raise ValueError( \"A",
"exist. Return the attribute. \"\"\" if hasattr(self, name): value =",
"Sequence, TypeVar, Union import jax import jax.numpy as jnp from",
"modules for better performance. Example: >>> net = pax.Linear(3, 3)",
"opt = opax.adam(1e-3)(net.parameters()) >>> flat_mods = pax.experimental.Flattener(model=net, optimizer=opt) >>> net,",
"= MLP([1, 2, 3]) % jnp.ones((1, 1)) >>> print(mlp.summary()) MLP(features=[1,",
"PAX module that registers attributes as states by default.\"\"\" parameters",
"return_list: bool = False) -> Union[str, List[str]]: if self.name is",
"list ... ... def __call__(self, x): ... sizes = zip(self.features[:-1],",
"=> relu(x) >>> y = net(jnp.array(-1)) >>> y DeviceArray(0, dtype=int32,",
"3) >>> opt = opax.adam(1e-3)(net.parameters()) >>> flat_mods = pax.experimental.Flattener(model=net, optimizer=opt)",
"jax.numpy as jnp from .module import Module, parameters_method T =",
"**kwargs): \"\"\"Create a new flattener.\"\"\" super().__init__() self.treedef_dict = {} self.leaves_dict",
"_ = MLP([1, 2, 3]) % jnp.ones((1, 1)) >>> print(mlp.summary())",
"x.parameters()) class StateModule(Module): \"\"\"A PAX module that registers attributes as",
"__repr__(self) -> str: if self.name is not None: return super().__repr__()",
"if self.name is not None: return super().__repr__() else: return f\"{self.__class__.__qualname__}({self.func.__name__})\"",
"\"\"\"Update the flattener. Example: >>> net = pax.Linear(3, 3) >>>",
"PAX module that registers attributes as parameters by default.\"\"\" def",
"__call__(self, *args, **kwargs): return self.func(*args, **kwargs) def __repr__(self) -> str:",
"getattr(self, name) else: assert callable(create_fn), \"Expect a callable function\" value",
"return new_self def parameters(self: T) -> T: \"\"\"Raise an error.",
"sizes = zip(self.features[:-1], self.features[1:]) ... for i, (in_dim, out_dim) in",
"if return_list else output class Flattener(Module): \"\"\"Flatten PAX modules for",
"scale.<locals>.Scale \"\"\" treedef_dict: Dict[str, Any] leaves_dict: Dict[str, Sequence[jnp.ndarray]] def __init__(self,",
"None: return super().__repr__() else: return f\"{self.__class__.__qualname__}({self.func.__name__})\" def summary(self, return_list: bool",
"= self.name elif isinstance(self.func, jax.custom_jvp) and hasattr(self.func, \"fun\"): if hasattr(self.func.fun,",
"self.func(*args, **kwargs) def __repr__(self) -> str: if self.name is not",
"treedef self.leaves_dict[name] = leaves def __getattr__(self, name: str) -> Any:",
"to a module. Example: >>> net = pax.Lambda(jax.nn.relu) >>> print(net.summary())",
">>> print(flats.net.summary()) Linear(in_dim=4, out_dim=4, with_bias=True) \"\"\" new_self = self.copy() for",
"__getattr__(self, name: str) -> Any: if name in self.treedef_dict: treedef",
"class MLP(pax.experimental.LazyModule): ... features: list ... ... def __call__(self, x):",
"T: \"\"\"Raise an error. Need to reconstruct the original module",
"x => relu(x) >>> y = net(jnp.array(-1)) >>> y DeviceArray(0,",
"pax.experimental.Flattener(model=net, optimizer=opt) >>> net, opt = flat_mods.model, flat_mods.optimizer >>> print(net.summary())",
"class ParameterModule(Module): \"\"\"A PAX module that registers attributes as parameters",
"super().__repr__() else: return f\"{self.__class__.__qualname__}({self.func.__name__})\" def summary(self, return_list: bool = False)",
"output = f\"x => {name}(x)\" return [output] if return_list else",
"LazyModule(Module): \"\"\"A lazy module is a module that only creates",
"= zip(self.features[:-1], self.features[1:]) ... for i, (in_dim, out_dim) in enumerate(sizes):",
"4)) >>> print(flats.net.summary()) Linear(in_dim=4, out_dim=4, with_bias=True) \"\"\" new_self = self.copy()",
">>> net, opt = flat_mods.model, flat_mods.optimizer >>> print(net.summary()) Linear(in_dim=3, out_dim=3,",
"def summary(self, return_list: bool = False) -> Union[str, List[str]]: if",
"default.\"\"\" def parameters(self): return self.apply_submodules(lambda x: x.parameters()) class StateModule(Module): \"\"\"A",
"= parameters_method() class LazyModule(Module): \"\"\"A lazy module is a module",
"new_self = self.copy() for name, value in kwargs.items(): leaves, treedef",
"value class Lambda(Module): \"\"\"Convert a function to a module. Example:",
"isinstance(self.func, jax.custom_jvp) and hasattr(self.func, \"fun\"): if hasattr(self.func.fun, \"__name__\"): name =",
"hasattr(self, name): value = getattr(self, name) else: assert callable(create_fn), \"Expect",
"else output class Flattener(Module): \"\"\"Flatten PAX modules for better performance.",
"function\" value = create_fn() setattr(self, name, value) return value class",
"% jnp.ones((1, 1)) >>> print(mlp.summary()) MLP(features=[1, 2, 3]) ├── Linear(in_dim=1,",
"TypeVar(\"T\", bound=Module) O = TypeVar(\"O\") class ParameterModule(Module): \"\"\"A PAX module",
"is not exist. Return the attribute. \"\"\" if hasattr(self, name):",
">>> flats = flats.update(net=pax.Linear(4, 4)) >>> print(flats.net.summary()) Linear(in_dim=4, out_dim=4, with_bias=True)",
"new_self.treedef_dict[name] = treedef new_self.leaves_dict[name] = leaves return new_self def parameters(self:",
"only stores ndarray leaves as non-trainable states.\\n\" \"Reconstruct the original",
"leaves) return value else: raise AttributeError() def update(self: T, **kwargs)",
"Modules.\"\"\" from typing import Any, Callable, Dict, List, Optional, Sequence,",
"x): ... sizes = zip(self.features[:-1], self.features[1:]) ... for i, (in_dim,",
"out_dim)) ... x = jax.nn.relu(fc(x)) ... return x ... ...",
"return value class Lambda(Module): \"\"\"Convert a function to a module.",
">>> net = pax.Linear(3, 3) >>> flats = pax.experimental.Flattener(net=net) >>>",
"├── Linear(in_dim=1, out_dim=2, with_bias=True) └── Linear(in_dim=2, out_dim=3, with_bias=True) \"\"\" def",
"= pax.experimental.Flattener(net=net) >>> flats = flats.update(net=pax.Linear(4, 4)) >>> print(flats.net.summary()) Linear(in_dim=4,",
"\"\"\" if hasattr(self, name): value = getattr(self, name) else: assert",
"bound=Module) O = TypeVar(\"O\") class ParameterModule(Module): \"\"\"A PAX module that",
"callable function\" value = create_fn() setattr(self, name, value) return value",
"class Lambda(Module): \"\"\"Convert a function to a module. Example: >>>",
"that registers attributes as parameters by default.\"\"\" def parameters(self): return",
"self.features[1:]) ... for i, (in_dim, out_dim) in enumerate(sizes): ... fc",
"str: if self.name is not None: return super().__repr__() else: return",
"├── Linear(in_dim=3, out_dim=3, with_bias=True) │ └── Linear(in_dim=3, out_dim=3, with_bias=True) └──",
"register a new attribute when it is not exist. Return",
"-> T: \"\"\"Update the flattener. Example: >>> net = pax.Linear(3,",
"T: \"\"\"Create and register a new attribute when it is",
"class StateModule(Module): \"\"\"A PAX module that registers attributes as states",
"new attribute when it is not exist. Return the attribute.",
"dtype=int32, weak_type=True) \"\"\" func: Callable def __init__(self, func: Callable, name:",
"in self.treedef_dict: treedef = self.treedef_dict[name] leaves = self.leaves_dict[name] value =",
"x ... ... >>> mlp, _ = MLP([1, 2, 3])",
"= create_fn() setattr(self, name, value) return value class Lambda(Module): \"\"\"Convert",
"leaves, treedef = jax.tree_flatten(value) new_self.treedef_dict[name] = treedef new_self.leaves_dict[name] = leaves",
"\"__name__\"): name = self.func.fun.__name__ else: name = f\"{self.func.fun}\" elif hasattr(self.func,",
"with_bias=True) \"\"\" def get_or_create(self, name, create_fn: Callable[[], T]) -> T:",
"return self.func(*args, **kwargs) def __repr__(self) -> str: if self.name is",
">>> y DeviceArray(0, dtype=int32, weak_type=True) \"\"\" func: Callable def __init__(self,",
"y DeviceArray(0, dtype=int32, weak_type=True) \"\"\" func: Callable def __init__(self, func:",
"as jnp from .module import Module, parameters_method T = TypeVar(\"T\",",
"pax.Lambda(jax.nn.relu) >>> print(net.summary()) x => relu(x) >>> y = net(jnp.array(-1))",
"parameters. \"\"\" raise ValueError( \"A flattener only stores ndarray leaves",
"... sizes = zip(self.features[:-1], self.features[1:]) ... for i, (in_dim, out_dim)",
"name = f\"{self.func.fun}\" elif hasattr(self.func, \"__name__\"): name = self.func.__name__ else:",
"-> Union[str, List[str]]: if self.name is not None: name =",
"-> T: \"\"\"Create and register a new attribute when it",
"super().__init__(name=name) self.func = func def __call__(self, *args, **kwargs): return self.func(*args,",
"Dict[str, Sequence[jnp.ndarray]] def __init__(self, **kwargs): \"\"\"Create a new flattener.\"\"\" super().__init__()",
"for name, value in kwargs.items(): leaves, treedef = jax.tree_flatten(value) self.treedef_dict[name]",
"non-trainable states.\\n\" \"Reconstruct the original module before getting parameters.\" )",
"self.leaves_dict[name] = leaves def __getattr__(self, name: str) -> Any: if",
"flattener. Example: >>> net = pax.Linear(3, 3) >>> flats =",
"treedef = self.treedef_dict[name] leaves = self.leaves_dict[name] value = jax.tree_unflatten(treedef, leaves)",
"hasattr(self.func, \"__name__\"): name = self.func.__name__ else: name = f\"{self.func}\" output",
"out_dim=3, with_bias=True) └── scale.<locals>.Scale \"\"\" treedef_dict: Dict[str, Any] leaves_dict: Dict[str,",
"= f\"x => {name}(x)\" return [output] if return_list else output",
"func: Callable, name: Optional[str] = None): super().__init__(name=name) self.func = func",
"= False) -> Union[str, List[str]]: if self.name is not None:",
"performance. Example: >>> net = pax.Linear(3, 3) >>> opt =",
"@dataclass ... class MLP(pax.experimental.LazyModule): ... features: list ... ... def",
"1)) >>> print(mlp.summary()) MLP(features=[1, 2, 3]) ├── Linear(in_dim=1, out_dim=2, with_bias=True)",
"attribute when it is not exist. Return the attribute. \"\"\"",
"= TypeVar(\"T\", bound=Module) O = TypeVar(\"O\") class ParameterModule(Module): \"\"\"A PAX",
"Callable[[], T]) -> T: \"\"\"Create and register a new attribute",
"-> Any: if name in self.treedef_dict: treedef = self.treedef_dict[name] leaves",
"= leaves return new_self def parameters(self: T) -> T: \"\"\"Raise",
"submodules when needed. Example: >>> from dataclasses import dataclass >>>",
"with_bias=True) │ └── Linear(in_dim=3, out_dim=3, with_bias=True) └── scale.<locals>.Scale \"\"\" treedef_dict:",
"treedef new_self.leaves_dict[name] = leaves return new_self def parameters(self: T) ->",
"hasattr(self.func.fun, \"__name__\"): name = self.func.fun.__name__ else: name = f\"{self.func.fun}\" elif",
"by default.\"\"\" parameters = parameters_method() class LazyModule(Module): \"\"\"A lazy module",
"parameters(self: T) -> T: \"\"\"Raise an error. Need to reconstruct",
"else: assert callable(create_fn), \"Expect a callable function\" value = create_fn()",
"= flat_mods.model, flat_mods.optimizer >>> print(net.summary()) Linear(in_dim=3, out_dim=3, with_bias=True) >>> print(opt.summary())",
"... ... >>> mlp, _ = MLP([1, 2, 3]) %",
"def __init__(self, func: Callable, name: Optional[str] = None): super().__init__(name=name) self.func",
"lazy module is a module that only creates submodules when",
"as non-trainable states.\\n\" \"Reconstruct the original module before getting parameters.\"",
"Return the attribute. \"\"\" if hasattr(self, name): value = getattr(self,",
"else: name = f\"{self.func.fun}\" elif hasattr(self.func, \"__name__\"): name = self.func.__name__",
"net = pax.Linear(3, 3) >>> opt = opax.adam(1e-3)(net.parameters()) >>> flat_mods",
"output class Flattener(Module): \"\"\"Flatten PAX modules for better performance. Example:",
"value = create_fn() setattr(self, name, value) return value class Lambda(Module):",
"import Any, Callable, Dict, List, Optional, Sequence, TypeVar, Union import",
"{} self.leaves_dict = {} for name, value in kwargs.items(): leaves,",
">>> net = pax.Linear(3, 3) >>> opt = opax.adam(1e-3)(net.parameters()) >>>",
"name = self.func.__name__ else: name = f\"{self.func}\" output = f\"x",
"ndarray leaves as non-trainable states.\\n\" \"Reconstruct the original module before",
"leaves return new_self def parameters(self: T) -> T: \"\"\"Raise an",
"\"\"\"Create and register a new attribute when it is not",
"__call__(self, x): ... sizes = zip(self.features[:-1], self.features[1:]) ... for i,",
"summary(self, return_list: bool = False) -> Union[str, List[str]]: if self.name",
"\"\"\"Create a new flattener.\"\"\" super().__init__() self.treedef_dict = {} self.leaves_dict =",
"module that only creates submodules when needed. Example: >>> from",
"self.leaves_dict[name] value = jax.tree_unflatten(treedef, leaves) return value else: raise AttributeError()",
"\"\"\"A lazy module is a module that only creates submodules",
"self.treedef_dict = {} self.leaves_dict = {} for name, value in",
"bool = False) -> Union[str, List[str]]: if self.name is not",
"Linear(in_dim=4, out_dim=4, with_bias=True) \"\"\" new_self = self.copy() for name, value"
] |
[
"def split_course_key(key): \"\"\"Split an OpenEdX course key by organization, course",
"given Request object.\"\"\" def __init__(self, token): \"\"\"Set-up token value in",
":class:`requests.Session` that automatically authenticates against edX's preferred authentication method up",
"import logging import re import requests from requests.auth import AuthBase",
"\"\"\" def __init__(self, token, *args, **kwargs): \"\"\"Extending the session object",
"course run url.\"\"\" return re.match(self.configuration[\"COURSE_REGEX\"], url).group(\"course_id\") def extract_course_number(self, data): \"\"\"Extract",
"\"\"\" import logging import re import requests from requests.auth import",
"(org/course/run). \"\"\" if key.startswith(\"course-v1:\"): organization, course, run = key[10:].split(\"+\") else:",
"an OpenEdX course key by organization, course and course run",
"edx token API client.\"\"\" return TokenAPIClient(self.configuration[\"API_TOKEN\"]) def extract_course_id(self, url): \"\"\"Extract",
"against edX's preferred authentication method up to Dogwood, given a",
"import BaseLMSBackend logger = logging.getLogger(__name__) def split_course_key(key): \"\"\"Split an OpenEdX",
"self.auth = EdXTokenAuth(token) class EdXLMSBackend(BaseLMSBackend): \"\"\"LMS backend for Richie tested",
"data): \"\"\"Extract the LMS course number from data dictionary.\"\"\" course_id",
"EdXTokenAuth(AuthBase): \"\"\"Attach HTTP token authentication to the given Request object.\"\"\"",
"\"application/json\"} ) return request class TokenAPIClient(requests.Session): \"\"\" A :class:`requests.Session` that",
".base import BaseLMSBackend logger = logging.getLogger(__name__) def split_course_key(key): \"\"\"Split an",
"object.\"\"\" def __init__(self, token): \"\"\"Set-up token value in the instance.\"\"\"",
"{\"X-Edx-Api-Key\": self.token, \"Content-Type\": \"application/json\"} ) return request class TokenAPIClient(requests.Session): \"\"\"",
"__init__(self, token, *args, **kwargs): \"\"\"Extending the session object by setting",
"token authentication to the given Request object.\"\"\" def __init__(self, token):",
"partial=False): \"\"\"Prepare data and return a bound serializer.\"\"\" return SyncCourseRunSerializer(data=data,",
"logger = logging.getLogger(__name__) def split_course_key(key): \"\"\"Split an OpenEdX course key",
"\"\"\" Backend to connect Open edX richie with an LMS",
"edX's preferred authentication method up to Dogwood, given a secret",
"up to Dogwood, given a secret token. For more usage",
"def __init__(self, token): \"\"\"Set-up token value in the instance.\"\"\" self.token",
"course_id = self.extract_course_id(data.get(\"resource_link\")) return split_course_key(course_id)[1] @staticmethod def get_course_run_serializer(data, partial=False): \"\"\"Prepare",
"return request class TokenAPIClient(requests.Session): \"\"\" A :class:`requests.Session` that automatically authenticates",
"the session object by setting the authentication token.\"\"\" super().__init__(*args, **kwargs)",
"client.\"\"\" return TokenAPIClient(self.configuration[\"API_TOKEN\"]) def extract_course_id(self, url): \"\"\"Extract the LMS course",
"organization, course, run = key[10:].split(\"+\") else: organization, course, run =",
"from ..serializers import SyncCourseRunSerializer from .base import BaseLMSBackend logger =",
"from data dictionary.\"\"\" course_id = self.extract_course_id(data.get(\"resource_link\")) return split_course_key(course_id)[1] @staticmethod def",
"return the request.\"\"\" request.headers.update( {\"X-Edx-Api-Key\": self.token, \"Content-Type\": \"application/json\"} ) return",
"EdX Dogwood to Hawthorn.\"\"\" @property def api_client(self): \"\"\"Instantiate and return",
"requests from requests.auth import AuthBase from ..serializers import SyncCourseRunSerializer from",
"object by setting the authentication token.\"\"\" super().__init__(*args, **kwargs) self.auth =",
"Dogwood, given a secret token. For more usage details, see",
"to connect Open edX richie with an LMS \"\"\" import",
"version 1 key (course-v1:org+course+run) and fallback the old version (org/course/run).",
"with Open EdX Dogwood to Hawthorn.\"\"\" @property def api_client(self): \"\"\"Instantiate",
"of the :class:`requests.Session` object: https://requests.readthedocs.io/en/master/user/advanced/#session-objects \"\"\" def __init__(self, token, *args,",
"authentication token.\"\"\" super().__init__(*args, **kwargs) self.auth = EdXTokenAuth(token) class EdXLMSBackend(BaseLMSBackend): \"\"\"LMS",
"data dictionary.\"\"\" course_id = self.extract_course_id(data.get(\"resource_link\")) return split_course_key(course_id)[1] @staticmethod def get_course_run_serializer(data,",
"LMS course id from the course run url.\"\"\" return re.match(self.configuration[\"COURSE_REGEX\"],",
"def __call__(self, request): \"\"\"Modify and return the request.\"\"\" request.headers.update( {\"X-Edx-Api-Key\":",
"**kwargs) self.auth = EdXTokenAuth(token) class EdXLMSBackend(BaseLMSBackend): \"\"\"LMS backend for Richie",
"course, run = key.split(\"/\") return organization, course, run class EdXTokenAuth(AuthBase):",
"__call__(self, request): \"\"\"Modify and return the request.\"\"\" request.headers.update( {\"X-Edx-Api-Key\": self.token,",
"get_course_run_serializer(data, partial=False): \"\"\"Prepare data and return a bound serializer.\"\"\" return",
"authenticates against edX's preferred authentication method up to Dogwood, given",
"the old version (org/course/run). \"\"\" if key.startswith(\"course-v1:\"): organization, course, run",
"\"\"\"LMS backend for Richie tested with Open EdX Dogwood to",
"HTTP token authentication to the given Request object.\"\"\" def __init__(self,",
"token. For more usage details, see documentation of the :class:`requests.Session`",
"for Richie tested with Open EdX Dogwood to Hawthorn.\"\"\" @property",
"and return an edx token API client.\"\"\" return TokenAPIClient(self.configuration[\"API_TOKEN\"]) def",
"= token def __call__(self, request): \"\"\"Modify and return the request.\"\"\"",
"in the instance.\"\"\" self.token = token def __call__(self, request): \"\"\"Modify",
"tested with Open EdX Dogwood to Hawthorn.\"\"\" @property def api_client(self):",
"if key.startswith(\"course-v1:\"): organization, course, run = key[10:].split(\"+\") else: organization, course,",
"the given Request object.\"\"\" def __init__(self, token): \"\"\"Set-up token value",
"return TokenAPIClient(self.configuration[\"API_TOKEN\"]) def extract_course_id(self, url): \"\"\"Extract the LMS course id",
"the LMS course id from the course run url.\"\"\" return",
"re import requests from requests.auth import AuthBase from ..serializers import",
"url).group(\"course_id\") def extract_course_number(self, data): \"\"\"Extract the LMS course number from",
"\"\"\" A :class:`requests.Session` that automatically authenticates against edX's preferred authentication",
"super().__init__(*args, **kwargs) self.auth = EdXTokenAuth(token) class EdXLMSBackend(BaseLMSBackend): \"\"\"LMS backend for",
"automatically authenticates against edX's preferred authentication method up to Dogwood,",
"authentication to the given Request object.\"\"\" def __init__(self, token): \"\"\"Set-up",
"class TokenAPIClient(requests.Session): \"\"\" A :class:`requests.Session` that automatically authenticates against edX's",
"preferred authentication method up to Dogwood, given a secret token.",
"old version (org/course/run). \"\"\" if key.startswith(\"course-v1:\"): organization, course, run =",
"\"\"\"Extending the session object by setting the authentication token.\"\"\" super().__init__(*args,",
"Hawthorn.\"\"\" @property def api_client(self): \"\"\"Instantiate and return an edx token",
"run url.\"\"\" return re.match(self.configuration[\"COURSE_REGEX\"], url).group(\"course_id\") def extract_course_number(self, data): \"\"\"Extract the",
"as a version 1 key (course-v1:org+course+run) and fallback the old",
"authentication method up to Dogwood, given a secret token. For",
"1 key (course-v1:org+course+run) and fallback the old version (org/course/run). \"\"\"",
"instance.\"\"\" self.token = token def __call__(self, request): \"\"\"Modify and return",
"\"\"\"Set-up token value in the instance.\"\"\" self.token = token def",
"method up to Dogwood, given a secret token. For more",
"return split_course_key(course_id)[1] @staticmethod def get_course_run_serializer(data, partial=False): \"\"\"Prepare data and return",
"\"\"\"Split an OpenEdX course key by organization, course and course",
"else: organization, course, run = key.split(\"/\") return organization, course, run",
"connect Open edX richie with an LMS \"\"\" import logging",
"TokenAPIClient(requests.Session): \"\"\" A :class:`requests.Session` that automatically authenticates against edX's preferred",
"object: https://requests.readthedocs.io/en/master/user/advanced/#session-objects \"\"\" def __init__(self, token, *args, **kwargs): \"\"\"Extending the",
"We first try splitting the key as a version 1",
"the key as a version 1 key (course-v1:org+course+run) and fallback",
"def extract_course_id(self, url): \"\"\"Extract the LMS course id from the",
"dictionary.\"\"\" course_id = self.extract_course_id(data.get(\"resource_link\")) return split_course_key(course_id)[1] @staticmethod def get_course_run_serializer(data, partial=False):",
"Backend to connect Open edX richie with an LMS \"\"\"",
"and return the request.\"\"\" request.headers.update( {\"X-Edx-Api-Key\": self.token, \"Content-Type\": \"application/json\"} )",
"the instance.\"\"\" self.token = token def __call__(self, request): \"\"\"Modify and",
"first try splitting the key as a version 1 key",
"class EdXLMSBackend(BaseLMSBackend): \"\"\"LMS backend for Richie tested with Open EdX",
"the authentication token.\"\"\" super().__init__(*args, **kwargs) self.auth = EdXTokenAuth(token) class EdXLMSBackend(BaseLMSBackend):",
"token def __call__(self, request): \"\"\"Modify and return the request.\"\"\" request.headers.update(",
"a version 1 key (course-v1:org+course+run) and fallback the old version",
"EdXTokenAuth(token) class EdXLMSBackend(BaseLMSBackend): \"\"\"LMS backend for Richie tested with Open",
"session object by setting the authentication token.\"\"\" super().__init__(*args, **kwargs) self.auth",
"**kwargs): \"\"\"Extending the session object by setting the authentication token.\"\"\"",
"that automatically authenticates against edX's preferred authentication method up to",
"token.\"\"\" super().__init__(*args, **kwargs) self.auth = EdXTokenAuth(token) class EdXLMSBackend(BaseLMSBackend): \"\"\"LMS backend",
"@staticmethod def get_course_run_serializer(data, partial=False): \"\"\"Prepare data and return a bound",
"to Dogwood, given a secret token. For more usage details,",
"def api_client(self): \"\"\"Instantiate and return an edx token API client.\"\"\"",
"A :class:`requests.Session` that automatically authenticates against edX's preferred authentication method",
"from .base import BaseLMSBackend logger = logging.getLogger(__name__) def split_course_key(key): \"\"\"Split",
"TokenAPIClient(self.configuration[\"API_TOKEN\"]) def extract_course_id(self, url): \"\"\"Extract the LMS course id from",
"Open edX richie with an LMS \"\"\" import logging import",
"Open EdX Dogwood to Hawthorn.\"\"\" @property def api_client(self): \"\"\"Instantiate and",
"course id from the course run url.\"\"\" return re.match(self.configuration[\"COURSE_REGEX\"], url).group(\"course_id\")",
"run = key.split(\"/\") return organization, course, run class EdXTokenAuth(AuthBase): \"\"\"Attach",
"token API client.\"\"\" return TokenAPIClient(self.configuration[\"API_TOKEN\"]) def extract_course_id(self, url): \"\"\"Extract the",
"to Hawthorn.\"\"\" @property def api_client(self): \"\"\"Instantiate and return an edx",
":class:`requests.Session` object: https://requests.readthedocs.io/en/master/user/advanced/#session-objects \"\"\" def __init__(self, token, *args, **kwargs): \"\"\"Extending",
"return organization, course, run class EdXTokenAuth(AuthBase): \"\"\"Attach HTTP token authentication",
"OpenEdX course key by organization, course and course run codes.",
"return re.match(self.configuration[\"COURSE_REGEX\"], url).group(\"course_id\") def extract_course_number(self, data): \"\"\"Extract the LMS course",
"run codes. We first try splitting the key as a",
"by organization, course and course run codes. We first try",
"value in the instance.\"\"\" self.token = token def __call__(self, request):",
"..serializers import SyncCourseRunSerializer from .base import BaseLMSBackend logger = logging.getLogger(__name__)",
"key.startswith(\"course-v1:\"): organization, course, run = key[10:].split(\"+\") else: organization, course, run",
"edX richie with an LMS \"\"\" import logging import re",
"request.\"\"\" request.headers.update( {\"X-Edx-Api-Key\": self.token, \"Content-Type\": \"application/json\"} ) return request class",
"the request.\"\"\" request.headers.update( {\"X-Edx-Api-Key\": self.token, \"Content-Type\": \"application/json\"} ) return request",
"secret token. For more usage details, see documentation of the",
"\"\"\"Prepare data and return a bound serializer.\"\"\" return SyncCourseRunSerializer(data=data, partial=partial)",
"the :class:`requests.Session` object: https://requests.readthedocs.io/en/master/user/advanced/#session-objects \"\"\" def __init__(self, token, *args, **kwargs):",
"from the course run url.\"\"\" return re.match(self.configuration[\"COURSE_REGEX\"], url).group(\"course_id\") def extract_course_number(self,",
"key.split(\"/\") return organization, course, run class EdXTokenAuth(AuthBase): \"\"\"Attach HTTP token",
"(course-v1:org+course+run) and fallback the old version (org/course/run). \"\"\" if key.startswith(\"course-v1:\"):",
"= key[10:].split(\"+\") else: organization, course, run = key.split(\"/\") return organization,",
"extract_course_number(self, data): \"\"\"Extract the LMS course number from data dictionary.\"\"\"",
"course key by organization, course and course run codes. We",
"Dogwood to Hawthorn.\"\"\" @property def api_client(self): \"\"\"Instantiate and return an",
"run class EdXTokenAuth(AuthBase): \"\"\"Attach HTTP token authentication to the given",
"\"\"\"Extract the LMS course number from data dictionary.\"\"\" course_id =",
"requests.auth import AuthBase from ..serializers import SyncCourseRunSerializer from .base import",
"import SyncCourseRunSerializer from .base import BaseLMSBackend logger = logging.getLogger(__name__) def",
"course, run class EdXTokenAuth(AuthBase): \"\"\"Attach HTTP token authentication to the",
"__init__(self, token): \"\"\"Set-up token value in the instance.\"\"\" self.token =",
"documentation of the :class:`requests.Session` object: https://requests.readthedocs.io/en/master/user/advanced/#session-objects \"\"\" def __init__(self, token,",
"the course run url.\"\"\" return re.match(self.configuration[\"COURSE_REGEX\"], url).group(\"course_id\") def extract_course_number(self, data):",
"by setting the authentication token.\"\"\" super().__init__(*args, **kwargs) self.auth = EdXTokenAuth(token)",
"API client.\"\"\" return TokenAPIClient(self.configuration[\"API_TOKEN\"]) def extract_course_id(self, url): \"\"\"Extract the LMS",
"AuthBase from ..serializers import SyncCourseRunSerializer from .base import BaseLMSBackend logger",
"\"\"\" if key.startswith(\"course-v1:\"): organization, course, run = key[10:].split(\"+\") else: organization,",
"\"\"\"Extract the LMS course id from the course run url.\"\"\"",
"usage details, see documentation of the :class:`requests.Session` object: https://requests.readthedocs.io/en/master/user/advanced/#session-objects \"\"\"",
"url.\"\"\" return re.match(self.configuration[\"COURSE_REGEX\"], url).group(\"course_id\") def extract_course_number(self, data): \"\"\"Extract the LMS",
"logging import re import requests from requests.auth import AuthBase from",
"richie with an LMS \"\"\" import logging import re import",
"split_course_key(key): \"\"\"Split an OpenEdX course key by organization, course and",
"import re import requests from requests.auth import AuthBase from ..serializers",
"logging.getLogger(__name__) def split_course_key(key): \"\"\"Split an OpenEdX course key by organization,",
"key by organization, course and course run codes. We first",
"run = key[10:].split(\"+\") else: organization, course, run = key.split(\"/\") return",
"class EdXTokenAuth(AuthBase): \"\"\"Attach HTTP token authentication to the given Request",
"an edx token API client.\"\"\" return TokenAPIClient(self.configuration[\"API_TOKEN\"]) def extract_course_id(self, url):",
"import requests from requests.auth import AuthBase from ..serializers import SyncCourseRunSerializer",
"extract_course_id(self, url): \"\"\"Extract the LMS course id from the course",
"the LMS course number from data dictionary.\"\"\" course_id = self.extract_course_id(data.get(\"resource_link\"))",
"an LMS \"\"\" import logging import re import requests from",
"try splitting the key as a version 1 key (course-v1:org+course+run)",
"organization, course, run class EdXTokenAuth(AuthBase): \"\"\"Attach HTTP token authentication to",
"organization, course, run = key.split(\"/\") return organization, course, run class",
"fallback the old version (org/course/run). \"\"\" if key.startswith(\"course-v1:\"): organization, course,",
"\"\"\"Instantiate and return an edx token API client.\"\"\" return TokenAPIClient(self.configuration[\"API_TOKEN\"])",
"more usage details, see documentation of the :class:`requests.Session` object: https://requests.readthedocs.io/en/master/user/advanced/#session-objects",
"https://requests.readthedocs.io/en/master/user/advanced/#session-objects \"\"\" def __init__(self, token, *args, **kwargs): \"\"\"Extending the session",
") return request class TokenAPIClient(requests.Session): \"\"\" A :class:`requests.Session` that automatically",
"request.headers.update( {\"X-Edx-Api-Key\": self.token, \"Content-Type\": \"application/json\"} ) return request class TokenAPIClient(requests.Session):",
"setting the authentication token.\"\"\" super().__init__(*args, **kwargs) self.auth = EdXTokenAuth(token) class",
"backend for Richie tested with Open EdX Dogwood to Hawthorn.\"\"\"",
"\"Content-Type\": \"application/json\"} ) return request class TokenAPIClient(requests.Session): \"\"\" A :class:`requests.Session`",
"api_client(self): \"\"\"Instantiate and return an edx token API client.\"\"\" return",
"to the given Request object.\"\"\" def __init__(self, token): \"\"\"Set-up token",
"def __init__(self, token, *args, **kwargs): \"\"\"Extending the session object by",
"request): \"\"\"Modify and return the request.\"\"\" request.headers.update( {\"X-Edx-Api-Key\": self.token, \"Content-Type\":",
"id from the course run url.\"\"\" return re.match(self.configuration[\"COURSE_REGEX\"], url).group(\"course_id\") def",
"SyncCourseRunSerializer from .base import BaseLMSBackend logger = logging.getLogger(__name__) def split_course_key(key):",
"request class TokenAPIClient(requests.Session): \"\"\" A :class:`requests.Session` that automatically authenticates against",
"= key.split(\"/\") return organization, course, run class EdXTokenAuth(AuthBase): \"\"\"Attach HTTP",
"version (org/course/run). \"\"\" if key.startswith(\"course-v1:\"): organization, course, run = key[10:].split(\"+\")",
"organization, course and course run codes. We first try splitting",
"re.match(self.configuration[\"COURSE_REGEX\"], url).group(\"course_id\") def extract_course_number(self, data): \"\"\"Extract the LMS course number",
"codes. We first try splitting the key as a version",
"a secret token. For more usage details, see documentation of",
"For more usage details, see documentation of the :class:`requests.Session` object:",
"key[10:].split(\"+\") else: organization, course, run = key.split(\"/\") return organization, course,",
"course and course run codes. We first try splitting the",
"<reponame>kernicPanel/richie \"\"\" Backend to connect Open edX richie with an",
"token, *args, **kwargs): \"\"\"Extending the session object by setting the",
"url): \"\"\"Extract the LMS course id from the course run",
"self.token = token def __call__(self, request): \"\"\"Modify and return the",
"with an LMS \"\"\" import logging import re import requests",
"= self.extract_course_id(data.get(\"resource_link\")) return split_course_key(course_id)[1] @staticmethod def get_course_run_serializer(data, partial=False): \"\"\"Prepare data",
"@property def api_client(self): \"\"\"Instantiate and return an edx token API",
"import AuthBase from ..serializers import SyncCourseRunSerializer from .base import BaseLMSBackend",
"details, see documentation of the :class:`requests.Session` object: https://requests.readthedocs.io/en/master/user/advanced/#session-objects \"\"\" def",
"LMS \"\"\" import logging import re import requests from requests.auth",
"LMS course number from data dictionary.\"\"\" course_id = self.extract_course_id(data.get(\"resource_link\")) return",
"number from data dictionary.\"\"\" course_id = self.extract_course_id(data.get(\"resource_link\")) return split_course_key(course_id)[1] @staticmethod",
"= logging.getLogger(__name__) def split_course_key(key): \"\"\"Split an OpenEdX course key by",
"*args, **kwargs): \"\"\"Extending the session object by setting the authentication",
"return an edx token API client.\"\"\" return TokenAPIClient(self.configuration[\"API_TOKEN\"]) def extract_course_id(self,",
"course number from data dictionary.\"\"\" course_id = self.extract_course_id(data.get(\"resource_link\")) return split_course_key(course_id)[1]",
"\"\"\"Attach HTTP token authentication to the given Request object.\"\"\" def",
"BaseLMSBackend logger = logging.getLogger(__name__) def split_course_key(key): \"\"\"Split an OpenEdX course",
"= EdXTokenAuth(token) class EdXLMSBackend(BaseLMSBackend): \"\"\"LMS backend for Richie tested with",
"key as a version 1 key (course-v1:org+course+run) and fallback the",
"course, run = key[10:].split(\"+\") else: organization, course, run = key.split(\"/\")",
"and course run codes. We first try splitting the key",
"self.token, \"Content-Type\": \"application/json\"} ) return request class TokenAPIClient(requests.Session): \"\"\" A",
"and fallback the old version (org/course/run). \"\"\" if key.startswith(\"course-v1:\"): organization,",
"def extract_course_number(self, data): \"\"\"Extract the LMS course number from data",
"split_course_key(course_id)[1] @staticmethod def get_course_run_serializer(data, partial=False): \"\"\"Prepare data and return a",
"key (course-v1:org+course+run) and fallback the old version (org/course/run). \"\"\" if",
"Richie tested with Open EdX Dogwood to Hawthorn.\"\"\" @property def",
"see documentation of the :class:`requests.Session` object: https://requests.readthedocs.io/en/master/user/advanced/#session-objects \"\"\" def __init__(self,",
"Request object.\"\"\" def __init__(self, token): \"\"\"Set-up token value in the",
"token): \"\"\"Set-up token value in the instance.\"\"\" self.token = token",
"given a secret token. For more usage details, see documentation",
"def get_course_run_serializer(data, partial=False): \"\"\"Prepare data and return a bound serializer.\"\"\"",
"token value in the instance.\"\"\" self.token = token def __call__(self,",
"\"\"\"Modify and return the request.\"\"\" request.headers.update( {\"X-Edx-Api-Key\": self.token, \"Content-Type\": \"application/json\"}",
"EdXLMSBackend(BaseLMSBackend): \"\"\"LMS backend for Richie tested with Open EdX Dogwood",
"self.extract_course_id(data.get(\"resource_link\")) return split_course_key(course_id)[1] @staticmethod def get_course_run_serializer(data, partial=False): \"\"\"Prepare data and",
"from requests.auth import AuthBase from ..serializers import SyncCourseRunSerializer from .base",
"course run codes. We first try splitting the key as",
"splitting the key as a version 1 key (course-v1:org+course+run) and"
] |
[
"some magic to bind an B-RPC method to an RPC",
"use the given encoding. \"\"\" def __init__(self, uri, transport=None, encoding=None,",
"__getattr__(self, name): # magic method dispatcher return _Method(self.__request, name) def",
"BRPC_ServerProxy(xmlrpclib.ServerProxy): \"\"\"uri [,options] -> a logical connection to an B-RPC",
"it are both omitted, \"/RPC2\" is assumed. The following options",
"1, 1, name=\"anime\") ping(\"phish\", 0, 1, 1) ping(\"games\", 0, 1,",
"import urllib type, uri = urllib.splittype(uri) if type not in",
"ServerProxy = new_server_proxy if __name__ == '__main__': s = ServerProxy('https://greg.mitte.bittorrent.com:7080/')",
"preceding it are both omitted, \"/RPC2\" is assumed. The following",
"= encoding self.__verbose = verbose self.__allow_none = allow_none def __request(self,",
"allow_none=0): # establish a \"logical\" server connection # get the",
"PyCurlTransport class PyCurlTransport(old_PyCurlTransport): def set_connection_params(self, h): h.add_header('User-Agent', \"brpclib.py/1.0\") h.add_header('Connection', \"Keep-Alive\")",
"available (Python 2.0), it also supports \"https\". If the target",
"BRPC_ServerProxy(url, transport=t) ServerProxy = new_server_proxy if __name__ == '__main__': s",
"xmlrpclib2 import * from BTL import brpc old_PyCurlTransport = PyCurlTransport",
"% (self.__host, self.__handler) ) __str__ = __repr__ def __getattr__(self, name):",
"if type not in (\"http\", \"https\"): raise IOError, \"unsupported B-RPC",
"if transport is None: if type == \"https\": transport =",
"self.__transport = transport self.__encoding = encoding self.__verbose = verbose self.__allow_none",
"response from input file/socket, and parse it return brpc.loads(response.getvalue())[0] #",
"return response def __repr__(self): return ( \"<ServerProxy for %s%s>\" %",
"assumed to use the given encoding. \"\"\" def __init__(self, uri,",
"to bind an B-RPC method to an RPC server. #",
"methodname, encoding=self.__encoding, allow_none=self.__allow_none) response = self.__transport.request( self.__host, self.__handler, request, verbose=self.__verbose",
"\"<ServerProxy for %s%s>\" % (self.__host, self.__handler) ) __str__ = __repr__",
"response): # read response from input file/socket, and parse it",
"response[0] return response def __repr__(self): return ( \"<ServerProxy for %s%s>\"",
"methodname, params): # call a method on the remote server",
"verbose=self.__verbose ) if len(response) == 1: response = response[0] return",
"passed to the server proxy are assumed to use the",
"BTL import brpc old_PyCurlTransport = PyCurlTransport class PyCurlTransport(old_PyCurlTransport): def set_connection_params(self,",
"<NAME> import xmlrpclib from xmlrpclib2 import * from BTL import",
"factory encoding: the request encoding (default is UTF-8) All 8-bit",
"request, verbose=self.__verbose ) if len(response) == 1: response = response[0]",
"(\"http\", \"https\"): raise IOError, \"unsupported B-RPC protocol\" self.__host, self.__handler =",
"8-bit strings passed to the server proxy are assumed to",
"to an B-RPC server uri is the connection point on",
"All 8-bit strings passed to the server proxy are assumed",
"= transport self.__encoding = encoding self.__verbose = verbose self.__allow_none =",
"== \"https\": transport = xmlrpclib.SafeTransport() else: transport = xmlrpclib.Transport() self.__transport",
"dispatcher return _Method(self.__request, name) def new_server_proxy(url): c = cache_set.get_cache(PyCURL_Cache, url)",
"% (kw2, dict(kw)) ping(0, 1, 1, name=\"potato\") ping(0, 1, 1,",
"the server, given as scheme://host/target. The standard implementation always supports",
"B-RPC server uri is the connection point on the server,",
"underscore is BAD! class BRPC_ServerProxy(xmlrpclib.ServerProxy): \"\"\"uri [,options] -> a logical",
"(args, kwargs) return self.__send(self.__name, args) # ARG! prevent repr(_Method()) from",
"def new_server_proxy(url): c = cache_set.get_cache(PyCURL_Cache, url) t = PyCurlTransport(c) return",
"request = brpc.dumps(params, methodname, encoding=self.__encoding, allow_none=self.__allow_none) response = self.__transport.request( self.__host,",
"if not self.__handler: self.__handler = \"/RPC2\" if transport is None:",
"self.__verbose = verbose self.__allow_none = allow_none def __request(self, methodname, params):",
"-> a logical connection to an B-RPC server uri is",
"__init__(self, uri, transport=None, encoding=None, verbose=0, allow_none=0): # establish a \"logical\"",
"allow_none=self.__allow_none) response = self.__transport.request( self.__host, self.__handler, request, verbose=self.__verbose ) if",
"\"http\" scheme. If SSL socket support is available (Python 2.0),",
"magic to bind an B-RPC method to an RPC server.",
"_parse_response(self, response): # read response from input file/socket, and parse",
"brpc.loads(response.getvalue())[0] # -------------------------------------------------------------------- # request dispatcher class _Method: # some",
"self.__handler = urllib.splithost(uri) if not self.__handler: self.__handler = \"/RPC2\" if",
"urllib type, uri = urllib.splittype(uri) if type not in (\"http\",",
"2.0), it also supports \"https\". If the target part and",
"== dict(kw), '%s dict is not %s' % (kw2, dict(kw))",
"RPC call! def __repr__(self): return \"<%s instance at 0x%08X>\" %",
"arguments: transport: a transport factory encoding: the request encoding (default",
"name): return _Method(self.__send, \"%s.%s\" % (self.__name, name)) def __call__(self, *args,",
"at 0x%08X>\" % (self.__class__, id(self)) # Double underscore is BAD!",
"is None: if type == \"https\": transport = xmlrpclib.SafeTransport() else:",
"_Method(self.__send, \"%s.%s\" % (self.__name, name)) def __call__(self, *args, **kwargs): args",
"def ping(*a, **kw): (a2, kw2) = s.ping(*a, **kw) assert a2",
"urllib.splittype(uri) if type not in (\"http\", \"https\"): raise IOError, \"unsupported",
"__repr__ def __getattr__(self, name): # magic method dispatcher return _Method(self.__request,",
"# ARG! prevent repr(_Method()) from submiting an RPC call! def",
"standard implementation always supports the \"http\" scheme. If SSL socket",
"self.__transport.request( self.__host, self.__handler, request, verbose=self.__verbose ) if len(response) == 1:",
"def set_connection_params(self, h): h.add_header('User-Agent', \"brpclib.py/1.0\") h.add_header('Connection', \"Keep-Alive\") h.add_header('Content-Type', \"application/octet-stream\") def",
"proxy are assumed to use the given encoding. \"\"\" def",
"return brpc.loads(response.getvalue())[0] # -------------------------------------------------------------------- # request dispatcher class _Method: #",
"(e.g. examples.getStateName) def __init__(self, send, name): self.__send = send self.__name",
"self.__send(self.__name, args) # ARG! prevent repr(_Method()) from submiting an RPC",
"an B-RPC server uri is the connection point on the",
"encoding=self.__encoding, allow_none=self.__allow_none) response = self.__transport.request( self.__host, self.__handler, request, verbose=self.__verbose )",
"== list(a), '%s list is not %s' % (r, list(a))",
"set_connection_params(self, h): h.add_header('User-Agent', \"brpclib.py/1.0\") h.add_header('Connection', \"Keep-Alive\") h.add_header('Content-Type', \"application/octet-stream\") def _parse_response(self,",
"transport = xmlrpclib.Transport() self.__transport = transport self.__encoding = encoding self.__verbose",
"list(a)) assert kw2 == dict(kw), '%s dict is not %s'",
"__getattr__(self, name): return _Method(self.__send, \"%s.%s\" % (self.__name, name)) def __call__(self,",
"\"application/octet-stream\") def _parse_response(self, response): # read response from input file/socket,",
"and the slash preceding it are both omitted, \"/RPC2\" is",
"[,options] -> a logical connection to an B-RPC server uri",
"# establish a \"logical\" server connection # get the url",
"for %s%s>\" % (self.__host, self.__handler) ) __str__ = __repr__ def",
"uri = urllib.splittype(uri) if type not in (\"http\", \"https\"): raise",
"keyword arguments: transport: a transport factory encoding: the request encoding",
"= allow_none def __request(self, methodname, params): # call a method",
"strings passed to the server proxy are assumed to use",
"the remote server request = brpc.dumps(params, methodname, encoding=self.__encoding, allow_none=self.__allow_none) response",
"server. # supports \"nested\" methods (e.g. examples.getStateName) def __init__(self, send,",
"\"/RPC2\" is assumed. The following options can be given as",
"If the target part and the slash preceding it are",
"the request encoding (default is UTF-8) All 8-bit strings passed",
"= PyCurlTransport class PyCurlTransport(old_PyCurlTransport): def set_connection_params(self, h): h.add_header('User-Agent', \"brpclib.py/1.0\") h.add_header('Connection',",
"is available (Python 2.0), it also supports \"https\". If the",
"brpc.dumps(params, methodname, encoding=self.__encoding, allow_none=self.__allow_none) response = self.__transport.request( self.__host, self.__handler, request,",
"transport=None, encoding=None, verbose=0, allow_none=0): # establish a \"logical\" server connection",
"assert kw2 == dict(kw), '%s dict is not %s' %",
"__name__ == '__main__': s = ServerProxy('https://greg.mitte.bittorrent.com:7080/') def ping(*a, **kw): (a2,",
"connection to an B-RPC server uri is the connection point",
"can be given as keyword arguments: transport: a transport factory",
"name): # magic method dispatcher return _Method(self.__request, name) def new_server_proxy(url):",
"new_server_proxy(url): c = cache_set.get_cache(PyCURL_Cache, url) t = PyCurlTransport(c) return BRPC_ServerProxy(url,",
"(kw2, dict(kw)) ping(0, 1, 1, name=\"potato\") ping(0, 1, 1, name=\"anime\")",
"# by <NAME> import xmlrpclib from xmlrpclib2 import * from",
"encoding. \"\"\" def __init__(self, uri, transport=None, encoding=None, verbose=0, allow_none=0): #",
"0x%08X>\" % (self.__class__, id(self)) # Double underscore is BAD! class",
"url) t = PyCurlTransport(c) return BRPC_ServerProxy(url, transport=t) ServerProxy = new_server_proxy",
"= xmlrpclib.SafeTransport() else: transport = xmlrpclib.Transport() self.__transport = transport self.__encoding",
"name=\"potato\") ping(0, 1, 1, name=\"anime\") ping(\"phish\", 0, 1, 1) ping(\"games\",",
"# get the url import urllib type, uri = urllib.splittype(uri)",
"self.__handler) ) __str__ = __repr__ def __getattr__(self, name): # magic",
"xmlrpclib.Transport() self.__transport = transport self.__encoding = encoding self.__verbose = verbose",
"(self.__host, self.__handler) ) __str__ = __repr__ def __getattr__(self, name): #",
"scheme://host/target. The standard implementation always supports the \"http\" scheme. If",
"def __init__(self, uri, transport=None, encoding=None, verbose=0, allow_none=0): # establish a",
"def __call__(self, *args, **kwargs): args = (args, kwargs) return self.__send(self.__name,",
"scheme. If SSL socket support is available (Python 2.0), it",
"= brpc.dumps(params, methodname, encoding=self.__encoding, allow_none=self.__allow_none) response = self.__transport.request( self.__host, self.__handler,",
"= (args, kwargs) return self.__send(self.__name, args) # ARG! prevent repr(_Method())",
"connection point on the server, given as scheme://host/target. The standard",
"__init__(self, send, name): self.__send = send self.__name = name def",
"ARG! prevent repr(_Method()) from submiting an RPC call! def __repr__(self):",
"socket support is available (Python 2.0), it also supports \"https\".",
"\"https\"): raise IOError, \"unsupported B-RPC protocol\" self.__host, self.__handler = urllib.splithost(uri)",
"transport is None: if type == \"https\": transport = xmlrpclib.SafeTransport()",
"B-RPC protocol\" self.__host, self.__handler = urllib.splithost(uri) if not self.__handler: self.__handler",
"def __repr__(self): return ( \"<ServerProxy for %s%s>\" % (self.__host, self.__handler)",
"request dispatcher class _Method: # some magic to bind an",
"\"unsupported B-RPC protocol\" self.__host, self.__handler = urllib.splithost(uri) if not self.__handler:",
"= self.__transport.request( self.__host, self.__handler, request, verbose=self.__verbose ) if len(response) ==",
"dict is not %s' % (kw2, dict(kw)) ping(0, 1, 1,",
"raise IOError, \"unsupported B-RPC protocol\" self.__host, self.__handler = urllib.splithost(uri) if",
"supports \"https\". If the target part and the slash preceding",
"an RPC server. # supports \"nested\" methods (e.g. examples.getStateName) def",
"-------------------------------------------------------------------- # request dispatcher class _Method: # some magic to",
"# Double underscore is BAD! class BRPC_ServerProxy(xmlrpclib.ServerProxy): \"\"\"uri [,options] ->",
"UTF-8) All 8-bit strings passed to the server proxy are",
"None: if type == \"https\": transport = xmlrpclib.SafeTransport() else: transport",
"method dispatcher return _Method(self.__request, name) def new_server_proxy(url): c = cache_set.get_cache(PyCURL_Cache,",
"method to an RPC server. # supports \"nested\" methods (e.g.",
"uri, transport=None, encoding=None, verbose=0, allow_none=0): # establish a \"logical\" server",
"on the server, given as scheme://host/target. The standard implementation always",
"__repr__(self): return ( \"<ServerProxy for %s%s>\" % (self.__host, self.__handler) )",
"call! def __repr__(self): return \"<%s instance at 0x%08X>\" % (self.__class__,",
"s = ServerProxy('https://greg.mitte.bittorrent.com:7080/') def ping(*a, **kw): (a2, kw2) = s.ping(*a,",
"import brpc old_PyCurlTransport = PyCurlTransport class PyCurlTransport(old_PyCurlTransport): def set_connection_params(self, h):",
"old_PyCurlTransport = PyCurlTransport class PyCurlTransport(old_PyCurlTransport): def set_connection_params(self, h): h.add_header('User-Agent', \"brpclib.py/1.0\")",
"c = cache_set.get_cache(PyCURL_Cache, url) t = PyCurlTransport(c) return BRPC_ServerProxy(url, transport=t)",
"in (\"http\", \"https\"): raise IOError, \"unsupported B-RPC protocol\" self.__host, self.__handler",
"ping(0, 1, 1, name=\"potato\") ping(0, 1, 1, name=\"anime\") ping(\"phish\", 0,",
"encoding: the request encoding (default is UTF-8) All 8-bit strings",
"= s.ping(*a, **kw) assert a2 == list(a), '%s list is",
"not self.__handler: self.__handler = \"/RPC2\" if transport is None: if",
"self.__send = send self.__name = name def __getattr__(self, name): return",
"the \"http\" scheme. If SSL socket support is available (Python",
"= response[0] return response def __repr__(self): return ( \"<ServerProxy for",
"(r, list(a)) assert kw2 == dict(kw), '%s dict is not",
"params): # call a method on the remote server request",
"assumed. The following options can be given as keyword arguments:",
"to the server proxy are assumed to use the given",
"urllib.splithost(uri) if not self.__handler: self.__handler = \"/RPC2\" if transport is",
"(a2, kw2) = s.ping(*a, **kw) assert a2 == list(a), '%s",
"= \"/RPC2\" if transport is None: if type == \"https\":",
"**kwargs): args = (args, kwargs) return self.__send(self.__name, args) # ARG!",
"self.__encoding = encoding self.__verbose = verbose self.__allow_none = allow_none def",
"\"\"\"uri [,options] -> a logical connection to an B-RPC server",
"send self.__name = name def __getattr__(self, name): return _Method(self.__send, \"%s.%s\"",
"the given encoding. \"\"\" def __init__(self, uri, transport=None, encoding=None, verbose=0,",
"the connection point on the server, given as scheme://host/target. The",
"class BRPC_ServerProxy(xmlrpclib.ServerProxy): \"\"\"uri [,options] -> a logical connection to an",
"prevent repr(_Method()) from submiting an RPC call! def __repr__(self): return",
"_Method(self.__request, name) def new_server_proxy(url): c = cache_set.get_cache(PyCURL_Cache, url) t =",
"return _Method(self.__request, name) def new_server_proxy(url): c = cache_set.get_cache(PyCURL_Cache, url) t",
"are both omitted, \"/RPC2\" is assumed. The following options can",
"h.add_header('Content-Type', \"application/octet-stream\") def _parse_response(self, response): # read response from input",
"RPC server. # supports \"nested\" methods (e.g. examples.getStateName) def __init__(self,",
"\"nested\" methods (e.g. examples.getStateName) def __init__(self, send, name): self.__send =",
"implementation always supports the \"http\" scheme. If SSL socket support",
"name def __getattr__(self, name): return _Method(self.__send, \"%s.%s\" % (self.__name, name))",
"# some magic to bind an B-RPC method to an",
"to an RPC server. # supports \"nested\" methods (e.g. examples.getStateName)",
"by <NAME> import xmlrpclib from xmlrpclib2 import * from BTL",
"return ( \"<ServerProxy for %s%s>\" % (self.__host, self.__handler) ) __str__",
"it return brpc.loads(response.getvalue())[0] # -------------------------------------------------------------------- # request dispatcher class _Method:",
"server proxy are assumed to use the given encoding. \"\"\"",
"PyCurlTransport(c) return BRPC_ServerProxy(url, transport=t) ServerProxy = new_server_proxy if __name__ ==",
"as keyword arguments: transport: a transport factory encoding: the request",
"protocol\" self.__host, self.__handler = urllib.splithost(uri) if not self.__handler: self.__handler =",
"**kw): (a2, kw2) = s.ping(*a, **kw) assert a2 == list(a),",
"options can be given as keyword arguments: transport: a transport",
"else: transport = xmlrpclib.Transport() self.__transport = transport self.__encoding = encoding",
"h): h.add_header('User-Agent', \"brpclib.py/1.0\") h.add_header('Connection', \"Keep-Alive\") h.add_header('Content-Type', \"application/octet-stream\") def _parse_response(self, response):",
"if type == \"https\": transport = xmlrpclib.SafeTransport() else: transport =",
"__request(self, methodname, params): # call a method on the remote",
"t = PyCurlTransport(c) return BRPC_ServerProxy(url, transport=t) ServerProxy = new_server_proxy if",
"'%s list is not %s' % (r, list(a)) assert kw2",
"ServerProxy('https://greg.mitte.bittorrent.com:7080/') def ping(*a, **kw): (a2, kw2) = s.ping(*a, **kw) assert",
"magic method dispatcher return _Method(self.__request, name) def new_server_proxy(url): c =",
"= urllib.splithost(uri) if not self.__handler: self.__handler = \"/RPC2\" if transport",
"as scheme://host/target. The standard implementation always supports the \"http\" scheme.",
"1: response = response[0] return response def __repr__(self): return (",
"# magic method dispatcher return _Method(self.__request, name) def new_server_proxy(url): c",
"PyCurlTransport(old_PyCurlTransport): def set_connection_params(self, h): h.add_header('User-Agent', \"brpclib.py/1.0\") h.add_header('Connection', \"Keep-Alive\") h.add_header('Content-Type', \"application/octet-stream\")",
"are assumed to use the given encoding. \"\"\" def __init__(self,",
"verbose=0, allow_none=0): # establish a \"logical\" server connection # get",
"not %s' % (r, list(a)) assert kw2 == dict(kw), '%s",
"self.__host, self.__handler = urllib.splithost(uri) if not self.__handler: self.__handler = \"/RPC2\"",
"a2 == list(a), '%s list is not %s' % (r,",
"given encoding. \"\"\" def __init__(self, uri, transport=None, encoding=None, verbose=0, allow_none=0):",
"remote server request = brpc.dumps(params, methodname, encoding=self.__encoding, allow_none=self.__allow_none) response =",
"(default is UTF-8) All 8-bit strings passed to the server",
"response = response[0] return response def __repr__(self): return ( \"<ServerProxy",
"type == \"https\": transport = xmlrpclib.SafeTransport() else: transport = xmlrpclib.Transport()",
"request encoding (default is UTF-8) All 8-bit strings passed to",
"__call__(self, *args, **kwargs): args = (args, kwargs) return self.__send(self.__name, args)",
"if len(response) == 1: response = response[0] return response def",
"__str__ = __repr__ def __getattr__(self, name): # magic method dispatcher",
"the target part and the slash preceding it are both",
"ping(*a, **kw): (a2, kw2) = s.ping(*a, **kw) assert a2 ==",
"is assumed. The following options can be given as keyword",
"self.__allow_none = allow_none def __request(self, methodname, params): # call a",
"given as keyword arguments: transport: a transport factory encoding: the",
"= cache_set.get_cache(PyCURL_Cache, url) t = PyCurlTransport(c) return BRPC_ServerProxy(url, transport=t) ServerProxy",
"to use the given encoding. \"\"\" def __init__(self, uri, transport=None,",
"1, 1, name=\"potato\") ping(0, 1, 1, name=\"anime\") ping(\"phish\", 0, 1,",
"dict(kw)) ping(0, 1, 1, name=\"potato\") ping(0, 1, 1, name=\"anime\") ping(\"phish\",",
"1, name=\"potato\") ping(0, 1, 1, name=\"anime\") ping(\"phish\", 0, 1, 1)",
"class _Method: # some magic to bind an B-RPC method",
"import * from BTL import brpc old_PyCurlTransport = PyCurlTransport class",
"assert a2 == list(a), '%s list is not %s' %",
"len(response) == 1: response = response[0] return response def __repr__(self):",
"a \"logical\" server connection # get the url import urllib",
"# call a method on the remote server request =",
"get the url import urllib type, uri = urllib.splittype(uri) if",
"self.__name = name def __getattr__(self, name): return _Method(self.__send, \"%s.%s\" %",
"logical connection to an B-RPC server uri is the connection",
"'%s dict is not %s' % (kw2, dict(kw)) ping(0, 1,",
"\"logical\" server connection # get the url import urllib type,",
"be given as keyword arguments: transport: a transport factory encoding:",
"not %s' % (kw2, dict(kw)) ping(0, 1, 1, name=\"potato\") ping(0,",
"*args, **kwargs): args = (args, kwargs) return self.__send(self.__name, args) #",
"= urllib.splittype(uri) if type not in (\"http\", \"https\"): raise IOError,",
"\"\"\" def __init__(self, uri, transport=None, encoding=None, verbose=0, allow_none=0): # establish",
"is not %s' % (kw2, dict(kw)) ping(0, 1, 1, name=\"potato\")",
"kw2 == dict(kw), '%s dict is not %s' % (kw2,",
"self.__handler, request, verbose=self.__verbose ) if len(response) == 1: response =",
"_Method: # some magic to bind an B-RPC method to",
"%s' % (r, list(a)) assert kw2 == dict(kw), '%s dict",
"a transport factory encoding: the request encoding (default is UTF-8)",
"# -------------------------------------------------------------------- # request dispatcher class _Method: # some magic",
"allow_none def __request(self, methodname, params): # call a method on",
"is BAD! class BRPC_ServerProxy(xmlrpclib.ServerProxy): \"\"\"uri [,options] -> a logical connection",
"(self.__class__, id(self)) # Double underscore is BAD! class BRPC_ServerProxy(xmlrpclib.ServerProxy): \"\"\"uri",
"brpc old_PyCurlTransport = PyCurlTransport class PyCurlTransport(old_PyCurlTransport): def set_connection_params(self, h): h.add_header('User-Agent',",
"If SSL socket support is available (Python 2.0), it also",
"the url import urllib type, uri = urllib.splittype(uri) if type",
"supports \"nested\" methods (e.g. examples.getStateName) def __init__(self, send, name): self.__send",
"= send self.__name = name def __getattr__(self, name): return _Method(self.__send,",
"the slash preceding it are both omitted, \"/RPC2\" is assumed.",
"and parse it return brpc.loads(response.getvalue())[0] # -------------------------------------------------------------------- # request dispatcher",
"SSL socket support is available (Python 2.0), it also supports",
"url import urllib type, uri = urllib.splittype(uri) if type not",
"**kw) assert a2 == list(a), '%s list is not %s'",
"kw2) = s.ping(*a, **kw) assert a2 == list(a), '%s list",
"# read response from input file/socket, and parse it return",
"dispatcher class _Method: # some magic to bind an B-RPC",
"following options can be given as keyword arguments: transport: a",
"\"brpclib.py/1.0\") h.add_header('Connection', \"Keep-Alive\") h.add_header('Content-Type', \"application/octet-stream\") def _parse_response(self, response): # read",
"def __request(self, methodname, params): # call a method on the",
"B-RPC method to an RPC server. # supports \"nested\" methods",
"== 1: response = response[0] return response def __repr__(self): return",
"transport: a transport factory encoding: the request encoding (default is",
"server request = brpc.dumps(params, methodname, encoding=self.__encoding, allow_none=self.__allow_none) response = self.__transport.request(",
"support is available (Python 2.0), it also supports \"https\". If",
"self.__handler = \"/RPC2\" if transport is None: if type ==",
"h.add_header('User-Agent', \"brpclib.py/1.0\") h.add_header('Connection', \"Keep-Alive\") h.add_header('Content-Type', \"application/octet-stream\") def _parse_response(self, response): #",
"= PyCurlTransport(c) return BRPC_ServerProxy(url, transport=t) ServerProxy = new_server_proxy if __name__",
"verbose self.__allow_none = allow_none def __request(self, methodname, params): # call",
"h.add_header('Connection', \"Keep-Alive\") h.add_header('Content-Type', \"application/octet-stream\") def _parse_response(self, response): # read response",
"an RPC call! def __repr__(self): return \"<%s instance at 0x%08X>\"",
"return _Method(self.__send, \"%s.%s\" % (self.__name, name)) def __call__(self, *args, **kwargs):",
"repr(_Method()) from submiting an RPC call! def __repr__(self): return \"<%s",
"Double underscore is BAD! class BRPC_ServerProxy(xmlrpclib.ServerProxy): \"\"\"uri [,options] -> a",
"not in (\"http\", \"https\"): raise IOError, \"unsupported B-RPC protocol\" self.__host,",
"def __getattr__(self, name): # magic method dispatcher return _Method(self.__request, name)",
"also supports \"https\". If the target part and the slash",
"given as scheme://host/target. The standard implementation always supports the \"http\"",
"\"<%s instance at 0x%08X>\" % (self.__class__, id(self)) # Double underscore",
"transport=t) ServerProxy = new_server_proxy if __name__ == '__main__': s =",
"transport = xmlrpclib.SafeTransport() else: transport = xmlrpclib.Transport() self.__transport = transport",
"% (self.__class__, id(self)) # Double underscore is BAD! class BRPC_ServerProxy(xmlrpclib.ServerProxy):",
"type, uri = urllib.splittype(uri) if type not in (\"http\", \"https\"):",
"the server proxy are assumed to use the given encoding.",
"self.__host, self.__handler, request, verbose=self.__verbose ) if len(response) == 1: response",
"= __repr__ def __getattr__(self, name): # magic method dispatcher return",
"method on the remote server request = brpc.dumps(params, methodname, encoding=self.__encoding,",
"def __getattr__(self, name): return _Method(self.__send, \"%s.%s\" % (self.__name, name)) def",
"is the connection point on the server, given as scheme://host/target.",
"ping(0, 1, 1, name=\"anime\") ping(\"phish\", 0, 1, 1) ping(\"games\", 0,",
"import xmlrpclib from xmlrpclib2 import * from BTL import brpc",
"transport factory encoding: the request encoding (default is UTF-8) All",
"target part and the slash preceding it are both omitted,",
"response def __repr__(self): return ( \"<ServerProxy for %s%s>\" % (self.__host,",
"= verbose self.__allow_none = allow_none def __request(self, methodname, params): #",
"server, given as scheme://host/target. The standard implementation always supports the",
"point on the server, given as scheme://host/target. The standard implementation",
"input file/socket, and parse it return brpc.loads(response.getvalue())[0] # -------------------------------------------------------------------- #",
"args = (args, kwargs) return self.__send(self.__name, args) # ARG! prevent",
"( \"<ServerProxy for %s%s>\" % (self.__host, self.__handler) ) __str__ =",
"xmlrpclib.SafeTransport() else: transport = xmlrpclib.Transport() self.__transport = transport self.__encoding =",
"%s' % (kw2, dict(kw)) ping(0, 1, 1, name=\"potato\") ping(0, 1,",
"* from BTL import brpc old_PyCurlTransport = PyCurlTransport class PyCurlTransport(old_PyCurlTransport):",
"instance at 0x%08X>\" % (self.__class__, id(self)) # Double underscore is",
"= xmlrpclib.Transport() self.__transport = transport self.__encoding = encoding self.__verbose =",
"submiting an RPC call! def __repr__(self): return \"<%s instance at",
"# supports \"nested\" methods (e.g. examples.getStateName) def __init__(self, send, name):",
"= ServerProxy('https://greg.mitte.bittorrent.com:7080/') def ping(*a, **kw): (a2, kw2) = s.ping(*a, **kw)",
"\"/RPC2\" if transport is None: if type == \"https\": transport",
"file/socket, and parse it return brpc.loads(response.getvalue())[0] # -------------------------------------------------------------------- # request",
"encoding=None, verbose=0, allow_none=0): # establish a \"logical\" server connection #",
"methods (e.g. examples.getStateName) def __init__(self, send, name): self.__send = send",
"supports the \"http\" scheme. If SSL socket support is available",
"response = self.__transport.request( self.__host, self.__handler, request, verbose=self.__verbose ) if len(response)",
"__repr__(self): return \"<%s instance at 0x%08X>\" % (self.__class__, id(self)) #",
"\"%s.%s\" % (self.__name, name)) def __call__(self, *args, **kwargs): args =",
"a logical connection to an B-RPC server uri is the",
"= name def __getattr__(self, name): return _Method(self.__send, \"%s.%s\" % (self.__name,",
"if __name__ == '__main__': s = ServerProxy('https://greg.mitte.bittorrent.com:7080/') def ping(*a, **kw):",
"type not in (\"http\", \"https\"): raise IOError, \"unsupported B-RPC protocol\"",
"== '__main__': s = ServerProxy('https://greg.mitte.bittorrent.com:7080/') def ping(*a, **kw): (a2, kw2)",
"\"https\". If the target part and the slash preceding it",
"args) # ARG! prevent repr(_Method()) from submiting an RPC call!",
"= new_server_proxy if __name__ == '__main__': s = ServerProxy('https://greg.mitte.bittorrent.com:7080/') def",
"kwargs) return self.__send(self.__name, args) # ARG! prevent repr(_Method()) from submiting",
"list is not %s' % (r, list(a)) assert kw2 ==",
"(self.__name, name)) def __call__(self, *args, **kwargs): args = (args, kwargs)",
") if len(response) == 1: response = response[0] return response",
"1, name=\"anime\") ping(\"phish\", 0, 1, 1) ping(\"games\", 0, 1, 1)",
"slash preceding it are both omitted, \"/RPC2\" is assumed. The",
"from submiting an RPC call! def __repr__(self): return \"<%s instance",
"s.ping(*a, **kw) assert a2 == list(a), '%s list is not",
"always supports the \"http\" scheme. If SSL socket support is",
"IOError, \"unsupported B-RPC protocol\" self.__host, self.__handler = urllib.splithost(uri) if not",
"encoding self.__verbose = verbose self.__allow_none = allow_none def __request(self, methodname,",
"return BRPC_ServerProxy(url, transport=t) ServerProxy = new_server_proxy if __name__ == '__main__':",
"% (r, list(a)) assert kw2 == dict(kw), '%s dict is",
"transport self.__encoding = encoding self.__verbose = verbose self.__allow_none = allow_none",
"new_server_proxy if __name__ == '__main__': s = ServerProxy('https://greg.mitte.bittorrent.com:7080/') def ping(*a,",
"return self.__send(self.__name, args) # ARG! prevent repr(_Method()) from submiting an",
"\"Keep-Alive\") h.add_header('Content-Type', \"application/octet-stream\") def _parse_response(self, response): # read response from",
"both omitted, \"/RPC2\" is assumed. The following options can be",
"self.__handler: self.__handler = \"/RPC2\" if transport is None: if type",
"cache_set.get_cache(PyCURL_Cache, url) t = PyCurlTransport(c) return BRPC_ServerProxy(url, transport=t) ServerProxy =",
"name) def new_server_proxy(url): c = cache_set.get_cache(PyCURL_Cache, url) t = PyCurlTransport(c)",
"% (self.__name, name)) def __call__(self, *args, **kwargs): args = (args,",
"The standard implementation always supports the \"http\" scheme. If SSL",
"BAD! class BRPC_ServerProxy(xmlrpclib.ServerProxy): \"\"\"uri [,options] -> a logical connection to",
"part and the slash preceding it are both omitted, \"/RPC2\"",
") __str__ = __repr__ def __getattr__(self, name): # magic method",
"it also supports \"https\". If the target part and the",
"'__main__': s = ServerProxy('https://greg.mitte.bittorrent.com:7080/') def ping(*a, **kw): (a2, kw2) =",
"encoding (default is UTF-8) All 8-bit strings passed to the",
"def __init__(self, send, name): self.__send = send self.__name = name",
"omitted, \"/RPC2\" is assumed. The following options can be given",
"uri is the connection point on the server, given as",
"def _parse_response(self, response): # read response from input file/socket, and",
"xmlrpclib from xmlrpclib2 import * from BTL import brpc old_PyCurlTransport",
"return \"<%s instance at 0x%08X>\" % (self.__class__, id(self)) # Double",
"send, name): self.__send = send self.__name = name def __getattr__(self,",
"from BTL import brpc old_PyCurlTransport = PyCurlTransport class PyCurlTransport(old_PyCurlTransport): def",
"dict(kw), '%s dict is not %s' % (kw2, dict(kw)) ping(0,",
"on the remote server request = brpc.dumps(params, methodname, encoding=self.__encoding, allow_none=self.__allow_none)",
"a method on the remote server request = brpc.dumps(params, methodname,",
"read response from input file/socket, and parse it return brpc.loads(response.getvalue())[0]",
"\"https\": transport = xmlrpclib.SafeTransport() else: transport = xmlrpclib.Transport() self.__transport =",
"name): self.__send = send self.__name = name def __getattr__(self, name):",
"# request dispatcher class _Method: # some magic to bind",
"name)) def __call__(self, *args, **kwargs): args = (args, kwargs) return",
"%s%s>\" % (self.__host, self.__handler) ) __str__ = __repr__ def __getattr__(self,",
"class PyCurlTransport(old_PyCurlTransport): def set_connection_params(self, h): h.add_header('User-Agent', \"brpclib.py/1.0\") h.add_header('Connection', \"Keep-Alive\") h.add_header('Content-Type',",
"call a method on the remote server request = brpc.dumps(params,",
"connection # get the url import urllib type, uri =",
"list(a), '%s list is not %s' % (r, list(a)) assert",
"examples.getStateName) def __init__(self, send, name): self.__send = send self.__name =",
"an B-RPC method to an RPC server. # supports \"nested\"",
"from xmlrpclib2 import * from BTL import brpc old_PyCurlTransport =",
"parse it return brpc.loads(response.getvalue())[0] # -------------------------------------------------------------------- # request dispatcher class",
"from input file/socket, and parse it return brpc.loads(response.getvalue())[0] # --------------------------------------------------------------------",
"The following options can be given as keyword arguments: transport:",
"bind an B-RPC method to an RPC server. # supports",
"def __repr__(self): return \"<%s instance at 0x%08X>\" % (self.__class__, id(self))",
"establish a \"logical\" server connection # get the url import",
"id(self)) # Double underscore is BAD! class BRPC_ServerProxy(xmlrpclib.ServerProxy): \"\"\"uri [,options]",
"(Python 2.0), it also supports \"https\". If the target part",
"server connection # get the url import urllib type, uri",
"server uri is the connection point on the server, given",
"is not %s' % (r, list(a)) assert kw2 == dict(kw),",
"is UTF-8) All 8-bit strings passed to the server proxy"
] |
[
"content_type=mimetype) response['Content-Length'] = f.size return response def serve_mixed(request, *args, **kwargs):",
"return django_serve(request, name, document_root) except Http404: # Then try serving",
"cache_control from django.views.static import serve as django_serve from database_files.models import",
"from the filesystem, then tries the database. \"\"\" name =",
"\"\"\" name = kwargs.get('name') or kwargs.get('path') document_root = kwargs.get('document_root') document_root",
"\"\"\" Retrieves the file from the database. \"\"\" f =",
"try: # First attempt to serve from filesystem. return django_serve(request,",
"Http404, HttpResponse from django.shortcuts import get_object_or_404 from django.views.decorators.cache import cache_control",
"name, document_root) except Http404: # Then try serving from database.",
"response['Content-Length'] = f.size return response def serve_mixed(request, *args, **kwargs): \"\"\"",
"serve as django_serve from database_files.models import File @cache_control(max_age=86400) def serve(request,",
"import os from django.conf import settings from django.http import Http404,",
"tries the database. \"\"\" name = kwargs.get('name') or kwargs.get('path') document_root",
"document_root = kwargs.get('document_root') document_root = document_root or settings.MEDIA_ROOT try: #",
"from database_files.models import File @cache_control(max_age=86400) def serve(request, name): \"\"\" Retrieves",
"get_object_or_404(File, name=name) f.dump() mimetype = mimetypes.guess_type(name)[0] or 'application/octet-stream' response =",
"or settings.MEDIA_ROOT try: # First attempt to serve from filesystem.",
"import mimetypes import os from django.conf import settings from django.http",
"f.dump() mimetype = mimetypes.guess_type(name)[0] or 'application/octet-stream' response = HttpResponse(f.content, content_type=mimetype)",
"import serve as django_serve from database_files.models import File @cache_control(max_age=86400) def",
"django.conf import settings from django.http import Http404, HttpResponse from django.shortcuts",
"or 'application/octet-stream' response = HttpResponse(f.content, content_type=mimetype) response['Content-Length'] = f.size return",
"file from the filesystem, then tries the database. \"\"\" name",
"mimetypes import os from django.conf import settings from django.http import",
"from django.views.decorators.cache import cache_control from django.views.static import serve as django_serve",
"attempts to serve the file from the filesystem, then tries",
"get_object_or_404 from django.views.decorators.cache import cache_control from django.views.static import serve as",
"= HttpResponse(f.content, content_type=mimetype) response['Content-Length'] = f.size return response def serve_mixed(request,",
"document_root or settings.MEDIA_ROOT try: # First attempt to serve from",
"import Http404, HttpResponse from django.shortcuts import get_object_or_404 from django.views.decorators.cache import",
"django.views.decorators.cache import cache_control from django.views.static import serve as django_serve from",
"Retrieves the file from the database. \"\"\" f = get_object_or_404(File,",
"filesystem. return django_serve(request, name, document_root) except Http404: # Then try",
"= get_object_or_404(File, name=name) f.dump() mimetype = mimetypes.guess_type(name)[0] or 'application/octet-stream' response",
"HttpResponse from django.shortcuts import get_object_or_404 from django.views.decorators.cache import cache_control from",
"response def serve_mixed(request, *args, **kwargs): \"\"\" First attempts to serve",
"@cache_control(max_age=86400) def serve(request, name): \"\"\" Retrieves the file from the",
"django_serve from database_files.models import File @cache_control(max_age=86400) def serve(request, name): \"\"\"",
"File @cache_control(max_age=86400) def serve(request, name): \"\"\" Retrieves the file from",
"import cache_control from django.views.static import serve as django_serve from database_files.models",
"serve_mixed(request, *args, **kwargs): \"\"\" First attempts to serve the file",
"django_serve(request, name, document_root) except Http404: # Then try serving from",
"response = HttpResponse(f.content, content_type=mimetype) response['Content-Length'] = f.size return response def",
"f = get_object_or_404(File, name=name) f.dump() mimetype = mimetypes.guess_type(name)[0] or 'application/octet-stream'",
"filesystem, then tries the database. \"\"\" name = kwargs.get('name') or",
"database. \"\"\" name = kwargs.get('name') or kwargs.get('path') document_root = kwargs.get('document_root')",
"attempt to serve from filesystem. return django_serve(request, name, document_root) except",
"the database. \"\"\" f = get_object_or_404(File, name=name) f.dump() mimetype =",
"import get_object_or_404 from django.views.decorators.cache import cache_control from django.views.static import serve",
"Http404: # Then try serving from database. return serve(request, name)",
"= f.size return response def serve_mixed(request, *args, **kwargs): \"\"\" First",
"base64 import mimetypes import os from django.conf import settings from",
"settings.MEDIA_ROOT try: # First attempt to serve from filesystem. return",
"document_root) except Http404: # Then try serving from database. return",
"\"\"\" First attempts to serve the file from the filesystem,",
"from the database. \"\"\" f = get_object_or_404(File, name=name) f.dump() mimetype",
"serve from filesystem. return django_serve(request, name, document_root) except Http404: #",
"# First attempt to serve from filesystem. return django_serve(request, name,",
"the filesystem, then tries the database. \"\"\" name = kwargs.get('name')",
"from django.conf import settings from django.http import Http404, HttpResponse from",
"= mimetypes.guess_type(name)[0] or 'application/octet-stream' response = HttpResponse(f.content, content_type=mimetype) response['Content-Length'] =",
"= kwargs.get('name') or kwargs.get('path') document_root = kwargs.get('document_root') document_root = document_root",
"from django.views.static import serve as django_serve from database_files.models import File",
"from filesystem. return django_serve(request, name, document_root) except Http404: # Then",
"import File @cache_control(max_age=86400) def serve(request, name): \"\"\" Retrieves the file",
"settings from django.http import Http404, HttpResponse from django.shortcuts import get_object_or_404",
"return response def serve_mixed(request, *args, **kwargs): \"\"\" First attempts to",
"def serve_mixed(request, *args, **kwargs): \"\"\" First attempts to serve the",
"f.size return response def serve_mixed(request, *args, **kwargs): \"\"\" First attempts",
"serve the file from the filesystem, then tries the database.",
"database_files.models import File @cache_control(max_age=86400) def serve(request, name): \"\"\" Retrieves the",
"= document_root or settings.MEDIA_ROOT try: # First attempt to serve",
"django.http import Http404, HttpResponse from django.shortcuts import get_object_or_404 from django.views.decorators.cache",
"then tries the database. \"\"\" name = kwargs.get('name') or kwargs.get('path')",
"file from the database. \"\"\" f = get_object_or_404(File, name=name) f.dump()",
"to serve the file from the filesystem, then tries the",
"the database. \"\"\" name = kwargs.get('name') or kwargs.get('path') document_root =",
"kwargs.get('path') document_root = kwargs.get('document_root') document_root = document_root or settings.MEDIA_ROOT try:",
"except Http404: # Then try serving from database. return serve(request,",
"to serve from filesystem. return django_serve(request, name, document_root) except Http404:",
"def serve(request, name): \"\"\" Retrieves the file from the database.",
"from django.shortcuts import get_object_or_404 from django.views.decorators.cache import cache_control from django.views.static",
"os from django.conf import settings from django.http import Http404, HttpResponse",
"**kwargs): \"\"\" First attempts to serve the file from the",
"HttpResponse(f.content, content_type=mimetype) response['Content-Length'] = f.size return response def serve_mixed(request, *args,",
"First attempt to serve from filesystem. return django_serve(request, name, document_root)",
"import base64 import mimetypes import os from django.conf import settings",
"First attempts to serve the file from the filesystem, then",
"= kwargs.get('document_root') document_root = document_root or settings.MEDIA_ROOT try: # First",
"django.views.static import serve as django_serve from database_files.models import File @cache_control(max_age=86400)",
"the file from the filesystem, then tries the database. \"\"\"",
"serve(request, name): \"\"\" Retrieves the file from the database. \"\"\"",
"django.shortcuts import get_object_or_404 from django.views.decorators.cache import cache_control from django.views.static import",
"kwargs.get('name') or kwargs.get('path') document_root = kwargs.get('document_root') document_root = document_root or",
"the file from the database. \"\"\" f = get_object_or_404(File, name=name)",
"name): \"\"\" Retrieves the file from the database. \"\"\" f",
"database. \"\"\" f = get_object_or_404(File, name=name) f.dump() mimetype = mimetypes.guess_type(name)[0]",
"\"\"\" f = get_object_or_404(File, name=name) f.dump() mimetype = mimetypes.guess_type(name)[0] or",
"mimetype = mimetypes.guess_type(name)[0] or 'application/octet-stream' response = HttpResponse(f.content, content_type=mimetype) response['Content-Length']",
"as django_serve from database_files.models import File @cache_control(max_age=86400) def serve(request, name):",
"name=name) f.dump() mimetype = mimetypes.guess_type(name)[0] or 'application/octet-stream' response = HttpResponse(f.content,",
"'application/octet-stream' response = HttpResponse(f.content, content_type=mimetype) response['Content-Length'] = f.size return response",
"mimetypes.guess_type(name)[0] or 'application/octet-stream' response = HttpResponse(f.content, content_type=mimetype) response['Content-Length'] = f.size",
"*args, **kwargs): \"\"\" First attempts to serve the file from",
"or kwargs.get('path') document_root = kwargs.get('document_root') document_root = document_root or settings.MEDIA_ROOT",
"kwargs.get('document_root') document_root = document_root or settings.MEDIA_ROOT try: # First attempt",
"name = kwargs.get('name') or kwargs.get('path') document_root = kwargs.get('document_root') document_root =",
"from django.http import Http404, HttpResponse from django.shortcuts import get_object_or_404 from",
"document_root = document_root or settings.MEDIA_ROOT try: # First attempt to",
"import settings from django.http import Http404, HttpResponse from django.shortcuts import"
] |
[
"sime size.\") if self._rate < 0 or self._rate > 1:",
"the filtering. parameters : :obj:`Dict` Parameters used to define the",
"noise. Attributes ---------- rem_indx : :obj:`List` Removed indexes (rows) from",
"pandas as pd from abc import ABC class Injector(ABC): \"\"\"Base",
"class must be >= 2.\") if self._attrs.shape[0] != self.labels.shape[0]: raise",
"self._labels = pd.DataFrame(labels) else: self._labels = labels self._rate = rate",
"self._num_noise = int(self._rate * self._attrs.shape[0]) self._label_types = set(self.labels[0].unique()) @property def",
"after the filtering. parameters : :obj:`Dict` Parameters used to define",
"self._rate > 1: raise ValueError(\"\") def _gen_random(self, seed: int =",
"\"\"\" def __init__(self, attributes, labels, rate: float = 0.1) ->",
"[] if not isinstance(attributes, pd.DataFrame): self._attrs = pd.DataFrame(attributes) else: self._attrs",
"123. \"\"\" rng = np.random.default_rng(seed) for example in self._new_noise: self._labels.iloc[example]",
"Defaults to 123. \"\"\" rng = np.random.default_rng(seed) for example in",
"np.random.default_rng(seed) for example in self._new_noise: self._labels.iloc[example] = rng.choice(list(self._label_types - set(self._labels.iloc[example])))",
"the sime size.\") if self._rate < 0 or self._rate >",
"pd.DataFrame(labels) else: self._labels = labels self._rate = rate self.verify() self._num_noise",
":obj:`Dict` Parameters used to define the behaviour of the filter.",
"isinstance(labels, pd.DataFrame): self._labels = pd.DataFrame(labels) else: self._labels = labels self._rate",
"self._rate < 0 or self._rate > 1: raise ValueError(\"\") def",
"1: raise ValueError(\"\") def _gen_random(self, seed: int = None): \"\"\"[summary]",
":obj:`Sequence` Filtered independent attributes(X) of the dataset. clean_classes : :obj:`Sequence`",
"if self._attrs.shape[0] != self.labels.shape[0]: raise ValueError(\"Attributes and classes must have",
"the filter. clean_data : :obj:`Sequence` Filtered independent attributes(X) of the",
"import numpy as np import pandas as pd from abc",
"of artificial noise. Attributes ---------- rem_indx : :obj:`List` Removed indexes",
"labels self._rate = rate self.verify() self._num_noise = int(self._rate * self._attrs.shape[0])",
": :obj:`List` Removed indexes (rows) from the dataset after the",
"the dataset. clean_classes : :obj:`Sequence` Filtered target attributes(y) of the",
"not isinstance(labels, pd.DataFrame): self._labels = pd.DataFrame(labels) else: self._labels = labels",
"ValueError(\"Number of examples in the minority class must be >=",
"None: self._new_noise = [] if not isinstance(attributes, pd.DataFrame): self._attrs =",
"= rate self.verify() self._num_noise = int(self._rate * self._attrs.shape[0]) self._label_types =",
"2: raise ValueError(\"Number of examples in the minority class must",
"> 1: raise ValueError(\"\") def _gen_random(self, seed: int = None):",
"@property def noise_indx(self): return self._new_noise def verify(self) -> None: if",
"the minority class must be >= 2.\") if self._attrs.shape[0] !=",
"of the dataset. \"\"\" def __init__(self, attributes, labels, rate: float",
"from abc import ABC class Injector(ABC): \"\"\"Base class for the",
"return self._new_noise def verify(self) -> None: if min(self._labels.value_counts()) < 2:",
"return self._labels @property def noise_indx(self): return self._new_noise def verify(self) ->",
"= int(self._rate * self._attrs.shape[0]) self._label_types = set(self.labels[0].unique()) @property def labels(self):",
"classes must have the sime size.\") if self._rate < 0",
"size.\") if self._rate < 0 or self._rate > 1: raise",
"def _gen_random(self, seed: int = None): \"\"\"[summary] Args: seed (int,",
"!= self.labels.shape[0]: raise ValueError(\"Attributes and classes must have the sime",
"must be >= 2.\") if self._attrs.shape[0] != self.labels.shape[0]: raise ValueError(\"Attributes",
"self._attrs = attributes if not isinstance(labels, pd.DataFrame): self._labels = pd.DataFrame(labels)",
"pd.DataFrame(attributes) else: self._attrs = attributes if not isinstance(labels, pd.DataFrame): self._labels",
"Removed indexes (rows) from the dataset after the filtering. parameters",
"self._labels = labels self._rate = rate self.verify() self._num_noise = int(self._rate",
"in the minority class must be >= 2.\") if self._attrs.shape[0]",
"Attributes ---------- rem_indx : :obj:`List` Removed indexes (rows) from the",
"float = 0.1) -> None: self._new_noise = [] if not",
"examples in the minority class must be >= 2.\") if",
"= np.random.default_rng(seed) for example in self._new_noise: self._labels.iloc[example] = rng.choice(list(self._label_types -",
":obj:`Sequence` Filtered target attributes(y) of the dataset. \"\"\" def __init__(self,",
"if min(self._labels.value_counts()) < 2: raise ValueError(\"Number of examples in the",
"injectors of artificial noise. Attributes ---------- rem_indx : :obj:`List` Removed",
"pd from abc import ABC class Injector(ABC): \"\"\"Base class for",
"labels(self): return self._labels @property def noise_indx(self): return self._new_noise def verify(self)",
"Filtered target attributes(y) of the dataset. \"\"\" def __init__(self, attributes,",
"= pd.DataFrame(attributes) else: self._attrs = attributes if not isinstance(labels, pd.DataFrame):",
"Injector(ABC): \"\"\"Base class for the injectors of artificial noise. Attributes",
"of examples in the minority class must be >= 2.\")",
"if self._rate < 0 or self._rate > 1: raise ValueError(\"\")",
"optional): [description]. Defaults to 123. \"\"\" rng = np.random.default_rng(seed) for",
"the dataset. \"\"\" def __init__(self, attributes, labels, rate: float =",
"to 123. \"\"\" rng = np.random.default_rng(seed) for example in self._new_noise:",
"= None): \"\"\"[summary] Args: seed (int, optional): [description]. Defaults to",
"attributes if not isinstance(labels, pd.DataFrame): self._labels = pd.DataFrame(labels) else: self._labels",
"clean_data : :obj:`Sequence` Filtered independent attributes(X) of the dataset. clean_classes",
"the injectors of artificial noise. Attributes ---------- rem_indx : :obj:`List`",
"rate: float = 0.1) -> None: self._new_noise = [] if",
"None: if min(self._labels.value_counts()) < 2: raise ValueError(\"Number of examples in",
"self.labels.shape[0]: raise ValueError(\"Attributes and classes must have the sime size.\")",
"\"\"\"Base class for the injectors of artificial noise. Attributes ----------",
"raise ValueError(\"\") def _gen_random(self, seed: int = None): \"\"\"[summary] Args:",
"(int, optional): [description]. Defaults to 123. \"\"\" rng = np.random.default_rng(seed)",
"def verify(self) -> None: if min(self._labels.value_counts()) < 2: raise ValueError(\"Number",
"have the sime size.\") if self._rate < 0 or self._rate",
"ValueError(\"Attributes and classes must have the sime size.\") if self._rate",
"= 0.1) -> None: self._new_noise = [] if not isinstance(attributes,",
"or self._rate > 1: raise ValueError(\"\") def _gen_random(self, seed: int",
"0.1) -> None: self._new_noise = [] if not isinstance(attributes, pd.DataFrame):",
"set(self.labels[0].unique()) @property def labels(self): return self._labels @property def noise_indx(self): return",
"used to define the behaviour of the filter. clean_data :",
"dataset. clean_classes : :obj:`Sequence` Filtered target attributes(y) of the dataset.",
"target attributes(y) of the dataset. \"\"\" def __init__(self, attributes, labels,",
"the behaviour of the filter. clean_data : :obj:`Sequence` Filtered independent",
"of the dataset. clean_classes : :obj:`Sequence` Filtered target attributes(y) of",
":obj:`List` Removed indexes (rows) from the dataset after the filtering.",
"* self._attrs.shape[0]) self._label_types = set(self.labels[0].unique()) @property def labels(self): return self._labels",
"ValueError(\"\") def _gen_random(self, seed: int = None): \"\"\"[summary] Args: seed",
"clean_classes : :obj:`Sequence` Filtered target attributes(y) of the dataset. \"\"\"",
"seed: int = None): \"\"\"[summary] Args: seed (int, optional): [description].",
"= attributes if not isinstance(labels, pd.DataFrame): self._labels = pd.DataFrame(labels) else:",
"define the behaviour of the filter. clean_data : :obj:`Sequence` Filtered",
"verify(self) -> None: if min(self._labels.value_counts()) < 2: raise ValueError(\"Number of",
"< 0 or self._rate > 1: raise ValueError(\"\") def _gen_random(self,",
"int = None): \"\"\"[summary] Args: seed (int, optional): [description]. Defaults",
"__init__(self, attributes, labels, rate: float = 0.1) -> None: self._new_noise",
"Filtered independent attributes(X) of the dataset. clean_classes : :obj:`Sequence` Filtered",
"np import pandas as pd from abc import ABC class",
"dataset. \"\"\" def __init__(self, attributes, labels, rate: float = 0.1)",
"Args: seed (int, optional): [description]. Defaults to 123. \"\"\" rng",
"and classes must have the sime size.\") if self._rate <",
"artificial noise. Attributes ---------- rem_indx : :obj:`List` Removed indexes (rows)",
">= 2.\") if self._attrs.shape[0] != self.labels.shape[0]: raise ValueError(\"Attributes and classes",
"rng = np.random.default_rng(seed) for example in self._new_noise: self._labels.iloc[example] = rng.choice(list(self._label_types",
"filtering. parameters : :obj:`Dict` Parameters used to define the behaviour",
"self._attrs = pd.DataFrame(attributes) else: self._attrs = attributes if not isinstance(labels,",
"import ABC class Injector(ABC): \"\"\"Base class for the injectors of",
"pd.DataFrame): self._labels = pd.DataFrame(labels) else: self._labels = labels self._rate =",
"if not isinstance(labels, pd.DataFrame): self._labels = pd.DataFrame(labels) else: self._labels =",
"pd.DataFrame): self._attrs = pd.DataFrame(attributes) else: self._attrs = attributes if not",
"labels, rate: float = 0.1) -> None: self._new_noise = []",
"= pd.DataFrame(labels) else: self._labels = labels self._rate = rate self.verify()",
": :obj:`Sequence` Filtered target attributes(y) of the dataset. \"\"\" def",
"self._labels @property def noise_indx(self): return self._new_noise def verify(self) -> None:",
"to define the behaviour of the filter. clean_data : :obj:`Sequence`",
"class Injector(ABC): \"\"\"Base class for the injectors of artificial noise.",
"attributes, labels, rate: float = 0.1) -> None: self._new_noise =",
"if not isinstance(attributes, pd.DataFrame): self._attrs = pd.DataFrame(attributes) else: self._attrs =",
"= [] if not isinstance(attributes, pd.DataFrame): self._attrs = pd.DataFrame(attributes) else:",
"parameters : :obj:`Dict` Parameters used to define the behaviour of",
"= set(self.labels[0].unique()) @property def labels(self): return self._labels @property def noise_indx(self):",
"not isinstance(attributes, pd.DataFrame): self._attrs = pd.DataFrame(attributes) else: self._attrs = attributes",
"None): \"\"\"[summary] Args: seed (int, optional): [description]. Defaults to 123.",
"rate self.verify() self._num_noise = int(self._rate * self._attrs.shape[0]) self._label_types = set(self.labels[0].unique())",
"filter. clean_data : :obj:`Sequence` Filtered independent attributes(X) of the dataset.",
"numpy as np import pandas as pd from abc import",
"behaviour of the filter. clean_data : :obj:`Sequence` Filtered independent attributes(X)",
"attributes(X) of the dataset. clean_classes : :obj:`Sequence` Filtered target attributes(y)",
"<reponame>TVect/NoiseFiltersPy<gh_stars>1-10 import numpy as np import pandas as pd from",
"---------- rem_indx : :obj:`List` Removed indexes (rows) from the dataset",
"rem_indx : :obj:`List` Removed indexes (rows) from the dataset after",
"as pd from abc import ABC class Injector(ABC): \"\"\"Base class",
"else: self._attrs = attributes if not isinstance(labels, pd.DataFrame): self._labels =",
"< 2: raise ValueError(\"Number of examples in the minority class",
"def noise_indx(self): return self._new_noise def verify(self) -> None: if min(self._labels.value_counts())",
"_gen_random(self, seed: int = None): \"\"\"[summary] Args: seed (int, optional):",
"raise ValueError(\"Attributes and classes must have the sime size.\") if",
"for the injectors of artificial noise. Attributes ---------- rem_indx :",
"the dataset after the filtering. parameters : :obj:`Dict` Parameters used",
"attributes(y) of the dataset. \"\"\" def __init__(self, attributes, labels, rate:",
"isinstance(attributes, pd.DataFrame): self._attrs = pd.DataFrame(attributes) else: self._attrs = attributes if",
"= labels self._rate = rate self.verify() self._num_noise = int(self._rate *",
"class for the injectors of artificial noise. Attributes ---------- rem_indx",
"independent attributes(X) of the dataset. clean_classes : :obj:`Sequence` Filtered target",
"self._new_noise def verify(self) -> None: if min(self._labels.value_counts()) < 2: raise",
"self._attrs.shape[0] != self.labels.shape[0]: raise ValueError(\"Attributes and classes must have the",
"-> None: if min(self._labels.value_counts()) < 2: raise ValueError(\"Number of examples",
"must have the sime size.\") if self._rate < 0 or",
"def labels(self): return self._labels @property def noise_indx(self): return self._new_noise def",
"ABC class Injector(ABC): \"\"\"Base class for the injectors of artificial",
"self._new_noise = [] if not isinstance(attributes, pd.DataFrame): self._attrs = pd.DataFrame(attributes)",
"Parameters used to define the behaviour of the filter. clean_data",
"indexes (rows) from the dataset after the filtering. parameters :",
"self._label_types = set(self.labels[0].unique()) @property def labels(self): return self._labels @property def",
"as np import pandas as pd from abc import ABC",
"raise ValueError(\"Number of examples in the minority class must be",
"(rows) from the dataset after the filtering. parameters : :obj:`Dict`",
"2.\") if self._attrs.shape[0] != self.labels.shape[0]: raise ValueError(\"Attributes and classes must",
"else: self._labels = labels self._rate = rate self.verify() self._num_noise =",
"from the dataset after the filtering. parameters : :obj:`Dict` Parameters",
": :obj:`Sequence` Filtered independent attributes(X) of the dataset. clean_classes :",
"import pandas as pd from abc import ABC class Injector(ABC):",
"be >= 2.\") if self._attrs.shape[0] != self.labels.shape[0]: raise ValueError(\"Attributes and",
"minority class must be >= 2.\") if self._attrs.shape[0] != self.labels.shape[0]:",
"@property def labels(self): return self._labels @property def noise_indx(self): return self._new_noise",
"-> None: self._new_noise = [] if not isinstance(attributes, pd.DataFrame): self._attrs",
"\"\"\" rng = np.random.default_rng(seed) for example in self._new_noise: self._labels.iloc[example] =",
": :obj:`Dict` Parameters used to define the behaviour of the",
"[description]. Defaults to 123. \"\"\" rng = np.random.default_rng(seed) for example",
"\"\"\"[summary] Args: seed (int, optional): [description]. Defaults to 123. \"\"\"",
"self._attrs.shape[0]) self._label_types = set(self.labels[0].unique()) @property def labels(self): return self._labels @property",
"seed (int, optional): [description]. Defaults to 123. \"\"\" rng =",
"0 or self._rate > 1: raise ValueError(\"\") def _gen_random(self, seed:",
"def __init__(self, attributes, labels, rate: float = 0.1) -> None:",
"int(self._rate * self._attrs.shape[0]) self._label_types = set(self.labels[0].unique()) @property def labels(self): return",
"min(self._labels.value_counts()) < 2: raise ValueError(\"Number of examples in the minority",
"noise_indx(self): return self._new_noise def verify(self) -> None: if min(self._labels.value_counts()) <",
"of the filter. clean_data : :obj:`Sequence` Filtered independent attributes(X) of",
"self._rate = rate self.verify() self._num_noise = int(self._rate * self._attrs.shape[0]) self._label_types",
"abc import ABC class Injector(ABC): \"\"\"Base class for the injectors",
"self.verify() self._num_noise = int(self._rate * self._attrs.shape[0]) self._label_types = set(self.labels[0].unique()) @property",
"dataset after the filtering. parameters : :obj:`Dict` Parameters used to"
] |
[
"Cellphone\") emergency_email = TextField(\"Emergency Contact Email\", [ validators.Required(message = \"Enter",
"render_kw={\"class\": 'text'}, description = \"Principal Email\") cs_teacher_name = TextField(\"CS Teacher",
"to come to hackBCA?\" free_response1_prompt_mentor = \"Please list languages/frameworks/technologies that",
"= \"School Name\") gender = SelectField(\"Gender\", [validators.Required(message = \"You must",
"= TextField(\"Emergency Contact Home Number\", [ validators.Required(message = \"Enter your",
"Password\", [ validators.Required(message = \"You must choose a new password.\"),",
"confirm_password = PasswordField(\"Confirm Password\", render_kw={\"class\": 'text'}, description = \"Confirm Password\")",
"= beginner_choices, render_kw={\"class\": 'text'}, description = \"Are you a beginner?\")",
"the MLH Privacy Policy.\", default = False) def validate(self): links",
"'text'}, description = \"Principal Name\") school_principal_email = TextField(\"Principal Email\", [",
"= TextField(\"Company/School Name\", [ validators.Required(message = \"Enter your company/schools's name.\")",
"match.\") attending_choices = [ (\"Attending\", \"Yes, I will!\"), (\"Not Attending\",",
"Name\") emergency_home_num = TextField(\"Emergency Contact Home Number\", [ validators.Required(message =",
"= \"Please read and agree to the MLH Terms and",
"\"You must select an option.\")], choices = grade_choices, render_kw={\"class\": 'text'},",
"\"American Indian or Alaskan Native\"), (\"multiracial\", \"Multiracial\"), (\"hispanic\", \"Hispanic origin\"),",
"[ validators.optional(), validators.URL(message = \"Invalid URL.\") ], render_kw={\"class\": 'text'}, description",
"Link (Optional)\") other_link = TextField(\"other\", [ validators.optional(), validators.URL(message = \"Invalid",
"attr) if not rv: return False return True def validate_other_gender(form,",
"if form['gender'].data == 'other' and field.data == \"\": raise ValidationError(\"Enter",
"= \"Please enter a valid phone number.\") ], render_kw={\"class\": 'text'},",
"[ (\"\", \"Are you a beginner?\"), (\"yes\", \"Yes\"), (\"no\", \"No\")",
"emergency_name = TextField(\"Emergency Contact Full Name\", [ validators.Required(message = \"You",
"validators.Required(message = \"You must answer this question.\"), validators.Length(max = 1500,",
"return True def validate_other_gender(form, field): if form['gender'].data == 'other' and",
"PasswordField(\"New Password\", [ validators.Required(message = \"You must choose a new",
"guardian_home_num = TextField(\"Guardian Home Number\", [ validators.Required(message = \"Enter your",
"a valid phone number.\") ], render_kw={\"class\": 'text'}, description = \"Phone",
"#2 (Optional)\") link3 = TextField(\"Link #3\", [ validators.optional(), validators.URL(message =",
"enter a name.\") ], render_kw={\"class\": 'text'}, description = \"Emergency Contact",
"PasswordField(\"Password\", [ validators.Required(message = \"You must enter your current password.\"),",
"[ validators.Required(message = \"You must enter your current password.\"), validators.Length(min",
"any allergies?\") # medical_information = TextAreaField(\"Medical Information\", [ # validators.optional(),",
"'text'}, description = \"Current Password\") new_password = PasswordField(\"New Password\", [",
"= TextField(\"Email\", [ validators.Required(message = \"Enter an email.\"), validators.Email(message =",
"must enter a last name.\") ], render_kw={\"class\": 'text'}, description =",
"\"Password\") confirm_password = PasswordField(\"<PASSWORD> Password\", render_kw={\"class\": 'text'}, description = \"Confirm",
"name.\") ], render_kw={\"class\": 'text'}, description = \"Guardian Name\") guardian_home_num =",
"your shirt size?\", [validators.Required(message = \"You must select an option.\")],",
"== \"\": raise ValidationError(\"Enter your gender.\") class MentorRegistrationForm(Form): email =",
"hackBCA III.\")], render_kw={\"class\": 'text'}, choices = attending_choices, description = \"Will",
"home number.\"), validators.Regexp(phone_regex, message = \"Please enter a valid phone",
"option.\")], choices = ethnicity_choices, render_kw={\"class\": 'text'}, description = \"Ethnicity\") grade",
"Cellphone\") guardian_email = TextField(\"Guardian Email\", [ validators.Required(message = \"Enter an",
"= [ (\"\", \"What grade are you in?\"), (\"9\", \"9th\"),",
"Number\", [ # validators.Required(message = \"Confirm your preferred contact number.\"),",
"= \"Please read and agree to the MLH Code of",
"link in links: #Temporarily prefix all links with http:// if",
"Teacher Name\", [ validators.optional(), ], render_kw={\"class\": 'text'}, description = \"CS",
"= val setattr(self, link, attr) rv = Form.validate(self) for link",
"TextField(\"Link #1\", [ validators.optional(), validators.URL(message = \"Invalid URL.\") ], render_kw={\"class\":",
"Privacy Policy.\", default = False) def validate_confirm_password(form, field): password =",
"class MentorRegistrationForm(Form): email = TextField(\"Email\", [ validators.Required(message = \"Enter an",
"must answer this question.\"), validators.Length(max = 1500, message = \"Response",
"validators.Required(message = \"Enter your emergency contact's cellphone.\"), validators.Regexp(phone_regex, message =",
"'text'}, description = \"Guardian Home Number\") guardian_cell_num = TextField(\"Guardian Cellphone\",",
"medical_information = TextAreaField(\"Medical Information\", [ # validators.optional(), # ], description",
"and agree to our rules.\") # ], description = \"I",
"(\"10\", \"10th\"), (\"11\", \"11th\"), (\"12\", \"12th\") ] shirt_sizes = [",
"description = \"Current Password\") new_password = PasswordField(\"New Password\", [ validators.Required(message",
"TextField(\"LinkedIn\", [ validators.optional(), validators.URL(message = \"Invalid URL.\") ], render_kw={\"class\": 'text'},",
"description = \"Link #3 (Optional)\") password = PasswordField(\"Password\", [ validators.Required(message",
"TextAreaField(free_response1_prompt_mentor, [ validators.Length(max = 1500, message = \"Response must be",
"than 1500 characters long.\") ], render_kw={\"class\": 'text'}, description = \"1500",
"you a beginner?\") ethnicity = SelectField(\"Ethnicity\", [validators.Required(message = \"You must",
"agree\",[ # validators.Required(message = \"Please read and agree to our",
"= \"Will you be at hackBCA?\") # t_shirt_size = SelectField(\"What",
"attr) if not rv: return False return True class LoginForm(Form):",
"school_phone_num = TextField(\"School Phone Number\", [ validators.Required(message = \"Enter school's",
"TextField(\"Principal Email\", [ validators.Required(message = \"Enter an email.\"), validators.Email(message =",
"about? (ex. Other allergies, illnesses, etc.)\") # hackbca_rules = BooleanField(\"I",
"long.\") ], render_kw={\"class\": 'text'}, description = \"1500 characters maximum.\") mentor_free_response2",
"Contact Cellphone\") emergency_email = TextField(\"Emergency Contact Email\", [ validators.Required(message =",
"description = \"I have read & agree to the MLH",
"forth by hackBCA.\", default = False) # mlh_terms = BooleanField(\"I",
")], render_kw={\"class\": 'text'}, description = \"CS Teacher Email (if applicable)\")",
"\"Enter an email.\"), validators.Email(message = \"Invalid email address.\") ], render_kw={\"class\":",
"I will!\"), (\"Not Attending\", \"No, I won't.\") ] class RsvpForm(Form):",
"validators.optional(), # ], description = \"Are there any other medical",
"for link in links: #Temporarily prefix all links with http://",
"password = form['password'].data if len(password) >= 8 and password !=",
"\"CS Teacher Name (if applicable)\") cs_teacher_email = TextField(\"CS Teacher Email\",",
"hackBCA.\", default = False) # mlh_terms = BooleanField(\"I agree\",[ #",
"all links with http:// if they are missing it attr",
"'text'}, description = \"Password\") confirm_password = PasswordField(\"<PASSWORD> Password\", render_kw={\"class\": 'text'},",
"free_response1_prompt_mentor = \"Please list languages/frameworks/technologies that you would like to",
"'text'}, description = \"Gender\") beginner = SelectField(\"Are you a beginner?\",",
"must select an option.\")], choices = num_hackathons_choices_mentor, render_kw={\"class\": 'text'}, description",
"validators.Required(message = \"You must enter a password.\"), validators.Length(min = 8,",
"= attending_choices) # phone = TextField(\"Phone Number\", [ # validators.Required(message",
"\"Ethnicity\"), (\"white\", \"White\"), (\"african_american\", \"African American\"), (\"asian_pacific\", \"Asian or Pacific",
"(\"asian_pacific\", \"Asian or Pacific Islander\"), (\"american_indian_alaskan_native\", \"American Indian or Alaskan",
"first name.\") ], render_kw={\"class\": 'text'}, description = \"First Name\") last_name",
"[ validators.Required(message = \"Enter an email.\"), validators.Email(message = \"Invalid email",
"your school address.\"), ], render_kw={\"class\": 'text'}, description = \"School Address\")",
"\"12th\") ] shirt_sizes = [ (\"\", \"What is your shirt",
"password = form['new_password'].data if len(password) >= 8 and password !=",
"BooleanField(\"I agree\",[ # validators.Required(message = \"Please read and agree to",
"\"What is your shirt size?\"), (\"XS\", \"Extra Small\"), (\"S\", \"Small\"),",
"], render_kw={\"class\": 'text'}, description = \"Email\") first_name = TextField(\"First Name\",",
"you would like to mentor students in.\" free_response2_prompt_mentor = \"Would",
"= \"Enter your emergency contact's home number.\"), validators.Regexp(phone_regex, message =",
"\"Emergency Contact Email\") school_address = TextField(\"School Address\", [ validators.Required(message =",
"ethnicity_choices, render_kw={\"class\": 'text'}, description = \"Ethnicity\") grade = SelectField(\"Grade\", [validators.Required(message",
"= \"Enter your emergency contact's cellphone.\"), validators.Regexp(phone_regex, message = \"Please",
"I won't.\") ] class RsvpForm(Form): # attending = RadioField(\"Are you",
"= \"Guardian Home Number\") guardian_cell_num = TextField(\"Guardian Cellphone\", [ validators.Required(message",
"school_town = TextField(\"School Town\", [ validators.Required(message = \"Enter your school",
"address.\"), ], render_kw={\"class\": 'text'}, description = \"School Address\") school_town =",
"SelectField, TextAreaField, BooleanField, validators, ValidationError, RadioField import re phone_regex =",
"at?\") mentor_free_response1 = TextAreaField(free_response1_prompt_mentor, [ validators.Length(max = 1500, message =",
"validators.Required(message = \"Enter your guardian's cellphone number.\"), validators.Regexp(phone_regex, message =",
"description = \"How many hackathons have you attended?\") free_response1 =",
"class HackerRegistrationForm(Form): email = TextField(\"Email\", [ validators.Required(message = \"Enter an",
"Other allergies, illnesses, etc.)\") # hackbca_rules = BooleanField(\"I agree\",[ #",
"hackathons have you mentored at?\"), (\"0\", \"0\"), (\"1\", \"1\"), (\"2\",",
"Conduct.\") ], description = \"I have read & agree to",
"= \"Invalid email address.\" )], render_kw={\"class\": 'text'}, description = \"Principal",
"\"Company/School Name\") phone = TextField(\"Phone Number\", [ validators.Required(message = \"Enter",
"a valid phone number.\") ], render_kw={\"class\": 'text'}, description = \"School",
"'text'}, description = \"Password\") class EmailForm(Form): email = TextField(\"Email\", [",
"and agree to the MLH Code of Conduct.\") ], description",
"characters.\") ], render_kw={\"class\": 'text'}, description = \"Password\") confirm_password = PasswordField(\"Confirm",
"be less than 1500 characters long.\") ], render_kw={\"class\": 'text'}, description",
"enter a name.\"), ], render_kw={\"class\": 'text'}, description = \"Principal Name\")",
"= getattr(self, link) val = attr.data originalValues[link] = val if",
"and password != field.data: raise ValidationError(\"Passwords must match.\") attending_choices =",
"[ validators.Required(message = \"Please read and agree to the MLH",
"URL.\") ], render_kw={\"class\": 'text'}, description = \"Github Link (Optional)\") linkedin_link",
"= TextField(\"School Name\", [ validators.Required(message = \"Enter your school's name.\")",
"Terms and Conditions.\") ], description = \"I agree to the",
"], render_kw={\"class\": 'text'}, description = \"Do you have any dietary",
"school = TextField(\"School Name\", [ validators.Required(message = \"Enter your school's",
"\"Response must be less than 1500 characters long.\") ], render_kw={\"class\":",
"description = \"Confirm New Password\") def validate_confirm_password(form, field): password =",
"= \"Guardian Name\") guardian_home_num = TextField(\"Guardian Home Number\", [ validators.Required(message",
"= SelectField(\"Gender\", [validators.Required(message = \"You must select an option.\")], choices",
"(\"L\", \"Large\"), (\"XL\", \"Extra Large\") ] type_account_choices = [ (\"hacker\",",
"choices = beginner_choices, render_kw={\"class\": 'text'}, description = \"Are you a",
"description = \"Last Name\") school = TextField(\"School Name\", [ validators.Required(message",
"\"1500 characters maximum.\") link1 = TextField(\"Link #1\", [ validators.optional(), validators.URL(message",
"at least 8 characters.\") ], render_kw={\"class\": 'text'}, description = \"Current",
"render_kw={\"class\": 'text'}, description = \"Last Name\") class ChangePasswordForm(Form): password =",
"choices = ethnicity_choices, render_kw={\"class\": 'text'}, description = \"Ethnicity\") grade =",
"# medical_information = TextAreaField(\"Medical Information\", [ # validators.optional(), # ],",
"in links: #Temporarily prefix all links with http:// if they",
"], description = \"Do you have any allergies?\") # medical_information",
"agree to the MLH Code of Conduct.\", default = False)",
"URL.\") ], render_kw={\"class\": 'text'}, description = \"LinkedIn Link (Optional)\") site_link",
"(\"S\", \"Small\"), (\"M\", \"Medium\"), (\"L\", \"Large\"), (\"XL\", \"Extra Large\") ]",
"MLH Terms and Conditions.\") ], description = \"I agree to",
"choices = num_hackathons_choices, render_kw={\"class\": 'text'}, description = \"How many hackathons",
"should know about? (ex. Other allergies, illnesses, etc.)\") # hackbca_rules",
"= TextField(\"Principal Email\", [ validators.Required(message = \"Enter an email.\"), validators.Email(message",
"attending hackBCA III?\", [validators.Required(message = \"Please tell us if you",
"\"Confirm New Password\") def validate_confirm_password(form, field): password = form['new_password'].data if",
"description = \"School Phone Number\") school_principal_name = TextField(\"Principal Name\", [",
"phone = TextField(\"Phone Number\", [ validators.Required(message = \"Enter your preferred",
"are you in?\"), (\"9\", \"9th\"), (\"10\", \"10th\"), (\"11\", \"11th\"), (\"12\",",
"'text'}, description = \"1500 characters maximum.\") github_link = TextField(\"Github Link\",",
"\"Are there any other medical issues that we should know",
"Code of Conduct.\") # ], description = \"I agree to",
"# attending = RadioField(\"Are you attending hackBCA III?\", [validators.Required(message =",
"Native\"), (\"multiracial\", \"Multiracial\"), (\"hispanic\", \"Hispanic origin\"), (\"other\", \"Other\"), (\"rns\", \"Rather",
"confirm_password = PasswordField(\"<PASSWORD> Password\", render_kw={\"class\": 'text'}, description = \"Confirm Password\")",
"\"Enter your emergency contact's cellphone.\"), validators.Regexp(phone_regex, message = \"Please enter",
"PasswordField(\"Confirm Password\", render_kw={\"class\": 'text'}, description = \"Confirm Password\") mlh_coc =",
"render_kw={\"class\": 'text'}, description = \"1500 characters maximum.\") github_link = TextField(\"Github",
"], description = \"I agree to the rules set forth",
"actual values attr = getattr(self, link) attr.data = originalValues[link] setattr(self,",
"state.\"), ], render_kw={\"class\": 'text'}, description = \"School State\") school_phone_num =",
"Town\") school_state = TextField(\"School State\", [ validators.Required(message = \"Enter your",
"'text'}, description = \"Link #1 (Optional)\") link2 = TextField(\"Link #2\",",
"= \"Age\") num_hackathons = SelectField(\"How many hackathons have you attended?\",",
"= [ (\"Attending\", \"Yes, I will!\"), (\"Not Attending\", \"No, I",
"shirt_sizes, description = \"What is your shirt size?\") dietary_restrictions =",
"\"Link #1 (Optional)\") link2 = TextField(\"Link #2\", [ validators.optional(), validators.URL(message",
"[validators.Required(message = \"You must select an option.\")], choices = num_hackathons_choices,",
"attr = getattr(self, link) attr.data = originalValues[link] setattr(self, link, attr)",
"have you attended?\", [validators.Required(message = \"You must select an option.\")],",
"etc.)\") # hackbca_rules = BooleanField(\"I agree\",[ # validators.Required(message = \"Please",
"illnesses, etc.)\") # hackbca_rules = BooleanField(\"I agree\",[ # validators.Required(message =",
"'other' and field.data == \"\": raise ValidationError(\"Enter your gender.\") class",
"len(password) >= 8 and password != field.data: raise ValidationError(\"Passwords must",
"(\"\", \"Ethnicity\"), (\"white\", \"White\"), (\"african_american\", \"African American\"), (\"asian_pacific\", \"Asian or",
"validators.Required(message = \"Enter your school town.\"), ], render_kw={\"class\": 'text'}, description",
"'text'}, description = \"1500 characters maximum.\") link1 = TextField(\"Link #1\",",
"val = attr.data originalValues[link] = val if re.match(\"^(http|https)://\", val) is",
"originalValues[link] = val if re.match(\"^(http|https)://\", val) is None: val =",
"\"Principal Email\") cs_teacher_name = TextField(\"CS Teacher Name\", [ validators.optional(), ],",
"come to hackBCA?\" free_response1_prompt_mentor = \"Please list languages/frameworks/technologies that you",
"you mentored at?\") mentor_free_response1 = TextAreaField(free_response1_prompt_mentor, [ validators.Length(max = 1500,",
"link2 = TextField(\"Link #2\", [ validators.optional(), validators.URL(message = \"Invalid URL.\")",
"= \"Link #3 (Optional)\") password = PasswordField(\"Password\", [ validators.Required(message =",
"please briefly describe your ideas.\" class HackerRegistrationForm(Form): email = TextField(\"Email\",",
"(\"african_american\", \"African American\"), (\"asian_pacific\", \"Asian or Pacific Islander\"), (\"american_indian_alaskan_native\", \"American",
"is your shirt size?\", [validators.Required(message = \"You must select an",
"] num_hackathons_choices = [ (\"\", \"How many hackathons have you",
"[validators.Required(message = \"You must select an option.\")], choices = shirt_sizes,",
"values back to actual values attr = getattr(self, link) attr.data",
"\"Invalid URL.\") ], render_kw={\"class\": 'text'}, description = \"LinkedIn Link (Optional)\")",
"[ validators.Required(message = \"You must enter a first name.\") ],",
"attr) rv = Form.validate(self) for link in links: #Revert link",
"render_kw={\"class\": 'text'}, description = \"Confirm New Password\") def validate_confirm_password(form, field):",
"False return True def validate_other_gender(form, field): if form['gender'].data == 'other'",
"\"3\"), (\"4\", \"4\"), (\"5\", \"5+\") ] grade_choices = [ (\"\",",
"in links: #Revert link values back to actual values attr",
"(ex. Other allergies, illnesses, etc.)\") # hackbca_rules = BooleanField(\"I agree\",[",
"you like to run a workshop? If so, please briefly",
"= TextField(\"Link #2\", [ validators.optional(), validators.URL(message = \"Invalid URL.\") ],",
"to our rules.\") # ], description = \"I agree to",
"select an option.\")], choices = beginner_choices, render_kw={\"class\": 'text'}, description =",
"languages/frameworks/technologies that you would like to mentor students in.\" free_response2_prompt_mentor",
"= \"Invalid URL.\") ], render_kw={\"class\": 'text'}, description = \"Link #2",
"\"Invalid email address.\") ], render_kw={\"class\": 'text'}, description = \"Email\") first_name",
"attr.data = originalValues[link] setattr(self, link, attr) if not rv: return",
"\"\": raise ValidationError(\"Enter your gender.\") class MentorRegistrationForm(Form): email = TextField(\"Email\",",
"'text'}, description = \"CS Teacher Email (if applicable)\") # class",
"# validators.optional(), # ], description = \"Are there any other",
"choose a new password.\"), validators.Length(min = 8, message = \"Password",
"If so, please briefly describe your ideas.\" class HackerRegistrationForm(Form): email",
"render_kw={\"class\": 'text'}, description = \"Do you have any dietary restrictions?\")",
"less than 1500 characters long.\") ], render_kw={\"class\": 'text'}, description =",
"your emergency contact's cellphone.\"), validators.Regexp(phone_regex, message = \"Please enter a",
"agree to the MLH Code of Conduct.\") # ], description",
"validators.Required(message = \"Enter your emergency contact's home number.\"), validators.Regexp(phone_regex, message",
"link, attr) rv = Form.validate(self) for link in links: #Revert",
"\"Invalid URL.\") ], render_kw={\"class\": 'text'}, description = \"Other Link (Optional)\")",
"\"Please enter a valid phone number.\") ], render_kw={\"class\": 'text'}, description",
"\"You must select an option.\")], choices = gender_choices, render_kw={\"class\": 'text'},",
"= PasswordField(\"Confirm Password\", render_kw={\"class\": 'text'}, description = \"Confirm Password\") mlh_coc",
"origin\"), (\"other\", \"Other\"), (\"rns\", \"Rather Not Say\") ] num_hackathons_choices =",
"[ validators.Required(message = \"Enter your guardian's cellphone number.\"), validators.Regexp(phone_regex, message",
"= \"Invalid URL.\") ], render_kw={\"class\": 'text'}, description = \"Personal Site",
"enter a name.\") ], render_kw={\"class\": 'text'}, description = \"Guardian Name\")",
"\"African American\"), (\"asian_pacific\", \"Asian or Pacific Islander\"), (\"american_indian_alaskan_native\", \"American Indian",
"+ val attr.data = val setattr(self, link, attr) rv =",
"= \"Enter your guardian's cellphone number.\"), validators.Regexp(phone_regex, message = \"Please",
"Town\", [ validators.Required(message = \"Enter your school town.\"), ], render_kw={\"class\":",
"= TextField(\"School Phone Number\", [ validators.Required(message = \"Enter school's home",
"\"Invalid email address.\" )], render_kw={\"class\": 'text'}, description = \"Email\") class",
"an option.\")], choices = grade_choices, render_kw={\"class\": 'text'}, description = \"Grade\")",
"import re phone_regex = \"(\\+\\d+-?)?((\\(?\\d{3}\\)?)|(\\d{3}))-?\\d{3}-?\\d{4}$\" gender_choices = [ (\"\", \"Gender\"),",
"\"Enter your guardian's home number.\"), validators.Regexp(phone_regex, message = \"Please enter",
"validate_confirm_password(form, field): password = form['password'].data if len(password) >= 8 and",
"last name.\") ], render_kw={\"class\": 'text'}, description = \"Last Name\") school",
"= TextField(\"Link #1\", [ validators.optional(), validators.URL(message = \"Invalid URL.\") ],",
"RadioField(\"Are you attending hackBCA III?\", [validators.Required(message = \"Please tell us",
"#1 (Optional)\") link2 = TextField(\"Link #2\", [ validators.optional(), validators.URL(message =",
"name.\"), ], render_kw={\"class\": 'text'}, description = \"Principal Name\") school_principal_email =",
"= \"Confirm New Password\") def validate_confirm_password(form, field): password = form['new_password'].data",
"render_kw={\"class\": 'text'}, description = \"Other Link (Optional)\") password = PasswordField(\"Password\",",
"default = False) def validate_confirm_password(form, field): password = form['password'].data if",
"[ validators.Required(message = \"Enter your school town.\"), ], render_kw={\"class\": 'text'},",
"[ validators.optional(), validators.Email(message = \"Invalid email address.\" )], render_kw={\"class\": 'text'},",
"TextField(\"Email\", [ validators.Required(message = \"Enter an email.\"), validators.Email(message = \"Invalid",
"valid phone number.\") ], render_kw={\"class\": 'text'}, description = \"Phone Number\")",
"\"http://\" + val attr.data = val setattr(self, link, attr) rv",
"render_kw={\"class\": 'text'}, description = \"Age\") num_hackathons = SelectField(\"How many hackathons",
"(Optional)\") link3 = TextField(\"Link #3\", [ validators.optional(), validators.URL(message = \"Invalid",
"], render_kw={\"class\": 'text'}, description = \"Github Link (Optional)\") linkedin_link =",
"beginner?\", [validators.Required(message = \"You must select an option.\")], choices =",
"workshop? If so, please briefly describe your ideas.\" class HackerRegistrationForm(Form):",
"= \"(\\+\\d+-?)?((\\(?\\d{3}\\)?)|(\\d{3}))-?\\d{3}-?\\d{4}$\" gender_choices = [ (\"\", \"Gender\"), (\"male\", \"Male\"), (\"female\",",
"dietary restrictions?\") guardian_name = TextField(\"Guardian Full Name\", [ validators.Required(message =",
"(\"3\", \"3\"), (\"4\", \"4\"), (\"5\", \"5+\") ] num_hackathons_choices_mentor = [",
"long.\") ], render_kw={\"class\": 'text'}, description = \"1500 characters maximum.\") link1",
"= \"You must enter a name.\"), ], render_kw={\"class\": 'text'}, description",
"\"How many hackathons have you mentored at?\") mentor_free_response1 = TextAreaField(free_response1_prompt_mentor,",
"your age\") ], render_kw={\"class\": 'text'}, description = \"Age\") num_hackathons =",
"validators.Email(message = \"Invalid email address.\" )], render_kw={\"class\": 'text'}, description =",
"validators.Required(message = \"Enter your guardian's home number.\"), validators.Regexp(phone_regex, message =",
"None: val = \"http://\" + val attr.data = val setattr(self,",
"your shirt size?\"), (\"XS\", \"Extra Small\"), (\"S\", \"Small\"), (\"M\", \"Medium\"),",
"= \"CS Teacher Email (if applicable)\") # class MentorRsvpForm(Form): #",
"know about? (ex. Other allergies, illnesses, etc.)\") # hackbca_rules =",
"preferred contact number.\"), validators.Regexp(phone_regex, message = \"Please enter a valid",
"'text'}, description = \"Confirm Password\") def validate_confirm_password(form, field): password =",
"[ validators.Required(message = \"Enter your preferred contact number.\"), validators.Regexp(phone_regex, message",
")], render_kw={\"class\": 'text'}, description = \"Email\") class RecoverForm(Form): password =",
"\"Are you a beginner?\") ethnicity = SelectField(\"Ethnicity\", [validators.Required(message = \"You",
"8 and password != field.data: raise ValidationError(\"Passwords must match.\") attending_choices",
"[ validators.Required(message = \"You must enter a name.\"), ], render_kw={\"class\":",
"= \"Invalid email address.\") ], render_kw={\"class\": 'text'}, description = \"Email\")",
"\"Other Link (Optional)\") password = PasswordField(\"Password\", [ validators.Required(message = \"You",
"render_kw={\"class\": 'text'}, description = \"CS Teacher Email (if applicable)\") #",
"] beginner_choices = [ (\"\", \"Are you a beginner?\"), (\"yes\",",
"= \"Enter your school address.\"), ], render_kw={\"class\": 'text'}, description =",
"\"You must choose a new password.\"), validators.Length(min = 8, message",
"8 and password != field.data: raise ValidationError(\"Passwords must match.\") def",
"to actual values attr = getattr(self, link) attr.data = originalValues[link]",
"gender = SelectField(\"Gender\", [validators.Required(message = \"You must select an option.\")],",
"\"Guardian Cellphone\") guardian_email = TextField(\"Guardian Email\", [ validators.Required(message = \"Enter",
"\"You must enter a name.\") ], render_kw={\"class\": 'text'}, description =",
"description = \"Link #1 (Optional)\") link2 = TextField(\"Link #2\", [",
"field.data == \"\": raise ValidationError(\"Enter your gender.\") class MentorRegistrationForm(Form): email",
"\"Please tell us if you are attending hackBCA III.\")], render_kw={\"class\":",
"school address.\"), ], render_kw={\"class\": 'text'}, description = \"School Address\") school_town",
"message = \"Please enter a valid phone number.\") ], render_kw={\"class\":",
"Not Say\") ] beginner_choices = [ (\"\", \"Are you a",
"select an option.\")], choices = num_hackathons_choices_mentor, render_kw={\"class\": 'text'}, description =",
"\"You must enter a first name.\") ], render_kw={\"class\": 'text'}, description",
"validators.Required(message = \"You must choose a new password.\"), validators.Length(min =",
"type_account_choices = [ (\"hacker\", \"Hacker\"), (\"mentor\", \"Mentor\") ] free_response1_prompt =",
"\"School Name\") gender = SelectField(\"Gender\", [validators.Required(message = \"You must select",
"t_shirt_size = SelectField(\"What is your shirt size?\", [validators.Required(message = \"You",
"TextField(\"School Name\", [ validators.Required(message = \"Enter your school's name.\") ],",
"= \"Invalid URL.\") ], render_kw={\"class\": 'text'}, description = \"Other Link",
"and agree to the MLH Code of Conduct.\") # ],",
"\"Large\"), (\"XL\", \"Extra Large\") ] type_account_choices = [ (\"hacker\", \"Hacker\"),",
"school_address = TextField(\"School Address\", [ validators.Required(message = \"Enter your school",
"= \"Email\") first_name = TextField(\"First Name\", [ validators.Required(message = \"You",
"= [ (\"\", \"How many hackathons have you mentored at?\"),",
"description = \"Are there any other medical issues that we",
"(\"white\", \"White\"), (\"african_american\", \"African American\"), (\"asian_pacific\", \"Asian or Pacific Islander\"),",
"choices = grade_choices, render_kw={\"class\": 'text'}, description = \"Grade\") age =",
"validators.optional(), # ], description = \"Do you have any allergies?\")",
"= \"Are there any other medical issues that we should",
"new password.\"), validators.Length(min = 8, message = \"Password must be",
"name.\") ], render_kw={\"class\": 'text'}, description = \"Last Name\") class ChangePasswordForm(Form):",
"(\"2\", \"2\"), (\"3\", \"3\"), (\"4\", \"4\"), (\"5\", \"5+\") ] num_hackathons_choices_mentor",
"\"4\"), (\"5\", \"5+\") ] grade_choices = [ (\"\", \"What grade",
"town.\"), ], render_kw={\"class\": 'text'}, description = \"School Town\") school_state =",
"def validate_other_gender(form, field): if form['gender'].data == 'other' and field.data ==",
"= \"Response must be less than 1500 characters long.\") ],",
"option.\")], choices = beginner_choices, render_kw={\"class\": 'text'}, description = \"Are you",
"github_link = TextField(\"Github Link\", [ validators.optional(), validators.URL(message = \"Invalid URL.\")",
"= \"Confirm Password\") def validate_confirm_password(form, field): password = form['password'].data if",
"Attending\", \"No, I won't.\") ] class RsvpForm(Form): # attending =",
"description = \"Grade\") age = TextField(\"Age\", [ validators.Required(message = \"Enter",
"least 8 characters.\") ], render_kw={\"class\": 'text'}, description = \"Current Password\")",
">= 8 and password != field.data: raise ValidationError(\"Passwords must match.\")",
"= \"Invalid email address.\" )], render_kw={\"class\": 'text'}, description = \"CS",
"(\"1\", \"1\"), (\"2\", \"2\"), (\"3\", \"3\"), (\"4\", \"4\"), (\"5\", \"5+\")",
"a beginner?\", [validators.Required(message = \"You must select an option.\")], choices",
"render_kw={\"class\": 'text'}, description = \"LinkedIn Link (Optional)\") site_link = TextField(\"Personal",
"at?\"), (\"0\", \"0\"), (\"1\", \"1\"), (\"2\", \"2\"), (\"3\", \"3\"), (\"4\",",
"an email.\"), validators.Email(message = \"Invalid email address.\" )], render_kw={\"class\": 'text'},",
"to mentor students in.\" free_response2_prompt_mentor = \"Would you like to",
"age\") ], render_kw={\"class\": 'text'}, description = \"Age\") num_hackathons = SelectField(\"How",
"[ validators.Required(message = \"You must enter a name.\") ], render_kw={\"class\":",
"Name\") phone = TextField(\"Phone Number\", [ validators.Required(message = \"Enter your",
"Contact Email\") school_address = TextField(\"School Address\", [ validators.Required(message = \"Enter",
"cs_teacher_email = TextField(\"CS Teacher Email\", [ validators.optional(), validators.Email(message = \"Invalid",
"render_kw={\"class\": 'text'}, description = \"Guardian Name\") guardian_home_num = TextField(\"Guardian Home",
"description = \"1500 characters maximum.\") mentor_free_response2 = TextAreaField(free_response2_prompt_mentor, [ validators.Length(max",
"], render_kw={\"class\": 'text'}, description = \"Principal Name\") school_principal_email = TextField(\"Principal",
"values attr = getattr(self, link) attr.data = originalValues[link] setattr(self, link,",
"\"Password must be at least 8 characters.\") ], render_kw={\"class\": 'text'},",
"\"You must enter a last name.\") ], render_kw={\"class\": 'text'}, description",
"\"Hispanic origin\"), (\"other\", \"Other\"), (\"rns\", \"Rather Not Say\") ] num_hackathons_choices",
"description = \"Will you be at hackBCA?\") # t_shirt_size =",
"applicable)\") cs_teacher_email = TextField(\"CS Teacher Email\", [ validators.optional(), validators.Email(message =",
"[ validators.Required(message = \"Enter your emergency contact's home number.\"), validators.Regexp(phone_regex,",
"password.\"), validators.Length(min = 8, message = \"Password must be at",
"free_response2_prompt_mentor = \"Would you like to run a workshop? If",
"#1\", [ validators.optional(), validators.URL(message = \"Invalid URL.\") ], render_kw={\"class\": 'text'},",
"], render_kw={\"class\": 'text'}, description = \"Link #2 (Optional)\") link3 =",
"links = [\"github_link\", \"linkedin_link\", \"site_link\", \"other_link\"] originalValues = {} for",
"message = \"Password must be at least 8 characters.\") ],",
"phone number.\") ], render_kw={\"class\": 'text'}, description = \"Emergency Contact Home",
"SelectField(\"How many hackathons have you mentored at?\", [validators.Required(message = \"You",
"Phone Number\") school_principal_name = TextField(\"Principal Name\", [ validators.Required(message = \"You",
"phone number.\") ], render_kw={\"class\": 'text'}, description = \"Emergency Contact Cellphone\")",
"def validate(self): links = [\"github_link\", \"linkedin_link\", \"site_link\", \"other_link\"] originalValues =",
"\"4\"), (\"5\", \"5+\") ] num_hackathons_choices_mentor = [ (\"\", \"How many",
"number.\"), # validators.Regexp(phone_regex, message = \"Please enter a valid phone",
"gender_choices = [ (\"\", \"Gender\"), (\"male\", \"Male\"), (\"female\", \"Female\"), (\"other\",",
"= \"You must enter a last name.\") ], render_kw={\"class\": 'text'},",
"contact number.\"), validators.Regexp(phone_regex, message = \"Please enter a valid phone",
"render_kw={\"class\": 'text'}, description = \"Github Link (Optional)\") linkedin_link = TextField(\"LinkedIn\",",
"an option.\")], choices = num_hackathons_choices, render_kw={\"class\": 'text'}, description = \"How",
"\"Guardian Home Number\") guardian_cell_num = TextField(\"Guardian Cellphone\", [ validators.Required(message =",
"that we should know about? (ex. Other allergies, illnesses, etc.)\")",
"have any allergies?\") # medical_information = TextAreaField(\"Medical Information\", [ #",
"= \"I agree to the rules set forth by hackBCA.\",",
"def validate(self): #Man I love validators.URL links = [\"link1\", \"link2\",",
"HackerRegistrationForm(Form): email = TextField(\"Email\", [ validators.Required(message = \"Enter an email.\"),",
"= \"Are you a beginner?\") ethnicity = SelectField(\"Ethnicity\", [validators.Required(message =",
"your school town.\"), ], render_kw={\"class\": 'text'}, description = \"School Town\")",
"= \"Password\") confirm_password = PasswordField(\"<PASSWORD> Password\", render_kw={\"class\": 'text'}, description =",
"Restrictions\", [ validators.optional(), ], render_kw={\"class\": 'text'}, description = \"Do you",
"= SelectField(\"How many hackathons have you attended?\", [validators.Required(message = \"You",
"school_principal_email = TextField(\"Principal Email\", [ validators.Required(message = \"Enter an email.\"),",
"if they are missing it attr = getattr(self, link) val",
"have you been to?\"), (\"0\", \"0\"), (\"1\", \"1\"), (\"2\", \"2\"),",
"characters maximum.\") mentor_free_response2 = TextAreaField(free_response2_prompt_mentor, [ validators.Length(max = 1500, message",
"\"Gender\") beginner = SelectField(\"Are you a beginner?\", [validators.Required(message = \"You",
"render_kw={\"class\": 'text'}, description = \"Personal Site Link (Optional)\") other_link =",
"# ], description = \"Phone Number Confirmation\") # t_shirt_size =",
"# validators.Regexp(phone_regex, message = \"Please enter a valid phone number.\")",
"'text'}, description = \"Link #2 (Optional)\") link3 = TextField(\"Link #3\",",
"phone_regex = \"(\\+\\d+-?)?((\\(?\\d{3}\\)?)|(\\d{3}))-?\\d{3}-?\\d{4}$\" gender_choices = [ (\"\", \"Gender\"), (\"male\", \"Male\"),",
"description = \"Emergency Contact Email\") school_address = TextField(\"School Address\", [",
"Contact Cellphone\", [ validators.Required(message = \"Enter your emergency contact's cellphone.\"),",
"email address.\") ], render_kw={\"class\": 'text'}, description = \"Email\") first_name =",
"\"Enter your emergency contact's home number.\"), validators.Regexp(phone_regex, message = \"Please",
"shirt size?\", [validators.Required(message = \"You must select an option.\")], choices",
"shirt size?\") # food_allergies = TextAreaField(\"Allergies\", [ # validators.optional(), #",
")], render_kw={\"class\": 'text'},description = \"Email\") password = PasswordField(\"Password\", [], render_kw={\"class\":",
"is your shirt size?\") dietary_restrictions = TextField(\"Dietary Restrictions\", [ validators.optional(),",
"Information\", [ # validators.optional(), # ], description = \"Are there",
"rules.\") # ], description = \"I agree to the rules",
"characters long.\") ], render_kw={\"class\": 'text'}, description = \"1500 characters maximum.\")",
"Name\", [ validators.Required(message = \"You must enter a name.\") ],",
"TextField(\"School Phone Number\", [ validators.Required(message = \"Enter school's home number.\"),",
"your shirt size?\") dietary_restrictions = TextField(\"Dietary Restrictions\", [ validators.optional(), ],",
"name.\") ], render_kw={\"class\": 'text'}, description = \"Emergency Contact Name\") emergency_home_num",
"] grade_choices = [ (\"\", \"What grade are you in?\"),",
"emergency contact's cellphone.\"), validators.Regexp(phone_regex, message = \"Please enter a valid",
"description = \"Emergency Contact Cellphone\") emergency_email = TextField(\"Emergency Contact Email\",",
"val if re.match(\"^(http|https)://\", val) is None: val = \"http://\" +",
"TextField(\"Personal Site\", [ validators.optional(), validators.URL(message = \"Invalid URL.\") ], render_kw={\"class\":",
"originalValues[link] setattr(self, link, attr) if not rv: return False return",
"validators.Required(message = \"Please read and agree to the MLH Terms",
"description = \"Password\") confirm_password = PasswordField(\"<PASSWORD> Password\", render_kw={\"class\": 'text'}, description",
"], render_kw={\"class\": 'text'}, description = \"First Name\") last_name = TextField(\"Last",
"# validators.Required(message = \"Please read and agree to the MLH",
"= TextField(\"CS Teacher Email\", [ validators.optional(), validators.Email(message = \"Invalid email",
"enter a last name.\") ], render_kw={\"class\": 'text'}, description = \"Last",
"], render_kw={\"class\": 'text'}, description = \"Emergency Contact Cellphone\") emergency_email =",
"Privacy Policy.\", default = False) def validate(self): links = [\"github_link\",",
"have you attended?\") free_response1 = TextAreaField(free_response1_prompt, [ validators.Required(message = \"You",
"\"I have read & agree to the MLH Code of",
"password = PasswordField(\"Password\", [], render_kw={\"class\": 'text'}, description = \"Password\") class",
"render_kw={\"class\": 'text'}, description = \"Confirm Password\") def validate_confirm_password(form, field): password",
"= SelectField(\"Ethnicity\", [validators.Required(message = \"You must select an option.\")], choices",
"render_kw={\"class\": 'text'}, description = \"Link #3 (Optional)\") password = PasswordField(\"Password\",",
"= \"You must select an option.\")], choices = num_hackathons_choices_mentor, render_kw={\"class\":",
"must be less than 1500 characters long.\") ], render_kw={\"class\": 'text'},",
"= TextField(\"Last Name\", [ validators.Required(message = \"You must enter a",
"you attended?\", [validators.Required(message = \"You must select an option.\")], choices",
"a name.\") ], render_kw={\"class\": 'text'}, description = \"Guardian Name\") guardian_home_num",
"Email\", [ validators.Required(message = \"Enter an email.\"), validators.Email(message = \"Invalid",
"valid phone number.\") # ], description = \"Phone Number Confirmation\")",
"\"You must select an option.\")], choices = num_hackathons_choices, render_kw={\"class\": 'text'},",
"(\"\", \"How many hackathons have you mentored at?\"), (\"0\", \"0\"),",
"= TextField(\"CS Teacher Name\", [ validators.optional(), ], render_kw={\"class\": 'text'}, description",
"SelectField(\"Ethnicity\", [validators.Required(message = \"You must select an option.\")], choices =",
"\"Medium\"), (\"L\", \"Large\"), (\"XL\", \"Extra Large\") ] type_account_choices = [",
"many hackathons have you mentored at?\"), (\"0\", \"0\"), (\"1\", \"1\"),",
"Name\") class ChangePasswordForm(Form): password = PasswordField(\"Password\", [ validators.Required(message = \"You",
"description = \"Email\") first_name = TextField(\"First Name\", [ validators.Required(message =",
"[ validators.Required(message = \"You must enter a password.\"), validators.Length(min =",
"a valid phone number.\") # ], description = \"Phone Number",
"name.\") ], render_kw={\"class\": 'text'}, description = \"First Name\") last_name =",
"= \"Do you have any dietary restrictions?\") guardian_name = TextField(\"Guardian",
"= \"Enter your preferred contact number.\"), validators.Regexp(phone_regex, message = \"Please",
"description = \"New Password\") confirm_password = PasswordField(\"<PASSWORD> Password\", render_kw={\"class\": 'text'},",
"Site\", [ validators.optional(), validators.URL(message = \"Invalid URL.\") ], render_kw={\"class\": 'text'},",
"= \"Last Name\") school = TextField(\"Company/School Name\", [ validators.Required(message =",
"description = \"School Town\") school_state = TextField(\"School State\", [ validators.Required(message",
"\"Age\") num_hackathons = SelectField(\"How many hackathons have you attended?\", [validators.Required(message",
"TextField(\"School Address\", [ validators.Required(message = \"Enter your school address.\"), ],",
"your company/schools's name.\") ], render_kw={\"class\": 'text'}, description = \"Company/School Name\")",
"(\"mentor\", \"Mentor\") ] free_response1_prompt = \"Why do you want to",
"and password != field.data: raise ValidationError(\"Passwords must match.\") class ChangeNameForm(Form):",
"val attr.data = val setattr(self, link, attr) rv = Form.validate(self)",
"links: #Revert link values back to actual values attr =",
"mentor students in.\" free_response2_prompt_mentor = \"Would you like to run",
"= TextField(\"Emergency Contact Full Name\", [ validators.Required(message = \"You must",
"], render_kw={\"class\": 'text'}, description = \"1500 characters maximum.\") github_link =",
"render_kw={\"class\": 'text'}, description = \"Emergency Contact Email\") school_address = TextField(\"School",
"= form['password'].data if len(password) >= 8 and password != field.data:",
"= \"You must select an option.\")], choices = beginner_choices, render_kw={\"class\":",
"option.\")], choices = shirt_sizes, description = \"What is your shirt",
"\"Will you be at hackBCA?\") # t_shirt_size = SelectField(\"What is",
"render_kw={\"class\": 'text'}, description = \"School Name\") gender = SelectField(\"Gender\", [validators.Required(message",
"validators.Required(message = \"You must enter a first name.\") ], render_kw={\"class\":",
"you in?\"), (\"9\", \"9th\"), (\"10\", \"10th\"), (\"11\", \"11th\"), (\"12\", \"12th\")",
"maximum.\") github_link = TextField(\"Github Link\", [ validators.optional(), validators.URL(message = \"Invalid",
"\"Hacker\"), (\"mentor\", \"Mentor\") ] free_response1_prompt = \"Why do you want",
"description = \"Confirm Password\") def validate_confirm_password(form, field): password = form['password'].data",
"description = \"I agree to the rules set forth by",
"shirt size?\") dietary_restrictions = TextField(\"Dietary Restrictions\", [ validators.optional(), ], render_kw={\"class\":",
"Conduct.\", default = False) mlh_terms = BooleanField(\"I agree\", [ validators.Required(message",
"to the MLH Code of Conduct.\", default = False) mlh_terms",
"school state.\"), ], render_kw={\"class\": 'text'}, description = \"School State\") school_phone_num",
"= TextField(\"Personal Site\", [ validators.optional(), validators.URL(message = \"Invalid URL.\") ],",
"Large\") ] type_account_choices = [ (\"hacker\", \"Hacker\"), (\"mentor\", \"Mentor\") ]",
"your emergency contact's home number.\"), validators.Regexp(phone_regex, message = \"Please enter",
"a name.\"), ], render_kw={\"class\": 'text'}, description = \"Principal Name\") school_principal_email",
"TextField(\"School Town\", [ validators.Required(message = \"Enter your school town.\"), ],",
"[ (\"\", \"Gender\"), (\"male\", \"Male\"), (\"female\", \"Female\"), (\"other\", \"Other\"), (\"rns\",",
"render_kw={\"class\": 'text'}, description = \"Gender\") beginner = SelectField(\"Are you a",
"return False return True class LoginForm(Form): email = TextField(\"Email\", [",
"your shirt size?\") # food_allergies = TextAreaField(\"Allergies\", [ # validators.optional(),",
"\"LinkedIn Link (Optional)\") site_link = TextField(\"Personal Site\", [ validators.optional(), validators.URL(message",
"(Optional)\") other_link = TextField(\"other\", [ validators.optional(), validators.URL(message = \"Invalid URL.\")",
"to the MLH Contest Terms and Conditions and the MLH",
"[validators.Required(message = \"You must select an option.\")], choices = num_hackathons_choices_mentor,",
"MLH Code of Conduct.\") # ], description = \"I agree",
"school's name.\") ], render_kw={\"class\": 'text'}, description = \"School Name\") gender",
"like to mentor students in.\" free_response2_prompt_mentor = \"Would you like",
"describe your ideas.\" class HackerRegistrationForm(Form): email = TextField(\"Email\", [ validators.Required(message",
"Number\") num_hackathons = SelectField(\"How many hackathons have you mentored at?\",",
"form['gender'].data == 'other' and field.data == \"\": raise ValidationError(\"Enter your",
"], description = \"Are there any other medical issues that",
"render_kw={\"class\": 'text'}, description = \"Email\") first_name = TextField(\"First Name\", [",
"= \"Emergency Contact Email\") school_address = TextField(\"School Address\", [ validators.Required(message",
"\"Enter your school address.\"), ], render_kw={\"class\": 'text'}, description = \"School",
"[ validators.optional(), ], render_kw={\"class\": 'text'}, description = \"Do you have",
"\"School Address\") school_town = TextField(\"School Town\", [ validators.Required(message = \"Enter",
"<filename>application/mod_user/forms.py from wtforms import Form, TextField, PasswordField, SelectField, TextAreaField, BooleanField,",
"render_kw={\"class\": 'text'}, description = \"Grade\") age = TextField(\"Age\", [ validators.Required(message",
"emergency_home_num = TextField(\"Emergency Contact Home Number\", [ validators.Required(message = \"Enter",
"\"I agree to the MLH Contest Terms and Conditions and",
"SelectField(\"Gender\", [validators.Required(message = \"You must select an option.\")], choices =",
"shirt_sizes = [ (\"\", \"What is your shirt size?\"), (\"XS\",",
"\"Last Name\") school = TextField(\"School Name\", [ validators.Required(message = \"Enter",
"will!\"), (\"Not Attending\", \"No, I won't.\") ] class RsvpForm(Form): #",
"and Conditions and the MLH Privacy Policy.\", default = False)",
"Small\"), (\"S\", \"Small\"), (\"M\", \"Medium\"), (\"L\", \"Large\"), (\"XL\", \"Extra Large\")",
"PasswordField(\"Password\", [], render_kw={\"class\": 'text'}, description = \"Password\") class EmailForm(Form): email",
"[ validators.Required(message = \"Enter your age\") ], render_kw={\"class\": 'text'}, description",
"Link\", [ validators.optional(), validators.URL(message = \"Invalid URL.\") ], render_kw={\"class\": 'text'},",
"= \"Please tell us if you are attending hackBCA III.\")],",
"'text'}, description = \"Grade\") age = TextField(\"Age\", [ validators.Required(message =",
"TextField(\"Phone Number\", [ validators.Required(message = \"Enter your preferred contact number.\"),",
"render_kw={\"class\": 'text'}, description = \"Are you a beginner?\") ethnicity =",
"description = \"LinkedIn Link (Optional)\") site_link = TextField(\"Personal Site\", [",
"== 'other' and field.data == \"\": raise ValidationError(\"Enter your gender.\")",
"description = \"Phone Number Confirmation\") # t_shirt_size = SelectField(\"What is",
"guardian_email = TextField(\"Guardian Email\", [ validators.Required(message = \"Enter an email.\"),",
"guardian_cell_num = TextField(\"Guardian Cellphone\", [ validators.Required(message = \"Enter your guardian's",
"attending_choices = [ (\"Attending\", \"Yes, I will!\"), (\"Not Attending\", \"No,",
"= originalValues[link] setattr(self, link, attr) if not rv: return False",
"link3 = TextField(\"Link #3\", [ validators.optional(), validators.URL(message = \"Invalid URL.\")",
"\"Emergency Contact Home Number\") emergency_cell_num = TextField(\"Emergency Contact Cellphone\", [",
"] ethnicity_choices = [ (\"\", \"Ethnicity\"), (\"white\", \"White\"), (\"african_american\", \"African",
"you a beginner?\", [validators.Required(message = \"You must select an option.\")],",
"description = \"Github Link (Optional)\") linkedin_link = TextField(\"LinkedIn\", [ validators.optional(),",
"Name\") school = TextField(\"School Name\", [ validators.Required(message = \"Enter your",
"= [\"link1\", \"link2\", \"link3\"] originalValues = {} for link in",
"description = \"First Name\") last_name = TextField(\"Last Name\", [ validators.Required(message",
"description = \"Company/School Name\") phone = TextField(\"Phone Number\", [ validators.Required(message",
"= \"1500 characters maximum.\") mentor_free_response2 = TextAreaField(free_response2_prompt_mentor, [ validators.Length(max =",
"default = False) def validate(self): links = [\"github_link\", \"linkedin_link\", \"site_link\",",
"mentor_free_response2 = TextAreaField(free_response2_prompt_mentor, [ validators.Length(max = 1500, message = \"Response",
"num_hackathons_choices = [ (\"\", \"How many hackathons have you been",
"= PasswordField(\"<PASSWORD> Password\", render_kw={\"class\": 'text'}, description = \"Confirm New Password\")",
"= \"You must select an option.\")], choices = ethnicity_choices, render_kw={\"class\":",
"= \"Phone Number\") num_hackathons = SelectField(\"How many hackathons have you",
"'text'}, description = \"Last Name\") school = TextField(\"School Name\", [",
"email address.\" )], render_kw={\"class\": 'text'}, description = \"CS Teacher Email",
"Policy.\", default = False) def validate(self): links = [\"github_link\", \"linkedin_link\",",
"description = \"CS Teacher Email (if applicable)\") # class MentorRsvpForm(Form):",
"last_name = TextField(\"Last Name\", [ validators.Required(message = \"You must enter",
"email.\"), validators.Email(message = \"Invalid email address.\" )], render_kw={\"class\": 'text'},description =",
"render_kw={\"class\": 'text'}, description = \"School Town\") school_state = TextField(\"School State\",",
"food_allergies = TextAreaField(\"Allergies\", [ # validators.optional(), # ], description =",
"free_response1_prompt = \"Why do you want to come to hackBCA?\"",
"mlh_terms = BooleanField(\"I agree\",[ # validators.Required(message = \"Please read and",
"address.\" )], render_kw={\"class\": 'text'}, description = \"Guardian Email\") emergency_name =",
"'text'}, description = \"Password\") confirm_password = PasswordField(\"Confirm Password\", render_kw={\"class\": 'text'},",
"least 8 characters.\") ], render_kw={\"class\": 'text'}, description = \"New Password\")",
"= num_hackathons_choices_mentor, render_kw={\"class\": 'text'}, description = \"How many hackathons have",
"[\"github_link\", \"linkedin_link\", \"site_link\", \"other_link\"] originalValues = {} for link in",
"= 8, message = \"Password must be at least 8",
"# validators.optional(), # ], description = \"Do you have any",
"description = \"Phone Number\") num_hackathons = SelectField(\"How many hackathons have",
"TextField(\"CS Teacher Email\", [ validators.optional(), validators.Email(message = \"Invalid email address.\"",
"'text'}, description = \"Emergency Contact Cellphone\") emergency_email = TextField(\"Emergency Contact",
"address.\" )], render_kw={\"class\": 'text'}, description = \"Emergency Contact Email\") school_address",
"a first name.\") ], render_kw={\"class\": 'text'}, description = \"First Name\")",
"(\"3\", \"3\"), (\"4\", \"4\"), (\"5\", \"5+\") ] grade_choices = [",
"of Conduct.\") ], description = \"I have read & agree",
"[ # validators.Required(message = \"Confirm your preferred contact number.\"), #",
"must choose a new password.\"), validators.Length(min = 8, message =",
"validators.URL(message = \"Invalid URL.\") ], render_kw={\"class\": 'text'}, description = \"Personal",
"an option.\")], choices = beginner_choices, render_kw={\"class\": 'text'}, description = \"Are",
"= \"Last Name\") school = TextField(\"School Name\", [ validators.Required(message =",
"love validators.URL links = [\"link1\", \"link2\", \"link3\"] originalValues = {}",
"gender.\") class MentorRegistrationForm(Form): email = TextField(\"Email\", [ validators.Required(message = \"Enter",
"\"2\"), (\"3\", \"3\"), (\"4\", \"4\"), (\"5\", \"5+\") ] num_hackathons_choices_mentor =",
"mentor_free_response1 = TextAreaField(free_response1_prompt_mentor, [ validators.Length(max = 1500, message = \"Response",
"attending = RadioField(\"Are you attending hackBCA III?\", [validators.Required(message = \"Please",
"Address\", [ validators.Required(message = \"Enter your school address.\"), ], render_kw={\"class\":",
"school town.\"), ], render_kw={\"class\": 'text'}, description = \"School Town\") school_state",
"is None: val = \"http://\" + val attr.data = val",
"at least 8 characters.\") ], render_kw={\"class\": 'text'}, description = \"Password\")",
"\"Invalid URL.\") ], render_kw={\"class\": 'text'}, description = \"Link #2 (Optional)\")",
"\"Github Link (Optional)\") linkedin_link = TextField(\"LinkedIn\", [ validators.optional(), validators.URL(message =",
"= False) mlh_terms = BooleanField(\"I agree\", [ validators.Required(message = \"Please",
"validate(self): #Man I love validators.URL links = [\"link1\", \"link2\", \"link3\"]",
"your preferred contact number.\"), validators.Regexp(phone_regex, message = \"Please enter a",
"= TextField(\"Phone Number\", [ # validators.Required(message = \"Confirm your preferred",
"URL.\") ], render_kw={\"class\": 'text'}, description = \"Link #1 (Optional)\") link2",
"III.\")], render_kw={\"class\": 'text'}, choices = attending_choices, description = \"Will you",
"render_kw={\"class\": 'text'}, description = \"Last Name\") school = TextField(\"School Name\",",
"description = \"Principal Email\") cs_teacher_name = TextField(\"CS Teacher Name\", [",
"III?\", [validators.Required(message = \"Please tell us if you are attending",
"password = PasswordField(\"Password\", [ validators.Required(message = \"You must enter a",
"\"Invalid URL.\") ], render_kw={\"class\": 'text'}, description = \"Github Link (Optional)\")",
"= \"Enter your school's name.\") ], render_kw={\"class\": 'text'}, description =",
"= \"Enter your school town.\"), ], render_kw={\"class\": 'text'}, description =",
"and the MLH Privacy Policy.\", default = False) def validate_confirm_password(form,",
"= TextField(\"Dietary Restrictions\", [ validators.optional(), ], render_kw={\"class\": 'text'}, description =",
"State\", [ validators.Required(message = \"Enter your school state.\"), ], render_kw={\"class\":",
"attr.data = val setattr(self, link, attr) rv = Form.validate(self) for",
"= \"Enter an email.\"), validators.Email(message = \"Invalid email address.\") ],",
"True class LoginForm(Form): email = TextField(\"Email\", [ validators.Required(message = \"Enter",
"[ validators.Required(message = \"You must choose a new password.\"), validators.Length(min",
"option.\")], choices = num_hackathons_choices_mentor, render_kw={\"class\": 'text'}, description = \"How many",
"agree to our rules.\") # ], description = \"I agree",
"mentored at?\"), (\"0\", \"0\"), (\"1\", \"1\"), (\"2\", \"2\"), (\"3\", \"3\"),",
"valid phone number.\") ], render_kw={\"class\": 'text'}, description = \"School Phone",
"(\"multiracial\", \"Multiracial\"), (\"hispanic\", \"Hispanic origin\"), (\"other\", \"Other\"), (\"rns\", \"Rather Not",
"], render_kw={\"class\": 'text'}, description = \"Guardian Name\") guardian_home_num = TextField(\"Guardian",
"], render_kw={\"class\": 'text'}, description = \"Other Link (Optional)\") password =",
"Conduct.\") # ], description = \"I agree to the MLH",
"= \"Invalid URL.\") ], render_kw={\"class\": 'text'}, description = \"Github Link",
"description = \"I agree to the MLH Contest Terms and",
"# t_shirt_size = SelectField(\"What is your shirt size?\", [validators.Required(message =",
"= \"Emergency Contact Home Number\") emergency_cell_num = TextField(\"Emergency Contact Cellphone\",",
"= \"School Address\") school_town = TextField(\"School Town\", [ validators.Required(message =",
"= TextField(\"LinkedIn\", [ validators.optional(), validators.URL(message = \"Invalid URL.\") ], render_kw={\"class\":",
"characters.\") ], render_kw={\"class\": 'text'}, description = \"Password\") confirm_password = PasswordField(\"<PASSWORD>",
"enter a first name.\") ], render_kw={\"class\": 'text'}, description = \"First",
"TextField(\"Last Name\", [ validators.Required(message = \"You must enter a last",
"an option.\")], choices = ethnicity_choices, render_kw={\"class\": 'text'}, description = \"Ethnicity\")",
"[ validators.Required(message = \"Enter your school address.\"), ], render_kw={\"class\": 'text'},",
"(\"hispanic\", \"Hispanic origin\"), (\"other\", \"Other\"), (\"rns\", \"Rather Not Say\") ]",
"name.\") ], render_kw={\"class\": 'text'}, description = \"Company/School Name\") phone =",
"\"10th\"), (\"11\", \"11th\"), (\"12\", \"12th\") ] shirt_sizes = [ (\"\",",
"= TextField(\"Guardian Email\", [ validators.Required(message = \"Enter an email.\"), validators.Email(message",
"(\"other\", \"Other\"), (\"rns\", \"Rather Not Say\") ] num_hackathons_choices = [",
"(\"11\", \"11th\"), (\"12\", \"12th\") ] shirt_sizes = [ (\"\", \"What",
"(if applicable)\") # class MentorRsvpForm(Form): # attending = RadioField(\"Are you",
"description = \"Do you have any dietary restrictions?\") guardian_name =",
"mentored at?\", [validators.Required(message = \"You must select an option.\")], choices",
"validators.optional(), validators.Email(message = \"Invalid email address.\" )], render_kw={\"class\": 'text'}, description",
"of Conduct.\") # ], description = \"I agree to the",
"\"link2\", \"link3\"] originalValues = {} for link in links: #Temporarily",
"= \"Enter an email.\"), validators.Email(message = \"Invalid email address.\" )],",
"class ChangePasswordForm(Form): password = PasswordField(\"Password\", [ validators.Required(message = \"You must",
"TextField(\"Link #3\", [ validators.optional(), validators.URL(message = \"Invalid URL.\") ], render_kw={\"class\":",
"\"Enter your school's name.\") ], render_kw={\"class\": 'text'}, description = \"School",
"description = \"Do you have any allergies?\") # medical_information =",
"(Optional)\") password = PasswordField(\"Password\", [ validators.Required(message = \"You must enter",
"your current password.\"), validators.Length(min = 8, message = \"Password must",
"= [ (\"hacker\", \"Hacker\"), (\"mentor\", \"Mentor\") ] free_response1_prompt = \"Why",
"# mlh_terms = BooleanField(\"I agree\",[ # validators.Required(message = \"Please read",
"= \"School State\") school_phone_num = TextField(\"School Phone Number\", [ validators.Required(message",
"email.\"), validators.Email(message = \"Invalid email address.\") ], render_kw={\"class\": 'text'}, description",
"read and agree to the MLH Code of Conduct.\") ],",
"us if you are attending hackBCA III.\")], choices = attending_choices)",
"grade_choices, render_kw={\"class\": 'text'}, description = \"Grade\") age = TextField(\"Age\", [",
"] type_account_choices = [ (\"hacker\", \"Hacker\"), (\"mentor\", \"Mentor\") ] free_response1_prompt",
"ValidationError, RadioField import re phone_regex = \"(\\+\\d+-?)?((\\(?\\d{3}\\)?)|(\\d{3}))-?\\d{3}-?\\d{4}$\" gender_choices = [",
"or Pacific Islander\"), (\"american_indian_alaskan_native\", \"American Indian or Alaskan Native\"), (\"multiracial\",",
"], render_kw={\"class\": 'text'}, description = \"Company/School Name\") phone = TextField(\"Phone",
"\"Small\"), (\"M\", \"Medium\"), (\"L\", \"Large\"), (\"XL\", \"Extra Large\") ] type_account_choices",
"Home Number\", [ validators.Required(message = \"Enter your guardian's home number.\"),",
"number.\") ], render_kw={\"class\": 'text'}, description = \"Guardian Cellphone\") guardian_email =",
"], render_kw={\"class\": 'text'}, description = \"Link #1 (Optional)\") link2 =",
"], render_kw={\"class\": 'text'}, description = \"Last Name\") class ChangePasswordForm(Form): password",
"[ (\"\", \"How many hackathons have you been to?\"), (\"0\",",
"'text'}, description = \"Last Name\") school = TextField(\"Company/School Name\", [",
"\"Guardian Email\") emergency_name = TextField(\"Emergency Contact Full Name\", [ validators.Required(message",
"validators.Regexp(phone_regex, message = \"Please enter a valid phone number.\") #",
"validators.Required(message = \"You must enter a last name.\") ], render_kw={\"class\":",
"'text'}, description = \"Principal Email\") cs_teacher_name = TextField(\"CS Teacher Name\",",
"= \"LinkedIn Link (Optional)\") site_link = TextField(\"Personal Site\", [ validators.optional(),",
"render_kw={\"class\": 'text'}, description = \"How many hackathons have you attended?\")",
"a new password.\"), validators.Length(min = 8, message = \"Password must",
"render_kw={\"class\": 'text'}, description = \"Link #1 (Optional)\") link2 = TextField(\"Link",
"= \"School Phone Number\") school_principal_name = TextField(\"Principal Name\", [ validators.Required(message",
"\"5+\") ] grade_choices = [ (\"\", \"What grade are you",
"password != field.data: raise ValidationError(\"Passwords must match.\") attending_choices = [",
"you mentored at?\"), (\"0\", \"0\"), (\"1\", \"1\"), (\"2\", \"2\"), (\"3\",",
"the MLH Terms and Conditions.\") ], description = \"I agree",
"hackBCA?\") # t_shirt_size = SelectField(\"What is your shirt size?\", [validators.Required(message",
"\"Extra Large\") ] type_account_choices = [ (\"hacker\", \"Hacker\"), (\"mentor\", \"Mentor\")",
"= 1500, message = \"Response must be less than 1500",
"\"Enter your guardian's cellphone number.\"), validators.Regexp(phone_regex, message = \"Please enter",
"description = \"Password\") class EmailForm(Form): email = TextField(\"Email\", [ validators.Required(message",
"render_kw={\"class\": 'text'}, description = \"Current Password\") new_password = PasswordField(\"New Password\",",
"Full Name\", [ validators.Required(message = \"You must enter a name.\")",
"!= field.data: raise ValidationError(\"Passwords must match.\") attending_choices = [ (\"Attending\",",
"choices = attending_choices) # phone = TextField(\"Phone Number\", [ #",
"company/schools's name.\") ], render_kw={\"class\": 'text'}, description = \"Company/School Name\") phone",
"\"Link #3 (Optional)\") password = PasswordField(\"Password\", [ validators.Required(message = \"You",
"render_kw={\"class\": 'text'}, description = \"New Password\") confirm_password = PasswordField(\"<PASSWORD> Password\",",
"[ (\"\", \"Ethnicity\"), (\"white\", \"White\"), (\"african_american\", \"African American\"), (\"asian_pacific\", \"Asian",
"if you are attending hackBCA III.\")], choices = attending_choices) #",
"\"3\"), (\"4\", \"4\"), (\"5\", \"5+\") ] num_hackathons_choices_mentor = [ (\"\",",
"\"School Phone Number\") school_principal_name = TextField(\"Principal Name\", [ validators.Required(message =",
"[ (\"\", \"How many hackathons have you mentored at?\"), (\"0\",",
"description = \"Personal Site Link (Optional)\") other_link = TextField(\"other\", [",
"\"You must select an option.\")], choices = num_hackathons_choices_mentor, render_kw={\"class\": 'text'},",
"beginner_choices, render_kw={\"class\": 'text'}, description = \"Are you a beginner?\") ethnicity",
"SelectField(\"Grade\", [validators.Required(message = \"You must select an option.\")], choices =",
"= TextField(\"Link #3\", [ validators.optional(), validators.URL(message = \"Invalid URL.\") ],",
"description = \"School State\") school_phone_num = TextField(\"School Phone Number\", [",
"\"You must select an option.\")], choices = beginner_choices, render_kw={\"class\": 'text'},",
"= \"Emergency Contact Name\") emergency_home_num = TextField(\"Emergency Contact Home Number\",",
"= \"Enter your guardian's home number.\"), validators.Regexp(phone_regex, message = \"Please",
"Number\") school_principal_name = TextField(\"Principal Name\", [ validators.Required(message = \"You must",
"\"Asian or Pacific Islander\"), (\"american_indian_alaskan_native\", \"American Indian or Alaskan Native\"),",
"(\"hacker\", \"Hacker\"), (\"mentor\", \"Mentor\") ] free_response1_prompt = \"Why do you",
"confirm_password = PasswordField(\"<PASSWORD> Password\", render_kw={\"class\": 'text'}, description = \"Confirm New",
"validators.Required(message = \"You must enter your current password.\"), validators.Length(min =",
"TextField(\"School State\", [ validators.Required(message = \"Enter your school state.\"), ],",
"or Alaskan Native\"), (\"multiracial\", \"Multiracial\"), (\"hispanic\", \"Hispanic origin\"), (\"other\", \"Other\"),",
"Say\") ] num_hackathons_choices = [ (\"\", \"How many hackathons have",
"= \"Enter your company/schools's name.\") ], render_kw={\"class\": 'text'}, description =",
"description = \"CS Teacher Name (if applicable)\") cs_teacher_email = TextField(\"CS",
"address.\") ], render_kw={\"class\": 'text'}, description = \"Email\") first_name = TextField(\"First",
"TextField(\"Guardian Cellphone\", [ validators.Required(message = \"Enter your guardian's cellphone number.\"),",
"render_kw={\"class\": 'text'}, description = \"Emergency Contact Name\") emergency_home_num = TextField(\"Emergency",
"email address.\" )], render_kw={\"class\": 'text'}, description = \"Principal Email\") cs_teacher_name",
"contact number.\"), # validators.Regexp(phone_regex, message = \"Please enter a valid",
"\"School State\") school_phone_num = TextField(\"School Phone Number\", [ validators.Required(message =",
"= \"Invalid email address.\" )], render_kw={\"class\": 'text'}, description = \"Emergency",
"from wtforms import Form, TextField, PasswordField, SelectField, TextAreaField, BooleanField, validators,",
"description = \"Age\") num_hackathons = SelectField(\"How many hackathons have you",
"beginner?\") ethnicity = SelectField(\"Ethnicity\", [validators.Required(message = \"You must select an",
"MentorRegistrationForm(Form): email = TextField(\"Email\", [ validators.Required(message = \"Enter an email.\"),",
"Name\", [ validators.Required(message = \"You must enter a last name.\")",
"Terms and Conditions and the MLH Privacy Policy.\", default =",
"number.\"), validators.Regexp(phone_regex, message = \"Please enter a valid phone number.\")",
"render_kw={\"class\": 'text'}, choices = attending_choices, description = \"Will you be",
"\"School Town\") school_state = TextField(\"School State\", [ validators.Required(message = \"Enter",
"description = \"Last Name\") school = TextField(\"Company/School Name\", [ validators.Required(message",
"number.\") # ], description = \"Phone Number Confirmation\") # t_shirt_size",
"= [ (\"\", \"How many hackathons have you been to?\"),",
"the MLH Code of Conduct.\", default = False) mlh_terms =",
"description = \"Guardian Cellphone\") guardian_email = TextField(\"Guardian Email\", [ validators.Required(message",
"description = \"Other Link (Optional)\") password = PasswordField(\"Password\", [ validators.Required(message",
"must select an option.\")], choices = shirt_sizes, description = \"What",
"Email (if applicable)\") # class MentorRsvpForm(Form): # attending = RadioField(\"Are",
"render_kw={\"class\": 'text'}, description = \"First Name\") last_name = TextField(\"Last Name\",",
"render_kw={\"class\": 'text'}, description = \"Guardian Cellphone\") guardian_email = TextField(\"Guardian Email\",",
"'text'}, description = \"Email\") first_name = TextField(\"First Name\", [ validators.Required(message",
"not rv: return False return True def validate_other_gender(form, field): if",
"Say\") ] beginner_choices = [ (\"\", \"Are you a beginner?\"),",
"\"Yes\"), (\"no\", \"No\") ] ethnicity_choices = [ (\"\", \"Ethnicity\"), (\"white\",",
"TextField(\"Emergency Contact Home Number\", [ validators.Required(message = \"Enter your emergency",
"= \"Invalid URL.\") ], render_kw={\"class\": 'text'}, description = \"Link #1",
"= \"First Name\") last_name = TextField(\"Last Name\", [ validators.Required(message =",
"allergies?\") # medical_information = TextAreaField(\"Medical Information\", [ # validators.optional(), #",
"[ validators.Required(message = \"You must enter a last name.\") ],",
"URL.\") ], render_kw={\"class\": 'text'}, description = \"Link #3 (Optional)\") password",
"'text'}, description = \"LinkedIn Link (Optional)\") site_link = TextField(\"Personal Site\",",
"], render_kw={\"class\": 'text'}, description = \"School Address\") school_town = TextField(\"School",
"description = \"What is your shirt size?\") dietary_restrictions = TextField(\"Dietary",
"students in.\" free_response2_prompt_mentor = \"Would you like to run a",
"validators.URL(message = \"Invalid URL.\") ], render_kw={\"class\": 'text'}, description = \"LinkedIn",
"school_state = TextField(\"School State\", [ validators.Required(message = \"Enter your school",
"PasswordField, SelectField, TextAreaField, BooleanField, validators, ValidationError, RadioField import re phone_regex",
"[validators.Required(message = \"You must select an option.\")], choices = ethnicity_choices,",
"\"Please read and agree to the MLH Terms and Conditions.\")",
"False) def validate_confirm_password(form, field): password = form['password'].data if len(password) >=",
"'text'}, description = \"Are you a beginner?\") ethnicity = SelectField(\"Ethnicity\",",
"TextField(\"Guardian Full Name\", [ validators.Required(message = \"You must enter a",
"Name\", [ validators.Required(message = \"You must enter a first name.\")",
"[ validators.Required(message = \"Enter your emergency contact's cellphone.\"), validators.Regexp(phone_regex, message",
"= \"I agree to the MLH Contest Terms and Conditions",
"contact's home number.\"), validators.Regexp(phone_regex, message = \"Please enter a valid",
"email address.\" )], render_kw={\"class\": 'text'},description = \"Email\") password = PasswordField(\"Password\",",
"other_link = TextField(\"other\", [ validators.optional(), validators.URL(message = \"Invalid URL.\") ],",
"current password.\"), validators.Length(min = 8, message = \"Password must be",
"hackathons have you mentored at?\") mentor_free_response1 = TextAreaField(free_response1_prompt_mentor, [ validators.Length(max",
"'text'}, description = \"Link #3 (Optional)\") password = PasswordField(\"Password\", [",
"= \"1500 characters maximum.\") link1 = TextField(\"Link #1\", [ validators.optional(),",
"= PasswordField(\"<PASSWORD> Password\", render_kw={\"class\": 'text'}, description = \"Confirm Password\") mlh_coc",
"EmailForm(Form): email = TextField(\"Email\", [ validators.Required(message = \"Enter an email.\"),",
"(\"M\", \"Medium\"), (\"L\", \"Large\"), (\"XL\", \"Extra Large\") ] type_account_choices =",
"\"No\") ] ethnicity_choices = [ (\"\", \"Ethnicity\"), (\"white\", \"White\"), (\"african_american\",",
"question.\"), validators.Length(max = 1500, message = \"Response must be less",
"= \"Github Link (Optional)\") linkedin_link = TextField(\"LinkedIn\", [ validators.optional(), validators.URL(message",
"TextField(\"Principal Name\", [ validators.Required(message = \"You must enter a name.\"),",
"\"Please tell us if you are attending hackBCA III.\")], choices",
"#Temporarily prefix all links with http:// if they are missing",
"Number\", [ validators.Required(message = \"Enter school's home number.\"), validators.Regexp(phone_regex, message",
"field.data: raise ValidationError(\"Passwords must match.\") class ChangeNameForm(Form): first_name = TextField(\"First",
"], render_kw={\"class\": 'text'}, description = \"School Name\") gender = SelectField(\"Gender\",",
"validators.Required(message = \"Enter your school state.\"), ], render_kw={\"class\": 'text'}, description",
"Code of Conduct.\") ], description = \"I have read &",
"\"How many hackathons have you mentored at?\"), (\"0\", \"0\"), (\"1\",",
"cellphone number.\"), validators.Regexp(phone_regex, message = \"Please enter a valid phone",
"], render_kw={\"class\": 'text'}, description = \"Phone Number\") num_hackathons = SelectField(\"How",
"allergies, illnesses, etc.)\") # hackbca_rules = BooleanField(\"I agree\",[ # validators.Required(message",
"URL.\") ], render_kw={\"class\": 'text'}, description = \"Other Link (Optional)\") password",
"validate(self): links = [\"github_link\", \"linkedin_link\", \"site_link\", \"other_link\"] originalValues = {}",
"= \"You must choose a new password.\"), validators.Length(min = 8,",
"\"Invalid email address.\" )], render_kw={\"class\": 'text'},description = \"Email\") password =",
"= \"Please enter a valid phone number.\") # ], description",
"valid phone number.\") ], render_kw={\"class\": 'text'}, description = \"Guardian Cellphone\")",
"\"Invalid email address.\" )], render_kw={\"class\": 'text'}, description = \"Principal Email\")",
"= BooleanField(\"I agree\", [ validators.Required(message = \"Please read and agree",
"= \"Other Link (Optional)\") password = PasswordField(\"Password\", [ validators.Required(message =",
"must enter a first name.\") ], render_kw={\"class\": 'text'}, description =",
"(Optional)\") linkedin_link = TextField(\"LinkedIn\", [ validators.optional(), validators.URL(message = \"Invalid URL.\")",
"Email\") school_address = TextField(\"School Address\", [ validators.Required(message = \"Enter your",
"attr = getattr(self, link) val = attr.data originalValues[link] = val",
"school_principal_name = TextField(\"Principal Name\", [ validators.Required(message = \"You must enter",
"(\"Not Attending\", \"No, I won't.\") ] class RsvpForm(Form): # attending",
"= \"Company/School Name\") phone = TextField(\"Phone Number\", [ validators.Required(message =",
"RadioField import re phone_regex = \"(\\+\\d+-?)?((\\(?\\d{3}\\)?)|(\\d{3}))-?\\d{3}-?\\d{4}$\" gender_choices = [ (\"\",",
"email address.\" )], render_kw={\"class\": 'text'}, description = \"Guardian Email\") emergency_name",
"characters maximum.\") github_link = TextField(\"Github Link\", [ validators.optional(), validators.URL(message =",
"the MLH Code of Conduct.\") ], description = \"I have",
"'text'}, description = \"Confirm New Password\") def validate_confirm_password(form, field): password",
"= \"Would you like to run a workshop? If so,",
"Email\") cs_teacher_name = TextField(\"CS Teacher Name\", [ validators.optional(), ], render_kw={\"class\":",
"render_kw={\"class\": 'text'}, description = \"Ethnicity\") grade = SelectField(\"Grade\", [validators.Required(message =",
"render_kw={\"class\": 'text'}, description = \"Emergency Contact Cellphone\") emergency_email = TextField(\"Emergency",
"render_kw={\"class\": 'text'},description = \"Email\") password = PasswordField(\"Password\", [], render_kw={\"class\": 'text'},",
"\"Please list languages/frameworks/technologies that you would like to mentor students",
"# hackbca_rules = BooleanField(\"I agree\",[ # validators.Required(message = \"Please read",
"Policy.\", default = False) def validate_confirm_password(form, field): password = form['password'].data",
"select an option.\")], choices = num_hackathons_choices, render_kw={\"class\": 'text'}, description =",
"first_name = TextField(\"First Name\", [ validators.Required(message = \"You must enter",
"maximum.\") link1 = TextField(\"Link #1\", [ validators.optional(), validators.URL(message = \"Invalid",
"to the MLH Terms and Conditions.\") ], description = \"I",
"default = False) # mlh_terms = BooleanField(\"I agree\",[ # validators.Required(message",
"you be at hackBCA?\") # t_shirt_size = SelectField(\"What is your",
"\"Last Name\") school = TextField(\"Company/School Name\", [ validators.Required(message = \"Enter",
"= TextField(\"other\", [ validators.optional(), validators.URL(message = \"Invalid URL.\") ], render_kw={\"class\":",
"you are attending hackBCA III.\")], render_kw={\"class\": 'text'}, choices = attending_choices,",
"tell us if you are attending hackBCA III.\")], render_kw={\"class\": 'text'},",
"last name.\") ], render_kw={\"class\": 'text'}, description = \"Last Name\") class",
"(\"american_indian_alaskan_native\", \"American Indian or Alaskan Native\"), (\"multiracial\", \"Multiracial\"), (\"hispanic\", \"Hispanic",
"PasswordField(\"<PASSWORD> Password\", render_kw={\"class\": 'text'}, description = \"Confirm New Password\") def",
"= shirt_sizes, description = \"What is your shirt size?\") #",
"= PasswordField(\"Password\", [ validators.Required(message = \"You must enter your current",
"'text'}, description = \"School Phone Number\") school_principal_name = TextField(\"Principal Name\",",
"would like to mentor students in.\" free_response2_prompt_mentor = \"Would you",
"grade are you in?\"), (\"9\", \"9th\"), (\"10\", \"10th\"), (\"11\", \"11th\"),",
"agree to the rules set forth by hackBCA.\", default =",
"not rv: return False return True class LoginForm(Form): email =",
"phone number.\") # ], description = \"Phone Number Confirmation\") #",
"with http:// if they are missing it attr = getattr(self,",
"render_kw={\"class\": 'text'}, description = \"Password\") confirm_password = PasswordField(\"Confirm Password\", render_kw={\"class\":",
"], render_kw={\"class\": 'text'}, description = \"Age\") num_hackathons = SelectField(\"How many",
"[ validators.Length(max = 1500, message = \"Response must be less",
"[ (\"\", \"What grade are you in?\"), (\"9\", \"9th\"), (\"10\",",
"a workshop? If so, please briefly describe your ideas.\" class",
"tell us if you are attending hackBCA III.\")], choices =",
"= \"Invalid URL.\") ], render_kw={\"class\": 'text'}, description = \"LinkedIn Link",
"size?\") # food_allergies = TextAreaField(\"Allergies\", [ # validators.optional(), # ],",
"= [ (\"\", \"What is your shirt size?\"), (\"XS\", \"Extra",
"\"Confirm your preferred contact number.\"), # validators.Regexp(phone_regex, message = \"Please",
"Link (Optional)\") site_link = TextField(\"Personal Site\", [ validators.optional(), validators.URL(message =",
"description = \"Guardian Email\") emergency_name = TextField(\"Emergency Contact Full Name\",",
"re phone_regex = \"(\\+\\d+-?)?((\\(?\\d{3}\\)?)|(\\d{3}))-?\\d{3}-?\\d{4}$\" gender_choices = [ (\"\", \"Gender\"), (\"male\",",
"BooleanField(\"I agree\", [ validators.Required(message = \"Please read and agree to",
"ValidationError(\"Enter your gender.\") class MentorRegistrationForm(Form): email = TextField(\"Email\", [ validators.Required(message",
"free_response1 = TextAreaField(free_response1_prompt, [ validators.Required(message = \"You must answer this",
"= PasswordField(\"Password\", [ validators.Required(message = \"You must enter a password.\"),",
"\"You must enter a password.\"), validators.Length(min = 8, message =",
"= \"You must enter a name.\") ], render_kw={\"class\": 'text'}, description",
"= \"How many hackathons have you mentored at?\") mentor_free_response1 =",
"= \"Link #1 (Optional)\") link2 = TextField(\"Link #2\", [ validators.optional(),",
"shirt size?\"), (\"XS\", \"Extra Small\"), (\"S\", \"Small\"), (\"M\", \"Medium\"), (\"L\",",
"render_kw={\"class\": 'text'}, description = \"Guardian Home Number\") guardian_cell_num = TextField(\"Guardian",
"us if you are attending hackBCA III.\")], render_kw={\"class\": 'text'}, choices",
"you attending hackBCA III?\", [validators.Required(message = \"Please tell us if",
"agree\", [ validators.Required(message = \"Please read and agree to the",
"must match.\") def validate(self): #Man I love validators.URL links =",
"'text'}, description = \"Ethnicity\") grade = SelectField(\"Grade\", [validators.Required(message = \"You",
"] shirt_sizes = [ (\"\", \"What is your shirt size?\"),",
"= TextField(\"Guardian Home Number\", [ validators.Required(message = \"Enter your guardian's",
"\"0\"), (\"1\", \"1\"), (\"2\", \"2\"), (\"3\", \"3\"), (\"4\", \"4\"), (\"5\",",
"emergency_email = TextField(\"Emergency Contact Email\", [ validators.Required(message = \"Enter an",
"RsvpForm(Form): # attending = RadioField(\"Are you attending hackBCA III?\", [validators.Required(message",
"[ validators.Required(message = \"Enter your company/schools's name.\") ], render_kw={\"class\": 'text'},",
"= attr.data originalValues[link] = val if re.match(\"^(http|https)://\", val) is None:",
")], render_kw={\"class\": 'text'}, description = \"Guardian Email\") emergency_name = TextField(\"Emergency",
"validators.Regexp(phone_regex, message = \"Please enter a valid phone number.\") ],",
"TextField(\"First Name\", [ validators.Required(message = \"You must enter a first",
"\"CS Teacher Email (if applicable)\") # class MentorRsvpForm(Form): # attending",
"ethnicity_choices = [ (\"\", \"Ethnicity\"), (\"white\", \"White\"), (\"african_american\", \"African American\"),",
"= form['new_password'].data if len(password) >= 8 and password != field.data:",
"gender_choices, render_kw={\"class\": 'text'}, description = \"Gender\") beginner = SelectField(\"Are you",
"many hackathons have you attended?\") free_response1 = TextAreaField(free_response1_prompt, [ validators.Required(message",
"\"I agree to the rules set forth by hackBCA.\", default",
"], render_kw={\"class\": 'text'}, description = \"Current Password\") new_password = PasswordField(\"New",
"render_kw={\"class\": 'text'}, description = \"CS Teacher Name (if applicable)\") cs_teacher_email",
"link1 = TextField(\"Link #1\", [ validators.optional(), validators.URL(message = \"Invalid URL.\")",
"SelectField(\"What is your shirt size?\", [validators.Required(message = \"You must select",
"name.\") ], render_kw={\"class\": 'text'}, description = \"School Name\") gender =",
"and field.data == \"\": raise ValidationError(\"Enter your gender.\") class MentorRegistrationForm(Form):",
"school = TextField(\"Company/School Name\", [ validators.Required(message = \"Enter your company/schools's",
"many hackathons have you mentored at?\") mentor_free_response1 = TextAreaField(free_response1_prompt_mentor, [",
"valid phone number.\") ], render_kw={\"class\": 'text'}, description = \"Emergency Contact",
"Teacher Name (if applicable)\") cs_teacher_email = TextField(\"CS Teacher Email\", [",
"must enter your current password.\"), validators.Length(min = 8, message =",
"\"Invalid email address.\" )], render_kw={\"class\": 'text'}, description = \"Guardian Email\")",
"\"Enter school's home number.\"), validators.Regexp(phone_regex, message = \"Please enter a",
"[validators.Required(message = \"Please tell us if you are attending hackBCA",
"Name\") gender = SelectField(\"Gender\", [validators.Required(message = \"You must select an",
"select an option.\")], choices = ethnicity_choices, render_kw={\"class\": 'text'}, description =",
"validators.Required(message = \"Enter school's home number.\"), validators.Regexp(phone_regex, message = \"Please",
"Indian or Alaskan Native\"), (\"multiracial\", \"Multiracial\"), (\"hispanic\", \"Hispanic origin\"), (\"other\",",
"validators.URL(message = \"Invalid URL.\") ], render_kw={\"class\": 'text'}, description = \"Link",
"if you are attending hackBCA III.\")], render_kw={\"class\": 'text'}, choices =",
"TextField(\"Emergency Contact Full Name\", [ validators.Required(message = \"You must enter",
"have any dietary restrictions?\") guardian_name = TextField(\"Guardian Full Name\", [",
"are attending hackBCA III.\")], render_kw={\"class\": 'text'}, choices = attending_choices, description",
"= TextField(\"Emergency Contact Cellphone\", [ validators.Required(message = \"Enter your emergency",
"hackBCA?\" free_response1_prompt_mentor = \"Please list languages/frameworks/technologies that you would like",
"Password\", render_kw={\"class\": 'text'}, description = \"Confirm Password\") mlh_coc = BooleanField(\"I",
"= \"You must select an option.\")], choices = grade_choices, render_kw={\"class\":",
"], render_kw={\"class\": 'text'}, description = \"LinkedIn Link (Optional)\") site_link =",
"# validators.Required(message = \"Confirm your preferred contact number.\"), # validators.Regexp(phone_regex,",
"ChangePasswordForm(Form): password = PasswordField(\"Password\", [ validators.Required(message = \"You must enter",
"cs_teacher_name = TextField(\"CS Teacher Name\", [ validators.optional(), ], render_kw={\"class\": 'text'},",
"Pacific Islander\"), (\"american_indian_alaskan_native\", \"American Indian or Alaskan Native\"), (\"multiracial\", \"Multiracial\"),",
"Islander\"), (\"american_indian_alaskan_native\", \"American Indian or Alaskan Native\"), (\"multiracial\", \"Multiracial\"), (\"hispanic\",",
"], render_kw={\"class\": 'text'}, description = \"CS Teacher Name (if applicable)\")",
"number.\") ], render_kw={\"class\": 'text'}, description = \"Emergency Contact Home Number\")",
"TextField(\"Age\", [ validators.Required(message = \"Enter your age\") ], render_kw={\"class\": 'text'},",
"agree to the MLH Terms and Conditions.\") ], description =",
"it attr = getattr(self, link) val = attr.data originalValues[link] =",
"must match.\") attending_choices = [ (\"Attending\", \"Yes, I will!\"), (\"Not",
"= ethnicity_choices, render_kw={\"class\": 'text'}, description = \"Ethnicity\") grade = SelectField(\"Grade\",",
"validators.Required(message = \"Enter an email.\"), validators.Email(message = \"Invalid email address.\")",
"hackathons have you been to?\"), (\"0\", \"0\"), (\"1\", \"1\"), (\"2\",",
"= \"School Town\") school_state = TextField(\"School State\", [ validators.Required(message =",
"address.\" )], render_kw={\"class\": 'text'}, description = \"Principal Email\") cs_teacher_name =",
"\"Please read and agree to the MLH Code of Conduct.\")",
"ValidationError(\"Passwords must match.\") def validate(self): #Man I love validators.URL links",
"a beginner?\"), (\"yes\", \"Yes\"), (\"no\", \"No\") ] ethnicity_choices = [",
"your guardian's cellphone number.\"), validators.Regexp(phone_regex, message = \"Please enter a",
"beginner_choices = [ (\"\", \"Are you a beginner?\"), (\"yes\", \"Yes\"),",
"Number\") guardian_cell_num = TextField(\"Guardian Cellphone\", [ validators.Required(message = \"Enter your",
"\"Email\") class RecoverForm(Form): password = PasswordField(\"Password\", [ validators.Required(message = \"You",
"at hackBCA?\") # t_shirt_size = SelectField(\"What is your shirt size?\",",
"(Optional)\") link2 = TextField(\"Link #2\", [ validators.optional(), validators.URL(message = \"Invalid",
"ethnicity = SelectField(\"Ethnicity\", [validators.Required(message = \"You must select an option.\")],",
"size?\") dietary_restrictions = TextField(\"Dietary Restrictions\", [ validators.optional(), ], render_kw={\"class\": 'text'},",
"for link in links: #Revert link values back to actual",
")], render_kw={\"class\": 'text'}, description = \"Emergency Contact Email\") school_address =",
"\"5+\") ] num_hackathons_choices_mentor = [ (\"\", \"How many hackathons have",
"render_kw={\"class\": 'text'}, description = \"School State\") school_phone_num = TextField(\"School Phone",
"\"Invalid email address.\" )], render_kw={\"class\": 'text'}, description = \"CS Teacher",
"Name\") last_name = TextField(\"Last Name\", [ validators.Required(message = \"You must",
"MLH Contest Terms and Conditions and the MLH Privacy Policy.\",",
"description = \"Guardian Name\") guardian_home_num = TextField(\"Guardian Home Number\", [",
"won't.\") ] class RsvpForm(Form): # attending = RadioField(\"Are you attending",
"val) is None: val = \"http://\" + val attr.data =",
"[validators.Required(message = \"You must select an option.\")], choices = grade_choices,",
"you attended?\") free_response1 = TextAreaField(free_response1_prompt, [ validators.Required(message = \"You must",
"attending_choices) # phone = TextField(\"Phone Number\", [ # validators.Required(message =",
"= \"You must answer this question.\"), validators.Length(max = 1500, message",
"description = \"Link #2 (Optional)\") link3 = TextField(\"Link #3\", [",
"email = TextField(\"Email\", [ validators.Required(message = \"Enter an email.\"), validators.Email(message",
"TextAreaField, BooleanField, validators, ValidationError, RadioField import re phone_regex = \"(\\+\\d+-?)?((\\(?\\d{3}\\)?)|(\\d{3}))-?\\d{3}-?\\d{4}$\"",
"Link (Optional)\") linkedin_link = TextField(\"LinkedIn\", [ validators.optional(), validators.URL(message = \"Invalid",
"do you want to come to hackBCA?\" free_response1_prompt_mentor = \"Please",
"'text'}, description = \"Guardian Cellphone\") guardian_email = TextField(\"Guardian Email\", [",
"must select an option.\")], choices = gender_choices, render_kw={\"class\": 'text'}, description",
"], render_kw={\"class\": 'text'}, description = \"Last Name\") school = TextField(\"Company/School",
"[\"link1\", \"link2\", \"link3\"] originalValues = {} for link in links:",
"choices = attending_choices, description = \"Will you be at hackBCA?\")",
"shirt_sizes, description = \"What is your shirt size?\") # food_allergies",
"description = \"What is your shirt size?\") # food_allergies =",
"= PasswordField(\"Password\", [], render_kw={\"class\": 'text'}, description = \"Password\") class EmailForm(Form):",
"validators.Required(message = \"Enter your company/schools's name.\") ], render_kw={\"class\": 'text'}, description",
"{} for link in links: #Temporarily prefix all links with",
"# phone = TextField(\"Phone Number\", [ # validators.Required(message = \"Confirm",
"\"What grade are you in?\"), (\"9\", \"9th\"), (\"10\", \"10th\"), (\"11\",",
"Contact Full Name\", [ validators.Required(message = \"You must enter a",
"validators.Required(message = \"Enter your preferred contact number.\"), validators.Regexp(phone_regex, message =",
"\"Current Password\") new_password = PasswordField(\"New Password\", [ validators.Required(message = \"You",
"at?\", [validators.Required(message = \"You must select an option.\")], choices =",
"\"White\"), (\"african_american\", \"African American\"), (\"asian_pacific\", \"Asian or Pacific Islander\"), (\"american_indian_alaskan_native\",",
"guardian_name = TextField(\"Guardian Full Name\", [ validators.Required(message = \"You must",
"\"Grade\") age = TextField(\"Age\", [ validators.Required(message = \"Enter your age\")",
"'text'}, description = \"Personal Site Link (Optional)\") other_link = TextField(\"other\",",
"field.data: raise ValidationError(\"Passwords must match.\") attending_choices = [ (\"Attending\", \"Yes,",
"attended?\") free_response1 = TextAreaField(free_response1_prompt, [ validators.Required(message = \"You must answer",
"= \"You must select an option.\")], choices = shirt_sizes, description",
"= TextField(\"School State\", [ validators.Required(message = \"Enter your school state.\"),",
"render_kw={\"class\": 'text'}, description = \"1500 characters maximum.\") mentor_free_response2 = TextAreaField(free_response2_prompt_mentor,",
"= \"Last Name\") class ChangePasswordForm(Form): password = PasswordField(\"Password\", [ validators.Required(message",
"= [ (\"\", \"Gender\"), (\"male\", \"Male\"), (\"female\", \"Female\"), (\"other\", \"Other\"),",
"emergency contact's home number.\"), validators.Regexp(phone_regex, message = \"Please enter a",
"[ (\"hacker\", \"Hacker\"), (\"mentor\", \"Mentor\") ] free_response1_prompt = \"Why do",
"= \"You must enter a password.\"), validators.Length(min = 8, message",
"validators.URL links = [\"link1\", \"link2\", \"link3\"] originalValues = {} for",
"attended?\", [validators.Required(message = \"You must select an option.\")], choices =",
"= \"Invalid email address.\" )], render_kw={\"class\": 'text'}, description = \"Email\")",
"Number\", [ validators.Required(message = \"Enter your guardian's home number.\"), validators.Regexp(phone_regex,",
"select an option.\")], choices = grade_choices, render_kw={\"class\": 'text'}, description =",
"8, message = \"Password must be at least 8 characters.\")",
"= \"New Password\") confirm_password = PasswordField(\"<PASSWORD> Password\", render_kw={\"class\": 'text'}, description",
"= val if re.match(\"^(http|https)://\", val) is None: val = \"http://\"",
"!= field.data: raise ValidationError(\"Passwords must match.\") def validate(self): #Man I",
"# ], description = \"Do you have any allergies?\") #",
"\"Enter your age\") ], render_kw={\"class\": 'text'}, description = \"Age\") num_hackathons",
"description = \"School Address\") school_town = TextField(\"School Town\", [ validators.Required(message",
"render_kw={\"class\": 'text'}, description = \"Password\") confirm_password = PasswordField(\"<PASSWORD> Password\", render_kw={\"class\":",
"raise ValidationError(\"Passwords must match.\") def validate(self): #Man I love validators.URL",
"select an option.\")], choices = gender_choices, render_kw={\"class\": 'text'}, description =",
"name.\") ], render_kw={\"class\": 'text'}, description = \"Last Name\") school =",
"hackbca_rules = BooleanField(\"I agree\",[ # validators.Required(message = \"Please read and",
"(\"male\", \"Male\"), (\"female\", \"Female\"), (\"other\", \"Other\"), (\"rns\", \"Rather Not Say\")",
"enter a valid phone number.\") ], render_kw={\"class\": 'text'}, description =",
"link) val = attr.data originalValues[link] = val if re.match(\"^(http|https)://\", val)",
"the MLH Contest Terms and Conditions and the MLH Privacy",
"Name\", [ validators.Required(message = \"Enter your company/schools's name.\") ], render_kw={\"class\":",
"= \"Enter your age\") ], render_kw={\"class\": 'text'}, description = \"Age\")",
"= TextField(\"Age\", [ validators.Required(message = \"Enter your age\") ], render_kw={\"class\":",
"at least 8 characters.\") ], render_kw={\"class\": 'text'}, description = \"New",
"http:// if they are missing it attr = getattr(self, link)",
"(if applicable)\") cs_teacher_email = TextField(\"CS Teacher Email\", [ validators.optional(), validators.Email(message",
"message = \"Please enter a valid phone number.\") # ],",
"description = \"Emergency Contact Home Number\") emergency_cell_num = TextField(\"Emergency Contact",
"\"other_link\"] originalValues = {} for link in links: #Temporarily prefix",
"Home Number\") emergency_cell_num = TextField(\"Emergency Contact Cellphone\", [ validators.Required(message =",
"= \"CS Teacher Name (if applicable)\") cs_teacher_email = TextField(\"CS Teacher",
"Site Link (Optional)\") other_link = TextField(\"other\", [ validators.optional(), validators.URL(message =",
"to run a workshop? If so, please briefly describe your",
"many hackathons have you been to?\"), (\"0\", \"0\"), (\"1\", \"1\"),",
"= \"http://\" + val attr.data = val setattr(self, link, attr)",
"Conditions.\") ], description = \"I agree to the MLH Contest",
"cellphone.\"), validators.Regexp(phone_regex, message = \"Please enter a valid phone number.\")",
"(\"5\", \"5+\") ] grade_choices = [ (\"\", \"What grade are",
"[ # validators.optional(), # ], description = \"Are there any",
"'text'}, description = \"New Password\") confirm_password = PasswordField(\"<PASSWORD> Password\", render_kw={\"class\":",
"\"Invalid URL.\") ], render_kw={\"class\": 'text'}, description = \"Personal Site Link",
"choices = shirt_sizes, description = \"What is your shirt size?\")",
"list languages/frameworks/technologies that you would like to mentor students in.\"",
"Password\") def validate_confirm_password(form, field): password = form['new_password'].data if len(password) >=",
"number.\") ], render_kw={\"class\": 'text'}, description = \"Phone Number\") num_hackathons =",
"class EmailForm(Form): email = TextField(\"Email\", [ validators.Required(message = \"Enter an",
"select an option.\")], choices = shirt_sizes, description = \"What is",
"= False) def validate_confirm_password(form, field): password = form['password'].data if len(password)",
"\"Enter your school town.\"), ], render_kw={\"class\": 'text'}, description = \"School",
"], render_kw={\"class\": 'text'}, description = \"School Phone Number\") school_principal_name =",
"must select an option.\")], choices = grade_choices, render_kw={\"class\": 'text'}, description",
"Confirmation\") # t_shirt_size = SelectField(\"What is your shirt size?\", [validators.Required(message",
"class LoginForm(Form): email = TextField(\"Email\", [ validators.Required(message = \"Enter an",
"address.\" )], render_kw={\"class\": 'text'}, description = \"CS Teacher Email (if",
"I love validators.URL links = [\"link1\", \"link2\", \"link3\"] originalValues =",
"= PasswordField(\"Confirm Password\", render_kw={\"class\": 'text'}, description = \"Confirm Password\") def",
"Number\") emergency_cell_num = TextField(\"Emergency Contact Cellphone\", [ validators.Required(message = \"Enter",
"maximum.\") mentor_free_response2 = TextAreaField(free_response2_prompt_mentor, [ validators.Length(max = 1500, message =",
"def validate_confirm_password(form, field): password = form['new_password'].data if len(password) >= 8",
"\"Invalid URL.\") ], render_kw={\"class\": 'text'}, description = \"Link #1 (Optional)\")",
"Email\", [ validators.optional(), validators.Email(message = \"Invalid email address.\" )], render_kw={\"class\":",
"import Form, TextField, PasswordField, SelectField, TextAreaField, BooleanField, validators, ValidationError, RadioField",
"read and agree to our rules.\") # ], description =",
"address.\" )], render_kw={\"class\": 'text'}, description = \"Email\") class RecoverForm(Form): password",
"hackBCA III?\", [validators.Required(message = \"Please tell us if you are",
"\"Other\"), (\"rns\", \"Rather Not Say\") ] num_hackathons_choices = [ (\"\",",
"# validators.Required(message = \"Please read and agree to our rules.\")",
"number.\") ], render_kw={\"class\": 'text'}, description = \"Guardian Home Number\") guardian_cell_num",
"(\"\", \"What is your shirt size?\"), (\"XS\", \"Extra Small\"), (\"S\",",
"are missing it attr = getattr(self, link) val = attr.data",
"(\"yes\", \"Yes\"), (\"no\", \"No\") ] ethnicity_choices = [ (\"\", \"Ethnicity\"),",
"setattr(self, link, attr) if not rv: return False return True",
"characters.\") ], render_kw={\"class\": 'text'}, description = \"Current Password\") new_password =",
"description = \"Principal Name\") school_principal_email = TextField(\"Principal Email\", [ validators.Required(message",
"], render_kw={\"class\": 'text'}, description = \"Password\") confirm_password = PasswordField(\"<PASSWORD> Password\",",
"link values back to actual values attr = getattr(self, link)",
"Name\", [ validators.Required(message = \"Enter your school's name.\") ], render_kw={\"class\":",
"read & agree to the MLH Code of Conduct.\", default",
"], render_kw={\"class\": 'text'}, description = \"Password\") confirm_password = PasswordField(\"Confirm Password\",",
"Address\") school_town = TextField(\"School Town\", [ validators.Required(message = \"Enter your",
"Password\") confirm_password = PasswordField(\"<PASSWORD> Password\", render_kw={\"class\": 'text'}, description = \"Confirm",
"], render_kw={\"class\": 'text'}, description = \"Emergency Contact Home Number\") emergency_cell_num",
"guardian's home number.\"), validators.Regexp(phone_regex, message = \"Please enter a valid",
"ideas.\" class HackerRegistrationForm(Form): email = TextField(\"Email\", [ validators.Required(message = \"Enter",
"validators.Required(message = \"Please read and agree to the MLH Code",
"[ (\"Attending\", \"Yes, I will!\"), (\"Not Attending\", \"No, I won't.\")",
"'text'}, description = \"Age\") num_hackathons = SelectField(\"How many hackathons have",
"= \"Confirm Password\") mlh_coc = BooleanField(\"I agree\", [ validators.Required(message =",
"option.\")], choices = grade_choices, render_kw={\"class\": 'text'}, description = \"Grade\") age",
"medical issues that we should know about? (ex. Other allergies,",
"BooleanField, validators, ValidationError, RadioField import re phone_regex = \"(\\+\\d+-?)?((\\(?\\d{3}\\)?)|(\\d{3}))-?\\d{3}-?\\d{4}$\" gender_choices",
"(\"12\", \"12th\") ] shirt_sizes = [ (\"\", \"What is your",
"preferred contact number.\"), # validators.Regexp(phone_regex, message = \"Please enter a",
"= \"You must select an option.\")], choices = num_hackathons_choices, render_kw={\"class\":",
"\"Personal Site Link (Optional)\") other_link = TextField(\"other\", [ validators.optional(), validators.URL(message",
"back to actual values attr = getattr(self, link) attr.data =",
"validators.Required(message = \"Enter an email.\"), validators.Email(message = \"Invalid email address.\"",
"a valid phone number.\") ], render_kw={\"class\": 'text'}, description = \"Emergency",
"\"Are you a beginner?\"), (\"yes\", \"Yes\"), (\"no\", \"No\") ] ethnicity_choices",
"'text'}, description = \"CS Teacher Name (if applicable)\") cs_teacher_email =",
"are attending hackBCA III.\")], choices = attending_choices) # phone =",
"hackBCA III.\")], choices = attending_choices) # phone = TextField(\"Phone Number\",",
"MLH Code of Conduct.\") ], description = \"I have read",
"= \"Principal Name\") school_principal_email = TextField(\"Principal Email\", [ validators.Required(message =",
"(\"XL\", \"Extra Large\") ] type_account_choices = [ (\"hacker\", \"Hacker\"), (\"mentor\",",
"= \"What is your shirt size?\") dietary_restrictions = TextField(\"Dietary Restrictions\",",
"MLH Code of Conduct.\", default = False) mlh_terms = BooleanField(\"I",
"PasswordField(\"Confirm Password\", render_kw={\"class\": 'text'}, description = \"Confirm Password\") def validate_confirm_password(form,",
"address.\" )], render_kw={\"class\": 'text'},description = \"Email\") password = PasswordField(\"Password\", [],",
"password != field.data: raise ValidationError(\"Passwords must match.\") def validate(self): #Man",
"render_kw={\"class\": 'text'}, description = \"1500 characters maximum.\") link1 = TextField(\"Link",
"(\"4\", \"4\"), (\"5\", \"5+\") ] num_hackathons_choices_mentor = [ (\"\", \"How",
"'text'}, description = \"Email\") class RecoverForm(Form): password = PasswordField(\"Password\", [",
"'text'}, description = \"Confirm Password\") mlh_coc = BooleanField(\"I agree\", [",
"[ validators.Required(message = \"You must answer this question.\"), validators.Length(max =",
"validators.Length(max = 1500, message = \"Response must be less than",
"render_kw={\"class\": 'text'}, description = \"Emergency Contact Home Number\") emergency_cell_num =",
"if not rv: return False return True class LoginForm(Form): email",
"your guardian's home number.\"), validators.Regexp(phone_regex, message = \"Please enter a",
"description = \"Guardian Home Number\") guardian_cell_num = TextField(\"Guardian Cellphone\", [",
"render_kw={\"class\": 'text'}, description = \"Guardian Email\") emergency_name = TextField(\"Emergency Contact",
"= Form.validate(self) for link in links: #Revert link values back",
"= grade_choices, render_kw={\"class\": 'text'}, description = \"Grade\") age = TextField(\"Age\",",
"RecoverForm(Form): password = PasswordField(\"Password\", [ validators.Required(message = \"You must enter",
"Password\", render_kw={\"class\": 'text'}, description = \"Confirm New Password\") def validate_confirm_password(form,",
"= \"Email\") password = PasswordField(\"Password\", [], render_kw={\"class\": 'text'}, description =",
"[ validators.Required(message = \"Enter your school's name.\") ], render_kw={\"class\": 'text'},",
"must select an option.\")], choices = beginner_choices, render_kw={\"class\": 'text'}, description",
"False) def validate(self): links = [\"github_link\", \"linkedin_link\", \"site_link\", \"other_link\"] originalValues",
"password = PasswordField(\"Password\", [ validators.Required(message = \"You must enter your",
"be at hackBCA?\") # t_shirt_size = SelectField(\"What is your shirt",
"\"Rather Not Say\") ] num_hackathons_choices = [ (\"\", \"How many",
"you been to?\"), (\"0\", \"0\"), (\"1\", \"1\"), (\"2\", \"2\"), (\"3\",",
"answer this question.\"), validators.Length(max = 1500, message = \"Response must",
"\"(\\+\\d+-?)?((\\(?\\d{3}\\)?)|(\\d{3}))-?\\d{3}-?\\d{4}$\" gender_choices = [ (\"\", \"Gender\"), (\"male\", \"Male\"), (\"female\", \"Female\"),",
"your school's name.\") ], render_kw={\"class\": 'text'}, description = \"School Name\")",
"Home Number\", [ validators.Required(message = \"Enter your emergency contact's home",
"emergency_cell_num = TextField(\"Emergency Contact Cellphone\", [ validators.Required(message = \"Enter your",
"return True class LoginForm(Form): email = TextField(\"Email\", [ validators.Required(message =",
"\"Email\") password = PasswordField(\"Password\", [], render_kw={\"class\": 'text'}, description = \"Password\")",
"Not Say\") ] num_hackathons_choices = [ (\"\", \"How many hackathons",
"URL.\") ], render_kw={\"class\": 'text'}, description = \"Link #2 (Optional)\") link3",
"agree to the MLH Code of Conduct.\") ], description =",
"Number\", [ validators.Required(message = \"Enter your preferred contact number.\"), validators.Regexp(phone_regex,",
"description = \"Email\") class RecoverForm(Form): password = PasswordField(\"Password\", [ validators.Required(message",
"email address.\" )], render_kw={\"class\": 'text'}, description = \"Email\") class RecoverForm(Form):",
"= \"I agree to the MLH Code of Conduct.\", default",
"'text'}, description = \"Do you have any dietary restrictions?\") guardian_name",
"\"Gender\"), (\"male\", \"Male\"), (\"female\", \"Female\"), (\"other\", \"Other\"), (\"rns\", \"Rather Not",
"# ], description = \"I agree to the MLH Code",
"TextField(\"Github Link\", [ validators.optional(), validators.URL(message = \"Invalid URL.\") ], render_kw={\"class\":",
"to the MLH Code of Conduct.\") # ], description =",
"\"What is your shirt size?\") dietary_restrictions = TextField(\"Dietary Restrictions\", [",
"], render_kw={\"class\": 'text'}, description = \"Last Name\") school = TextField(\"School",
"validators.Required(message = \"Please read and agree to our rules.\") #",
"description = \"How many hackathons have you mentored at?\") mentor_free_response1",
"Name\", [ validators.optional(), ], render_kw={\"class\": 'text'}, description = \"CS Teacher",
"been to?\"), (\"0\", \"0\"), (\"1\", \"1\"), (\"2\", \"2\"), (\"3\", \"3\"),",
"Home Number\") guardian_cell_num = TextField(\"Guardian Cellphone\", [ validators.Required(message = \"Enter",
"\"Please enter a valid phone number.\") # ], description =",
"\"Invalid email address.\" )], render_kw={\"class\": 'text'}, description = \"Emergency Contact",
"link, attr) if not rv: return False return True def",
"Password\") mlh_coc = BooleanField(\"I agree\", [ validators.Required(message = \"Please read",
"render_kw={\"class\": 'text'}, description = \"School Address\") school_town = TextField(\"School Town\",",
"(\"no\", \"No\") ] ethnicity_choices = [ (\"\", \"Ethnicity\"), (\"white\", \"White\"),",
"= SelectField(\"How many hackathons have you mentored at?\", [validators.Required(message =",
"= \"1500 characters maximum.\") github_link = TextField(\"Github Link\", [ validators.optional(),",
"valid phone number.\") ], render_kw={\"class\": 'text'}, description = \"Guardian Home",
"an option.\")], choices = shirt_sizes, description = \"What is your",
"characters maximum.\") link1 = TextField(\"Link #1\", [ validators.optional(), validators.URL(message =",
"validators.Required(message = \"You must enter a name.\") ], render_kw={\"class\": 'text'},",
"\"No, I won't.\") ] class RsvpForm(Form): # attending = RadioField(\"Are",
"beginner = SelectField(\"Are you a beginner?\", [validators.Required(message = \"You must",
"Teacher Email (if applicable)\") # class MentorRsvpForm(Form): # attending =",
"Conditions and the MLH Privacy Policy.\", default = False) def",
"field): password = form['password'].data if len(password) >= 8 and password",
"your school state.\"), ], render_kw={\"class\": 'text'}, description = \"School State\")",
"= getattr(self, link) attr.data = originalValues[link] setattr(self, link, attr) if",
"'text'}, description = \"Company/School Name\") phone = TextField(\"Phone Number\", [",
"New Password\") def validate_confirm_password(form, field): password = form['new_password'].data if len(password)",
"class ChangeNameForm(Form): first_name = TextField(\"First Name\", [ validators.Required(message = \"You",
"= TextField(\"Principal Name\", [ validators.Required(message = \"You must enter a",
"\"Enter your preferred contact number.\"), validators.Regexp(phone_regex, message = \"Please enter",
"'text'}, description = \"How many hackathons have you mentored at?\")",
"rv: return False return True class LoginForm(Form): email = TextField(\"Email\",",
"field): if form['gender'].data == 'other' and field.data == \"\": raise",
"like to run a workshop? If so, please briefly describe",
"= \"Link #2 (Optional)\") link3 = TextField(\"Link #3\", [ validators.optional(),",
"!= field.data: raise ValidationError(\"Passwords must match.\") class ChangeNameForm(Form): first_name =",
"TextField(\"Guardian Home Number\", [ validators.Required(message = \"Enter your guardian's home",
"be at least 8 characters.\") ], render_kw={\"class\": 'text'}, description =",
"\"First Name\") last_name = TextField(\"Last Name\", [ validators.Required(message = \"You",
"\"Principal Name\") school_principal_email = TextField(\"Principal Email\", [ validators.Required(message = \"Enter",
"our rules.\") # ], description = \"I agree to the",
"TextField(\"Guardian Email\", [ validators.Required(message = \"Enter an email.\"), validators.Email(message =",
"contact's cellphone.\"), validators.Regexp(phone_regex, message = \"Please enter a valid phone",
"wtforms import Form, TextField, PasswordField, SelectField, TextAreaField, BooleanField, validators, ValidationError,",
"school's home number.\"), validators.Regexp(phone_regex, message = \"Please enter a valid",
"description = \"1500 characters maximum.\") link1 = TextField(\"Link #1\", [",
"number.\") ], render_kw={\"class\": 'text'}, description = \"Emergency Contact Cellphone\") emergency_email",
"\"Multiracial\"), (\"hispanic\", \"Hispanic origin\"), (\"other\", \"Other\"), (\"rns\", \"Rather Not Say\")",
"'text'}, description = \"Guardian Name\") guardian_home_num = TextField(\"Guardian Home Number\",",
"(\"XS\", \"Extra Small\"), (\"S\", \"Small\"), (\"M\", \"Medium\"), (\"L\", \"Large\"), (\"XL\",",
"description = \"Password\") confirm_password = PasswordField(\"Confirm Password\", render_kw={\"class\": 'text'}, description",
"TextAreaField(free_response2_prompt_mentor, [ validators.Length(max = 1500, message = \"Response must be",
"'text'}, description = \"Last Name\") class ChangePasswordForm(Form): password = PasswordField(\"Password\",",
"\"1\"), (\"2\", \"2\"), (\"3\", \"3\"), (\"4\", \"4\"), (\"5\", \"5+\") ]",
"= TextAreaField(\"Medical Information\", [ # validators.optional(), # ], description =",
"ChangeNameForm(Form): first_name = TextField(\"First Name\", [ validators.Required(message = \"You must",
"\"Confirm Password\") def validate_confirm_password(form, field): password = form['password'].data if len(password)",
"long.\") ], render_kw={\"class\": 'text'}, description = \"1500 characters maximum.\") github_link",
"size?\", [validators.Required(message = \"You must select an option.\")], choices =",
"render_kw={\"class\": 'text'}, description = \"Company/School Name\") phone = TextField(\"Phone Number\",",
"must enter a name.\") ], render_kw={\"class\": 'text'}, description = \"Guardian",
"\"Enter your company/schools's name.\") ], render_kw={\"class\": 'text'}, description = \"Company/School",
"validators.URL(message = \"Invalid URL.\") ], render_kw={\"class\": 'text'}, description = \"Github",
"render_kw={\"class\": 'text'}, description = \"School Phone Number\") school_principal_name = TextField(\"Principal",
"], render_kw={\"class\": 'text'}, description = \"Link #3 (Optional)\") password =",
"description = \"Gender\") beginner = SelectField(\"Are you a beginner?\", [validators.Required(message",
"link, attr) if not rv: return False return True class",
"by hackBCA.\", default = False) # mlh_terms = BooleanField(\"I agree\",[",
"render_kw={\"class\": 'text'}, description = \"Password\") class EmailForm(Form): email = TextField(\"Email\",",
"description = \"I agree to the MLH Code of Conduct.\",",
"], render_kw={\"class\": 'text'}, description = \"Guardian Home Number\") guardian_cell_num =",
"field): password = form['new_password'].data if len(password) >= 8 and password",
"to?\"), (\"0\", \"0\"), (\"1\", \"1\"), (\"2\", \"2\"), (\"3\", \"3\"), (\"4\",",
"have you mentored at?\", [validators.Required(message = \"You must select an",
"= TextField(\"Guardian Cellphone\", [ validators.Required(message = \"Enter your guardian's cellphone",
"a beginner?\") ethnicity = SelectField(\"Ethnicity\", [validators.Required(message = \"You must select",
"Number Confirmation\") # t_shirt_size = SelectField(\"What is your shirt size?\",",
"[validators.Required(message = \"You must select an option.\")], choices = gender_choices,",
"guardian's cellphone number.\"), validators.Regexp(phone_regex, message = \"Please enter a valid",
"], description = \"I agree to the MLH Code of",
"phone number.\") ], render_kw={\"class\": 'text'}, description = \"Phone Number\") num_hackathons",
"you are attending hackBCA III.\")], choices = attending_choices) # phone",
"MentorRsvpForm(Form): # attending = RadioField(\"Are you attending hackBCA III?\", [validators.Required(message",
"= \"Confirm your preferred contact number.\"), # validators.Regexp(phone_regex, message =",
"], description = \"I agree to the MLH Contest Terms",
"phone number.\") ], render_kw={\"class\": 'text'}, description = \"School Phone Number\")",
"\"Other\"), (\"rns\", \"Rather Not Say\") ] beginner_choices = [ (\"\",",
"number.\") ], render_kw={\"class\": 'text'}, description = \"School Phone Number\") school_principal_name",
"they are missing it attr = getattr(self, link) val =",
"URL.\") ], render_kw={\"class\": 'text'}, description = \"Personal Site Link (Optional)\")",
"\"Please read and agree to our rules.\") # ], description",
"], render_kw={\"class\": 'text'}, description = \"1500 characters maximum.\") link1 =",
"re.match(\"^(http|https)://\", val) is None: val = \"http://\" + val attr.data",
"TextField(\"CS Teacher Name\", [ validators.optional(), ], render_kw={\"class\": 'text'}, description =",
"an option.\")], choices = num_hackathons_choices_mentor, render_kw={\"class\": 'text'}, description = \"How",
"phone = TextField(\"Phone Number\", [ # validators.Required(message = \"Confirm your",
"= \"Password\") confirm_password = PasswordField(\"Confirm Password\", render_kw={\"class\": 'text'}, description =",
"the rules set forth by hackBCA.\", default = False) #",
"Link (Optional)\") password = PasswordField(\"Password\", [ validators.Required(message = \"You must",
"num_hackathons = SelectField(\"How many hackathons have you mentored at?\", [validators.Required(message",
"\"Emergency Contact Cellphone\") emergency_email = TextField(\"Emergency Contact Email\", [ validators.Required(message",
"(\"5\", \"5+\") ] num_hackathons_choices_mentor = [ (\"\", \"How many hackathons",
"MLH Privacy Policy.\", default = False) def validate_confirm_password(form, field): password",
"\"Male\"), (\"female\", \"Female\"), (\"other\", \"Other\"), (\"rns\", \"Rather Not Say\") ]",
")], render_kw={\"class\": 'text'}, description = \"Principal Email\") cs_teacher_name = TextField(\"CS",
"\"1500 characters maximum.\") mentor_free_response2 = TextAreaField(free_response2_prompt_mentor, [ validators.Length(max = 1500,",
"in.\" free_response2_prompt_mentor = \"Would you like to run a workshop?",
"match.\") def validate(self): #Man I love validators.URL links = [\"link1\",",
"your preferred contact number.\"), # validators.Regexp(phone_regex, message = \"Please enter",
"you want to come to hackBCA?\" free_response1_prompt_mentor = \"Please list",
"# class MentorRsvpForm(Form): # attending = RadioField(\"Are you attending hackBCA",
"attending hackBCA III.\")], render_kw={\"class\": 'text'}, choices = attending_choices, description =",
"description = \"Emergency Contact Name\") emergency_home_num = TextField(\"Emergency Contact Home",
"\"Female\"), (\"other\", \"Other\"), (\"rns\", \"Rather Not Say\") ] beginner_choices =",
"attr.data originalValues[link] = val if re.match(\"^(http|https)://\", val) is None: val",
"getattr(self, link) val = attr.data originalValues[link] = val if re.match(\"^(http|https)://\",",
"= \"I have read & agree to the MLH Code",
"agree to the MLH Contest Terms and Conditions and the",
"'text'}, description = \"School Name\") gender = SelectField(\"Gender\", [validators.Required(message =",
"TextAreaField(\"Medical Information\", [ # validators.optional(), # ], description = \"Are",
"phone number.\") ], render_kw={\"class\": 'text'}, description = \"Guardian Home Number\")",
"= \"Grade\") age = TextField(\"Age\", [ validators.Required(message = \"Enter your",
"ValidationError(\"Passwords must match.\") attending_choices = [ (\"Attending\", \"Yes, I will!\"),",
"validators.Email(message = \"Invalid email address.\" )], render_kw={\"class\": 'text'},description = \"Email\")",
"choices = gender_choices, render_kw={\"class\": 'text'}, description = \"Gender\") beginner =",
"'text'}, choices = attending_choices, description = \"Will you be at",
"Form, TextField, PasswordField, SelectField, TextAreaField, BooleanField, validators, ValidationError, RadioField import",
"TextField(\"Phone Number\", [ # validators.Required(message = \"Confirm your preferred contact",
"= [\"github_link\", \"linkedin_link\", \"site_link\", \"other_link\"] originalValues = {} for link",
"to the MLH Code of Conduct.\") ], description = \"I",
"(\"0\", \"0\"), (\"1\", \"1\"), (\"2\", \"2\"), (\"3\", \"3\"), (\"4\", \"4\"),",
"render_kw={\"class\": 'text'}, description = \"Last Name\") school = TextField(\"Company/School Name\",",
"to hackBCA?\" free_response1_prompt_mentor = \"Please list languages/frameworks/technologies that you would",
"so, please briefly describe your ideas.\" class HackerRegistrationForm(Form): email =",
"III.\")], choices = attending_choices) # phone = TextField(\"Phone Number\", [",
"(\"\", \"Are you a beginner?\"), (\"yes\", \"Yes\"), (\"no\", \"No\") ]",
"= False) def validate(self): links = [\"github_link\", \"linkedin_link\", \"site_link\", \"other_link\"]",
"PasswordField(\"Password\", [ validators.Required(message = \"You must enter a password.\"), validators.Length(min",
"'text'}, description = \"Other Link (Optional)\") password = PasswordField(\"Password\", [",
"\"I agree to the MLH Code of Conduct.\", default =",
"\"Phone Number Confirmation\") # t_shirt_size = SelectField(\"What is your shirt",
"must enter a password.\"), validators.Length(min = 8, message = \"Password",
"Number\", [ validators.Required(message = \"Enter your emergency contact's home number.\"),",
"\"Do you have any dietary restrictions?\") guardian_name = TextField(\"Guardian Full",
"Contact Home Number\", [ validators.Required(message = \"Enter your emergency contact's",
"validators.Required(message = \"Confirm your preferred contact number.\"), # validators.Regexp(phone_regex, message",
"run a workshop? If so, please briefly describe your ideas.\"",
"Password\", render_kw={\"class\": 'text'}, description = \"Confirm Password\") def validate_confirm_password(form, field):",
"], render_kw={\"class\": 'text'}, description = \"Personal Site Link (Optional)\") other_link",
"a valid phone number.\") ], render_kw={\"class\": 'text'}, description = \"Guardian",
"if not rv: return False return True def validate_other_gender(form, field):",
"set forth by hackBCA.\", default = False) # mlh_terms =",
"\"Invalid URL.\") ], render_kw={\"class\": 'text'}, description = \"Link #3 (Optional)\")",
"password != field.data: raise ValidationError(\"Passwords must match.\") class ChangeNameForm(Form): first_name",
"must select an option.\")], choices = ethnicity_choices, render_kw={\"class\": 'text'}, description",
"is your shirt size?\"), (\"XS\", \"Extra Small\"), (\"S\", \"Small\"), (\"M\",",
"missing it attr = getattr(self, link) val = attr.data originalValues[link]",
"#Revert link values back to actual values attr = getattr(self,",
"choices = num_hackathons_choices_mentor, render_kw={\"class\": 'text'}, description = \"How many hackathons",
"= \"Please list languages/frameworks/technologies that you would like to mentor",
"[ validators.Required(message = \"Enter school's home number.\"), validators.Regexp(phone_regex, message =",
"] free_response1_prompt = \"Why do you want to come to",
"= \"Invalid URL.\") ], render_kw={\"class\": 'text'}, description = \"Link #3",
"= TextAreaField(free_response1_prompt_mentor, [ validators.Length(max = 1500, message = \"Response must",
"\"You must select an option.\")], choices = ethnicity_choices, render_kw={\"class\": 'text'},",
"\"Link #2 (Optional)\") link3 = TextField(\"Link #3\", [ validators.optional(), validators.URL(message",
"= \"Guardian Cellphone\") guardian_email = TextField(\"Guardian Email\", [ validators.Required(message =",
"], render_kw={\"class\": 'text'}, description = \"Emergency Contact Name\") emergency_home_num =",
"'text'}, description = \"School State\") school_phone_num = TextField(\"School Phone Number\",",
"that you would like to mentor students in.\" free_response2_prompt_mentor =",
"linkedin_link = TextField(\"LinkedIn\", [ validators.optional(), validators.URL(message = \"Invalid URL.\") ],",
"\"Do you have any allergies?\") # medical_information = TextAreaField(\"Medical Information\",",
"and password != field.data: raise ValidationError(\"Passwords must match.\") def validate(self):",
"grade = SelectField(\"Grade\", [validators.Required(message = \"You must select an option.\")],",
"description = \"Are you a beginner?\") ethnicity = SelectField(\"Ethnicity\", [validators.Required(message",
"field.data: raise ValidationError(\"Passwords must match.\") def validate(self): #Man I love",
"validators.Email(message = \"Invalid email address.\") ], render_kw={\"class\": 'text'}, description =",
"= gender_choices, render_kw={\"class\": 'text'}, description = \"Gender\") beginner = SelectField(\"Are",
"= \"Password\") class EmailForm(Form): email = TextField(\"Email\", [ validators.Required(message =",
"= \"Please read and agree to our rules.\") # ],",
"must enter a name.\"), ], render_kw={\"class\": 'text'}, description = \"Principal",
"briefly describe your ideas.\" class HackerRegistrationForm(Form): email = TextField(\"Email\", [",
"TextField, PasswordField, SelectField, TextAreaField, BooleanField, validators, ValidationError, RadioField import re",
"\"Yes, I will!\"), (\"Not Attending\", \"No, I won't.\") ] class",
"validate_other_gender(form, field): if form['gender'].data == 'other' and field.data == \"\":",
"= \"Emergency Contact Cellphone\") emergency_email = TextField(\"Emergency Contact Email\", [",
"\"You must answer this question.\"), validators.Length(max = 1500, message =",
"& agree to the MLH Code of Conduct.\", default =",
"originalValues = {} for link in links: #Temporarily prefix all",
"you a beginner?\"), (\"yes\", \"Yes\"), (\"no\", \"No\") ] ethnicity_choices =",
"], render_kw={\"class\": 'text'}, description = \"School Town\") school_state = TextField(\"School",
"any other medical issues that we should know about? (ex.",
"render_kw={\"class\": 'text'}, description = \"Email\") class RecoverForm(Form): password = PasswordField(\"Password\",",
"validators.Required(message = \"Enter your school address.\"), ], render_kw={\"class\": 'text'}, description",
"Name\") school_principal_email = TextField(\"Principal Email\", [ validators.Required(message = \"Enter an",
"'text'}, description = \"Github Link (Optional)\") linkedin_link = TextField(\"LinkedIn\", [",
"# food_allergies = TextAreaField(\"Allergies\", [ # validators.optional(), # ], description",
"\"Mentor\") ] free_response1_prompt = \"Why do you want to come",
"], render_kw={\"class\": 'text'}, description = \"Guardian Cellphone\") guardian_email = TextField(\"Guardian",
"class RsvpForm(Form): # attending = RadioField(\"Are you attending hackBCA III?\",",
"1500 characters long.\") ], render_kw={\"class\": 'text'}, description = \"1500 characters",
"8 characters.\") ], render_kw={\"class\": 'text'}, description = \"New Password\") confirm_password",
"= \"How many hackathons have you attended?\") free_response1 = TextAreaField(free_response1_prompt,",
"validators.optional(), ], render_kw={\"class\": 'text'}, description = \"CS Teacher Name (if",
"mlh_terms = BooleanField(\"I agree\", [ validators.Required(message = \"Please read and",
"= SelectField(\"Are you a beginner?\", [validators.Required(message = \"You must select",
"you have any allergies?\") # medical_information = TextAreaField(\"Medical Information\", [",
"read and agree to the MLH Code of Conduct.\") #",
"an option.\")], choices = gender_choices, render_kw={\"class\": 'text'}, description = \"Gender\")",
"8 characters.\") ], render_kw={\"class\": 'text'}, description = \"Current Password\") new_password",
"[ (\"\", \"What is your shirt size?\"), (\"XS\", \"Extra Small\"),",
"\"Extra Small\"), (\"S\", \"Small\"), (\"M\", \"Medium\"), (\"L\", \"Large\"), (\"XL\", \"Extra",
"def validate_confirm_password(form, field): password = form['password'].data if len(password) >= 8",
"[ validators.Required(message = \"Enter your school state.\"), ], render_kw={\"class\": 'text'},",
"= \"Do you have any allergies?\") # medical_information = TextAreaField(\"Medical",
"links = [\"link1\", \"link2\", \"link3\"] originalValues = {} for link",
"prefix all links with http:// if they are missing it",
"], render_kw={\"class\": 'text'}, description = \"1500 characters maximum.\") mentor_free_response2 =",
"], render_kw={\"class\": 'text'}, description = \"New Password\") confirm_password = PasswordField(\"<PASSWORD>",
"= \"Invalid email address.\" )], render_kw={\"class\": 'text'},description = \"Email\") password",
"least 8 characters.\") ], render_kw={\"class\": 'text'}, description = \"Password\") confirm_password",
"validators.Length(min = 8, message = \"Password must be at least",
"= \"You must select an option.\")], choices = gender_choices, render_kw={\"class\":",
"= {} for link in links: #Temporarily prefix all links",
"ValidationError(\"Passwords must match.\") class ChangeNameForm(Form): first_name = TextField(\"First Name\", [",
"Form.validate(self) for link in links: #Revert link values back to",
"= TextField(\"School Town\", [ validators.Required(message = \"Enter your school town.\"),",
"(\"2\", \"2\"), (\"3\", \"3\"), (\"4\", \"4\"), (\"5\", \"5+\") ] grade_choices",
"validators.Required(message = \"Enter your age\") ], render_kw={\"class\": 'text'}, description =",
"num_hackathons_choices, render_kw={\"class\": 'text'}, description = \"How many hackathons have you",
"= \"Personal Site Link (Optional)\") other_link = TextField(\"other\", [ validators.optional(),",
"False) # mlh_terms = BooleanField(\"I agree\",[ # validators.Required(message = \"Please",
"= TextField(\"Guardian Full Name\", [ validators.Required(message = \"You must enter",
"Name\", [ validators.Required(message = \"You must enter a name.\"), ],",
"phone number.\") ], render_kw={\"class\": 'text'}, description = \"Guardian Cellphone\") guardian_email",
"(\"female\", \"Female\"), (\"other\", \"Other\"), (\"rns\", \"Rather Not Say\") ] beginner_choices",
"\"Password\") class EmailForm(Form): email = TextField(\"Email\", [ validators.Required(message = \"Enter",
"Password\") new_password = PasswordField(\"New Password\", [ validators.Required(message = \"You must",
"8 characters.\") ], render_kw={\"class\": 'text'}, description = \"Password\") confirm_password =",
"size?\"), (\"XS\", \"Extra Small\"), (\"S\", \"Small\"), (\"M\", \"Medium\"), (\"L\", \"Large\"),",
"getattr(self, link) attr.data = originalValues[link] setattr(self, link, attr) if not",
"raise ValidationError(\"Passwords must match.\") class ChangeNameForm(Form): first_name = TextField(\"First Name\",",
"\"site_link\", \"other_link\"] originalValues = {} for link in links: #Temporarily",
"must select an option.\")], choices = num_hackathons_choices, render_kw={\"class\": 'text'}, description",
"mlh_coc = BooleanField(\"I agree\", [ validators.Required(message = \"Please read and",
"links: #Temporarily prefix all links with http:// if they are",
"form['password'].data if len(password) >= 8 and password != field.data: raise",
"Contact Name\") emergency_home_num = TextField(\"Emergency Contact Home Number\", [ validators.Required(message",
"(\"rns\", \"Rather Not Say\") ] beginner_choices = [ (\"\", \"Are",
"option.\")], choices = gender_choices, render_kw={\"class\": 'text'}, description = \"Gender\") beginner",
"have you mentored at?\") mentor_free_response1 = TextAreaField(free_response1_prompt_mentor, [ validators.Length(max =",
"Alaskan Native\"), (\"multiracial\", \"Multiracial\"), (\"hispanic\", \"Hispanic origin\"), (\"other\", \"Other\"), (\"rns\",",
"an email.\"), validators.Email(message = \"Invalid email address.\") ], render_kw={\"class\": 'text'},",
"restrictions?\") guardian_name = TextField(\"Guardian Full Name\", [ validators.Required(message = \"You",
"TextField(\"other\", [ validators.optional(), validators.URL(message = \"Invalid URL.\") ], render_kw={\"class\": 'text'},",
"your ideas.\" class HackerRegistrationForm(Form): email = TextField(\"Email\", [ validators.Required(message =",
"= SelectField(\"Grade\", [validators.Required(message = \"You must select an option.\")], choices",
"], render_kw={\"class\": 'text'}, description = \"School State\") school_phone_num = TextField(\"School",
"= \"Enter school's home number.\"), validators.Regexp(phone_regex, message = \"Please enter",
"\"Phone Number\") num_hackathons = SelectField(\"How many hackathons have you mentored",
"grade_choices = [ (\"\", \"What grade are you in?\"), (\"9\",",
"must enter a name.\") ], render_kw={\"class\": 'text'}, description = \"Emergency",
"validators.optional(), validators.URL(message = \"Invalid URL.\") ], render_kw={\"class\": 'text'}, description =",
"(\"\", \"What grade are you in?\"), (\"9\", \"9th\"), (\"10\", \"10th\"),",
"\"2\"), (\"3\", \"3\"), (\"4\", \"4\"), (\"5\", \"5+\") ] grade_choices =",
"validators.URL(message = \"Invalid URL.\") ], render_kw={\"class\": 'text'}, description = \"Other",
"render_kw={\"class\": 'text'}, description = \"How many hackathons have you mentored",
"LoginForm(Form): email = TextField(\"Email\", [ validators.Required(message = \"Enter an email.\"),",
"Code of Conduct.\", default = False) mlh_terms = BooleanField(\"I agree\",",
"of Conduct.\", default = False) mlh_terms = BooleanField(\"I agree\", [",
"raise ValidationError(\"Enter your gender.\") class MentorRegistrationForm(Form): email = TextField(\"Email\", [",
"= attending_choices, description = \"Will you be at hackBCA?\") #",
"render_kw={\"class\": 'text'}, description = \"Confirm Password\") mlh_coc = BooleanField(\"I agree\",",
"Contest Terms and Conditions and the MLH Privacy Policy.\", default",
"raise ValidationError(\"Passwords must match.\") attending_choices = [ (\"Attending\", \"Yes, I",
"#3 (Optional)\") password = PasswordField(\"Password\", [ validators.Required(message = \"You must",
"Contact Home Number\") emergency_cell_num = TextField(\"Emergency Contact Cellphone\", [ validators.Required(message",
"have you mentored at?\"), (\"0\", \"0\"), (\"1\", \"1\"), (\"2\", \"2\"),",
"= \"Email\") class RecoverForm(Form): password = PasswordField(\"Password\", [ validators.Required(message =",
"= PasswordField(\"New Password\", [ validators.Required(message = \"You must choose a",
"must be at least 8 characters.\") ], render_kw={\"class\": 'text'}, description",
"enter a valid phone number.\") # ], description = \"Phone",
"enter your current password.\"), validators.Length(min = 8, message = \"Password",
"the MLH Privacy Policy.\", default = False) def validate_confirm_password(form, field):",
"an email.\"), validators.Email(message = \"Invalid email address.\" )], render_kw={\"class\": 'text'},description",
"form['new_password'].data if len(password) >= 8 and password != field.data: raise",
"= \"Why do you want to come to hackBCA?\" free_response1_prompt_mentor",
"this question.\"), validators.Length(max = 1500, message = \"Response must be",
"= TextAreaField(\"Allergies\", [ # validators.optional(), # ], description = \"Do",
"you have any dietary restrictions?\") guardian_name = TextField(\"Guardian Full Name\",",
"if len(password) >= 8 and password != field.data: raise ValidationError(\"Passwords",
"links with http:// if they are missing it attr =",
"description = \"Ethnicity\") grade = SelectField(\"Grade\", [validators.Required(message = \"You must",
"[ validators.Required(message = \"Enter your guardian's home number.\"), validators.Regexp(phone_regex, message",
"= \"Principal Email\") cs_teacher_name = TextField(\"CS Teacher Name\", [ validators.optional(),",
"[validators.Required(message = \"You must select an option.\")], choices = beginner_choices,",
"= \"Ethnicity\") grade = SelectField(\"Grade\", [validators.Required(message = \"You must select",
"many hackathons have you mentored at?\", [validators.Required(message = \"You must",
"= TextField(\"Github Link\", [ validators.optional(), validators.URL(message = \"Invalid URL.\") ],",
"there any other medical issues that we should know about?",
"= TextField(\"Phone Number\", [ validators.Required(message = \"Enter your preferred contact",
"TextField(\"Company/School Name\", [ validators.Required(message = \"Enter your company/schools's name.\") ],",
"TextField(\"Emergency Contact Cellphone\", [ validators.Required(message = \"Enter your emergency contact's",
"option.\")], choices = num_hackathons_choices, render_kw={\"class\": 'text'}, description = \"How many",
"= SelectField(\"What is your shirt size?\", [validators.Required(message = \"You must",
"num_hackathons_choices_mentor, render_kw={\"class\": 'text'}, description = \"How many hackathons have you",
"\"Password\") confirm_password = PasswordField(\"Confirm Password\", render_kw={\"class\": 'text'}, description = \"Confirm",
"if re.match(\"^(http|https)://\", val) is None: val = \"http://\" + val",
"(\"other\", \"Other\"), (\"rns\", \"Rather Not Say\") ] beginner_choices = [",
"attending hackBCA III.\")], choices = attending_choices) # phone = TextField(\"Phone",
"(\"4\", \"4\"), (\"5\", \"5+\") ] grade_choices = [ (\"\", \"What",
"#2\", [ validators.optional(), validators.URL(message = \"Invalid URL.\") ], render_kw={\"class\": 'text'},",
"# ], description = \"I agree to the rules set",
"# ], description = \"Are there any other medical issues",
"'text'}, description = \"Phone Number\") num_hackathons = SelectField(\"How many hackathons",
"(\"rns\", \"Rather Not Say\") ] num_hackathons_choices = [ (\"\", \"How",
"agree\",[ # validators.Required(message = \"Please read and agree to the",
"'text'}, description = \"1500 characters maximum.\") mentor_free_response2 = TextAreaField(free_response2_prompt_mentor, [",
"read and agree to the MLH Terms and Conditions.\") ],",
"\"Ethnicity\") grade = SelectField(\"Grade\", [validators.Required(message = \"You must select an",
"site_link = TextField(\"Personal Site\", [ validators.optional(), validators.URL(message = \"Invalid URL.\")",
"email.\"), validators.Email(message = \"Invalid email address.\" )], render_kw={\"class\": 'text'}, description",
"= shirt_sizes, description = \"What is your shirt size?\") dietary_restrictions",
"dietary_restrictions = TextField(\"Dietary Restrictions\", [ validators.optional(), ], render_kw={\"class\": 'text'}, description",
"'text'}, description = \"Emergency Contact Email\") school_address = TextField(\"School Address\",",
"1500, message = \"Response must be less than 1500 characters",
"link in links: #Revert link values back to actual values",
"\"New Password\") confirm_password = PasswordField(\"<PASSWORD> Password\", render_kw={\"class\": 'text'}, description =",
"= \"Current Password\") new_password = PasswordField(\"New Password\", [ validators.Required(message =",
"a password.\"), validators.Length(min = 8, message = \"Password must be",
"hackathons have you attended?\", [validators.Required(message = \"You must select an",
"other medical issues that we should know about? (ex. Other",
"= num_hackathons_choices, render_kw={\"class\": 'text'}, description = \"How many hackathons have",
"False) mlh_terms = BooleanField(\"I agree\", [ validators.Required(message = \"Please read",
"setattr(self, link, attr) rv = Form.validate(self) for link in links:",
"MLH Privacy Policy.\", default = False) def validate(self): links =",
"Password\") def validate_confirm_password(form, field): password = form['password'].data if len(password) >=",
"hackathons have you mentored at?\", [validators.Required(message = \"You must select",
"'text'}, description = \"How many hackathons have you attended?\") free_response1",
"render_kw={\"class\": 'text'}, description = \"Principal Name\") school_principal_email = TextField(\"Principal Email\",",
"= \"Gender\") beginner = SelectField(\"Are you a beginner?\", [validators.Required(message =",
"PasswordField(\"<PASSWORD> Password\", render_kw={\"class\": 'text'}, description = \"Confirm Password\") mlh_coc =",
"#Man I love validators.URL links = [\"link1\", \"link2\", \"link3\"] originalValues",
"match.\") class ChangeNameForm(Form): first_name = TextField(\"First Name\", [ validators.Required(message =",
"TextField(\"Link #2\", [ validators.optional(), validators.URL(message = \"Invalid URL.\") ], render_kw={\"class\":",
"= \"You must enter a first name.\") ], render_kw={\"class\": 'text'},",
"], description = \"I have read & agree to the",
"num_hackathons = SelectField(\"How many hackathons have you attended?\", [validators.Required(message =",
"we should know about? (ex. Other allergies, illnesses, etc.)\") #",
"[ validators.optional(), ], render_kw={\"class\": 'text'}, description = \"CS Teacher Name",
"State\") school_phone_num = TextField(\"School Phone Number\", [ validators.Required(message = \"Enter",
"default = False) mlh_terms = BooleanField(\"I agree\", [ validators.Required(message =",
"validators.Required(message = \"Enter your school's name.\") ], render_kw={\"class\": 'text'}, description",
"description = \"School Name\") gender = SelectField(\"Gender\", [validators.Required(message = \"You",
"Name\") guardian_home_num = TextField(\"Guardian Home Number\", [ validators.Required(message = \"Enter",
"= \"What is your shirt size?\") # food_allergies = TextAreaField(\"Allergies\",",
"message = \"Response must be less than 1500 characters long.\")",
"\"What is your shirt size?\") # food_allergies = TextAreaField(\"Allergies\", [",
"val setattr(self, link, attr) rv = Form.validate(self) for link in",
"class RecoverForm(Form): password = PasswordField(\"Password\", [ validators.Required(message = \"You must",
"\"Email\") first_name = TextField(\"First Name\", [ validators.Required(message = \"You must",
"beginner?\"), (\"yes\", \"Yes\"), (\"no\", \"No\") ] ethnicity_choices = [ (\"\",",
"Cellphone\", [ validators.Required(message = \"Enter your guardian's cellphone number.\"), validators.Regexp(phone_regex,",
"num_hackathons_choices_mentor = [ (\"\", \"How many hackathons have you mentored",
"a last name.\") ], render_kw={\"class\": 'text'}, description = \"Last Name\")",
"the MLH Code of Conduct.\") # ], description = \"I",
"\"Confirm Password\") mlh_coc = BooleanField(\"I agree\", [ validators.Required(message = \"Please",
"= TextField(\"School Address\", [ validators.Required(message = \"Enter your school address.\"),",
"True def validate_other_gender(form, field): if form['gender'].data == 'other' and field.data",
"'text'}, description = \"School Town\") school_state = TextField(\"School State\", [",
"= False) # mlh_terms = BooleanField(\"I agree\",[ # validators.Required(message =",
"(\"\", \"How many hackathons have you been to?\"), (\"0\", \"0\"),",
"val = \"http://\" + val attr.data = val setattr(self, link,",
"= \"Invalid email address.\" )], render_kw={\"class\": 'text'}, description = \"Guardian",
"'text'}, description = \"First Name\") last_name = TextField(\"Last Name\", [",
"\"You must enter a name.\"), ], render_kw={\"class\": 'text'}, description =",
"a name.\") ], render_kw={\"class\": 'text'}, description = \"Emergency Contact Name\")",
"return False return True def validate_other_gender(form, field): if form['gender'].data ==",
"] class RsvpForm(Form): # attending = RadioField(\"Are you attending hackBCA",
"[ # validators.optional(), # ], description = \"Do you have",
"\"Would you like to run a workshop? If so, please",
"Cellphone\", [ validators.Required(message = \"Enter your emergency contact's cellphone.\"), validators.Regexp(phone_regex,",
"any dietary restrictions?\") guardian_name = TextField(\"Guardian Full Name\", [ validators.Required(message",
"\"Guardian Name\") guardian_home_num = TextField(\"Guardian Home Number\", [ validators.Required(message =",
"TextField(\"Dietary Restrictions\", [ validators.optional(), ], render_kw={\"class\": 'text'}, description = \"Do",
"render_kw={\"class\": 'text'}, description = \"Link #2 (Optional)\") link3 = TextField(\"Link",
"mentored at?\") mentor_free_response1 = TextAreaField(free_response1_prompt_mentor, [ validators.Length(max = 1500, message",
"\"link3\"] originalValues = {} for link in links: #Temporarily prefix",
"validate_confirm_password(form, field): password = form['new_password'].data if len(password) >= 8 and",
"class MentorRsvpForm(Form): # attending = RadioField(\"Are you attending hackBCA III?\",",
"\"Why do you want to come to hackBCA?\" free_response1_prompt_mentor =",
"= TextAreaField(free_response1_prompt, [ validators.Required(message = \"You must answer this question.\"),",
"email address.\" )], render_kw={\"class\": 'text'}, description = \"Emergency Contact Email\")",
"\"linkedin_link\", \"site_link\", \"other_link\"] originalValues = {} for link in links:",
"False return True class LoginForm(Form): email = TextField(\"Email\", [ validators.Required(message",
"\"How many hackathons have you been to?\"), (\"0\", \"0\"), (\"1\",",
"8 and password != field.data: raise ValidationError(\"Passwords must match.\") class",
"want to come to hackBCA?\" free_response1_prompt_mentor = \"Please list languages/frameworks/technologies",
"\"Emergency Contact Name\") emergency_home_num = TextField(\"Emergency Contact Home Number\", [",
"= TextField(\"Emergency Contact Email\", [ validators.Required(message = \"Enter an email.\"),",
"new_password = PasswordField(\"New Password\", [ validators.Required(message = \"You must choose",
"validators, ValidationError, RadioField import re phone_regex = \"(\\+\\d+-?)?((\\(?\\d{3}\\)?)|(\\d{3}))-?\\d{3}-?\\d{4}$\" gender_choices =",
"age = TextField(\"Age\", [ validators.Required(message = \"Enter your age\") ],",
"(\"\", \"Gender\"), (\"male\", \"Male\"), (\"female\", \"Female\"), (\"other\", \"Other\"), (\"rns\", \"Rather",
"link) attr.data = originalValues[link] setattr(self, link, attr) if not rv:",
"= \"Guardian Email\") emergency_name = TextField(\"Emergency Contact Full Name\", [",
"Name (if applicable)\") cs_teacher_email = TextField(\"CS Teacher Email\", [ validators.optional(),",
"characters.\") ], render_kw={\"class\": 'text'}, description = \"New Password\") confirm_password =",
"#3\", [ validators.optional(), validators.URL(message = \"Invalid URL.\") ], render_kw={\"class\": 'text'},",
"is your shirt size?\") # food_allergies = TextAreaField(\"Allergies\", [ #",
"= \"Enter your school state.\"), ], render_kw={\"class\": 'text'}, description =",
"validators.Required(message = \"You must enter a name.\"), ], render_kw={\"class\": 'text'},",
"description = \"Last Name\") class ChangePasswordForm(Form): password = PasswordField(\"Password\", [",
"\"11th\"), (\"12\", \"12th\") ] shirt_sizes = [ (\"\", \"What is",
"many hackathons have you attended?\", [validators.Required(message = \"You must select",
"Contact Email\", [ validators.Required(message = \"Enter an email.\"), validators.Email(message =",
"rv = Form.validate(self) for link in links: #Revert link values",
"Name\") school = TextField(\"Company/School Name\", [ validators.Required(message = \"Enter your",
"(\"Attending\", \"Yes, I will!\"), (\"Not Attending\", \"No, I won't.\") ]",
"= RadioField(\"Are you attending hackBCA III?\", [validators.Required(message = \"Please tell",
"attending_choices, description = \"Will you be at hackBCA?\") # t_shirt_size",
"= [ (\"\", \"Ethnicity\"), (\"white\", \"White\"), (\"african_american\", \"African American\"), (\"asian_pacific\",",
"\"Enter an email.\"), validators.Email(message = \"Invalid email address.\" )], render_kw={\"class\":",
"must match.\") class ChangeNameForm(Form): first_name = TextField(\"First Name\", [ validators.Required(message",
"(Optional)\") site_link = TextField(\"Personal Site\", [ validators.optional(), validators.URL(message = \"Invalid",
"[], render_kw={\"class\": 'text'}, description = \"Password\") class EmailForm(Form): email =",
"to the rules set forth by hackBCA.\", default = False)",
"in?\"), (\"9\", \"9th\"), (\"10\", \"10th\"), (\"11\", \"11th\"), (\"12\", \"12th\") ]",
"rv: return False return True def validate_other_gender(form, field): if form['gender'].data",
"Phone Number\", [ validators.Required(message = \"Enter school's home number.\"), validators.Regexp(phone_regex,",
"'text'}, description = \"Emergency Contact Name\") emergency_home_num = TextField(\"Emergency Contact",
"= TextField(\"First Name\", [ validators.Required(message = \"You must enter a",
"and Conditions.\") ], description = \"I agree to the MLH",
"render_kw={\"class\": 'text'}, description = \"Phone Number\") num_hackathons = SelectField(\"How many",
"description = \"Confirm Password\") mlh_coc = BooleanField(\"I agree\", [ validators.Required(message",
"(\"9\", \"9th\"), (\"10\", \"10th\"), (\"11\", \"11th\"), (\"12\", \"12th\") ] shirt_sizes",
"applicable)\") # class MentorRsvpForm(Form): # attending = RadioField(\"Are you attending",
"\"Last Name\") class ChangePasswordForm(Form): password = PasswordField(\"Password\", [ validators.Required(message =",
"= \"You must enter your current password.\"), validators.Length(min = 8,",
"= \"Password must be at least 8 characters.\") ], render_kw={\"class\":",
"\"You must select an option.\")], choices = shirt_sizes, description =",
"= \"Phone Number Confirmation\") # t_shirt_size = SelectField(\"What is your",
"= [ (\"\", \"Are you a beginner?\"), (\"yes\", \"Yes\"), (\"no\",",
"SelectField(\"How many hackathons have you attended?\", [validators.Required(message = \"You must",
"'text'}, description = \"Guardian Email\") emergency_name = TextField(\"Emergency Contact Full",
"'text'},description = \"Email\") password = PasswordField(\"Password\", [], render_kw={\"class\": 'text'}, description",
"you mentored at?\", [validators.Required(message = \"You must select an option.\")],",
"validators.optional(), ], render_kw={\"class\": 'text'}, description = \"Do you have any",
"'text'}, description = \"Emergency Contact Home Number\") emergency_cell_num = TextField(\"Emergency",
"SelectField(\"Are you a beginner?\", [validators.Required(message = \"You must select an",
"= TextAreaField(free_response2_prompt_mentor, [ validators.Length(max = 1500, message = \"Response must",
"TextField(\"Emergency Contact Email\", [ validators.Required(message = \"Enter an email.\"), validators.Email(message",
"TextAreaField(\"Allergies\", [ # validators.optional(), # ], description = \"Do you",
"= BooleanField(\"I agree\",[ # validators.Required(message = \"Please read and agree",
"\"Enter your school state.\"), ], render_kw={\"class\": 'text'}, description = \"School",
"description = \"1500 characters maximum.\") github_link = TextField(\"Github Link\", [",
"rules set forth by hackBCA.\", default = False) # mlh_terms",
"\"How many hackathons have you attended?\") free_response1 = TextAreaField(free_response1_prompt, [",
"TextAreaField(free_response1_prompt, [ validators.Required(message = \"You must answer this question.\"), validators.Length(max",
"Teacher Email\", [ validators.optional(), validators.Email(message = \"Invalid email address.\" )],",
"\"You must enter your current password.\"), validators.Length(min = 8, message",
"have read & agree to the MLH Code of Conduct.\",",
"enter a password.\"), validators.Length(min = 8, message = \"Password must",
"and the MLH Privacy Policy.\", default = False) def validate(self):",
"'text'}, description = \"School Address\") school_town = TextField(\"School Town\", [",
"hackathons have you attended?\") free_response1 = TextAreaField(free_response1_prompt, [ validators.Required(message =",
"issues that we should know about? (ex. Other allergies, illnesses,",
"\"1500 characters maximum.\") github_link = TextField(\"Github Link\", [ validators.optional(), validators.URL(message",
"\"Rather Not Say\") ] beginner_choices = [ (\"\", \"Are you",
"] num_hackathons_choices_mentor = [ (\"\", \"How many hackathons have you",
"], description = \"Phone Number Confirmation\") # t_shirt_size = SelectField(\"What",
"Email\") emergency_name = TextField(\"Emergency Contact Full Name\", [ validators.Required(message =",
"and agree to the MLH Terms and Conditions.\") ], description",
"your gender.\") class MentorRegistrationForm(Form): email = TextField(\"Email\", [ validators.Required(message =",
"\"9th\"), (\"10\", \"10th\"), (\"11\", \"11th\"), (\"12\", \"12th\") ] shirt_sizes =",
"American\"), (\"asian_pacific\", \"Asian or Pacific Islander\"), (\"american_indian_alaskan_native\", \"American Indian or"
] |
[
"in query] return json.jsonify({ 'meta': { 'pager_data': { 'totalItems': total_items,",
"def index(): return render_template('index.html') @app.route('/location') def location(): req_title = request.args.get('title',",
"else total_pages query = query.paginate(current_page, LOCATION_ITEMS_PER_PAGE) locations = [l.as_dict() for",
"for l in query] return json.jsonify({ 'meta': { 'pager_data': {",
"** '%{}%'.format(req_title)) total_items = query.count() total_pages = ceil(total_items / LOCATION_ITEMS_PER_PAGE)",
"send_from_directory('static', path) @app.route('/') def index(): return render_template('index.html') @app.route('/location') def location():",
"'itemsPerPage': LOCATION_ITEMS_PER_PAGE, }, }, 'entities': { 'locations': locations, }, })",
"import os from flask import json from flask import Flask",
"# from json_loader import prepare_locations from models import Location #",
"utf-8 '''フロントコントローラを提供する ''' from math import ceil import os from",
"** '%{}%'.format(req_title))) movies = [{'id': index, 'title': l.title} for index,",
"json.jsonify({ 'meta': { 'pager_data': { 'totalItems': total_items, 'totalPages': total_pages, 'currentItems':",
"current_page = req_page if req_page <= total_pages else total_pages query",
"= os.environ['GOOGLE_API_KEY'] app.config['ROOT'] = (app.config['APPLICATION_ROOT'] if app.config['APPLICATION_ROOT'] else '') @app.route('/static/<path:path>')",
"req_page <= total_pages else total_pages query = query.paginate(current_page, LOCATION_ITEMS_PER_PAGE) locations",
"1 query = Location.selectbase() if req_title: query = query.where(Location.title **",
"# from json_loader import load_locations # from json_loader import prepare_locations",
"'%{}%'.format(req_title)) total_items = query.count() total_pages = ceil(total_items / LOCATION_ITEMS_PER_PAGE) current_page",
"= query.where(Location.title ** '%{}%'.format(req_title)) total_items = query.count() total_pages = ceil(total_items",
"os.environ['GOOGLE_API_KEY'] app.config['ROOT'] = (app.config['APPLICATION_ROOT'] if app.config['APPLICATION_ROOT'] else '') @app.route('/static/<path:path>') def",
"from flask import Flask from flask import request from flask",
"@app.route('/location') def location(): req_title = request.args.get('title', None) try: req_page =",
"e: req_page = 1 query = Location.selectbase() if req_title: query",
"'meta': { 'pager_data': { 'totalItems': total_items, 'totalPages': total_pages, 'currentItems': len(locations),",
"= query.count() total_pages = ceil(total_items / LOCATION_ITEMS_PER_PAGE) current_page = req_page",
".distinct() .where(Location.title ** '%{}%'.format(req_title))) movies = [{'id': index, 'title': l.title}",
"app.config['ROOT'] = (app.config['APPLICATION_ROOT'] if app.config['APPLICATION_ROOT'] else '') @app.route('/static/<path:path>') def send_js(path):",
"def movie(): req_title = request.args.get('title', None) if not req_title: return",
"from flask import render_template # from json_loader import load_locations #",
"flask import request from flask import send_from_directory from flask import",
"LOCATION_ITEMS_PER_PAGE) locations = [l.as_dict() for l in query] return json.jsonify({",
"current_page, 'itemsPerPage': LOCATION_ITEMS_PER_PAGE, }, }, 'entities': { 'locations': locations, },",
"flask import send_from_directory from flask import render_template # from json_loader",
"return json.jsonify([]) query = (Location.select(Location.title) .distinct() .where(Location.title ** '%{}%'.format(req_title))) movies",
"from flask import json from flask import Flask from flask",
"except ValueError as e: req_page = 1 query = Location.selectbase()",
"send_from_directory from flask import render_template # from json_loader import load_locations",
"if req_page <= total_pages else total_pages query = query.paginate(current_page, LOCATION_ITEMS_PER_PAGE)",
"movies = [{'id': index, 'title': l.title} for index, l in",
"req_title = request.args.get('title', None) if not req_title: return json.jsonify([]) query",
"Flask from flask import request from flask import send_from_directory from",
"int(request.args.get('page', 1)) except ValueError as e: req_page = 1 query",
"req_title: return json.jsonify([]) query = (Location.select(Location.title) .distinct() .where(Location.title ** '%{}%'.format(req_title)))",
"app.config['APPLICATION_ROOT'] else '') @app.route('/static/<path:path>') def send_js(path): return send_from_directory('static', path) @app.route('/')",
"@app.route('/') def index(): return render_template('index.html') @app.route('/location') def location(): req_title =",
"{ 'pager_data': { 'totalItems': total_items, 'totalPages': total_pages, 'currentItems': len(locations), 'currentPage':",
"query = (Location.select(Location.title) .distinct() .where(Location.title ** '%{}%'.format(req_title))) movies = [{'id':",
"ページ毎のロケ地表示する LOCATION_ITEMS_PER_PAGE = 20 app = Flask(__name__) app.config['GOOGLE_API_KEY'] = os.environ['GOOGLE_API_KEY']",
"req_page = int(request.args.get('page', 1)) except ValueError as e: req_page =",
"# coding: utf-8 '''フロントコントローラを提供する ''' from math import ceil import",
".where(Location.title ** '%{}%'.format(req_title))) movies = [{'id': index, 'title': l.title} for",
"}) @app.route('/movie') def movie(): req_title = request.args.get('title', None) if not",
"= 20 app = Flask(__name__) app.config['GOOGLE_API_KEY'] = os.environ['GOOGLE_API_KEY'] app.config['ROOT'] =",
"@app.route('/movie') def movie(): req_title = request.args.get('title', None) if not req_title:",
"@app.route('/static/<path:path>') def send_js(path): return send_from_directory('static', path) @app.route('/') def index(): return",
"query = query.paginate(current_page, LOCATION_ITEMS_PER_PAGE) locations = [l.as_dict() for l in",
"# ページ毎のロケ地表示する LOCATION_ITEMS_PER_PAGE = 20 app = Flask(__name__) app.config['GOOGLE_API_KEY'] =",
"LOCATION_ITEMS_PER_PAGE) current_page = req_page if req_page <= total_pages else total_pages",
"if req_title: query = query.where(Location.title ** '%{}%'.format(req_title)) total_items = query.count()",
"json_loader import load_locations # from json_loader import prepare_locations from models",
"return send_from_directory('static', path) @app.route('/') def index(): return render_template('index.html') @app.route('/location') def",
"}, }) @app.route('/movie') def movie(): req_title = request.args.get('title', None) if",
"= Flask(__name__) app.config['GOOGLE_API_KEY'] = os.environ['GOOGLE_API_KEY'] app.config['ROOT'] = (app.config['APPLICATION_ROOT'] if app.config['APPLICATION_ROOT']",
"ValueError as e: req_page = 1 query = Location.selectbase() if",
"total_pages else total_pages query = query.paginate(current_page, LOCATION_ITEMS_PER_PAGE) locations = [l.as_dict()",
"return json.jsonify({ 'meta': { 'pager_data': { 'totalItems': total_items, 'totalPages': total_pages,",
"total_pages = ceil(total_items / LOCATION_ITEMS_PER_PAGE) current_page = req_page if req_page",
"locations = [l.as_dict() for l in query] return json.jsonify({ 'meta':",
"req_page if req_page <= total_pages else total_pages query = query.paginate(current_page,",
"import request from flask import send_from_directory from flask import render_template",
"import Location # ページ毎のロケ地表示する LOCATION_ITEMS_PER_PAGE = 20 app = Flask(__name__)",
"if not req_title: return json.jsonify([]) query = (Location.select(Location.title) .distinct() .where(Location.title",
"import Flask from flask import request from flask import send_from_directory",
"'totalItems': total_items, 'totalPages': total_pages, 'currentItems': len(locations), 'currentPage': current_page, 'itemsPerPage': LOCATION_ITEMS_PER_PAGE,",
"math import ceil import os from flask import json from",
"Flask(__name__) app.config['GOOGLE_API_KEY'] = os.environ['GOOGLE_API_KEY'] app.config['ROOT'] = (app.config['APPLICATION_ROOT'] if app.config['APPLICATION_ROOT'] else",
"= [l.as_dict() for l in query] return json.jsonify({ 'meta': {",
"movie(): req_title = request.args.get('title', None) if not req_title: return json.jsonify([])",
"send_js(path): return send_from_directory('static', path) @app.route('/') def index(): return render_template('index.html') @app.route('/location')",
"try: req_page = int(request.args.get('page', 1)) except ValueError as e: req_page",
"import json from flask import Flask from flask import request",
"'') @app.route('/static/<path:path>') def send_js(path): return send_from_directory('static', path) @app.route('/') def index():",
"= (Location.select(Location.title) .distinct() .where(Location.title ** '%{}%'.format(req_title))) movies = [{'id': index,",
"= 1 query = Location.selectbase() if req_title: query = query.where(Location.title",
"load_locations # from json_loader import prepare_locations from models import Location",
"from json_loader import prepare_locations from models import Location # ページ毎のロケ地表示する",
"from flask import request from flask import send_from_directory from flask",
"import ceil import os from flask import json from flask",
"'locations': locations, }, }) @app.route('/movie') def movie(): req_title = request.args.get('title',",
"index, 'title': l.title} for index, l in enumerate(query)] return json.jsonify(movies)",
"not req_title: return json.jsonify([]) query = (Location.select(Location.title) .distinct() .where(Location.title **",
"= [{'id': index, 'title': l.title} for index, l in enumerate(query)]",
"}, }, 'entities': { 'locations': locations, }, }) @app.route('/movie') def",
"[{'id': index, 'title': l.title} for index, l in enumerate(query)] return",
"'currentPage': current_page, 'itemsPerPage': LOCATION_ITEMS_PER_PAGE, }, }, 'entities': { 'locations': locations,",
"'totalPages': total_pages, 'currentItems': len(locations), 'currentPage': current_page, 'itemsPerPage': LOCATION_ITEMS_PER_PAGE, }, },",
"req_page = 1 query = Location.selectbase() if req_title: query =",
"LOCATION_ITEMS_PER_PAGE, }, }, 'entities': { 'locations': locations, }, }) @app.route('/movie')",
"total_items, 'totalPages': total_pages, 'currentItems': len(locations), 'currentPage': current_page, 'itemsPerPage': LOCATION_ITEMS_PER_PAGE, },",
"import send_from_directory from flask import render_template # from json_loader import",
"ceil(total_items / LOCATION_ITEMS_PER_PAGE) current_page = req_page if req_page <= total_pages",
"= Location.selectbase() if req_title: query = query.where(Location.title ** '%{}%'.format(req_title)) total_items",
"None) if not req_title: return json.jsonify([]) query = (Location.select(Location.title) .distinct()",
"def location(): req_title = request.args.get('title', None) try: req_page = int(request.args.get('page',",
"app.config['GOOGLE_API_KEY'] = os.environ['GOOGLE_API_KEY'] app.config['ROOT'] = (app.config['APPLICATION_ROOT'] if app.config['APPLICATION_ROOT'] else '')",
"= (app.config['APPLICATION_ROOT'] if app.config['APPLICATION_ROOT'] else '') @app.route('/static/<path:path>') def send_js(path): return",
"/ LOCATION_ITEMS_PER_PAGE) current_page = req_page if req_page <= total_pages else",
"app = Flask(__name__) app.config['GOOGLE_API_KEY'] = os.environ['GOOGLE_API_KEY'] app.config['ROOT'] = (app.config['APPLICATION_ROOT'] if",
"flask import json from flask import Flask from flask import",
"request.args.get('title', None) try: req_page = int(request.args.get('page', 1)) except ValueError as",
"json_loader import prepare_locations from models import Location # ページ毎のロケ地表示する LOCATION_ITEMS_PER_PAGE",
"Location # ページ毎のロケ地表示する LOCATION_ITEMS_PER_PAGE = 20 app = Flask(__name__) app.config['GOOGLE_API_KEY']",
"json from flask import Flask from flask import request from",
"flask import Flask from flask import request from flask import",
"len(locations), 'currentPage': current_page, 'itemsPerPage': LOCATION_ITEMS_PER_PAGE, }, }, 'entities': { 'locations':",
"models import Location # ページ毎のロケ地表示する LOCATION_ITEMS_PER_PAGE = 20 app =",
"render_template # from json_loader import load_locations # from json_loader import",
"total_items = query.count() total_pages = ceil(total_items / LOCATION_ITEMS_PER_PAGE) current_page =",
"req_title: query = query.where(Location.title ** '%{}%'.format(req_title)) total_items = query.count() total_pages",
"= request.args.get('title', None) if not req_title: return json.jsonify([]) query =",
"prepare_locations from models import Location # ページ毎のロケ地表示する LOCATION_ITEMS_PER_PAGE = 20",
"locations, }, }) @app.route('/movie') def movie(): req_title = request.args.get('title', None)",
"{ 'totalItems': total_items, 'totalPages': total_pages, 'currentItems': len(locations), 'currentPage': current_page, 'itemsPerPage':",
"path) @app.route('/') def index(): return render_template('index.html') @app.route('/location') def location(): req_title",
"Location.selectbase() if req_title: query = query.where(Location.title ** '%{}%'.format(req_title)) total_items =",
"= req_page if req_page <= total_pages else total_pages query =",
"query.paginate(current_page, LOCATION_ITEMS_PER_PAGE) locations = [l.as_dict() for l in query] return",
"{ 'locations': locations, }, }) @app.route('/movie') def movie(): req_title =",
"'''フロントコントローラを提供する ''' from math import ceil import os from flask",
"import load_locations # from json_loader import prepare_locations from models import",
"else '') @app.route('/static/<path:path>') def send_js(path): return send_from_directory('static', path) @app.route('/') def",
"= ceil(total_items / LOCATION_ITEMS_PER_PAGE) current_page = req_page if req_page <=",
"request.args.get('title', None) if not req_title: return json.jsonify([]) query = (Location.select(Location.title)",
"flask import render_template # from json_loader import load_locations # from",
"20 app = Flask(__name__) app.config['GOOGLE_API_KEY'] = os.environ['GOOGLE_API_KEY'] app.config['ROOT'] = (app.config['APPLICATION_ROOT']",
"from math import ceil import os from flask import json",
"query = query.where(Location.title ** '%{}%'.format(req_title)) total_items = query.count() total_pages =",
"}, 'entities': { 'locations': locations, }, }) @app.route('/movie') def movie():",
"from flask import send_from_directory from flask import render_template # from",
"from json_loader import load_locations # from json_loader import prepare_locations from",
"total_pages, 'currentItems': len(locations), 'currentPage': current_page, 'itemsPerPage': LOCATION_ITEMS_PER_PAGE, }, }, 'entities':",
"= request.args.get('title', None) try: req_page = int(request.args.get('page', 1)) except ValueError",
"index(): return render_template('index.html') @app.route('/location') def location(): req_title = request.args.get('title', None)",
"req_title = request.args.get('title', None) try: req_page = int(request.args.get('page', 1)) except",
"import prepare_locations from models import Location # ページ毎のロケ地表示する LOCATION_ITEMS_PER_PAGE =",
"l in query] return json.jsonify({ 'meta': { 'pager_data': { 'totalItems':",
"query.where(Location.title ** '%{}%'.format(req_title)) total_items = query.count() total_pages = ceil(total_items /",
"request from flask import send_from_directory from flask import render_template #",
"(app.config['APPLICATION_ROOT'] if app.config['APPLICATION_ROOT'] else '') @app.route('/static/<path:path>') def send_js(path): return send_from_directory('static',",
"total_pages query = query.paginate(current_page, LOCATION_ITEMS_PER_PAGE) locations = [l.as_dict() for l",
"coding: utf-8 '''フロントコントローラを提供する ''' from math import ceil import os",
"LOCATION_ITEMS_PER_PAGE = 20 app = Flask(__name__) app.config['GOOGLE_API_KEY'] = os.environ['GOOGLE_API_KEY'] app.config['ROOT']",
"'currentItems': len(locations), 'currentPage': current_page, 'itemsPerPage': LOCATION_ITEMS_PER_PAGE, }, }, 'entities': {",
"1)) except ValueError as e: req_page = 1 query =",
"from models import Location # ページ毎のロケ地表示する LOCATION_ITEMS_PER_PAGE = 20 app",
"''' from math import ceil import os from flask import",
"render_template('index.html') @app.route('/location') def location(): req_title = request.args.get('title', None) try: req_page",
"location(): req_title = request.args.get('title', None) try: req_page = int(request.args.get('page', 1))",
"<= total_pages else total_pages query = query.paginate(current_page, LOCATION_ITEMS_PER_PAGE) locations =",
"query] return json.jsonify({ 'meta': { 'pager_data': { 'totalItems': total_items, 'totalPages':",
"'pager_data': { 'totalItems': total_items, 'totalPages': total_pages, 'currentItems': len(locations), 'currentPage': current_page,",
"ceil import os from flask import json from flask import",
"None) try: req_page = int(request.args.get('page', 1)) except ValueError as e:",
"import render_template # from json_loader import load_locations # from json_loader",
"json.jsonify([]) query = (Location.select(Location.title) .distinct() .where(Location.title ** '%{}%'.format(req_title))) movies =",
"as e: req_page = 1 query = Location.selectbase() if req_title:",
"'entities': { 'locations': locations, }, }) @app.route('/movie') def movie(): req_title",
"'%{}%'.format(req_title))) movies = [{'id': index, 'title': l.title} for index, l",
"def send_js(path): return send_from_directory('static', path) @app.route('/') def index(): return render_template('index.html')",
"[l.as_dict() for l in query] return json.jsonify({ 'meta': { 'pager_data':",
"query = Location.selectbase() if req_title: query = query.where(Location.title ** '%{}%'.format(req_title))",
"return render_template('index.html') @app.route('/location') def location(): req_title = request.args.get('title', None) try:",
"= query.paginate(current_page, LOCATION_ITEMS_PER_PAGE) locations = [l.as_dict() for l in query]",
"(Location.select(Location.title) .distinct() .where(Location.title ** '%{}%'.format(req_title))) movies = [{'id': index, 'title':",
"query.count() total_pages = ceil(total_items / LOCATION_ITEMS_PER_PAGE) current_page = req_page if",
"= int(request.args.get('page', 1)) except ValueError as e: req_page = 1",
"os from flask import json from flask import Flask from",
"if app.config['APPLICATION_ROOT'] else '') @app.route('/static/<path:path>') def send_js(path): return send_from_directory('static', path)"
] |
[
"\"\"\"Harder variant of standard dungeons like ``Corrupted Decrepit Sewers`` or",
"in ( \"Zombie\", \"Animal\", \"Skeleton\", \"Spider\", \"Silverfish\",): return DungeonType.REMOVED elif",
"\"Decrepit Sewers\", \"Infested Pit\", \"Ice Barrows\", \"Lost Sanctuary\", \"Sand-Swept Tomb\",",
"Graveyard`` or ``Fallen Factory``\"\"\" CORRUPTED = \"CORRUPTED\" \"\"\"Harder variant of",
"\"Ice Barrows\", \"Lost Sanctuary\", \"Sand-Swept Tomb\", \"Underworld Crypt\", \"Undergrowth Ruins\",",
"( \"Zombie\", \"Animal\", \"Skeleton\", \"Spider\", \"Silverfish\",): return DungeonType.REMOVED elif self.name",
"{self.name}\") @property def completed(self) -> int: \"\"\"Total runs completed by",
"return DungeonType.REMOVED_MINI elif self.name in ( \"Decrepit Sewers\", \"Infested Pit\",",
"Tomb\", \"Underworld Crypt\", \"Undergrowth Ruins\", \"Eldritch Outlook\", \"Galleon's Graveyard\", \"Fallen",
"dungeon: {self.name}\") @property def completed(self) -> int: \"\"\"Total runs completed",
"STANDARD = \"STANDARD\" \"\"\"Generic dungeons like ``Galleon's Graveyard`` or ``Fallen",
":py:class:`Player`\"\"\" @property def name(self) -> str: \"\"\"Name of the dungeon",
"def type(self) -> DungeonType: \"\"\"Type of the dungeon.\"\"\" if self.name.startswith(\"Corrupted\"):",
"class Dungeon(CorkusBase): \"\"\"Represents a `Dungeon <https://wynncraft.fandom.com/wiki/Dungeons>`_ completed by a :py:class:`Player`\"\"\"",
"Outlook\", \"Galleon's Graveyard\", \"Fallen Factory\"): return DungeonType.STANDARD else: raise ValueError(f\"Invalid",
"class DungeonType(Enum): REMOVED = \"REMOVED\" \"\"\"Dungeons that were removed from",
"in ( \"Jungle\", \"Ice\", \"Ocean\"): return DungeonType.REMOVED_MINI elif self.name in",
"= \"REMOVED\" \"\"\"Dungeons that were removed from the game in",
"dungeon.\"\"\" if self.name.startswith(\"Corrupted\"): return DungeonType.CORRUPTED elif self.name in ( \"Zombie\",",
"\"Animal\", \"Skeleton\", \"Spider\", \"Silverfish\",): return DungeonType.REMOVED elif self.name in (",
"``Galleon's Graveyard`` or ``Fallen Factory``\"\"\" CORRUPTED = \"CORRUPTED\" \"\"\"Harder variant",
"CORRUPTED = \"CORRUPTED\" \"\"\"Harder variant of standard dungeons like ``Corrupted",
"like ``Ice`` or ``Ocean``\"\"\" STANDARD = \"STANDARD\" \"\"\"Generic dungeons like",
"type(self) -> DungeonType: \"\"\"Type of the dungeon.\"\"\" if self.name.startswith(\"Corrupted\"): return",
"``1.17`` like ``Ice`` or ``Ocean``\"\"\" STANDARD = \"STANDARD\" \"\"\"Generic dungeons",
"<https://wynncraft.fandom.com/wiki/Dungeons>`_ completed by a :py:class:`Player`\"\"\" @property def name(self) -> str:",
"runs completed by the player. Failed runs are not counted.\"\"\"",
"``Corrupted Decrepit Sewers`` or ``Corrupted Sand-Swept Tomb``\"\"\" class Dungeon(CorkusBase): \"\"\"Represents",
"DungeonType.REMOVED elif self.name in ( \"Jungle\", \"Ice\", \"Ocean\"): return DungeonType.REMOVED_MINI",
"in version ``1.14.1`` like ``Skeleton`` or ``Spider``\"\"\" REMOVED_MINI = \"REMOVED_MINI\"",
"that were removed from the game in version ``1.14.1`` like",
"elif self.name in ( \"Jungle\", \"Ice\", \"Ocean\"): return DungeonType.REMOVED_MINI elif",
"Tomb``\"\"\" class Dungeon(CorkusBase): \"\"\"Represents a `Dungeon <https://wynncraft.fandom.com/wiki/Dungeons>`_ completed by a",
"Decrepit Sewers`` or ``Corrupted Sand-Swept Tomb``\"\"\" class Dungeon(CorkusBase): \"\"\"Represents a",
"( \"Decrepit Sewers\", \"Infested Pit\", \"Ice Barrows\", \"Lost Sanctuary\", \"Sand-Swept",
"= \"REMOVED_MINI\" \"\"\"Minidungeons that were reworked in version ``1.17`` like",
"like ``Decrepit Sewers``, ``Galleon's Graveyard`` or ``Fallen Factory``.\"\"\" return self._attributes.get(\"name\",",
"\"Silverfish\",): return DungeonType.REMOVED elif self.name in ( \"Jungle\", \"Ice\", \"Ocean\"):",
"standard dungeons like ``Corrupted Decrepit Sewers`` or ``Corrupted Sand-Swept Tomb``\"\"\"",
"DungeonType: \"\"\"Type of the dungeon.\"\"\" if self.name.startswith(\"Corrupted\"): return DungeonType.CORRUPTED elif",
"def completed(self) -> int: \"\"\"Total runs completed by the player.",
"or ``Fallen Factory``\"\"\" CORRUPTED = \"CORRUPTED\" \"\"\"Harder variant of standard",
"of the dungeon.\"\"\" if self.name.startswith(\"Corrupted\"): return DungeonType.CORRUPTED elif self.name in",
"the dungeon.\"\"\" if self.name.startswith(\"Corrupted\"): return DungeonType.CORRUPTED elif self.name in (",
"CorkusBase from enum import Enum class DungeonType(Enum): REMOVED = \"REMOVED\"",
"``Ocean``\"\"\" STANDARD = \"STANDARD\" \"\"\"Generic dungeons like ``Galleon's Graveyard`` or",
"from the game in version ``1.14.1`` like ``Skeleton`` or ``Spider``\"\"\"",
"Graveyard\", \"Fallen Factory\"): return DungeonType.STANDARD else: raise ValueError(f\"Invalid dungeon: {self.name}\")",
"\"\"\"Generic dungeons like ``Galleon's Graveyard`` or ``Fallen Factory``\"\"\" CORRUPTED =",
"enum import Enum class DungeonType(Enum): REMOVED = \"REMOVED\" \"\"\"Dungeons that",
"Graveyard`` or ``Fallen Factory``.\"\"\" return self._attributes.get(\"name\", \"\") @property def type(self)",
"\"Skeleton\", \"Spider\", \"Silverfish\",): return DungeonType.REMOVED elif self.name in ( \"Jungle\",",
"removed from the game in version ``1.14.1`` like ``Skeleton`` or",
"\"Eldritch Outlook\", \"Galleon's Graveyard\", \"Fallen Factory\"): return DungeonType.STANDARD else: raise",
"from enum import Enum class DungeonType(Enum): REMOVED = \"REMOVED\" \"\"\"Dungeons",
"Sewers`` or ``Corrupted Sand-Swept Tomb``\"\"\" class Dungeon(CorkusBase): \"\"\"Represents a `Dungeon",
"<filename>corkus/objects/dungeon.py from __future__ import annotations from .base import CorkusBase from",
"dungeon like ``Decrepit Sewers``, ``Galleon's Graveyard`` or ``Fallen Factory``.\"\"\" return",
"return DungeonType.STANDARD else: raise ValueError(f\"Invalid dungeon: {self.name}\") @property def completed(self)",
"return DungeonType.REMOVED elif self.name in ( \"Jungle\", \"Ice\", \"Ocean\"): return",
"or ``Fallen Factory``.\"\"\" return self._attributes.get(\"name\", \"\") @property def type(self) ->",
"self.name in ( \"Jungle\", \"Ice\", \"Ocean\"): return DungeonType.REMOVED_MINI elif self.name",
"__future__ import annotations from .base import CorkusBase from enum import",
"\"Ocean\"): return DungeonType.REMOVED_MINI elif self.name in ( \"Decrepit Sewers\", \"Infested",
"from .base import CorkusBase from enum import Enum class DungeonType(Enum):",
"the game in version ``1.14.1`` like ``Skeleton`` or ``Spider``\"\"\" REMOVED_MINI",
"counted.\"\"\" return self._attributes.get(\"completed\", 0) def __repr__(self) -> str: return f\"<Dungeon",
"name(self) -> str: \"\"\"Name of the dungeon like ``Decrepit Sewers``,",
"dungeons like ``Galleon's Graveyard`` or ``Fallen Factory``\"\"\" CORRUPTED = \"CORRUPTED\"",
"completed by the player. Failed runs are not counted.\"\"\" return",
"\"Spider\", \"Silverfish\",): return DungeonType.REMOVED elif self.name in ( \"Jungle\", \"Ice\",",
"Dungeon(CorkusBase): \"\"\"Represents a `Dungeon <https://wynncraft.fandom.com/wiki/Dungeons>`_ completed by a :py:class:`Player`\"\"\" @property",
"DungeonType(Enum): REMOVED = \"REMOVED\" \"\"\"Dungeons that were removed from the",
"Sand-Swept Tomb``\"\"\" class Dungeon(CorkusBase): \"\"\"Represents a `Dungeon <https://wynncraft.fandom.com/wiki/Dungeons>`_ completed by",
"like ``Corrupted Decrepit Sewers`` or ``Corrupted Sand-Swept Tomb``\"\"\" class Dungeon(CorkusBase):",
"self._attributes.get(\"name\", \"\") @property def type(self) -> DungeonType: \"\"\"Type of the",
"``Ice`` or ``Ocean``\"\"\" STANDARD = \"STANDARD\" \"\"\"Generic dungeons like ``Galleon's",
"Barrows\", \"Lost Sanctuary\", \"Sand-Swept Tomb\", \"Underworld Crypt\", \"Undergrowth Ruins\", \"Eldritch",
"\"Infested Pit\", \"Ice Barrows\", \"Lost Sanctuary\", \"Sand-Swept Tomb\", \"Underworld Crypt\",",
"reworked in version ``1.17`` like ``Ice`` or ``Ocean``\"\"\" STANDARD =",
"return DungeonType.CORRUPTED elif self.name in ( \"Zombie\", \"Animal\", \"Skeleton\", \"Spider\",",
"that were reworked in version ``1.17`` like ``Ice`` or ``Ocean``\"\"\"",
"\"Zombie\", \"Animal\", \"Skeleton\", \"Spider\", \"Silverfish\",): return DungeonType.REMOVED elif self.name in",
"of standard dungeons like ``Corrupted Decrepit Sewers`` or ``Corrupted Sand-Swept",
"@property def completed(self) -> int: \"\"\"Total runs completed by the",
"runs are not counted.\"\"\" return self._attributes.get(\"completed\", 0) def __repr__(self) ->",
"Factory``.\"\"\" return self._attributes.get(\"name\", \"\") @property def type(self) -> DungeonType: \"\"\"Type",
"elif self.name in ( \"Decrepit Sewers\", \"Infested Pit\", \"Ice Barrows\",",
"int: \"\"\"Total runs completed by the player. Failed runs are",
"like ``Galleon's Graveyard`` or ``Fallen Factory``\"\"\" CORRUPTED = \"CORRUPTED\" \"\"\"Harder",
"``Galleon's Graveyard`` or ``Fallen Factory``.\"\"\" return self._attributes.get(\"name\", \"\") @property def",
"def name(self) -> str: \"\"\"Name of the dungeon like ``Decrepit",
"str: \"\"\"Name of the dungeon like ``Decrepit Sewers``, ``Galleon's Graveyard``",
"like ``Skeleton`` or ``Spider``\"\"\" REMOVED_MINI = \"REMOVED_MINI\" \"\"\"Minidungeons that were",
"DungeonType.CORRUPTED elif self.name in ( \"Zombie\", \"Animal\", \"Skeleton\", \"Spider\", \"Silverfish\",):",
"Pit\", \"Ice Barrows\", \"Lost Sanctuary\", \"Sand-Swept Tomb\", \"Underworld Crypt\", \"Undergrowth",
"self._attributes.get(\"completed\", 0) def __repr__(self) -> str: return f\"<Dungeon name={self.name!r} completed={self.completed}>\"",
"if self.name.startswith(\"Corrupted\"): return DungeonType.CORRUPTED elif self.name in ( \"Zombie\", \"Animal\",",
"\"CORRUPTED\" \"\"\"Harder variant of standard dungeons like ``Corrupted Decrepit Sewers``",
"Enum class DungeonType(Enum): REMOVED = \"REMOVED\" \"\"\"Dungeons that were removed",
"by a :py:class:`Player`\"\"\" @property def name(self) -> str: \"\"\"Name of",
"Sewers\", \"Infested Pit\", \"Ice Barrows\", \"Lost Sanctuary\", \"Sand-Swept Tomb\", \"Underworld",
"or ``Corrupted Sand-Swept Tomb``\"\"\" class Dungeon(CorkusBase): \"\"\"Represents a `Dungeon <https://wynncraft.fandom.com/wiki/Dungeons>`_",
"a :py:class:`Player`\"\"\" @property def name(self) -> str: \"\"\"Name of the",
"\"Galleon's Graveyard\", \"Fallen Factory\"): return DungeonType.STANDARD else: raise ValueError(f\"Invalid dungeon:",
"\"\") @property def type(self) -> DungeonType: \"\"\"Type of the dungeon.\"\"\"",
"\"\"\"Name of the dungeon like ``Decrepit Sewers``, ``Galleon's Graveyard`` or",
"Failed runs are not counted.\"\"\" return self._attributes.get(\"completed\", 0) def __repr__(self)",
"the player. Failed runs are not counted.\"\"\" return self._attributes.get(\"completed\", 0)",
"\"\"\"Represents a `Dungeon <https://wynncraft.fandom.com/wiki/Dungeons>`_ completed by a :py:class:`Player`\"\"\" @property def",
"ValueError(f\"Invalid dungeon: {self.name}\") @property def completed(self) -> int: \"\"\"Total runs",
"``Fallen Factory``\"\"\" CORRUPTED = \"CORRUPTED\" \"\"\"Harder variant of standard dungeons",
"= \"CORRUPTED\" \"\"\"Harder variant of standard dungeons like ``Corrupted Decrepit",
"self.name in ( \"Decrepit Sewers\", \"Infested Pit\", \"Ice Barrows\", \"Lost",
"-> str: \"\"\"Name of the dungeon like ``Decrepit Sewers``, ``Galleon's",
"variant of standard dungeons like ``Corrupted Decrepit Sewers`` or ``Corrupted",
"\"Undergrowth Ruins\", \"Eldritch Outlook\", \"Galleon's Graveyard\", \"Fallen Factory\"): return DungeonType.STANDARD",
"not counted.\"\"\" return self._attributes.get(\"completed\", 0) def __repr__(self) -> str: return",
"``1.14.1`` like ``Skeleton`` or ``Spider``\"\"\" REMOVED_MINI = \"REMOVED_MINI\" \"\"\"Minidungeons that",
"are not counted.\"\"\" return self._attributes.get(\"completed\", 0) def __repr__(self) -> str:",
"``Decrepit Sewers``, ``Galleon's Graveyard`` or ``Fallen Factory``.\"\"\" return self._attributes.get(\"name\", \"\")",
"DungeonType.STANDARD else: raise ValueError(f\"Invalid dungeon: {self.name}\") @property def completed(self) ->",
"were reworked in version ``1.17`` like ``Ice`` or ``Ocean``\"\"\" STANDARD",
"completed by a :py:class:`Player`\"\"\" @property def name(self) -> str: \"\"\"Name",
"import annotations from .base import CorkusBase from enum import Enum",
"by the player. Failed runs are not counted.\"\"\" return self._attributes.get(\"completed\",",
"\"STANDARD\" \"\"\"Generic dungeons like ``Galleon's Graveyard`` or ``Fallen Factory``\"\"\" CORRUPTED",
"Factory``\"\"\" CORRUPTED = \"CORRUPTED\" \"\"\"Harder variant of standard dungeons like",
"`Dungeon <https://wynncraft.fandom.com/wiki/Dungeons>`_ completed by a :py:class:`Player`\"\"\" @property def name(self) ->",
"REMOVED_MINI = \"REMOVED_MINI\" \"\"\"Minidungeons that were reworked in version ``1.17``",
"the dungeon like ``Decrepit Sewers``, ``Galleon's Graveyard`` or ``Fallen Factory``.\"\"\"",
"Factory\"): return DungeonType.STANDARD else: raise ValueError(f\"Invalid dungeon: {self.name}\") @property def",
".base import CorkusBase from enum import Enum class DungeonType(Enum): REMOVED",
"or ``Spider``\"\"\" REMOVED_MINI = \"REMOVED_MINI\" \"\"\"Minidungeons that were reworked in",
"self.name.startswith(\"Corrupted\"): return DungeonType.CORRUPTED elif self.name in ( \"Zombie\", \"Animal\", \"Skeleton\",",
"game in version ``1.14.1`` like ``Skeleton`` or ``Spider``\"\"\" REMOVED_MINI =",
"\"Underworld Crypt\", \"Undergrowth Ruins\", \"Eldritch Outlook\", \"Galleon's Graveyard\", \"Fallen Factory\"):",
"dungeons like ``Corrupted Decrepit Sewers`` or ``Corrupted Sand-Swept Tomb``\"\"\" class",
"elif self.name in ( \"Zombie\", \"Animal\", \"Skeleton\", \"Spider\", \"Silverfish\",): return",
"from __future__ import annotations from .base import CorkusBase from enum",
"REMOVED = \"REMOVED\" \"\"\"Dungeons that were removed from the game",
"\"\"\"Minidungeons that were reworked in version ``1.17`` like ``Ice`` or",
"-> int: \"\"\"Total runs completed by the player. Failed runs",
"were removed from the game in version ``1.14.1`` like ``Skeleton``",
"self.name in ( \"Zombie\", \"Animal\", \"Skeleton\", \"Spider\", \"Silverfish\",): return DungeonType.REMOVED",
"-> DungeonType: \"\"\"Type of the dungeon.\"\"\" if self.name.startswith(\"Corrupted\"): return DungeonType.CORRUPTED",
"\"Ice\", \"Ocean\"): return DungeonType.REMOVED_MINI elif self.name in ( \"Decrepit Sewers\",",
"completed(self) -> int: \"\"\"Total runs completed by the player. Failed",
"Sewers``, ``Galleon's Graveyard`` or ``Fallen Factory``.\"\"\" return self._attributes.get(\"name\", \"\") @property",
"Crypt\", \"Undergrowth Ruins\", \"Eldritch Outlook\", \"Galleon's Graveyard\", \"Fallen Factory\"): return",
"\"\"\"Dungeons that were removed from the game in version ``1.14.1``",
"``Skeleton`` or ``Spider``\"\"\" REMOVED_MINI = \"REMOVED_MINI\" \"\"\"Minidungeons that were reworked",
"\"REMOVED_MINI\" \"\"\"Minidungeons that were reworked in version ``1.17`` like ``Ice``",
"= \"STANDARD\" \"\"\"Generic dungeons like ``Galleon's Graveyard`` or ``Fallen Factory``\"\"\"",
"annotations from .base import CorkusBase from enum import Enum class",
"else: raise ValueError(f\"Invalid dungeon: {self.name}\") @property def completed(self) -> int:",
"\"\"\"Type of the dungeon.\"\"\" if self.name.startswith(\"Corrupted\"): return DungeonType.CORRUPTED elif self.name",
"``Spider``\"\"\" REMOVED_MINI = \"REMOVED_MINI\" \"\"\"Minidungeons that were reworked in version",
"( \"Jungle\", \"Ice\", \"Ocean\"): return DungeonType.REMOVED_MINI elif self.name in (",
"Sanctuary\", \"Sand-Swept Tomb\", \"Underworld Crypt\", \"Undergrowth Ruins\", \"Eldritch Outlook\", \"Galleon's",
"@property def type(self) -> DungeonType: \"\"\"Type of the dungeon.\"\"\" if",
"player. Failed runs are not counted.\"\"\" return self._attributes.get(\"completed\", 0) def",
"or ``Ocean``\"\"\" STANDARD = \"STANDARD\" \"\"\"Generic dungeons like ``Galleon's Graveyard``",
"in version ``1.17`` like ``Ice`` or ``Ocean``\"\"\" STANDARD = \"STANDARD\"",
"\"Lost Sanctuary\", \"Sand-Swept Tomb\", \"Underworld Crypt\", \"Undergrowth Ruins\", \"Eldritch Outlook\",",
"\"Jungle\", \"Ice\", \"Ocean\"): return DungeonType.REMOVED_MINI elif self.name in ( \"Decrepit",
"version ``1.17`` like ``Ice`` or ``Ocean``\"\"\" STANDARD = \"STANDARD\" \"\"\"Generic",
"of the dungeon like ``Decrepit Sewers``, ``Galleon's Graveyard`` or ``Fallen",
"Ruins\", \"Eldritch Outlook\", \"Galleon's Graveyard\", \"Fallen Factory\"): return DungeonType.STANDARD else:",
"return self._attributes.get(\"completed\", 0) def __repr__(self) -> str: return f\"<Dungeon name={self.name!r}",
"raise ValueError(f\"Invalid dungeon: {self.name}\") @property def completed(self) -> int: \"\"\"Total",
"import Enum class DungeonType(Enum): REMOVED = \"REMOVED\" \"\"\"Dungeons that were",
"``Corrupted Sand-Swept Tomb``\"\"\" class Dungeon(CorkusBase): \"\"\"Represents a `Dungeon <https://wynncraft.fandom.com/wiki/Dungeons>`_ completed",
"version ``1.14.1`` like ``Skeleton`` or ``Spider``\"\"\" REMOVED_MINI = \"REMOVED_MINI\" \"\"\"Minidungeons",
"``Fallen Factory``.\"\"\" return self._attributes.get(\"name\", \"\") @property def type(self) -> DungeonType:",
"\"Fallen Factory\"): return DungeonType.STANDARD else: raise ValueError(f\"Invalid dungeon: {self.name}\") @property",
"a `Dungeon <https://wynncraft.fandom.com/wiki/Dungeons>`_ completed by a :py:class:`Player`\"\"\" @property def name(self)",
"import CorkusBase from enum import Enum class DungeonType(Enum): REMOVED =",
"\"Sand-Swept Tomb\", \"Underworld Crypt\", \"Undergrowth Ruins\", \"Eldritch Outlook\", \"Galleon's Graveyard\",",
"@property def name(self) -> str: \"\"\"Name of the dungeon like",
"\"\"\"Total runs completed by the player. Failed runs are not",
"DungeonType.REMOVED_MINI elif self.name in ( \"Decrepit Sewers\", \"Infested Pit\", \"Ice",
"return self._attributes.get(\"name\", \"\") @property def type(self) -> DungeonType: \"\"\"Type of",
"in ( \"Decrepit Sewers\", \"Infested Pit\", \"Ice Barrows\", \"Lost Sanctuary\",",
"\"REMOVED\" \"\"\"Dungeons that were removed from the game in version"
] |
[
"class Brisk: def __init__(self, thresh=60, octaves=4): self.thresh = thresh self.octaves",
"self.thresh = thresh self.octaves = octaves self.descriptor_extractor = pybrisk.create() def",
"img, self.thresh, self.octaves) def compute(self, img, keypoints): return pybrisk.compute(self.descriptor_extractor, img,",
"def detect(self, img): return pybrisk.detect(self.descriptor_extractor, img, self.thresh, self.octaves) def compute(self,",
"pybrisk.create() def __del__(self): pybrisk.destroy(self.descriptor_extractor) def detect(self, img): return pybrisk.detect(self.descriptor_extractor, img,",
"__init__(self, thresh=60, octaves=4): self.thresh = thresh self.octaves = octaves self.descriptor_extractor",
"= pybrisk.create() def __del__(self): pybrisk.destroy(self.descriptor_extractor) def detect(self, img): return pybrisk.detect(self.descriptor_extractor,",
"thresh=60, octaves=4): self.thresh = thresh self.octaves = octaves self.descriptor_extractor =",
"img): return pybrisk.detect(self.descriptor_extractor, img, self.thresh, self.octaves) def compute(self, img, keypoints):",
"pybrisk.detect(self.descriptor_extractor, img, self.thresh, self.octaves) def compute(self, img, keypoints): return pybrisk.compute(self.descriptor_extractor,",
"self.descriptor_extractor = pybrisk.create() def __del__(self): pybrisk.destroy(self.descriptor_extractor) def detect(self, img): return",
"octaves=4): self.thresh = thresh self.octaves = octaves self.descriptor_extractor = pybrisk.create()",
"def __init__(self, thresh=60, octaves=4): self.thresh = thresh self.octaves = octaves",
"def __del__(self): pybrisk.destroy(self.descriptor_extractor) def detect(self, img): return pybrisk.detect(self.descriptor_extractor, img, self.thresh,",
"= octaves self.descriptor_extractor = pybrisk.create() def __del__(self): pybrisk.destroy(self.descriptor_extractor) def detect(self,",
"Brisk: def __init__(self, thresh=60, octaves=4): self.thresh = thresh self.octaves =",
"self.thresh, self.octaves) def compute(self, img, keypoints): return pybrisk.compute(self.descriptor_extractor, img, keypoints)",
"__del__(self): pybrisk.destroy(self.descriptor_extractor) def detect(self, img): return pybrisk.detect(self.descriptor_extractor, img, self.thresh, self.octaves)",
"= thresh self.octaves = octaves self.descriptor_extractor = pybrisk.create() def __del__(self):",
"return pybrisk.detect(self.descriptor_extractor, img, self.thresh, self.octaves) def compute(self, img, keypoints): return",
"thresh self.octaves = octaves self.descriptor_extractor = pybrisk.create() def __del__(self): pybrisk.destroy(self.descriptor_extractor)",
"<filename>src/brisk.py import pybrisk class Brisk: def __init__(self, thresh=60, octaves=4): self.thresh",
"self.octaves = octaves self.descriptor_extractor = pybrisk.create() def __del__(self): pybrisk.destroy(self.descriptor_extractor) def",
"pybrisk class Brisk: def __init__(self, thresh=60, octaves=4): self.thresh = thresh",
"octaves self.descriptor_extractor = pybrisk.create() def __del__(self): pybrisk.destroy(self.descriptor_extractor) def detect(self, img):",
"pybrisk.destroy(self.descriptor_extractor) def detect(self, img): return pybrisk.detect(self.descriptor_extractor, img, self.thresh, self.octaves) def",
"import pybrisk class Brisk: def __init__(self, thresh=60, octaves=4): self.thresh =",
"detect(self, img): return pybrisk.detect(self.descriptor_extractor, img, self.thresh, self.octaves) def compute(self, img,"
] |
[
"def set_outlet_name(self, name, outlet_id): if outlet_id < len(self.outlets): self.outlets[outlet_id].name =",
"to {1} state'.format(outlet_id, outlet_state)) command = bytearray([STARTING_OUTLET_COMMAND + (outlet_id <<",
"in p.description] self.serial_interface = serial.Serial(ports[0], SERIAL_BAUD_RATE, timeout=SERIAL_TIMEOUT) except IndexError: send_ifttt_log(__name__,",
"None def set_outlet_name(self, name, outlet_id): if outlet_id < len(self.outlets): self.outlets[outlet_id].name",
"outlet_id < len(self.outlets): self.outlets[outlet_id].state = 1 self._send_outlet_command(outlet_id, self.outlets[outlet_id].state) def turn_off_outlet(self,",
"could be upon!') def _send_outlet_command(self, outlet_id, outlet_state): try: print('Changing outlet",
"serial ports could be upon!') def _send_outlet_command(self, outlet_id, outlet_state): try:",
"if outlet_id < len(self.outlets): self.outlets[outlet_id].state = 1 self._send_outlet_command(outlet_id, self.outlets[outlet_id].state) def",
"self.serial_interface_string in p.description] self.serial_interface = serial.Serial(ports[0], SERIAL_BAUD_RATE, timeout=SERIAL_TIMEOUT) except IndexError:",
"= name def set_serial_interface(self, serial_interface_string): try: print('Setting serial interface with",
"serial interface with description: {}'.format(serial_interface_string)) self.serial_interface_string = serial_interface_string ports =",
"try: print('Setting serial interface with description: {}'.format(serial_interface_string)) self.serial_interface_string = serial_interface_string",
"= _outlet_interface.set_serial_interface toggle_outlet = _outlet_interface.toggle_outlet turn_on_outlet = _outlet_interface.turn_on_outlet turn_off_outlet =",
"outlet_id < len(self.outlets): self.outlets[outlet_id].name = name def set_serial_interface(self, serial_interface_string): try:",
"= name class _OutletInterface: def __init__(self): self.outlets = [_Outlet('Outlet 0'),",
"serial.tools.list_ports from hale_hub.constants import STARTING_OUTLET_COMMAND, SERIAL_BAUD_RATE, SERIAL_TIMEOUT from hale_hub.ifttt_logger import",
"ports could be upon!') def _send_outlet_command(self, outlet_id, outlet_state): try: print('Changing",
"outlet_id): if outlet_id < len(self.outlets): self.outlets[outlet_id].state = 1 self._send_outlet_command(outlet_id, self.outlets[outlet_id].state)",
"command = bytearray([STARTING_OUTLET_COMMAND + (outlet_id << 1) + outlet_state]) print('Writing",
"1'), _Outlet('Outlet 2')] self.serial_interface = None self.serial_interface_string = None def",
"_OutletInterface() set_outlet_serial_interface = _outlet_interface.set_serial_interface toggle_outlet = _outlet_interface.toggle_outlet turn_on_outlet = _outlet_interface.turn_on_outlet",
"_Outlet('Outlet 1'), _Outlet('Outlet 2')] self.serial_interface = None self.serial_interface_string = None",
"import STARTING_OUTLET_COMMAND, SERIAL_BAUD_RATE, SERIAL_TIMEOUT from hale_hub.ifttt_logger import send_ifttt_log class _Outlet:",
"p in serial.tools.list_ports.comports() if self.serial_interface_string in p.description] self.serial_interface = serial.Serial(ports[0],",
"send_ifttt_log(__name__, 'No serial bytes could be written') if self.serial_interface.is_open(): self.serial_interface.close()",
"serial.Serial(ports[0], SERIAL_BAUD_RATE, timeout=SERIAL_TIMEOUT) except IndexError: send_ifttt_log(__name__, 'No serial ports could",
"serial_interface_string ports = [p.device for p in serial.tools.list_ports.comports() if self.serial_interface_string",
"= _outlet_interface.turn_on_outlet turn_off_outlet = _outlet_interface.turn_off_outlet get_outlets = _outlet_interface.get_outlets set_outlet_name =",
"self.set_serial_interface(self.serial_interface_string) def toggle_outlet(self, outlet_id): if outlet_id < len(self.outlets): self.outlets[outlet_id].state ^=",
"{0} to {1} state'.format(outlet_id, outlet_state)) command = bytearray([STARTING_OUTLET_COMMAND + (outlet_id",
"= [_Outlet('Outlet 0'), _Outlet('Outlet 1'), _Outlet('Outlet 2')] self.serial_interface = None",
"'No serial bytes could be written') if self.serial_interface.is_open(): self.serial_interface.close() self.set_serial_interface(self.serial_interface_string)",
"1) + outlet_state]) print('Writing {0} to serial'.format(command)) self.serial_interface.write(command) except (serial.SerialException,",
"= [p.device for p in serial.tools.list_ports.comports() if self.serial_interface_string in p.description]",
"= 0 self.name = name class _OutletInterface: def __init__(self): self.outlets",
"= serial.Serial(ports[0], SERIAL_BAUD_RATE, timeout=SERIAL_TIMEOUT) except IndexError: send_ifttt_log(__name__, 'No serial ports",
"self.serial_interface.is_open(): self.serial_interface.close() self.set_serial_interface(self.serial_interface_string) def toggle_outlet(self, outlet_id): if outlet_id < len(self.outlets):",
"turn_off_outlet(self, outlet_id): if outlet_id < len(self.outlets): self.outlets[outlet_id].state = 0 self._send_outlet_command(outlet_id,",
"serial_interface_string): try: print('Setting serial interface with description: {}'.format(serial_interface_string)) self.serial_interface_string =",
"except (serial.SerialException, AttributeError): send_ifttt_log(__name__, 'No serial bytes could be written')",
"< len(self.outlets): self.outlets[outlet_id].state ^= 1 self._send_outlet_command(outlet_id, self.outlets[outlet_id].state) def turn_on_outlet(self, outlet_id):",
"def get_outlets(self): return self.outlets _outlet_interface = _OutletInterface() set_outlet_serial_interface = _outlet_interface.set_serial_interface",
"None self.serial_interface_string = None def set_outlet_name(self, name, outlet_id): if outlet_id",
"set_serial_interface(self, serial_interface_string): try: print('Setting serial interface with description: {}'.format(serial_interface_string)) self.serial_interface_string",
"self.outlets _outlet_interface = _OutletInterface() set_outlet_serial_interface = _outlet_interface.set_serial_interface toggle_outlet = _outlet_interface.toggle_outlet",
"AttributeError): send_ifttt_log(__name__, 'No serial bytes could be written') if self.serial_interface.is_open():",
"state'.format(outlet_id, outlet_state)) command = bytearray([STARTING_OUTLET_COMMAND + (outlet_id << 1) +",
"import serial.tools.list_ports from hale_hub.constants import STARTING_OUTLET_COMMAND, SERIAL_BAUD_RATE, SERIAL_TIMEOUT from hale_hub.ifttt_logger",
"self.outlets = [_Outlet('Outlet 0'), _Outlet('Outlet 1'), _Outlet('Outlet 2')] self.serial_interface =",
"def _send_outlet_command(self, outlet_id, outlet_state): try: print('Changing outlet {0} to {1}",
"return self.outlets _outlet_interface = _OutletInterface() set_outlet_serial_interface = _outlet_interface.set_serial_interface toggle_outlet =",
"upon!') def _send_outlet_command(self, outlet_id, outlet_state): try: print('Changing outlet {0} to",
"from hale_hub.ifttt_logger import send_ifttt_log class _Outlet: def __init__(self, name): self.state",
"= 0 self._send_outlet_command(outlet_id, self.outlets[outlet_id].state) def get_outlets(self): return self.outlets _outlet_interface =",
"self.outlets[outlet_id].state) def get_outlets(self): return self.outlets _outlet_interface = _OutletInterface() set_outlet_serial_interface =",
"len(self.outlets): self.outlets[outlet_id].state = 1 self._send_outlet_command(outlet_id, self.outlets[outlet_id].state) def turn_off_outlet(self, outlet_id): if",
"with description: {}'.format(serial_interface_string)) self.serial_interface_string = serial_interface_string ports = [p.device for",
"+ outlet_state]) print('Writing {0} to serial'.format(command)) self.serial_interface.write(command) except (serial.SerialException, AttributeError):",
"len(self.outlets): self.outlets[outlet_id].name = name def set_serial_interface(self, serial_interface_string): try: print('Setting serial",
"self.serial_interface = serial.Serial(ports[0], SERIAL_BAUD_RATE, timeout=SERIAL_TIMEOUT) except IndexError: send_ifttt_log(__name__, 'No serial",
"timeout=SERIAL_TIMEOUT) except IndexError: send_ifttt_log(__name__, 'No serial ports could be upon!')",
"import serial import serial.tools.list_ports from hale_hub.constants import STARTING_OUTLET_COMMAND, SERIAL_BAUD_RATE, SERIAL_TIMEOUT",
"+ (outlet_id << 1) + outlet_state]) print('Writing {0} to serial'.format(command))",
"if self.serial_interface.is_open(): self.serial_interface.close() self.set_serial_interface(self.serial_interface_string) def toggle_outlet(self, outlet_id): if outlet_id <",
"outlet_id < len(self.outlets): self.outlets[outlet_id].state ^= 1 self._send_outlet_command(outlet_id, self.outlets[outlet_id].state) def turn_on_outlet(self,",
"outlet_state]) print('Writing {0} to serial'.format(command)) self.serial_interface.write(command) except (serial.SerialException, AttributeError): send_ifttt_log(__name__,",
"turn_on_outlet = _outlet_interface.turn_on_outlet turn_off_outlet = _outlet_interface.turn_off_outlet get_outlets = _outlet_interface.get_outlets set_outlet_name",
"SERIAL_TIMEOUT from hale_hub.ifttt_logger import send_ifttt_log class _Outlet: def __init__(self, name):",
"= None def set_outlet_name(self, name, outlet_id): if outlet_id < len(self.outlets):",
"def __init__(self, name): self.state = 0 self.name = name class",
"{0} to serial'.format(command)) self.serial_interface.write(command) except (serial.SerialException, AttributeError): send_ifttt_log(__name__, 'No serial",
"len(self.outlets): self.outlets[outlet_id].state ^= 1 self._send_outlet_command(outlet_id, self.outlets[outlet_id].state) def turn_on_outlet(self, outlet_id): if",
"bytearray([STARTING_OUTLET_COMMAND + (outlet_id << 1) + outlet_state]) print('Writing {0} to",
"< len(self.outlets): self.outlets[outlet_id].name = name def set_serial_interface(self, serial_interface_string): try: print('Setting",
"be written') if self.serial_interface.is_open(): self.serial_interface.close() self.set_serial_interface(self.serial_interface_string) def toggle_outlet(self, outlet_id): if",
"outlet_id): if outlet_id < len(self.outlets): self.outlets[outlet_id].state = 0 self._send_outlet_command(outlet_id, self.outlets[outlet_id].state)",
"name): self.state = 0 self.name = name class _OutletInterface: def",
"self.serial_interface_string = None def set_outlet_name(self, name, outlet_id): if outlet_id <",
"if outlet_id < len(self.outlets): self.outlets[outlet_id].name = name def set_serial_interface(self, serial_interface_string):",
"= _outlet_interface.toggle_outlet turn_on_outlet = _outlet_interface.turn_on_outlet turn_off_outlet = _outlet_interface.turn_off_outlet get_outlets =",
"self.outlets[outlet_id].state) def turn_off_outlet(self, outlet_id): if outlet_id < len(self.outlets): self.outlets[outlet_id].state =",
"self.outlets[outlet_id].state = 1 self._send_outlet_command(outlet_id, self.outlets[outlet_id].state) def turn_off_outlet(self, outlet_id): if outlet_id",
"1 self._send_outlet_command(outlet_id, self.outlets[outlet_id].state) def turn_off_outlet(self, outlet_id): if outlet_id < len(self.outlets):",
"^= 1 self._send_outlet_command(outlet_id, self.outlets[outlet_id].state) def turn_on_outlet(self, outlet_id): if outlet_id <",
"<< 1) + outlet_state]) print('Writing {0} to serial'.format(command)) self.serial_interface.write(command) except",
"toggle_outlet = _outlet_interface.toggle_outlet turn_on_outlet = _outlet_interface.turn_on_outlet turn_off_outlet = _outlet_interface.turn_off_outlet get_outlets",
"{1} state'.format(outlet_id, outlet_state)) command = bytearray([STARTING_OUTLET_COMMAND + (outlet_id << 1)",
"[p.device for p in serial.tools.list_ports.comports() if self.serial_interface_string in p.description] self.serial_interface",
"(outlet_id << 1) + outlet_state]) print('Writing {0} to serial'.format(command)) self.serial_interface.write(command)",
"STARTING_OUTLET_COMMAND, SERIAL_BAUD_RATE, SERIAL_TIMEOUT from hale_hub.ifttt_logger import send_ifttt_log class _Outlet: def",
"= 1 self._send_outlet_command(outlet_id, self.outlets[outlet_id].state) def turn_off_outlet(self, outlet_id): if outlet_id <",
"from hale_hub.constants import STARTING_OUTLET_COMMAND, SERIAL_BAUD_RATE, SERIAL_TIMEOUT from hale_hub.ifttt_logger import send_ifttt_log",
"print('Changing outlet {0} to {1} state'.format(outlet_id, outlet_state)) command = bytearray([STARTING_OUTLET_COMMAND",
"get_outlets(self): return self.outlets _outlet_interface = _OutletInterface() set_outlet_serial_interface = _outlet_interface.set_serial_interface toggle_outlet",
"serial import serial.tools.list_ports from hale_hub.constants import STARTING_OUTLET_COMMAND, SERIAL_BAUD_RATE, SERIAL_TIMEOUT from",
"hale_hub.ifttt_logger import send_ifttt_log class _Outlet: def __init__(self, name): self.state =",
"set_outlet_name(self, name, outlet_id): if outlet_id < len(self.outlets): self.outlets[outlet_id].name = name",
"self.outlets[outlet_id].state) def turn_on_outlet(self, outlet_id): if outlet_id < len(self.outlets): self.outlets[outlet_id].state =",
"outlet_id < len(self.outlets): self.outlets[outlet_id].state = 0 self._send_outlet_command(outlet_id, self.outlets[outlet_id].state) def get_outlets(self):",
"self.serial_interface.close() self.set_serial_interface(self.serial_interface_string) def toggle_outlet(self, outlet_id): if outlet_id < len(self.outlets): self.outlets[outlet_id].state",
"except IndexError: send_ifttt_log(__name__, 'No serial ports could be upon!') def",
"_outlet_interface.toggle_outlet turn_on_outlet = _outlet_interface.turn_on_outlet turn_off_outlet = _outlet_interface.turn_off_outlet get_outlets = _outlet_interface.get_outlets",
"in serial.tools.list_ports.comports() if self.serial_interface_string in p.description] self.serial_interface = serial.Serial(ports[0], SERIAL_BAUD_RATE,",
"print('Writing {0} to serial'.format(command)) self.serial_interface.write(command) except (serial.SerialException, AttributeError): send_ifttt_log(__name__, 'No",
"import send_ifttt_log class _Outlet: def __init__(self, name): self.state = 0",
"= bytearray([STARTING_OUTLET_COMMAND + (outlet_id << 1) + outlet_state]) print('Writing {0}",
"_send_outlet_command(self, outlet_id, outlet_state): try: print('Changing outlet {0} to {1} state'.format(outlet_id,",
"turn_on_outlet(self, outlet_id): if outlet_id < len(self.outlets): self.outlets[outlet_id].state = 1 self._send_outlet_command(outlet_id,",
"SERIAL_BAUD_RATE, timeout=SERIAL_TIMEOUT) except IndexError: send_ifttt_log(__name__, 'No serial ports could be",
"def set_serial_interface(self, serial_interface_string): try: print('Setting serial interface with description: {}'.format(serial_interface_string))",
"set_outlet_serial_interface = _outlet_interface.set_serial_interface toggle_outlet = _outlet_interface.toggle_outlet turn_on_outlet = _outlet_interface.turn_on_outlet turn_off_outlet",
"interface with description: {}'.format(serial_interface_string)) self.serial_interface_string = serial_interface_string ports = [p.device",
"self.outlets[outlet_id].state = 0 self._send_outlet_command(outlet_id, self.outlets[outlet_id].state) def get_outlets(self): return self.outlets _outlet_interface",
"def __init__(self): self.outlets = [_Outlet('Outlet 0'), _Outlet('Outlet 1'), _Outlet('Outlet 2')]",
"written') if self.serial_interface.is_open(): self.serial_interface.close() self.set_serial_interface(self.serial_interface_string) def toggle_outlet(self, outlet_id): if outlet_id",
"def turn_on_outlet(self, outlet_id): if outlet_id < len(self.outlets): self.outlets[outlet_id].state = 1",
"p.description] self.serial_interface = serial.Serial(ports[0], SERIAL_BAUD_RATE, timeout=SERIAL_TIMEOUT) except IndexError: send_ifttt_log(__name__, 'No",
"IndexError: send_ifttt_log(__name__, 'No serial ports could be upon!') def _send_outlet_command(self,",
"_outlet_interface = _OutletInterface() set_outlet_serial_interface = _outlet_interface.set_serial_interface toggle_outlet = _outlet_interface.toggle_outlet turn_on_outlet",
"send_ifttt_log class _Outlet: def __init__(self, name): self.state = 0 self.name",
"def turn_off_outlet(self, outlet_id): if outlet_id < len(self.outlets): self.outlets[outlet_id].state = 0",
"< len(self.outlets): self.outlets[outlet_id].state = 0 self._send_outlet_command(outlet_id, self.outlets[outlet_id].state) def get_outlets(self): return",
"toggle_outlet(self, outlet_id): if outlet_id < len(self.outlets): self.outlets[outlet_id].state ^= 1 self._send_outlet_command(outlet_id,",
"_Outlet: def __init__(self, name): self.state = 0 self.name = name",
"len(self.outlets): self.outlets[outlet_id].state = 0 self._send_outlet_command(outlet_id, self.outlets[outlet_id].state) def get_outlets(self): return self.outlets",
"= serial_interface_string ports = [p.device for p in serial.tools.list_ports.comports() if",
"be upon!') def _send_outlet_command(self, outlet_id, outlet_state): try: print('Changing outlet {0}",
"self.serial_interface.write(command) except (serial.SerialException, AttributeError): send_ifttt_log(__name__, 'No serial bytes could be",
"2')] self.serial_interface = None self.serial_interface_string = None def set_outlet_name(self, name,",
"self.outlets[outlet_id].name = name def set_serial_interface(self, serial_interface_string): try: print('Setting serial interface",
"description: {}'.format(serial_interface_string)) self.serial_interface_string = serial_interface_string ports = [p.device for p",
"0'), _Outlet('Outlet 1'), _Outlet('Outlet 2')] self.serial_interface = None self.serial_interface_string =",
"serial'.format(command)) self.serial_interface.write(command) except (serial.SerialException, AttributeError): send_ifttt_log(__name__, 'No serial bytes could",
"_outlet_interface.set_serial_interface toggle_outlet = _outlet_interface.toggle_outlet turn_on_outlet = _outlet_interface.turn_on_outlet turn_off_outlet = _outlet_interface.turn_off_outlet",
"def toggle_outlet(self, outlet_id): if outlet_id < len(self.outlets): self.outlets[outlet_id].state ^= 1",
"outlet {0} to {1} state'.format(outlet_id, outlet_state)) command = bytearray([STARTING_OUTLET_COMMAND +",
"name, outlet_id): if outlet_id < len(self.outlets): self.outlets[outlet_id].name = name def",
"if outlet_id < len(self.outlets): self.outlets[outlet_id].state ^= 1 self._send_outlet_command(outlet_id, self.outlets[outlet_id].state) def",
"ports = [p.device for p in serial.tools.list_ports.comports() if self.serial_interface_string in",
"outlet_state): try: print('Changing outlet {0} to {1} state'.format(outlet_id, outlet_state)) command",
"self.serial_interface_string = serial_interface_string ports = [p.device for p in serial.tools.list_ports.comports()",
"self._send_outlet_command(outlet_id, self.outlets[outlet_id].state) def turn_on_outlet(self, outlet_id): if outlet_id < len(self.outlets): self.outlets[outlet_id].state",
"serial.tools.list_ports.comports() if self.serial_interface_string in p.description] self.serial_interface = serial.Serial(ports[0], SERIAL_BAUD_RATE, timeout=SERIAL_TIMEOUT)",
"self.state = 0 self.name = name class _OutletInterface: def __init__(self):",
"self._send_outlet_command(outlet_id, self.outlets[outlet_id].state) def get_outlets(self): return self.outlets _outlet_interface = _OutletInterface() set_outlet_serial_interface",
"self.name = name class _OutletInterface: def __init__(self): self.outlets = [_Outlet('Outlet",
"_outlet_interface.turn_on_outlet turn_off_outlet = _outlet_interface.turn_off_outlet get_outlets = _outlet_interface.get_outlets set_outlet_name = _outlet_interface.set_outlet_name",
"outlet_id): if outlet_id < len(self.outlets): self.outlets[outlet_id].name = name def set_serial_interface(self,",
"bytes could be written') if self.serial_interface.is_open(): self.serial_interface.close() self.set_serial_interface(self.serial_interface_string) def toggle_outlet(self,",
"SERIAL_BAUD_RATE, SERIAL_TIMEOUT from hale_hub.ifttt_logger import send_ifttt_log class _Outlet: def __init__(self,",
"__init__(self): self.outlets = [_Outlet('Outlet 0'), _Outlet('Outlet 1'), _Outlet('Outlet 2')] self.serial_interface",
"_Outlet('Outlet 2')] self.serial_interface = None self.serial_interface_string = None def set_outlet_name(self,",
"1 self._send_outlet_command(outlet_id, self.outlets[outlet_id].state) def turn_on_outlet(self, outlet_id): if outlet_id < len(self.outlets):",
"self.outlets[outlet_id].state ^= 1 self._send_outlet_command(outlet_id, self.outlets[outlet_id].state) def turn_on_outlet(self, outlet_id): if outlet_id",
"outlet_id, outlet_state): try: print('Changing outlet {0} to {1} state'.format(outlet_id, outlet_state))",
"try: print('Changing outlet {0} to {1} state'.format(outlet_id, outlet_state)) command =",
"__init__(self, name): self.state = 0 self.name = name class _OutletInterface:",
"to serial'.format(command)) self.serial_interface.write(command) except (serial.SerialException, AttributeError): send_ifttt_log(__name__, 'No serial bytes",
"self._send_outlet_command(outlet_id, self.outlets[outlet_id].state) def turn_off_outlet(self, outlet_id): if outlet_id < len(self.outlets): self.outlets[outlet_id].state",
"'No serial ports could be upon!') def _send_outlet_command(self, outlet_id, outlet_state):",
"outlet_id): if outlet_id < len(self.outlets): self.outlets[outlet_id].state ^= 1 self._send_outlet_command(outlet_id, self.outlets[outlet_id].state)",
"[_Outlet('Outlet 0'), _Outlet('Outlet 1'), _Outlet('Outlet 2')] self.serial_interface = None self.serial_interface_string",
"= _OutletInterface() set_outlet_serial_interface = _outlet_interface.set_serial_interface toggle_outlet = _outlet_interface.toggle_outlet turn_on_outlet =",
"class _OutletInterface: def __init__(self): self.outlets = [_Outlet('Outlet 0'), _Outlet('Outlet 1'),",
"0 self.name = name class _OutletInterface: def __init__(self): self.outlets =",
"outlet_state)) command = bytearray([STARTING_OUTLET_COMMAND + (outlet_id << 1) + outlet_state])",
"(serial.SerialException, AttributeError): send_ifttt_log(__name__, 'No serial bytes could be written') if",
"_OutletInterface: def __init__(self): self.outlets = [_Outlet('Outlet 0'), _Outlet('Outlet 1'), _Outlet('Outlet",
"class _Outlet: def __init__(self, name): self.state = 0 self.name =",
"{}'.format(serial_interface_string)) self.serial_interface_string = serial_interface_string ports = [p.device for p in",
"for p in serial.tools.list_ports.comports() if self.serial_interface_string in p.description] self.serial_interface =",
"if self.serial_interface_string in p.description] self.serial_interface = serial.Serial(ports[0], SERIAL_BAUD_RATE, timeout=SERIAL_TIMEOUT) except",
"hale_hub.constants import STARTING_OUTLET_COMMAND, SERIAL_BAUD_RATE, SERIAL_TIMEOUT from hale_hub.ifttt_logger import send_ifttt_log class",
"send_ifttt_log(__name__, 'No serial ports could be upon!') def _send_outlet_command(self, outlet_id,",
"0 self._send_outlet_command(outlet_id, self.outlets[outlet_id].state) def get_outlets(self): return self.outlets _outlet_interface = _OutletInterface()",
"< len(self.outlets): self.outlets[outlet_id].state = 1 self._send_outlet_command(outlet_id, self.outlets[outlet_id].state) def turn_off_outlet(self, outlet_id):",
"if outlet_id < len(self.outlets): self.outlets[outlet_id].state = 0 self._send_outlet_command(outlet_id, self.outlets[outlet_id].state) def",
"= None self.serial_interface_string = None def set_outlet_name(self, name, outlet_id): if",
"self.serial_interface = None self.serial_interface_string = None def set_outlet_name(self, name, outlet_id):",
"name def set_serial_interface(self, serial_interface_string): try: print('Setting serial interface with description:",
"serial bytes could be written') if self.serial_interface.is_open(): self.serial_interface.close() self.set_serial_interface(self.serial_interface_string) def",
"print('Setting serial interface with description: {}'.format(serial_interface_string)) self.serial_interface_string = serial_interface_string ports",
"name class _OutletInterface: def __init__(self): self.outlets = [_Outlet('Outlet 0'), _Outlet('Outlet",
"could be written') if self.serial_interface.is_open(): self.serial_interface.close() self.set_serial_interface(self.serial_interface_string) def toggle_outlet(self, outlet_id):"
] |
[
"core_xyz_ref_nonan[0] p0 = core_xyz_tar_nonan[0] w0 = p0 - q0 #",
"core_xyz_ref_nonan[-1] - core_xyz_ref_nonan[0] core_vec_tar = core_xyz_tar_nonan[-1] - core_xyz_tar_nonan[0] # Obtain",
"a = np.dot(u, u) b = np.dot(u, v) c =",
"= core_xyz_ref_nonan[-1] - core_xyz_ref_nonan[0] core_vec_tar = core_xyz_tar_nonan[-1] - core_xyz_tar_nonan[0] #",
"= core_vec_tar # Math part... a = np.dot(u, u) b",
"helical core vectors... core_xyz_ref_nonan = remove_nan(core_xyz_ref) core_xyz_tar_nonan = remove_nan(core_xyz_tar) core_vec_ref",
"the following aspects of two helical cores. - Interhelical angle",
"b = np.dot(u, v) c = np.dot(v, v) d =",
"(a * e - b * d) / de #",
"/ b else: sc, tc = (b * e -",
"between the centers. - Interhelical angle (0-90 degree) ''' #",
"core_xyz_tar): ''' Measure the following aspects of two helical cores.",
"* e - b * d) / de # Calculate",
"ih_ang def calc_interangle(core_xyz_ref, core_xyz_tar): ''' Measure the following aspects of",
"core_xyz_tar_nonan[-1] - core_xyz_tar_nonan[0] # Obtain the starting point... q0 =",
"= np.linalg.norm(ih_dvec) # Obtain the helical core vectors... core_xyz_ref_nonan =",
"/ de, (a * e - b * d) /",
"degree) ''' # Obtain the helical core vectors... core_xyz_ref_nonan =",
"# Construct the interhelical distance vector... ih_dvec = center_tar -",
"python3 # -*- coding: utf-8 -*- import numpy as np",
"= np.dot(v, w0) de = a * c - b",
"remove_nan(core_xyz_ref) core_xyz_tar_nonan = remove_nan(core_xyz_tar) core_vec_ref = core_xyz_ref_nonan[-1] - core_xyz_ref_nonan[0] core_vec_tar",
"core_vec_ref / np.linalg.norm(core_vec_ref) core_vec_tar_unit = core_vec_tar / np.linalg.norm(core_vec_tar) ih_ang =",
"0: sc, tc = 0, d / b else: sc,",
"- Interhelical angle (0-90 degree) ''' # Obtain the centers...",
"Interhelical distance vector between the centers. - Interhelical angle (0-90",
"- center_ref # Calculate the length of interhelical distance vector...",
"np.dot(core_vec_ref_unit, core_vec_tar_unit) ) return ih_dvec, norm_ih_dvec, core_vec_ref_unit, core_vec_tar_unit, ih_ang def",
"# Obtain the starting point... q0 = core_xyz_ref_nonan[0] p0 =",
"Q is ref, P is tar. ''' # Obtain the",
"b else: sc, tc = (b * e - c",
"center_ref # Calculate the length of interhelical distance vector... norm_ih_dvec",
"Obtain the centers... center_ref = np.nanmean(core_xyz_ref, axis = 0) center_tar",
"xyzs[~np.isnan(xyzs).any(axis = 1)] def measure_twocores(core_xyz_ref, core_xyz_tar): ''' Measure the following",
"ih_dvec, norm_ih_dvec, core_vec_ref_unit, core_vec_tar_unit, ih_ang def calc_interangle(core_xyz_ref, core_xyz_tar): ''' Measure",
"== 0: sc, tc = 0, d / b else:",
"inter_angle = np.pi - inter_angle return inter_angle def calc_interdist(core_xyz_ref, core_xyz_tar):",
"np.linalg.norm(core_vec_ref) core_vec_tar_unit = core_vec_tar / np.linalg.norm(core_vec_tar) ih_ang = np.arccos( np.dot(core_vec_ref_unit,",
"numpy as np def remove_nan(xyzs): return xyzs[~np.isnan(xyzs).any(axis = 1)] def",
"= core_xyz_tar_nonan[-1] - core_xyz_tar_nonan[0] # Calculate the interhelical angle... core_vec_ref_unit",
"= remove_nan(core_xyz_tar) core_vec_ref = core_xyz_ref_nonan[-1] - core_xyz_ref_nonan[0] core_vec_tar = core_xyz_tar_nonan[-1]",
"core_vec_tar_unit = core_vec_tar / np.linalg.norm(core_vec_tar) inter_angle = np.arccos( np.dot(core_vec_ref_unit, core_vec_tar_unit)",
"- Interhelical distance vector between the centers. - Interhelical angle",
"norm_ih_dvec = np.linalg.norm(ih_dvec) # Obtain the helical core vectors... core_xyz_ref_nonan",
"ref, P is tar. ''' # Obtain the helical core",
"helical cores. - Interhelical distance vector between the centers. Refers",
"of interhelical distance vector... norm_ih_dvec = np.linalg.norm(ih_dvec) # Obtain the",
"core_vec_tar_unit) ) if inter_angle > np.pi / 2.0: inter_angle =",
"np.dot(u, w0) e = np.dot(v, w0) de = a *",
"interhelical distance vector... ih_dvec = center_tar - center_ref # Calculate",
"q0 = core_xyz_ref_nonan[0] p0 = core_xyz_tar_nonan[0] w0 = p0 -",
"import numpy as np def remove_nan(xyzs): return xyzs[~np.isnan(xyzs).any(axis = 1)]",
"is tar. ''' # Obtain the helical core vectors... core_xyz_ref_nonan",
"= center_tar - center_ref # Calculate the length of interhelical",
"core_vec_ref = core_xyz_ref_nonan[-1] - core_xyz_ref_nonan[0] core_vec_tar = core_xyz_tar_nonan[-1] - core_xyz_tar_nonan[0]",
"return inter_angle def calc_interdist(core_xyz_ref, core_xyz_tar): ''' Measure the following aspects",
"- core_xyz_ref_nonan[0] core_vec_tar = core_xyz_tar_nonan[-1] - core_xyz_tar_nonan[0] # Obtain the",
"np.linalg.norm(core_vec_ref) core_vec_tar_unit = core_vec_tar / np.linalg.norm(core_vec_tar) inter_angle = np.arccos( np.dot(core_vec_ref_unit,",
"tar. ''' # Obtain the helical core vectors... core_xyz_ref_nonan =",
"v = core_vec_ref u = core_vec_tar # Math part... a",
"= core_xyz_tar_nonan[0] w0 = p0 - q0 # Obtain the",
"ih_dvec = center_tar - center_ref # Calculate the length of",
"return ih_dvec, norm_ih_dvec, core_vec_ref_unit, core_vec_tar_unit, ih_ang def calc_interangle(core_xyz_ref, core_xyz_tar): '''",
"- Interhelical angle (0-90 degree) ''' # Obtain the helical",
"-*- import numpy as np def remove_nan(xyzs): return xyzs[~np.isnan(xyzs).any(axis =",
"core_xyz_tar_nonan[0] w0 = p0 - q0 # Obtain the directional",
"core_vec_tar / np.linalg.norm(core_vec_tar) ih_ang = np.arccos( np.dot(core_vec_ref_unit, core_vec_tar_unit) ) return",
"is ref, P is tar. ''' # Obtain the helical",
"d) / de # Calculate distance... wc = w0 +",
"q0 # Obtain the directional vector with magnitude... v =",
"/ np.linalg.norm(core_vec_tar) ih_ang = np.arccos( np.dot(core_vec_ref_unit, core_vec_tar_unit) ) return ih_dvec,",
"length of interhelical distance vector... norm_ih_dvec = np.linalg.norm(ih_dvec) # Obtain",
"center_tar - center_ref # Calculate the length of interhelical distance",
"c * d) / de, (a * e - b",
"w0) e = np.dot(v, w0) de = a * c",
"e - c * d) / de, (a * e",
"vectors... core_xyz_ref_nonan = remove_nan(core_xyz_ref) core_xyz_tar_nonan = remove_nan(core_xyz_tar) core_vec_ref = core_xyz_ref_nonan[-1]",
"distance vector between the centers. - Interhelical angle (0-90 degree)",
"= np.nanmean(core_xyz_tar, axis = 0) # Construct the interhelical distance",
"axis = 0) # Construct the interhelical distance vector... ih_dvec",
"the starting point... q0 = core_xyz_ref_nonan[0] p0 = core_xyz_tar_nonan[0] w0",
"u - tc * v inter_dist = np.linalg.norm(wc) return inter_dist",
"# Obtain the helical core vectors... core_xyz_ref_nonan = remove_nan(core_xyz_ref) core_xyz_tar_nonan",
"vector with magnitude... v = core_vec_ref u = core_vec_tar #",
"= w0 + sc * u - tc * v",
"= 0, d / b else: sc, tc = (b",
"distance vector... norm_ih_dvec = np.linalg.norm(ih_dvec) # Obtain the helical core",
"= remove_nan(core_xyz_ref) core_xyz_tar_nonan = remove_nan(core_xyz_tar) core_vec_ref = core_xyz_ref_nonan[-1] - core_xyz_ref_nonan[0]",
"/ np.linalg.norm(core_vec_tar) inter_angle = np.arccos( np.dot(core_vec_ref_unit, core_vec_tar_unit) ) if inter_angle",
"inter_angle = np.arccos( np.dot(core_vec_ref_unit, core_vec_tar_unit) ) if inter_angle > np.pi",
"the length of interhelical distance vector... norm_ih_dvec = np.linalg.norm(ih_dvec) #",
"np.dot(core_vec_ref_unit, core_vec_tar_unit) ) if inter_angle > np.pi / 2.0: inter_angle",
"# Denominator if de == 0: sc, tc = 0,",
"c - b * b # Denominator if de ==",
"utf-8 -*- import numpy as np def remove_nan(xyzs): return xyzs[~np.isnan(xyzs).any(axis",
"coding: utf-8 -*- import numpy as np def remove_nan(xyzs): return",
"sc, tc = 0, d / b else: sc, tc",
"core_vec_tar_unit) ) return ih_dvec, norm_ih_dvec, core_vec_ref_unit, core_vec_tar_unit, ih_ang def calc_interangle(core_xyz_ref,",
"core vectors... core_xyz_ref_nonan = remove_nan(core_xyz_ref) core_xyz_tar_nonan = remove_nan(core_xyz_tar) core_vec_ref =",
"vector between the centers. - Interhelical angle (0-90 degree) '''",
"+ sc * u - tc * v inter_dist =",
"* d) / de, (a * e - b *",
"center_ref = np.nanmean(core_xyz_ref, axis = 0) center_tar = np.nanmean(core_xyz_tar, axis",
"for the method. Q is ref, P is tar. '''",
"0, d / b else: sc, tc = (b *",
"np.dot(u, u) b = np.dot(u, v) c = np.dot(v, v)",
"''' # Obtain the helical core vectors... core_xyz_ref_nonan = remove_nan(core_xyz_ref)",
"following aspects of two helical cores. - Interhelical angle (0-90",
"1)] def measure_twocores(core_xyz_ref, core_xyz_tar): ''' Measure the following aspects of",
"with magnitude... v = core_vec_ref u = core_vec_tar # Math",
"def calc_interangle(core_xyz_ref, core_xyz_tar): ''' Measure the following aspects of two",
"Measure the following aspects of two helical cores. - Interhelical",
"(b * e - c * d) / de, (a",
"Denominator if de == 0: sc, tc = 0, d",
"P is tar. ''' # Obtain the helical core vectors...",
"following aspects of two helical cores. - Interhelical distance vector",
"core_vec_ref / np.linalg.norm(core_vec_ref) core_vec_tar_unit = core_vec_tar / np.linalg.norm(core_vec_tar) inter_angle =",
"''' # Obtain the centers... center_ref = np.nanmean(core_xyz_ref, axis =",
"starting point... q0 = core_xyz_ref_nonan[0] p0 = core_xyz_tar_nonan[0] w0 =",
"magnitude... v = core_vec_ref u = core_vec_tar # Math part...",
"- c * d) / de, (a * e -",
"0) center_tar = np.nanmean(core_xyz_tar, axis = 0) # Construct the",
"b # Denominator if de == 0: sc, tc =",
"= np.arccos( np.dot(core_vec_ref_unit, core_vec_tar_unit) ) if inter_angle > np.pi /",
"calc_interdist(core_xyz_ref, core_xyz_tar): ''' Measure the following aspects of two helical",
"core_vec_tar_unit, ih_ang def calc_interangle(core_xyz_ref, core_xyz_tar): ''' Measure the following aspects",
"p0 - q0 # Obtain the directional vector with magnitude...",
"between the centers. Refers to http://geomalgorithms.com/a07-_distance.html for the method. Q",
"= core_xyz_tar_nonan[-1] - core_xyz_tar_nonan[0] # Obtain the starting point... q0",
"= np.dot(u, w0) e = np.dot(v, w0) de = a",
"Calculate the length of interhelical distance vector... norm_ih_dvec = np.linalg.norm(ih_dvec)",
"= np.nanmean(core_xyz_ref, axis = 0) center_tar = np.nanmean(core_xyz_tar, axis =",
"Obtain the helical core vectors... core_xyz_ref_nonan = remove_nan(core_xyz_ref) core_xyz_tar_nonan =",
"* c - b * b # Denominator if de",
"core_xyz_ref_nonan[0] core_vec_tar = core_xyz_tar_nonan[-1] - core_xyz_tar_nonan[0] # Calculate the interhelical",
"b * b # Denominator if de == 0: sc,",
"v) d = np.dot(u, w0) e = np.dot(v, w0) de",
"tc = 0, d / b else: sc, tc =",
"centers... center_ref = np.nanmean(core_xyz_ref, axis = 0) center_tar = np.nanmean(core_xyz_tar,",
"core_xyz_tar_nonan[0] # Obtain the starting point... q0 = core_xyz_ref_nonan[0] p0",
"e = np.dot(v, w0) de = a * c -",
"the directional vector with magnitude... v = core_vec_ref u =",
"core_vec_tar # Math part... a = np.dot(u, u) b =",
"angle (0-90 degree) ''' # Obtain the helical core vectors...",
"a * c - b * b # Denominator if",
"sc, tc = (b * e - c * d)",
"angle (0-90 degree) ''' # Obtain the centers... center_ref =",
"core_xyz_tar_nonan = remove_nan(core_xyz_tar) core_vec_ref = core_xyz_ref_nonan[-1] - core_xyz_ref_nonan[0] core_vec_tar =",
"Obtain the directional vector with magnitude... v = core_vec_ref u",
"core_xyz_tar_nonan[0] # Calculate the interhelical angle... core_vec_ref_unit = core_vec_ref /",
"the following aspects of two helical cores. - Interhelical distance",
"# Calculate distance... wc = w0 + sc * u",
"/ np.linalg.norm(core_vec_ref) core_vec_tar_unit = core_vec_tar / np.linalg.norm(core_vec_tar) inter_angle = np.arccos(",
"def remove_nan(xyzs): return xyzs[~np.isnan(xyzs).any(axis = 1)] def measure_twocores(core_xyz_ref, core_xyz_tar): '''",
"# -*- coding: utf-8 -*- import numpy as np def",
"the interhelical angle... core_vec_ref_unit = core_vec_ref / np.linalg.norm(core_vec_ref) core_vec_tar_unit =",
"return xyzs[~np.isnan(xyzs).any(axis = 1)] def measure_twocores(core_xyz_ref, core_xyz_tar): ''' Measure the",
"w0 = p0 - q0 # Obtain the directional vector",
"e - b * d) / de # Calculate distance...",
"# Math part... a = np.dot(u, u) b = np.dot(u,",
"cores. - Interhelical distance vector between the centers. Refers to",
"Interhelical angle (0-90 degree) ''' # Obtain the helical core",
"= np.dot(v, v) d = np.dot(u, w0) e = np.dot(v,",
"de # Calculate distance... wc = w0 + sc *",
"core_xyz_tar_nonan[-1] - core_xyz_tar_nonan[0] # Calculate the interhelical angle... core_vec_ref_unit =",
"* d) / de # Calculate distance... wc = w0",
"Refers to http://geomalgorithms.com/a07-_distance.html for the method. Q is ref, P",
"- b * b # Denominator if de == 0:",
"= core_vec_tar / np.linalg.norm(core_vec_tar) inter_angle = np.arccos( np.dot(core_vec_ref_unit, core_vec_tar_unit) )",
"the method. Q is ref, P is tar. ''' #",
"= core_vec_ref / np.linalg.norm(core_vec_ref) core_vec_tar_unit = core_vec_tar / np.linalg.norm(core_vec_tar) ih_ang",
"inter_angle > np.pi / 2.0: inter_angle = np.pi - inter_angle",
"= (b * e - c * d) / de,",
"core_vec_ref u = core_vec_tar # Math part... a = np.dot(u,",
"the centers. - Interhelical angle (0-90 degree) ''' # Obtain",
"core_vec_tar / np.linalg.norm(core_vec_tar) inter_angle = np.arccos( np.dot(core_vec_ref_unit, core_vec_tar_unit) ) if",
"if inter_angle > np.pi / 2.0: inter_angle = np.pi -",
"w0 + sc * u - tc * v inter_dist",
"measure_twocores(core_xyz_ref, core_xyz_tar): ''' Measure the following aspects of two helical",
"cores. - Interhelical angle (0-90 degree) ''' # Obtain the",
"of two helical cores. - Interhelical distance vector between the",
"of two helical cores. - Interhelical angle (0-90 degree) '''",
"= 0) # Construct the interhelical distance vector... ih_dvec =",
"= core_vec_ref / np.linalg.norm(core_vec_ref) core_vec_tar_unit = core_vec_tar / np.linalg.norm(core_vec_tar) inter_angle",
"(0-90 degree) ''' # Obtain the centers... center_ref = np.nanmean(core_xyz_ref,",
"core_vec_ref_unit, core_vec_tar_unit, ih_ang def calc_interangle(core_xyz_ref, core_xyz_tar): ''' Measure the following",
"aspects of two helical cores. - Interhelical angle (0-90 degree)",
"ih_ang = np.arccos( np.dot(core_vec_ref_unit, core_vec_tar_unit) ) return ih_dvec, norm_ih_dvec, core_vec_ref_unit,",
"= np.pi - inter_angle return inter_angle def calc_interdist(core_xyz_ref, core_xyz_tar): '''",
"interhelical distance vector... norm_ih_dvec = np.linalg.norm(ih_dvec) # Obtain the helical",
"cores. - Interhelical distance vector between the centers. - Interhelical",
"wc = w0 + sc * u - tc *",
"(0-90 degree) ''' # Obtain the helical core vectors... core_xyz_ref_nonan",
"tc = (b * e - c * d) /",
") return ih_dvec, norm_ih_dvec, core_vec_ref_unit, core_vec_tar_unit, ih_ang def calc_interangle(core_xyz_ref, core_xyz_tar):",
"- core_xyz_tar_nonan[0] # Calculate the interhelical angle... core_vec_ref_unit = core_vec_ref",
"0) # Construct the interhelical distance vector... ih_dvec = center_tar",
"- core_xyz_tar_nonan[0] # Obtain the starting point... q0 = core_xyz_ref_nonan[0]",
"axis = 0) center_tar = np.nanmean(core_xyz_tar, axis = 0) #",
"distance vector... ih_dvec = center_tar - center_ref # Calculate the",
"np.arccos( np.dot(core_vec_ref_unit, core_vec_tar_unit) ) if inter_angle > np.pi / 2.0:",
"the centers. Refers to http://geomalgorithms.com/a07-_distance.html for the method. Q is",
"aspects of two helical cores. - Interhelical distance vector between",
"calc_interangle(core_xyz_ref, core_xyz_tar): ''' Measure the following aspects of two helical",
"method. Q is ref, P is tar. ''' # Obtain",
"= 0) center_tar = np.nanmean(core_xyz_tar, axis = 0) # Construct",
"= a * c - b * b # Denominator",
"w0) de = a * c - b * b",
"b * d) / de # Calculate distance... wc =",
"centers. Refers to http://geomalgorithms.com/a07-_distance.html for the method. Q is ref,",
"vector... ih_dvec = center_tar - center_ref # Calculate the length",
"core_vec_ref_unit = core_vec_ref / np.linalg.norm(core_vec_ref) core_vec_tar_unit = core_vec_tar / np.linalg.norm(core_vec_tar)",
"np.arccos( np.dot(core_vec_ref_unit, core_vec_tar_unit) ) return ih_dvec, norm_ih_dvec, core_vec_ref_unit, core_vec_tar_unit, ih_ang",
"= np.dot(u, u) b = np.dot(u, v) c = np.dot(v,",
"np.pi - inter_angle return inter_angle def calc_interdist(core_xyz_ref, core_xyz_tar): ''' Measure",
"else: sc, tc = (b * e - c *",
"http://geomalgorithms.com/a07-_distance.html for the method. Q is ref, P is tar.",
"- b * d) / de # Calculate distance... wc",
"interhelical angle... core_vec_ref_unit = core_vec_ref / np.linalg.norm(core_vec_ref) core_vec_tar_unit = core_vec_tar",
"Construct the interhelical distance vector... ih_dvec = center_tar - center_ref",
"de = a * c - b * b #",
"Math part... a = np.dot(u, u) b = np.dot(u, v)",
"> np.pi / 2.0: inter_angle = np.pi - inter_angle return",
"= core_xyz_ref_nonan[0] p0 = core_xyz_tar_nonan[0] w0 = p0 - q0",
"= np.arccos( np.dot(core_vec_ref_unit, core_vec_tar_unit) ) return ih_dvec, norm_ih_dvec, core_vec_ref_unit, core_vec_tar_unit,",
"* e - c * d) / de, (a *",
"Calculate the interhelical angle... core_vec_ref_unit = core_vec_ref / np.linalg.norm(core_vec_ref) core_vec_tar_unit",
"the centers... center_ref = np.nanmean(core_xyz_ref, axis = 0) center_tar =",
"/ np.linalg.norm(core_vec_ref) core_vec_tar_unit = core_vec_tar / np.linalg.norm(core_vec_tar) ih_ang = np.arccos(",
"directional vector with magnitude... v = core_vec_ref u = core_vec_tar",
"def measure_twocores(core_xyz_ref, core_xyz_tar): ''' Measure the following aspects of two",
"de, (a * e - b * d) / de",
"core_vec_tar_unit = core_vec_tar / np.linalg.norm(core_vec_tar) ih_ang = np.arccos( np.dot(core_vec_ref_unit, core_vec_tar_unit)",
"c = np.dot(v, v) d = np.dot(u, w0) e =",
"inter_angle return inter_angle def calc_interdist(core_xyz_ref, core_xyz_tar): ''' Measure the following",
"two helical cores. - Interhelical angle (0-90 degree) ''' #",
"core_xyz_ref_nonan[-1] - core_xyz_ref_nonan[0] core_vec_tar = core_xyz_tar_nonan[-1] - core_xyz_tar_nonan[0] # Calculate",
"centers. - Interhelical angle (0-90 degree) ''' # Obtain the",
"center_tar = np.nanmean(core_xyz_tar, axis = 0) # Construct the interhelical",
") if inter_angle > np.pi / 2.0: inter_angle = np.pi",
"Obtain the starting point... q0 = core_xyz_ref_nonan[0] p0 = core_xyz_tar_nonan[0]",
"''' Measure the following aspects of two helical cores. -",
"u) b = np.dot(u, v) c = np.dot(v, v) d",
"distance vector between the centers. Refers to http://geomalgorithms.com/a07-_distance.html for the",
"inter_angle def calc_interdist(core_xyz_ref, core_xyz_tar): ''' Measure the following aspects of",
"np.pi / 2.0: inter_angle = np.pi - inter_angle return inter_angle",
"u = core_vec_tar # Math part... a = np.dot(u, u)",
"# Calculate the interhelical angle... core_vec_ref_unit = core_vec_ref / np.linalg.norm(core_vec_ref)",
"core_vec_tar = core_xyz_tar_nonan[-1] - core_xyz_tar_nonan[0] # Calculate the interhelical angle...",
"Interhelical distance vector between the centers. Refers to http://geomalgorithms.com/a07-_distance.html for",
"sc * u - tc * v inter_dist = np.linalg.norm(wc)",
"core_xyz_ref_nonan = remove_nan(core_xyz_ref) core_xyz_tar_nonan = remove_nan(core_xyz_tar) core_vec_ref = core_xyz_ref_nonan[-1] -",
"np.linalg.norm(core_vec_tar) inter_angle = np.arccos( np.dot(core_vec_ref_unit, core_vec_tar_unit) ) if inter_angle >",
"vector... norm_ih_dvec = np.linalg.norm(ih_dvec) # Obtain the helical core vectors...",
"the helical core vectors... core_xyz_ref_nonan = remove_nan(core_xyz_ref) core_xyz_tar_nonan = remove_nan(core_xyz_tar)",
"- inter_angle return inter_angle def calc_interdist(core_xyz_ref, core_xyz_tar): ''' Measure the",
"2.0: inter_angle = np.pi - inter_angle return inter_angle def calc_interdist(core_xyz_ref,",
"as np def remove_nan(xyzs): return xyzs[~np.isnan(xyzs).any(axis = 1)] def measure_twocores(core_xyz_ref,",
"helical cores. - Interhelical distance vector between the centers. -",
"np def remove_nan(xyzs): return xyzs[~np.isnan(xyzs).any(axis = 1)] def measure_twocores(core_xyz_ref, core_xyz_tar):",
"np.linalg.norm(ih_dvec) # Obtain the helical core vectors... core_xyz_ref_nonan = remove_nan(core_xyz_ref)",
"-*- coding: utf-8 -*- import numpy as np def remove_nan(xyzs):",
"= 1)] def measure_twocores(core_xyz_ref, core_xyz_tar): ''' Measure the following aspects",
"two helical cores. - Interhelical distance vector between the centers.",
"#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as",
"de == 0: sc, tc = 0, d / b",
"p0 = core_xyz_tar_nonan[0] w0 = p0 - q0 # Obtain",
"helical cores. - Interhelical angle (0-90 degree) ''' # Obtain",
"/ de # Calculate distance... wc = w0 + sc",
"# Obtain the centers... center_ref = np.nanmean(core_xyz_ref, axis = 0)",
"= p0 - q0 # Obtain the directional vector with",
"to http://geomalgorithms.com/a07-_distance.html for the method. Q is ref, P is",
"= core_vec_ref u = core_vec_tar # Math part... a =",
"# Calculate the length of interhelical distance vector... norm_ih_dvec =",
"degree) ''' # Obtain the centers... center_ref = np.nanmean(core_xyz_ref, axis",
"v) c = np.dot(v, v) d = np.dot(u, w0) e",
"* b # Denominator if de == 0: sc, tc",
"d / b else: sc, tc = (b * e",
"norm_ih_dvec, core_vec_ref_unit, core_vec_tar_unit, ih_ang def calc_interangle(core_xyz_ref, core_xyz_tar): ''' Measure the",
"= core_vec_tar / np.linalg.norm(core_vec_tar) ih_ang = np.arccos( np.dot(core_vec_ref_unit, core_vec_tar_unit) )",
"np.linalg.norm(core_vec_tar) ih_ang = np.arccos( np.dot(core_vec_ref_unit, core_vec_tar_unit) ) return ih_dvec, norm_ih_dvec,",
"np.nanmean(core_xyz_tar, axis = 0) # Construct the interhelical distance vector...",
"core_vec_tar = core_xyz_tar_nonan[-1] - core_xyz_tar_nonan[0] # Obtain the starting point...",
"remove_nan(core_xyz_tar) core_vec_ref = core_xyz_ref_nonan[-1] - core_xyz_ref_nonan[0] core_vec_tar = core_xyz_tar_nonan[-1] -",
"part... a = np.dot(u, u) b = np.dot(u, v) c",
"np.dot(u, v) c = np.dot(v, v) d = np.dot(u, w0)",
"point... q0 = core_xyz_ref_nonan[0] p0 = core_xyz_tar_nonan[0] w0 = p0",
"d) / de, (a * e - b * d)",
"distance... wc = w0 + sc * u - tc",
"Interhelical angle (0-90 degree) ''' # Obtain the centers... center_ref",
"the interhelical distance vector... ih_dvec = center_tar - center_ref #",
"core_xyz_ref_nonan[0] core_vec_tar = core_xyz_tar_nonan[-1] - core_xyz_tar_nonan[0] # Obtain the starting",
"- core_xyz_ref_nonan[0] core_vec_tar = core_xyz_tar_nonan[-1] - core_xyz_tar_nonan[0] # Calculate the",
"# Obtain the directional vector with magnitude... v = core_vec_ref",
"d = np.dot(u, w0) e = np.dot(v, w0) de =",
"remove_nan(xyzs): return xyzs[~np.isnan(xyzs).any(axis = 1)] def measure_twocores(core_xyz_ref, core_xyz_tar): ''' Measure",
"/ 2.0: inter_angle = np.pi - inter_angle return inter_angle def",
"= np.dot(u, v) c = np.dot(v, v) d = np.dot(u,",
"np.dot(v, w0) de = a * c - b *",
"if de == 0: sc, tc = 0, d /",
"np.dot(v, v) d = np.dot(u, w0) e = np.dot(v, w0)",
"* u - tc * v inter_dist = np.linalg.norm(wc) return",
"Calculate distance... wc = w0 + sc * u -",
"- q0 # Obtain the directional vector with magnitude... v",
"def calc_interdist(core_xyz_ref, core_xyz_tar): ''' Measure the following aspects of two",
"- Interhelical distance vector between the centers. Refers to http://geomalgorithms.com/a07-_distance.html",
"np.nanmean(core_xyz_ref, axis = 0) center_tar = np.nanmean(core_xyz_tar, axis = 0)",
"vector between the centers. Refers to http://geomalgorithms.com/a07-_distance.html for the method.",
"angle... core_vec_ref_unit = core_vec_ref / np.linalg.norm(core_vec_ref) core_vec_tar_unit = core_vec_tar /"
] |
[
"2) if len(sline) == 9: nums_9_chars.append(num) nums.append(num) count_even = 0",
"[] for line in f: sline = line.strip() num =",
"nums: List[int] = [] nums_9_chars: List[int] = [] for line",
"2 == 0: count_even += 1 if num > max_num:",
"List[int] = [] for line in f: sline = line.strip()",
"= int(sline, 2) if len(sline) == 9: nums_9_chars.append(num) nums.append(num) count_even",
"in nums: if num % 2 == 0: count_even +=",
"1 if num > max_num: max_num = num print(f\"{count_even=}\") print(f\"max_num(10):",
"with open(\"dane/liczby.txt\") as f: nums: List[int] = [] nums_9_chars: List[int]",
"0 max_num = 0 for num in nums: if num",
"line in f: sline = line.strip() num = int(sline, 2)",
"== 9: nums_9_chars.append(num) nums.append(num) count_even = 0 max_num = 0",
"f: sline = line.strip() num = int(sline, 2) if len(sline)",
"[] nums_9_chars: List[int] = [] for line in f: sline",
"sline = line.strip() num = int(sline, 2) if len(sline) ==",
"in nums_9_chars: sum_9_chars += num print(f\"count of numbers with 9",
"as f: nums: List[int] = [] nums_9_chars: List[int] = []",
"List[int] = [] nums_9_chars: List[int] = [] for line in",
"for num in nums_9_chars: sum_9_chars += num print(f\"count of numbers",
"max_num(2): {bin(max_num)[2:]}\") sum_9_chars = 0 for num in nums_9_chars: sum_9_chars",
"= [] for line in f: sline = line.strip() num",
"int(sline, 2) if len(sline) == 9: nums_9_chars.append(num) nums.append(num) count_even =",
"print(f\"count of numbers with 9 digits: {len(nums_9_chars)}, their sum: {bin(sum_9_chars)[2:]}\")",
"print(f\"max_num(10): {max_num}, max_num(2): {bin(max_num)[2:]}\") sum_9_chars = 0 for num in",
"num print(f\"count of numbers with 9 digits: {len(nums_9_chars)}, their sum:",
"= 0 max_num = 0 for num in nums: if",
"0 for num in nums_9_chars: sum_9_chars += num print(f\"count of",
"line.strip() num = int(sline, 2) if len(sline) == 9: nums_9_chars.append(num)",
"= [] nums_9_chars: List[int] = [] for line in f:",
"nums.append(num) count_even = 0 max_num = 0 for num in",
"in f: sline = line.strip() num = int(sline, 2) if",
"nums: if num % 2 == 0: count_even += 1",
"== 0: count_even += 1 if num > max_num: max_num",
"sum_9_chars = 0 for num in nums_9_chars: sum_9_chars += num",
"for line in f: sline = line.strip() num = int(sline,",
"= line.strip() num = int(sline, 2) if len(sline) == 9:",
"9: nums_9_chars.append(num) nums.append(num) count_even = 0 max_num = 0 for",
"num % 2 == 0: count_even += 1 if num",
"max_num = 0 for num in nums: if num %",
"+= num print(f\"count of numbers with 9 digits: {len(nums_9_chars)}, their",
"0 for num in nums: if num % 2 ==",
"from typing import List with open(\"dane/liczby.txt\") as f: nums: List[int]",
"for num in nums: if num % 2 == 0:",
"num in nums_9_chars: sum_9_chars += num print(f\"count of numbers with",
"if num > max_num: max_num = num print(f\"{count_even=}\") print(f\"max_num(10): {max_num},",
"% 2 == 0: count_even += 1 if num >",
"0: count_even += 1 if num > max_num: max_num =",
"= num print(f\"{count_even=}\") print(f\"max_num(10): {max_num}, max_num(2): {bin(max_num)[2:]}\") sum_9_chars = 0",
"<reponame>bartekpacia/informatyka-frycz<gh_stars>1-10 from typing import List with open(\"dane/liczby.txt\") as f: nums:",
"{max_num}, max_num(2): {bin(max_num)[2:]}\") sum_9_chars = 0 for num in nums_9_chars:",
"nums_9_chars.append(num) nums.append(num) count_even = 0 max_num = 0 for num",
"count_even += 1 if num > max_num: max_num = num",
"> max_num: max_num = num print(f\"{count_even=}\") print(f\"max_num(10): {max_num}, max_num(2): {bin(max_num)[2:]}\")",
"count_even = 0 max_num = 0 for num in nums:",
"typing import List with open(\"dane/liczby.txt\") as f: nums: List[int] =",
"f: nums: List[int] = [] nums_9_chars: List[int] = [] for",
"num in nums: if num % 2 == 0: count_even",
"{bin(max_num)[2:]}\") sum_9_chars = 0 for num in nums_9_chars: sum_9_chars +=",
"nums_9_chars: sum_9_chars += num print(f\"count of numbers with 9 digits:",
"nums_9_chars: List[int] = [] for line in f: sline =",
"import List with open(\"dane/liczby.txt\") as f: nums: List[int] = []",
"num = int(sline, 2) if len(sline) == 9: nums_9_chars.append(num) nums.append(num)",
"max_num: max_num = num print(f\"{count_even=}\") print(f\"max_num(10): {max_num}, max_num(2): {bin(max_num)[2:]}\") sum_9_chars",
"max_num = num print(f\"{count_even=}\") print(f\"max_num(10): {max_num}, max_num(2): {bin(max_num)[2:]}\") sum_9_chars =",
"+= 1 if num > max_num: max_num = num print(f\"{count_even=}\")",
"= 0 for num in nums: if num % 2",
"if num % 2 == 0: count_even += 1 if",
"print(f\"{count_even=}\") print(f\"max_num(10): {max_num}, max_num(2): {bin(max_num)[2:]}\") sum_9_chars = 0 for num",
"len(sline) == 9: nums_9_chars.append(num) nums.append(num) count_even = 0 max_num =",
"List with open(\"dane/liczby.txt\") as f: nums: List[int] = [] nums_9_chars:",
"if len(sline) == 9: nums_9_chars.append(num) nums.append(num) count_even = 0 max_num",
"= 0 for num in nums_9_chars: sum_9_chars += num print(f\"count",
"open(\"dane/liczby.txt\") as f: nums: List[int] = [] nums_9_chars: List[int] =",
"num print(f\"{count_even=}\") print(f\"max_num(10): {max_num}, max_num(2): {bin(max_num)[2:]}\") sum_9_chars = 0 for",
"num > max_num: max_num = num print(f\"{count_even=}\") print(f\"max_num(10): {max_num}, max_num(2):",
"sum_9_chars += num print(f\"count of numbers with 9 digits: {len(nums_9_chars)},"
] |
[
"fib(n-2) def fib_fast(n): from math import sqrt s5 = sqrt(5)",
"** n y = (1 - s5) ** n return",
"0, 1 if n == 0: print a elif n",
"else: return fib(n-1) + fib(n-2) def fib_fast(n): from math import",
"fib(i), print for i in range(n): print fib_fast(i), def print_fib2(n):",
"i in range(n): print fib(i), print for i in range(n):",
"(1 - s5) ** n return int((x - y)/(s5 *",
"0: print a elif n == 1: print a, b",
"import sqrt s5 = sqrt(5) x = (1 + s5)",
"def print_fib2(n): fibs = [0, 1] a, b = 0,",
"n return int((x - y)/(s5 * 2**n)) def print_fib(n): for",
"range(2, n): a, b = b, a + b print",
"def print_fib(n): for i in range(n): print fib(i), print for",
"range(n): print fib_fast(i), def print_fib2(n): fibs = [0, 1] a,",
"return fib(n-1) + fib(n-2) def fib_fast(n): from math import sqrt",
"math import sqrt s5 = sqrt(5) x = (1 +",
"= sqrt(5) x = (1 + s5) ** n y",
"in range(2, n): a, b = b, a + b",
"y)/(s5 * 2**n)) def print_fib(n): for i in range(n): print",
"y = (1 - s5) ** n return int((x -",
"s5) ** n return int((x - y)/(s5 * 2**n)) def",
"fib_fast(i), def print_fib2(n): fibs = [0, 1] a, b =",
"= (1 - s5) ** n return int((x - y)/(s5",
"b = 0, 1 if n == 0: print a",
"1: print a, b else: print 0, 1, for i",
"a elif n == 1: print a, b else: print",
"(1 + s5) ** n y = (1 - s5)",
"= [0, 1] a, b = 0, 1 if n",
"in range(n): print fib_fast(i), def print_fib2(n): fibs = [0, 1]",
"sqrt s5 = sqrt(5) x = (1 + s5) **",
"1 if n == 0: print a elif n ==",
"n == 0: print a elif n == 1: print",
"0, 1, for i in range(2, n): a, b =",
"== 1: print a, b else: print 0, 1, for",
"for i in range(n): print fib(i), print for i in",
"print for i in range(n): print fib_fast(i), def print_fib2(n): fibs",
"s5 = sqrt(5) x = (1 + s5) ** n",
"= (1 + s5) ** n y = (1 -",
"if n < 2: return n else: return fib(n-1) +",
"= b, a + b print b, if __name__ ==",
"print 0, 1, for i in range(2, n): a, b",
"[0, 1] a, b = 0, 1 if n ==",
"a + b print b, if __name__ == \"__main__\": print_fib(10)",
"for i in range(2, n): a, b = b, a",
"+ b print b, if __name__ == \"__main__\": print_fib(10) print",
"= 0, 1 if n == 0: print a elif",
"print_fib2(n): fibs = [0, 1] a, b = 0, 1",
"from math import sqrt s5 = sqrt(5) x = (1",
"print_fib(n): for i in range(n): print fib(i), print for i",
"return int((x - y)/(s5 * 2**n)) def print_fib(n): for i",
"fibs = [0, 1] a, b = 0, 1 if",
"- s5) ** n return int((x - y)/(s5 * 2**n))",
"sqrt(5) x = (1 + s5) ** n y =",
"i in range(2, n): a, b = b, a +",
"def fib_fast(n): from math import sqrt s5 = sqrt(5) x",
"1, for i in range(2, n): a, b = b,",
"+ fib(n-2) def fib_fast(n): from math import sqrt s5 =",
"for i in range(n): print fib_fast(i), def print_fib2(n): fibs =",
"range(n): print fib(i), print for i in range(n): print fib_fast(i),",
"fib(n-1) + fib(n-2) def fib_fast(n): from math import sqrt s5",
"print fib(i), print for i in range(n): print fib_fast(i), def",
"a, b = b, a + b print b, if",
"a, b = 0, 1 if n == 0: print",
"2: return n else: return fib(n-1) + fib(n-2) def fib_fast(n):",
"2**n)) def print_fib(n): for i in range(n): print fib(i), print",
"b, a + b print b, if __name__ == \"__main__\":",
"a, b else: print 0, 1, for i in range(2,",
"n y = (1 - s5) ** n return int((x",
"print fib_fast(i), def print_fib2(n): fibs = [0, 1] a, b",
"print a elif n == 1: print a, b else:",
"s5) ** n y = (1 - s5) ** n",
"n): a, b = b, a + b print b,",
"fib(n): if n < 2: return n else: return fib(n-1)",
"+ s5) ** n y = (1 - s5) **",
"print a, b else: print 0, 1, for i in",
"fib_fast(n): from math import sqrt s5 = sqrt(5) x =",
"return n else: return fib(n-1) + fib(n-2) def fib_fast(n): from",
"b = b, a + b print b, if __name__",
"def fib(n): if n < 2: return n else: return",
"== 0: print a elif n == 1: print a,",
"x = (1 + s5) ** n y = (1",
"< 2: return n else: return fib(n-1) + fib(n-2) def",
"* 2**n)) def print_fib(n): for i in range(n): print fib(i),",
"b print b, if __name__ == \"__main__\": print_fib(10) print print_fib2(10)",
"1] a, b = 0, 1 if n == 0:",
"b else: print 0, 1, for i in range(2, n):",
"n < 2: return n else: return fib(n-1) + fib(n-2)",
"i in range(n): print fib_fast(i), def print_fib2(n): fibs = [0,",
"- y)/(s5 * 2**n)) def print_fib(n): for i in range(n):",
"** n return int((x - y)/(s5 * 2**n)) def print_fib(n):",
"else: print 0, 1, for i in range(2, n): a,",
"n else: return fib(n-1) + fib(n-2) def fib_fast(n): from math",
"in range(n): print fib(i), print for i in range(n): print",
"elif n == 1: print a, b else: print 0,",
"n == 1: print a, b else: print 0, 1,",
"int((x - y)/(s5 * 2**n)) def print_fib(n): for i in",
"if n == 0: print a elif n == 1:"
] |
[
"List from src.model.Etape import Etape from src.model.Grille import Grille from",
"= 0 g_y = 0 for index_etape in range(lines[index-1][1]): #ajoute",
"range(lines[0][2]): grille.robots.append(Robot()) # Crée les points de montage, et les",
"correspondant # crée les robots for idx_robot in range(lines[0][2]): grille.robots.append(Robot())",
"qui permet de lire le fichier texte d'input fourni par",
"calcul la distance et la surface aproximative entre chaque étape",
"# Crée les instances Taches et Etapes for index_tache in",
"tache_tampon.centre_gravite.distance(etape)) \\ .distance(tache_tampon.centre_gravite) grille.add_tache(tache_tampon) # calcul la distance et la",
"d'entiers for index_line in range(len(lines)): lines[index_line] = lines[index_line].split(' ') for",
"distance et la surface aproximative entre chaque étape for etape_from,",
"fichier assert os.path.isfile(file_path) with open(file_path, 'r') as file: index: int",
"les points de montage, et les place dans la grille",
"in range(len(lines)): lines[index_line] = lines[index_line].split(' ') for index_val in range(len(lines[index_line])):",
"from src.model.Grille import Grille from src.model.ItemCase import ItemCase from src.model.PointMontage",
"import Robot from src.model.Tache import Tache class ParseInput: \"\"\"Parser qui",
"idx_point_montage in range(lines[0][3]): index += 1 grille.add_point_montage(PointMontage(lines[index][0], lines[index][1])) # Récupère",
"de tour d'horloge autorisé grille.step_simulation = lines[0][5] # Récupére les",
"fichier en données et classes exploitables pour nous \"\"\" grille:",
"src.model.Etape import Etape from src.model.Grille import Grille from src.model.ItemCase import",
"index: int = 0 # récupère toutes les lignes du",
"de Grille grille = Grille(lines[0][0], lines[0][1]) # instancie dans grille",
"dans la grille (et ne pas oublier de l'associer à",
"pas oublier de l'associer à la tâche) # Crée les",
"tache_tampon.add_etape(etape) g_x += (etape.x - g_x)/len(tache_tampon.etapes) g_y += (etape.y -",
"classe tache tache_tampon.centre_gravite = ItemCase(int(g_x), int(g_y)) tache_tampon.distance_centre_gravite = max(tache_tampon.etapes, key=lambda",
"l'instancier et la mettre dans la grille (et ne pas",
"tache tache_tampon.centre_gravite = ItemCase(int(g_x), int(g_y)) tache_tampon.distance_centre_gravite = max(tache_tampon.etapes, key=lambda etape:",
"et la mettre dans la grille (et ne pas oublier",
"Grille(lines[0][0], lines[0][1]) # instancie dans grille le nombre de robot",
"= int(lines[index_line][index_val]) # crée un instance de Grille grille =",
"de lire le fichier texte d'input fourni par Google. Va",
"le nombre de robot correspondant # crée les robots for",
"= lines[index_line].split(' ') for index_val in range(len(lines[index_line])): lines[index_line][index_val] = int(lines[index_line][index_val])",
"et les place dans la grille for idx_point_montage in range(lines[0][3]):",
"et Etapes for index_tache in range(lines[0][4]): index += 1 tache_tampon:",
"dans la grille for idx_point_montage in range(lines[0][3]): index += 1",
"Transformation des lignes en liste d'entiers for index_line in range(len(lines)):",
"# instancier dans grille les tâches correspondantes # si une",
"Etape from src.model.Grille import Grille from src.model.ItemCase import ItemCase from",
"str) -> Grille: \"\"\"parse le fichier google et retourne la",
"1 grille.add_point_montage(PointMontage(lines[index][0], lines[index][1])) # Récupère le nombre de tour d'horloge",
"range(lines[0][3]): index += 1 grille.add_point_montage(PointMontage(lines[index][0], lines[index][1])) # Récupère le nombre",
"# si une étape (assembly point) n'est pas encore créée",
"Crée les points de montage, et les place dans la",
"index_etape in range(lines[index-1][1]): #ajoute les étapes etape = Etape(lines[index][index_etape*2+0], lines[index][index_etape*2+1])",
"Grille def __init__(self): pass def parse(self, file_path: str) -> Grille:",
"et la surface aproximative entre chaque étape for etape_from, etape_to",
"chaque étape for etape_from, etape_to in zip(tache_tampon.etapes[0::1], tache_tampon.etapes[1::1]): tache_tampon.distance +=",
"liste d'entiers for index_line in range(len(lines)): lines[index_line] = lines[index_line].split(' ')",
"# l'instancier et la mettre dans la grille (et ne",
"tache_tampon: Tache = Tache(lines[index][0], index_tache) index += 1 g_x =",
"#ajoute les paramètres dans la classe tache tache_tampon.centre_gravite = ItemCase(int(g_x),",
"le fichier texte d'input fourni par Google. Va transformer ce",
"Récupére les informations de chaque tâche # instancier dans grille",
"= ItemCase(int(g_x), int(g_y)) tache_tampon.distance_centre_gravite = max(tache_tampon.etapes, key=lambda etape: tache_tampon.centre_gravite.distance(etape)) \\",
"étape (assembly point) n'est pas encore créée dans la grille",
"Grille \"\"\" # tests si file_path est un fichier assert",
"# Crée les points de montage, et les place dans",
"l'associer à la tâche) # Crée les instances Taches et",
"grille (et ne pas oublier de l'associer à la tâche)",
"Récupère le nombre de tour d'horloge autorisé grille.step_simulation = lines[0][5]",
"in zip(tache_tampon.etapes[0::1], tache_tampon.etapes[1::1]): tache_tampon.distance += etape_from.distance(etape_to) tache_tampon.surface += etape_from.distance(etape_to) return",
"grille = Grille(lines[0][0], lines[0][1]) # instancie dans grille le nombre",
"google et retourne la Grille correspondante :rtype: Grille \"\"\" #",
"in range(lines[0][2]): grille.robots.append(Robot()) # Crée les points de montage, et",
"lignes du fichiers lines: List = file.readlines() # Transformation des",
"# Récupére les informations de chaque tâche # instancier dans",
"par Google. Va transformer ce fichier en données et classes",
"idx_robot in range(lines[0][2]): grille.robots.append(Robot()) # Crée les points de montage,",
"oublier de l'associer à la tâche) # Crée les instances",
"(assembly point) n'est pas encore créée dans la grille aux",
"la surface aproximative entre chaque étape for etape_from, etape_to in",
"Etape(lines[index][index_etape*2+0], lines[index][index_etape*2+1]) tache_tampon.add_etape(etape) g_x += (etape.x - g_x)/len(tache_tampon.etapes) g_y +=",
"aproximative entre chaque étape for etape_from, etape_to in zip(tache_tampon.etapes[0::1], tache_tampon.etapes[1::1]):",
"nous \"\"\" grille: Grille def __init__(self): pass def parse(self, file_path:",
"lines: List = file.readlines() # Transformation des lignes en liste",
"Grille correspondante :rtype: Grille \"\"\" # tests si file_path est",
"import ItemCase from src.model.PointMontage import PointMontage from src.model.Robot import Robot",
"pour nous \"\"\" grille: Grille def __init__(self): pass def parse(self,",
"les paramètres dans la classe tache tache_tampon.centre_gravite = ItemCase(int(g_x), int(g_y))",
"g_x)/len(tache_tampon.etapes) g_y += (etape.y - g_y)/len(tache_tampon.etapes) #ajoute les paramètres dans",
"etape_to in zip(tache_tampon.etapes[0::1], tache_tampon.etapes[1::1]): tache_tampon.distance += etape_from.distance(etape_to) tache_tampon.surface += etape_from.distance(etape_to)",
"Etapes for index_tache in range(lines[0][4]): index += 1 tache_tampon: Tache",
"src.model.Tache import Tache class ParseInput: \"\"\"Parser qui permet de lire",
"la Grille correspondante :rtype: Grille \"\"\" # tests si file_path",
"grille.robots.append(Robot()) # Crée les points de montage, et les place",
"tache_tampon.distance_centre_gravite = max(tache_tampon.etapes, key=lambda etape: tache_tampon.centre_gravite.distance(etape)) \\ .distance(tache_tampon.centre_gravite) grille.add_tache(tache_tampon) #",
"max(tache_tampon.etapes, key=lambda etape: tache_tampon.centre_gravite.distance(etape)) \\ .distance(tache_tampon.centre_gravite) grille.add_tache(tache_tampon) # calcul la",
"range(len(lines[index_line])): lines[index_line][index_val] = int(lines[index_line][index_val]) # crée un instance de Grille",
"\"\"\"Parser qui permet de lire le fichier texte d'input fourni",
"lines[index][1])) # Récupère le nombre de tour d'horloge autorisé grille.step_simulation",
"assert os.path.isfile(file_path) with open(file_path, 'r') as file: index: int =",
"# crée les robots for idx_robot in range(lines[0][2]): grille.robots.append(Robot()) #",
"grille.add_point_montage(PointMontage(lines[index][0], lines[index][1])) # Récupère le nombre de tour d'horloge autorisé",
"tache_tampon.centre_gravite = ItemCase(int(g_x), int(g_y)) tache_tampon.distance_centre_gravite = max(tache_tampon.etapes, key=lambda etape: tache_tampon.centre_gravite.distance(etape))",
"Taches et Etapes for index_tache in range(lines[0][4]): index += 1",
"List = file.readlines() # Transformation des lignes en liste d'entiers",
"ItemCase from src.model.PointMontage import PointMontage from src.model.Robot import Robot from",
"+= 1 tache_tampon: Tache = Tache(lines[index][0], index_tache) index += 1",
"- g_y)/len(tache_tampon.etapes) #ajoute les paramètres dans la classe tache tache_tampon.centre_gravite",
"file: index: int = 0 # récupère toutes les lignes",
"# tests si file_path est un fichier assert os.path.isfile(file_path) with",
"autorisé grille.step_simulation = lines[0][5] # Récupére les informations de chaque",
"Grille from src.model.ItemCase import ItemCase from src.model.PointMontage import PointMontage from",
"from src.model.Robot import Robot from src.model.Tache import Tache class ParseInput:",
"Tache class ParseInput: \"\"\"Parser qui permet de lire le fichier",
"os.path.isfile(file_path) with open(file_path, 'r') as file: index: int = 0",
"grille for idx_point_montage in range(lines[0][3]): index += 1 grille.add_point_montage(PointMontage(lines[index][0], lines[index][1]))",
"in range(lines[0][4]): index += 1 tache_tampon: Tache = Tache(lines[index][0], index_tache)",
"robots for idx_robot in range(lines[0][2]): grille.robots.append(Robot()) # Crée les points",
"os from typing import List from src.model.Etape import Etape from",
"from src.model.Tache import Tache class ParseInput: \"\"\"Parser qui permet de",
"la classe tache tache_tampon.centre_gravite = ItemCase(int(g_x), int(g_y)) tache_tampon.distance_centre_gravite = max(tache_tampon.etapes,",
"lignes en liste d'entiers for index_line in range(len(lines)): lines[index_line] =",
"file.readlines() # Transformation des lignes en liste d'entiers for index_line",
"range(lines[0][4]): index += 1 tache_tampon: Tache = Tache(lines[index][0], index_tache) index",
"lines[0][5] # Récupére les informations de chaque tâche # instancier",
"exploitables pour nous \"\"\" grille: Grille def __init__(self): pass def",
"en données et classes exploitables pour nous \"\"\" grille: Grille",
"tour d'horloge autorisé grille.step_simulation = lines[0][5] # Récupére les informations",
"= Etape(lines[index][index_etape*2+0], lines[index][index_etape*2+1]) tache_tampon.add_etape(etape) g_x += (etape.x - g_x)/len(tache_tampon.etapes) g_y",
"dans grille le nombre de robot correspondant # crée les",
"# Transformation des lignes en liste d'entiers for index_line in",
"file_path: str) -> Grille: \"\"\"parse le fichier google et retourne",
"int(lines[index_line][index_val]) # crée un instance de Grille grille = Grille(lines[0][0],",
"<filename>src/model/ParseInput.py import os from typing import List from src.model.Etape import",
"def __init__(self): pass def parse(self, file_path: str) -> Grille: \"\"\"parse",
"# crée un instance de Grille grille = Grille(lines[0][0], lines[0][1])",
"toutes les lignes du fichiers lines: List = file.readlines() #",
"instancier dans grille les tâches correspondantes # si une étape",
"retourne la Grille correspondante :rtype: Grille \"\"\" # tests si",
"Robot from src.model.Tache import Tache class ParseInput: \"\"\"Parser qui permet",
"cordonnées correspondantes, # l'instancier et la mettre dans la grille",
"for index_etape in range(lines[index-1][1]): #ajoute les étapes etape = Etape(lines[index][index_etape*2+0],",
"Tache(lines[index][0], index_tache) index += 1 g_x = 0 g_y =",
"un fichier assert os.path.isfile(file_path) with open(file_path, 'r') as file: index:",
"fichier google et retourne la Grille correspondante :rtype: Grille \"\"\"",
"import PointMontage from src.model.Robot import Robot from src.model.Tache import Tache",
"for index_line in range(len(lines)): lines[index_line] = lines[index_line].split(' ') for index_val",
"range(lines[index-1][1]): #ajoute les étapes etape = Etape(lines[index][index_etape*2+0], lines[index][index_etape*2+1]) tache_tampon.add_etape(etape) g_x",
"la distance et la surface aproximative entre chaque étape for",
"\"\"\" # tests si file_path est un fichier assert os.path.isfile(file_path)",
"= 0 # récupère toutes les lignes du fichiers lines:",
"en liste d'entiers for index_line in range(len(lines)): lines[index_line] = lines[index_line].split('",
"crée un instance de Grille grille = Grille(lines[0][0], lines[0][1]) #",
"crée les robots for idx_robot in range(lines[0][2]): grille.robots.append(Robot()) # Crée",
"Crée les instances Taches et Etapes for index_tache in range(lines[0][4]):",
"une étape (assembly point) n'est pas encore créée dans la",
"n'est pas encore créée dans la grille aux cordonnées correspondantes,",
"et retourne la Grille correspondante :rtype: Grille \"\"\" # tests",
"def parse(self, file_path: str) -> Grille: \"\"\"parse le fichier google",
"index += 1 grille.add_point_montage(PointMontage(lines[index][0], lines[index][1])) # Récupère le nombre de",
"for idx_robot in range(lines[0][2]): grille.robots.append(Robot()) # Crée les points de",
"nombre de robot correspondant # crée les robots for idx_robot",
"correspondantes # si une étape (assembly point) n'est pas encore",
"1 g_x = 0 g_y = 0 for index_etape in",
"le nombre de tour d'horloge autorisé grille.step_simulation = lines[0][5] #",
"la grille (et ne pas oublier de l'associer à la",
"# Récupère le nombre de tour d'horloge autorisé grille.step_simulation =",
"etape = Etape(lines[index][index_etape*2+0], lines[index][index_etape*2+1]) tache_tampon.add_etape(etape) g_x += (etape.x - g_x)/len(tache_tampon.etapes)",
"src.model.Grille import Grille from src.model.ItemCase import ItemCase from src.model.PointMontage import",
"= max(tache_tampon.etapes, key=lambda etape: tache_tampon.centre_gravite.distance(etape)) \\ .distance(tache_tampon.centre_gravite) grille.add_tache(tache_tampon) # calcul",
"Va transformer ce fichier en données et classes exploitables pour",
"Tache = Tache(lines[index][0], index_tache) index += 1 g_x = 0",
"paramètres dans la classe tache tache_tampon.centre_gravite = ItemCase(int(g_x), int(g_y)) tache_tampon.distance_centre_gravite",
"index += 1 tache_tampon: Tache = Tache(lines[index][0], index_tache) index +=",
"from typing import List from src.model.Etape import Etape from src.model.Grille",
"etape_from, etape_to in zip(tache_tampon.etapes[0::1], tache_tampon.etapes[1::1]): tache_tampon.distance += etape_from.distance(etape_to) tache_tampon.surface +=",
"g_y = 0 for index_etape in range(lines[index-1][1]): #ajoute les étapes",
"chaque tâche # instancier dans grille les tâches correspondantes #",
"in range(lines[0][3]): index += 1 grille.add_point_montage(PointMontage(lines[index][0], lines[index][1])) # Récupère le",
"les informations de chaque tâche # instancier dans grille les",
"in range(len(lines[index_line])): lines[index_line][index_val] = int(lines[index_line][index_val]) # crée un instance de",
"range(len(lines)): lines[index_line] = lines[index_line].split(' ') for index_val in range(len(lines[index_line])): lines[index_line][index_val]",
"du fichiers lines: List = file.readlines() # Transformation des lignes",
"= file.readlines() # Transformation des lignes en liste d'entiers for",
"nombre de tour d'horloge autorisé grille.step_simulation = lines[0][5] # Récupére",
"parse(self, file_path: str) -> Grille: \"\"\"parse le fichier google et",
"0 for index_etape in range(lines[index-1][1]): #ajoute les étapes etape =",
"encore créée dans la grille aux cordonnées correspondantes, # l'instancier",
"de l'associer à la tâche) # Crée les instances Taches",
"pass def parse(self, file_path: str) -> Grille: \"\"\"parse le fichier",
"+= 1 grille.add_point_montage(PointMontage(lines[index][0], lines[index][1])) # Récupère le nombre de tour",
"for etape_from, etape_to in zip(tache_tampon.etapes[0::1], tache_tampon.etapes[1::1]): tache_tampon.distance += etape_from.distance(etape_to) tache_tampon.surface",
".distance(tache_tampon.centre_gravite) grille.add_tache(tache_tampon) # calcul la distance et la surface aproximative",
"les lignes du fichiers lines: List = file.readlines() # Transformation",
"+= (etape.y - g_y)/len(tache_tampon.etapes) #ajoute les paramètres dans la classe",
"import Grille from src.model.ItemCase import ItemCase from src.model.PointMontage import PointMontage",
"ce fichier en données et classes exploitables pour nous \"\"\"",
"+= (etape.x - g_x)/len(tache_tampon.etapes) g_y += (etape.y - g_y)/len(tache_tampon.etapes) #ajoute",
"class ParseInput: \"\"\"Parser qui permet de lire le fichier texte",
"dans grille les tâches correspondantes # si une étape (assembly",
"src.model.ItemCase import ItemCase from src.model.PointMontage import PointMontage from src.model.Robot import",
"grille.step_simulation = lines[0][5] # Récupére les informations de chaque tâche",
"key=lambda etape: tache_tampon.centre_gravite.distance(etape)) \\ .distance(tache_tampon.centre_gravite) grille.add_tache(tache_tampon) # calcul la distance",
"robot correspondant # crée les robots for idx_robot in range(lines[0][2]):",
"les robots for idx_robot in range(lines[0][2]): grille.robots.append(Robot()) # Crée les",
"PointMontage from src.model.Robot import Robot from src.model.Tache import Tache class",
"le fichier google et retourne la Grille correspondante :rtype: Grille",
"# récupère toutes les lignes du fichiers lines: List =",
"open(file_path, 'r') as file: index: int = 0 # récupère",
"étape for etape_from, etape_to in zip(tache_tampon.etapes[0::1], tache_tampon.etapes[1::1]): tache_tampon.distance += etape_from.distance(etape_to)",
"fichier texte d'input fourni par Google. Va transformer ce fichier",
"permet de lire le fichier texte d'input fourni par Google.",
"les instances Taches et Etapes for index_tache in range(lines[0][4]): index",
"mettre dans la grille (et ne pas oublier de l'associer",
"aux cordonnées correspondantes, # l'instancier et la mettre dans la",
"index_val in range(len(lines[index_line])): lines[index_line][index_val] = int(lines[index_line][index_val]) # crée un instance",
"tâches correspondantes # si une étape (assembly point) n'est pas",
"index_tache in range(lines[0][4]): index += 1 tache_tampon: Tache = Tache(lines[index][0],",
"0 g_y = 0 for index_etape in range(lines[index-1][1]): #ajoute les",
":rtype: Grille \"\"\" # tests si file_path est un fichier",
"lines[index][index_etape*2+1]) tache_tampon.add_etape(etape) g_x += (etape.x - g_x)/len(tache_tampon.etapes) g_y += (etape.y",
"grille les tâches correspondantes # si une étape (assembly point)",
"la mettre dans la grille (et ne pas oublier de",
"créée dans la grille aux cordonnées correspondantes, # l'instancier et",
"in range(lines[index-1][1]): #ajoute les étapes etape = Etape(lines[index][index_etape*2+0], lines[index][index_etape*2+1]) tache_tampon.add_etape(etape)",
"import os from typing import List from src.model.Etape import Etape",
"instancie dans grille le nombre de robot correspondant # crée",
"surface aproximative entre chaque étape for etape_from, etape_to in zip(tache_tampon.etapes[0::1],",
"d'horloge autorisé grille.step_simulation = lines[0][5] # Récupére les informations de",
"index_line in range(len(lines)): lines[index_line] = lines[index_line].split(' ') for index_val in",
"pas encore créée dans la grille aux cordonnées correspondantes, #",
"grille aux cordonnées correspondantes, # l'instancier et la mettre dans",
"lines[index_line] = lines[index_line].split(' ') for index_val in range(len(lines[index_line])): lines[index_line][index_val] =",
"de montage, et les place dans la grille for idx_point_montage",
"= lines[0][5] # Récupére les informations de chaque tâche #",
"#ajoute les étapes etape = Etape(lines[index][index_etape*2+0], lines[index][index_etape*2+1]) tache_tampon.add_etape(etape) g_x +=",
"index_tache) index += 1 g_x = 0 g_y = 0",
"à la tâche) # Crée les instances Taches et Etapes",
"d'input fourni par Google. Va transformer ce fichier en données",
"si une étape (assembly point) n'est pas encore créée dans",
"'r') as file: index: int = 0 # récupère toutes",
"lines[0][1]) # instancie dans grille le nombre de robot correspondant",
"int = 0 # récupère toutes les lignes du fichiers",
"la grille aux cordonnées correspondantes, # l'instancier et la mettre",
"Grille grille = Grille(lines[0][0], lines[0][1]) # instancie dans grille le",
"= Grille(lines[0][0], lines[0][1]) # instancie dans grille le nombre de",
"dans la grille aux cordonnées correspondantes, # l'instancier et la",
"(etape.y - g_y)/len(tache_tampon.etapes) #ajoute les paramètres dans la classe tache",
"(et ne pas oublier de l'associer à la tâche) #",
"points de montage, et les place dans la grille for",
"les tâches correspondantes # si une étape (assembly point) n'est",
"import Etape from src.model.Grille import Grille from src.model.ItemCase import ItemCase",
"g_x = 0 g_y = 0 for index_etape in range(lines[index-1][1]):",
"les place dans la grille for idx_point_montage in range(lines[0][3]): index",
"texte d'input fourni par Google. Va transformer ce fichier en",
"etape: tache_tampon.centre_gravite.distance(etape)) \\ .distance(tache_tampon.centre_gravite) grille.add_tache(tache_tampon) # calcul la distance et",
"tests si file_path est un fichier assert os.path.isfile(file_path) with open(file_path,",
"-> Grille: \"\"\"parse le fichier google et retourne la Grille",
"# instancie dans grille le nombre de robot correspondant #",
"tâche) # Crée les instances Taches et Etapes for index_tache",
"les étapes etape = Etape(lines[index][index_etape*2+0], lines[index][index_etape*2+1]) tache_tampon.add_etape(etape) g_x += (etape.x",
"Grille: \"\"\"parse le fichier google et retourne la Grille correspondante",
"tâche # instancier dans grille les tâches correspondantes # si",
"la grille for idx_point_montage in range(lines[0][3]): index += 1 grille.add_point_montage(PointMontage(lines[index][0],",
"place dans la grille for idx_point_montage in range(lines[0][3]): index +=",
"des lignes en liste d'entiers for index_line in range(len(lines)): lines[index_line]",
"src.model.Robot import Robot from src.model.Tache import Tache class ParseInput: \"\"\"Parser",
"import List from src.model.Etape import Etape from src.model.Grille import Grille",
"si file_path est un fichier assert os.path.isfile(file_path) with open(file_path, 'r')",
"récupère toutes les lignes du fichiers lines: List = file.readlines()",
"lines[index_line][index_val] = int(lines[index_line][index_val]) # crée un instance de Grille grille",
"de chaque tâche # instancier dans grille les tâches correspondantes",
"= 0 for index_etape in range(lines[index-1][1]): #ajoute les étapes etape",
"la tâche) # Crée les instances Taches et Etapes for",
"ParseInput: \"\"\"Parser qui permet de lire le fichier texte d'input",
"informations de chaque tâche # instancier dans grille les tâches",
"for index_val in range(len(lines[index_line])): lines[index_line][index_val] = int(lines[index_line][index_val]) # crée un",
"étapes etape = Etape(lines[index][index_etape*2+0], lines[index][index_etape*2+1]) tache_tampon.add_etape(etape) g_x += (etape.x -",
"point) n'est pas encore créée dans la grille aux cordonnées",
"correspondante :rtype: Grille \"\"\" # tests si file_path est un",
"for index_tache in range(lines[0][4]): index += 1 tache_tampon: Tache =",
"typing import List from src.model.Etape import Etape from src.model.Grille import",
"g_x += (etape.x - g_x)/len(tache_tampon.etapes) g_y += (etape.y - g_y)/len(tache_tampon.etapes)",
"import Tache class ParseInput: \"\"\"Parser qui permet de lire le",
"\"\"\"parse le fichier google et retourne la Grille correspondante :rtype:",
"') for index_val in range(len(lines[index_line])): lines[index_line][index_val] = int(lines[index_line][index_val]) # crée",
"zip(tache_tampon.etapes[0::1], tache_tampon.etapes[1::1]): tache_tampon.distance += etape_from.distance(etape_to) tache_tampon.surface += etape_from.distance(etape_to) return grille",
"instances Taches et Etapes for index_tache in range(lines[0][4]): index +=",
"from src.model.ItemCase import ItemCase from src.model.PointMontage import PointMontage from src.model.Robot",
"transformer ce fichier en données et classes exploitables pour nous",
"lines[index_line].split(' ') for index_val in range(len(lines[index_line])): lines[index_line][index_val] = int(lines[index_line][index_val]) #",
"ItemCase(int(g_x), int(g_y)) tache_tampon.distance_centre_gravite = max(tache_tampon.etapes, key=lambda etape: tache_tampon.centre_gravite.distance(etape)) \\ .distance(tache_tampon.centre_gravite)",
"données et classes exploitables pour nous \"\"\" grille: Grille def",
"un instance de Grille grille = Grille(lines[0][0], lines[0][1]) # instancie",
"g_y += (etape.y - g_y)/len(tache_tampon.etapes) #ajoute les paramètres dans la",
"g_y)/len(tache_tampon.etapes) #ajoute les paramètres dans la classe tache tache_tampon.centre_gravite =",
"from src.model.Etape import Etape from src.model.Grille import Grille from src.model.ItemCase",
"fourni par Google. Va transformer ce fichier en données et",
"entre chaque étape for etape_from, etape_to in zip(tache_tampon.etapes[0::1], tache_tampon.etapes[1::1]): tache_tampon.distance",
"\\ .distance(tache_tampon.centre_gravite) grille.add_tache(tache_tampon) # calcul la distance et la surface",
"fichiers lines: List = file.readlines() # Transformation des lignes en",
"- g_x)/len(tache_tampon.etapes) g_y += (etape.y - g_y)/len(tache_tampon.etapes) #ajoute les paramètres",
"classes exploitables pour nous \"\"\" grille: Grille def __init__(self): pass",
"instance de Grille grille = Grille(lines[0][0], lines[0][1]) # instancie dans",
"1 tache_tampon: Tache = Tache(lines[index][0], index_tache) index += 1 g_x",
"de robot correspondant # crée les robots for idx_robot in",
"et classes exploitables pour nous \"\"\" grille: Grille def __init__(self):",
"grille.add_tache(tache_tampon) # calcul la distance et la surface aproximative entre",
"__init__(self): pass def parse(self, file_path: str) -> Grille: \"\"\"parse le",
"Google. Va transformer ce fichier en données et classes exploitables",
"= Tache(lines[index][0], index_tache) index += 1 g_x = 0 g_y",
"0 # récupère toutes les lignes du fichiers lines: List",
"index += 1 g_x = 0 g_y = 0 for",
"montage, et les place dans la grille for idx_point_montage in",
"# calcul la distance et la surface aproximative entre chaque",
"file_path est un fichier assert os.path.isfile(file_path) with open(file_path, 'r') as",
"grille le nombre de robot correspondant # crée les robots",
"as file: index: int = 0 # récupère toutes les",
"est un fichier assert os.path.isfile(file_path) with open(file_path, 'r') as file:",
"correspondantes, # l'instancier et la mettre dans la grille (et",
"grille: Grille def __init__(self): pass def parse(self, file_path: str) ->",
"for idx_point_montage in range(lines[0][3]): index += 1 grille.add_point_montage(PointMontage(lines[index][0], lines[index][1])) #",
"ne pas oublier de l'associer à la tâche) # Crée",
"int(g_y)) tache_tampon.distance_centre_gravite = max(tache_tampon.etapes, key=lambda etape: tache_tampon.centre_gravite.distance(etape)) \\ .distance(tache_tampon.centre_gravite) grille.add_tache(tache_tampon)",
"dans la classe tache tache_tampon.centre_gravite = ItemCase(int(g_x), int(g_y)) tache_tampon.distance_centre_gravite =",
"\"\"\" grille: Grille def __init__(self): pass def parse(self, file_path: str)",
"+= 1 g_x = 0 g_y = 0 for index_etape",
"src.model.PointMontage import PointMontage from src.model.Robot import Robot from src.model.Tache import",
"(etape.x - g_x)/len(tache_tampon.etapes) g_y += (etape.y - g_y)/len(tache_tampon.etapes) #ajoute les",
"from src.model.PointMontage import PointMontage from src.model.Robot import Robot from src.model.Tache",
"lire le fichier texte d'input fourni par Google. Va transformer",
"with open(file_path, 'r') as file: index: int = 0 #"
] |
[
"if not len(res) == len(exp_res): log(red(\"FAIL\"), ex_name, \": expected a",
"= np.array([1, 1]) T = 1 exp_res = (np.array([0, 2]),",
"not len(res) == len(exp_res): log(red(\"FAIL\"), ex_name, \": expected a tuple",
"\" but got array of shape\", res.shape) return True if",
"theta, theta_0 = 1, np.array([-1, 1]), -1.5 L = 0.2",
"\", type(res)) return if not len(res) == len(exp_res): log(red(\"FAIL\"), ex_name,",
"\"Pegasos single update\" feature_vector = np.array([1, 2]) label, theta, theta_0",
"theta_0 = 1, np.array([-1, 1]), -2 L = 0.2 eta",
"if k not in stop_keys]) elif keys == stop_keys: log(green(\"PASS\"),",
"\", \"He really really loves her\"] keys = [\"he\", \"loves\",",
"2) if check_tuple( ex_name, p1.perceptron, exp_res, feature_matrix, labels, T): return",
"<filename>test.py<gh_stars>0 import os import sys import time import traceback import",
"NotImplementedError: log(red(\"FAIL\"), ex_name, \": not implemented\") return True if not",
"1, np.array([-1, 1]), -1 exp_res = (np.array([0, 3]), 0) if",
"but got list of size\", len(res)) return True if not",
"removed\") else: log(red(\"FAIL\"), ex_name, \": keys are missing:\", [k for",
"Expected\", exp_res, \", got: \", res) return True def check_list(ex_name,",
"check_tuple( ex_name + \" (boundary case)\", p1.perceptron_single_step_update, exp_res, feature_vector, label,",
"zip(res, exp_res)): log(red(\"FAIL\"), ex_name, \": incorrect answer. Expected\", exp_res, \",",
"= np.array([1, 1]) T = 1 L = 1 exp_res",
"np.array([[1, 2]]) labels = np.array([1]) T = 1 exp_res =",
"\", exp_vals, \" got \", vals) return log(green(\"PASS\"), ex_name, \"\")",
"os import sys import time import traceback import project1_Copy as",
"if check_list( ex_name, p1.get_order, [0], 1): log(\"You should revert `get_order`",
"expected a list of size \", len(exp_res), \" but got",
"exp_keys = ['beach', 'better', 'he', 'is', 'loves', 'nothing', 'on', 'the',",
"T = 2 exp_res = (np.array([1, 2]), 1) if check_tuple(",
"pass\") return if check_list( ex_name, p1.get_order, [1, 0], 2): log(\"You",
"np.array([[1, 2], [1, 2]]) label, theta, theta_0 = np.array([1, 1]),",
"theta, theta_0): return log(green(\"PASS\"), ex_name, \"\") def check_perceptron(): ex_name =",
"= np.array([1]) T = 1 exp_res = (np.array([1, 2]), 1)",
"T = 1 exp_res = (np.array([-0.5, 1]), 1.5) if check_tuple(",
"not return a tuple, type: \", type(res)) return vals =",
"'the', 'there', 'to', 'walk'] stop_keys = ['beach', 'better', 'loves', 'nothing',",
"np.array([1]) T = 1 L = 0.2 exp_res = (np.array([1,",
"'nothing', 'walk'] if keys == exp_keys: log(yellow(\"WARN\"), ex_name, \": does",
"[k for k in keys if k not in stop_keys])",
"type(res)) return if not len(res) == len(exp_res): log(red(\"FAIL\"), ex_name, \":",
"res.shape) return True if not all(equals(x, y) for x, y",
"case)\", p1.pegasos_single_step_update, exp_res, feature_vector, label, L, eta, theta, theta_0): return",
"\", res) return True def equals(x, y): if type(y) ==",
"numpy array, type: \", type(res)) return True if not len(res)",
"1]), -1 exp_res = (np.array([0, 3]), 0) if check_tuple( ex_name",
"eta, theta, theta_0): return log(green(\"PASS\"), ex_name, \"\") def check_pegasos(): ex_name",
"2]), 1) if check_tuple( ex_name, p1.pegasos, exp_res, feature_matrix, labels, T,",
"return True if not len(res) == len(exp_res): log(red(\"FAIL\"), ex_name, \":",
"x, y in zip(res, exp_res)): log(red(\"FAIL\"), ex_name, \": incorrect answer.",
"loss single\" feature_vector = np.array([1, 2]) label, theta, theta_0 =",
"eta = 0.1 exp_res = (np.array([-0.88, 1.18]), -1.4) if check_tuple(",
"check_tuple( ex_name + \" (boundary case)\", p1.pegasos_single_step_update, exp_res, feature_vector, label,",
"return True def check_array(ex_name, f, exp_res, *args): try: res =",
"np.array([1, 1]), np.array([-1, 1]), -0.2 exp_res = 1 - 0.8",
"np.array([[1, 2]]) labels = np.array([1]) T = 1 L =",
"+ \" (boundary case)\", p1.pegasos_single_step_update, exp_res, feature_vector, label, L, eta,",
"[1, 1], [1, 1]]) theta = np.array([1, 1]) theta_0 =",
"- 0.8 if check_real( ex_name, p1.hinge_loss_full, exp_res, feature_vector, label, theta,",
"exp_res, feature_matrix, theta, theta_0): return log(green(\"PASS\"), ex_name, \"\") def check_classifier_accuracy():",
"keys if k not in stop_keys]) def check_extract_bow_feature_vectors(): ex_name =",
"return '\\033[1;32m%s\\033[m' % s def yellow(s): return '\\033[1;33m%s\\033[m' % s",
"check_get_order(): ex_name = \"Get order\" if check_list( ex_name, p1.get_order, [0],",
"tuple of size\", len(res)) return True if not all(equals(x, y)",
"a numpy array, type: \", type(res)) return if not len(res)",
"def check_hinge_loss_single(): ex_name = \"Hinge loss single\" feature_vector = np.array([1,",
"labels, T): return feature_matrix = np.array([[1, 2]]) labels = np.array([1])",
"def check_list(ex_name, f, exp_res, *args): try: res = f(*args) except",
"log(red(\"FAIL\"), ex_name, \": not implemented\") return True if not np.isreal(res):",
"exp_res, \", got: \", res) return True def check_list(ex_name, f,",
"check_tuple( ex_name, p1.perceptron, exp_res, feature_matrix, labels, T): return feature_matrix =",
"shape\", res.shape) return log(green(\"PASS\"), ex_name) if (res == exp_res).all(): log(yellow(\"WARN\"),",
"of size \", len(exp_res), \" but got list of size\",",
"not len(res) == len(exp_res): log(red(\"FAIL\"), ex_name, \": expected a list",
"1, 0], [1, 1, 1, 1]]) non_bin_res = np.array( [[1,",
"return log(green(\"PASS\"), ex_name, \"\") def check_average_perceptron(): ex_name = \"Average perceptron\"",
"the beach\", \"There is nothing better\"] try: res = p1.bag_of_words(texts)",
"1]) theta_0 = 0 exp_res = np.array([1, 1, 1]) if",
"-0.2 exp_res = 1 - 0.8 if check_real( ex_name, p1.hinge_loss_full,",
"\": not implemented\") return if not type(res) == dict: log(red(\"FAIL\"),",
"return '\\033[1;33m%s\\033[m' % s def red(s): return '\\033[1;31m%s\\033[m' % s",
"p1 import numpy as np verbose = False def green(s):",
"ex_name, \": not implemented\") return if not type(res) == dict:",
"= 1, np.array([-1, 1]), -1.5 exp_res = (np.array([0, 3]), -0.5)",
"2]]) label, theta, theta_0 = np.array([1, 1]), np.array([-1, 1]), -0.2",
"set of indices. Expected: \", exp_vals, \" got \", vals)",
"ex_name, p1.perceptron_single_step_update, exp_res, feature_vector, label, theta, theta_0): return feature_vector =",
"order\" if check_list( ex_name, p1.get_order, [0], 1): log(\"You should revert",
"1]), -1.5 exp_res = (np.array([0, 3]), -0.5) if check_tuple( ex_name,",
"= 2 exp_res = (np.array([-0.25, 1.5]), 1.75) if check_tuple( ex_name,",
"if check_tuple( ex_name, p1.perceptron, exp_res, feature_matrix, labels, T): return feature_matrix",
"'better', 'loves', 'nothing', 'walk'] if keys == exp_keys: log(yellow(\"WARN\"), ex_name,",
"(np.array([0, 3]), 0) if check_tuple( ex_name + \" (boundary case)\",",
"T = 2 exp_res = (np.array([0, 2]), 2) if check_tuple(",
"label, L, eta, theta, theta_0): return feature_vector = np.array([1, 2])",
"import sys import time import traceback import project1_Copy as p1",
"case)\", p1.classify, exp_res, feature_matrix, theta, theta_0): return log(green(\"PASS\"), ex_name, \"\")",
"train_labels = np.array([1, -1, 1]) val_labels = np.array([-1, 1]) exp_res",
"log(yellow(\"WARN\"), ex_name, \": uses binary indicators as features\") elif (res",
"exit(1) def check_real(ex_name, f, exp_res, *args): try: res = f(*args)",
"dictionary = {k:i for i, k in enumerate(keys)} exp_res =",
"p1.pegasos, exp_res, feature_matrix, labels, T, L): return log(green(\"PASS\"), ex_name, \"\")",
"0.2 eta = 0.1 exp_res = (np.array([-0.88, 1.18]), -1.4) if",
"feature_vector = np.array([1, 1]) label, theta, theta_0 = 1, np.array([-1,",
"return a numpy array, type: \", type(res)) return True if",
"k not in stop_keys]) elif keys == stop_keys: log(green(\"PASS\"), ex_name,",
"label, theta, theta_0 = 1, np.array([-1, 1]), -1.5 exp_res =",
"ex_name, \"\") def check_classifier_accuracy(): ex_name = \"Classifier accuracy\" train_feature_matrix =",
"= 0.2 eta = 0.1 exp_res = (np.array([-0.88, 1.18]), -1.4)",
"ex_name = \"Bag of words\" texts = [ \"He loves",
"ex_name + \" (boundary case)\", p1.classify, exp_res, feature_matrix, theta, theta_0):",
"vals = sorted(res.values()) exp_vals = list(range(len(res.keys()))) if not vals ==",
"if not type(res) == tuple: log(red(\"FAIL\"), ex_name, \": does not",
"\"Extract bow feature vectors\" texts = [ \"He loves her",
"as p1 import numpy as np verbose = False def",
"log(red(\"FAIL\"), ex_name, \": does not return a numpy array, type:",
"check_extract_bow_feature_vectors(): ex_name = \"Extract bow feature vectors\" texts = [",
"traceback import project1_Copy as p1 import numpy as np verbose",
"return True if not type(res) == list: log(red(\"FAIL\"), ex_name, \":",
"really loves her\"] keys = [\"he\", \"loves\", \"her\", \"really\"] dictionary",
"\"Average perceptron\" feature_matrix = np.array([[1, 2]]) labels = np.array([1]) T",
"vectors\" texts = [ \"He loves her \", \"He really",
"check_hinge_loss_single() check_hinge_loss_full() check_perceptron_single_update() check_perceptron() check_average_perceptron() check_pegasos_single_update() check_pegasos() check_classify() check_classifier_accuracy() check_bag_of_words()",
"perceptron\" feature_matrix = np.array([[1, 2]]) labels = np.array([1]) T =",
"exp_res, feature_vector, label, theta, theta_0): return log(green(\"PASS\"), ex_name, \"\") def",
"= f(*args) except NotImplementedError: log(red(\"FAIL\"), ex_name, \": not implemented\") return",
"theta_0): return log(green(\"PASS\"), ex_name, \"\") def check_perceptron_single_update(): ex_name = \"Perceptron",
"ex_name, \"\") def check_classify(): ex_name = \"Classify\" feature_matrix = np.array([[1,",
"\"Classifier accuracy\" train_feature_matrix = np.array([[1, 0], [1, -1], [2, 3]])",
"\": uses binary indicators as features\") elif (res == non_bin_res).all():",
"return a list, type: \", type(res)) return True if not",
"\"\") def check_perceptron(): ex_name = \"Perceptron\" feature_matrix = np.array([[1, 2]])",
"label, theta, theta_0): return feature_vector = np.array([1, 2]) label, theta,",
"not return a numpy array, type: \", type(res)) return True",
"(np.array([1, 2]), 1) if check_tuple( ex_name, p1.average_perceptron, exp_res, feature_matrix, labels,",
"exp_res = np.array([1, 1, 1]) if check_array( ex_name, p1.classify, exp_res,",
"theta, theta_0 = 1, np.array([-1, 1]), -1 exp_res = (np.array([0,",
"should revert `get_order` to its original implementation for this test",
"[ \"He loves her \", \"He really really loves her\"]",
"2]), 1) if check_tuple( ex_name, p1.average_perceptron, exp_res, feature_matrix, labels, T):",
"stopwords removed\") else: log(red(\"FAIL\"), ex_name, \": keys are missing:\", [k",
"= [ \"He loves to walk on the beach\", \"There",
"if (res == exp_res).all(): log(yellow(\"WARN\"), ex_name, \": uses binary indicators",
"label, theta, theta_0 = 1, np.array([-1, 1]), -1.5 L =",
"1]) if check_array( ex_name, p1.classify, exp_res, feature_matrix, theta, theta_0): return",
"(np.array([0, 3]), -0.5) if check_tuple( ex_name, p1.perceptron_single_step_update, exp_res, feature_vector, label,",
"exp_res, *args): try: res = f(*args) except NotImplementedError: log(red(\"FAIL\"), ex_name,",
"def green(s): return '\\033[1;32m%s\\033[m' % s def yellow(s): return '\\033[1;33m%s\\033[m'",
"feature_matrix, labels, T): return feature_matrix = np.array([[1, 2]]) labels =",
"1, 0 T=1 if check_tuple( ex_name, p1.classifier_accuracy, exp_res, p1.perceptron, train_feature_matrix,",
"\"loves\", \"her\", \"really\"] dictionary = {k:i for i, k in",
"\"\") def check_classifier_accuracy(): ex_name = \"Classifier accuracy\" train_feature_matrix = np.array([[1,",
"feature_vector, label, L, eta, theta, theta_0): return feature_vector = np.array([1,",
"1]) T = 1 L = 1 exp_res = (np.array([1-1/np.sqrt(2),",
"if not np.isreal(res): log(red(\"FAIL\"), ex_name, \": does not return a",
"vals) return log(green(\"PASS\"), ex_name, \"\") keys = sorted(res.keys()) exp_keys =",
"0], [1, 1, 1, 1]]) non_bin_res = np.array( [[1, 1,",
"check_classify() check_classifier_accuracy() check_bag_of_words() check_extract_bow_feature_vectors() except Exception: log_exit(traceback.format_exc()) if __name__ ==",
"or are not unexpected:\", [k for k in keys if",
"2 exp_res = (np.array([1, 2]), 1) if check_tuple( ex_name, p1.average_perceptron,",
"wrong set of indices. Expected: \", exp_vals, \" got \",",
"= (np.array([-0.5, 1]), 1.5) if check_tuple( ex_name, p1.average_perceptron, exp_res, feature_matrix,",
"\": expected an array of shape \", exp_res.shape, \" but",
"not return a list, type: \", type(res)) return True if",
"== y).all() return x == y def check_tuple(ex_name, f, exp_res,",
"1], [1, 1], [1, 1]]) theta = np.array([1, 1]) theta_0",
"val_feature_matrix = np.array([[1, 1], [2, -1]]) train_labels = np.array([1, -1,",
"NotImplementedError: log(red(\"FAIL\"), ex_name, \": not implemented\") return if not type(res)",
"feature_matrix = np.array([[-1, 1]]) theta = np.array([1, 1]) theta_0 =",
"\"Get order\" if check_list( ex_name, p1.get_order, [0], 1): log(\"You should",
"log(green(\"PASS\"), ex_name, \"\") def check_average_perceptron(): ex_name = \"Average perceptron\" feature_matrix",
"= 1 L = 1 exp_res = (np.array([1-1/np.sqrt(2), 1-1/np.sqrt(2)]), 1)",
"return if not len(res) == len(exp_res): log(red(\"FAIL\"), ex_name, \": expected",
"len(exp_res): log(red(\"FAIL\"), ex_name, \": expected a list of size \",",
"of shape\", res.shape) return log(green(\"PASS\"), ex_name) if (res == exp_res).all():",
"np.array([1, 1]) T = 1 exp_res = (np.array([-0.5, 1]), 1.5)",
"log(red(\"FAIL\"), ex_name, \": not implemented\") return True if not type(res)",
"**kwargs) except NotImplementedError: log(red(\"FAIL\"), ex_name, \": not implemented\") return True",
"ex_name = \"Hinge loss full\" feature_vector = np.array([[1, 2], [1,",
"res) return True def check_list(ex_name, f, exp_res, *args): try: res",
"exp_res = (np.array([1, 2]), 1) if check_tuple( ex_name, p1.perceptron, exp_res,",
"beach\", \"There is nothing better\"] try: res = p1.bag_of_words(texts) except",
"p1.pegasos_single_step_update, exp_res, feature_vector, label, L, eta, theta, theta_0): return feature_vector",
"implementation for this test to pass\") return log(green(\"PASS\"), ex_name, \"\")",
"check_pegasos_single_update(): ex_name = \"Pegasos single update\" feature_vector = np.array([1, 2])",
"Expected: \", exp_vals, \" got \", vals) return log(green(\"PASS\"), ex_name,",
"0.1 exp_res = (np.array([-0.88, 1.18]), -1.4) if check_tuple( ex_name, p1.pegasos_single_step_update,",
"1, 1, 1]]) non_bin_res = np.array( [[1, 1, 1, 0],",
"ex_name, p1.get_order, [0], 1): log(\"You should revert `get_order` to its",
"np.array([1, 2]) label, theta, theta_0 = 1, np.array([-1, 1]), -0.2",
"= \"Hinge loss single\" feature_vector = np.array([1, 2]) label, theta,",
"not in keys], \" or are not unexpected:\", [k for",
"check_hinge_loss_full(): ex_name = \"Hinge loss full\" feature_vector = np.array([[1, 2],",
"np.array([-1, 1]), 1 L = 0.2 eta = 0.1 exp_res",
"its original implementation for this test to pass\") return log(green(\"PASS\"),",
"label, theta, theta_0 = 1, np.array([-1, 1]), -2 L =",
"label, theta, theta_0): return log(green(\"PASS\"), ex_name, \"\") def check_perceptron(): ex_name",
"train_feature_matrix = np.array([[1, 0], [1, -1], [2, 3]]) val_feature_matrix =",
"res) return True def check_array(ex_name, f, exp_res, *args): try: res",
"\" or are not unexpected:\", [k for k in keys",
"k in keys if k not in stop_keys]) def check_extract_bow_feature_vectors():",
"np.array([1]) T = 1 exp_res = (np.array([1, 2]), 1) if",
"type(res)) return True if not len(res) == len(exp_res): log(red(\"FAIL\"), ex_name,",
"T, L): return log(green(\"PASS\"), ex_name, \"\") def check_classify(): ex_name =",
"ex_name, \": keys are missing:\", [k for k in stop_keys",
"log(red(\"FAIL\"), ex_name, \": unexpected feature matrix\") return def main(): log(green(\"PASS\"),",
"'\\033[1;32m%s\\033[m' % s def yellow(s): return '\\033[1;33m%s\\033[m' % s def",
"= 1, np.array([-1, 1]), 1 L = 0.2 eta =",
"this test to pass\") return if check_list( ex_name, p1.get_order, [1,",
"= sorted(res.keys()) exp_keys = ['beach', 'better', 'he', 'is', 'loves', 'nothing',",
"are missing:\", [k for k in stop_keys if k not",
"len(exp_res), \" but got list of size\", len(res)) return True",
"labels = np.array([1]) T = 1 exp_res = (np.array([1, 2]),",
"= 0.2 exp_res = (np.array([1, 2]), 1) if check_tuple( ex_name,",
"= np.array([1, 1, 1]) if check_array( ex_name, p1.classify, exp_res, feature_matrix,",
"check_get_order() check_hinge_loss_single() check_hinge_loss_full() check_perceptron_single_update() check_perceptron() check_average_perceptron() check_pegasos_single_update() check_pegasos() check_classify() check_classifier_accuracy()",
"\", res) return True def check_array(ex_name, f, exp_res, *args): try:",
"labels, T): return log(green(\"PASS\"), ex_name, \"\") def check_average_perceptron(): ex_name =",
"ex_name, \": expected an array of shape \", exp_res.shape, \"",
"print(\" \".join(map(str, m))) def log_exit(*m): log(red(\"ERROR:\"), *m) exit(1) def check_real(ex_name,",
"theta_0): return log(green(\"PASS\"), ex_name, \"\") def check_pegasos(): ex_name = \"Pegasos\"",
"def check_perceptron_single_update(): ex_name = \"Perceptron single update\" feature_vector = np.array([1,",
"theta_0 = 1, np.array([-1, 1]), -1 exp_res = (np.array([0, 3]),",
"exp_res).all(): log(yellow(\"WARN\"), ex_name, \": uses binary indicators as features\") elif",
"theta, theta_0 = 1, np.array([-1, 1]), -1.5 exp_res = (np.array([0,",
"L=0.2 if check_tuple( ex_name, p1.classifier_accuracy, exp_res, p1.pegasos, train_feature_matrix, val_feature_matrix, train_labels,",
"True if not all(equals(x, y) for x, y in zip(res,",
"1) if check_tuple( ex_name, p1.pegasos, exp_res, feature_matrix, labels, T, L):",
"True def check_list(ex_name, f, exp_res, *args): try: res = f(*args)",
"p1.perceptron_single_step_update, exp_res, feature_vector, label, theta, theta_0): return log(green(\"PASS\"), ex_name, \"\")",
"1, 1]]) non_bin_res = np.array( [[1, 1, 1, 0], [1,",
"return log(green(\"PASS\"), ex_name, \"\") def check_perceptron(): ex_name = \"Perceptron\" feature_matrix",
"exp_res, \", got: \", res) return True def check_array(ex_name, f,",
"array of shape\", res.shape) return True if not all(equals(x, y)",
"label, L, eta, theta, theta_0): return log(green(\"PASS\"), ex_name, \"\") def",
"np.array( [[1, 1, 1, 0], [1, 1, 1, 2]]) try:",
"got: \", res) return True def check_get_order(): ex_name = \"Get",
"exp_res, *args, **kwargs): try: res = f(*args, **kwargs) except NotImplementedError:",
"1, 0], [1, 1, 1, 2]]) try: res = p1.extract_bow_feature_vectors(texts,",
"\"Perceptron\" feature_matrix = np.array([[1, 2]]) labels = np.array([1]) T =",
"theta_0 = 1, np.array([-1, 1]), -1.5 L = 0.2 eta",
"= 0.1 exp_res = (np.array([-0.88, 1.08]), 1.1) if check_tuple( ex_name",
"exp_keys: log(yellow(\"WARN\"), ex_name, \": does not remove stopwords:\", [k for",
"\"really\"] dictionary = {k:i for i, k in enumerate(keys)} exp_res",
"0.8 if check_real( ex_name, p1.hinge_loss_single, exp_res, feature_vector, label, theta, theta_0):",
"equals(x, y): if type(y) == np.ndarray: return (x == y).all()",
"0 T=1 if check_tuple( ex_name, p1.classifier_accuracy, exp_res, p1.perceptron, train_feature_matrix, val_feature_matrix,",
"if check_tuple( ex_name, p1.average_perceptron, exp_res, feature_matrix, labels, T): return log(green(\"PASS\"),",
"exp_vals, \" got \", vals) return log(green(\"PASS\"), ex_name, \"\") keys",
"return True if not np.isreal(res): log(red(\"FAIL\"), ex_name, \": does not",
"= \"Average perceptron\" feature_matrix = np.array([[1, 2]]) labels = np.array([1])",
"unexpected feature matrix\") return def main(): log(green(\"PASS\"), \"Import project1\") try:",
"check_tuple(ex_name, f, exp_res, *args, **kwargs): try: res = f(*args, **kwargs)",
"len(exp_res): log(red(\"FAIL\"), ex_name, \": expected a tuple of size \",",
"= np.array([[-1, 1]]) theta = np.array([1, 1]) theta_0 = 0",
"1]), 1 L = 0.2 eta = 0.1 exp_res =",
"\"\") def check_average_perceptron(): ex_name = \"Average perceptron\" feature_matrix = np.array([[1,",
"theta, theta_0): return feature_vector = np.array([1, 2]) label, theta, theta_0",
"exp_res, feature_vector, label, L, eta, theta, theta_0): return log(green(\"PASS\"), ex_name,",
"1]) T = 2 exp_res = (np.array([-0.25, 1.5]), 1.75) if",
"labels = np.array([1, 1]) T = 1 exp_res = (np.array([0,",
"= np.array( [[1, 1, 1, 0], [1, 1, 1, 1]])",
"return a tuple, type: \", type(res)) return vals = sorted(res.values())",
"p1.hinge_loss_single, exp_res, feature_vector, label, theta, theta_0): return log(green(\"PASS\"), ex_name, \"\")",
"1]]) labels = np.array([1, 1]) T = 1 L =",
"does not return a numpy array, type: \", type(res)) return",
"not np.isreal(res): log(red(\"FAIL\"), ex_name, \": does not return a real",
"1, 0 T=1 L=0.2 if check_tuple( ex_name, p1.classifier_accuracy, exp_res, p1.pegasos,",
"p1.classifier_accuracy, exp_res, p1.pegasos, train_feature_matrix, val_feature_matrix, train_labels, val_labels, T=T, L=L): return",
"1-1/np.sqrt(2)]), 1) if check_tuple( ex_name, p1.pegasos, exp_res, feature_matrix, labels, T,",
"tuple: log(red(\"FAIL\"), ex_name, \": does not return a tuple, type:",
"\", got: \", res) return True def equals(x, y): if",
"T=T, L=L): return log(green(\"PASS\"), ex_name, \"\") def check_bag_of_words(): ex_name =",
"log(red(\"FAIL\"), ex_name, \": does not return a list, type: \",",
"sorted(res.keys()) exp_keys = ['beach', 'better', 'he', 'is', 'loves', 'nothing', 'on',",
"array, type: \", type(res)) return True if not len(res) ==",
"= \"Bag of words\" texts = [ \"He loves to",
"== non_bin_res).all(): log(green(\"PASS\"), ex_name, \": correct non binary features\") else:",
"ex_name, p1.pegasos_single_step_update, exp_res, feature_vector, label, L, eta, theta, theta_0): return",
"\", got: \", res) return True def check_array(ex_name, f, exp_res,",
"implemented\") return if not type(res) == np.ndarray: log(red(\"FAIL\"), ex_name, \":",
"a tuple, type: \", type(res)) return True if not len(res)",
"1.18]), -1.9) if check_tuple( ex_name, p1.pegasos_single_step_update, exp_res, feature_vector, label, L,",
"log(red(\"FAIL\"), ex_name, \": wrong set of indices. Expected: \", exp_vals,",
"np.array([1, -1, 1]) val_labels = np.array([-1, 1]) exp_res = 1,",
"-1.4) if check_tuple( ex_name, p1.pegasos_single_step_update, exp_res, feature_vector, label, L, eta,",
"(np.array([-0.5, 1]), 1.5) if check_tuple( ex_name, p1.average_perceptron, exp_res, feature_matrix, labels,",
"val_feature_matrix, train_labels, val_labels, T=T, L=L): return log(green(\"PASS\"), ex_name, \"\") def",
"0 exp_res = np.array([-1]) if check_array( ex_name + \" (boundary",
"1, np.array([-1, 1]), -0.2 exp_res = 1 - 0.8 if",
"\" got \", vals) return log(green(\"PASS\"), ex_name, \"\") keys =",
"exp_res)): log(red(\"FAIL\"), ex_name, \": incorrect answer. Expected\", exp_res, \", got:",
"= \"Pegasos\" feature_matrix = np.array([[1, 2]]) labels = np.array([1]) T",
"size \", len(exp_res), \" but got list of size\", len(res))",
"shape\", res.shape) return True if not all(equals(x, y) for x,",
"time import traceback import project1_Copy as p1 import numpy as",
"True if not type(res) == np.ndarray: log(red(\"FAIL\"), ex_name, \": does",
"= (np.array([-0.88, 1.08]), 1.1) if check_tuple( ex_name + \" (boundary",
"1.1) if check_tuple( ex_name + \" (boundary case)\", p1.pegasos_single_step_update, exp_res,",
"type: \", type(res)) return if not len(res) == len(exp_res): log(red(\"FAIL\"),",
"loss full\" feature_vector = np.array([[1, 2], [1, 2]]) label, theta,",
"exp_res, p1.pegasos, train_feature_matrix, val_feature_matrix, train_labels, val_labels, T=T, L=L): return log(green(\"PASS\"),",
"sys import time import traceback import project1_Copy as p1 import",
"size\", len(res)) return True if not all(equals(x, y) for x,",
"(np.array([-0.25, 1.5]), 1.75) if check_tuple( ex_name, p1.average_perceptron, exp_res, feature_matrix, labels,",
"to its original implementation for this test to pass\") return",
"for this test to pass\") return if check_list( ex_name, p1.get_order,",
"if check_tuple( ex_name, p1.pegasos, exp_res, feature_matrix, labels, T, L): return",
"feature_matrix = np.array([[1, 1], [1, 1], [1, 1]]) theta =",
"= 1, 0 T=1 L=0.2 if check_tuple( ex_name, p1.classifier_accuracy, exp_res,",
"ex_name, \": not implemented\") return if not type(res) == np.ndarray:",
"p1.classify, exp_res, feature_matrix, theta, theta_0): return feature_matrix = np.array([[-1, 1]])",
"loves to walk on the beach\", \"There is nothing better\"]",
"p1.get_order, [0], 1): log(\"You should revert `get_order` to its original",
"exp_res, feature_vector, label, theta, theta_0): return feature_vector = np.array([1, 2])",
"2]) label, theta, theta_0 = 1, np.array([-1, 1]), -0.2 exp_res",
"1, 1]) if check_array( ex_name, p1.classify, exp_res, feature_matrix, theta, theta_0):",
"nothing better\"] try: res = p1.bag_of_words(texts) except NotImplementedError: log(red(\"FAIL\"), ex_name,",
"theta_0 = 0 exp_res = np.array([1, 1, 1]) if check_array(",
"not type(res) == list: log(red(\"FAIL\"), ex_name, \": does not return",
"[0], 1): log(\"You should revert `get_order` to its original implementation",
"implemented\") return if not type(res) == dict: log(red(\"FAIL\"), ex_name, \":",
"= 0.1 exp_res = (np.array([-0.88, 1.18]), -1.9) if check_tuple( ex_name,",
"== stop_keys: log(green(\"PASS\"), ex_name, \" stopwords removed\") else: log(red(\"FAIL\"), ex_name,",
"def check_array(ex_name, f, exp_res, *args): try: res = f(*args) except",
"\": correct non binary features\") else: log(red(\"FAIL\"), ex_name, \": unexpected",
"check_array( ex_name, p1.classify, exp_res, feature_matrix, theta, theta_0): return feature_matrix =",
"\": not implemented\") return True if not type(res) == list:",
"return vals = sorted(res.values()) exp_vals = list(range(len(res.keys()))) if not vals",
"ex_name, \"\") def check_pegasos_single_update(): ex_name = \"Pegasos single update\" feature_vector",
"np.array([[-1, 1]]) theta = np.array([1, 1]) theta_0 = 0 exp_res",
"= 1, 0 T=1 if check_tuple( ex_name, p1.classifier_accuracy, exp_res, p1.perceptron,",
"True if not len(res) == len(exp_res): log(red(\"FAIL\"), ex_name, \": expected",
"all(equals(x, y) for x, y in zip(res, exp_res)): log(red(\"FAIL\"), ex_name,",
"'walk'] stop_keys = ['beach', 'better', 'loves', 'nothing', 'walk'] if keys",
"log_exit(*m): log(red(\"ERROR:\"), *m) exit(1) def check_real(ex_name, f, exp_res, *args): try:",
"tuple of size \", len(exp_res), \" but got tuple of",
"shape \", exp_res.shape, \" but got array of shape\", res.shape)",
"\" but got tuple of size\", len(res)) return True if",
"= np.array([1, 1]) T = 2 exp_res = (np.array([0, 2]),",
"return log(green(\"PASS\"), ex_name, \"\") def check_hinge_loss_full(): ex_name = \"Hinge loss",
"if check_list( ex_name, p1.get_order, [1, 0], 2): log(\"You should revert",
"1 exp_res = (np.array([1, 2]), 1) if check_tuple( ex_name, p1.perceptron,",
"np.array([-1]) if check_array( ex_name + \" (boundary case)\", p1.classify, exp_res,",
"= np.array( [[1, 1, 1, 0], [1, 1, 1, 2]])",
"1]), -2 L = 0.2 eta = 0.1 exp_res =",
"\" but got array of shape\", res.shape) return log(green(\"PASS\"), ex_name)",
"\", len(exp_res), \" but got list of size\", len(res)) return",
"log(red(\"ERROR:\"), *m) exit(1) def check_real(ex_name, f, exp_res, *args): try: res",
"np.array([[1, 0], [1, -1], [2, 3]]) val_feature_matrix = np.array([[1, 1],",
"1]), 1.5) if check_tuple( ex_name, p1.average_perceptron, exp_res, feature_matrix, labels, T):",
"*args, **kwargs): try: res = f(*args, **kwargs) except NotImplementedError: log(red(\"FAIL\"),",
"if check_tuple( ex_name, p1.classifier_accuracy, exp_res, p1.perceptron, train_feature_matrix, val_feature_matrix, train_labels, val_labels,",
"as np verbose = False def green(s): return '\\033[1;32m%s\\033[m' %",
"p1.classifier_accuracy, exp_res, p1.perceptron, train_feature_matrix, val_feature_matrix, train_labels, val_labels, T=T): return train_feature_matrix",
"np.ndarray: log(red(\"FAIL\"), ex_name, \": does not return a numpy array,",
"exp_res = (np.array([0, 2]), 2) if check_tuple( ex_name, p1.perceptron, exp_res,",
"theta_0): return feature_matrix = np.array([[-1, 1]]) theta = np.array([1, 1])",
"val_labels = np.array([-1, 1]) exp_res = 1, 0 T=1 if",
"binary indicators as features\") elif (res == non_bin_res).all(): log(green(\"PASS\"), ex_name,",
"try: res = f(*args) except NotImplementedError: log(red(\"FAIL\"), ex_name, \": not",
"= (np.array([0, 2]), 2) if check_tuple( ex_name, p1.perceptron, exp_res, feature_matrix,",
"np.array([[1, 1], [1, 1]]) labels = np.array([1, 1]) T =",
"\"He loves to walk on the beach\", \"There is nothing",
"exp_res, feature_matrix, labels, T): return feature_matrix = np.array([[1, 2]]) labels",
"matrix\") return def main(): log(green(\"PASS\"), \"Import project1\") try: check_get_order() check_hinge_loss_single()",
"'\\033[1;31m%s\\033[m' % s def log(*m): print(\" \".join(map(str, m))) def log_exit(*m):",
"return feature_matrix = np.array([[1, 2], [-1, 0]]) labels = np.array([1,",
"True if not np.isreal(res): log(red(\"FAIL\"), ex_name, \": does not return",
"return a numpy array, type: \", type(res)) return if not",
"not implemented\") return if not type(res) == np.ndarray: log(red(\"FAIL\"), ex_name,",
"not return a tuple, type: \", type(res)) return True if",
"tuple, type: \", type(res)) return True if not len(res) ==",
"= np.array([[1, 2], [1, 2]]) label, theta, theta_0 = np.array([1,",
"theta_0): return feature_vector = np.array([1, 2]) label, theta, theta_0 =",
"in stop_keys]) def check_extract_bow_feature_vectors(): ex_name = \"Extract bow feature vectors\"",
"ex_name) if (res == exp_res).all(): log(yellow(\"WARN\"), ex_name, \": uses binary",
"check_tuple( ex_name, p1.classifier_accuracy, exp_res, p1.pegasos, train_feature_matrix, val_feature_matrix, train_labels, val_labels, T=T,",
"check_list( ex_name, p1.get_order, [0], 1): log(\"You should revert `get_order` to",
"in keys], \" or are not unexpected:\", [k for k",
"\": wrong set of indices. Expected: \", exp_vals, \" got",
"indicators as features\") elif (res == non_bin_res).all(): log(green(\"PASS\"), ex_name, \":",
"features\") elif (res == non_bin_res).all(): log(green(\"PASS\"), ex_name, \": correct non",
"theta_0 = 0 exp_res = np.array([-1]) if check_array( ex_name +",
"theta_0): return feature_vector = np.array([1, 1]) label, theta, theta_0 =",
"\": does not return a real number, type: \", type(res))",
"2]) label, theta, theta_0 = 1, np.array([-1, 1]), -2 L",
"= [\"he\", \"loves\", \"her\", \"really\"] dictionary = {k:i for i,",
"L = 0.2 exp_res = (np.array([1, 2]), 1) if check_tuple(",
"0.2 eta = 0.1 exp_res = (np.array([-0.88, 1.18]), -1.9) if",
"ex_name, p1.hinge_loss_full, exp_res, feature_vector, label, theta, theta_0): return log(green(\"PASS\"), ex_name,",
"for k in stop_keys if k not in keys], \"",
"type(y) == np.ndarray: return (x == y).all() return x ==",
"2]), 1) if check_tuple( ex_name, p1.perceptron, exp_res, feature_matrix, labels, T):",
"but got tuple of size\", len(res)) return True if not",
"exp_res = (np.array([1-1/np.sqrt(2), 1-1/np.sqrt(2)]), 1) if check_tuple( ex_name, p1.pegasos, exp_res,",
"= \"Perceptron single update\" feature_vector = np.array([1, 2]) label, theta,",
"(np.array([-0.88, 1.18]), -1.4) if check_tuple( ex_name, p1.pegasos_single_step_update, exp_res, feature_vector, label,",
"check_tuple( ex_name, p1.pegasos, exp_res, feature_matrix, labels, T, L): return feature_matrix",
"== y def check_tuple(ex_name, f, exp_res, *args, **kwargs): try: res",
"0.1 exp_res = (np.array([-0.88, 1.08]), 1.1) if check_tuple( ex_name +",
"def check_classify(): ex_name = \"Classify\" feature_matrix = np.array([[1, 1], [1,",
"main(): log(green(\"PASS\"), \"Import project1\") try: check_get_order() check_hinge_loss_single() check_hinge_loss_full() check_perceptron_single_update() check_perceptron()",
"return feature_matrix = np.array([[-1, 1]]) theta = np.array([1, 1]) theta_0",
"ex_name = \"Pegasos\" feature_matrix = np.array([[1, 2]]) labels = np.array([1])",
"feature_vector, label, theta, theta_0): return log(green(\"PASS\"), ex_name, \"\") def check_hinge_loss_full():",
"res = f(*args) except NotImplementedError: log(red(\"FAIL\"), ex_name, \": not implemented\")",
"feature_vector, label, theta, theta_0): return log(green(\"PASS\"), ex_name, \"\") def check_perceptron_single_update():",
"not vals == exp_vals: log(red(\"FAIL\"), ex_name, \": wrong set of",
"got tuple of size\", len(res)) return True if not all(equals(x,",
"(boundary case)\", p1.perceptron_single_step_update, exp_res, feature_vector, label, theta, theta_0): return log(green(\"PASS\"),",
"return a tuple, type: \", type(res)) return True if not",
"theta, theta_0): return log(green(\"PASS\"), ex_name, \"\") def check_perceptron_single_update(): ex_name =",
"ex_name, \"\") def check_hinge_loss_single(): ex_name = \"Hinge loss single\" feature_vector",
"= \"Perceptron\" feature_matrix = np.array([[1, 2]]) labels = np.array([1]) T",
"train_feature_matrix, val_feature_matrix, train_labels, val_labels, T=T): return train_feature_matrix = np.array([[1, 0],",
"\"Hinge loss single\" feature_vector = np.array([1, 2]) label, theta, theta_0",
"0], [1, 1, 1, 2]]) try: res = p1.extract_bow_feature_vectors(texts, dictionary)",
"0]]) labels = np.array([1, 1]) T = 2 exp_res =",
"feature_vector, label, theta, theta_0): return log(green(\"PASS\"), ex_name, \"\") def check_perceptron():",
"np verbose = False def green(s): return '\\033[1;32m%s\\033[m' % s",
"\", type(res)) return True if not len(res) == len(exp_res): log(red(\"FAIL\"),",
"answer. Expected\", exp_res, \", got: \", res) return True def",
"len(exp_res), \" but got tuple of size\", len(res)) return True",
"exp_res: log(red(\"FAIL\"), ex_name, \": incorrect answer. Expected\", exp_res, \", got:",
"True if not type(res) == list: log(red(\"FAIL\"), ex_name, \": does",
"p1.average_perceptron, exp_res, feature_matrix, labels, T): return feature_matrix = np.array([[1, 2],",
"p1.average_perceptron, exp_res, feature_matrix, labels, T): return feature_matrix = np.array([[1, 2]])",
"= (np.array([-0.88, 1.18]), -1.9) if check_tuple( ex_name, p1.pegasos_single_step_update, exp_res, feature_vector,",
"ex_name, p1.classifier_accuracy, exp_res, p1.perceptron, train_feature_matrix, val_feature_matrix, train_labels, val_labels, T=T): return",
"test to pass\") return if check_list( ex_name, p1.get_order, [1, 0],",
"\"Pegasos\" feature_matrix = np.array([[1, 2]]) labels = np.array([1]) T =",
"if check_real( ex_name, p1.hinge_loss_single, exp_res, feature_vector, label, theta, theta_0): return",
"labels, T): return feature_matrix = np.array([[1, 2], [-1, 0]]) labels",
"== dict: log(red(\"FAIL\"), ex_name, \": does not return a tuple,",
"exp_res = 1 - 0.8 if check_real( ex_name, p1.hinge_loss_single, exp_res,",
"p1.get_order, [1, 0], 2): log(\"You should revert `get_order` to its",
"this test to pass\") return log(green(\"PASS\"), ex_name, \"\") def check_hinge_loss_single():",
"exp_res, feature_matrix, labels, T): return feature_matrix = np.array([[1, 2], [-1,",
"walk on the beach\", \"There is nothing better\"] try: res",
"try: res = p1.extract_bow_feature_vectors(texts, dictionary) except NotImplementedError: log(red(\"FAIL\"), ex_name, \":",
"labels = np.array([1, 1]) T = 1 L = 1",
"1, np.array([-1, 1]), 1 L = 0.2 eta = 0.1",
"log(green(\"PASS\"), ex_name, \"\") keys = sorted(res.keys()) exp_keys = ['beach', 'better',",
"not unexpected:\", [k for k in keys if k not",
"non_bin_res = np.array( [[1, 1, 1, 0], [1, 1, 1,",
"labels, T, L): return log(green(\"PASS\"), ex_name, \"\") def check_classify(): ex_name",
"check_bag_of_words() check_extract_bow_feature_vectors() except Exception: log_exit(traceback.format_exc()) if __name__ == \"__main__\": main()",
"if res != exp_res: log(red(\"FAIL\"), ex_name, \": incorrect answer. Expected\",",
"theta_0): return log(green(\"PASS\"), ex_name, \"\") def check_perceptron(): ex_name = \"Perceptron\"",
"= 1 L = 0.2 exp_res = (np.array([1, 2]), 1)",
"L): return log(green(\"PASS\"), ex_name, \"\") def check_classify(): ex_name = \"Classify\"",
"np.array([1]) T = 2 exp_res = (np.array([1, 2]), 1) if",
"is nothing better\"] try: res = p1.bag_of_words(texts) except NotImplementedError: log(red(\"FAIL\"),",
"not return a numpy array, type: \", type(res)) return if",
"y in zip(res, exp_res)): log(red(\"FAIL\"), ex_name, \": incorrect answer. Expected\",",
"True if not type(res) == tuple: log(red(\"FAIL\"), ex_name, \": does",
"return True if not type(res) == np.ndarray: log(red(\"FAIL\"), ex_name, \":",
"theta, theta_0 = 1, np.array([-1, 1]), -0.2 exp_res = 1",
"label, theta, theta_0 = 1, np.array([-1, 1]), -1 exp_res =",
"0 T=1 L=0.2 if check_tuple( ex_name, p1.classifier_accuracy, exp_res, p1.pegasos, train_feature_matrix,",
"check_hinge_loss_full() check_perceptron_single_update() check_perceptron() check_average_perceptron() check_pegasos_single_update() check_pegasos() check_classify() check_classifier_accuracy() check_bag_of_words() check_extract_bow_feature_vectors()",
"does not return a tuple, type: \", type(res)) return vals",
"= np.array([1, 1]) label, theta, theta_0 = 1, np.array([-1, 1]),",
"x == y def check_tuple(ex_name, f, exp_res, *args, **kwargs): try:",
"numpy array, type: \", type(res)) return if not len(res) ==",
"[1, 0], 2): log(\"You should revert `get_order` to its original",
"= np.array([[1, 2]]) labels = np.array([1]) T = 1 exp_res",
"\" (boundary case)\", p1.perceptron_single_step_update, exp_res, feature_vector, label, theta, theta_0): return",
"if not vals == exp_vals: log(red(\"FAIL\"), ex_name, \": wrong set",
"does not remove stopwords:\", [k for k in keys if",
"'he', 'is', 'loves', 'nothing', 'on', 'the', 'there', 'to', 'walk'] stop_keys",
"= ['beach', 'better', 'loves', 'nothing', 'walk'] if keys == exp_keys:",
"feature_vector = np.array([1, 2]) label, theta, theta_0 = 1, np.array([-1,",
"2]) label, theta, theta_0 = 1, np.array([-1, 1]), -1.5 exp_res",
"log(red(\"FAIL\"), ex_name, \": not implemented\") return if not type(res) ==",
"keys == exp_keys: log(yellow(\"WARN\"), ex_name, \": does not remove stopwords:\",",
"if check_real( ex_name, p1.hinge_loss_full, exp_res, feature_vector, label, theta, theta_0): return",
"if check_tuple( ex_name, p1.pegasos_single_step_update, exp_res, feature_vector, label, L, eta, theta,",
"1, np.array([-1, 1]), -2 L = 0.2 eta = 0.1",
"[[1, 1, 1, 0], [1, 1, 1, 2]]) try: res",
"np.array([1, 1]) T = 1 exp_res = (np.array([0, 2]), 2)",
"check_perceptron(): ex_name = \"Perceptron\" feature_matrix = np.array([[1, 2]]) labels =",
"\"Classify\" feature_matrix = np.array([[1, 1], [1, 1], [1, 1]]) theta",
"return log(green(\"PASS\"), ex_name, \"\") def check_classify(): ex_name = \"Classify\" feature_matrix",
"\": does not return a tuple, type: \", type(res)) return",
"= np.array([1, 1]), np.array([-1, 1]), -0.2 exp_res = 1 -",
"exp_vals = list(range(len(res.keys()))) if not vals == exp_vals: log(red(\"FAIL\"), ex_name,",
"return True if not type(res) == tuple: log(red(\"FAIL\"), ex_name, \":",
"T=1 if check_tuple( ex_name, p1.classifier_accuracy, exp_res, p1.perceptron, train_feature_matrix, val_feature_matrix, train_labels,",
"not in stop_keys]) elif keys == stop_keys: log(green(\"PASS\"), ex_name, \"",
"1 exp_res = (np.array([-0.5, 1]), 1.5) if check_tuple( ex_name, p1.average_perceptron,",
"len(exp_res): log(red(\"FAIL\"), ex_name, \": expected an array of shape \",",
"3]), -0.5) if check_tuple( ex_name, p1.perceptron_single_step_update, exp_res, feature_vector, label, theta,",
"if check_tuple( ex_name, p1.classifier_accuracy, exp_res, p1.pegasos, train_feature_matrix, val_feature_matrix, train_labels, val_labels,",
"= np.array([[1, 2], [-1, 0]]) labels = np.array([1, 1]) T",
"tuple, type: \", type(res)) return vals = sorted(res.values()) exp_vals =",
"keys are missing:\", [k for k in stop_keys if k",
"except NotImplementedError: log(red(\"FAIL\"), ex_name, \": not implemented\") return if not",
"exp_vals: log(red(\"FAIL\"), ex_name, \": wrong set of indices. Expected: \",",
"ex_name = \"Classify\" feature_matrix = np.array([[1, 1], [1, 1], [1,",
"enumerate(keys)} exp_res = np.array( [[1, 1, 1, 0], [1, 1,",
"1 exp_res = (np.array([0, 2]), 2) if check_tuple( ex_name, p1.perceptron,",
"2 exp_res = (np.array([1, 2]), 1) if check_tuple( ex_name, p1.perceptron,",
"1) if check_tuple( ex_name, p1.average_perceptron, exp_res, feature_matrix, labels, T): return",
"check_classify(): ex_name = \"Classify\" feature_matrix = np.array([[1, 1], [1, 1],",
"def check_perceptron(): ex_name = \"Perceptron\" feature_matrix = np.array([[1, 2]]) labels",
"number, type: \", type(res)) return True if res != exp_res:",
"== np.ndarray: return (x == y).all() return x == y",
"2 exp_res = (np.array([0, 2]), 2) if check_tuple( ex_name, p1.perceptron,",
"feature_matrix = np.array([[1, 1], [1, 1]]) labels = np.array([1, 1])",
"does not return a real number, type: \", type(res)) return",
"y): if type(y) == np.ndarray: return (x == y).all() return",
"ex_name, \"\") def check_perceptron(): ex_name = \"Perceptron\" feature_matrix = np.array([[1,",
"implemented\") return True if not np.isreal(res): log(red(\"FAIL\"), ex_name, \": does",
"check_tuple( ex_name, p1.classifier_accuracy, exp_res, p1.perceptron, train_feature_matrix, val_feature_matrix, train_labels, val_labels, T=T):",
"check_tuple( ex_name, p1.perceptron, exp_res, feature_matrix, labels, T): return log(green(\"PASS\"), ex_name,",
"np.array([1, 2]) label, theta, theta_0 = 1, np.array([-1, 1]), -2",
"ex_name, \"\") def check_pegasos(): ex_name = \"Pegasos\" feature_matrix = np.array([[1,",
"np.array([[1, 2]]) labels = np.array([1]) T = 2 exp_res =",
"= 2 exp_res = (np.array([0, 2]), 2) if check_tuple( ex_name,",
"= np.array([1, -1, 1]) val_labels = np.array([-1, 1]) exp_res =",
"log(green(\"PASS\"), ex_name, \"\") def check_perceptron(): ex_name = \"Perceptron\" feature_matrix =",
"L, eta, theta, theta_0): return feature_vector = np.array([1, 2]) label,",
"train_labels, val_labels, T=T, L=L): return log(green(\"PASS\"), ex_name, \"\") def check_bag_of_words():",
"log(yellow(\"WARN\"), ex_name, \": does not remove stopwords:\", [k for k",
"np.array([1, 1]) theta_0 = 0 exp_res = np.array([1, 1, 1])",
"1], [2, -1]]) train_labels = np.array([1, -1, 1]) val_labels =",
"check_list( ex_name, p1.get_order, [1, 0], 2): log(\"You should revert `get_order`",
"log(red(\"FAIL\"), ex_name, \": expected an array of shape \", exp_res.shape,",
"res) return True def check_get_order(): ex_name = \"Get order\" if",
"its original implementation for this test to pass\") return if",
"eta = 0.1 exp_res = (np.array([-0.88, 1.08]), 1.1) if check_tuple(",
"a real number, type: \", type(res)) return True if res",
"s def red(s): return '\\033[1;31m%s\\033[m' % s def log(*m): print(\"",
"def check_get_order(): ex_name = \"Get order\" if check_list( ex_name, p1.get_order,",
"= (np.array([0, 3]), -0.5) if check_tuple( ex_name, p1.perceptron_single_step_update, exp_res, feature_vector,",
"= (np.array([-0.25, 1.5]), 1.75) if check_tuple( ex_name, p1.average_perceptron, exp_res, feature_matrix,",
"exp_res = 1, 0 T=1 L=0.2 if check_tuple( ex_name, p1.classifier_accuracy,",
"return True def equals(x, y): if type(y) == np.ndarray: return",
"try: res = f(*args, **kwargs) except NotImplementedError: log(red(\"FAIL\"), ex_name, \":",
"missing:\", [k for k in stop_keys if k not in",
"[1, 1, 1, 2]]) try: res = p1.extract_bow_feature_vectors(texts, dictionary) except",
"if not len(res) == len(exp_res): log(red(\"FAIL\"), ex_name, \": expected an",
"implemented\") return True if not type(res) == tuple: log(red(\"FAIL\"), ex_name,",
"theta, theta_0): return log(green(\"PASS\"), ex_name, \"\") def check_pegasos(): ex_name =",
"keys == stop_keys: log(green(\"PASS\"), ex_name, \" stopwords removed\") else: log(red(\"FAIL\"),",
"= 1, np.array([-1, 1]), -2 L = 0.2 eta =",
"array, type: \", type(res)) return if not len(res) == len(exp_res):",
"correct non binary features\") else: log(red(\"FAIL\"), ex_name, \": unexpected feature",
"ex_name = \"Extract bow feature vectors\" texts = [ \"He",
"\": does not return a numpy array, type: \", type(res))",
"0 exp_res = np.array([1, 1, 1]) if check_array( ex_name, p1.classify,",
"if not all(equals(x, y) for x, y in zip(res, exp_res)):",
"a numpy array, type: \", type(res)) return True if not",
"\"Import project1\") try: check_get_order() check_hinge_loss_single() check_hinge_loss_full() check_perceptron_single_update() check_perceptron() check_average_perceptron() check_pegasos_single_update()",
"return feature_matrix = np.array([[1, 2]]) labels = np.array([1]) T =",
"does not return a list, type: \", type(res)) return True",
"if check_array( ex_name, p1.classify, exp_res, feature_matrix, theta, theta_0): return feature_matrix",
"not all(equals(x, y) for x, y in zip(res, exp_res)): log(red(\"FAIL\"),",
"import traceback import project1_Copy as p1 import numpy as np",
"theta = np.array([1, 1]) theta_0 = 0 exp_res = np.array([-1])",
"np.array([1, 1]) T = 1 L = 1 exp_res =",
"p1.bag_of_words(texts) except NotImplementedError: log(red(\"FAIL\"), ex_name, \": not implemented\") return if",
"ex_name, \": does not remove stopwords:\", [k for k in",
"k in stop_keys if k not in keys], \" or",
"exp_res, \", got: \", res) return True def equals(x, y):",
"== list: log(red(\"FAIL\"), ex_name, \": does not return a list,",
"= (np.array([0, 3]), 0) if check_tuple( ex_name + \" (boundary",
"= 0.1 exp_res = (np.array([-0.88, 1.18]), -1.4) if check_tuple( ex_name,",
"if keys == exp_keys: log(yellow(\"WARN\"), ex_name, \": does not remove",
"= \"Extract bow feature vectors\" texts = [ \"He loves",
"== tuple: log(red(\"FAIL\"), ex_name, \": does not return a tuple,",
"single update\" feature_vector = np.array([1, 2]) label, theta, theta_0 =",
"T = 1 exp_res = (np.array([1, 2]), 1) if check_tuple(",
"project1_Copy as p1 import numpy as np verbose = False",
"== len(exp_res): log(red(\"FAIL\"), ex_name, \": expected a list of size",
"check_real( ex_name, p1.hinge_loss_single, exp_res, feature_vector, label, theta, theta_0): return log(green(\"PASS\"),",
"log(green(\"PASS\"), ex_name, \"\") def check_hinge_loss_single(): ex_name = \"Hinge loss single\"",
"(res == non_bin_res).all(): log(green(\"PASS\"), ex_name, \": correct non binary features\")",
"import numpy as np verbose = False def green(s): return",
"feature_matrix, labels, T): return log(green(\"PASS\"), ex_name, \"\") def check_average_perceptron(): ex_name",
"= 1, np.array([-1, 1]), -0.2 exp_res = 1 - 0.8",
"= 0.2 eta = 0.1 exp_res = (np.array([-0.88, 1.08]), 1.1)",
"check_perceptron_single_update(): ex_name = \"Perceptron single update\" feature_vector = np.array([1, 2])",
"-1.9) if check_tuple( ex_name, p1.pegasos_single_step_update, exp_res, feature_vector, label, L, eta,",
"keys], \" or are not unexpected:\", [k for k in",
"revert `get_order` to its original implementation for this test to",
"not type(res) == np.ndarray: log(red(\"FAIL\"), ex_name, \": does not return",
"= \"Get order\" if check_list( ex_name, p1.get_order, [0], 1): log(\"You",
"def yellow(s): return '\\033[1;33m%s\\033[m' % s def red(s): return '\\033[1;31m%s\\033[m'",
"(x == y).all() return x == y def check_tuple(ex_name, f,",
"== len(exp_res): log(red(\"FAIL\"), ex_name, \": expected a tuple of size",
"not implemented\") return True if not type(res) == np.ndarray: log(red(\"FAIL\"),",
"0.1 exp_res = (np.array([-0.88, 1.18]), -1.9) if check_tuple( ex_name, p1.pegasos_single_step_update,",
"def main(): log(green(\"PASS\"), \"Import project1\") try: check_get_order() check_hinge_loss_single() check_hinge_loss_full() check_perceptron_single_update()",
"if check_tuple( ex_name + \" (boundary case)\", p1.pegasos_single_step_update, exp_res, feature_vector,",
"return log(green(\"PASS\"), ex_name, \"\") def check_pegasos(): ex_name = \"Pegasos\" feature_matrix",
"-1, 1]) val_labels = np.array([-1, 1]) exp_res = 1, 0",
"= {k:i for i, k in enumerate(keys)} exp_res = np.array(",
"for k in keys if k not in stop_keys]) elif",
"\": expected a tuple of size \", len(exp_res), \" but",
"2]) label, theta, theta_0 = 1, np.array([-1, 1]), -1 exp_res",
"i, k in enumerate(keys)} exp_res = np.array( [[1, 1, 1,",
"non binary features\") else: log(red(\"FAIL\"), ex_name, \": unexpected feature matrix\")",
"2]]) labels = np.array([1]) T = 1 exp_res = (np.array([1,",
"ex_name, \": not implemented\") return True if not type(res) ==",
"\", type(res)) return True if res != exp_res: log(red(\"FAIL\"), ex_name,",
"are not unexpected:\", [k for k in keys if k",
"return log(green(\"PASS\"), ex_name, \"\") def check_perceptron_single_update(): ex_name = \"Perceptron single",
"\"Hinge loss full\" feature_vector = np.array([[1, 2], [1, 2]]) label,",
"[1, -1], [2, 3]]) val_feature_matrix = np.array([[1, 1], [2, -1]])",
"log(green(\"PASS\"), ex_name, \"\") def check_pegasos_single_update(): ex_name = \"Pegasos single update\"",
"but got array of shape\", res.shape) return True if not",
"p1.pegasos_single_step_update, exp_res, feature_vector, label, L, eta, theta, theta_0): return log(green(\"PASS\"),",
"stop_keys]) elif keys == stop_keys: log(green(\"PASS\"), ex_name, \" stopwords removed\")",
"theta_0 = 1, np.array([-1, 1]), -0.2 exp_res = 1 -",
"sorted(res.values()) exp_vals = list(range(len(res.keys()))) if not vals == exp_vals: log(red(\"FAIL\"),",
"1, np.array([-1, 1]), -1.5 exp_res = (np.array([0, 3]), -0.5) if",
"a list of size \", len(exp_res), \" but got list",
"for this test to pass\") return log(green(\"PASS\"), ex_name, \"\") def",
"= np.array([[1, 1], [2, -1]]) train_labels = np.array([1, -1, 1])",
"got array of shape\", res.shape) return True if not all(equals(x,",
"exp_res = (np.array([1, 2]), 1) if check_tuple( ex_name, p1.pegasos, exp_res,",
"'to', 'walk'] stop_keys = ['beach', 'better', 'loves', 'nothing', 'walk'] if",
"list: log(red(\"FAIL\"), ex_name, \": does not return a list, type:",
"texts = [ \"He loves to walk on the beach\",",
"her \", \"He really really loves her\"] keys = [\"he\",",
"ex_name, \": uses binary indicators as features\") elif (res ==",
"y) for x, y in zip(res, exp_res)): log(red(\"FAIL\"), ex_name, \":",
"1.75) if check_tuple( ex_name, p1.average_perceptron, exp_res, feature_matrix, labels, T): return",
"res != exp_res: log(red(\"FAIL\"), ex_name, \": incorrect answer. Expected\", exp_res,",
"np.array([1, 1]) theta_0 = 0 exp_res = np.array([-1]) if check_array(",
"bow feature vectors\" texts = [ \"He loves her \",",
"= 1 - 0.8 if check_real( ex_name, p1.hinge_loss_single, exp_res, feature_vector,",
"exp_res, feature_matrix, labels, T): return log(green(\"PASS\"), ex_name, \"\") def check_average_perceptron():",
"got: \", res) return True def check_list(ex_name, f, exp_res, *args):",
"better\"] try: res = p1.bag_of_words(texts) except NotImplementedError: log(red(\"FAIL\"), ex_name, \":",
"not type(res) == dict: log(red(\"FAIL\"), ex_name, \": does not return",
"\", type(res)) return vals = sorted(res.values()) exp_vals = list(range(len(res.keys()))) if",
"ex_name, \": correct non binary features\") else: log(red(\"FAIL\"), ex_name, \":",
"= np.array([[1, 2]]) labels = np.array([1]) T = 2 exp_res",
"= np.array([1, 1]) T = 1 exp_res = (np.array([-0.5, 1]),",
"\", res) return True def check_list(ex_name, f, exp_res, *args): try:",
"in keys if k not in stop_keys]) elif keys ==",
"(np.array([-0.88, 1.08]), 1.1) if check_tuple( ex_name + \" (boundary case)\",",
"loves her\"] keys = [\"he\", \"loves\", \"her\", \"really\"] dictionary =",
"update\" feature_vector = np.array([1, 2]) label, theta, theta_0 = 1,",
"res = p1.extract_bow_feature_vectors(texts, dictionary) except NotImplementedError: log(red(\"FAIL\"), ex_name, \": not",
"red(s): return '\\033[1;31m%s\\033[m' % s def log(*m): print(\" \".join(map(str, m)))",
"exp_res = np.array( [[1, 1, 1, 0], [1, 1, 1,",
"def check_pegasos(): ex_name = \"Pegasos\" feature_matrix = np.array([[1, 2]]) labels",
"[1, 2]]) label, theta, theta_0 = np.array([1, 1]), np.array([-1, 1]),",
"a tuple, type: \", type(res)) return vals = sorted(res.values()) exp_vals",
"= np.array([1, 1]) theta_0 = 0 exp_res = np.array([1, 1,",
"= np.array([[1, 0], [1, -1], [2, 3]]) val_feature_matrix = np.array([[1,",
"True def equals(x, y): if type(y) == np.ndarray: return (x",
"f, exp_res, *args, **kwargs): try: res = f(*args, **kwargs) except",
"ex_name, \": does not return a tuple, type: \", type(res))",
"ex_name, \"\") def check_bag_of_words(): ex_name = \"Bag of words\" texts",
"\" (boundary case)\", p1.classify, exp_res, feature_matrix, theta, theta_0): return log(green(\"PASS\"),",
"1]]) non_bin_res = np.array( [[1, 1, 1, 0], [1, 1,",
"exp_res = (np.array([0, 3]), 0) if check_tuple( ex_name + \"",
"-0.2 exp_res = 1 - 0.8 if check_real( ex_name, p1.hinge_loss_single,",
"ex_name, \": does not return a list, type: \", type(res))",
"1): log(\"You should revert `get_order` to its original implementation for",
"\"He loves her \", \"He really really loves her\"] keys",
"(np.array([1, 2]), 1) if check_tuple( ex_name, p1.pegasos, exp_res, feature_matrix, labels,",
"labels = np.array([1, 1]) T = 2 exp_res = (np.array([0,",
"1]) exp_res = 1, 0 T=1 L=0.2 if check_tuple( ex_name,",
"not implemented\") return True if not np.isreal(res): log(red(\"FAIL\"), ex_name, \":",
"if k not in keys], \" or are not unexpected:\",",
"ex_name, \": expected a list of size \", len(exp_res), \"",
"**kwargs): try: res = f(*args, **kwargs) except NotImplementedError: log(red(\"FAIL\"), ex_name,",
"incorrect answer. Expected\", exp_res, \", got: \", res) return True",
"- 0.8 if check_real( ex_name, p1.hinge_loss_single, exp_res, feature_vector, label, theta,",
"\"\") def check_classify(): ex_name = \"Classify\" feature_matrix = np.array([[1, 1],",
"log(red(\"FAIL\"), ex_name, \": expected a list of size \", len(exp_res),",
"`get_order` to its original implementation for this test to pass\")",
"s def yellow(s): return '\\033[1;33m%s\\033[m' % s def red(s): return",
"def check_real(ex_name, f, exp_res, *args): try: res = f(*args) except",
"list of size \", len(exp_res), \" but got list of",
"\": not implemented\") return True if not np.isreal(res): log(red(\"FAIL\"), ex_name,",
"== exp_vals: log(red(\"FAIL\"), ex_name, \": wrong set of indices. Expected:",
"labels = np.array([1, 1]) T = 2 exp_res = (np.array([-0.25,",
"check_pegasos() check_classify() check_classifier_accuracy() check_bag_of_words() check_extract_bow_feature_vectors() except Exception: log_exit(traceback.format_exc()) if __name__",
"['beach', 'better', 'he', 'is', 'loves', 'nothing', 'on', 'the', 'there', 'to',",
"if check_tuple( ex_name, p1.average_perceptron, exp_res, feature_matrix, labels, T): return feature_matrix",
"= \"Classify\" feature_matrix = np.array([[1, 1], [1, 1], [1, 1]])",
"log(green(\"PASS\"), ex_name, \" stopwords removed\") else: log(red(\"FAIL\"), ex_name, \": keys",
"(np.array([1, 2]), 1) if check_tuple( ex_name, p1.perceptron, exp_res, feature_matrix, labels,",
"= (np.array([1, 2]), 1) if check_tuple( ex_name, p1.average_perceptron, exp_res, feature_matrix,",
"return feature_vector = np.array([1, 2]) label, theta, theta_0 = 1,",
"expected a tuple of size \", len(exp_res), \" but got",
"0) if check_tuple( ex_name + \" (boundary case)\", p1.perceptron_single_step_update, exp_res,",
"labels, T): return log(green(\"PASS\"), ex_name, \"\") def check_pegasos_single_update(): ex_name =",
"exp_res, feature_vector, label, L, eta, theta, theta_0): return feature_vector =",
"size \", len(exp_res), \" but got tuple of size\", len(res))",
"an array of shape \", exp_res.shape, \" but got array",
"ex_name = \"Hinge loss single\" feature_vector = np.array([1, 2]) label,",
"\"\") def check_hinge_loss_single(): ex_name = \"Hinge loss single\" feature_vector =",
"T): return log(green(\"PASS\"), ex_name, \"\") def check_average_perceptron(): ex_name = \"Average",
"ex_name, p1.average_perceptron, exp_res, feature_matrix, labels, T): return feature_matrix = np.array([[1,",
"[2, 3]]) val_feature_matrix = np.array([[1, 1], [2, -1]]) train_labels =",
"= \"Classifier accuracy\" train_feature_matrix = np.array([[1, 0], [1, -1], [2,",
"1, 1, 0], [1, 1, 1, 2]]) try: res =",
"log(*m): print(\" \".join(map(str, m))) def log_exit(*m): log(red(\"ERROR:\"), *m) exit(1) def",
"1]) val_labels = np.array([-1, 1]) exp_res = 1, 0 T=1",
"T=T): return train_feature_matrix = np.array([[1, 0], [1, -1], [2, 3]])",
"s def log(*m): print(\" \".join(map(str, m))) def log_exit(*m): log(red(\"ERROR:\"), *m)",
"check_tuple( ex_name, p1.pegasos_single_step_update, exp_res, feature_vector, label, L, eta, theta, theta_0):",
"stopwords:\", [k for k in keys if k not in",
"feature_matrix, labels, T): return feature_matrix = np.array([[1, 2], [-1, 0]])",
"T = 1 exp_res = (np.array([0, 2]), 2) if check_tuple(",
"does not return a tuple, type: \", type(res)) return True",
"log(red(\"FAIL\"), ex_name, \": expected a tuple of size \", len(exp_res),",
"def check_extract_bow_feature_vectors(): ex_name = \"Extract bow feature vectors\" texts =",
"log(green(\"PASS\"), ex_name, \": correct non binary features\") else: log(red(\"FAIL\"), ex_name,",
"if check_tuple( ex_name + \" (boundary case)\", p1.perceptron_single_step_update, exp_res, feature_vector,",
"test to pass\") return log(green(\"PASS\"), ex_name, \"\") def check_hinge_loss_single(): ex_name",
"L = 0.2 eta = 0.1 exp_res = (np.array([-0.88, 1.18]),",
"exp_res = (np.array([-0.88, 1.18]), -1.4) if check_tuple( ex_name, p1.pegasos_single_step_update, exp_res,",
"'on', 'the', 'there', 'to', 'walk'] stop_keys = ['beach', 'better', 'loves',",
"import project1_Copy as p1 import numpy as np verbose =",
"ex_name, p1.hinge_loss_single, exp_res, feature_vector, label, theta, theta_0): return log(green(\"PASS\"), ex_name,",
"ex_name, \"\") def check_perceptron_single_update(): ex_name = \"Perceptron single update\" feature_vector",
"3]), 0) if check_tuple( ex_name + \" (boundary case)\", p1.perceptron_single_step_update,",
"np.array([-1, 1]), -1.5 L = 0.2 eta = 0.1 exp_res",
"np.array([-1, 1]) exp_res = 1, 0 T=1 L=0.2 if check_tuple(",
"log(green(\"PASS\"), ex_name) if (res == exp_res).all(): log(yellow(\"WARN\"), ex_name, \": uses",
"= np.array([-1]) if check_array( ex_name + \" (boundary case)\", p1.classify,",
"*args): try: res = f(*args) except NotImplementedError: log(red(\"FAIL\"), ex_name, \":",
"not implemented\") return True if not type(res) == tuple: log(red(\"FAIL\"),",
"\"\") def check_pegasos_single_update(): ex_name = \"Pegasos single update\" feature_vector =",
"= np.array([[1, 1], [1, 1]]) labels = np.array([1, 1]) T",
"ex_name = \"Classifier accuracy\" train_feature_matrix = np.array([[1, 0], [1, -1],",
"return True def check_get_order(): ex_name = \"Get order\" if check_list(",
"np.array([1, 1, 1]) if check_array( ex_name, p1.classify, exp_res, feature_matrix, theta,",
"val_labels, T=T): return train_feature_matrix = np.array([[1, 0], [1, -1], [2,",
"\"He really really loves her\"] keys = [\"he\", \"loves\", \"her\",",
"theta, theta_0 = 1, np.array([-1, 1]), -2 L = 0.2",
"1) if check_tuple( ex_name, p1.perceptron, exp_res, feature_matrix, labels, T): return",
"res.shape) return log(green(\"PASS\"), ex_name) if (res == exp_res).all(): log(yellow(\"WARN\"), ex_name,",
"type(res) == tuple: log(red(\"FAIL\"), ex_name, \": does not return a",
"return log(green(\"PASS\"), ex_name, \"\") def check_bag_of_words(): ex_name = \"Bag of",
"def check_classifier_accuracy(): ex_name = \"Classifier accuracy\" train_feature_matrix = np.array([[1, 0],",
"\": not implemented\") return True if not type(res) == np.ndarray:",
"def check_bag_of_words(): ex_name = \"Bag of words\" texts = [",
"\", vals) return log(green(\"PASS\"), ex_name, \"\") keys = sorted(res.keys()) exp_keys",
"feature_matrix, labels, T): return log(green(\"PASS\"), ex_name, \"\") def check_pegasos_single_update(): ex_name",
"of shape\", res.shape) return True if not all(equals(x, y) for",
"exp_res, feature_matrix, labels, T): return log(green(\"PASS\"), ex_name, \"\") def check_pegasos_single_update():",
"\": keys are missing:\", [k for k in stop_keys if",
"if check_array( ex_name + \" (boundary case)\", p1.classify, exp_res, feature_matrix,",
"return log(green(\"PASS\"), ex_name) if (res == exp_res).all(): log(yellow(\"WARN\"), ex_name, \":",
"1]), -1.5 L = 0.2 eta = 0.1 exp_res =",
"theta, theta_0): return log(green(\"PASS\"), ex_name, \"\") def check_hinge_loss_full(): ex_name =",
"= 0 exp_res = np.array([-1]) if check_array( ex_name + \"",
"list, type: \", type(res)) return True if not len(res) ==",
"2], [-1, 0]]) labels = np.array([1, 1]) T = 1",
"labels = np.array([1, 1]) T = 1 exp_res = (np.array([-0.5,",
"= (np.array([1-1/np.sqrt(2), 1-1/np.sqrt(2)]), 1) if check_tuple( ex_name, p1.pegasos, exp_res, feature_matrix,",
"exp_res = 1, 0 T=1 if check_tuple( ex_name, p1.classifier_accuracy, exp_res,",
"['beach', 'better', 'loves', 'nothing', 'walk'] if keys == exp_keys: log(yellow(\"WARN\"),",
"project1\") try: check_get_order() check_hinge_loss_single() check_hinge_loss_full() check_perceptron_single_update() check_perceptron() check_average_perceptron() check_pegasos_single_update() check_pegasos()",
"ex_name, \"\") def check_hinge_loss_full(): ex_name = \"Hinge loss full\" feature_vector",
"feature_matrix, theta, theta_0): return feature_matrix = np.array([[-1, 1]]) theta =",
"log(green(\"PASS\"), ex_name, \"\") def check_hinge_loss_full(): ex_name = \"Hinge loss full\"",
"feature_matrix, labels, T, L): return feature_matrix = np.array([[1, 1], [1,",
"check_pegasos(): ex_name = \"Pegasos\" feature_matrix = np.array([[1, 2]]) labels =",
"not implemented\") return True if not type(res) == list: log(red(\"FAIL\"),",
"check_average_perceptron(): ex_name = \"Average perceptron\" feature_matrix = np.array([[1, 2]]) labels",
"type: \", type(res)) return True if not len(res) == len(exp_res):",
"log(red(\"FAIL\"), ex_name, \": does not return a tuple, type: \",",
"of size \", len(exp_res), \" but got tuple of size\",",
"\"\") def check_pegasos(): ex_name = \"Pegasos\" feature_matrix = np.array([[1, 2]])",
"np.array([1, 1]) label, theta, theta_0 = 1, np.array([-1, 1]), 1",
"ex_name = \"Perceptron\" feature_matrix = np.array([[1, 2]]) labels = np.array([1])",
"= 0 exp_res = np.array([1, 1, 1]) if check_array( ex_name,",
"log(red(\"FAIL\"), ex_name, \": keys are missing:\", [k for k in",
"elif (res == non_bin_res).all(): log(green(\"PASS\"), ex_name, \": correct non binary",
"for i, k in enumerate(keys)} exp_res = np.array( [[1, 1,",
"= np.array([1, 1]) theta_0 = 0 exp_res = np.array([-1]) if",
"ex_name + \" (boundary case)\", p1.pegasos_single_step_update, exp_res, feature_vector, label, L,",
"\"Bag of words\" texts = [ \"He loves to walk",
"implemented\") return True if not type(res) == np.ndarray: log(red(\"FAIL\"), ex_name,",
"'walk'] if keys == exp_keys: log(yellow(\"WARN\"), ex_name, \": does not",
"\", len(exp_res), \" but got tuple of size\", len(res)) return",
"log(\"You should revert `get_order` to its original implementation for this",
"\"\") def check_hinge_loss_full(): ex_name = \"Hinge loss full\" feature_vector =",
"p1.pegasos, exp_res, feature_matrix, labels, T, L): return feature_matrix = np.array([[1,",
"check_array( ex_name + \" (boundary case)\", p1.classify, exp_res, feature_matrix, theta,",
"False def green(s): return '\\033[1;32m%s\\033[m' % s def yellow(s): return",
"== np.ndarray: log(red(\"FAIL\"), ex_name, \": does not return a numpy",
"np.array([-1, 1]), -1.5 exp_res = (np.array([0, 3]), -0.5) if check_tuple(",
"= (np.array([1, 2]), 1) if check_tuple( ex_name, p1.perceptron, exp_res, feature_matrix,",
"label, theta, theta_0 = 1, np.array([-1, 1]), -0.2 exp_res =",
"p1.pegasos, train_feature_matrix, val_feature_matrix, train_labels, val_labels, T=T, L=L): return log(green(\"PASS\"), ex_name,",
"log(green(\"PASS\"), ex_name, \"\") def check_pegasos(): ex_name = \"Pegasos\" feature_matrix =",
"\"\") def check_perceptron_single_update(): ex_name = \"Perceptron single update\" feature_vector =",
"not return a real number, type: \", type(res)) return True",
"feature_vector = np.array([[1, 2], [1, 2]]) label, theta, theta_0 =",
"unexpected:\", [k for k in keys if k not in",
"return '\\033[1;31m%s\\033[m' % s def log(*m): print(\" \".join(map(str, m))) def",
"return log(green(\"PASS\"), ex_name, \"\") def check_pegasos_single_update(): ex_name = \"Pegasos single",
"check_real( ex_name, p1.hinge_loss_full, exp_res, feature_vector, label, theta, theta_0): return log(green(\"PASS\"),",
"0.2 eta = 0.1 exp_res = (np.array([-0.88, 1.08]), 1.1) if",
"ex_name, p1.get_order, [1, 0], 2): log(\"You should revert `get_order` to",
"def log(*m): print(\" \".join(map(str, m))) def log_exit(*m): log(red(\"ERROR:\"), *m) exit(1)",
"array of shape \", exp_res.shape, \" but got array of",
"p1.hinge_loss_full, exp_res, feature_vector, label, theta, theta_0): return log(green(\"PASS\"), ex_name, \"\")",
"check_real(ex_name, f, exp_res, *args): try: res = f(*args) except NotImplementedError:",
"p1.average_perceptron, exp_res, feature_matrix, labels, T): return log(green(\"PASS\"), ex_name, \"\") def",
"= 1 exp_res = (np.array([-0.5, 1]), 1.5) if check_tuple( ex_name,",
"np.array([-1, 1]), -0.2 exp_res = 1 - 0.8 if check_real(",
"ex_name, p1.classify, exp_res, feature_matrix, theta, theta_0): return feature_matrix = np.array([[-1,",
"log(green(\"PASS\"), \"Import project1\") try: check_get_order() check_hinge_loss_single() check_hinge_loss_full() check_perceptron_single_update() check_perceptron() check_average_perceptron()",
"= ['beach', 'better', 'he', 'is', 'loves', 'nothing', 'on', 'the', 'there',",
"np.array( [[1, 1, 1, 0], [1, 1, 1, 1]]) non_bin_res",
"\", res) return True def check_get_order(): ex_name = \"Get order\"",
"-1.5 exp_res = (np.array([0, 3]), -0.5) if check_tuple( ex_name, p1.perceptron_single_step_update,",
"of size\", len(res)) return True if not all(equals(x, y) for",
"\" stopwords removed\") else: log(red(\"FAIL\"), ex_name, \": keys are missing:\",",
"\"\") def check_bag_of_words(): ex_name = \"Bag of words\" texts =",
"if not type(res) == dict: log(red(\"FAIL\"), ex_name, \": does not",
"ex_name, p1.pegasos, exp_res, feature_matrix, labels, T, L): return log(green(\"PASS\"), ex_name,",
"really really loves her\"] keys = [\"he\", \"loves\", \"her\", \"really\"]",
"val_feature_matrix, train_labels, val_labels, T=T): return train_feature_matrix = np.array([[1, 0], [1,",
"= \"Pegasos single update\" feature_vector = np.array([1, 2]) label, theta,",
"type(res)) return True if res != exp_res: log(red(\"FAIL\"), ex_name, \":",
"theta_0): return log(green(\"PASS\"), ex_name, \"\") def check_hinge_loss_full(): ex_name = \"Hinge",
"return True if not all(equals(x, y) for x, y in",
"type(res) == dict: log(red(\"FAIL\"), ex_name, \": does not return a",
"verbose = False def green(s): return '\\033[1;32m%s\\033[m' % s def",
"= (np.array([1, 2]), 1) if check_tuple( ex_name, p1.pegasos, exp_res, feature_matrix,",
"len(res) == len(exp_res): log(red(\"FAIL\"), ex_name, \": expected an array of",
"T=1 L=0.2 if check_tuple( ex_name, p1.classifier_accuracy, exp_res, p1.pegasos, train_feature_matrix, val_feature_matrix,",
"remove stopwords:\", [k for k in keys if k not",
"if not type(res) == list: log(red(\"FAIL\"), ex_name, \": does not",
"type(res) == list: log(red(\"FAIL\"), ex_name, \": does not return a",
"def check_hinge_loss_full(): ex_name = \"Hinge loss full\" feature_vector = np.array([[1,",
"2]), 2) if check_tuple( ex_name, p1.perceptron, exp_res, feature_matrix, labels, T):",
"exp_res = (np.array([-0.88, 1.08]), 1.1) if check_tuple( ex_name + \"",
"theta, theta_0): return log(green(\"PASS\"), ex_name, \"\") def check_classifier_accuracy(): ex_name =",
"in keys if k not in stop_keys]) def check_extract_bow_feature_vectors(): ex_name",
"= np.array([-1, 1]) exp_res = 1, 0 T=1 L=0.2 if",
"1]), -0.2 exp_res = 1 - 0.8 if check_real( ex_name,",
"type: \", type(res)) return True if res != exp_res: log(red(\"FAIL\"),",
"val_labels = np.array([-1, 1]) exp_res = 1, 0 T=1 L=0.2",
"else: log(red(\"FAIL\"), ex_name, \": keys are missing:\", [k for k",
"ex_name, \": expected a tuple of size \", len(exp_res), \"",
"check_tuple( ex_name, p1.perceptron_single_step_update, exp_res, feature_vector, label, theta, theta_0): return feature_vector",
"feature_matrix = np.array([[1, 2]]) labels = np.array([1]) T = 1",
"f(*args, **kwargs) except NotImplementedError: log(red(\"FAIL\"), ex_name, \": not implemented\") return",
"\", got: \", res) return True def check_get_order(): ex_name =",
"== exp_res).all(): log(yellow(\"WARN\"), ex_name, \": uses binary indicators as features\")",
"check_perceptron_single_update() check_perceptron() check_average_perceptron() check_pegasos_single_update() check_pegasos() check_classify() check_classifier_accuracy() check_bag_of_words() check_extract_bow_feature_vectors() except",
"in zip(res, exp_res)): log(red(\"FAIL\"), ex_name, \": incorrect answer. Expected\", exp_res,",
"return if not type(res) == np.ndarray: log(red(\"FAIL\"), ex_name, \": does",
"theta, theta_0 = 1, np.array([-1, 1]), 1 L = 0.2",
"return feature_matrix = np.array([[1, 1], [1, 1]]) labels = np.array([1,",
"\": does not return a list, type: \", type(res)) return",
"ex_name = \"Perceptron single update\" feature_vector = np.array([1, 2]) label,",
"y).all() return x == y def check_tuple(ex_name, f, exp_res, *args,",
"check_tuple( ex_name, p1.average_perceptron, exp_res, feature_matrix, labels, T): return feature_matrix =",
"np.ndarray: return (x == y).all() return x == y def",
"% s def log(*m): print(\" \".join(map(str, m))) def log_exit(*m): log(red(\"ERROR:\"),",
"label, theta, theta_0 = np.array([1, 1]), np.array([-1, 1]), -0.2 exp_res",
"\" but got list of size\", len(res)) return True if",
"theta_0 = np.array([1, 1]), np.array([-1, 1]), -0.2 exp_res = 1",
"(np.array([-0.88, 1.18]), -1.9) if check_tuple( ex_name, p1.pegasos_single_step_update, exp_res, feature_vector, label,",
"2], [1, 2]]) label, theta, theta_0 = np.array([1, 1]), np.array([-1,",
"1 exp_res = (np.array([1-1/np.sqrt(2), 1-1/np.sqrt(2)]), 1) if check_tuple( ex_name, p1.pegasos,",
"p1.classify, exp_res, feature_matrix, theta, theta_0): return log(green(\"PASS\"), ex_name, \"\") def",
"[ \"He loves to walk on the beach\", \"There is",
"theta = np.array([1, 1]) theta_0 = 0 exp_res = np.array([1,",
"label, theta, theta_0): return log(green(\"PASS\"), ex_name, \"\") def check_perceptron_single_update(): ex_name",
"exp_res = np.array([-1]) if check_array( ex_name + \" (boundary case)\",",
"theta, theta_0): return feature_vector = np.array([1, 1]) label, theta, theta_0",
"log(green(\"PASS\"), ex_name, \"\") def check_classify(): ex_name = \"Classify\" feature_matrix =",
"return train_feature_matrix = np.array([[1, 0], [1, -1], [2, 3]]) val_feature_matrix",
"keys = sorted(res.keys()) exp_keys = ['beach', 'better', 'he', 'is', 'loves',",
"theta, theta_0 = np.array([1, 1]), np.array([-1, 1]), -0.2 exp_res =",
"check_classifier_accuracy(): ex_name = \"Classifier accuracy\" train_feature_matrix = np.array([[1, 0], [1,",
"T = 1 L = 1 exp_res = (np.array([1-1/np.sqrt(2), 1-1/np.sqrt(2)]),",
"check_tuple( ex_name, p1.pegasos, exp_res, feature_matrix, labels, T, L): return log(green(\"PASS\"),",
"= 1 - 0.8 if check_real( ex_name, p1.hinge_loss_full, exp_res, feature_vector,",
"vals == exp_vals: log(red(\"FAIL\"), ex_name, \": wrong set of indices.",
"(res == exp_res).all(): log(yellow(\"WARN\"), ex_name, \": uses binary indicators as",
"\", exp_res.shape, \" but got array of shape\", res.shape) return",
"feature_matrix = np.array([[1, 2]]) labels = np.array([1]) T = 2",
"= (np.array([-0.88, 1.18]), -1.4) if check_tuple( ex_name, p1.pegasos_single_step_update, exp_res, feature_vector,",
"got: \", res) return True def equals(x, y): if type(y)",
"log(green(\"PASS\"), ex_name, \"\") def check_classifier_accuracy(): ex_name = \"Classifier accuracy\" train_feature_matrix",
"check_bag_of_words(): ex_name = \"Bag of words\" texts = [ \"He",
"\": not implemented\") return if not type(res) == np.ndarray: log(red(\"FAIL\"),",
"1 L = 0.2 exp_res = (np.array([1, 2]), 1) if",
"res = p1.bag_of_words(texts) except NotImplementedError: log(red(\"FAIL\"), ex_name, \": not implemented\")",
"\": not implemented\") return True if not type(res) == tuple:",
"exp_res = (np.array([1, 2]), 1) if check_tuple( ex_name, p1.average_perceptron, exp_res,",
"ex_name, \": not implemented\") return True if not np.isreal(res): log(red(\"FAIL\"),",
"return True def check_list(ex_name, f, exp_res, *args): try: res =",
"T): return feature_matrix = np.array([[1, 2]]) labels = np.array([1]) T",
"ex_name, \": does not return a numpy array, type: \",",
"2]]) try: res = p1.extract_bow_feature_vectors(texts, dictionary) except NotImplementedError: log(red(\"FAIL\"), ex_name,",
"stop_keys]) def check_extract_bow_feature_vectors(): ex_name = \"Extract bow feature vectors\" texts",
"res) return True def equals(x, y): if type(y) == np.ndarray:",
"1, np.array([-1, 1]), -1.5 L = 0.2 eta = 0.1",
"stop_keys: log(green(\"PASS\"), ex_name, \" stopwords removed\") else: log(red(\"FAIL\"), ex_name, \":",
"= np.array([-1, 1]) exp_res = 1, 0 T=1 if check_tuple(",
"numpy as np verbose = False def green(s): return '\\033[1;32m%s\\033[m'",
"exp_res = 1 - 0.8 if check_real( ex_name, p1.hinge_loss_full, exp_res,",
"L, eta, theta, theta_0): return feature_vector = np.array([1, 1]) label,",
"T = 2 exp_res = (np.array([-0.25, 1.5]), 1.75) if check_tuple(",
"-2 L = 0.2 eta = 0.1 exp_res = (np.array([-0.88,",
"theta, theta_0): return feature_matrix = np.array([[-1, 1]]) theta = np.array([1,",
"in stop_keys if k not in keys], \" or are",
"if k not in stop_keys]) def check_extract_bow_feature_vectors(): ex_name = \"Extract",
"[[1, 1, 1, 0], [1, 1, 1, 1]]) non_bin_res =",
"features\") else: log(red(\"FAIL\"), ex_name, \": unexpected feature matrix\") return def",
"try: check_get_order() check_hinge_loss_single() check_hinge_loss_full() check_perceptron_single_update() check_perceptron() check_average_perceptron() check_pegasos_single_update() check_pegasos() check_classify()",
"= 1, np.array([-1, 1]), -1.5 L = 0.2 eta =",
"exp_res, feature_matrix, labels, T, L): return log(green(\"PASS\"), ex_name, \"\") def",
"theta_0 = 1, np.array([-1, 1]), 1 L = 0.2 eta",
"exp_res, feature_matrix, theta, theta_0): return feature_matrix = np.array([[-1, 1]]) theta",
"1], [1, 1]]) theta = np.array([1, 1]) theta_0 = 0",
"exp_res = (np.array([0, 3]), -0.5) if check_tuple( ex_name, p1.perceptron_single_step_update, exp_res,",
"ex_name, p1.perceptron, exp_res, feature_matrix, labels, T): return log(green(\"PASS\"), ex_name, \"\")",
"theta_0): return log(green(\"PASS\"), ex_name, \"\") def check_classifier_accuracy(): ex_name = \"Classifier",
"dictionary) except NotImplementedError: log(red(\"FAIL\"), ex_name, \": not implemented\") return if",
"+ \" (boundary case)\", p1.perceptron_single_step_update, exp_res, feature_vector, label, theta, theta_0):",
"not type(res) == tuple: log(red(\"FAIL\"), ex_name, \": does not return",
"theta_0 = 1, np.array([-1, 1]), -1.5 exp_res = (np.array([0, 3]),",
"labels, T, L): return feature_matrix = np.array([[1, 1], [1, 1]])",
"exp_res.shape, \" but got array of shape\", res.shape) return log(green(\"PASS\"),",
"type(res) == np.ndarray: log(red(\"FAIL\"), ex_name, \": does not return a",
"accuracy\" train_feature_matrix = np.array([[1, 0], [1, -1], [2, 3]]) val_feature_matrix",
"== exp_keys: log(yellow(\"WARN\"), ex_name, \": does not remove stopwords:\", [k",
"1, 2]]) try: res = p1.extract_bow_feature_vectors(texts, dictionary) except NotImplementedError: log(red(\"FAIL\"),",
"np.array([[1, 2], [-1, 0]]) labels = np.array([1, 1]) T =",
"np.array([-1, 1]), -1 exp_res = (np.array([0, 3]), 0) if check_tuple(",
"to pass\") return log(green(\"PASS\"), ex_name, \"\") def check_hinge_loss_single(): ex_name =",
"check_array(ex_name, f, exp_res, *args): try: res = f(*args) except NotImplementedError:",
"pass\") return log(green(\"PASS\"), ex_name, \"\") def check_hinge_loss_single(): ex_name = \"Hinge",
"train_feature_matrix, val_feature_matrix, train_labels, val_labels, T=T, L=L): return log(green(\"PASS\"), ex_name, \"\")",
"not remove stopwords:\", [k for k in keys if k",
"array of shape\", res.shape) return log(green(\"PASS\"), ex_name) if (res ==",
"exp_res = (np.array([-0.5, 1]), 1.5) if check_tuple( ex_name, p1.average_perceptron, exp_res,",
"return True if res != exp_res: log(red(\"FAIL\"), ex_name, \": incorrect",
"= f(*args, **kwargs) except NotImplementedError: log(red(\"FAIL\"), ex_name, \": not implemented\")",
"green(s): return '\\033[1;32m%s\\033[m' % s def yellow(s): return '\\033[1;33m%s\\033[m' %",
"np.array([1, 2]) label, theta, theta_0 = 1, np.array([-1, 1]), -1.5",
"labels = np.array([1]) T = 2 exp_res = (np.array([1, 2]),",
"keys = [\"he\", \"loves\", \"her\", \"really\"] dictionary = {k:i for",
"to pass\") return if check_list( ex_name, p1.get_order, [1, 0], 2):",
"ex_name, p1.perceptron, exp_res, feature_matrix, labels, T): return feature_matrix = np.array([[1,",
"feature_vector, label, theta, theta_0): return feature_vector = np.array([1, 2]) label,",
"a list, type: \", type(res)) return True if not len(res)",
"exp_res.shape, \" but got array of shape\", res.shape) return True",
"import os import sys import time import traceback import project1_Copy",
"def equals(x, y): if type(y) == np.ndarray: return (x ==",
"1]) label, theta, theta_0 = 1, np.array([-1, 1]), 1 L",
"L = 1 exp_res = (np.array([1-1/np.sqrt(2), 1-1/np.sqrt(2)]), 1) if check_tuple(",
"\"\") keys = sorted(res.keys()) exp_keys = ['beach', 'better', 'he', 'is',",
"in stop_keys]) elif keys == stop_keys: log(green(\"PASS\"), ex_name, \" stopwords",
"got: \", res) return True def check_array(ex_name, f, exp_res, *args):",
"= 1, np.array([-1, 1]), -1 exp_res = (np.array([0, 3]), 0)",
"= 1 exp_res = (np.array([1, 2]), 1) if check_tuple( ex_name,",
"ex_name = \"Pegasos single update\" feature_vector = np.array([1, 2]) label,",
"np.isreal(res): log(red(\"FAIL\"), ex_name, \": does not return a real number,",
"Expected\", exp_res, \", got: \", res) return True def equals(x,",
"(boundary case)\", p1.pegasos_single_step_update, exp_res, feature_vector, label, L, eta, theta, theta_0):",
"True def check_array(ex_name, f, exp_res, *args): try: res = f(*args)",
"loves her \", \"He really really loves her\"] keys =",
"[1, 1]]) theta = np.array([1, 1]) theta_0 = 0 exp_res",
"return log(green(\"PASS\"), ex_name, \"\") def check_hinge_loss_single(): ex_name = \"Hinge loss",
"non_bin_res).all(): log(green(\"PASS\"), ex_name, \": correct non binary features\") else: log(red(\"FAIL\"),",
"p1.perceptron, exp_res, feature_matrix, labels, T): return feature_matrix = np.array([[1, 2]])",
"def check_pegasos_single_update(): ex_name = \"Pegasos single update\" feature_vector = np.array([1,",
"(np.array([1-1/np.sqrt(2), 1-1/np.sqrt(2)]), 1) if check_tuple( ex_name, p1.pegasos, exp_res, feature_matrix, labels,",
"not len(res) == len(exp_res): log(red(\"FAIL\"), ex_name, \": expected an array",
"of words\" texts = [ \"He loves to walk on",
"= sorted(res.values()) exp_vals = list(range(len(res.keys()))) if not vals == exp_vals:",
"len(res) == len(exp_res): log(red(\"FAIL\"), ex_name, \": expected a list of",
"+ \" (boundary case)\", p1.classify, exp_res, feature_matrix, theta, theta_0): return",
"if type(y) == np.ndarray: return (x == y).all() return x",
"np.array([1, 1]) T = 2 exp_res = (np.array([-0.25, 1.5]), 1.75)",
"her\"] keys = [\"he\", \"loves\", \"her\", \"really\"] dictionary = {k:i",
"2]]) labels = np.array([1]) T = 2 exp_res = (np.array([1,",
"-1]]) train_labels = np.array([1, -1, 1]) val_labels = np.array([-1, 1])",
"ex_name = \"Get order\" if check_list( ex_name, p1.get_order, [0], 1):",
"val_labels, T=T, L=L): return log(green(\"PASS\"), ex_name, \"\") def check_bag_of_words(): ex_name",
"ex_name, \"\") def check_average_perceptron(): ex_name = \"Average perceptron\" feature_matrix =",
"!= exp_res: log(red(\"FAIL\"), ex_name, \": incorrect answer. Expected\", exp_res, \",",
"1]) T = 2 exp_res = (np.array([0, 2]), 2) if",
"yellow(s): return '\\033[1;33m%s\\033[m' % s def red(s): return '\\033[1;31m%s\\033[m' %",
"(boundary case)\", p1.classify, exp_res, feature_matrix, theta, theta_0): return log(green(\"PASS\"), ex_name,",
"feature_matrix, theta, theta_0): return log(green(\"PASS\"), ex_name, \"\") def check_classifier_accuracy(): ex_name",
"check_tuple( ex_name, p1.average_perceptron, exp_res, feature_matrix, labels, T): return log(green(\"PASS\"), ex_name,",
"'loves', 'nothing', 'on', 'the', 'there', 'to', 'walk'] stop_keys = ['beach',",
"1.08]), 1.1) if check_tuple( ex_name + \" (boundary case)\", p1.pegasos_single_step_update,",
"\": does not remove stopwords:\", [k for k in keys",
"return feature_vector = np.array([1, 1]) label, theta, theta_0 = 1,",
"return def main(): log(green(\"PASS\"), \"Import project1\") try: check_get_order() check_hinge_loss_single() check_hinge_loss_full()",
"True def check_get_order(): ex_name = \"Get order\" if check_list( ex_name,",
"True if res != exp_res: log(red(\"FAIL\"), ex_name, \": incorrect answer.",
"in enumerate(keys)} exp_res = np.array( [[1, 1, 1, 0], [1,",
"exp_res, feature_matrix, labels, T, L): return feature_matrix = np.array([[1, 1],",
"label, theta, theta_0): return log(green(\"PASS\"), ex_name, \"\") def check_hinge_loss_full(): ex_name",
"Expected\", exp_res, \", got: \", res) return True def check_get_order():",
"label, theta, theta_0 = 1, np.array([-1, 1]), 1 L =",
"0]]) labels = np.array([1, 1]) T = 1 exp_res =",
"\"her\", \"really\"] dictionary = {k:i for i, k in enumerate(keys)}",
"1, 1, 2]]) try: res = p1.extract_bow_feature_vectors(texts, dictionary) except NotImplementedError:",
"log(green(\"PASS\"), ex_name, \"\") def check_perceptron_single_update(): ex_name = \"Perceptron single update\"",
"for k in keys if k not in stop_keys]) def",
"check_average_perceptron() check_pegasos_single_update() check_pegasos() check_classify() check_classifier_accuracy() check_bag_of_words() check_extract_bow_feature_vectors() except Exception: log_exit(traceback.format_exc())",
"keys if k not in stop_keys]) elif keys == stop_keys:",
"a tuple of size \", len(exp_res), \" but got tuple",
"eta = 0.1 exp_res = (np.array([-0.88, 1.18]), -1.9) if check_tuple(",
"single\" feature_vector = np.array([1, 2]) label, theta, theta_0 = 1,",
"real number, type: \", type(res)) return True if res !=",
"\"There is nothing better\"] try: res = p1.bag_of_words(texts) except NotImplementedError:",
"return if not type(res) == dict: log(red(\"FAIL\"), ex_name, \": does",
"binary features\") else: log(red(\"FAIL\"), ex_name, \": unexpected feature matrix\") return",
"exp_res, \", got: \", res) return True def check_get_order(): ex_name",
"def red(s): return '\\033[1;31m%s\\033[m' % s def log(*m): print(\" \".join(map(str,",
"stop_keys = ['beach', 'better', 'loves', 'nothing', 'walk'] if keys ==",
"= [ \"He loves her \", \"He really really loves",
"np.array([-1, 1]), -2 L = 0.2 eta = 0.1 exp_res",
"check_list(ex_name, f, exp_res, *args): try: res = f(*args) except NotImplementedError:",
"1 - 0.8 if check_real( ex_name, p1.hinge_loss_single, exp_res, feature_vector, label,",
"texts = [ \"He loves her \", \"He really really",
"p1.perceptron, exp_res, feature_matrix, labels, T): return log(green(\"PASS\"), ex_name, \"\") def",
"1 L = 0.2 eta = 0.1 exp_res = (np.array([-0.88,",
"= np.array([1]) T = 1 L = 0.2 exp_res =",
"log(green(\"PASS\"), ex_name, \"\") def check_bag_of_words(): ex_name = \"Bag of words\"",
"log(red(\"FAIL\"), ex_name, \": does not return a real number, type:",
"but got array of shape\", res.shape) return log(green(\"PASS\"), ex_name) if",
"0], [1, -1], [2, 3]]) val_feature_matrix = np.array([[1, 1], [2,",
"ex_name, \" stopwords removed\") else: log(red(\"FAIL\"), ex_name, \": keys are",
"m))) def log_exit(*m): log(red(\"ERROR:\"), *m) exit(1) def check_real(ex_name, f, exp_res,",
"exp_res = (np.array([-0.25, 1.5]), 1.75) if check_tuple( ex_name, p1.average_perceptron, exp_res,",
"f, exp_res, *args): try: res = f(*args) except NotImplementedError: log(red(\"FAIL\"),",
"1]) T = 1 exp_res = (np.array([0, 2]), 2) if",
"eta, theta, theta_0): return feature_vector = np.array([1, 1]) label, theta,",
"check_pegasos_single_update() check_pegasos() check_classify() check_classifier_accuracy() check_bag_of_words() check_extract_bow_feature_vectors() except Exception: log_exit(traceback.format_exc()) if",
"ex_name + \" (boundary case)\", p1.perceptron_single_step_update, exp_res, feature_vector, label, theta,",
"\": expected a list of size \", len(exp_res), \" but",
"list(range(len(res.keys()))) if not vals == exp_vals: log(red(\"FAIL\"), ex_name, \": wrong",
"= np.array([[1, 1], [1, 1], [1, 1]]) theta = np.array([1,",
"ex_name, p1.pegasos, exp_res, feature_matrix, labels, T, L): return feature_matrix =",
"1]) theta_0 = 0 exp_res = np.array([-1]) if check_array( ex_name",
"on the beach\", \"There is nothing better\"] try: res =",
"'is', 'loves', 'nothing', 'on', 'the', 'there', 'to', 'walk'] stop_keys =",
"not implemented\") return if not type(res) == dict: log(red(\"FAIL\"), ex_name,",
"p1.perceptron, train_feature_matrix, val_feature_matrix, train_labels, val_labels, T=T): return train_feature_matrix = np.array([[1,",
"'loves', 'nothing', 'walk'] if keys == exp_keys: log(yellow(\"WARN\"), ex_name, \":",
"elif keys == stop_keys: log(green(\"PASS\"), ex_name, \" stopwords removed\") else:",
"y def check_tuple(ex_name, f, exp_res, *args, **kwargs): try: res =",
"return log(green(\"PASS\"), ex_name, \"\") keys = sorted(res.keys()) exp_keys = ['beach',",
"indices. Expected: \", exp_vals, \" got \", vals) return log(green(\"PASS\"),",
"= False def green(s): return '\\033[1;32m%s\\033[m' % s def yellow(s):",
"T): return log(green(\"PASS\"), ex_name, \"\") def check_pegasos_single_update(): ex_name = \"Pegasos",
"return x == y def check_tuple(ex_name, f, exp_res, *args, **kwargs):",
"return log(green(\"PASS\"), ex_name, \"\") def check_classifier_accuracy(): ex_name = \"Classifier accuracy\"",
"return (x == y).all() return x == y def check_tuple(ex_name,",
"ex_name, p1.classifier_accuracy, exp_res, p1.pegasos, train_feature_matrix, val_feature_matrix, train_labels, val_labels, T=T, L=L):",
"type(res)) return vals = sorted(res.values()) exp_vals = list(range(len(res.keys()))) if not",
"-1.5 L = 0.2 eta = 0.1 exp_res = (np.array([-0.88,",
"T, L): return feature_matrix = np.array([[1, 1], [1, 1]]) labels",
"L): return feature_matrix = np.array([[1, 1], [1, 1]]) labels =",
"== len(exp_res): log(red(\"FAIL\"), ex_name, \": expected an array of shape",
"train_labels, val_labels, T=T): return train_feature_matrix = np.array([[1, 0], [1, -1],",
"[k for k in stop_keys if k not in keys],",
"[-1, 0]]) labels = np.array([1, 1]) T = 1 exp_res",
"ex_name, \": wrong set of indices. Expected: \", exp_vals, \"",
"exp_res, p1.perceptron, train_feature_matrix, val_feature_matrix, train_labels, val_labels, T=T): return train_feature_matrix =",
"case)\", p1.perceptron_single_step_update, exp_res, feature_vector, label, theta, theta_0): return log(green(\"PASS\"), ex_name,",
"np.array([-1, 1]) exp_res = 1, 0 T=1 if check_tuple( ex_name,",
"words\" texts = [ \"He loves to walk on the",
"to walk on the beach\", \"There is nothing better\"] try:",
"= np.array([1]) T = 2 exp_res = (np.array([1, 2]), 1)",
"1]) T = 1 exp_res = (np.array([-0.5, 1]), 1.5) if",
"p1.perceptron_single_step_update, exp_res, feature_vector, label, theta, theta_0): return feature_vector = np.array([1,",
"(np.array([0, 2]), 2) if check_tuple( ex_name, p1.perceptron, exp_res, feature_matrix, labels,",
"2): log(\"You should revert `get_order` to its original implementation for",
"[1, 1]]) labels = np.array([1, 1]) T = 1 L",
"1], [1, 1]]) labels = np.array([1, 1]) T = 1",
"1.5) if check_tuple( ex_name, p1.average_perceptron, exp_res, feature_matrix, labels, T): return",
"= np.array([[1, 2]]) labels = np.array([1]) T = 1 L",
"Expected\", exp_res, \", got: \", res) return True def check_array(ex_name,",
"if not type(res) == np.ndarray: log(red(\"FAIL\"), ex_name, \": does not",
"if check_tuple( ex_name, p1.perceptron_single_step_update, exp_res, feature_vector, label, theta, theta_0): return",
"1.18]), -1.4) if check_tuple( ex_name, p1.pegasos_single_step_update, exp_res, feature_vector, label, L,",
"got array of shape\", res.shape) return log(green(\"PASS\"), ex_name) if (res",
"= np.array([1, 1]) T = 2 exp_res = (np.array([-0.25, 1.5]),",
"= 1 exp_res = (np.array([1-1/np.sqrt(2), 1-1/np.sqrt(2)]), 1) if check_tuple( ex_name,",
"f(*args) except NotImplementedError: log(red(\"FAIL\"), ex_name, \": not implemented\") return True",
"res = f(*args, **kwargs) except NotImplementedError: log(red(\"FAIL\"), ex_name, \": not",
"-1], [2, 3]]) val_feature_matrix = np.array([[1, 1], [2, -1]]) train_labels",
"% s def yellow(s): return '\\033[1;33m%s\\033[m' % s def red(s):",
"feature_vector, label, L, eta, theta, theta_0): return log(green(\"PASS\"), ex_name, \"\")",
"'there', 'to', 'walk'] stop_keys = ['beach', 'better', 'loves', 'nothing', 'walk']",
"= 0.2 eta = 0.1 exp_res = (np.array([-0.88, 1.18]), -1.9)",
"-1 exp_res = (np.array([0, 3]), 0) if check_tuple( ex_name +",
"label, L, eta, theta, theta_0): return feature_vector = np.array([1, 1])",
"\" (boundary case)\", p1.pegasos_single_step_update, exp_res, feature_vector, label, L, eta, theta,",
"return if check_list( ex_name, p1.get_order, [1, 0], 2): log(\"You should",
"[2, -1]]) train_labels = np.array([1, -1, 1]) val_labels = np.array([-1,",
"'better', 'he', 'is', 'loves', 'nothing', 'on', 'the', 'there', 'to', 'walk']",
"as features\") elif (res == non_bin_res).all(): log(green(\"PASS\"), ex_name, \": correct",
"ex_name, \"\") keys = sorted(res.keys()) exp_keys = ['beach', 'better', 'he',",
"feature vectors\" texts = [ \"He loves her \", \"He",
"= 2 exp_res = (np.array([1, 2]), 1) if check_tuple( ex_name,",
"= np.array([1, 2]) label, theta, theta_0 = 1, np.array([-1, 1]),",
"= \"Hinge loss full\" feature_vector = np.array([[1, 2], [1, 2]])",
"-0.5) if check_tuple( ex_name, p1.perceptron_single_step_update, exp_res, feature_vector, label, theta, theta_0):",
"[-1, 0]]) labels = np.array([1, 1]) T = 2 exp_res",
"'\\033[1;33m%s\\033[m' % s def red(s): return '\\033[1;31m%s\\033[m' % s def",
"except NotImplementedError: log(red(\"FAIL\"), ex_name, \": not implemented\") return True if",
"ex_name, \": unexpected feature matrix\") return def main(): log(green(\"PASS\"), \"Import",
"of shape \", exp_res.shape, \" but got array of shape\",",
"np.array([[1, 1], [1, 1], [1, 1]]) theta = np.array([1, 1])",
"type: \", type(res)) return vals = sorted(res.values()) exp_vals = list(range(len(res.keys())))",
"got \", vals) return log(green(\"PASS\"), ex_name, \"\") keys = sorted(res.keys())",
"k not in stop_keys]) def check_extract_bow_feature_vectors(): ex_name = \"Extract bow",
"full\" feature_vector = np.array([[1, 2], [1, 2]]) label, theta, theta_0",
"log(red(\"FAIL\"), ex_name, \": incorrect answer. Expected\", exp_res, \", got: \",",
"ex_name, p1.average_perceptron, exp_res, feature_matrix, labels, T): return log(green(\"PASS\"), ex_name, \"\")",
"*m) exit(1) def check_real(ex_name, f, exp_res, *args): try: res =",
"= list(range(len(res.keys()))) if not vals == exp_vals: log(red(\"FAIL\"), ex_name, \":",
"[\"he\", \"loves\", \"her\", \"really\"] dictionary = {k:i for i, k",
"ex_name, \": does not return a real number, type: \",",
"% s def red(s): return '\\033[1;31m%s\\033[m' % s def log(*m):",
"\"Perceptron single update\" feature_vector = np.array([1, 2]) label, theta, theta_0",
"of indices. Expected: \", exp_vals, \" got \", vals) return",
"original implementation for this test to pass\") return if check_list(",
"1 exp_res = (np.array([1, 2]), 1) if check_tuple( ex_name, p1.average_perceptron,",
"if check_tuple( ex_name, p1.perceptron, exp_res, feature_matrix, labels, T): return log(green(\"PASS\"),",
"= p1.extract_bow_feature_vectors(texts, dictionary) except NotImplementedError: log(red(\"FAIL\"), ex_name, \": not implemented\")",
"got list of size\", len(res)) return True if not all(equals(x,",
"list of size\", len(res)) return True if not all(equals(x, y)",
"3]]) val_feature_matrix = np.array([[1, 1], [2, -1]]) train_labels = np.array([1,",
"p1.perceptron, exp_res, feature_matrix, labels, T): return feature_matrix = np.array([[1, 2],",
"L = 0.2 eta = 0.1 exp_res = (np.array([-0.88, 1.08]),",
"2 exp_res = (np.array([-0.25, 1.5]), 1.75) if check_tuple( ex_name, p1.average_perceptron,",
"T = 1 L = 0.2 exp_res = (np.array([1, 2]),",
"labels = np.array([1]) T = 1 L = 0.2 exp_res",
"k not in keys], \" or are not unexpected:\", [k",
"1]]) theta = np.array([1, 1]) theta_0 = 0 exp_res =",
"k in keys if k not in stop_keys]) elif keys",
"def check_tuple(ex_name, f, exp_res, *args, **kwargs): try: res = f(*args,",
"implementation for this test to pass\") return if check_list( ex_name,",
"= 1 exp_res = (np.array([0, 2]), 2) if check_tuple( ex_name,",
"p1.extract_bow_feature_vectors(texts, dictionary) except NotImplementedError: log(red(\"FAIL\"), ex_name, \": not implemented\") return",
"check_classifier_accuracy() check_bag_of_words() check_extract_bow_feature_vectors() except Exception: log_exit(traceback.format_exc()) if __name__ == \"__main__\":",
"check_perceptron() check_average_perceptron() check_pegasos_single_update() check_pegasos() check_classify() check_classifier_accuracy() check_bag_of_words() check_extract_bow_feature_vectors() except Exception:",
"np.array([1, 1]) T = 2 exp_res = (np.array([0, 2]), 2)",
"\": incorrect answer. Expected\", exp_res, \", got: \", res) return",
"k in enumerate(keys)} exp_res = np.array( [[1, 1, 1, 0],",
"1, 1, 0], [1, 1, 1, 1]]) non_bin_res = np.array(",
"return a real number, type: \", type(res)) return True if",
"feature matrix\") return def main(): log(green(\"PASS\"), \"Import project1\") try: check_get_order()",
"len(res) == len(exp_res): log(red(\"FAIL\"), ex_name, \": expected a tuple of",
"feature_matrix, labels, T, L): return log(green(\"PASS\"), ex_name, \"\") def check_classify():",
"0], 2): log(\"You should revert `get_order` to its original implementation",
"\".join(map(str, m))) def log_exit(*m): log(red(\"ERROR:\"), *m) exit(1) def check_real(ex_name, f,",
"np.array([1, 2]) label, theta, theta_0 = 1, np.array([-1, 1]), -1",
"L, eta, theta, theta_0): return log(green(\"PASS\"), ex_name, \"\") def check_pegasos():",
"not in stop_keys]) def check_extract_bow_feature_vectors(): ex_name = \"Extract bow feature",
"uses binary indicators as features\") elif (res == non_bin_res).all(): log(green(\"PASS\"),",
"0.8 if check_real( ex_name, p1.hinge_loss_full, exp_res, feature_vector, label, theta, theta_0):",
"stop_keys if k not in keys], \" or are not",
"'nothing', 'on', 'the', 'there', 'to', 'walk'] stop_keys = ['beach', 'better',",
"2]]) labels = np.array([1]) T = 1 L = 0.2",
"1]) exp_res = 1, 0 T=1 if check_tuple( ex_name, p1.classifier_accuracy,",
"original implementation for this test to pass\") return log(green(\"PASS\"), ex_name,",
"\", got: \", res) return True def check_list(ex_name, f, exp_res,",
"try: res = p1.bag_of_words(texts) except NotImplementedError: log(red(\"FAIL\"), ex_name, \": not",
"\": unexpected feature matrix\") return def main(): log(green(\"PASS\"), \"Import project1\")",
"np.array([[1, 1], [2, -1]]) train_labels = np.array([1, -1, 1]) val_labels",
"ex_name, \": incorrect answer. Expected\", exp_res, \", got: \", res)",
"1]), np.array([-1, 1]), -0.2 exp_res = 1 - 0.8 if",
"1.5]), 1.75) if check_tuple( ex_name, p1.average_perceptron, exp_res, feature_matrix, labels, T):",
"L=L): return log(green(\"PASS\"), ex_name, \"\") def check_bag_of_words(): ex_name = \"Bag",
"= p1.bag_of_words(texts) except NotImplementedError: log(red(\"FAIL\"), ex_name, \": not implemented\") return",
"0.2 exp_res = (np.array([1, 2]), 1) if check_tuple( ex_name, p1.pegasos,",
"for x, y in zip(res, exp_res)): log(red(\"FAIL\"), ex_name, \": incorrect",
"implemented\") return True if not type(res) == list: log(red(\"FAIL\"), ex_name,",
"import time import traceback import project1_Copy as p1 import numpy",
"2]) label, theta, theta_0 = 1, np.array([-1, 1]), -1.5 L",
"T): return feature_matrix = np.array([[1, 2], [-1, 0]]) labels =",
"exp_res = (np.array([-0.88, 1.18]), -1.9) if check_tuple( ex_name, p1.pegasos_single_step_update, exp_res,",
"def log_exit(*m): log(red(\"ERROR:\"), *m) exit(1) def check_real(ex_name, f, exp_res, *args):",
"[1, 1, 1, 1]]) non_bin_res = np.array( [[1, 1, 1,",
"len(res)) return True if not all(equals(x, y) for x, y",
"ex_name = \"Average perceptron\" feature_matrix = np.array([[1, 2]]) labels =",
"feature_matrix = np.array([[1, 2], [-1, 0]]) labels = np.array([1, 1])",
"else: log(red(\"FAIL\"), ex_name, \": unexpected feature matrix\") return def main():",
"dict: log(red(\"FAIL\"), ex_name, \": does not return a tuple, type:",
"2], [-1, 0]]) labels = np.array([1, 1]) T = 2",
"1 - 0.8 if check_real( ex_name, p1.hinge_loss_full, exp_res, feature_vector, label,",
"check_hinge_loss_single(): ex_name = \"Hinge loss single\" feature_vector = np.array([1, 2])",
"1 L = 1 exp_res = (np.array([1-1/np.sqrt(2), 1-1/np.sqrt(2)]), 1) if",
"{k:i for i, k in enumerate(keys)} exp_res = np.array( [[1,",
"def check_average_perceptron(): ex_name = \"Average perceptron\" feature_matrix = np.array([[1, 2]])",
"expected an array of shape \", exp_res.shape, \" but got",
"eta, theta, theta_0): return feature_vector = np.array([1, 2]) label, theta,"
] |
[
"`file_content` inside, where `file_name` == `file.name`. Passes test if `find_maximum_and_minimum`(`file.name`)",
"for module `homework_1.tasks.task_3`. \"\"\" from tempfile import NamedTemporaryFile from typing",
"), pytest.param( \"1\\n2\\n3\\n4\\n5\\n\", (1, 5), id=\"'1\\n2\\n3\\n4\\n5\\n', result is (1, 5).\",",
"`file.name`. Passes test if `find_maximum_and_minimum`(`file.name`) is equal to `expected_result`. \"\"\"",
"(1, 5).\", ), pytest.param( \"1\\n-2\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n11\\n-12\\n\", (-12, 11), id=\"'1\\n-2\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n11\\n-12\\n', result: (11,-12).\",",
"\"11\\n-12\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n1\\n-2\\n\", (-12, 11), id=\"'11\\n-12\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n1\\n-2\\n', result: (11,-12).\", ), pytest.param( \"\\n\".join(str(num) for",
"(11,-12).\", ), pytest.param( \"\\n\".join(str(num) for num in range(0, 667000)), (0,",
"pytest.param( \"11\\n-12\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n1\\n-2\\n\", (-12, 11), id=\"'11\\n-12\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n1\\n-2\\n', result: (11,-12).\", ), pytest.param( \"\\n\".join(str(num)",
"id=\"'0\\n', result is (0, 0).\", ), pytest.param( \"1\\n2\\n3\\n4\\n5\\n\", (1, 5),",
"11), id=\"'1\\n-2\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n11\\n-12\\n', result: (11,-12).\", ), pytest.param( \"11\\n-12\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n1\\n-2\\n\", (-12, 11), id=\"'11\\n-12\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n1\\n-2\\n',",
"'\\n'.\", ), ], ) def test_find_maximum_and_minimum(file_content: str, expected_result: Tuple[int, int]):",
"Passes test if `find_maximum_and_minimum`(`file.name`) is equal to `expected_result`. \"\"\" with",
"pytest.param( \"1\\n2\\n3\\n4\\n5\\n\", (1, 5), id=\"'1\\n2\\n3\\n4\\n5\\n', result is (1, 5).\", ),",
"id=\"'1\\n2\\n3\\n4\\n5\\n', result is (1, 5).\", ), pytest.param( \"1\\n-2\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n11\\n-12\\n\", (-12, 11),",
"result: (11,-12).\", ), pytest.param( \"\\n\".join(str(num) for num in range(0, 667000)),",
"test if `find_maximum_and_minimum`(`file.name`) is equal to `expected_result`. \"\"\" with NamedTemporaryFile(mode=\"wt\")",
"\"1\\n2\\n3\\n4\\n5\\n\", (1, 5), id=\"'1\\n2\\n3\\n4\\n5\\n', result is (1, 5).\", ), pytest.param(",
"file using `NamedTemporaryFile` instance with writed `file_content` inside, where `file_name`",
"5).\", ), pytest.param( \"1\\n-2\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n11\\n-12\\n\", (-12, 11), id=\"'1\\n-2\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n11\\n-12\\n', result: (11,-12).\", ),",
"instance with writed `file_content` inside, where `file_name` == `file.name`. Passes",
"with NamedTemporaryFile(mode=\"wt\") as file: file.write(file_content) file.seek(0) assert find_maximum_and_minimum(file.name) == expected_result",
"expected_result: Tuple[int, int]): \"\"\" Mocks file using `NamedTemporaryFile` instance with",
"find_maximum_and_minimum @pytest.mark.parametrize( [\"file_content\", \"expected_result\"], [ pytest.param( \"0\\n\", (0, 0), id=\"'0\\n',",
"pytest.param( \"\\n\".join(str(num) for num in range(0, 667000)), (0, 666999), id=\"Integers",
"), pytest.param( \"1\\n-2\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n11\\n-12\\n\", (-12, 11), id=\"'1\\n-2\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n11\\n-12\\n', result: (11,-12).\", ), pytest.param(",
"0 to 666999 delimited by '\\n'.\", ), ], ) def",
"delimited by '\\n'.\", ), ], ) def test_find_maximum_and_minimum(file_content: str, expected_result:",
"in range(0, 667000)), (0, 666999), id=\"Integers from 0 to 666999",
"is equal to `expected_result`. \"\"\" with NamedTemporaryFile(mode=\"wt\") as file: file.write(file_content)",
"0).\", ), pytest.param( \"1\\n2\\n3\\n4\\n5\\n\", (1, 5), id=\"'1\\n2\\n3\\n4\\n5\\n', result is (1,",
"import NamedTemporaryFile from typing import Tuple import pytest from homework_1.tasks.task_3",
"def test_find_maximum_and_minimum(file_content: str, expected_result: Tuple[int, int]): \"\"\" Mocks file using",
"writed `file_content` inside, where `file_name` == `file.name`. Passes test if",
"666999), id=\"Integers from 0 to 666999 delimited by '\\n'.\", ),",
"Unit tests for module `homework_1.tasks.task_3`. \"\"\" from tempfile import NamedTemporaryFile",
"\"\\n\".join(str(num) for num in range(0, 667000)), (0, 666999), id=\"Integers from",
"for num in range(0, 667000)), (0, 666999), id=\"Integers from 0",
"range(0, 667000)), (0, 666999), id=\"Integers from 0 to 666999 delimited",
"(11,-12).\", ), pytest.param( \"11\\n-12\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n1\\n-2\\n\", (-12, 11), id=\"'11\\n-12\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n1\\n-2\\n', result: (11,-12).\", ),",
"to `expected_result`. \"\"\" with NamedTemporaryFile(mode=\"wt\") as file: file.write(file_content) file.seek(0) assert",
"[\"file_content\", \"expected_result\"], [ pytest.param( \"0\\n\", (0, 0), id=\"'0\\n', result is",
"to 666999 delimited by '\\n'.\", ), ], ) def test_find_maximum_and_minimum(file_content:",
"`NamedTemporaryFile` instance with writed `file_content` inside, where `file_name` == `file.name`.",
"`homework_1.tasks.task_3`. \"\"\" from tempfile import NamedTemporaryFile from typing import Tuple",
"pytest from homework_1.tasks.task_3 import find_maximum_and_minimum @pytest.mark.parametrize( [\"file_content\", \"expected_result\"], [ pytest.param(",
"(-12, 11), id=\"'11\\n-12\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n1\\n-2\\n', result: (11,-12).\", ), pytest.param( \"\\n\".join(str(num) for num",
"0), id=\"'0\\n', result is (0, 0).\", ), pytest.param( \"1\\n2\\n3\\n4\\n5\\n\", (1,",
"(0, 666999), id=\"Integers from 0 to 666999 delimited by '\\n'.\",",
"\"0\\n\", (0, 0), id=\"'0\\n', result is (0, 0).\", ), pytest.param(",
"11), id=\"'11\\n-12\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n1\\n-2\\n', result: (11,-12).\", ), pytest.param( \"\\n\".join(str(num) for num in",
"inside, where `file_name` == `file.name`. Passes test if `find_maximum_and_minimum`(`file.name`) is",
"Mocks file using `NamedTemporaryFile` instance with writed `file_content` inside, where",
"from tempfile import NamedTemporaryFile from typing import Tuple import pytest",
"), pytest.param( \"11\\n-12\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n1\\n-2\\n\", (-12, 11), id=\"'11\\n-12\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n1\\n-2\\n', result: (11,-12).\", ), pytest.param(",
"id=\"'11\\n-12\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n1\\n-2\\n', result: (11,-12).\", ), pytest.param( \"\\n\".join(str(num) for num in range(0,",
"], ) def test_find_maximum_and_minimum(file_content: str, expected_result: Tuple[int, int]): \"\"\" Mocks",
"Tuple[int, int]): \"\"\" Mocks file using `NamedTemporaryFile` instance with writed",
"[ pytest.param( \"0\\n\", (0, 0), id=\"'0\\n', result is (0, 0).\",",
"(1, 5), id=\"'1\\n2\\n3\\n4\\n5\\n', result is (1, 5).\", ), pytest.param( \"1\\n-2\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n11\\n-12\\n\",",
"\"\"\" from tempfile import NamedTemporaryFile from typing import Tuple import",
"if `find_maximum_and_minimum`(`file.name`) is equal to `expected_result`. \"\"\" with NamedTemporaryFile(mode=\"wt\") as",
"using `NamedTemporaryFile` instance with writed `file_content` inside, where `file_name` ==",
"(-12, 11), id=\"'1\\n-2\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n11\\n-12\\n', result: (11,-12).\", ), pytest.param( \"11\\n-12\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n1\\n-2\\n\", (-12, 11),",
"`file_name` == `file.name`. Passes test if `find_maximum_and_minimum`(`file.name`) is equal to",
"from homework_1.tasks.task_3 import find_maximum_and_minimum @pytest.mark.parametrize( [\"file_content\", \"expected_result\"], [ pytest.param( \"0\\n\",",
"equal to `expected_result`. \"\"\" with NamedTemporaryFile(mode=\"wt\") as file: file.write(file_content) file.seek(0)",
"5), id=\"'1\\n2\\n3\\n4\\n5\\n', result is (1, 5).\", ), pytest.param( \"1\\n-2\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n11\\n-12\\n\", (-12,",
"is (0, 0).\", ), pytest.param( \"1\\n2\\n3\\n4\\n5\\n\", (1, 5), id=\"'1\\n2\\n3\\n4\\n5\\n', result",
"num in range(0, 667000)), (0, 666999), id=\"Integers from 0 to",
"is (1, 5).\", ), pytest.param( \"1\\n-2\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n11\\n-12\\n\", (-12, 11), id=\"'1\\n-2\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n11\\n-12\\n', result:",
"from typing import Tuple import pytest from homework_1.tasks.task_3 import find_maximum_and_minimum",
") def test_find_maximum_and_minimum(file_content: str, expected_result: Tuple[int, int]): \"\"\" Mocks file",
"test_find_maximum_and_minimum(file_content: str, expected_result: Tuple[int, int]): \"\"\" Mocks file using `NamedTemporaryFile`",
"id=\"'1\\n-2\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n11\\n-12\\n', result: (11,-12).\", ), pytest.param( \"11\\n-12\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n1\\n-2\\n\", (-12, 11), id=\"'11\\n-12\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n1\\n-2\\n', result:",
"result: (11,-12).\", ), pytest.param( \"11\\n-12\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n1\\n-2\\n\", (-12, 11), id=\"'11\\n-12\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n1\\n-2\\n', result: (11,-12).\",",
"result is (1, 5).\", ), pytest.param( \"1\\n-2\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n11\\n-12\\n\", (-12, 11), id=\"'1\\n-2\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n11\\n-12\\n',",
"id=\"Integers from 0 to 666999 delimited by '\\n'.\", ), ],",
"module `homework_1.tasks.task_3`. \"\"\" from tempfile import NamedTemporaryFile from typing import",
"by '\\n'.\", ), ], ) def test_find_maximum_and_minimum(file_content: str, expected_result: Tuple[int,",
"from 0 to 666999 delimited by '\\n'.\", ), ], )",
"@pytest.mark.parametrize( [\"file_content\", \"expected_result\"], [ pytest.param( \"0\\n\", (0, 0), id=\"'0\\n', result",
"(0, 0).\", ), pytest.param( \"1\\n2\\n3\\n4\\n5\\n\", (1, 5), id=\"'1\\n2\\n3\\n4\\n5\\n', result is",
"), ], ) def test_find_maximum_and_minimum(file_content: str, expected_result: Tuple[int, int]): \"\"\"",
"str, expected_result: Tuple[int, int]): \"\"\" Mocks file using `NamedTemporaryFile` instance",
"\"expected_result\"], [ pytest.param( \"0\\n\", (0, 0), id=\"'0\\n', result is (0,",
"`find_maximum_and_minimum`(`file.name`) is equal to `expected_result`. \"\"\" with NamedTemporaryFile(mode=\"wt\") as file:",
"), pytest.param( \"\\n\".join(str(num) for num in range(0, 667000)), (0, 666999),",
"import pytest from homework_1.tasks.task_3 import find_maximum_and_minimum @pytest.mark.parametrize( [\"file_content\", \"expected_result\"], [",
"\"\"\" Mocks file using `NamedTemporaryFile` instance with writed `file_content` inside,",
"\"\"\" with NamedTemporaryFile(mode=\"wt\") as file: file.write(file_content) file.seek(0) assert find_maximum_and_minimum(file.name) ==",
"tests for module `homework_1.tasks.task_3`. \"\"\" from tempfile import NamedTemporaryFile from",
"\"\"\" Unit tests for module `homework_1.tasks.task_3`. \"\"\" from tempfile import",
"homework_1.tasks.task_3 import find_maximum_and_minimum @pytest.mark.parametrize( [\"file_content\", \"expected_result\"], [ pytest.param( \"0\\n\", (0,",
"== `file.name`. Passes test if `find_maximum_and_minimum`(`file.name`) is equal to `expected_result`.",
"typing import Tuple import pytest from homework_1.tasks.task_3 import find_maximum_and_minimum @pytest.mark.parametrize(",
"import Tuple import pytest from homework_1.tasks.task_3 import find_maximum_and_minimum @pytest.mark.parametrize( [\"file_content\",",
"pytest.param( \"0\\n\", (0, 0), id=\"'0\\n', result is (0, 0).\", ),",
"(0, 0), id=\"'0\\n', result is (0, 0).\", ), pytest.param( \"1\\n2\\n3\\n4\\n5\\n\",",
"`expected_result`. \"\"\" with NamedTemporaryFile(mode=\"wt\") as file: file.write(file_content) file.seek(0) assert find_maximum_and_minimum(file.name)",
"tempfile import NamedTemporaryFile from typing import Tuple import pytest from",
"result is (0, 0).\", ), pytest.param( \"1\\n2\\n3\\n4\\n5\\n\", (1, 5), id=\"'1\\n2\\n3\\n4\\n5\\n',",
"where `file_name` == `file.name`. Passes test if `find_maximum_and_minimum`(`file.name`) is equal",
"int]): \"\"\" Mocks file using `NamedTemporaryFile` instance with writed `file_content`",
"with writed `file_content` inside, where `file_name` == `file.name`. Passes test",
"import find_maximum_and_minimum @pytest.mark.parametrize( [\"file_content\", \"expected_result\"], [ pytest.param( \"0\\n\", (0, 0),",
"NamedTemporaryFile from typing import Tuple import pytest from homework_1.tasks.task_3 import",
"666999 delimited by '\\n'.\", ), ], ) def test_find_maximum_and_minimum(file_content: str,",
"Tuple import pytest from homework_1.tasks.task_3 import find_maximum_and_minimum @pytest.mark.parametrize( [\"file_content\", \"expected_result\"],",
"pytest.param( \"1\\n-2\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n11\\n-12\\n\", (-12, 11), id=\"'1\\n-2\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n11\\n-12\\n', result: (11,-12).\", ), pytest.param( \"11\\n-12\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n1\\n-2\\n\",",
"\"1\\n-2\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n11\\n-12\\n\", (-12, 11), id=\"'1\\n-2\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n11\\n-12\\n', result: (11,-12).\", ), pytest.param( \"11\\n-12\\n3\\n-4\\n5\\n-6\\n7\\n-8\\n9\\n-10\\n1\\n-2\\n\", (-12,",
"667000)), (0, 666999), id=\"Integers from 0 to 666999 delimited by"
] |
[
"# coding:utf-8 import app.admin.views.start import app.admin.views.book import app.admin.views.user import app.admin.views.site"
] |
[
"_, test = chainer.datasets.get_mnist(ndim=3) test_data, test_label = test._datasets # テストデータを学習した低次元空間(2次元)に写像",
"model.forward_once(test_data) feat = y.data # ラベルごとに描画 c = ['#ff0000', '#ffff00',",
"'#009999'] # 各ラベルごとに異なる色でプロット # 同じクラス内のインスタンスが近くに集まり、 # 異なるクラスのインスタンスが離れていれば成功 for i in",
"'#999900', '#009900', '#009999'] # 各ラベルごとに異なる色でプロット # 同じクラス内のインスタンスが近くに集まり、 # 異なるクラスのインスタンスが離れていれば成功 for",
"import chainer import chainer.links as L from net import SiameseNetwork",
"'2', '3', '4', '5', '6', '7', '8', '9']) plt.savefig(os.path.join('result', 'result.png'))",
"'#009900', '#009999'] # 各ラベルごとに異なる色でプロット # 同じクラス内のインスタンスが近くに集まり、 # 異なるクラスのインスタンスが離れていれば成功 for i",
"test_label = test._datasets # テストデータを学習した低次元空間(2次元)に写像 y = model.forward_once(test_data) feat =",
"'#00ff00', '#00ffff', '#0000ff', '#ff00ff', '#990000', '#999900', '#009900', '#009999'] # 各ラベルごとに異なる色でプロット",
"1], '.', c=c[i]) plt.legend(['0', '1', '2', '3', '4', '5', '6',",
"# 異なるクラスのインスタンスが離れていれば成功 for i in range(10): f = feat[np.where(test_label ==",
"= y.data # ラベルごとに描画 c = ['#ff0000', '#ffff00', '#00ff00', '#00ffff',",
"テストデータを学習した低次元空間(2次元)に写像 y = model.forward_once(test_data) feat = y.data # ラベルごとに描画 c",
"f = feat[np.where(test_label == i)] plt.plot(f[:, 0], f[:, 1], '.',",
"'#ffff00', '#00ff00', '#00ffff', '#0000ff', '#ff00ff', '#990000', '#999900', '#009900', '#009999'] #",
"f[:, 1], '.', c=c[i]) plt.legend(['0', '1', '2', '3', '4', '5',",
"# テストデータを学習した低次元空間(2次元)に写像 y = model.forward_once(test_data) feat = y.data # ラベルごとに描画",
"= test._datasets # テストデータを学習した低次元空間(2次元)に写像 y = model.forward_once(test_data) feat = y.data",
"c=c[i]) plt.legend(['0', '1', '2', '3', '4', '5', '6', '7', '8',",
"feat[np.where(test_label == i)] plt.plot(f[:, 0], f[:, 1], '.', c=c[i]) plt.legend(['0',",
"0], f[:, 1], '.', c=c[i]) plt.legend(['0', '1', '2', '3', '4',",
"y.data # ラベルごとに描画 c = ['#ff0000', '#ffff00', '#00ff00', '#00ffff', '#0000ff',",
"# ラベルごとに描画 c = ['#ff0000', '#ffff00', '#00ff00', '#00ffff', '#0000ff', '#ff00ff',",
"import chainer.links as L from net import SiameseNetwork import numpy",
"test_data, test_label = test._datasets # テストデータを学習した低次元空間(2次元)に写像 y = model.forward_once(test_data) feat",
"numpy as np import matplotlib.pyplot as plt # 訓練済みモデルをロード model",
"model = SiameseNetwork() chainer.serializers.load_npz(os.path.join('result', 'model.npz'), model) # テストデータをロード _, test",
"chainer.links as L from net import SiameseNetwork import numpy as",
"各ラベルごとに異なる色でプロット # 同じクラス内のインスタンスが近くに集まり、 # 異なるクラスのインスタンスが離れていれば成功 for i in range(10): f",
"as np import matplotlib.pyplot as plt # 訓練済みモデルをロード model =",
"# 訓練済みモデルをロード model = SiameseNetwork() chainer.serializers.load_npz(os.path.join('result', 'model.npz'), model) # テストデータをロード",
"= ['#ff0000', '#ffff00', '#00ff00', '#00ffff', '#0000ff', '#ff00ff', '#990000', '#999900', '#009900',",
"test = chainer.datasets.get_mnist(ndim=3) test_data, test_label = test._datasets # テストデータを学習した低次元空間(2次元)に写像 y",
"import numpy as np import matplotlib.pyplot as plt # 訓練済みモデルをロード",
"os import chainer import chainer.links as L from net import",
"SiameseNetwork() chainer.serializers.load_npz(os.path.join('result', 'model.npz'), model) # テストデータをロード _, test = chainer.datasets.get_mnist(ndim=3)",
"# 各ラベルごとに異なる色でプロット # 同じクラス内のインスタンスが近くに集まり、 # 異なるクラスのインスタンスが離れていれば成功 for i in range(10):",
"'.', c=c[i]) plt.legend(['0', '1', '2', '3', '4', '5', '6', '7',",
"= model.forward_once(test_data) feat = y.data # ラベルごとに描画 c = ['#ff0000',",
"異なるクラスのインスタンスが離れていれば成功 for i in range(10): f = feat[np.where(test_label == i)]",
"同じクラス内のインスタンスが近くに集まり、 # 異なるクラスのインスタンスが離れていれば成功 for i in range(10): f = feat[np.where(test_label",
"['#ff0000', '#ffff00', '#00ff00', '#00ffff', '#0000ff', '#ff00ff', '#990000', '#999900', '#009900', '#009999']",
"'model.npz'), model) # テストデータをロード _, test = chainer.datasets.get_mnist(ndim=3) test_data, test_label",
"= feat[np.where(test_label == i)] plt.plot(f[:, 0], f[:, 1], '.', c=c[i])",
"for i in range(10): f = feat[np.where(test_label == i)] plt.plot(f[:,",
"plt.plot(f[:, 0], f[:, 1], '.', c=c[i]) plt.legend(['0', '1', '2', '3',",
"matplotlib.pyplot as plt # 訓練済みモデルをロード model = SiameseNetwork() chainer.serializers.load_npz(os.path.join('result', 'model.npz'),",
"plt # 訓練済みモデルをロード model = SiameseNetwork() chainer.serializers.load_npz(os.path.join('result', 'model.npz'), model) #",
"'#ff00ff', '#990000', '#999900', '#009900', '#009999'] # 各ラベルごとに異なる色でプロット # 同じクラス内のインスタンスが近くに集まり、 #",
"test._datasets # テストデータを学習した低次元空間(2次元)に写像 y = model.forward_once(test_data) feat = y.data #",
"'#0000ff', '#ff00ff', '#990000', '#999900', '#009900', '#009999'] # 各ラベルごとに異なる色でプロット # 同じクラス内のインスタンスが近くに集まり、",
"ラベルごとに描画 c = ['#ff0000', '#ffff00', '#00ff00', '#00ffff', '#0000ff', '#ff00ff', '#990000',",
"# 同じクラス内のインスタンスが近くに集まり、 # 異なるクラスのインスタンスが離れていれば成功 for i in range(10): f =",
"net import SiameseNetwork import numpy as np import matplotlib.pyplot as",
"chainer.serializers.load_npz(os.path.join('result', 'model.npz'), model) # テストデータをロード _, test = chainer.datasets.get_mnist(ndim=3) test_data,",
"= chainer.datasets.get_mnist(ndim=3) test_data, test_label = test._datasets # テストデータを学習した低次元空間(2次元)に写像 y =",
"y = model.forward_once(test_data) feat = y.data # ラベルごとに描画 c =",
"as L from net import SiameseNetwork import numpy as np",
"i in range(10): f = feat[np.where(test_label == i)] plt.plot(f[:, 0],",
"'#990000', '#999900', '#009900', '#009999'] # 各ラベルごとに異なる色でプロット # 同じクラス内のインスタンスが近くに集まり、 # 異なるクラスのインスタンスが離れていれば成功",
"L from net import SiameseNetwork import numpy as np import",
"model) # テストデータをロード _, test = chainer.datasets.get_mnist(ndim=3) test_data, test_label =",
"== i)] plt.plot(f[:, 0], f[:, 1], '.', c=c[i]) plt.legend(['0', '1',",
"range(10): f = feat[np.where(test_label == i)] plt.plot(f[:, 0], f[:, 1],",
"i)] plt.plot(f[:, 0], f[:, 1], '.', c=c[i]) plt.legend(['0', '1', '2',",
"as plt # 訓練済みモデルをロード model = SiameseNetwork() chainer.serializers.load_npz(os.path.join('result', 'model.npz'), model)",
"'1', '2', '3', '4', '5', '6', '7', '8', '9']) plt.savefig(os.path.join('result',",
"# テストデータをロード _, test = chainer.datasets.get_mnist(ndim=3) test_data, test_label = test._datasets",
"テストデータをロード _, test = chainer.datasets.get_mnist(ndim=3) test_data, test_label = test._datasets #",
"'#00ffff', '#0000ff', '#ff00ff', '#990000', '#999900', '#009900', '#009999'] # 各ラベルごとに異なる色でプロット #",
"import matplotlib.pyplot as plt # 訓練済みモデルをロード model = SiameseNetwork() chainer.serializers.load_npz(os.path.join('result',",
"np import matplotlib.pyplot as plt # 訓練済みモデルをロード model = SiameseNetwork()",
"plt.legend(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'])",
"feat = y.data # ラベルごとに描画 c = ['#ff0000', '#ffff00', '#00ff00',",
"訓練済みモデルをロード model = SiameseNetwork() chainer.serializers.load_npz(os.path.join('result', 'model.npz'), model) # テストデータをロード _,",
"chainer import chainer.links as L from net import SiameseNetwork import",
"SiameseNetwork import numpy as np import matplotlib.pyplot as plt #",
"= SiameseNetwork() chainer.serializers.load_npz(os.path.join('result', 'model.npz'), model) # テストデータをロード _, test =",
"c = ['#ff0000', '#ffff00', '#00ff00', '#00ffff', '#0000ff', '#ff00ff', '#990000', '#999900',",
"import os import chainer import chainer.links as L from net",
"in range(10): f = feat[np.where(test_label == i)] plt.plot(f[:, 0], f[:,",
"from net import SiameseNetwork import numpy as np import matplotlib.pyplot",
"<reponame>aidiary/chainer-siamese import os import chainer import chainer.links as L from",
"import SiameseNetwork import numpy as np import matplotlib.pyplot as plt",
"chainer.datasets.get_mnist(ndim=3) test_data, test_label = test._datasets # テストデータを学習した低次元空間(2次元)に写像 y = model.forward_once(test_data)"
] |
[
"1 self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) logging.debug(\"\\tmove LEFT foot to \" + TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) self._next_foot",
"+ 1 self._right_direction = \"FW\" else: self._right_color = self._right_color -",
"1000)) act_millis = time() * 1000 - self._starting_millis logging.debug(\"\\tActual: %d:%d.%d\"",
"self.max_delay = max_delay self._last_beat_millis = 0 self._left_color = randrange(0, len(TwoFeetTempoMove.COLORS_ALPHA))",
"switch on foot if self._next_foot == 'RIGHT': self._next_foot = 'LEFT'",
"if self._left_color == 0: self._left_color = self._left_color + 1 self._left_direction",
"assert max_delay > 0 self.min_delay = min_delay self.max_delay = max_delay",
"= self.min_delay + 10 def tempo_found_callback(self, seconds, millis, confidence): act_delay",
"act_delay = millis - self._last_beat_millis + randrange(0, self.max_delay) if act_delay",
"/ 1000, millis % 1000)) act_millis = time() * 1000",
"(TwoFeetTempoMove.COLORS_ALPHA[self._left_color], TwoFeetTempoMove.COLORS_ALPHA[self._right_color])) self.tt_gui = TwisterTempoGUI() self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) self._starting_millis = time()",
"- self._starting_millis logging.debug(\"\\tActual: %d:%d.%d\" % (act_millis / 60000, act_millis /",
"logging.info(\"Starting with LEFT: %s, RIGHT: %s\" % (TwoFeetTempoMove.COLORS_ALPHA[self._left_color], TwoFeetTempoMove.COLORS_ALPHA[self._right_color])) self.tt_gui",
"# randomized next foot on air move if self._next_foot ==",
"import logging from TwisterTempoGUI import TwisterTempoGUI class TwoFeetTempoMove(object): COLORS_ALPHA =",
"1: self._left_color = self._left_color - 1 self._left_direction = \"BW\" else:",
"move if self._next_foot == 'RIGHT': self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color], on_air=True) else: self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color], on_air=True)",
">= self.min_delay: self._last_beat_millis = millis self.beat_found() def beat_found(self): millis =",
"\"FW\" self._next_foot = 'RIGHT' logging.info(\"Starting with LEFT: %s, RIGHT: %s\"",
"self.min_delay + 10 def tempo_found_callback(self, seconds, millis, confidence): act_delay =",
"both feet on same circle if self._next_foot == 'RIGHT': self._right_color",
"255), 2: (255, 255, 0), 3: (0, 255, 0)} FOOT_CHANGE_PERC",
"time import logging from TwisterTempoGUI import TwisterTempoGUI class TwoFeetTempoMove(object): COLORS_ALPHA",
"moves else: if random() < TwoFeetTempoMove.FOOT_CHANGE_PERC: # randomize at 30%",
"= \"BW\" else: self._right_color = self._right_color + 1 else: if",
"= \"FW\" self._next_foot = 'RIGHT' logging.info(\"Starting with LEFT: %s, RIGHT:",
"COLORS_RGB = {0: (255, 0, 0), 1: (0, 0, 255),",
"%d:%d.%d\" % (millis / 60000, millis / 1000, millis %",
"def get_colors_rgb(self): return {'RIGHT': TwoFeetTempoMove.COLORS_RGB[self._right_color], 'LEFT': TwoFeetTempoMove.COLORS_RGB[self._left_color]} def increase_speed(self): self.min_delay",
"= 'LEFT' else: self._next_foot = 'RIGHT' if self._next_foot == 'RIGHT':",
"self._left_color self.tt_gui.set_large_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) else: self._left_color = self._right_color self.tt_gui.set_large_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) logging.debug(\"\\tmove both feet",
"self._next_foot = 'RIGHT' if self._next_foot == 'RIGHT': if self._right_direction ==",
"time() * 1000 def get_colors_alpha(self): return {'RIGHT': TwoFeetTempoMove.COLORS_ALPHA[self._right_color], 'LEFT': TwoFeetTempoMove.COLORS_ALPHA[self._left_color]}",
"randrange(0, len(TwoFeetTempoMove.COLORS_ALPHA)) self._right_color = randrange(0, len(TwoFeetTempoMove.COLORS_ALPHA)) self._left_direction = \"FW\" self._right_direction",
"if act_delay >= self.min_delay: self._last_beat_millis = millis self.beat_found() def beat_found(self):",
"def tempo_found_callback(self, seconds, millis, confidence): act_delay = millis - self._last_beat_millis",
"self.tt_gui.set_large_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) logging.debug(\"\\tmove both feet on same circle\") # end special",
"\"FW\": if self._right_color == len(TwoFeetTempoMove.COLORS_ALPHA) - 1: self._right_color = self._right_color",
"self.min_delay = self.min_delay - 10 def decrease_speed(self): self.min_delay = self.min_delay",
"(255, 0, 0), 1: (0, 0, 255), 2: (255, 255,",
"RIGHT foot to \" + TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) self._next_foot = 'LEFT' else:",
"special moves else: if random() < TwoFeetTempoMove.FOOT_CHANGE_PERC: # randomize at",
"self._left_color == len(TwoFeetTempoMove.COLORS_ALPHA) - 1: self._left_color = self._left_color - 1",
"FEET_ON_SAME_CIRCLE_PERC = 0.05 def __init__(self, min_delay=0, max_delay=100): assert min_delay >=",
"self._left_direction = \"BW\" else: self._left_color = self._left_color + 1 else:",
"< TwoFeetTempoMove.FOOT_ON_AIR_PERC: # randomized next foot on air move if",
"circle if self._next_foot == 'RIGHT': self._right_color = self._left_color self.tt_gui.set_large_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) else:",
"random() < TwoFeetTempoMove.FEET_ON_SAME_CIRCLE_PERC: # randomized both feet on same circle",
"decrease_speed(self): self.min_delay = self.min_delay + 10 def tempo_found_callback(self, seconds, millis,",
"% (millis / 60000, millis / 1000, millis % 1000))",
"TwoFeetTempoMove.FEET_ON_SAME_CIRCLE_PERC: # randomized both feet on same circle if self._next_foot",
"= \"FW\" else: self._right_color = self._right_color - 1 self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) logging.debug(\"\\tmove",
"self._left_color - 1 self._left_direction = \"BW\" else: self._left_color = self._left_color",
"len(TwoFeetTempoMove.COLORS_ALPHA) - 1: self._right_color = self._right_color - 1 self._right_direction =",
"= self._last_beat_millis logging.debug(\"Randomized beat found at: %d:%d.%d\" % (millis /",
"== 'RIGHT': self._next_foot = 'LEFT' else: self._next_foot = 'RIGHT' if",
"/ 1000, act_millis % 1000)) # special moves if random()",
"logging.debug(\"\\tmove RIGHT foot to \" + TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) self._next_foot = 'LEFT'",
"= self._left_color + 1 self._left_direction = \"FW\" else: self._left_color =",
"self._next_foot = 'LEFT' else: if self._left_direction == \"FW\": if self._left_color",
"from TwisterTempoGUI import TwisterTempoGUI class TwoFeetTempoMove(object): COLORS_ALPHA = {0: 'RED',",
"to \" + TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) self._next_foot = 'LEFT' else: if self._left_direction",
"len(TwoFeetTempoMove.COLORS_ALPHA)) self._left_direction = \"FW\" self._right_direction = \"FW\" self._next_foot = 'RIGHT'",
"millis, confidence): act_delay = millis - self._last_beat_millis + randrange(0, self.max_delay)",
"else: if self._right_color == 0: self._right_color = self._right_color + 1",
"= 0.3 FOOT_ON_AIR_PERC = 0.08 FEET_ON_SAME_CIRCLE_PERC = 0.05 def __init__(self,",
"on foot if self._next_foot == 'RIGHT': self._next_foot = 'LEFT' else:",
"TwoFeetTempoMove.COLORS_RGB[self._right_color], 'LEFT': TwoFeetTempoMove.COLORS_RGB[self._left_color]} def increase_speed(self): self.min_delay = self.min_delay - 10",
"TwoFeetTempoMove.FOOT_CHANGE_PERC: # randomize at 30% the switch on foot if",
"def get_colors_alpha(self): return {'RIGHT': TwoFeetTempoMove.COLORS_ALPHA[self._right_color], 'LEFT': TwoFeetTempoMove.COLORS_ALPHA[self._left_color]} def get_colors_rgb(self): return",
"TwoFeetTempoMove.COLORS_ALPHA[self._left_color]} def get_colors_rgb(self): return {'RIGHT': TwoFeetTempoMove.COLORS_RGB[self._right_color], 'LEFT': TwoFeetTempoMove.COLORS_RGB[self._left_color]} def increase_speed(self):",
"if self._next_foot == 'RIGHT': self._right_color = self._left_color self.tt_gui.set_large_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) else: self._left_color",
"at 30% the switch on foot if self._next_foot == 'RIGHT':",
"self._starting_millis = time() * 1000 def get_colors_alpha(self): return {'RIGHT': TwoFeetTempoMove.COLORS_ALPHA[self._right_color],",
"= self._left_color self.tt_gui.set_large_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) else: self._left_color = self._right_color self.tt_gui.set_large_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) logging.debug(\"\\tmove both",
"def increase_speed(self): self.min_delay = self.min_delay - 10 def decrease_speed(self): self.min_delay",
"found at: %d:%d.%d\" % (millis / 60000, millis / 1000,",
"self.tt_gui = TwisterTempoGUI() self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) self._starting_millis = time() * 1000",
"random from time import time import logging from TwisterTempoGUI import",
"# end special moves else: if random() < TwoFeetTempoMove.FOOT_CHANGE_PERC: #",
"1000, act_millis % 1000)) # special moves if random() <",
"act_millis % 1000)) # special moves if random() < TwoFeetTempoMove.FOOT_ON_AIR_PERC:",
"2: (255, 255, 0), 3: (0, 255, 0)} FOOT_CHANGE_PERC =",
"+ 1 else: if self._left_color == 0: self._left_color = self._left_color",
"at: %d:%d.%d\" % (millis / 60000, millis / 1000, millis",
"{'RIGHT': TwoFeetTempoMove.COLORS_ALPHA[self._right_color], 'LEFT': TwoFeetTempoMove.COLORS_ALPHA[self._left_color]} def get_colors_rgb(self): return {'RIGHT': TwoFeetTempoMove.COLORS_RGB[self._right_color], 'LEFT':",
"%s\" % (TwoFeetTempoMove.COLORS_ALPHA[self._left_color], TwoFeetTempoMove.COLORS_ALPHA[self._right_color])) self.tt_gui = TwisterTempoGUI() self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) self._starting_millis",
"# randomized both feet on same circle if self._next_foot ==",
"self._right_direction = \"BW\" else: self._right_color = self._right_color + 1 else:",
"= 'LEFT' else: if self._left_direction == \"FW\": if self._left_color ==",
"self._right_color - 1 self._right_direction = \"BW\" else: self._right_color = self._right_color",
"\"FW\": if self._left_color == len(TwoFeetTempoMove.COLORS_ALPHA) - 1: self._left_color = self._left_color",
"{'RIGHT': TwoFeetTempoMove.COLORS_RGB[self._right_color], 'LEFT': TwoFeetTempoMove.COLORS_RGB[self._left_color]} def increase_speed(self): self.min_delay = self.min_delay -",
"255, 0)} FOOT_CHANGE_PERC = 0.3 FOOT_ON_AIR_PERC = 0.08 FEET_ON_SAME_CIRCLE_PERC =",
"randrange(0, self.max_delay) if act_delay >= self.min_delay: self._last_beat_millis = millis self.beat_found()",
"randrange, random from time import time import logging from TwisterTempoGUI",
"TwisterTempoGUI() self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) self._starting_millis = time() * 1000 def get_colors_alpha(self):",
"else: if self._left_direction == \"FW\": if self._left_color == len(TwoFeetTempoMove.COLORS_ALPHA) -",
"== len(TwoFeetTempoMove.COLORS_ALPHA) - 1: self._left_color = self._left_color - 1 self._left_direction",
"logging.debug(\"\\tActual: %d:%d.%d\" % (act_millis / 60000, act_millis / 1000, act_millis",
"TwoFeetTempoMove.COLORS_ALPHA[self._right_color])) self.tt_gui = TwisterTempoGUI() self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) self._starting_millis = time() *",
"if random() < TwoFeetTempoMove.FOOT_ON_AIR_PERC: # randomized next foot on air",
"self.tt_gui.set_large_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) else: self._left_color = self._right_color self.tt_gui.set_large_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) logging.debug(\"\\tmove both feet on",
"self.beat_found() def beat_found(self): millis = self._last_beat_millis logging.debug(\"Randomized beat found at:",
"self.min_delay = min_delay self.max_delay = max_delay self._last_beat_millis = 0 self._left_color",
"on same circle if self._next_foot == 'RIGHT': self._right_color = self._left_color",
"60000, millis / 1000, millis % 1000)) act_millis = time()",
"self._right_color - 1 self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) logging.debug(\"\\tmove RIGHT foot to \" +",
"% (TwoFeetTempoMove.COLORS_ALPHA[self._left_color], TwoFeetTempoMove.COLORS_ALPHA[self._right_color])) self.tt_gui = TwisterTempoGUI() self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) self._starting_millis =",
"self._next_foot == 'RIGHT': self._next_foot = 'LEFT' else: self._next_foot = 'RIGHT'",
"'RIGHT': self._right_color = self._left_color self.tt_gui.set_large_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) else: self._left_color = self._right_color self.tt_gui.set_large_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color])",
"special moves if random() < TwoFeetTempoMove.FOOT_ON_AIR_PERC: # randomized next foot",
"else: if random() < TwoFeetTempoMove.FOOT_CHANGE_PERC: # randomize at 30% the",
"1: 'BLUE', 2: 'YELLOW', 3: 'GREEN'} COLORS_RGB = {0: (255,",
"if self._left_direction == \"FW\": if self._left_color == len(TwoFeetTempoMove.COLORS_ALPHA) - 1:",
"self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color], on_air=True) else: self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color], on_air=True) logging.debug(\"\\tmove next foot On Air\")",
"if self._next_foot == 'RIGHT': self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color], on_air=True) else: self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color], on_air=True) logging.debug(\"\\tmove",
"on_air=True) else: self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color], on_air=True) logging.debug(\"\\tmove next foot On Air\") elif",
"logging.debug(\"Randomized beat found at: %d:%d.%d\" % (millis / 60000, millis",
"TwisterTempoGUI class TwoFeetTempoMove(object): COLORS_ALPHA = {0: 'RED', 1: 'BLUE', 2:",
"self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) logging.debug(\"\\tmove RIGHT foot to \" + TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) self._next_foot =",
"%s, RIGHT: %s\" % (TwoFeetTempoMove.COLORS_ALPHA[self._left_color], TwoFeetTempoMove.COLORS_ALPHA[self._right_color])) self.tt_gui = TwisterTempoGUI() self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color])",
"self._right_color = self._right_color + 1 else: if self._right_color == 0:",
"1 self._right_direction = \"FW\" else: self._right_color = self._right_color - 1",
"self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) self._starting_millis = time() * 1000 def get_colors_alpha(self): return",
"\"FW\" else: self._left_color = self._left_color - 1 self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) logging.debug(\"\\tmove LEFT",
"self._right_color + 1 self._right_direction = \"FW\" else: self._right_color = self._right_color",
"+ 1 self._left_direction = \"FW\" else: self._left_color = self._left_color -",
"= millis - self._last_beat_millis + randrange(0, self.max_delay) if act_delay >=",
"self._right_direction = \"FW\" self._next_foot = 'RIGHT' logging.info(\"Starting with LEFT: %s,",
"== \"FW\": if self._right_color == len(TwoFeetTempoMove.COLORS_ALPHA) - 1: self._right_color =",
"class TwoFeetTempoMove(object): COLORS_ALPHA = {0: 'RED', 1: 'BLUE', 2: 'YELLOW',",
"random() < TwoFeetTempoMove.FOOT_CHANGE_PERC: # randomize at 30% the switch on",
"'LEFT': TwoFeetTempoMove.COLORS_ALPHA[self._left_color]} def get_colors_rgb(self): return {'RIGHT': TwoFeetTempoMove.COLORS_RGB[self._right_color], 'LEFT': TwoFeetTempoMove.COLORS_RGB[self._left_color]} def",
"= \"FW\" else: self._left_color = self._left_color - 1 self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) logging.debug(\"\\tmove",
"time() * 1000 - self._starting_millis logging.debug(\"\\tActual: %d:%d.%d\" % (act_millis /",
"self._left_color = self._left_color + 1 else: if self._left_color == 0:",
"- 1: self._left_color = self._left_color - 1 self._left_direction = \"BW\"",
"'BLUE', 2: 'YELLOW', 3: 'GREEN'} COLORS_RGB = {0: (255, 0,",
"self._last_beat_millis + randrange(0, self.max_delay) if act_delay >= self.min_delay: self._last_beat_millis =",
"TwoFeetTempoMove(object): COLORS_ALPHA = {0: 'RED', 1: 'BLUE', 2: 'YELLOW', 3:",
"self.min_delay - 10 def decrease_speed(self): self.min_delay = self.min_delay + 10",
"TwoFeetTempoMove.FOOT_ON_AIR_PERC: # randomized next foot on air move if self._next_foot",
"On Air\") elif random() < TwoFeetTempoMove.FEET_ON_SAME_CIRCLE_PERC: # randomized both feet",
"self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color], on_air=True) logging.debug(\"\\tmove next foot On Air\") elif random() <",
"LEFT: %s, RIGHT: %s\" % (TwoFeetTempoMove.COLORS_ALPHA[self._left_color], TwoFeetTempoMove.COLORS_ALPHA[self._right_color])) self.tt_gui = TwisterTempoGUI()",
"if self._right_direction == \"FW\": if self._right_color == len(TwoFeetTempoMove.COLORS_ALPHA) - 1:",
"self.min_delay = self.min_delay + 10 def tempo_found_callback(self, seconds, millis, confidence):",
"self.max_delay) if act_delay >= self.min_delay: self._last_beat_millis = millis self.beat_found() def",
"self._left_color = randrange(0, len(TwoFeetTempoMove.COLORS_ALPHA)) self._right_color = randrange(0, len(TwoFeetTempoMove.COLORS_ALPHA)) self._left_direction =",
"1 self._left_direction = \"BW\" else: self._left_color = self._left_color + 1",
"else: self._left_color = self._left_color - 1 self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) logging.debug(\"\\tmove LEFT foot",
"randomized both feet on same circle if self._next_foot == 'RIGHT':",
"same circle\") # end special moves else: if random() <",
"= millis self.beat_found() def beat_found(self): millis = self._last_beat_millis logging.debug(\"Randomized beat",
"beat found at: %d:%d.%d\" % (millis / 60000, millis /",
"'RED', 1: 'BLUE', 2: 'YELLOW', 3: 'GREEN'} COLORS_RGB = {0:",
"\"BW\" else: self._right_color = self._right_color + 1 else: if self._right_color",
"= 0.05 def __init__(self, min_delay=0, max_delay=100): assert min_delay >= 0",
"circle\") # end special moves else: if random() < TwoFeetTempoMove.FOOT_CHANGE_PERC:",
"== 'RIGHT': if self._right_direction == \"FW\": if self._right_color == len(TwoFeetTempoMove.COLORS_ALPHA)",
"TwoFeetTempoMove.COLORS_ALPHA[self._right_color], 'LEFT': TwoFeetTempoMove.COLORS_ALPHA[self._left_color]} def get_colors_rgb(self): return {'RIGHT': TwoFeetTempoMove.COLORS_RGB[self._right_color], 'LEFT': TwoFeetTempoMove.COLORS_RGB[self._left_color]}",
"= {0: 'RED', 1: 'BLUE', 2: 'YELLOW', 3: 'GREEN'} COLORS_RGB",
"= self._left_color - 1 self._left_direction = \"BW\" else: self._left_color =",
"TwisterTempoGUI import TwisterTempoGUI class TwoFeetTempoMove(object): COLORS_ALPHA = {0: 'RED', 1:",
"logging.debug(\"\\tmove both feet on same circle\") # end special moves",
"1 else: if self._left_color == 0: self._left_color = self._left_color +",
"def decrease_speed(self): self.min_delay = self.min_delay + 10 def tempo_found_callback(self, seconds,",
"Air\") elif random() < TwoFeetTempoMove.FEET_ON_SAME_CIRCLE_PERC: # randomized both feet on",
"millis / 1000, millis % 1000)) act_millis = time() *",
"= max_delay self._last_beat_millis = 0 self._left_color = randrange(0, len(TwoFeetTempoMove.COLORS_ALPHA)) self._right_color",
"if self._next_foot == 'RIGHT': if self._right_direction == \"FW\": if self._right_color",
"elif random() < TwoFeetTempoMove.FEET_ON_SAME_CIRCLE_PERC: # randomized both feet on same",
"else: self._right_color = self._right_color + 1 else: if self._right_color ==",
"self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) logging.debug(\"\\tmove LEFT foot to \" + TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) self._next_foot =",
"self._right_color = self._right_color - 1 self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) logging.debug(\"\\tmove RIGHT foot to",
"self._last_beat_millis logging.debug(\"Randomized beat found at: %d:%d.%d\" % (millis / 60000,",
"+ 10 def tempo_found_callback(self, seconds, millis, confidence): act_delay = millis",
"foot to \" + TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) self._next_foot = 'LEFT' else: if",
"on same circle\") # end special moves else: if random()",
"on_air=True) logging.debug(\"\\tmove next foot On Air\") elif random() < TwoFeetTempoMove.FEET_ON_SAME_CIRCLE_PERC:",
"from time import time import logging from TwisterTempoGUI import TwisterTempoGUI",
"# special moves if random() < TwoFeetTempoMove.FOOT_ON_AIR_PERC: # randomized next",
"millis = self._last_beat_millis logging.debug(\"Randomized beat found at: %d:%d.%d\" % (millis",
"0)} FOOT_CHANGE_PERC = 0.3 FOOT_ON_AIR_PERC = 0.08 FEET_ON_SAME_CIRCLE_PERC = 0.05",
"RIGHT: %s\" % (TwoFeetTempoMove.COLORS_ALPHA[self._left_color], TwoFeetTempoMove.COLORS_ALPHA[self._right_color])) self.tt_gui = TwisterTempoGUI() self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color])",
"* 1000 def get_colors_alpha(self): return {'RIGHT': TwoFeetTempoMove.COLORS_ALPHA[self._right_color], 'LEFT': TwoFeetTempoMove.COLORS_ALPHA[self._left_color]} def",
"3: (0, 255, 0)} FOOT_CHANGE_PERC = 0.3 FOOT_ON_AIR_PERC = 0.08",
"+ randrange(0, self.max_delay) if act_delay >= self.min_delay: self._last_beat_millis = millis",
"return {'RIGHT': TwoFeetTempoMove.COLORS_RGB[self._right_color], 'LEFT': TwoFeetTempoMove.COLORS_RGB[self._left_color]} def increase_speed(self): self.min_delay = self.min_delay",
"1 else: if self._right_color == 0: self._right_color = self._right_color +",
"\"BW\" else: self._left_color = self._left_color + 1 else: if self._left_color",
"0), 3: (0, 255, 0)} FOOT_CHANGE_PERC = 0.3 FOOT_ON_AIR_PERC =",
"self._right_color = randrange(0, len(TwoFeetTempoMove.COLORS_ALPHA)) self._left_direction = \"FW\" self._right_direction = \"FW\"",
"<reponame>b0nz0/TwisterTempo<gh_stars>0 from random import randrange, random from time import time",
"feet on same circle if self._next_foot == 'RIGHT': self._right_color =",
"if self._right_color == len(TwoFeetTempoMove.COLORS_ALPHA) - 1: self._right_color = self._right_color -",
"self._next_foot == 'RIGHT': self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color], on_air=True) else: self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color], on_air=True) logging.debug(\"\\tmove next",
"time import time import logging from TwisterTempoGUI import TwisterTempoGUI class",
"self._left_color + 1 self._left_direction = \"FW\" else: self._left_color = self._left_color",
"= time() * 1000 - self._starting_millis logging.debug(\"\\tActual: %d:%d.%d\" % (act_millis",
"3: 'GREEN'} COLORS_RGB = {0: (255, 0, 0), 1: (0,",
">= 0 assert max_delay > 0 self.min_delay = min_delay self.max_delay",
"255, 0), 3: (0, 255, 0)} FOOT_CHANGE_PERC = 0.3 FOOT_ON_AIR_PERC",
"if random() < TwoFeetTempoMove.FOOT_CHANGE_PERC: # randomize at 30% the switch",
"end special moves else: if random() < TwoFeetTempoMove.FOOT_CHANGE_PERC: # randomize",
"logging from TwisterTempoGUI import TwisterTempoGUI class TwoFeetTempoMove(object): COLORS_ALPHA = {0:",
"self._left_color - 1 self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) logging.debug(\"\\tmove LEFT foot to \" +",
"< TwoFeetTempoMove.FEET_ON_SAME_CIRCLE_PERC: # randomized both feet on same circle if",
"'LEFT' else: if self._left_direction == \"FW\": if self._left_color == len(TwoFeetTempoMove.COLORS_ALPHA)",
"import randrange, random from time import time import logging from",
"next foot On Air\") elif random() < TwoFeetTempoMove.FEET_ON_SAME_CIRCLE_PERC: # randomized",
"act_millis = time() * 1000 - self._starting_millis logging.debug(\"\\tActual: %d:%d.%d\" %",
"% 1000)) # special moves if random() < TwoFeetTempoMove.FOOT_ON_AIR_PERC: #",
"'RIGHT' if self._next_foot == 'RIGHT': if self._right_direction == \"FW\": if",
"randrange(0, len(TwoFeetTempoMove.COLORS_ALPHA)) self._left_direction = \"FW\" self._right_direction = \"FW\" self._next_foot =",
"return {'RIGHT': TwoFeetTempoMove.COLORS_ALPHA[self._right_color], 'LEFT': TwoFeetTempoMove.COLORS_ALPHA[self._left_color]} def get_colors_rgb(self): return {'RIGHT': TwoFeetTempoMove.COLORS_RGB[self._right_color],",
"millis - self._last_beat_millis + randrange(0, self.max_delay) if act_delay >= self.min_delay:",
"0 assert max_delay > 0 self.min_delay = min_delay self.max_delay =",
"'RIGHT': if self._right_direction == \"FW\": if self._right_color == len(TwoFeetTempoMove.COLORS_ALPHA) -",
"else: self._left_color = self._left_color + 1 else: if self._left_color ==",
"= 0.08 FEET_ON_SAME_CIRCLE_PERC = 0.05 def __init__(self, min_delay=0, max_delay=100): assert",
"min_delay self.max_delay = max_delay self._last_beat_millis = 0 self._left_color = randrange(0,",
"= self._left_color + 1 else: if self._left_color == 0: self._left_color",
"1000 def get_colors_alpha(self): return {'RIGHT': TwoFeetTempoMove.COLORS_ALPHA[self._right_color], 'LEFT': TwoFeetTempoMove.COLORS_ALPHA[self._left_color]} def get_colors_rgb(self):",
"= self._right_color - 1 self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) logging.debug(\"\\tmove RIGHT foot to \"",
"- 10 def decrease_speed(self): self.min_delay = self.min_delay + 10 def",
"self._right_direction == \"FW\": if self._right_color == len(TwoFeetTempoMove.COLORS_ALPHA) - 1: self._right_color",
"self._right_color = self._right_color + 1 self._right_direction = \"FW\" else: self._right_color",
"logging.debug(\"\\tmove next foot On Air\") elif random() < TwoFeetTempoMove.FEET_ON_SAME_CIRCLE_PERC: #",
"'RIGHT': self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color], on_air=True) else: self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color], on_air=True) logging.debug(\"\\tmove next foot On",
"0.08 FEET_ON_SAME_CIRCLE_PERC = 0.05 def __init__(self, min_delay=0, max_delay=100): assert min_delay",
"self._right_color == len(TwoFeetTempoMove.COLORS_ALPHA) - 1: self._right_color = self._right_color - 1",
"self._next_foot == 'RIGHT': self._right_color = self._left_color self.tt_gui.set_large_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) else: self._left_color =",
"self._last_beat_millis = 0 self._left_color = randrange(0, len(TwoFeetTempoMove.COLORS_ALPHA)) self._right_color = randrange(0,",
"max_delay=100): assert min_delay >= 0 assert max_delay > 0 self.min_delay",
"else: self._left_color = self._right_color self.tt_gui.set_large_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) logging.debug(\"\\tmove both feet on same",
"self._left_color = self._right_color self.tt_gui.set_large_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) logging.debug(\"\\tmove both feet on same circle\")",
"0), 1: (0, 0, 255), 2: (255, 255, 0), 3:",
"'RIGHT': self._next_foot = 'LEFT' else: self._next_foot = 'RIGHT' if self._next_foot",
"1 self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) logging.debug(\"\\tmove RIGHT foot to \" + TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) self._next_foot",
"'RIGHT' logging.info(\"Starting with LEFT: %s, RIGHT: %s\" % (TwoFeetTempoMove.COLORS_ALPHA[self._left_color], TwoFeetTempoMove.COLORS_ALPHA[self._right_color]))",
"random() < TwoFeetTempoMove.FOOT_ON_AIR_PERC: # randomized next foot on air move",
"\"FW\" else: self._right_color = self._right_color - 1 self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) logging.debug(\"\\tmove RIGHT",
"confidence): act_delay = millis - self._last_beat_millis + randrange(0, self.max_delay) if",
"self._left_direction = \"FW\" self._right_direction = \"FW\" self._next_foot = 'RIGHT' logging.info(\"Starting",
"% (act_millis / 60000, act_millis / 1000, act_millis % 1000))",
"foot if self._next_foot == 'RIGHT': self._next_foot = 'LEFT' else: self._next_foot",
"0, 0), 1: (0, 0, 255), 2: (255, 255, 0),",
"# randomize at 30% the switch on foot if self._next_foot",
"TwoFeetTempoMove.COLORS_RGB[self._left_color]} def increase_speed(self): self.min_delay = self.min_delay - 10 def decrease_speed(self):",
"'GREEN'} COLORS_RGB = {0: (255, 0, 0), 1: (0, 0,",
"(act_millis / 60000, act_millis / 1000, act_millis % 1000)) #",
"0: self._right_color = self._right_color + 1 self._right_direction = \"FW\" else:",
"- 1: self._right_color = self._right_color - 1 self._right_direction = \"BW\"",
"0: self._left_color = self._left_color + 1 self._left_direction = \"FW\" else:",
"max_delay > 0 self.min_delay = min_delay self.max_delay = max_delay self._last_beat_millis",
"/ 60000, act_millis / 1000, act_millis % 1000)) # special",
"both feet on same circle\") # end special moves else:",
"foot On Air\") elif random() < TwoFeetTempoMove.FEET_ON_SAME_CIRCLE_PERC: # randomized both",
"self._right_color self.tt_gui.set_large_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) logging.debug(\"\\tmove both feet on same circle\") # end",
"moves if random() < TwoFeetTempoMove.FOOT_ON_AIR_PERC: # randomized next foot on",
"self._left_color = self._left_color - 1 self._left_direction = \"BW\" else: self._left_color",
"(millis / 60000, millis / 1000, millis % 1000)) act_millis",
"act_millis / 1000, act_millis % 1000)) # special moves if",
"10 def decrease_speed(self): self.min_delay = self.min_delay + 10 def tempo_found_callback(self,",
"self._next_foot == 'RIGHT': if self._right_direction == \"FW\": if self._right_color ==",
"else: self._next_foot = 'RIGHT' if self._next_foot == 'RIGHT': if self._right_direction",
"== len(TwoFeetTempoMove.COLORS_ALPHA) - 1: self._right_color = self._right_color - 1 self._right_direction",
"self.min_delay: self._last_beat_millis = millis self.beat_found() def beat_found(self): millis = self._last_beat_millis",
"else: self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color], on_air=True) logging.debug(\"\\tmove next foot On Air\") elif random()",
"1000 - self._starting_millis logging.debug(\"\\tActual: %d:%d.%d\" % (act_millis / 60000, act_millis",
"0.05 def __init__(self, min_delay=0, max_delay=100): assert min_delay >= 0 assert",
"- 1 self._left_direction = \"BW\" else: self._left_color = self._left_color +",
"'LEFT' else: self._next_foot = 'RIGHT' if self._next_foot == 'RIGHT': if",
"the switch on foot if self._next_foot == 'RIGHT': self._next_foot =",
"= randrange(0, len(TwoFeetTempoMove.COLORS_ALPHA)) self._left_direction = \"FW\" self._right_direction = \"FW\" self._next_foot",
"= 0 self._left_color = randrange(0, len(TwoFeetTempoMove.COLORS_ALPHA)) self._right_color = randrange(0, len(TwoFeetTempoMove.COLORS_ALPHA))",
"= self._left_color - 1 self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) logging.debug(\"\\tmove LEFT foot to \"",
"get_colors_alpha(self): return {'RIGHT': TwoFeetTempoMove.COLORS_ALPHA[self._right_color], 'LEFT': TwoFeetTempoMove.COLORS_ALPHA[self._left_color]} def get_colors_rgb(self): return {'RIGHT':",
"{0: (255, 0, 0), 1: (0, 0, 255), 2: (255,",
"COLORS_ALPHA = {0: 'RED', 1: 'BLUE', 2: 'YELLOW', 3: 'GREEN'}",
"- self._last_beat_millis + randrange(0, self.max_delay) if act_delay >= self.min_delay: self._last_beat_millis",
"+ 1 else: if self._right_color == 0: self._right_color = self._right_color",
"% 1000)) act_millis = time() * 1000 - self._starting_millis logging.debug(\"\\tActual:",
"== 0: self._left_color = self._left_color + 1 self._left_direction = \"FW\"",
"2: 'YELLOW', 3: 'GREEN'} COLORS_RGB = {0: (255, 0, 0),",
"- 1 self._right_direction = \"BW\" else: self._right_color = self._right_color +",
"len(TwoFeetTempoMove.COLORS_ALPHA)) self._right_color = randrange(0, len(TwoFeetTempoMove.COLORS_ALPHA)) self._left_direction = \"FW\" self._right_direction =",
"TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) self._next_foot = 'LEFT' else: if self._left_direction == \"FW\": if",
"import TwisterTempoGUI class TwoFeetTempoMove(object): COLORS_ALPHA = {0: 'RED', 1: 'BLUE',",
"__init__(self, min_delay=0, max_delay=100): assert min_delay >= 0 assert max_delay >",
"{0: 'RED', 1: 'BLUE', 2: 'YELLOW', 3: 'GREEN'} COLORS_RGB =",
"1: self._right_color = self._right_color - 1 self._right_direction = \"BW\" else:",
"randomize at 30% the switch on foot if self._next_foot ==",
"self._left_color = self._left_color + 1 self._left_direction = \"FW\" else: self._left_color",
"1 self._right_direction = \"BW\" else: self._right_color = self._right_color + 1",
"- 1 self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) logging.debug(\"\\tmove RIGHT foot to \" + TwoFeetTempoMove.COLORS_ALPHA[self._right_color])",
"def beat_found(self): millis = self._last_beat_millis logging.debug(\"Randomized beat found at: %d:%d.%d\"",
"self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) self._starting_millis = time() * 1000 def get_colors_alpha(self): return {'RIGHT':",
"self._right_color + 1 else: if self._right_color == 0: self._right_color =",
"== \"FW\": if self._left_color == len(TwoFeetTempoMove.COLORS_ALPHA) - 1: self._left_color =",
"\"FW\" self._right_direction = \"FW\" self._next_foot = 'RIGHT' logging.info(\"Starting with LEFT:",
"self._right_color = self._right_color - 1 self._right_direction = \"BW\" else: self._right_color",
"= TwisterTempoGUI() self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) self._starting_millis = time() * 1000 def",
"60000, act_millis / 1000, act_millis % 1000)) # special moves",
"millis % 1000)) act_millis = time() * 1000 - self._starting_millis",
"self._right_color = self._left_color self.tt_gui.set_large_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) else: self._left_color = self._right_color self.tt_gui.set_large_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) logging.debug(\"\\tmove",
"get_colors_rgb(self): return {'RIGHT': TwoFeetTempoMove.COLORS_RGB[self._right_color], 'LEFT': TwoFeetTempoMove.COLORS_RGB[self._left_color]} def increase_speed(self): self.min_delay =",
"max_delay self._last_beat_millis = 0 self._left_color = randrange(0, len(TwoFeetTempoMove.COLORS_ALPHA)) self._right_color =",
"increase_speed(self): self.min_delay = self.min_delay - 10 def decrease_speed(self): self.min_delay =",
"= self.min_delay - 10 def decrease_speed(self): self.min_delay = self.min_delay +",
"self._left_color = self._left_color - 1 self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) logging.debug(\"\\tmove LEFT foot to",
"(255, 255, 0), 3: (0, 255, 0)} FOOT_CHANGE_PERC = 0.3",
"assert min_delay >= 0 assert max_delay > 0 self.min_delay =",
"len(TwoFeetTempoMove.COLORS_ALPHA) - 1: self._left_color = self._left_color - 1 self._left_direction =",
"= self._right_color + 1 else: if self._right_color == 0: self._right_color",
"if self._left_color == len(TwoFeetTempoMove.COLORS_ALPHA) - 1: self._left_color = self._left_color -",
"- 1 self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) logging.debug(\"\\tmove LEFT foot to \" + TwoFeetTempoMove.COLORS_ALPHA[self._left_color])",
"\" + TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) self._next_foot = 'LEFT' else: if self._left_direction ==",
"== 'RIGHT': self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color], on_air=True) else: self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color], on_air=True) logging.debug(\"\\tmove next foot",
"= min_delay self.max_delay = max_delay self._last_beat_millis = 0 self._left_color =",
"* 1000 - self._starting_millis logging.debug(\"\\tActual: %d:%d.%d\" % (act_millis / 60000,",
"30% the switch on foot if self._next_foot == 'RIGHT': self._next_foot",
"min_delay=0, max_delay=100): assert min_delay >= 0 assert max_delay > 0",
"0, 255), 2: (255, 255, 0), 3: (0, 255, 0)}",
"= \"FW\" self._right_direction = \"FW\" self._next_foot = 'RIGHT' logging.info(\"Starting with",
"= 'RIGHT' logging.info(\"Starting with LEFT: %s, RIGHT: %s\" % (TwoFeetTempoMove.COLORS_ALPHA[self._left_color],",
"self._starting_millis logging.debug(\"\\tActual: %d:%d.%d\" % (act_millis / 60000, act_millis / 1000,",
"min_delay >= 0 assert max_delay > 0 self.min_delay = min_delay",
"== 0: self._right_color = self._right_color + 1 self._right_direction = \"FW\"",
"self._left_color + 1 else: if self._left_color == 0: self._left_color =",
"= 'RIGHT' if self._next_foot == 'RIGHT': if self._right_direction == \"FW\":",
"= {0: (255, 0, 0), 1: (0, 0, 255), 2:",
"logging.debug(\"\\tmove LEFT foot to \" + TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) self._next_foot = 'RIGHT'",
"0.3 FOOT_ON_AIR_PERC = 0.08 FEET_ON_SAME_CIRCLE_PERC = 0.05 def __init__(self, min_delay=0,",
"self._next_foot = 'LEFT' else: self._next_foot = 'RIGHT' if self._next_foot ==",
"tempo_found_callback(self, seconds, millis, confidence): act_delay = millis - self._last_beat_millis +",
"self._right_direction = \"FW\" else: self._right_color = self._right_color - 1 self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color])",
"import time import logging from TwisterTempoGUI import TwisterTempoGUI class TwoFeetTempoMove(object):",
"same circle if self._next_foot == 'RIGHT': self._right_color = self._left_color self.tt_gui.set_large_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color])",
"= self._right_color self.tt_gui.set_large_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color]) logging.debug(\"\\tmove both feet on same circle\") #",
"0 self.min_delay = min_delay self.max_delay = max_delay self._last_beat_millis = 0",
"10 def tempo_found_callback(self, seconds, millis, confidence): act_delay = millis -",
"foot on air move if self._next_foot == 'RIGHT': self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color], on_air=True)",
"else: if self._left_color == 0: self._left_color = self._left_color + 1",
"millis self.beat_found() def beat_found(self): millis = self._last_beat_millis logging.debug(\"Randomized beat found",
"1000)) # special moves if random() < TwoFeetTempoMove.FOOT_ON_AIR_PERC: # randomized",
"= self._right_color + 1 self._right_direction = \"FW\" else: self._right_color =",
"beat_found(self): millis = self._last_beat_millis logging.debug(\"Randomized beat found at: %d:%d.%d\" %",
"on air move if self._next_foot == 'RIGHT': self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color], on_air=True) else:",
"+ TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) self._next_foot = 'LEFT' else: if self._left_direction == \"FW\":",
"self._left_direction == \"FW\": if self._left_color == len(TwoFeetTempoMove.COLORS_ALPHA) - 1: self._left_color",
"from random import randrange, random from time import time import",
"self._left_color == 0: self._left_color = self._left_color + 1 self._left_direction =",
"0 self._left_color = randrange(0, len(TwoFeetTempoMove.COLORS_ALPHA)) self._right_color = randrange(0, len(TwoFeetTempoMove.COLORS_ALPHA)) self._left_direction",
"1000, millis % 1000)) act_millis = time() * 1000 -",
"1: (0, 0, 255), 2: (255, 255, 0), 3: (0,",
"= randrange(0, len(TwoFeetTempoMove.COLORS_ALPHA)) self._right_color = randrange(0, len(TwoFeetTempoMove.COLORS_ALPHA)) self._left_direction = \"FW\"",
"self._right_color == 0: self._right_color = self._right_color + 1 self._right_direction =",
"act_delay >= self.min_delay: self._last_beat_millis = millis self.beat_found() def beat_found(self): millis",
"feet on same circle\") # end special moves else: if",
"'YELLOW', 3: 'GREEN'} COLORS_RGB = {0: (255, 0, 0), 1:",
"else: self._right_color = self._right_color - 1 self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) logging.debug(\"\\tmove RIGHT foot",
"= \"BW\" else: self._left_color = self._left_color + 1 else: if",
"self._left_direction = \"FW\" else: self._left_color = self._left_color - 1 self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color])",
"== 'RIGHT': self._right_color = self._left_color self.tt_gui.set_large_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color]) else: self._left_color = self._right_color",
"seconds, millis, confidence): act_delay = millis - self._last_beat_millis + randrange(0,",
"next foot on air move if self._next_foot == 'RIGHT': self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color],",
"= self._right_color - 1 self._right_direction = \"BW\" else: self._right_color =",
"FOOT_CHANGE_PERC = 0.3 FOOT_ON_AIR_PERC = 0.08 FEET_ON_SAME_CIRCLE_PERC = 0.05 def",
"FOOT_ON_AIR_PERC = 0.08 FEET_ON_SAME_CIRCLE_PERC = 0.05 def __init__(self, min_delay=0, max_delay=100):",
"(0, 255, 0)} FOOT_CHANGE_PERC = 0.3 FOOT_ON_AIR_PERC = 0.08 FEET_ON_SAME_CIRCLE_PERC",
"< TwoFeetTempoMove.FOOT_CHANGE_PERC: # randomize at 30% the switch on foot",
"(0, 0, 255), 2: (255, 255, 0), 3: (0, 255,",
"self._last_beat_millis = millis self.beat_found() def beat_found(self): millis = self._last_beat_millis logging.debug(\"Randomized",
"self._next_foot = 'RIGHT' logging.info(\"Starting with LEFT: %s, RIGHT: %s\" %",
"%d:%d.%d\" % (act_millis / 60000, act_millis / 1000, act_millis %",
"air move if self._next_foot == 'RIGHT': self.tt_gui.set_right_color(TwoFeetTempoMove.COLORS_ALPHA[self._right_color], on_air=True) else: self.tt_gui.set_left_color(TwoFeetTempoMove.COLORS_ALPHA[self._left_color],",
"if self._next_foot == 'RIGHT': self._next_foot = 'LEFT' else: self._next_foot =",
"randomized next foot on air move if self._next_foot == 'RIGHT':",
"= time() * 1000 def get_colors_alpha(self): return {'RIGHT': TwoFeetTempoMove.COLORS_ALPHA[self._right_color], 'LEFT':",
"with LEFT: %s, RIGHT: %s\" % (TwoFeetTempoMove.COLORS_ALPHA[self._left_color], TwoFeetTempoMove.COLORS_ALPHA[self._right_color])) self.tt_gui =",
"1 self._left_direction = \"FW\" else: self._left_color = self._left_color - 1",
"random import randrange, random from time import time import logging",
"if self._right_color == 0: self._right_color = self._right_color + 1 self._right_direction",
"'LEFT': TwoFeetTempoMove.COLORS_RGB[self._left_color]} def increase_speed(self): self.min_delay = self.min_delay - 10 def",
"def __init__(self, min_delay=0, max_delay=100): assert min_delay >= 0 assert max_delay",
"/ 60000, millis / 1000, millis % 1000)) act_millis =",
"> 0 self.min_delay = min_delay self.max_delay = max_delay self._last_beat_millis ="
] |
[
"plugin to generate statistics from blog posts (number of posts",
"charts. Project location: https://github.com/romainx/panorama \"\"\" __version__ = \"0.2.0\" __author__ =",
"from blog posts (number of posts per month, categories and",
"(number of posts per month, categories and so on) display",
"to generate statistics from blog posts (number of posts per",
"__version__ = \"0.2.0\" __author__ = \"romainx\" from .panorama import *",
"\"\"\" Panorama is a Pelican plugin to generate statistics from",
"them as beautiful charts. Project location: https://github.com/romainx/panorama \"\"\" __version__ =",
"location: https://github.com/romainx/panorama \"\"\" __version__ = \"0.2.0\" __author__ = \"romainx\" from",
"beautiful charts. Project location: https://github.com/romainx/panorama \"\"\" __version__ = \"0.2.0\" __author__",
"Panorama is a Pelican plugin to generate statistics from blog",
"per month, categories and so on) display them as beautiful",
"generate statistics from blog posts (number of posts per month,",
"blog posts (number of posts per month, categories and so",
"categories and so on) display them as beautiful charts. Project",
"-*- \"\"\" Panorama is a Pelican plugin to generate statistics",
"Project location: https://github.com/romainx/panorama \"\"\" __version__ = \"0.2.0\" __author__ = \"romainx\"",
"coding: utf-8 -*- \"\"\" Panorama is a Pelican plugin to",
"https://github.com/romainx/panorama \"\"\" __version__ = \"0.2.0\" __author__ = \"romainx\" from .panorama",
"of posts per month, categories and so on) display them",
"posts per month, categories and so on) display them as",
"-*- coding: utf-8 -*- \"\"\" Panorama is a Pelican plugin",
"display them as beautiful charts. Project location: https://github.com/romainx/panorama \"\"\" __version__",
"Pelican plugin to generate statistics from blog posts (number of",
"is a Pelican plugin to generate statistics from blog posts",
"statistics from blog posts (number of posts per month, categories",
"posts (number of posts per month, categories and so on)",
"as beautiful charts. Project location: https://github.com/romainx/panorama \"\"\" __version__ = \"0.2.0\"",
"<filename>plugins/panorama/panorama/__init__.py # -*- coding: utf-8 -*- \"\"\" Panorama is a",
"and so on) display them as beautiful charts. Project location:",
"so on) display them as beautiful charts. Project location: https://github.com/romainx/panorama",
"\"\"\" __version__ = \"0.2.0\" __author__ = \"romainx\" from .panorama import",
"a Pelican plugin to generate statistics from blog posts (number",
"utf-8 -*- \"\"\" Panorama is a Pelican plugin to generate",
"on) display them as beautiful charts. Project location: https://github.com/romainx/panorama \"\"\"",
"# -*- coding: utf-8 -*- \"\"\" Panorama is a Pelican",
"month, categories and so on) display them as beautiful charts."
] |
[
"then issue a warning. # # Stops that are close",
"self.__dict__.update(field_dict) else: self.from_stop_id = from_stop_id self.to_stop_id = to_stop_id self.transfer_type =",
"self.ValidateFromStopIdIsValid(problems) and valid_stop_ids valid_stop_ids = self.ValidateToStopIdIsValid(problems) and valid_stop_ids # We",
"= None if field_dict: self.__dict__.update(field_dict) else: self.from_stop_id = from_stop_id self.to_stop_id",
"range(0, 4)): problems.InvalidValue('transfer_type', self.transfer_type) return False return True def ValidateMinimumTransferTime(self,",
"both stop IDs to be valid to able to validate",
"2.0 (the \"License\"); # you may not use this file",
"if util.IsEmpty(self.min_transfer_time): return if self.min_transfer_time < 0: # Error has",
"If smaller than 24h but bigger than 3h issue a",
"a transfer \" \\ \"time and most likely indicates \"",
"valid to able to validate their distance and # the",
"# Use the default, recommended transfer, if attribute is not",
"not blocking, and should not prevent the transfer # from",
"/ FAST_WALKING_SPEED: problems.TransferWalkingSpeedTooFast(from_stop_id=self.from_stop_id, to_stop_id=self.to_stop_id, transfer_time=self.min_transfer_time, distance=distance) def ValidateBeforeAdd(self, problems): result",
"together (less than 240m appart) never trigger this # warning,",
"util.NonNegIntStringToInt(self.min_transfer_time) except (TypeError, ValueError): pass else: self.min_transfer_time = None if",
"but bigger than 3h issue a warning. # These errors",
"It has a value, but it is not an integer",
"problems.InvalidValue('to_stop_id', self.to_stop_id) return False return True def ValidateTransferDistance(self, problems): distance",
"(C) 2007 Google Inc. # # Licensed under the Apache",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"schedule.AddTransferObject(self) def ValidateFromStopIdIsPresent(self, problems): if util.IsEmpty(self.from_stop_id): problems.MissingValue('from_stop_id') return False return",
"to the schedule. if (isinstance(self.min_transfer_time, int)): if self.min_transfer_time < 0:",
"self.to_stop_id not in self._schedule.stops.keys(): problems.InvalidValue('to_stop_id', self.to_stop_id) return False return True",
"return True def ValidateTransferType(self, problems): if not util.IsEmpty(self.transfer_type): if (not",
"min_transfer_time. FAST_WALKING_SPEED= 2 # 2m/s if self.min_transfer_time + 120 <",
"to be valid to able to validate their distance and",
"distance=distance) def ValidateBeforeAdd(self, problems): result = True result = self.ValidateFromStopIdIsPresent(problems)",
"schedule=None, from_stop_id=None, to_stop_id=None, transfer_type=None, min_transfer_time=None, field_dict=None): self._schedule = None if",
"util.IsEmpty(self.min_transfer_time): return if self.min_transfer_time < 0: # Error has already",
"Note from Tom, Nov 25, 2009: Maybe calling __init__ with",
"language governing permissions and # limitations under the License. from",
"Validate(self, problems=problems_module.default_problem_reporter): if self.ValidateBeforeAdd(problems) and self._schedule: self.ValidateAfterAdd(problems) def _ID(self): return",
"result = self.ValidateFromStopIdIsPresent(problems) and result result = self.ValidateToStopIdIsPresent(problems) and result",
"# Error has already been reported, and it does not",
"use this file except in compliance with the License. #",
"regardless of min_transfer_time. FAST_WALKING_SPEED= 2 # 2m/s if self.min_transfer_time +",
"!= 2: problems.MinimumTransferTimeSetWithInvalidTransferType( self.transfer_type) # If min_transfer_time is negative, equal",
"but it is not an integer problems.InvalidValue('min_transfer_time', self.min_transfer_time, reason=\"If present,",
"FAST_WALKING_SPEED: problems.TransferWalkingSpeedTooFast(from_stop_id=self.from_stop_id, to_stop_id=self.to_stop_id, transfer_time=self.min_transfer_time, distance=distance) def ValidateBeforeAdd(self, problems): result =",
"FAST_WALKING_SPEED= 2 # 2m/s if self.min_transfer_time + 120 < distance",
"with negative times. return distance = self.GetTransferDistance() # If min_transfer_time",
"warning, regardless of min_transfer_time. FAST_WALKING_SPEED= 2 # 2m/s if self.min_transfer_time",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"problems): if self.to_stop_id not in self._schedule.stops.keys(): problems.InvalidValue('to_stop_id', self.to_stop_id) return False",
"License. # You may obtain a copy of the License",
"is negative, equal to or bigger than 24h, issue #",
"'to_stop_id'] def __init__(self, schedule=None, from_stop_id=None, to_stop_id=None, transfer_type=None, min_transfer_time=None, field_dict=None): self._schedule",
"= 'transfers' _ID_COLUMNS = ['from_stop_id', 'to_stop_id'] def __init__(self, schedule=None, from_stop_id=None,",
"very fast # (2m/s) then issue a warning. # #",
"# These errors are not blocking, and should not prevent",
"default, recommended transfer, if attribute is not set or blank",
"under the License is distributed on an \"AS IS\" BASIS,",
"def ValidateToStopIdIsValid(self, problems): if self.to_stop_id not in self._schedule.stops.keys(): problems.InvalidValue('to_stop_id', self.to_stop_id)",
"License for the specific language governing permissions and # limitations",
"Use the default, recommended transfer, if attribute is not set",
"# Copyright (C) 2007 Google Inc. # # Licensed under",
"Copyright (C) 2007 Google Inc. # # Licensed under the",
"problems as problems_module import util class Transfer(GtfsObjectBase): \"\"\"Represents a transfer",
"distance / FAST_WALKING_SPEED: problems.TransferWalkingSpeedTooFast(from_stop_id=self.from_stop_id, to_stop_id=self.to_stop_id, transfer_time=self.min_transfer_time, distance=distance) def ValidateBeforeAdd(self, problems):",
"= ['from_stop_id', 'to_stop_id', 'transfer_type'] _FIELD_NAMES = _REQUIRED_FIELD_NAMES + ['min_transfer_time'] _TABLE_NAME",
"2m/s if self.min_transfer_time + 120 < distance / FAST_WALKING_SPEED: problems.TransferWalkingSpeedTooFast(from_stop_id=self.from_stop_id,",
"distance = self.GetTransferDistance() if distance > 10000: problems.TransferDistanceTooBig(self.from_stop_id, self.to_stop_id, distance)",
"util.NonNegIntStringToInt(self.transfer_type) except (TypeError, ValueError): pass if hasattr(self, 'min_transfer_time'): try: self.min_transfer_time",
"= min_transfer_time if getattr(self, 'transfer_type', None) in (\"\", None): #",
"True def ValidateTransferDistance(self, problems): distance = self.GetTransferDistance() if distance >",
"indicates \" \\ \"an error.\") else: # It has a",
"Tom, Nov 25, 2009: Maybe calling __init__ with a schedule",
"issue a warning. # These errors are not blocking, and",
"ValidateFromStopIdIsPresent(self, problems): if util.IsEmpty(self.from_stop_id): problems.MissingValue('from_stop_id') return False return True def",
"in compliance with the License. # You may obtain a",
"walking speed with negative times. return distance = self.GetTransferDistance() #",
"software # distributed under the License is distributed on an",
"except (TypeError, ValueError): pass else: self.min_transfer_time = None if schedule",
"a DeprecationWarning. A schedule factory probably won't # use it",
"from_stop_id=None, to_stop_id=None, transfer_type=None, min_transfer_time=None, field_dict=None): self._schedule = None if field_dict:",
"to calculate walking speed with negative times. return distance =",
"self._schedule.stops[self.from_stop_id] to_stop = self._schedule.stops[self.to_stop_id] distance = util.ApproximateDistanceBetweenStops(from_stop, to_stop) return distance",
"to validate their distance and # the walking time between",
"than 240m appart) never trigger this # warning, regardless of",
"3h issue a warning. # These errors are not blocking,",
"large for a transfer \" \\ \"time and most likely",
"ValueError): pass if hasattr(self, 'min_transfer_time'): try: self.min_transfer_time = util.NonNegIntStringToInt(self.min_transfer_time) except",
"value, but it is not an integer problems.InvalidValue('min_transfer_time', self.min_transfer_time, reason=\"If",
"else: try: self.transfer_type = util.NonNegIntStringToInt(self.transfer_type) except (TypeError, ValueError): pass if",
"use it and other GenericGTFSObject subclasses don't support it. schedule.AddTransferObject(self)",
"problems=problems_module.default_problem_reporter): if self.ValidateBeforeAdd(problems) and self._schedule: self.ValidateAfterAdd(problems) def _ID(self): return tuple(self[i]",
"or bigger than 24h, issue # an error. If smaller",
"if self.min_transfer_time < 0: problems.InvalidValue('min_transfer_time', self.min_transfer_time, reason=\"This field cannot contain",
"and valid_stop_ids valid_stop_ids = self.ValidateToStopIdIsValid(problems) and valid_stop_ids # We need",
"from_stop_id self.to_stop_id = to_stop_id self.transfer_type = transfer_type self.min_transfer_time = min_transfer_time",
"this field should contain \" \\ \"an integer value.\") return",
"'transfer_type'] _FIELD_NAMES = _REQUIRED_FIELD_NAMES + ['min_transfer_time'] _TABLE_NAME = 'transfers' _ID_COLUMNS",
"problems.MissingValue('to_stop_id') return False return True def ValidateTransferType(self, problems): if not",
"_ID_COLUMNS = ['from_stop_id', 'to_stop_id'] def __init__(self, schedule=None, from_stop_id=None, to_stop_id=None, transfer_type=None,",
"field should contain \" \\ \"an integer value.\") return False",
"and result return result def ValidateAfterAdd(self, problems): valid_stop_ids = True",
"blank self.transfer_type = 0 else: try: self.transfer_type = util.NonNegIntStringToInt(self.transfer_type) except",
"schedule # should output a DeprecationWarning. A schedule factory probably",
"blocking, and should not prevent the transfer # from being",
"not set or blank self.transfer_type = 0 else: try: self.transfer_type",
"self.to_stop_id = to_stop_id self.transfer_type = transfer_type self.min_transfer_time = min_transfer_time if",
"the transfer # from being added to the schedule. if",
"is not an integer problems.InvalidValue('min_transfer_time', self.min_transfer_time, reason=\"If present, this field",
"if self.min_transfer_time < 0: # Error has already been reported,",
"def ValidateFromStopIdIsPresent(self, problems): if util.IsEmpty(self.from_stop_id): problems.MissingValue('from_stop_id') return False return True",
"not in self._schedule.stops.keys(): problems.InvalidValue('to_stop_id', self.to_stop_id) return False return True def",
"in a schedule\"\"\" _REQUIRED_FIELD_NAMES = ['from_stop_id', 'to_stop_id', 'transfer_type'] _FIELD_NAMES =",
"output a DeprecationWarning. A schedule factory probably won't # use",
"> 10000: problems.TransferDistanceTooBig(self.from_stop_id, self.to_stop_id, distance) elif distance > 2000: problems.TransferDistanceTooBig(self.from_stop_id,",
"walking time between them if valid_stop_ids: self.ValidateTransferDistance(problems) self.ValidateTransferWalkingTime(problems) def Validate(self,",
"True def ValidateTransferType(self, problems): if not util.IsEmpty(self.transfer_type): if (not isinstance(self.transfer_type,",
"negative \" \\ \"value.\") elif self.min_transfer_time >= 24*3600: problems.InvalidValue('min_transfer_time', self.min_transfer_time,",
"120s isn't enough for someone walking very fast # (2m/s)",
"_REQUIRED_FIELD_NAMES = ['from_stop_id', 'to_stop_id', 'transfer_type'] _FIELD_NAMES = _REQUIRED_FIELD_NAMES + ['min_transfer_time']",
"OF ANY KIND, either express or implied. # See the",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"bigger than 3h issue a warning. # These errors are",
"subclasses don't support it. schedule.AddTransferObject(self) def ValidateFromStopIdIsPresent(self, problems): if util.IsEmpty(self.from_stop_id):",
"return distance def ValidateFromStopIdIsValid(self, problems): if self.from_stop_id not in self._schedule.stops.keys():",
"ANY KIND, either express or implied. # See the License",
"See the License for the specific language governing permissions and",
"Stops that are close together (less than 240m appart) never",
"# We need both stop IDs to be valid to",
"# # Stops that are close together (less than 240m",
"the License. # You may obtain a copy of the",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"for the specific language governing permissions and # limitations under",
"to in writing, software # distributed under the License is",
"_REQUIRED_FIELD_NAMES + ['min_transfer_time'] _TABLE_NAME = 'transfers' _ID_COLUMNS = ['from_stop_id', 'to_stop_id']",
"self.min_transfer_time = util.NonNegIntStringToInt(self.min_transfer_time) except (TypeError, ValueError): pass else: self.min_transfer_time =",
"ValidateBeforeAdd(self, problems): result = True result = self.ValidateFromStopIdIsPresent(problems) and result",
"False return True def ValidateToStopIdIsValid(self, problems): if self.to_stop_id not in",
"valid_stop_ids: self.ValidateTransferDistance(problems) self.ValidateTransferWalkingTime(problems) def Validate(self, problems=problems_module.default_problem_reporter): if self.ValidateBeforeAdd(problems) and self._schedule:",
"# See the License for the specific language governing permissions",
"tuple(self[i] for i in self._ID_COLUMNS) def AddToSchedule(self, schedule, problems): schedule.AddTransferObject(self,",
"self.from_stop_id = from_stop_id self.to_stop_id = to_stop_id self.transfer_type = transfer_type self.min_transfer_time",
"False return True def ValidateToStopIdIsPresent(self, problems): if util.IsEmpty(self.to_stop_id): problems.MissingValue('to_stop_id') return",
"(isinstance(self.min_transfer_time, int)): if self.min_transfer_time < 0: problems.InvalidValue('min_transfer_time', self.min_transfer_time, reason=\"This field",
"has already been reported, and it does not make sense",
"# If min_transfer_time + 120s isn't enough for someone walking",
"or agreed to in writing, software # distributed under the",
"problems): valid_stop_ids = True valid_stop_ids = self.ValidateFromStopIdIsValid(problems) and valid_stop_ids valid_stop_ids",
"required by applicable law or agreed to in writing, software",
"2 # 2m/s if self.min_transfer_time + 120 < distance /",
"not an integer problems.InvalidValue('min_transfer_time', self.min_transfer_time, reason=\"If present, this field should",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"and it does not make sense # to calculate walking",
"self.min_transfer_time = min_transfer_time if getattr(self, 'transfer_type', None) in (\"\", None):",
"already been reported, and it does not make sense #",
"with the License. # You may obtain a copy of",
"added to the schedule. if (isinstance(self.min_transfer_time, int)): if self.min_transfer_time <",
"a \" \\ \"transfer time and most likely \" \\",
"and result result = self.ValidateMinimumTransferTime(problems) and result return result def",
"from being added to the schedule. if (isinstance(self.min_transfer_time, int)): if",
"result = self.ValidateMinimumTransferTime(problems) and result return result def ValidateAfterAdd(self, problems):",
"problems.InvalidValue('min_transfer_time', self.min_transfer_time, reason=\"If present, this field should contain \" \\",
"True def GetTransferDistance(self): from_stop = self._schedule.stops[self.from_stop_id] to_stop = self._schedule.stops[self.to_stop_id] distance",
"time and most likely \" \\ \"indicates an error.\") elif",
"If min_transfer_time is negative, equal to or bigger than 24h,",
"to_stop) return distance def ValidateFromStopIdIsValid(self, problems): if self.from_stop_id not in",
"compliance with the License. # You may obtain a copy",
"agreed to in writing, software # distributed under the License",
"_ID(self): return tuple(self[i] for i in self._ID_COLUMNS) def AddToSchedule(self, schedule,",
"= self._schedule.stops[self.to_stop_id] distance = util.ApproximateDistanceBetweenStops(from_stop, to_stop) return distance def ValidateFromStopIdIsValid(self,",
"if getattr(self, 'transfer_type', None) in (\"\", None): # Use the",
"distributed under the License is distributed on an \"AS IS\"",
"self._schedule.stops[self.to_stop_id] distance = util.ApproximateDistanceBetweenStops(from_stop, to_stop) return distance def ValidateFromStopIdIsValid(self, problems):",
"error. If smaller than 24h but bigger than 3h issue",
"\" \\ \"an error.\") else: # It has a value,",
"Error has already been reported, and it does not make",
"= _REQUIRED_FIELD_NAMES + ['min_transfer_time'] _TABLE_NAME = 'transfers' _ID_COLUMNS = ['from_stop_id',",
"try: self.transfer_type = util.NonNegIntStringToInt(self.transfer_type) except (TypeError, ValueError): pass if hasattr(self,",
"likely \" \\ \"indicates an error.\") elif self.min_transfer_time >= 3*3600:",
"_TABLE_NAME = 'transfers' _ID_COLUMNS = ['from_stop_id', 'to_stop_id'] def __init__(self, schedule=None,",
"someone walking very fast # (2m/s) then issue a warning.",
"util.IsEmpty(self.from_stop_id): problems.MissingValue('from_stop_id') return False return True def ValidateToStopIdIsPresent(self, problems): if",
"field cannot contain a negative \" \\ \"value.\") elif self.min_transfer_time",
"min_transfer_time is negative, equal to or bigger than 24h, issue",
"return if self.min_transfer_time < 0: # Error has already been",
"of min_transfer_time. FAST_WALKING_SPEED= 2 # 2m/s if self.min_transfer_time + 120",
"result result = self.ValidateTransferType(problems) and result result = self.ValidateMinimumTransferTime(problems) and",
"express or implied. # See the License for the specific",
"return result def ValidateAfterAdd(self, problems): valid_stop_ids = True valid_stop_ids =",
"False return True def GetTransferDistance(self): from_stop = self._schedule.stops[self.from_stop_id] to_stop =",
"except in compliance with the License. # You may obtain",
"reason=\"The value is very large for a \" \\ \"transfer",
"ValidateToStopIdIsValid(self, problems): if self.to_stop_id not in self._schedule.stops.keys(): problems.InvalidValue('to_stop_id', self.to_stop_id) return",
"self._schedule.stops.keys(): problems.InvalidValue('to_stop_id', self.to_stop_id) return False return True def ValidateTransferDistance(self, problems):",
"def _ID(self): return tuple(self[i] for i in self._ID_COLUMNS) def AddToSchedule(self,",
"result result = self.ValidateToStopIdIsPresent(problems) and result result = self.ValidateTransferType(problems) and",
"if self.ValidateBeforeAdd(problems) and self._schedule: self.ValidateAfterAdd(problems) def _ID(self): return tuple(self[i] for",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"0 else: try: self.transfer_type = util.NonNegIntStringToInt(self.transfer_type) except (TypeError, ValueError): pass",
"ValidateTransferDistance(self, problems): distance = self.GetTransferDistance() if distance > 10000: problems.TransferDistanceTooBig(self.from_stop_id,",
"them if valid_stop_ids: self.ValidateTransferDistance(problems) self.ValidateTransferWalkingTime(problems) def Validate(self, problems=problems_module.default_problem_reporter): if self.ValidateBeforeAdd(problems)",
"not use this file except in compliance with the License.",
"valid_stop_ids = True valid_stop_ids = self.ValidateFromStopIdIsValid(problems) and valid_stop_ids valid_stop_ids =",
"between them if valid_stop_ids: self.ValidateTransferDistance(problems) self.ValidateTransferWalkingTime(problems) def Validate(self, problems=problems_module.default_problem_reporter): if",
"# from being added to the schedule. if (isinstance(self.min_transfer_time, int)):",
"#!/usr/bin/python2.5 # Copyright (C) 2007 Google Inc. # # Licensed",
"(less than 240m appart) never trigger this # warning, regardless",
"if util.IsEmpty(self.to_stop_id): problems.MissingValue('to_stop_id') return False return True def ValidateTransferType(self, problems):",
"if attribute is not set or blank self.transfer_type = 0",
"'to_stop_id', 'transfer_type'] _FIELD_NAMES = _REQUIRED_FIELD_NAMES + ['min_transfer_time'] _TABLE_NAME = 'transfers'",
"don't support it. schedule.AddTransferObject(self) def ValidateFromStopIdIsPresent(self, problems): if util.IsEmpty(self.from_stop_id): problems.MissingValue('from_stop_id')",
"if self.transfer_type != 2: problems.MinimumTransferTimeSetWithInvalidTransferType( self.transfer_type) # If min_transfer_time is",
"writing, software # distributed under the License is distributed on",
"(not isinstance(self.transfer_type, int)) or \\ (self.transfer_type not in range(0, 4)):",
"you may not use this file except in compliance with",
"validate their distance and # the walking time between them",
"self.min_transfer_time < 0: # Error has already been reported, and",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"if not util.IsEmpty(self.min_transfer_time): if self.transfer_type != 2: problems.MinimumTransferTimeSetWithInvalidTransferType( self.transfer_type) #",
"problems): result = True result = self.ValidateFromStopIdIsPresent(problems) and result result",
"not util.IsEmpty(self.transfer_type): if (not isinstance(self.transfer_type, int)) or \\ (self.transfer_type not",
"\\ \"an integer value.\") return False return True def GetTransferDistance(self):",
"able to validate their distance and # the walking time",
"self.to_stop_id) return False return True def ValidateTransferDistance(self, problems): distance =",
"return True def ValidateToStopIdIsValid(self, problems): if self.to_stop_id not in self._schedule.stops.keys():",
"A schedule factory probably won't # use it and other",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"should output a DeprecationWarning. A schedule factory probably won't #",
"problems.InvalidValue('min_transfer_time', self.min_transfer_time, type=problems_module.TYPE_WARNING, reason=\"The value is large for a transfer",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"valid_stop_ids = self.ValidateToStopIdIsValid(problems) and valid_stop_ids # We need both stop",
"a schedule # should output a DeprecationWarning. A schedule factory",
"large for a \" \\ \"transfer time and most likely",
"does not make sense # to calculate walking speed with",
"elif self.min_transfer_time >= 3*3600: problems.InvalidValue('min_transfer_time', self.min_transfer_time, type=problems_module.TYPE_WARNING, reason=\"The value is",
"problems.InvalidValue('min_transfer_time', self.min_transfer_time, reason=\"The value is very large for a \"",
"4)): problems.InvalidValue('transfer_type', self.transfer_type) return False return True def ValidateMinimumTransferTime(self, problems):",
"transfer in a schedule\"\"\" _REQUIRED_FIELD_NAMES = ['from_stop_id', 'to_stop_id', 'transfer_type'] _FIELD_NAMES",
"warning. # These errors are not blocking, and should not",
"and # the walking time between them if valid_stop_ids: self.ValidateTransferDistance(problems)",
"and should not prevent the transfer # from being added",
"distance > 10000: problems.TransferDistanceTooBig(self.from_stop_id, self.to_stop_id, distance) elif distance > 2000:",
"ValidateToStopIdIsPresent(self, problems): if util.IsEmpty(self.to_stop_id): problems.MissingValue('to_stop_id') return False return True def",
"True valid_stop_ids = self.ValidateFromStopIdIsValid(problems) and valid_stop_ids valid_stop_ids = self.ValidateToStopIdIsValid(problems) and",
"trigger this # warning, regardless of min_transfer_time. FAST_WALKING_SPEED= 2 #",
"ValueError): pass else: self.min_transfer_time = None if schedule is not",
"def ValidateToStopIdIsPresent(self, problems): if util.IsEmpty(self.to_stop_id): problems.MissingValue('to_stop_id') return False return True",
"and result result = self.ValidateToStopIdIsPresent(problems) and result result = self.ValidateTransferType(problems)",
"These errors are not blocking, and should not prevent the",
"= self.ValidateToStopIdIsPresent(problems) and result result = self.ValidateTransferType(problems) and result result",
"util.IsEmpty(self.transfer_type): if (not isinstance(self.transfer_type, int)) or \\ (self.transfer_type not in",
"False return True def ValidateTransferType(self, problems): if not util.IsEmpty(self.transfer_type): if",
"# use it and other GenericGTFSObject subclasses don't support it.",
"problems.TransferDistanceTooBig(self.from_stop_id, self.to_stop_id, distance, type=problems_module.TYPE_WARNING) def ValidateTransferWalkingTime(self, problems): if util.IsEmpty(self.min_transfer_time): return",
"\" \\ \"an integer value.\") return False return True def",
"def ValidateTransferDistance(self, problems): distance = self.GetTransferDistance() if distance > 10000:",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"value.\") return False return True def GetTransferDistance(self): from_stop = self._schedule.stops[self.from_stop_id]",
"a value, but it is not an integer problems.InvalidValue('min_transfer_time', self.min_transfer_time,",
"error.\") elif self.min_transfer_time >= 3*3600: problems.InvalidValue('min_transfer_time', self.min_transfer_time, type=problems_module.TYPE_WARNING, reason=\"The value",
"speed with negative times. return distance = self.GetTransferDistance() # If",
"reason=\"This field cannot contain a negative \" \\ \"value.\") elif",
"the License is distributed on an \"AS IS\" BASIS, #",
"self.transfer_type = 0 else: try: self.transfer_type = util.NonNegIntStringToInt(self.transfer_type) except (TypeError,",
"util.IsEmpty(self.to_stop_id): problems.MissingValue('to_stop_id') return False return True def ValidateTransferType(self, problems): if",
"is not set or blank self.transfer_type = 0 else: try:",
"problems): if not util.IsEmpty(self.min_transfer_time): if self.transfer_type != 2: problems.MinimumTransferTimeSetWithInvalidTransferType( self.transfer_type)",
"= self.ValidateFromStopIdIsValid(problems) and valid_stop_ids valid_stop_ids = self.ValidateToStopIdIsValid(problems) and valid_stop_ids #",
"attribute is not set or blank self.transfer_type = 0 else:",
"__init__(self, schedule=None, from_stop_id=None, to_stop_id=None, transfer_type=None, min_transfer_time=None, field_dict=None): self._schedule = None",
"ValidateTransferType(self, problems): if not util.IsEmpty(self.transfer_type): if (not isinstance(self.transfer_type, int)) or",
"< 0: # Error has already been reported, and it",
"transfer_time=self.min_transfer_time, distance=distance) def ValidateBeforeAdd(self, problems): result = True result =",
"If min_transfer_time + 120s isn't enough for someone walking very",
"pass if hasattr(self, 'min_transfer_time'): try: self.min_transfer_time = util.NonNegIntStringToInt(self.min_transfer_time) except (TypeError,",
"License. from gtfsobjectbase import GtfsObjectBase import problems as problems_module import",
"should not prevent the transfer # from being added to",
"schedule. if (isinstance(self.min_transfer_time, int)): if self.min_transfer_time < 0: problems.InvalidValue('min_transfer_time', self.min_transfer_time,",
"problems.TransferWalkingSpeedTooFast(from_stop_id=self.from_stop_id, to_stop_id=self.to_stop_id, transfer_time=self.min_transfer_time, distance=distance) def ValidateBeforeAdd(self, problems): result = True",
"return False return True def ValidateToStopIdIsValid(self, problems): if self.to_stop_id not",
"not in range(0, 4)): problems.InvalidValue('transfer_type', self.transfer_type) return False return True",
"valid_stop_ids valid_stop_ids = self.ValidateToStopIdIsValid(problems) and valid_stop_ids # We need both",
"(TypeError, ValueError): pass if hasattr(self, 'min_transfer_time'): try: self.min_transfer_time = util.NonNegIntStringToInt(self.min_transfer_time)",
"(2m/s) then issue a warning. # # Stops that are",
"if self.min_transfer_time + 120 < distance / FAST_WALKING_SPEED: problems.TransferWalkingSpeedTooFast(from_stop_id=self.from_stop_id, to_stop_id=self.to_stop_id,",
">= 24*3600: problems.InvalidValue('min_transfer_time', self.min_transfer_time, reason=\"The value is very large for",
"law or agreed to in writing, software # distributed under",
"240m appart) never trigger this # warning, regardless of min_transfer_time.",
"min_transfer_time if getattr(self, 'transfer_type', None) in (\"\", None): # Use",
"# (2m/s) then issue a warning. # # Stops that",
"else: self.min_transfer_time = None if schedule is not None: #",
"(self.transfer_type not in range(0, 4)): problems.InvalidValue('transfer_type', self.transfer_type) return False return",
"type=problems_module.TYPE_WARNING, reason=\"The value is large for a transfer \" \\",
"need both stop IDs to be valid to able to",
"problems.InvalidValue('transfer_type', self.transfer_type) return False return True def ValidateMinimumTransferTime(self, problems): if",
"__init__ with a schedule # should output a DeprecationWarning. A",
"self.ValidateMinimumTransferTime(problems) and result return result def ValidateAfterAdd(self, problems): valid_stop_ids =",
"return tuple(self[i] for i in self._ID_COLUMNS) def AddToSchedule(self, schedule, problems):",
"a warning. # These errors are not blocking, and should",
"None if schedule is not None: # Note from Tom,",
"warning. # # Stops that are close together (less than",
"in range(0, 4)): problems.InvalidValue('transfer_type', self.transfer_type) return False return True def",
"result return result def ValidateAfterAdd(self, problems): valid_stop_ids = True valid_stop_ids",
"self.min_transfer_time, type=problems_module.TYPE_WARNING, reason=\"The value is large for a transfer \"",
"distance > 2000: problems.TransferDistanceTooBig(self.from_stop_id, self.to_stop_id, distance, type=problems_module.TYPE_WARNING) def ValidateTransferWalkingTime(self, problems):",
"True result = self.ValidateFromStopIdIsPresent(problems) and result result = self.ValidateToStopIdIsPresent(problems) and",
"try: self.min_transfer_time = util.NonNegIntStringToInt(self.min_transfer_time) except (TypeError, ValueError): pass else: self.min_transfer_time",
"field_dict=None): self._schedule = None if field_dict: self.__dict__.update(field_dict) else: self.from_stop_id =",
"the walking time between them if valid_stop_ids: self.ValidateTransferDistance(problems) self.ValidateTransferWalkingTime(problems) def",
"from gtfsobjectbase import GtfsObjectBase import problems as problems_module import util",
"> 2000: problems.TransferDistanceTooBig(self.from_stop_id, self.to_stop_id, distance, type=problems_module.TYPE_WARNING) def ValidateTransferWalkingTime(self, problems): if",
"# 2m/s if self.min_transfer_time + 120 < distance / FAST_WALKING_SPEED:",
"may obtain a copy of the License at # #",
"if schedule is not None: # Note from Tom, Nov",
"problems): if util.IsEmpty(self.to_stop_id): problems.MissingValue('to_stop_id') return False return True def ValidateTransferType(self,",
"prevent the transfer # from being added to the schedule.",
"never trigger this # warning, regardless of min_transfer_time. FAST_WALKING_SPEED= 2",
"under the License. from gtfsobjectbase import GtfsObjectBase import problems as",
"calculate walking speed with negative times. return distance = self.GetTransferDistance()",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"Inc. # # Licensed under the Apache License, Version 2.0",
"self.min_transfer_time = None if schedule is not None: # Note",
"the default, recommended transfer, if attribute is not set or",
"calling __init__ with a schedule # should output a DeprecationWarning.",
"schedule factory probably won't # use it and other GenericGTFSObject",
"issue # an error. If smaller than 24h but bigger",
"None) in (\"\", None): # Use the default, recommended transfer,",
"if (not isinstance(self.transfer_type, int)) or \\ (self.transfer_type not in range(0,",
"may not use this file except in compliance with the",
"problems): if self.from_stop_id not in self._schedule.stops.keys(): problems.InvalidValue('from_stop_id', self.from_stop_id) return False",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"make sense # to calculate walking speed with negative times.",
"close together (less than 240m appart) never trigger this #",
"self.ValidateAfterAdd(problems) def _ID(self): return tuple(self[i] for i in self._ID_COLUMNS) def",
"value is large for a transfer \" \\ \"time and",
"this file except in compliance with the License. # You",
"self.ValidateToStopIdIsValid(problems) and valid_stop_ids # We need both stop IDs to",
"True def ValidateToStopIdIsValid(self, problems): if self.to_stop_id not in self._schedule.stops.keys(): problems.InvalidValue('to_stop_id',",
"return True def GetTransferDistance(self): from_stop = self._schedule.stops[self.from_stop_id] to_stop = self._schedule.stops[self.to_stop_id]",
"['min_transfer_time'] _TABLE_NAME = 'transfers' _ID_COLUMNS = ['from_stop_id', 'to_stop_id'] def __init__(self,",
"ValidateTransferWalkingTime(self, problems): if util.IsEmpty(self.min_transfer_time): return if self.min_transfer_time < 0: #",
"is very large for a \" \\ \"transfer time and",
"return False return True def ValidateToStopIdIsPresent(self, problems): if util.IsEmpty(self.to_stop_id): problems.MissingValue('to_stop_id')",
"24h, issue # an error. If smaller than 24h but",
"integer value.\") return False return True def GetTransferDistance(self): from_stop =",
"self.to_stop_id, distance, type=problems_module.TYPE_WARNING) def ValidateTransferWalkingTime(self, problems): if util.IsEmpty(self.min_transfer_time): return if",
"(TypeError, ValueError): pass else: self.min_transfer_time = None if schedule is",
"not util.IsEmpty(self.min_transfer_time): if self.transfer_type != 2: problems.MinimumTransferTimeSetWithInvalidTransferType( self.transfer_type) # If",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"cannot contain a negative \" \\ \"value.\") elif self.min_transfer_time >=",
"# # Licensed under the Apache License, Version 2.0 (the",
"bigger than 24h, issue # an error. If smaller than",
"return False return True def ValidateTransferDistance(self, problems): distance = self.GetTransferDistance()",
"# to calculate walking speed with negative times. return distance",
"and result result = self.ValidateTransferType(problems) and result result = self.ValidateMinimumTransferTime(problems)",
"file except in compliance with the License. # You may",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"isinstance(self.transfer_type, int)) or \\ (self.transfer_type not in range(0, 4)): problems.InvalidValue('transfer_type',",
"field_dict: self.__dict__.update(field_dict) else: self.from_stop_id = from_stop_id self.to_stop_id = to_stop_id self.transfer_type",
"is large for a transfer \" \\ \"time and most",
">= 3*3600: problems.InvalidValue('min_transfer_time', self.min_transfer_time, type=problems_module.TYPE_WARNING, reason=\"The value is large for",
"problems): if util.IsEmpty(self.from_stop_id): problems.MissingValue('from_stop_id') return False return True def ValidateToStopIdIsPresent(self,",
"0: problems.InvalidValue('min_transfer_time', self.min_transfer_time, reason=\"This field cannot contain a negative \"",
"GtfsObjectBase import problems as problems_module import util class Transfer(GtfsObjectBase): \"\"\"Represents",
"contain a negative \" \\ \"value.\") elif self.min_transfer_time >= 24*3600:",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"util.ApproximateDistanceBetweenStops(from_stop, to_stop) return distance def ValidateFromStopIdIsValid(self, problems): if self.from_stop_id not",
"Transfer(GtfsObjectBase): \"\"\"Represents a transfer in a schedule\"\"\" _REQUIRED_FIELD_NAMES = ['from_stop_id',",
"a negative \" \\ \"value.\") elif self.min_transfer_time >= 24*3600: problems.InvalidValue('min_transfer_time',",
"\"value.\") elif self.min_transfer_time >= 24*3600: problems.InvalidValue('min_transfer_time', self.min_transfer_time, reason=\"The value is",
"elif distance > 2000: problems.TransferDistanceTooBig(self.from_stop_id, self.to_stop_id, distance, type=problems_module.TYPE_WARNING) def ValidateTransferWalkingTime(self,",
"= None if schedule is not None: # Note from",
"= self.GetTransferDistance() # If min_transfer_time + 120s isn't enough for",
"min_transfer_time=None, field_dict=None): self._schedule = None if field_dict: self.__dict__.update(field_dict) else: self.from_stop_id",
"governing permissions and # limitations under the License. from gtfsobjectbase",
"if valid_stop_ids: self.ValidateTransferDistance(problems) self.ValidateTransferWalkingTime(problems) def Validate(self, problems=problems_module.default_problem_reporter): if self.ValidateBeforeAdd(problems) and",
"transfer, if attribute is not set or blank self.transfer_type =",
"\\ \"value.\") elif self.min_transfer_time >= 24*3600: problems.InvalidValue('min_transfer_time', self.min_transfer_time, reason=\"The value",
"result result = self.ValidateMinimumTransferTime(problems) and result return result def ValidateAfterAdd(self,",
"+ ['min_transfer_time'] _TABLE_NAME = 'transfers' _ID_COLUMNS = ['from_stop_id', 'to_stop_id'] def",
"= self._schedule.stops[self.from_stop_id] to_stop = self._schedule.stops[self.to_stop_id] distance = util.ApproximateDistanceBetweenStops(from_stop, to_stop) return",
"not make sense # to calculate walking speed with negative",
"are not blocking, and should not prevent the transfer #",
"from Tom, Nov 25, 2009: Maybe calling __init__ with a",
"problems): if util.IsEmpty(self.min_transfer_time): return if self.min_transfer_time < 0: # Error",
"and most likely \" \\ \"indicates an error.\") elif self.min_transfer_time",
"def ValidateAfterAdd(self, problems): valid_stop_ids = True valid_stop_ids = self.ValidateFromStopIdIsValid(problems) and",
"\" \\ \"time and most likely indicates \" \\ \"an",
"result def ValidateAfterAdd(self, problems): valid_stop_ids = True valid_stop_ids = self.ValidateFromStopIdIsValid(problems)",
"= self.ValidateToStopIdIsValid(problems) and valid_stop_ids # We need both stop IDs",
"DeprecationWarning. A schedule factory probably won't # use it and",
"\" \\ \"transfer time and most likely \" \\ \"indicates",
"type=problems_module.TYPE_WARNING) def ValidateTransferWalkingTime(self, problems): if util.IsEmpty(self.min_transfer_time): return if self.min_transfer_time <",
"appart) never trigger this # warning, regardless of min_transfer_time. FAST_WALKING_SPEED=",
"= True valid_stop_ids = self.ValidateFromStopIdIsValid(problems) and valid_stop_ids valid_stop_ids = self.ValidateToStopIdIsValid(problems)",
"transfer \" \\ \"time and most likely indicates \" \\",
"self.min_transfer_time < 0: problems.InvalidValue('min_transfer_time', self.min_transfer_time, reason=\"This field cannot contain a",
"if self.from_stop_id not in self._schedule.stops.keys(): problems.InvalidValue('from_stop_id', self.from_stop_id) return False return",
"to_stop = self._schedule.stops[self.to_stop_id] distance = util.ApproximateDistanceBetweenStops(from_stop, to_stop) return distance def",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"False return True def ValidateMinimumTransferTime(self, problems): if not util.IsEmpty(self.min_transfer_time): if",
"schedule is not None: # Note from Tom, Nov 25,",
"self.min_transfer_time + 120 < distance / FAST_WALKING_SPEED: problems.TransferWalkingSpeedTooFast(from_stop_id=self.from_stop_id, to_stop_id=self.to_stop_id, transfer_time=self.min_transfer_time,",
"negative times. return distance = self.GetTransferDistance() # If min_transfer_time +",
"pass else: self.min_transfer_time = None if schedule is not None:",
"most likely \" \\ \"indicates an error.\") elif self.min_transfer_time >=",
"problems.InvalidValue('from_stop_id', self.from_stop_id) return False return True def ValidateToStopIdIsValid(self, problems): if",
"should contain \" \\ \"an integer value.\") return False return",
"def Validate(self, problems=problems_module.default_problem_reporter): if self.ValidateBeforeAdd(problems) and self._schedule: self.ValidateAfterAdd(problems) def _ID(self):",
"self.transfer_type) # If min_transfer_time is negative, equal to or bigger",
"= ['from_stop_id', 'to_stop_id'] def __init__(self, schedule=None, from_stop_id=None, to_stop_id=None, transfer_type=None, min_transfer_time=None,",
"or implied. # See the License for the specific language",
"ValidateMinimumTransferTime(self, problems): if not util.IsEmpty(self.min_transfer_time): if self.transfer_type != 2: problems.MinimumTransferTimeSetWithInvalidTransferType(",
"['from_stop_id', 'to_stop_id'] def __init__(self, schedule=None, from_stop_id=None, to_stop_id=None, transfer_type=None, min_transfer_time=None, field_dict=None):",
"it is not an integer problems.InvalidValue('min_transfer_time', self.min_transfer_time, reason=\"If present, this",
"self.from_stop_id not in self._schedule.stops.keys(): problems.InvalidValue('from_stop_id', self.from_stop_id) return False return True",
"KIND, either express or implied. # See the License for",
"specific language governing permissions and # limitations under the License.",
"return False return True def ValidateMinimumTransferTime(self, problems): if not util.IsEmpty(self.min_transfer_time):",
"self.transfer_type) return False return True def ValidateMinimumTransferTime(self, problems): if not",
"if (isinstance(self.min_transfer_time, int)): if self.min_transfer_time < 0: problems.InvalidValue('min_transfer_time', self.min_transfer_time, reason=\"This",
"valid_stop_ids = self.ValidateFromStopIdIsValid(problems) and valid_stop_ids valid_stop_ids = self.ValidateToStopIdIsValid(problems) and valid_stop_ids",
"return False return True def GetTransferDistance(self): from_stop = self._schedule.stops[self.from_stop_id] to_stop",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"= 0 else: try: self.transfer_type = util.NonNegIntStringToInt(self.transfer_type) except (TypeError, ValueError):",
"10000: problems.TransferDistanceTooBig(self.from_stop_id, self.to_stop_id, distance) elif distance > 2000: problems.TransferDistanceTooBig(self.from_stop_id, self.to_stop_id,",
"class Transfer(GtfsObjectBase): \"\"\"Represents a transfer in a schedule\"\"\" _REQUIRED_FIELD_NAMES =",
"2000: problems.TransferDistanceTooBig(self.from_stop_id, self.to_stop_id, distance, type=problems_module.TYPE_WARNING) def ValidateTransferWalkingTime(self, problems): if util.IsEmpty(self.min_transfer_time):",
"self.GetTransferDistance() # If min_transfer_time + 120s isn't enough for someone",
"Google Inc. # # Licensed under the Apache License, Version",
"= from_stop_id self.to_stop_id = to_stop_id self.transfer_type = transfer_type self.min_transfer_time =",
"self.transfer_type != 2: problems.MinimumTransferTimeSetWithInvalidTransferType( self.transfer_type) # If min_transfer_time is negative,",
"\" \\ \"value.\") elif self.min_transfer_time >= 24*3600: problems.InvalidValue('min_transfer_time', self.min_transfer_time, reason=\"The",
"that are close together (less than 240m appart) never trigger",
"this # warning, regardless of min_transfer_time. FAST_WALKING_SPEED= 2 # 2m/s",
"Maybe calling __init__ with a schedule # should output a",
"it and other GenericGTFSObject subclasses don't support it. schedule.AddTransferObject(self) def",
"likely indicates \" \\ \"an error.\") else: # It has",
"(the \"License\"); # you may not use this file except",
"2009: Maybe calling __init__ with a schedule # should output",
"in self._schedule.stops.keys(): problems.InvalidValue('to_stop_id', self.to_stop_id) return False return True def ValidateTransferDistance(self,",
"# you may not use this file except in compliance",
"['from_stop_id', 'to_stop_id', 'transfer_type'] _FIELD_NAMES = _REQUIRED_FIELD_NAMES + ['min_transfer_time'] _TABLE_NAME =",
"\\ \"an error.\") else: # It has a value, but",
"the License. from gtfsobjectbase import GtfsObjectBase import problems as problems_module",
"def ValidateTransferWalkingTime(self, problems): if util.IsEmpty(self.min_transfer_time): return if self.min_transfer_time < 0:",
"in (\"\", None): # Use the default, recommended transfer, if",
"self.min_transfer_time, reason=\"This field cannot contain a negative \" \\ \"value.\")",
"# should output a DeprecationWarning. A schedule factory probably won't",
"getattr(self, 'transfer_type', None) in (\"\", None): # Use the default,",
"'min_transfer_time'): try: self.min_transfer_time = util.NonNegIntStringToInt(self.min_transfer_time) except (TypeError, ValueError): pass else:",
"self._schedule.stops.keys(): problems.InvalidValue('from_stop_id', self.from_stop_id) return False return True def ValidateToStopIdIsValid(self, problems):",
"than 3h issue a warning. # These errors are not",
"< 0: problems.InvalidValue('min_transfer_time', self.min_transfer_time, reason=\"This field cannot contain a negative",
"factory probably won't # use it and other GenericGTFSObject subclasses",
"# # Unless required by applicable law or agreed to",
"reported, and it does not make sense # to calculate",
"24*3600: problems.InvalidValue('min_transfer_time', self.min_transfer_time, reason=\"The value is very large for a",
"distance) elif distance > 2000: problems.TransferDistanceTooBig(self.from_stop_id, self.to_stop_id, distance, type=problems_module.TYPE_WARNING) def",
"hasattr(self, 'min_transfer_time'): try: self.min_transfer_time = util.NonNegIntStringToInt(self.min_transfer_time) except (TypeError, ValueError): pass",
"recommended transfer, if attribute is not set or blank self.transfer_type",
"if hasattr(self, 'min_transfer_time'): try: self.min_transfer_time = util.NonNegIntStringToInt(self.min_transfer_time) except (TypeError, ValueError):",
"transfer_type=None, min_transfer_time=None, field_dict=None): self._schedule = None if field_dict: self.__dict__.update(field_dict) else:",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"except (TypeError, ValueError): pass if hasattr(self, 'min_transfer_time'): try: self.min_transfer_time =",
"self.min_transfer_time >= 24*3600: problems.InvalidValue('min_transfer_time', self.min_transfer_time, reason=\"The value is very large",
"self.min_transfer_time, reason=\"The value is very large for a \" \\",
"for a \" \\ \"transfer time and most likely \"",
"for a transfer \" \\ \"time and most likely indicates",
"it does not make sense # to calculate walking speed",
"ValidateAfterAdd(self, problems): valid_stop_ids = True valid_stop_ids = self.ValidateFromStopIdIsValid(problems) and valid_stop_ids",
"Version 2.0 (the \"License\"); # you may not use this",
"def __init__(self, schedule=None, from_stop_id=None, to_stop_id=None, transfer_type=None, min_transfer_time=None, field_dict=None): self._schedule =",
"reason=\"If present, this field should contain \" \\ \"an integer",
"0: # Error has already been reported, and it does",
"2: problems.MinimumTransferTimeSetWithInvalidTransferType( self.transfer_type) # If min_transfer_time is negative, equal to",
"problems): if not util.IsEmpty(self.transfer_type): if (not isinstance(self.transfer_type, int)) or \\",
"else: # It has a value, but it is not",
"a warning. # # Stops that are close together (less",
"integer problems.InvalidValue('min_transfer_time', self.min_transfer_time, reason=\"If present, this field should contain \"",
"\\ (self.transfer_type not in range(0, 4)): problems.InvalidValue('transfer_type', self.transfer_type) return False",
"distance def ValidateFromStopIdIsValid(self, problems): if self.from_stop_id not in self._schedule.stops.keys(): problems.InvalidValue('from_stop_id',",
"= self.GetTransferDistance() if distance > 10000: problems.TransferDistanceTooBig(self.from_stop_id, self.to_stop_id, distance) elif",
"implied. # See the License for the specific language governing",
"being added to the schedule. if (isinstance(self.min_transfer_time, int)): if self.min_transfer_time",
"to_stop_id=None, transfer_type=None, min_transfer_time=None, field_dict=None): self._schedule = None if field_dict: self.__dict__.update(field_dict)",
"ValidateFromStopIdIsValid(self, problems): if self.from_stop_id not in self._schedule.stops.keys(): problems.InvalidValue('from_stop_id', self.from_stop_id) return",
"result = self.ValidateTransferType(problems) and result result = self.ValidateMinimumTransferTime(problems) and result",
"with a schedule # should output a DeprecationWarning. A schedule",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"24h but bigger than 3h issue a warning. # These",
"are close together (less than 240m appart) never trigger this",
"problems.MissingValue('from_stop_id') return False return True def ValidateToStopIdIsPresent(self, problems): if util.IsEmpty(self.to_stop_id):",
"contain \" \\ \"an integer value.\") return False return True",
"import problems as problems_module import util class Transfer(GtfsObjectBase): \"\"\"Represents a",
"= self.ValidateMinimumTransferTime(problems) and result return result def ValidateAfterAdd(self, problems): valid_stop_ids",
"by applicable law or agreed to in writing, software #",
"self.transfer_type = util.NonNegIntStringToInt(self.transfer_type) except (TypeError, ValueError): pass if hasattr(self, 'min_transfer_time'):",
"if not util.IsEmpty(self.transfer_type): if (not isinstance(self.transfer_type, int)) or \\ (self.transfer_type",
"= True result = self.ValidateFromStopIdIsPresent(problems) and result result = self.ValidateToStopIdIsPresent(problems)",
"problems.InvalidValue('min_transfer_time', self.min_transfer_time, reason=\"This field cannot contain a negative \" \\",
"GenericGTFSObject subclasses don't support it. schedule.AddTransferObject(self) def ValidateFromStopIdIsPresent(self, problems): if",
"not prevent the transfer # from being added to the",
"else: self.from_stop_id = from_stop_id self.to_stop_id = to_stop_id self.transfer_type = transfer_type",
"as problems_module import util class Transfer(GtfsObjectBase): \"\"\"Represents a transfer in",
"or \\ (self.transfer_type not in range(0, 4)): problems.InvalidValue('transfer_type', self.transfer_type) return",
"def GetTransferDistance(self): from_stop = self._schedule.stops[self.from_stop_id] to_stop = self._schedule.stops[self.to_stop_id] distance =",
"valid_stop_ids # We need both stop IDs to be valid",
"None): # Use the default, recommended transfer, if attribute is",
"= self.ValidateTransferType(problems) and result result = self.ValidateMinimumTransferTime(problems) and result return",
"is not None: # Note from Tom, Nov 25, 2009:",
"True def ValidateMinimumTransferTime(self, problems): if not util.IsEmpty(self.min_transfer_time): if self.transfer_type !=",
"\"\"\"Represents a transfer in a schedule\"\"\" _REQUIRED_FIELD_NAMES = ['from_stop_id', 'to_stop_id',",
"negative, equal to or bigger than 24h, issue # an",
"def ValidateFromStopIdIsValid(self, problems): if self.from_stop_id not in self._schedule.stops.keys(): problems.InvalidValue('from_stop_id', self.from_stop_id)",
"not in self._schedule.stops.keys(): problems.InvalidValue('from_stop_id', self.from_stop_id) return False return True def",
"their distance and # the walking time between them if",
"for someone walking very fast # (2m/s) then issue a",
"permissions and # limitations under the License. from gtfsobjectbase import",
"_FIELD_NAMES = _REQUIRED_FIELD_NAMES + ['min_transfer_time'] _TABLE_NAME = 'transfers' _ID_COLUMNS =",
"self._schedule: self.ValidateAfterAdd(problems) def _ID(self): return tuple(self[i] for i in self._ID_COLUMNS)",
"problems_module import util class Transfer(GtfsObjectBase): \"\"\"Represents a transfer in a",
"has a value, but it is not an integer problems.InvalidValue('min_transfer_time',",
"a schedule\"\"\" _REQUIRED_FIELD_NAMES = ['from_stop_id', 'to_stop_id', 'transfer_type'] _FIELD_NAMES = _REQUIRED_FIELD_NAMES",
"+ 120 < distance / FAST_WALKING_SPEED: problems.TransferWalkingSpeedTooFast(from_stop_id=self.from_stop_id, to_stop_id=self.to_stop_id, transfer_time=self.min_transfer_time, distance=distance)",
"to_stop_id self.transfer_type = transfer_type self.min_transfer_time = min_transfer_time if getattr(self, 'transfer_type',",
"False return True def ValidateTransferDistance(self, problems): distance = self.GetTransferDistance() if",
"< distance / FAST_WALKING_SPEED: problems.TransferWalkingSpeedTooFast(from_stop_id=self.from_stop_id, to_stop_id=self.to_stop_id, transfer_time=self.min_transfer_time, distance=distance) def ValidateBeforeAdd(self,",
"def ValidateTransferType(self, problems): if not util.IsEmpty(self.transfer_type): if (not isinstance(self.transfer_type, int))",
"result = True result = self.ValidateFromStopIdIsPresent(problems) and result result =",
"schedule\"\"\" _REQUIRED_FIELD_NAMES = ['from_stop_id', 'to_stop_id', 'transfer_type'] _FIELD_NAMES = _REQUIRED_FIELD_NAMES +",
"an error. If smaller than 24h but bigger than 3h",
"elif self.min_transfer_time >= 24*3600: problems.InvalidValue('min_transfer_time', self.min_transfer_time, reason=\"The value is very",
"We need both stop IDs to be valid to able",
"True def ValidateToStopIdIsPresent(self, problems): if util.IsEmpty(self.to_stop_id): problems.MissingValue('to_stop_id') return False return",
"return distance = self.GetTransferDistance() # If min_transfer_time + 120s isn't",
"equal to or bigger than 24h, issue # an error.",
"self.min_transfer_time, reason=\"If present, this field should contain \" \\ \"an",
"times. return distance = self.GetTransferDistance() # If min_transfer_time + 120s",
"# limitations under the License. from gtfsobjectbase import GtfsObjectBase import",
"+ 120s isn't enough for someone walking very fast #",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"probably won't # use it and other GenericGTFSObject subclasses don't",
"Unless required by applicable law or agreed to in writing,",
"(\"\", None): # Use the default, recommended transfer, if attribute",
"self.ValidateTransferWalkingTime(problems) def Validate(self, problems=problems_module.default_problem_reporter): if self.ValidateBeforeAdd(problems) and self._schedule: self.ValidateAfterAdd(problems) def",
"for i in self._ID_COLUMNS) def AddToSchedule(self, schedule, problems): schedule.AddTransferObject(self, problems)",
"\"time and most likely indicates \" \\ \"an error.\") else:",
"util class Transfer(GtfsObjectBase): \"\"\"Represents a transfer in a schedule\"\"\" _REQUIRED_FIELD_NAMES",
"a transfer in a schedule\"\"\" _REQUIRED_FIELD_NAMES = ['from_stop_id', 'to_stop_id', 'transfer_type']",
"= to_stop_id self.transfer_type = transfer_type self.min_transfer_time = min_transfer_time if getattr(self,",
"present, this field should contain \" \\ \"an integer value.\")",
"be valid to able to validate their distance and #",
"the specific language governing permissions and # limitations under the",
"value is very large for a \" \\ \"transfer time",
"applicable law or agreed to in writing, software # distributed",
"enough for someone walking very fast # (2m/s) then issue",
"and valid_stop_ids # We need both stop IDs to be",
"not None: # Note from Tom, Nov 25, 2009: Maybe",
"self.transfer_type = transfer_type self.min_transfer_time = min_transfer_time if getattr(self, 'transfer_type', None)",
"problems.TransferDistanceTooBig(self.from_stop_id, self.to_stop_id, distance) elif distance > 2000: problems.TransferDistanceTooBig(self.from_stop_id, self.to_stop_id, distance,",
"and most likely indicates \" \\ \"an error.\") else: #",
"min_transfer_time + 120s isn't enough for someone walking very fast",
"\\ \"transfer time and most likely \" \\ \"indicates an",
"self.ValidateTransferType(problems) and result result = self.ValidateMinimumTransferTime(problems) and result return result",
"support it. schedule.AddTransferObject(self) def ValidateFromStopIdIsPresent(self, problems): if util.IsEmpty(self.from_stop_id): problems.MissingValue('from_stop_id') return",
"in writing, software # distributed under the License is distributed",
"self.ValidateFromStopIdIsPresent(problems) and result result = self.ValidateToStopIdIsPresent(problems) and result result =",
"error.\") else: # It has a value, but it is",
"been reported, and it does not make sense # to",
"and self._schedule: self.ValidateAfterAdd(problems) def _ID(self): return tuple(self[i] for i in",
"in self._schedule.stops.keys(): problems.InvalidValue('from_stop_id', self.from_stop_id) return False return True def ValidateToStopIdIsValid(self,",
"= util.NonNegIntStringToInt(self.min_transfer_time) except (TypeError, ValueError): pass else: self.min_transfer_time = None",
"issue a warning. # # Stops that are close together",
"set or blank self.transfer_type = 0 else: try: self.transfer_type =",
"to_stop_id=self.to_stop_id, transfer_time=self.min_transfer_time, distance=distance) def ValidateBeforeAdd(self, problems): result = True result",
"Nov 25, 2009: Maybe calling __init__ with a schedule #",
"# warning, regardless of min_transfer_time. FAST_WALKING_SPEED= 2 # 2m/s if",
"reason=\"The value is large for a transfer \" \\ \"time",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"\"transfer time and most likely \" \\ \"indicates an error.\")",
"License, Version 2.0 (the \"License\"); # you may not use",
"# You may obtain a copy of the License at",
"return True def ValidateTransferDistance(self, problems): distance = self.GetTransferDistance() if distance",
"self.ValidateBeforeAdd(problems) and self._schedule: self.ValidateAfterAdd(problems) def _ID(self): return tuple(self[i] for i",
"self._schedule = None if field_dict: self.__dict__.update(field_dict) else: self.from_stop_id = from_stop_id",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"smaller than 24h but bigger than 3h issue a warning.",
"'transfer_type', None) in (\"\", None): # Use the default, recommended",
"\"an integer value.\") return False return True def GetTransferDistance(self): from_stop",
"\\ \"indicates an error.\") elif self.min_transfer_time >= 3*3600: problems.InvalidValue('min_transfer_time', self.min_transfer_time,",
"distance = util.ApproximateDistanceBetweenStops(from_stop, to_stop) return distance def ValidateFromStopIdIsValid(self, problems): if",
"if distance > 10000: problems.TransferDistanceTooBig(self.from_stop_id, self.to_stop_id, distance) elif distance >",
"return True def ValidateToStopIdIsPresent(self, problems): if util.IsEmpty(self.to_stop_id): problems.MissingValue('to_stop_id') return False",
"self.ValidateToStopIdIsPresent(problems) and result result = self.ValidateTransferType(problems) and result result =",
"the License for the specific language governing permissions and #",
"an error.\") elif self.min_transfer_time >= 3*3600: problems.InvalidValue('min_transfer_time', self.min_transfer_time, type=problems_module.TYPE_WARNING, reason=\"The",
"distance = self.GetTransferDistance() # If min_transfer_time + 120s isn't enough",
"walking very fast # (2m/s) then issue a warning. #",
"result = self.ValidateToStopIdIsPresent(problems) and result result = self.ValidateTransferType(problems) and result",
"return False return True def ValidateTransferType(self, problems): if not util.IsEmpty(self.transfer_type):",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"either express or implied. # See the License for the",
"int)): if self.min_transfer_time < 0: problems.InvalidValue('min_transfer_time', self.min_transfer_time, reason=\"This field cannot",
"self.to_stop_id, distance) elif distance > 2000: problems.TransferDistanceTooBig(self.from_stop_id, self.to_stop_id, distance, type=problems_module.TYPE_WARNING)",
"transfer_type self.min_transfer_time = min_transfer_time if getattr(self, 'transfer_type', None) in (\"\",",
"def ValidateBeforeAdd(self, problems): result = True result = self.ValidateFromStopIdIsPresent(problems) and",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"\"an error.\") else: # It has a value, but it",
"# Note from Tom, Nov 25, 2009: Maybe calling __init__",
"\"indicates an error.\") elif self.min_transfer_time >= 3*3600: problems.InvalidValue('min_transfer_time', self.min_transfer_time, type=problems_module.TYPE_WARNING,",
"distance, type=problems_module.TYPE_WARNING) def ValidateTransferWalkingTime(self, problems): if util.IsEmpty(self.min_transfer_time): return if self.min_transfer_time",
"and other GenericGTFSObject subclasses don't support it. schedule.AddTransferObject(self) def ValidateFromStopIdIsPresent(self,",
"transfer # from being added to the schedule. if (isinstance(self.min_transfer_time,",
"to able to validate their distance and # the walking",
"self.GetTransferDistance() if distance > 10000: problems.TransferDistanceTooBig(self.from_stop_id, self.to_stop_id, distance) elif distance",
"self.min_transfer_time >= 3*3600: problems.InvalidValue('min_transfer_time', self.min_transfer_time, type=problems_module.TYPE_WARNING, reason=\"The value is large",
"problems.MinimumTransferTimeSetWithInvalidTransferType( self.transfer_type) # If min_transfer_time is negative, equal to or",
"to or bigger than 24h, issue # an error. If",
"than 24h, issue # an error. If smaller than 24h",
"an integer problems.InvalidValue('min_transfer_time', self.min_transfer_time, reason=\"If present, this field should contain",
"problems): distance = self.GetTransferDistance() if distance > 10000: problems.TransferDistanceTooBig(self.from_stop_id, self.to_stop_id,",
"# If min_transfer_time is negative, equal to or bigger than",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"GetTransferDistance(self): from_stop = self._schedule.stops[self.from_stop_id] to_stop = self._schedule.stops[self.to_stop_id] distance = util.ApproximateDistanceBetweenStops(from_stop,",
"\\ \"time and most likely indicates \" \\ \"an error.\")",
"util.IsEmpty(self.min_transfer_time): if self.transfer_type != 2: problems.MinimumTransferTimeSetWithInvalidTransferType( self.transfer_type) # If min_transfer_time",
"other GenericGTFSObject subclasses don't support it. schedule.AddTransferObject(self) def ValidateFromStopIdIsPresent(self, problems):",
"= util.NonNegIntStringToInt(self.transfer_type) except (TypeError, ValueError): pass if hasattr(self, 'min_transfer_time'): try:",
"def ValidateMinimumTransferTime(self, problems): if not util.IsEmpty(self.min_transfer_time): if self.transfer_type != 2:",
"sense # to calculate walking speed with negative times. return",
"None if field_dict: self.__dict__.update(field_dict) else: self.from_stop_id = from_stop_id self.to_stop_id =",
"return True def ValidateMinimumTransferTime(self, problems): if not util.IsEmpty(self.min_transfer_time): if self.transfer_type",
"3*3600: problems.InvalidValue('min_transfer_time', self.min_transfer_time, type=problems_module.TYPE_WARNING, reason=\"The value is large for a",
"if self.to_stop_id not in self._schedule.stops.keys(): problems.InvalidValue('to_stop_id', self.to_stop_id) return False return",
"= self.ValidateFromStopIdIsPresent(problems) and result result = self.ValidateToStopIdIsPresent(problems) and result result",
"if util.IsEmpty(self.from_stop_id): problems.MissingValue('from_stop_id') return False return True def ValidateToStopIdIsPresent(self, problems):",
"# the walking time between them if valid_stop_ids: self.ValidateTransferDistance(problems) self.ValidateTransferWalkingTime(problems)",
"self.from_stop_id) return False return True def ValidateToStopIdIsValid(self, problems): if self.to_stop_id",
"\"License\"); # you may not use this file except in",
"# an error. If smaller than 24h but bigger than",
"# Stops that are close together (less than 240m appart)",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"'transfers' _ID_COLUMNS = ['from_stop_id', 'to_stop_id'] def __init__(self, schedule=None, from_stop_id=None, to_stop_id=None,",
"from_stop = self._schedule.stops[self.from_stop_id] to_stop = self._schedule.stops[self.to_stop_id] distance = util.ApproximateDistanceBetweenStops(from_stop, to_stop)",
"# distributed under the License is distributed on an \"AS",
"# It has a value, but it is not an",
"gtfsobjectbase import GtfsObjectBase import problems as problems_module import util class",
"# Unless required by applicable law or agreed to in",
"it. schedule.AddTransferObject(self) def ValidateFromStopIdIsPresent(self, problems): if util.IsEmpty(self.from_stop_id): problems.MissingValue('from_stop_id') return False",
"self.ValidateTransferDistance(problems) self.ValidateTransferWalkingTime(problems) def Validate(self, problems=problems_module.default_problem_reporter): if self.ValidateBeforeAdd(problems) and self._schedule: self.ValidateAfterAdd(problems)",
"import util class Transfer(GtfsObjectBase): \"\"\"Represents a transfer in a schedule\"\"\"",
"time between them if valid_stop_ids: self.ValidateTransferDistance(problems) self.ValidateTransferWalkingTime(problems) def Validate(self, problems=problems_module.default_problem_reporter):",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"errors are not blocking, and should not prevent the transfer",
"None: # Note from Tom, Nov 25, 2009: Maybe calling",
"stop IDs to be valid to able to validate their",
"very large for a \" \\ \"transfer time and most",
"and # limitations under the License. from gtfsobjectbase import GtfsObjectBase",
"than 24h but bigger than 3h issue a warning. #",
"You may obtain a copy of the License at #",
"int)) or \\ (self.transfer_type not in range(0, 4)): problems.InvalidValue('transfer_type', self.transfer_type)",
"distance and # the walking time between them if valid_stop_ids:",
"most likely indicates \" \\ \"an error.\") else: # It",
"isn't enough for someone walking very fast # (2m/s) then",
"fast # (2m/s) then issue a warning. # # Stops",
"import GtfsObjectBase import problems as problems_module import util class Transfer(GtfsObjectBase):",
"2007 Google Inc. # # Licensed under the Apache License,",
"25, 2009: Maybe calling __init__ with a schedule # should",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"or blank self.transfer_type = 0 else: try: self.transfer_type = util.NonNegIntStringToInt(self.transfer_type)",
"won't # use it and other GenericGTFSObject subclasses don't support",
"120 < distance / FAST_WALKING_SPEED: problems.TransferWalkingSpeedTooFast(from_stop_id=self.from_stop_id, to_stop_id=self.to_stop_id, transfer_time=self.min_transfer_time, distance=distance) def",
"if field_dict: self.__dict__.update(field_dict) else: self.from_stop_id = from_stop_id self.to_stop_id = to_stop_id",
"the schedule. if (isinstance(self.min_transfer_time, int)): if self.min_transfer_time < 0: problems.InvalidValue('min_transfer_time',",
"= transfer_type self.min_transfer_time = min_transfer_time if getattr(self, 'transfer_type', None) in",
"= util.ApproximateDistanceBetweenStops(from_stop, to_stop) return distance def ValidateFromStopIdIsValid(self, problems): if self.from_stop_id",
"\" \\ \"indicates an error.\") elif self.min_transfer_time >= 3*3600: problems.InvalidValue('min_transfer_time',",
"IDs to be valid to able to validate their distance",
"limitations under the License. from gtfsobjectbase import GtfsObjectBase import problems"
] |
[
"name='find_friends'), path('profile',views.profile, name='profile'), path('profile_update', views.profile_update, name='profile_update'), path('user/<str:username>', UserPostListView.as_view(), name='user_posts'), path('post/<int:pk>/',PostDetailView.as_view(),",
"path('profile_photos',views.profile_photos, name='profile_photos'), path('comment_update/<int:id>',views.comment_update, name='comment_update'), path('comment/<int:pk>/update',CommentUpdateView.as_view(), name='comment-update' ), path('delete/<int:id>',views.delete, name='delete'), path('favourite',views.favourite,",
"path('post/new/',PostCreateView.as_view(), name='post-create' ), path('post_update',views.post_update, name='post_update'), path('post/<int:pk>/update',PostUpdateView.as_view(), name='post-update' ), path('profile_photos',views.profile_photos, name='profile_photos'),",
"import UserPostListView, PostDetailView, PostDeleteview, PostCreateView, PostUpdateView,CommentUpdateView, VideoCreateView, video_update urlpatterns =",
"VideoCreateView, video_update urlpatterns = [ path('',views.base, name='base'), path('login',views.login, name='login'), path('register',views.register,",
"name='like_post'), path('find_friends',views.find_friends, name='find_friends'), path('profile',views.profile, name='profile'), path('profile_update', views.profile_update, name='profile_update'), path('user/<str:username>', UserPostListView.as_view(),",
"path from . import views from . views import UserPostListView,",
"= [ path('',views.base, name='base'), path('login',views.login, name='login'), path('register',views.register, name='register'), path('index',views.index, name='index'),",
"PostCreateView, PostUpdateView,CommentUpdateView, VideoCreateView, video_update urlpatterns = [ path('',views.base, name='base'), path('login',views.login,",
"path('profile',views.profile, name='profile'), path('profile_update', views.profile_update, name='profile_update'), path('user/<str:username>', UserPostListView.as_view(), name='user_posts'), path('post/<int:pk>/',PostDetailView.as_view(), name='post_details'",
"from django.urls import path from . import views from .",
"path('login',views.login, name='login'), path('register',views.register, name='register'), path('index',views.index, name='index'), path('logout',views.logout, name='logout'), path('like_post', views.like_post,",
"PostDetailView, PostDeleteview, PostCreateView, PostUpdateView,CommentUpdateView, VideoCreateView, video_update urlpatterns = [ path('',views.base,",
"name='comment-update' ), path('delete/<int:id>',views.delete, name='delete'), path('favourite',views.favourite, name='favourite'), path('favourite_posts',views.favourite_posts, name='favourite_posts'), path('video/new/',VideoCreateView.as_view(), name='video-create'",
"), path('profile_posts',views.profile_posts, name='profile_posts'), path('results',views.results, name='results'), path('post/new/',PostCreateView.as_view(), name='post-create' ), path('post_update',views.post_update, name='post_update'),",
"views.profile_update, name='profile_update'), path('user/<str:username>', UserPostListView.as_view(), name='user_posts'), path('post/<int:pk>/',PostDetailView.as_view(), name='post_details' ), path('post/<int:pk>/delete/',PostDeleteview.as_view(), name='post_delete'",
"), path('post/<int:pk>/video',video_update.as_view(), name='video_update' ), # path('<str:username>',views.userprofile, name='userprofile'), path('video_posts',views.video_posts, name='video_posts'), path('user_videos',views.user_videos,name='user_videos'),",
"path('profile_posts',views.profile_posts, name='profile_posts'), path('results',views.results, name='results'), path('post/new/',PostCreateView.as_view(), name='post-create' ), path('post_update',views.post_update, name='post_update'), path('post/<int:pk>/update',PostUpdateView.as_view(),",
"name='results'), path('post/new/',PostCreateView.as_view(), name='post-create' ), path('post_update',views.post_update, name='post_update'), path('post/<int:pk>/update',PostUpdateView.as_view(), name='post-update' ), path('profile_photos',views.profile_photos,",
"name='user_posts'), path('post/<int:pk>/',PostDetailView.as_view(), name='post_details' ), path('post/<int:pk>/delete/',PostDeleteview.as_view(), name='post_delete' ), path('profile_posts',views.profile_posts, name='profile_posts'), path('results',views.results,",
"import views from . views import UserPostListView, PostDetailView, PostDeleteview, PostCreateView,",
". import views from . views import UserPostListView, PostDetailView, PostDeleteview,",
"path('post/<int:pk>/',PostDetailView.as_view(), name='post_details' ), path('post/<int:pk>/delete/',PostDeleteview.as_view(), name='post_delete' ), path('profile_posts',views.profile_posts, name='profile_posts'), path('results',views.results, name='results'),",
". views import UserPostListView, PostDetailView, PostDeleteview, PostCreateView, PostUpdateView,CommentUpdateView, VideoCreateView, video_update",
"name='profile_update'), path('user/<str:username>', UserPostListView.as_view(), name='user_posts'), path('post/<int:pk>/',PostDetailView.as_view(), name='post_details' ), path('post/<int:pk>/delete/',PostDeleteview.as_view(), name='post_delete' ),",
"views import UserPostListView, PostDetailView, PostDeleteview, PostCreateView, PostUpdateView,CommentUpdateView, VideoCreateView, video_update urlpatterns",
"path('user/<str:username>', UserPostListView.as_view(), name='user_posts'), path('post/<int:pk>/',PostDetailView.as_view(), name='post_details' ), path('post/<int:pk>/delete/',PostDeleteview.as_view(), name='post_delete' ), path('profile_posts',views.profile_posts,",
"path('delete/<int:id>',views.delete, name='delete'), path('favourite',views.favourite, name='favourite'), path('favourite_posts',views.favourite_posts, name='favourite_posts'), path('video/new/',VideoCreateView.as_view(), name='video-create' ), path('post/<int:pk>/video',video_update.as_view(),",
"name='delete'), path('favourite',views.favourite, name='favourite'), path('favourite_posts',views.favourite_posts, name='favourite_posts'), path('video/new/',VideoCreateView.as_view(), name='video-create' ), path('post/<int:pk>/video',video_update.as_view(), name='video_update'",
"django.urls import path from . import views from . views",
"name='profile'), path('profile_update', views.profile_update, name='profile_update'), path('user/<str:username>', UserPostListView.as_view(), name='user_posts'), path('post/<int:pk>/',PostDetailView.as_view(), name='post_details' ),",
"import path from . import views from . views import",
"[ path('',views.base, name='base'), path('login',views.login, name='login'), path('register',views.register, name='register'), path('index',views.index, name='index'), path('logout',views.logout,",
"path('favourite_posts',views.favourite_posts, name='favourite_posts'), path('video/new/',VideoCreateView.as_view(), name='video-create' ), path('post/<int:pk>/video',video_update.as_view(), name='video_update' ), # path('<str:username>',views.userprofile,",
"), path('post/<int:pk>/delete/',PostDeleteview.as_view(), name='post_delete' ), path('profile_posts',views.profile_posts, name='profile_posts'), path('results',views.results, name='results'), path('post/new/',PostCreateView.as_view(), name='post-create'",
"name='comment_update'), path('comment/<int:pk>/update',CommentUpdateView.as_view(), name='comment-update' ), path('delete/<int:id>',views.delete, name='delete'), path('favourite',views.favourite, name='favourite'), path('favourite_posts',views.favourite_posts, name='favourite_posts'),",
"name='post_delete' ), path('profile_posts',views.profile_posts, name='profile_posts'), path('results',views.results, name='results'), path('post/new/',PostCreateView.as_view(), name='post-create' ), path('post_update',views.post_update,",
"name='profile_posts'), path('results',views.results, name='results'), path('post/new/',PostCreateView.as_view(), name='post-create' ), path('post_update',views.post_update, name='post_update'), path('post/<int:pk>/update',PostUpdateView.as_view(), name='post-update'",
"), path('profile_photos',views.profile_photos, name='profile_photos'), path('comment_update/<int:id>',views.comment_update, name='comment_update'), path('comment/<int:pk>/update',CommentUpdateView.as_view(), name='comment-update' ), path('delete/<int:id>',views.delete, name='delete'),",
"name='video-create' ), path('post/<int:pk>/video',video_update.as_view(), name='video_update' ), # path('<str:username>',views.userprofile, name='userprofile'), path('video_posts',views.video_posts, name='video_posts'),",
"path('post/<int:pk>/video',video_update.as_view(), name='video_update' ), # path('<str:username>',views.userprofile, name='userprofile'), path('video_posts',views.video_posts, name='video_posts'), path('user_videos',views.user_videos,name='user_videos'), ]",
"), path('delete/<int:id>',views.delete, name='delete'), path('favourite',views.favourite, name='favourite'), path('favourite_posts',views.favourite_posts, name='favourite_posts'), path('video/new/',VideoCreateView.as_view(), name='video-create' ),",
"name='favourite'), path('favourite_posts',views.favourite_posts, name='favourite_posts'), path('video/new/',VideoCreateView.as_view(), name='video-create' ), path('post/<int:pk>/video',video_update.as_view(), name='video_update' ), #",
"path('comment_update/<int:id>',views.comment_update, name='comment_update'), path('comment/<int:pk>/update',CommentUpdateView.as_view(), name='comment-update' ), path('delete/<int:id>',views.delete, name='delete'), path('favourite',views.favourite, name='favourite'), path('favourite_posts',views.favourite_posts,",
"name='login'), path('register',views.register, name='register'), path('index',views.index, name='index'), path('logout',views.logout, name='logout'), path('like_post', views.like_post, name='like_post'),",
"name='post-update' ), path('profile_photos',views.profile_photos, name='profile_photos'), path('comment_update/<int:id>',views.comment_update, name='comment_update'), path('comment/<int:pk>/update',CommentUpdateView.as_view(), name='comment-update' ), path('delete/<int:id>',views.delete,",
"path('post_update',views.post_update, name='post_update'), path('post/<int:pk>/update',PostUpdateView.as_view(), name='post-update' ), path('profile_photos',views.profile_photos, name='profile_photos'), path('comment_update/<int:id>',views.comment_update, name='comment_update'), path('comment/<int:pk>/update',CommentUpdateView.as_view(),",
"path('comment/<int:pk>/update',CommentUpdateView.as_view(), name='comment-update' ), path('delete/<int:id>',views.delete, name='delete'), path('favourite',views.favourite, name='favourite'), path('favourite_posts',views.favourite_posts, name='favourite_posts'), path('video/new/',VideoCreateView.as_view(),",
"name='post_update'), path('post/<int:pk>/update',PostUpdateView.as_view(), name='post-update' ), path('profile_photos',views.profile_photos, name='profile_photos'), path('comment_update/<int:id>',views.comment_update, name='comment_update'), path('comment/<int:pk>/update',CommentUpdateView.as_view(), name='comment-update'",
"), path('post_update',views.post_update, name='post_update'), path('post/<int:pk>/update',PostUpdateView.as_view(), name='post-update' ), path('profile_photos',views.profile_photos, name='profile_photos'), path('comment_update/<int:id>',views.comment_update, name='comment_update'),",
"path('post/<int:pk>/update',PostUpdateView.as_view(), name='post-update' ), path('profile_photos',views.profile_photos, name='profile_photos'), path('comment_update/<int:id>',views.comment_update, name='comment_update'), path('comment/<int:pk>/update',CommentUpdateView.as_view(), name='comment-update' ),",
"path('results',views.results, name='results'), path('post/new/',PostCreateView.as_view(), name='post-create' ), path('post_update',views.post_update, name='post_update'), path('post/<int:pk>/update',PostUpdateView.as_view(), name='post-update' ),",
"name='logout'), path('like_post', views.like_post, name='like_post'), path('find_friends',views.find_friends, name='find_friends'), path('profile',views.profile, name='profile'), path('profile_update', views.profile_update,",
"path('like_post', views.like_post, name='like_post'), path('find_friends',views.find_friends, name='find_friends'), path('profile',views.profile, name='profile'), path('profile_update', views.profile_update, name='profile_update'),",
"path('post/<int:pk>/delete/',PostDeleteview.as_view(), name='post_delete' ), path('profile_posts',views.profile_posts, name='profile_posts'), path('results',views.results, name='results'), path('post/new/',PostCreateView.as_view(), name='post-create' ),",
"name='post_details' ), path('post/<int:pk>/delete/',PostDeleteview.as_view(), name='post_delete' ), path('profile_posts',views.profile_posts, name='profile_posts'), path('results',views.results, name='results'), path('post/new/',PostCreateView.as_view(),",
"name='register'), path('index',views.index, name='index'), path('logout',views.logout, name='logout'), path('like_post', views.like_post, name='like_post'), path('find_friends',views.find_friends, name='find_friends'),",
"name='post-create' ), path('post_update',views.post_update, name='post_update'), path('post/<int:pk>/update',PostUpdateView.as_view(), name='post-update' ), path('profile_photos',views.profile_photos, name='profile_photos'), path('comment_update/<int:id>',views.comment_update,",
"views.like_post, name='like_post'), path('find_friends',views.find_friends, name='find_friends'), path('profile',views.profile, name='profile'), path('profile_update', views.profile_update, name='profile_update'), path('user/<str:username>',",
"path('video/new/',VideoCreateView.as_view(), name='video-create' ), path('post/<int:pk>/video',video_update.as_view(), name='video_update' ), # path('<str:username>',views.userprofile, name='userprofile'), path('video_posts',views.video_posts,",
"from . import views from . views import UserPostListView, PostDetailView,",
"name='favourite_posts'), path('video/new/',VideoCreateView.as_view(), name='video-create' ), path('post/<int:pk>/video',video_update.as_view(), name='video_update' ), # path('<str:username>',views.userprofile, name='userprofile'),",
"path('find_friends',views.find_friends, name='find_friends'), path('profile',views.profile, name='profile'), path('profile_update', views.profile_update, name='profile_update'), path('user/<str:username>', UserPostListView.as_view(), name='user_posts'),",
"views from . views import UserPostListView, PostDetailView, PostDeleteview, PostCreateView, PostUpdateView,CommentUpdateView,",
"PostDeleteview, PostCreateView, PostUpdateView,CommentUpdateView, VideoCreateView, video_update urlpatterns = [ path('',views.base, name='base'),",
"path('logout',views.logout, name='logout'), path('like_post', views.like_post, name='like_post'), path('find_friends',views.find_friends, name='find_friends'), path('profile',views.profile, name='profile'), path('profile_update',",
"path('favourite',views.favourite, name='favourite'), path('favourite_posts',views.favourite_posts, name='favourite_posts'), path('video/new/',VideoCreateView.as_view(), name='video-create' ), path('post/<int:pk>/video',video_update.as_view(), name='video_update' ),",
"UserPostListView, PostDetailView, PostDeleteview, PostCreateView, PostUpdateView,CommentUpdateView, VideoCreateView, video_update urlpatterns = [",
"urlpatterns = [ path('',views.base, name='base'), path('login',views.login, name='login'), path('register',views.register, name='register'), path('index',views.index,",
"path('profile_update', views.profile_update, name='profile_update'), path('user/<str:username>', UserPostListView.as_view(), name='user_posts'), path('post/<int:pk>/',PostDetailView.as_view(), name='post_details' ), path('post/<int:pk>/delete/',PostDeleteview.as_view(),",
"path('',views.base, name='base'), path('login',views.login, name='login'), path('register',views.register, name='register'), path('index',views.index, name='index'), path('logout',views.logout, name='logout'),",
"PostUpdateView,CommentUpdateView, VideoCreateView, video_update urlpatterns = [ path('',views.base, name='base'), path('login',views.login, name='login'),",
"name='base'), path('login',views.login, name='login'), path('register',views.register, name='register'), path('index',views.index, name='index'), path('logout',views.logout, name='logout'), path('like_post',",
"video_update urlpatterns = [ path('',views.base, name='base'), path('login',views.login, name='login'), path('register',views.register, name='register'),",
"path('index',views.index, name='index'), path('logout',views.logout, name='logout'), path('like_post', views.like_post, name='like_post'), path('find_friends',views.find_friends, name='find_friends'), path('profile',views.profile,",
"from . views import UserPostListView, PostDetailView, PostDeleteview, PostCreateView, PostUpdateView,CommentUpdateView, VideoCreateView,",
"UserPostListView.as_view(), name='user_posts'), path('post/<int:pk>/',PostDetailView.as_view(), name='post_details' ), path('post/<int:pk>/delete/',PostDeleteview.as_view(), name='post_delete' ), path('profile_posts',views.profile_posts, name='profile_posts'),",
"name='profile_photos'), path('comment_update/<int:id>',views.comment_update, name='comment_update'), path('comment/<int:pk>/update',CommentUpdateView.as_view(), name='comment-update' ), path('delete/<int:id>',views.delete, name='delete'), path('favourite',views.favourite, name='favourite'),",
"name='index'), path('logout',views.logout, name='logout'), path('like_post', views.like_post, name='like_post'), path('find_friends',views.find_friends, name='find_friends'), path('profile',views.profile, name='profile'),",
"path('register',views.register, name='register'), path('index',views.index, name='index'), path('logout',views.logout, name='logout'), path('like_post', views.like_post, name='like_post'), path('find_friends',views.find_friends,"
] |
[
"contains = cell.contains(dolfin.Point(Px, Py)) printc(\"Cell\", cell.index(), \"contains P:\", contains, c=contains)",
"''' compute_collision() will compute the collision of all the entities",
"be tricky. You may also want to compare with the",
"Point while compute_first_collision() will always return its first entry. Especially",
"compare with the Cell.contains(Point) tool. ''' # Script by Rudy",
"shapes, plot, printc n = 4 Px = 0.5 Py",
"cell in dolfin.cells(mesh): contains = cell.contains(dolfin.Point(Px, Py)) printc(\"Cell\", cell.index(), \"contains",
"mesh = dolfin.UnitSquareMesh(n, n) bbt = mesh.bounding_box_tree() collisions = bbt.compute_collisions(dolfin.Point(Px,",
"mesh.bounding_box_tree() collisions = bbt.compute_collisions(dolfin.Point(Px, Py)) collisions1st = bbt.compute_first_entity_collision(dolfin.Point(Px, Py)) printc(\"collisions",
"the entities with a Point while compute_first_collision() will always return",
"vtkplotter.dolfin import shapes, plot, printc n = 4 Px =",
"compute_first_collision() will always return its first entry. Especially if a",
": \", collisions) printc(\"collisions 1st: \", collisions1st) for cell in",
"tool. ''' # Script by Rudy at https://fenicsproject.discourse.group/t/ # any-function-to-determine-if-the-point-is-in-the-mesh/275/3",
"P:\", contains, c=contains) ########################################### pt = shapes.Point([Px, Py], c='blue') plot(mesh,",
"a point is on an element edge this can be",
"\", collisions) printc(\"collisions 1st: \", collisions1st) for cell in dolfin.cells(mesh):",
"bbt = mesh.bounding_box_tree() collisions = bbt.compute_collisions(dolfin.Point(Px, Py)) collisions1st = bbt.compute_first_entity_collision(dolfin.Point(Px,",
"the collision of all the entities with a Point while",
"Rudy at https://fenicsproject.discourse.group/t/ # any-function-to-determine-if-the-point-is-in-the-mesh/275/3 import dolfin from vtkplotter.dolfin import",
"collisions) printc(\"collisions 1st: \", collisions1st) for cell in dolfin.cells(mesh): contains",
"= cell.contains(dolfin.Point(Px, Py)) printc(\"Cell\", cell.index(), \"contains P:\", contains, c=contains) ###########################################",
"cell.index(), \"contains P:\", contains, c=contains) ########################################### pt = shapes.Point([Px, Py],",
"0.5 mesh = dolfin.UnitSquareMesh(n, n) bbt = mesh.bounding_box_tree() collisions =",
"Py)) collisions1st = bbt.compute_first_entity_collision(dolfin.Point(Px, Py)) printc(\"collisions : \", collisions) printc(\"collisions",
"You may also want to compare with the Cell.contains(Point) tool.",
"collision of all the entities with a Point while compute_first_collision()",
"dolfin.UnitSquareMesh(n, n) bbt = mesh.bounding_box_tree() collisions = bbt.compute_collisions(dolfin.Point(Px, Py)) collisions1st",
"entities with a Point while compute_first_collision() will always return its",
"Py)) printc(\"Cell\", cell.index(), \"contains P:\", contains, c=contains) ########################################### pt =",
"return its first entry. Especially if a point is on",
"# any-function-to-determine-if-the-point-is-in-the-mesh/275/3 import dolfin from vtkplotter.dolfin import shapes, plot, printc",
"at https://fenicsproject.discourse.group/t/ # any-function-to-determine-if-the-point-is-in-the-mesh/275/3 import dolfin from vtkplotter.dolfin import shapes,",
"= 0.5 mesh = dolfin.UnitSquareMesh(n, n) bbt = mesh.bounding_box_tree() collisions",
"printc(\"collisions : \", collisions) printc(\"collisions 1st: \", collisions1st) for cell",
"https://fenicsproject.discourse.group/t/ # any-function-to-determine-if-the-point-is-in-the-mesh/275/3 import dolfin from vtkplotter.dolfin import shapes, plot,",
"c=contains) ########################################### pt = shapes.Point([Px, Py], c='blue') plot(mesh, pt, text=__doc__)",
"n) bbt = mesh.bounding_box_tree() collisions = bbt.compute_collisions(dolfin.Point(Px, Py)) collisions1st =",
"contains, c=contains) ########################################### pt = shapes.Point([Px, Py], c='blue') plot(mesh, pt,",
"4 Px = 0.5 Py = 0.5 mesh = dolfin.UnitSquareMesh(n,",
"= dolfin.UnitSquareMesh(n, n) bbt = mesh.bounding_box_tree() collisions = bbt.compute_collisions(dolfin.Point(Px, Py))",
"Px = 0.5 Py = 0.5 mesh = dolfin.UnitSquareMesh(n, n)",
"for cell in dolfin.cells(mesh): contains = cell.contains(dolfin.Point(Px, Py)) printc(\"Cell\", cell.index(),",
"Script by Rudy at https://fenicsproject.discourse.group/t/ # any-function-to-determine-if-the-point-is-in-the-mesh/275/3 import dolfin from",
"n = 4 Px = 0.5 Py = 0.5 mesh",
"collisions1st = bbt.compute_first_entity_collision(dolfin.Point(Px, Py)) printc(\"collisions : \", collisions) printc(\"collisions 1st:",
"import shapes, plot, printc n = 4 Px = 0.5",
"printc(\"collisions 1st: \", collisions1st) for cell in dolfin.cells(mesh): contains =",
"with a Point while compute_first_collision() will always return its first",
"import dolfin from vtkplotter.dolfin import shapes, plot, printc n =",
"= bbt.compute_first_entity_collision(dolfin.Point(Px, Py)) printc(\"collisions : \", collisions) printc(\"collisions 1st: \",",
"= 4 Px = 0.5 Py = 0.5 mesh =",
"Especially if a point is on an element edge this",
"collisions1st) for cell in dolfin.cells(mesh): contains = cell.contains(dolfin.Point(Px, Py)) printc(\"Cell\",",
"if a point is on an element edge this can",
"compute_collision() will compute the collision of all the entities with",
"from vtkplotter.dolfin import shapes, plot, printc n = 4 Px",
"Cell.contains(Point) tool. ''' # Script by Rudy at https://fenicsproject.discourse.group/t/ #",
"with the Cell.contains(Point) tool. ''' # Script by Rudy at",
"edge this can be tricky. You may also want to",
"will always return its first entry. Especially if a point",
"will compute the collision of all the entities with a",
"''' # Script by Rudy at https://fenicsproject.discourse.group/t/ # any-function-to-determine-if-the-point-is-in-the-mesh/275/3 import",
"an element edge this can be tricky. You may also",
"1st: \", collisions1st) for cell in dolfin.cells(mesh): contains = cell.contains(dolfin.Point(Px,",
"a Point while compute_first_collision() will always return its first entry.",
"<reponame>ismarou/vtkplotter-examples<filename>vtkplotter_examples/other/dolfin/collisions.py<gh_stars>1-10 ''' compute_collision() will compute the collision of all the",
"dolfin.cells(mesh): contains = cell.contains(dolfin.Point(Px, Py)) printc(\"Cell\", cell.index(), \"contains P:\", contains,",
"the Cell.contains(Point) tool. ''' # Script by Rudy at https://fenicsproject.discourse.group/t/",
"any-function-to-determine-if-the-point-is-in-the-mesh/275/3 import dolfin from vtkplotter.dolfin import shapes, plot, printc n",
"point is on an element edge this can be tricky.",
"while compute_first_collision() will always return its first entry. Especially if",
"plot, printc n = 4 Px = 0.5 Py =",
"its first entry. Especially if a point is on an",
"can be tricky. You may also want to compare with",
"on an element edge this can be tricky. You may",
"Py = 0.5 mesh = dolfin.UnitSquareMesh(n, n) bbt = mesh.bounding_box_tree()",
"by Rudy at https://fenicsproject.discourse.group/t/ # any-function-to-determine-if-the-point-is-in-the-mesh/275/3 import dolfin from vtkplotter.dolfin",
"entry. Especially if a point is on an element edge",
"always return its first entry. Especially if a point is",
"= mesh.bounding_box_tree() collisions = bbt.compute_collisions(dolfin.Point(Px, Py)) collisions1st = bbt.compute_first_entity_collision(dolfin.Point(Px, Py))",
"printc n = 4 Px = 0.5 Py = 0.5",
"bbt.compute_first_entity_collision(dolfin.Point(Px, Py)) printc(\"collisions : \", collisions) printc(\"collisions 1st: \", collisions1st)",
"printc(\"Cell\", cell.index(), \"contains P:\", contains, c=contains) ########################################### pt = shapes.Point([Px,",
"cell.contains(dolfin.Point(Px, Py)) printc(\"Cell\", cell.index(), \"contains P:\", contains, c=contains) ########################################### pt",
"all the entities with a Point while compute_first_collision() will always",
"in dolfin.cells(mesh): contains = cell.contains(dolfin.Point(Px, Py)) printc(\"Cell\", cell.index(), \"contains P:\",",
"\"contains P:\", contains, c=contains) ########################################### pt = shapes.Point([Px, Py], c='blue')",
"= 0.5 Py = 0.5 mesh = dolfin.UnitSquareMesh(n, n) bbt",
"first entry. Especially if a point is on an element",
"of all the entities with a Point while compute_first_collision() will",
"want to compare with the Cell.contains(Point) tool. ''' # Script",
"to compare with the Cell.contains(Point) tool. ''' # Script by",
"also want to compare with the Cell.contains(Point) tool. ''' #",
"bbt.compute_collisions(dolfin.Point(Px, Py)) collisions1st = bbt.compute_first_entity_collision(dolfin.Point(Px, Py)) printc(\"collisions : \", collisions)",
"element edge this can be tricky. You may also want",
"is on an element edge this can be tricky. You",
"collisions = bbt.compute_collisions(dolfin.Point(Px, Py)) collisions1st = bbt.compute_first_entity_collision(dolfin.Point(Px, Py)) printc(\"collisions :",
"this can be tricky. You may also want to compare",
"tricky. You may also want to compare with the Cell.contains(Point)",
"0.5 Py = 0.5 mesh = dolfin.UnitSquareMesh(n, n) bbt =",
"\", collisions1st) for cell in dolfin.cells(mesh): contains = cell.contains(dolfin.Point(Px, Py))",
"Py)) printc(\"collisions : \", collisions) printc(\"collisions 1st: \", collisions1st) for",
"# Script by Rudy at https://fenicsproject.discourse.group/t/ # any-function-to-determine-if-the-point-is-in-the-mesh/275/3 import dolfin",
"dolfin from vtkplotter.dolfin import shapes, plot, printc n = 4",
"= bbt.compute_collisions(dolfin.Point(Px, Py)) collisions1st = bbt.compute_first_entity_collision(dolfin.Point(Px, Py)) printc(\"collisions : \",",
"compute the collision of all the entities with a Point",
"may also want to compare with the Cell.contains(Point) tool. '''"
] |
[
"station_from = os.getenv('STATION_FROM') station_to = os.getenv('STATION_TO') date = datetime.date.today().strftime('%Y-%m-%d') js",
"get_rasp(key, station_from, station_to, date) filtered = filter_rasp(js['segments'], 300) message =",
"datetime.date.today().strftime('%Y-%m-%d') js = get_rasp(key, station_from, station_to, date) filtered = filter_rasp(js['segments'],",
"1000) if len(message) > 1024: print('Too long message: {} >",
"= datetime.date.today().strftime('%Y-%m-%d') js = get_rasp(key, station_from, station_to, date) filtered =",
"from alice_check_train.rasp_api import get_rasp, filter_rasp def main(): key = os.getenv('RASP_KEY')",
"= os.getenv('RASP_KEY') station_from = os.getenv('STATION_FROM') station_to = os.getenv('STATION_TO') date =",
"filtered = filter_rasp(js['segments'], 300) message = rasp_to_text(filtered, 1000) if len(message)",
"rasp_to_text(filtered, 1000) if len(message) > 1024: print('Too long message: {}",
"print('Too long message: {} > 1024'.format(len(message))) print(message) if __name__ ==",
"long message: {} > 1024'.format(len(message))) print(message) if __name__ == '__main__':",
"import rasp_to_text from alice_check_train.rasp_api import get_rasp, filter_rasp def main(): key",
"import datetime import os from alice_check_train.main import rasp_to_text from alice_check_train.rasp_api",
"= filter_rasp(js['segments'], 300) message = rasp_to_text(filtered, 1000) if len(message) >",
"= rasp_to_text(filtered, 1000) if len(message) > 1024: print('Too long message:",
"os from alice_check_train.main import rasp_to_text from alice_check_train.rasp_api import get_rasp, filter_rasp",
"message = rasp_to_text(filtered, 1000) if len(message) > 1024: print('Too long",
"1024: print('Too long message: {} > 1024'.format(len(message))) print(message) if __name__",
"<reponame>AsciiShell/Alice-Check-Train import datetime import os from alice_check_train.main import rasp_to_text from",
"alice_check_train.rasp_api import get_rasp, filter_rasp def main(): key = os.getenv('RASP_KEY') station_from",
"datetime import os from alice_check_train.main import rasp_to_text from alice_check_train.rasp_api import",
"get_rasp, filter_rasp def main(): key = os.getenv('RASP_KEY') station_from = os.getenv('STATION_FROM')",
"main(): key = os.getenv('RASP_KEY') station_from = os.getenv('STATION_FROM') station_to = os.getenv('STATION_TO')",
"os.getenv('STATION_TO') date = datetime.date.today().strftime('%Y-%m-%d') js = get_rasp(key, station_from, station_to, date)",
"len(message) > 1024: print('Too long message: {} > 1024'.format(len(message))) print(message)",
"message: {} > 1024'.format(len(message))) print(message) if __name__ == '__main__': main()",
"date = datetime.date.today().strftime('%Y-%m-%d') js = get_rasp(key, station_from, station_to, date) filtered",
"def main(): key = os.getenv('RASP_KEY') station_from = os.getenv('STATION_FROM') station_to =",
"alice_check_train.main import rasp_to_text from alice_check_train.rasp_api import get_rasp, filter_rasp def main():",
"station_from, station_to, date) filtered = filter_rasp(js['segments'], 300) message = rasp_to_text(filtered,",
"300) message = rasp_to_text(filtered, 1000) if len(message) > 1024: print('Too",
"station_to = os.getenv('STATION_TO') date = datetime.date.today().strftime('%Y-%m-%d') js = get_rasp(key, station_from,",
"import get_rasp, filter_rasp def main(): key = os.getenv('RASP_KEY') station_from =",
"rasp_to_text from alice_check_train.rasp_api import get_rasp, filter_rasp def main(): key =",
"os.getenv('STATION_FROM') station_to = os.getenv('STATION_TO') date = datetime.date.today().strftime('%Y-%m-%d') js = get_rasp(key,",
"= os.getenv('STATION_TO') date = datetime.date.today().strftime('%Y-%m-%d') js = get_rasp(key, station_from, station_to,",
"filter_rasp def main(): key = os.getenv('RASP_KEY') station_from = os.getenv('STATION_FROM') station_to",
"os.getenv('RASP_KEY') station_from = os.getenv('STATION_FROM') station_to = os.getenv('STATION_TO') date = datetime.date.today().strftime('%Y-%m-%d')",
"> 1024: print('Too long message: {} > 1024'.format(len(message))) print(message) if",
"= os.getenv('STATION_FROM') station_to = os.getenv('STATION_TO') date = datetime.date.today().strftime('%Y-%m-%d') js =",
"station_to, date) filtered = filter_rasp(js['segments'], 300) message = rasp_to_text(filtered, 1000)",
"from alice_check_train.main import rasp_to_text from alice_check_train.rasp_api import get_rasp, filter_rasp def",
"= get_rasp(key, station_from, station_to, date) filtered = filter_rasp(js['segments'], 300) message",
"date) filtered = filter_rasp(js['segments'], 300) message = rasp_to_text(filtered, 1000) if",
"key = os.getenv('RASP_KEY') station_from = os.getenv('STATION_FROM') station_to = os.getenv('STATION_TO') date",
"js = get_rasp(key, station_from, station_to, date) filtered = filter_rasp(js['segments'], 300)",
"filter_rasp(js['segments'], 300) message = rasp_to_text(filtered, 1000) if len(message) > 1024:",
"import os from alice_check_train.main import rasp_to_text from alice_check_train.rasp_api import get_rasp,",
"if len(message) > 1024: print('Too long message: {} > 1024'.format(len(message)))"
] |
[
"# for recall calculation query_template = ''' { \"size\": 50,",
"\"\" for num in vector: vector_str += str(num) + ','",
"enumerate(queries): assert len(query)==dim query_str = \"\" for num in query:",
"'''{ \"index\" : { \"refresh_interval\": \"1s\" } } ''' response",
"float dataset # path = '/tmp/sift-128-euclidean.hdf5' # float dataset path",
"for ef_search in ef_search_list: ef_data = '''{ \"index\": { \"knn.algo_param.ef_search\":",
"+= hits_q total_time_list.append(total_time) hits_list.append(hits) print(total_time_list) total_time_avg = mean(total_time_list[2:-1]) hits_avg =",
"'https://vpc-....ap-southeast-1.es.amazonaws.com/' # two nodes url = host + 'sift-index/' requestHeaders",
"hits_q = len(list(set(neighbor_id_from_result) & set(neighbor_id_gt))) # print(\"# hits of this",
"warmup_url = 'http://127.0.0.1:9200/_opendistro/_knn/warmup/sift-index' warmup_url = host + '_opendistro/_knn/warmup/sift-index' warmup_response =",
"i in range(len(queries)): # for ele in result['responses']: # tooks.append(int(ele['took']))",
"response = requests.put(refresh_url, data=refresh_data, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB')) assert response.status_code==requests.codes.ok #",
"\"properties\": { \"sift_vector\": { \"type\": \"knn_vector\", \"dimension\": 128 } }",
"for (id,vector) in enumerate(vectors): assert len(vector)==dim vector_str = \"\" for",
"ef_data % ef_search ### Update Index Setting: efSearch response =",
"of this query with topk=50: %d\" % hits_q) hits +=",
"response = requests.put(cluster_url, data=cluster_data, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB'), headers=requestHeaders) assert response.status_code==requests.codes.ok #",
"# distances = np.array(hf[\"distances\"][:]) num_queries, q_dim = queries.shape print(\"num_queries: %d\"",
"len(neighbor_id_from_result)==50 # print(\"neighbor_id_from_result: \") # print(neighbor_id_from_result) neighbor_id_gt = neighbors[id][0:50] #",
"= [] for count in range(5): total_time = 0 #",
"import asyncio import time import httpx from requests.auth import HTTPBasicAuth",
"vector_str += str(num) + ',' vector_str = vector_str[:-1] id_str =",
"= 0 # for recall calculation query_template = ''' {",
"for i in range(len(queries)): # for ele in result['responses']: #",
"print(neighbor_id_gt) hits_q = len(list(set(neighbor_id_from_result) & set(neighbor_id_gt))) # print(\"# hits of",
": { \"refresh_interval\": \"1s\" } } ''' response = requests.put(refresh_url,",
"% (query_str) query_template += single_query_done query_data = query_template # print(query_data)",
"\"index\": { \"knn\": true, \"knn.space_type\": \"l2\", \"knn.algo_param.m\": 6, \"knn.algo_param.ef_construction\": 50,",
"data=data, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB')) # response = requests.put(url, data=data, verify=False,",
"groups in HDF5 file. vectors = np.array(hf[\"train\"][:]) num_vectors, dim =",
"print(response.text) result = json.loads(response.text) # QPS total_time = result['took'] #",
"query_template += single_query_done query_data = query_template # print(query_data) response =",
"QPS total_time = result['took'] # tooks = [] # for",
"ele in result['responses']: # tooks.append(int(ele['took'])) for id in range(len(queries)): #",
"total_time_list = [] hits_list = [] for count in range(5):",
"# GET sift-index/_search single_query_done = single_query % (query_str) query_template +=",
"assert response.status_code==requests.codes.ok # response = requests.post('http://127.0.0.1:9200/sift-index/_refresh', verify=False, headers=requestHeaders) # assert",
"key of hf is %s\" % key) #Names of the",
"'https://vpc-....ap-southeast-1.es.amazonaws.com/' # single node # host = 'https://vpc-....ap-southeast-1.es.amazonaws.com/' # two",
"# for recall calculation query_template = ''' ''' single_query =",
"'http://127.0.0.1:9200/sift-index/' host = 'https://vpc-....ap-southeast-1.es.amazonaws.com/' # single node # host =",
"for key in hf.keys(): print(\"A key of hf is %s\"",
"50, \"query\": {\"knn\": {\"sift_vector\": {\"vector\": [%s],\"k\": 50}}}}\\n''' for (id,query) in",
"= mean(hits_list) QPS = 1.0 * nq / (total_time_avg /",
"time.time() print(\"Insert Time: %d mins\" % ((end - start) /",
"= requests.put(cluster_url, data=cluster_data, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB'), headers=requestHeaders) assert response.status_code==requests.codes.ok # Bulkload",
"6, \"knn.algo_param.ef_construction\": 50, \"knn.algo_param.ef_search\": 50, \"refresh_interval\": -1, \"translog.flush_threshold_size\": \"10gb\", \"number_of_replicas\":",
"= 1.0 * hits_avg / (nq * 50) print(ef_search, QPS,",
"requests.post('http://127.0.0.1:9200/sift-index/_refresh', verify=False, headers=requestHeaders) # assert response.status_code==requests.codes.ok # merge_url = 'http://127.0.0.1:9200/sift-index/_forcemerge?max_num_segments=1'",
"= requests.post('http://127.0.0.1:9200/sift-index/_refresh', verify=False, headers=requestHeaders) # assert response.status_code==requests.codes.ok # merge_url =",
"dim) bulk_data = \"\" start = time.time() for (id,vector) in",
"\"query\": {\"knn\": {\"sift_vector\": {\"vector\": [%s],\"k\": 50}}} } ''' queries =",
"bulk_template % (id_str, vector_str) bulk_data += single_bulk_done if (id+1) %",
"'I#<PASSWORD>TAHB'), headers=requestHeaders) assert response.status_code==requests.codes.ok bulk_data = \"\" end = time.time()",
"neighbor_id_from_result.append(int(ele['_id'])) assert len(neighbor_id_from_result)==50 # print(\"neighbor_id_from_result: \") # print(neighbor_id_from_result) neighbor_id_gt =",
"'http://127.0.0.1:9200/_opendistro/_knn/warmup/sift-index' warmup_url = host + '_opendistro/_knn/warmup/sift-index' warmup_response = requests.get(warmup_url, headers=requestHeaders,",
"== 0: print(str(id+1)) # POST _bulk response = requests.put(url +",
"%d } }''' ef_data = ef_data % ef_search ### Update",
"} }, \"mappings\": { \"properties\": { \"sift_vector\": { \"type\": \"knn_vector\",",
"60.0)) # Unit: min # refresh_url = 'http://127.0.0.1:9200/sift-index/_settings' refresh_url =",
"'I#<PASSWORD>'), timeout=600) assert merge_response.status_code==requests.codes.ok # warmup_url = 'http://127.0.0.1:9200/_opendistro/_knn/warmup/sift-index' warmup_url =",
"cluster_url = host + '_cluster/settings' cluster_data = '''{ \"persistent\" :",
"Time: %d mins\" % ((end - start) / 60.0)) #",
"0 # in ms hits = 0 # for recall",
"= np.array(hf[\"distances\"][:]) num_queries, q_dim = queries.shape print(\"num_queries: %d\" % num_queries)",
"in range(len(queries)): # for ele in result['responses']: # tooks.append(int(ele['took'])) for",
"headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#<PASSWORD>'), timeout=600) assert merge_response.status_code==requests.codes.ok # warmup_url = 'http://127.0.0.1:9200/_opendistro/_knn/warmup/sift-index'",
"auth=HTTPBasicAuth('admin', 'I#vu7bTAHB')) assert response.status_code==requests.codes.ok # response = requests.post('http://127.0.0.1:9200/sift-index/_refresh', verify=False, headers=requestHeaders)",
"warmup_url = host + '_opendistro/_knn/warmup/sift-index' warmup_response = requests.get(warmup_url, headers=requestHeaders, auth=HTTPBasicAuth('admin',",
"hits_q) hits += hits_q total_time_list.append(total_time) hits_list.append(hits) print(total_time_list) total_time_avg = mean(total_time_list[2:-1])",
": { \"knn.algo_param.index_thread_qty\": 16 } } ''' response = requests.put(cluster_url,",
"100000 == 0: print(str(id+1)) # POST _bulk response = requests.put(url",
"''' { \"size\": 50, \"query\": {\"knn\": {\"sift_vector\": {\"vector\": [%s],\"k\": 50}}}",
"ef_search in ef_search_list: ef_data = '''{ \"index\": { \"knn.algo_param.ef_search\": %d",
"q_dim) assert q_dim==dim ef_search_list = [50, 100, 150, 200, 250,",
"asyncio import time import httpx from requests.auth import HTTPBasicAuth from",
"# print(neighbor_id_gt) hits_q = len(list(set(neighbor_id_from_result) & set(neighbor_id_gt))) # print(\"# hits",
"verify=False, headers=requestHeaders) # assert response.status_code==requests.codes.ok # merge_url = 'http://127.0.0.1:9200/sift-index/_forcemerge?max_num_segments=1' merge_url",
"assert q_dim==dim ef_search_list = [50, 100, 150, 200, 250, 300]",
"# Recall neighbor_id_from_result = [] for ele in result['responses'][id]['hits']['hits']: neighbor_id_from_result.append(int(ele['_id']))",
"from requests.auth import HTTPBasicAuth from statistics import mean # if",
"= 'http://127.0.0.1:9200/sift-index/' host = 'https://vpc-....ap-southeast-1.es.amazonaws.com/' # single node # host",
"\"knn.algo_param.ef_search\": 50, \"refresh_interval\": -1, \"translog.flush_threshold_size\": \"10gb\", \"number_of_replicas\": 0 } },",
"of hf is %s\" % key) #Names of the groups",
"= ''' { \"size\": 50, \"query\": {\"knn\": {\"sift_vector\": {\"vector\": [%s],\"k\":",
"\"knn.algo_param.ef_search\": %d } }''' ef_data = ef_data % ef_search ###",
"# host = 'https://vpc-....ap-southeast-1.es.amazonaws.com/' # two nodes url = host",
"# url = 'http://127.0.0.1:9200/sift-index/' host = 'https://vpc-....ap-southeast-1.es.amazonaws.com/' # single node",
"auth=auth) assert response.status_code==requests.codes.ok # cluster_url = 'http://127.0.0.1:9200/_cluster/settings' cluster_url = host",
"assert len(query)==dim query_str = \"\" for num in query: query_str",
"%d\" % q_dim) assert q_dim==dim ef_search_list = [50, 100, 150,",
"id_str = str(id) single_bulk_done = bulk_template % (id_str, vector_str) bulk_data",
"\"l2\", \"knn.algo_param.m\": 6, \"knn.algo_param.ef_construction\": 50, \"knn.algo_param.ef_search\": 50, \"refresh_interval\": -1, \"translog.flush_threshold_size\":",
"# sys.exit() # path = '/tmp/sift-128-euclidean.hdf5.1M' # float dataset #",
"\"number_of_replicas\": 0 } }, \"mappings\": { \"properties\": { \"sift_vector\": {",
"mins\" % ((end - start) / 60.0)) # Unit: min",
"# topK=50 # print(\"neighbor_id_gt\") # print(neighbor_id_gt) hits_q = len(list(set(neighbor_id_from_result) &",
"the efSearch!\") # sys.exit() # path = '/tmp/sift-128-euclidean.hdf5.1M' # float",
"}, \"mappings\": { \"properties\": { \"sift_vector\": { \"type\": \"knn_vector\", \"dimension\":",
"{\"knn\": {\"sift_vector\": {\"vector\": [%s],\"k\": 50}}} } ''' queries = np.array(hf[\"test\"][:])",
"{ \"size\": 50, \"query\": {\"knn\": {\"sift_vector\": {\"vector\": [%s],\"k\": 50}}} }",
"requests.put(url, data=data, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB')) # response = requests.put(url, data=data,",
"} ''' queries = np.array(hf[\"test\"][:]) nq = len(queries) neighbors =",
"%d\" % num_queries) print(\"q_dim: %d\" % q_dim) assert q_dim==dim ef_search_list",
"if len(sys.argv) != 2: # print(\"Type in the efSearch!\") #",
"num in query: query_str += str(num) + ',' query_str =",
"2: # print(\"Type in the efSearch!\") # sys.exit() # path",
"import mean # if len(sys.argv) != 2: # print(\"Type in",
"import h5py import numpy as np import json import aiohttp",
"0 # for recall calculation query_template = ''' { \"size\":",
"%d\" % num_vectors) print(\"dim: %d\" % dim) bulk_data = \"\"",
"headers=requestHeaders, auth=auth) assert response.status_code==requests.codes.ok # cluster_url = 'http://127.0.0.1:9200/_cluster/settings' cluster_url =",
"= 'http://127.0.0.1:9200/_cluster/settings' cluster_url = host + '_cluster/settings' cluster_data = '''{",
"# https://medium.com/@kumon/how-to-realize-similarity-search-with-elasticsearch-3dd5641b9adb # https://docs.aws.amazon.com/opensearch-service/latest/developerguide/knn.html import sys import requests import h5py",
"150, 200, 250, 300] for ef_search in ef_search_list: ef_data =",
"id in range(len(queries)): # Recall neighbor_id_from_result = [] for ele",
"true, \"knn.space_type\": \"l2\", \"knn.algo_param.m\": 6, \"knn.algo_param.ef_construction\": 50, \"knn.algo_param.ef_search\": 50, \"refresh_interval\":",
"# cluster_url = 'http://127.0.0.1:9200/_cluster/settings' cluster_url = host + '_cluster/settings' cluster_data",
"np.array(hf[\"test\"][:]) nq = len(queries) neighbors = np.array(hf[\"neighbors\"][:]) # distances =",
"'<PASSWORD>'), stream=True) assert response.status_code==requests.codes.ok # print(response.text) result = json.loads(response.text) #",
"0 } }, \"mappings\": { \"properties\": { \"sift_vector\": { \"type\":",
"print(\"num_vectors: %d\" % num_vectors) print(\"dim: %d\" % dim) bulk_data =",
"total_time = result['took'] # tooks = [] # for i",
"np.array(hf[\"train\"][:]) num_vectors, dim = vectors.shape print(\"num_vectors: %d\" % num_vectors) print(\"dim:",
"',' vector_str = vector_str[:-1] id_str = str(id) single_bulk_done = bulk_template",
"query_str = \"\" for num in query: query_str += str(num)",
"# print(\"# hits of this query with topk=50: %d\" %",
"refresh_url = 'http://127.0.0.1:9200/sift-index/_settings' refresh_url = host + 'sift-index/_settings' refresh_data =",
"{ \"knn.algo_param.index_thread_qty\": 16 } } ''' response = requests.put(cluster_url, data=cluster_data,",
"\"persistent\" : { \"knn.algo_param.index_thread_qty\": 16 } } ''' response =",
"'sift-index/' requestHeaders = {'content-type': 'application/json'} # https://stackoverflow.com/questions/51378099/content-type-header-not-supported auth = HTTPBasicAuth('admin',",
"[] for ele in result['responses'][id]['hits']['hits']: neighbor_id_from_result.append(int(ele['_id'])) assert len(neighbor_id_from_result)==50 # print(\"neighbor_id_from_result:",
"print(\"neighbor_id_gt\") # print(neighbor_id_gt) hits_q = len(list(set(neighbor_id_from_result) & set(neighbor_id_gt))) # print(\"#",
"(id_str, vector_str) bulk_data += single_bulk_done if (id+1) % 100000 ==",
"= requests.put(url, data=data, verify=False, headers=requestHeaders, auth=auth) assert response.status_code==requests.codes.ok # cluster_url",
"% 100000 == 0: print(str(id+1)) # POST _bulk response =",
"calculation query_template = ''' { \"size\": 50, \"query\": {\"knn\": {\"sift_vector\":",
"auth=HTTPBasicAuth('admin', '<PASSWORD>'), stream=True) assert response.status_code==requests.codes.ok # print(response.text) result = json.loads(response.text)",
"auth=HTTPBasicAuth('admin', 'I#<PASSWORD>'), timeout=600) assert merge_response.status_code==requests.codes.ok # warmup_url = 'http://127.0.0.1:9200/_opendistro/_knn/warmup/sift-index' warmup_url",
"# QPS total_time = result['took'] # tooks = [] #",
"query_template = ''' ''' single_query = '''{}\\n{\"size\": 50, \"query\": {\"knn\":",
"= json.loads(response.text) # QPS total_time = result['took'] # tooks =",
"# Bulkload into index bulk_template = '{ \"index\": { \"_index\":",
"dataset # path = '/tmp/sift-128-euclidean.hdf5' # float dataset path =",
"in ef_search_list: ef_data = '''{ \"index\": { \"knn.algo_param.ef_search\": %d }",
"import sys import requests import h5py import numpy as np",
"two nodes url = host + 'sift-index/' requestHeaders = {'content-type':",
"-1, \"translog.flush_threshold_size\": \"10gb\", \"number_of_replicas\": 0 } }, \"mappings\": { \"properties\":",
"= requests.put(url, data=data, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB')) # response = requests.put(url,",
"16 } } ''' response = requests.put(cluster_url, data=cluster_data, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB'),",
"= \"\" end = time.time() print(\"Insert Time: %d mins\" %",
"'{ \"index\": { \"_index\": \"sift-index\", \"_id\": \"%s\" } }\\n{ \"sift_vector\":",
"\") # print(neighbor_id_from_result) neighbor_id_gt = neighbors[id][0:50] # topK=50 # print(\"neighbor_id_gt\")",
"1.0 * nq / (total_time_avg / 1000.0) recall = 1.0",
"\"\" start = time.time() for (id,vector) in enumerate(vectors): assert len(vector)==dim",
"sys.exit() # path = '/tmp/sift-128-euclidean.hdf5.1M' # float dataset # path",
"= host + 'sift-index/' requestHeaders = {'content-type': 'application/json'} # https://stackoverflow.com/questions/51378099/content-type-header-not-supported",
"merge_url = host + 'sift-index/_forcemerge?max_num_segments=1' merge_response = requests.post(merge_url, headers=requestHeaders, auth=HTTPBasicAuth('admin',",
"} ''' response = requests.put(refresh_url, data=refresh_data, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB')) assert",
"https://docs.aws.amazon.com/opensearch-service/latest/developerguide/knn.html import sys import requests import h5py import numpy as",
"= [] for ele in result['responses'][id]['hits']['hits']: neighbor_id_from_result.append(int(ele['_id'])) assert len(neighbor_id_from_result)==50 #",
"# float dataset path = '/home/ubuntu/sift-128-euclidean.hdf5' # float dataset output_csv",
"vector_str = \"\" for num in vector: vector_str += str(num)",
"= [] hits_list = [] for count in range(5): total_time",
"= '''{ \"index\": { \"knn.algo_param.ef_search\": %d } }''' ef_data =",
"httpx from requests.auth import HTTPBasicAuth from statistics import mean #",
"50, \"knn.algo_param.ef_search\": 50, \"refresh_interval\": -1, \"translog.flush_threshold_size\": \"10gb\", \"number_of_replicas\": 0 }",
"node # host = 'https://vpc-....ap-southeast-1.es.amazonaws.com/' # two nodes url =",
"requests.get(url + '_msearch', data=query_data, headers=requestHeaders, auth=HTTPBasicAuth('admin', '<PASSWORD>'), stream=True) assert response.status_code==requests.codes.ok",
"assert len(vector)==dim vector_str = \"\" for num in vector: vector_str",
"# Build an index #https://stackoverflow.com/questions/17301938/making-a-request-to-a-restful-api-using-python # PUT sift-index data =",
"headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I<PASSWORD>')) assert warmup_response.status_code==requests.codes.ok # Send queries total_time =",
"= vector_str[:-1] id_str = str(id) single_bulk_done = bulk_template % (id_str,",
"if (id+1) % 100000 == 0: print(str(id+1)) # POST _bulk",
"ef_search ### Update Index Setting: efSearch response = requests.put(url +",
"neighbors[id][0:50] # topK=50 # print(\"neighbor_id_gt\") # print(neighbor_id_gt) hits_q = len(list(set(neighbor_id_from_result)",
"requests.get(warmup_url, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I<PASSWORD>')) assert warmup_response.status_code==requests.codes.ok # Send queries total_time",
"start) / 60.0)) # Unit: min # refresh_url = 'http://127.0.0.1:9200/sift-index/_settings'",
"host + 'sift-index/_settings' refresh_data = '''{ \"index\" : { \"refresh_interval\":",
"hits_q total_time_list.append(total_time) hits_list.append(hits) print(total_time_list) total_time_avg = mean(total_time_list[2:-1]) hits_avg = mean(hits_list)",
"len(query)==dim query_str = \"\" for num in query: query_str +=",
"= '''{ \"persistent\" : { \"knn.algo_param.index_thread_qty\": 16 } } '''",
"= '''{}\\n{\"size\": 50, \"query\": {\"knn\": {\"sift_vector\": {\"vector\": [%s],\"k\": 50}}}}\\n''' for",
"np.array(hf[\"neighbors\"][:]) # distances = np.array(hf[\"distances\"][:]) num_queries, q_dim = queries.shape print(\"num_queries:",
"end = time.time() print(\"Insert Time: %d mins\" % ((end -",
"bulk_template = '{ \"index\": { \"_index\": \"sift-index\", \"_id\": \"%s\" }",
"q_dim = queries.shape print(\"num_queries: %d\" % num_queries) print(\"q_dim: %d\" %",
"merge_response.status_code==requests.codes.ok # warmup_url = 'http://127.0.0.1:9200/_opendistro/_knn/warmup/sift-index' warmup_url = host + '_opendistro/_knn/warmup/sift-index'",
"str(id) single_bulk_done = bulk_template % (id_str, vector_str) bulk_data += single_bulk_done",
"headers=requestHeaders, auth=HTTPBasicAuth('admin', '<PASSWORD>')) assert response.status_code==requests.codes.ok total_time_list = [] hits_list =",
"(id,query) in enumerate(queries): assert len(query)==dim query_str = \"\" for num",
"PUT sift-index data = '''{ \"settings\": { \"index\": { \"knn\":",
"Send queries total_time = 0 # in ms hits =",
"requests.post(merge_url, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#<PASSWORD>'), timeout=600) assert merge_response.status_code==requests.codes.ok # warmup_url =",
"= bulk_template % (id_str, vector_str) bulk_data += single_bulk_done if (id+1)",
"assert response.status_code==requests.codes.ok total_time_list = [] hits_list = [] for count",
"} ''' response = requests.put(cluster_url, data=cluster_data, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB'), headers=requestHeaders) assert",
"= h5py.File(path, 'r') for key in hf.keys(): print(\"A key of",
"50, \"query\": {\"knn\": {\"sift_vector\": {\"vector\": [%s],\"k\": 50}}} } ''' queries",
"response = requests.put(url + '_settings', data=ef_data, headers=requestHeaders, auth=HTTPBasicAuth('admin', '<PASSWORD>')) assert",
"for recall calculation query_template = ''' ''' single_query = '''{}\\n{\"size\":",
"= 0 # in ms hits = 0 # for",
"headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB')) assert response.status_code==requests.codes.ok # response = requests.post('http://127.0.0.1:9200/sift-index/_refresh', verify=False,",
"for ele in result['responses']: # tooks.append(int(ele['took'])) for id in range(len(queries)):",
"} }''' # https://medium.com/@kumon/how-to-realize-similarity-search-with-elasticsearch-3dd5641b9adb response = requests.put(url, data=data, headers=requestHeaders, auth=HTTPBasicAuth('admin',",
"nq / (total_time_avg / 1000.0) recall = 1.0 * hits_avg",
"output_csv = '/tmp/sift-es.csv' # url = 'http://127.0.0.1:9200/sift-index/' host = 'https://vpc-....ap-southeast-1.es.amazonaws.com/'",
"_bulk response = requests.put(url + '_bulk', data=bulk_data, auth=HTTPBasicAuth('admin', 'I#<PASSWORD>TAHB'), headers=requestHeaders)",
"\"query\": {\"knn\": {\"sift_vector\": {\"vector\": [%s],\"k\": 50}}}}\\n''' for (id,query) in enumerate(queries):",
"= mean(total_time_list[2:-1]) hits_avg = mean(hits_list) QPS = 1.0 * nq",
"= '/tmp/sift-es.csv' # url = 'http://127.0.0.1:9200/sift-index/' host = 'https://vpc-....ap-southeast-1.es.amazonaws.com/' #",
"/ 1000.0) recall = 1.0 * hits_avg / (nq *",
"\"index\": { \"_index\": \"sift-index\", \"_id\": \"%s\" } }\\n{ \"sift_vector\": [%s]",
"single_bulk_done if (id+1) % 100000 == 0: print(str(id+1)) # POST",
"} } ''' response = requests.put(refresh_url, data=refresh_data, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB'))",
"[%s],\"k\": 50}}} } ''' queries = np.array(hf[\"test\"][:]) nq = len(queries)",
"print(\"num_queries: %d\" % num_queries) print(\"q_dim: %d\" % q_dim) assert q_dim==dim",
"= 'https://vpc-....ap-southeast-1.es.amazonaws.com/' # two nodes url = host + 'sift-index/'",
"hits_avg = mean(hits_list) QPS = 1.0 * nq / (total_time_avg",
"= host + '_cluster/settings' cluster_data = '''{ \"persistent\" : {",
"vector: vector_str += str(num) + ',' vector_str = vector_str[:-1] id_str",
"= query_template # print(query_data) response = requests.get(url + '_msearch', data=query_data,",
"for id in range(len(queries)): # Recall neighbor_id_from_result = [] for",
"Recall neighbor_id_from_result = [] for ele in result['responses'][id]['hits']['hits']: neighbor_id_from_result.append(int(ele['_id'])) assert",
"len(queries) neighbors = np.array(hf[\"neighbors\"][:]) # distances = np.array(hf[\"distances\"][:]) num_queries, q_dim",
"= query_str[:-1] # GET sift-index/_search single_query_done = single_query % (query_str)",
"min # refresh_url = 'http://127.0.0.1:9200/sift-index/_settings' refresh_url = host + 'sift-index/_settings'",
"{ \"knn.algo_param.ef_search\": %d } }''' ef_data = ef_data % ef_search",
"\"knn_vector\", \"dimension\": 128 } } } }''' # https://medium.com/@kumon/how-to-realize-similarity-search-with-elasticsearch-3dd5641b9adb response",
"% hits_q) hits += hits_q total_time_list.append(total_time) hits_list.append(hits) print(total_time_list) total_time_avg =",
"assert warmup_response.status_code==requests.codes.ok # Send queries total_time = 0 # in",
"+ 'sift-index/' requestHeaders = {'content-type': 'application/json'} # https://stackoverflow.com/questions/51378099/content-type-header-not-supported auth =",
"} }''' ef_data = ef_data % ef_search ### Update Index",
"path = '/tmp/sift-128-euclidean.hdf5.1M' # float dataset # path = '/tmp/sift-128-euclidean.hdf5'",
"in query: query_str += str(num) + ',' query_str = query_str[:-1]",
"HTTPBasicAuth('admin', '<PASSWORD>') # Build an index #https://stackoverflow.com/questions/17301938/making-a-request-to-a-restful-api-using-python # PUT sift-index",
"single_bulk_done = bulk_template % (id_str, vector_str) bulk_data += single_bulk_done if",
"'I<PASSWORD>')) assert warmup_response.status_code==requests.codes.ok # Send queries total_time = 0 #",
"+= str(num) + ',' vector_str = vector_str[:-1] id_str = str(id)",
"json.loads(response.text) # QPS total_time = result['took'] # tooks = []",
"for count in range(5): total_time = 0 # in ms",
"# warmup_url = 'http://127.0.0.1:9200/_opendistro/_knn/warmup/sift-index' warmup_url = host + '_opendistro/_knn/warmup/sift-index' warmup_response",
"(query_str) query_template += single_query_done query_data = query_template # print(query_data) response",
"queries.shape print(\"num_queries: %d\" % num_queries) print(\"q_dim: %d\" % q_dim) assert",
"# path = '/tmp/sift-128-euclidean.hdf5.1M' # float dataset # path =",
"% (id_str, vector_str) bulk_data += single_bulk_done if (id+1) % 100000",
"',' query_str = query_str[:-1] # GET sift-index/_search single_query_done = single_query",
"vector_str[:-1] id_str = str(id) single_bulk_done = bulk_template % (id_str, vector_str)",
"single node # host = 'https://vpc-....ap-southeast-1.es.amazonaws.com/' # two nodes url",
"assert response.status_code==requests.codes.ok # Bulkload into index bulk_template = '{ \"index\":",
"data=data, verify=False, headers=requestHeaders, auth=auth) assert response.status_code==requests.codes.ok # cluster_url = 'http://127.0.0.1:9200/_cluster/settings'",
"% num_vectors) print(\"dim: %d\" % dim) bulk_data = \"\" start",
"''' ''' single_query = '''{}\\n{\"size\": 50, \"query\": {\"knn\": {\"sift_vector\": {\"vector\":",
"= {'content-type': 'application/json'} # https://stackoverflow.com/questions/51378099/content-type-header-not-supported auth = HTTPBasicAuth('admin', '<PASSWORD>') #",
"auth = HTTPBasicAuth('admin', '<PASSWORD>') # Build an index #https://stackoverflow.com/questions/17301938/making-a-request-to-a-restful-api-using-python #",
"an index #https://stackoverflow.com/questions/17301938/making-a-request-to-a-restful-api-using-python # PUT sift-index data = '''{ \"settings\":",
"= requests.put(refresh_url, data=refresh_data, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB')) assert response.status_code==requests.codes.ok # response",
"'http://127.0.0.1:9200/_cluster/settings' cluster_url = host + '_cluster/settings' cluster_data = '''{ \"persistent\"",
"in vector: vector_str += str(num) + ',' vector_str = vector_str[:-1]",
"= len(queries) neighbors = np.array(hf[\"neighbors\"][:]) # distances = np.array(hf[\"distances\"][:]) num_queries,",
"auth=HTTPBasicAuth('admin', '<PASSWORD>')) assert response.status_code==requests.codes.ok total_time_list = [] hits_list = []",
"single_query_done query_data = query_template # print(query_data) response = requests.get(url +",
"+ '_msearch', data=query_data, headers=requestHeaders, auth=HTTPBasicAuth('admin', '<PASSWORD>'), stream=True) assert response.status_code==requests.codes.ok #",
"enumerate(vectors): assert len(vector)==dim vector_str = \"\" for num in vector:",
"vectors = np.array(hf[\"train\"][:]) num_vectors, dim = vectors.shape print(\"num_vectors: %d\" %",
"### Update Index Setting: efSearch response = requests.put(url + '_settings',",
"'_bulk', data=bulk_data, auth=HTTPBasicAuth('admin', 'I#<PASSWORD>TAHB'), headers=requestHeaders) assert response.status_code==requests.codes.ok bulk_data = \"\"",
"'_cluster/settings' cluster_data = '''{ \"persistent\" : { \"knn.algo_param.index_thread_qty\": 16 }",
"print(neighbor_id_from_result) neighbor_id_gt = neighbors[id][0:50] # topK=50 # print(\"neighbor_id_gt\") # print(neighbor_id_gt)",
"num_vectors) print(\"dim: %d\" % dim) bulk_data = \"\" start =",
"print(\"dim: %d\" % dim) bulk_data = \"\" start = time.time()",
"% dim) bulk_data = \"\" start = time.time() for (id,vector)",
"Unit: min # refresh_url = 'http://127.0.0.1:9200/sift-index/_settings' refresh_url = host +",
"single_query % (query_str) query_template += single_query_done query_data = query_template #",
"bulk_data += single_bulk_done if (id+1) % 100000 == 0: print(str(id+1))",
"# POST _bulk response = requests.put(url + '_bulk', data=bulk_data, auth=HTTPBasicAuth('admin',",
"response = requests.put(url, data=data, verify=False, headers=requestHeaders, auth=auth) assert response.status_code==requests.codes.ok #",
"}''' ef_data = ef_data % ef_search ### Update Index Setting:",
"Build an index #https://stackoverflow.com/questions/17301938/making-a-request-to-a-restful-api-using-python # PUT sift-index data = '''{",
"# for i in range(len(queries)): # for ele in result['responses']:",
"{ \"_index\": \"sift-index\", \"_id\": \"%s\" } }\\n{ \"sift_vector\": [%s] }\\n'",
"[%s],\"k\": 50}}}}\\n''' for (id,query) in enumerate(queries): assert len(query)==dim query_str =",
"for num in vector: vector_str += str(num) + ',' vector_str",
"np.array(hf[\"distances\"][:]) num_queries, q_dim = queries.shape print(\"num_queries: %d\" % num_queries) print(\"q_dim:",
"[] for count in range(5): total_time = 0 # in",
"stream=True) assert response.status_code==requests.codes.ok # print(response.text) result = json.loads(response.text) # QPS",
"% ef_search ### Update Index Setting: efSearch response = requests.put(url",
"hits_list.append(hits) print(total_time_list) total_time_avg = mean(total_time_list[2:-1]) hits_avg = mean(hits_list) QPS =",
"\"10gb\", \"number_of_replicas\": 0 } }, \"mappings\": { \"properties\": { \"sift_vector\":",
"in result['responses'][id]['hits']['hits']: neighbor_id_from_result.append(int(ele['_id'])) assert len(neighbor_id_from_result)==50 # print(\"neighbor_id_from_result: \") # print(neighbor_id_from_result)",
"aiohttp import asyncio import time import httpx from requests.auth import",
"50}}} } ''' queries = np.array(hf[\"test\"][:]) nq = len(queries) neighbors",
"1.0 * hits_avg / (nq * 50) print(ef_search, QPS, recall)",
"+= single_query_done query_data = query_template # print(query_data) response = requests.get(url",
"= '''{ \"index\" : { \"refresh_interval\": \"1s\" } } '''",
"import json import aiohttp import asyncio import time import httpx",
"cluster_data = '''{ \"persistent\" : { \"knn.algo_param.index_thread_qty\": 16 } }",
"data=refresh_data, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB')) assert response.status_code==requests.codes.ok # response = requests.post('http://127.0.0.1:9200/sift-index/_refresh',",
"= \"\" for num in query: query_str += str(num) +",
"+ 'sift-index/_settings' refresh_data = '''{ \"index\" : { \"refresh_interval\": \"1s\"",
"dim = vectors.shape print(\"num_vectors: %d\" % num_vectors) print(\"dim: %d\" %",
"vector_str = vector_str[:-1] id_str = str(id) single_bulk_done = bulk_template %",
"vectors.shape print(\"num_vectors: %d\" % num_vectors) print(\"dim: %d\" % dim) bulk_data",
"{ \"sift_vector\": { \"type\": \"knn_vector\", \"dimension\": 128 } } }",
"hf.keys(): print(\"A key of hf is %s\" % key) #Names",
"q_dim==dim ef_search_list = [50, 100, 150, 200, 250, 300] for",
"= '/tmp/sift-128-euclidean.hdf5.1M' # float dataset # path = '/tmp/sift-128-euclidean.hdf5' #",
"= np.array(hf[\"test\"][:]) nq = len(queries) neighbors = np.array(hf[\"neighbors\"][:]) # distances",
"h5py import numpy as np import json import aiohttp import",
"\"size\": 50, \"query\": {\"knn\": {\"sift_vector\": {\"vector\": [%s],\"k\": 50}}} } '''",
"ef_search_list = [50, 100, 150, 200, 250, 300] for ef_search",
"'''{ \"settings\": { \"index\": { \"knn\": true, \"knn.space_type\": \"l2\", \"knn.algo_param.m\":",
"POST _bulk response = requests.put(url + '_bulk', data=bulk_data, auth=HTTPBasicAuth('admin', 'I#<PASSWORD>TAHB'),",
"# assert response.status_code==requests.codes.ok # merge_url = 'http://127.0.0.1:9200/sift-index/_forcemerge?max_num_segments=1' merge_url = host",
"'application/json'} # https://stackoverflow.com/questions/51378099/content-type-header-not-supported auth = HTTPBasicAuth('admin', '<PASSWORD>') # Build an",
"+= str(num) + ',' query_str = query_str[:-1] # GET sift-index/_search",
"time.time() for (id,vector) in enumerate(vectors): assert len(vector)==dim vector_str = \"\"",
"% num_queries) print(\"q_dim: %d\" % q_dim) assert q_dim==dim ef_search_list =",
"} }\\n{ \"sift_vector\": [%s] }\\n' hf = h5py.File(path, 'r') for",
"} } ''' response = requests.put(cluster_url, data=cluster_data, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB'), headers=requestHeaders)",
"\"_id\": \"%s\" } }\\n{ \"sift_vector\": [%s] }\\n' hf = h5py.File(path,",
"# two nodes url = host + 'sift-index/' requestHeaders =",
"+ ',' query_str = query_str[:-1] # GET sift-index/_search single_query_done =",
"= '{ \"index\": { \"_index\": \"sift-index\", \"_id\": \"%s\" } }\\n{",
"warmup_response.status_code==requests.codes.ok # Send queries total_time = 0 # in ms",
"import requests import h5py import numpy as np import json",
"print(\"A key of hf is %s\" % key) #Names of",
"# path = '/tmp/sift-128-euclidean.hdf5' # float dataset path = '/home/ubuntu/sift-128-euclidean.hdf5'",
"hits += hits_q total_time_list.append(total_time) hits_list.append(hits) print(total_time_list) total_time_avg = mean(total_time_list[2:-1]) hits_avg",
"'sift-index/_forcemerge?max_num_segments=1' merge_response = requests.post(merge_url, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#<PASSWORD>'), timeout=600) assert merge_response.status_code==requests.codes.ok",
"'_msearch', data=query_data, headers=requestHeaders, auth=HTTPBasicAuth('admin', '<PASSWORD>'), stream=True) assert response.status_code==requests.codes.ok # print(response.text)",
"hits of this query with topk=50: %d\" % hits_q) hits",
"tooks.append(int(ele['took'])) for id in range(len(queries)): # Recall neighbor_id_from_result = []",
"= time.time() for (id,vector) in enumerate(vectors): assert len(vector)==dim vector_str =",
"json import aiohttp import asyncio import time import httpx from",
"'/tmp/sift-es.csv' # url = 'http://127.0.0.1:9200/sift-index/' host = 'https://vpc-....ap-southeast-1.es.amazonaws.com/' # single",
"single_query = '''{}\\n{\"size\": 50, \"query\": {\"knn\": {\"sift_vector\": {\"vector\": [%s],\"k\": 50}}}}\\n'''",
"in range(5): total_time = 0 # in ms hits =",
"# print(\"neighbor_id_gt\") # print(neighbor_id_gt) hits_q = len(list(set(neighbor_id_from_result) & set(neighbor_id_gt))) #",
"data = '''{ \"settings\": { \"index\": { \"knn\": true, \"knn.space_type\":",
"= result['took'] # tooks = [] # for i in",
"= '/tmp/sift-128-euclidean.hdf5' # float dataset path = '/home/ubuntu/sift-128-euclidean.hdf5' # float",
"'I#vu7bTAHB')) # response = requests.put(url, data=data, verify=False, headers=requestHeaders, auth=auth) assert",
"requests.put(cluster_url, data=cluster_data, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB'), headers=requestHeaders) assert response.status_code==requests.codes.ok # Bulkload into",
"print(\"Type in the efSearch!\") # sys.exit() # path = '/tmp/sift-128-euclidean.hdf5.1M'",
"{ \"knn\": true, \"knn.space_type\": \"l2\", \"knn.algo_param.m\": 6, \"knn.algo_param.ef_construction\": 50, \"knn.algo_param.ef_search\":",
"+ '_bulk', data=bulk_data, auth=HTTPBasicAuth('admin', 'I#<PASSWORD>TAHB'), headers=requestHeaders) assert response.status_code==requests.codes.ok bulk_data =",
"the groups in HDF5 file. vectors = np.array(hf[\"train\"][:]) num_vectors, dim",
"\"settings\": { \"index\": { \"knn\": true, \"knn.space_type\": \"l2\", \"knn.algo_param.m\": 6,",
"= [] # for i in range(len(queries)): # for ele",
"ele in result['responses'][id]['hits']['hits']: neighbor_id_from_result.append(int(ele['_id'])) assert len(neighbor_id_from_result)==50 # print(\"neighbor_id_from_result: \") #",
"index #https://stackoverflow.com/questions/17301938/making-a-request-to-a-restful-api-using-python # PUT sift-index data = '''{ \"settings\": {",
"'r') for key in hf.keys(): print(\"A key of hf is",
"= str(id) single_bulk_done = bulk_template % (id_str, vector_str) bulk_data +=",
"response.status_code==requests.codes.ok # cluster_url = 'http://127.0.0.1:9200/_cluster/settings' cluster_url = host + '_cluster/settings'",
"https://stackoverflow.com/questions/51378099/content-type-header-not-supported auth = HTTPBasicAuth('admin', '<PASSWORD>') # Build an index #https://stackoverflow.com/questions/17301938/making-a-request-to-a-restful-api-using-python",
"% q_dim) assert q_dim==dim ef_search_list = [50, 100, 150, 200,",
"single_query_done = single_query % (query_str) query_template += single_query_done query_data =",
"{ \"refresh_interval\": \"1s\" } } ''' response = requests.put(refresh_url, data=refresh_data,",
"\"_index\": \"sift-index\", \"_id\": \"%s\" } }\\n{ \"sift_vector\": [%s] }\\n' hf",
"\"sift_vector\": [%s] }\\n' hf = h5py.File(path, 'r') for key in",
"data=ef_data, headers=requestHeaders, auth=HTTPBasicAuth('admin', '<PASSWORD>')) assert response.status_code==requests.codes.ok total_time_list = [] hits_list",
"{\"vector\": [%s],\"k\": 50}}}}\\n''' for (id,query) in enumerate(queries): assert len(query)==dim query_str",
"{'content-type': 'application/json'} # https://stackoverflow.com/questions/51378099/content-type-header-not-supported auth = HTTPBasicAuth('admin', '<PASSWORD>') # Build",
"requests.put(url + '_bulk', data=bulk_data, auth=HTTPBasicAuth('admin', 'I#<PASSWORD>TAHB'), headers=requestHeaders) assert response.status_code==requests.codes.ok bulk_data",
"\"refresh_interval\": \"1s\" } } ''' response = requests.put(refresh_url, data=refresh_data, headers=requestHeaders,",
"total_time = 0 # in ms hits = 0 #",
"calculation query_template = ''' ''' single_query = '''{}\\n{\"size\": 50, \"query\":",
"= ''' ''' single_query = '''{}\\n{\"size\": 50, \"query\": {\"knn\": {\"sift_vector\":",
"# Unit: min # refresh_url = 'http://127.0.0.1:9200/sift-index/_settings' refresh_url = host",
"refresh_url = host + 'sift-index/_settings' refresh_data = '''{ \"index\" :",
"of the groups in HDF5 file. vectors = np.array(hf[\"train\"][:]) num_vectors,",
"print(\"Insert Time: %d mins\" % ((end - start) / 60.0))",
"= 'http://127.0.0.1:9200/_opendistro/_knn/warmup/sift-index' warmup_url = host + '_opendistro/_knn/warmup/sift-index' warmup_response = requests.get(warmup_url,",
"= requests.get(warmup_url, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I<PASSWORD>')) assert warmup_response.status_code==requests.codes.ok # Send queries",
"neighbor_id_from_result = [] for ele in result['responses'][id]['hits']['hits']: neighbor_id_from_result.append(int(ele['_id'])) assert len(neighbor_id_from_result)==50",
"file. vectors = np.array(hf[\"train\"][:]) num_vectors, dim = vectors.shape print(\"num_vectors: %d\"",
"is %s\" % key) #Names of the groups in HDF5",
"sys import requests import h5py import numpy as np import",
"print(str(id+1)) # POST _bulk response = requests.put(url + '_bulk', data=bulk_data,",
"= time.time() print(\"Insert Time: %d mins\" % ((end - start)",
"assert response.status_code==requests.codes.ok # merge_url = 'http://127.0.0.1:9200/sift-index/_forcemerge?max_num_segments=1' merge_url = host +",
"hits_list = [] for count in range(5): total_time = 0",
"% ((end - start) / 60.0)) # Unit: min #",
"(total_time_avg / 1000.0) recall = 1.0 * hits_avg / (nq",
"= host + 'sift-index/_forcemerge?max_num_segments=1' merge_response = requests.post(merge_url, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#<PASSWORD>'),",
"in ms hits = 0 # for recall calculation query_template",
"requests import h5py import numpy as np import json import",
"= 'http://127.0.0.1:9200/sift-index/_settings' refresh_url = host + 'sift-index/_settings' refresh_data = '''{",
"url = 'http://127.0.0.1:9200/sift-index/' host = 'https://vpc-....ap-southeast-1.es.amazonaws.com/' # single node #",
"\"sift-index\", \"_id\": \"%s\" } }\\n{ \"sift_vector\": [%s] }\\n' hf =",
"'I#vu7bTAHB')) assert response.status_code==requests.codes.ok # response = requests.post('http://127.0.0.1:9200/sift-index/_refresh', verify=False, headers=requestHeaders) #",
"'<PASSWORD>') # Build an index #https://stackoverflow.com/questions/17301938/making-a-request-to-a-restful-api-using-python # PUT sift-index data",
"requests.put(url, data=data, verify=False, headers=requestHeaders, auth=auth) assert response.status_code==requests.codes.ok # cluster_url =",
"# response = requests.put(url, data=data, verify=False, headers=requestHeaders, auth=auth) assert response.status_code==requests.codes.ok",
"# print(\"Type in the efSearch!\") # sys.exit() # path =",
"cluster_url = 'http://127.0.0.1:9200/_cluster/settings' cluster_url = host + '_cluster/settings' cluster_data =",
"# https://medium.com/@kumon/how-to-realize-similarity-search-with-elasticsearch-3dd5641b9adb response = requests.put(url, data=data, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB')) #",
"nodes url = host + 'sift-index/' requestHeaders = {'content-type': 'application/json'}",
"+ ',' vector_str = vector_str[:-1] id_str = str(id) single_bulk_done =",
"= 1.0 * nq / (total_time_avg / 1000.0) recall =",
"auth=HTTPBasicAuth('admin', 'I#<PASSWORD>TAHB'), headers=requestHeaders) assert response.status_code==requests.codes.ok bulk_data = \"\" end =",
"print(total_time_list) total_time_avg = mean(total_time_list[2:-1]) hits_avg = mean(hits_list) QPS = 1.0",
"requests.auth import HTTPBasicAuth from statistics import mean # if len(sys.argv)",
"\"%s\" } }\\n{ \"sift_vector\": [%s] }\\n' hf = h5py.File(path, 'r')",
"50, \"refresh_interval\": -1, \"translog.flush_threshold_size\": \"10gb\", \"number_of_replicas\": 0 } }, \"mappings\":",
"# https://stackoverflow.com/questions/51378099/content-type-header-not-supported auth = HTTPBasicAuth('admin', '<PASSWORD>') # Build an index",
"as np import json import aiohttp import asyncio import time",
"\"knn.algo_param.m\": 6, \"knn.algo_param.ef_construction\": 50, \"knn.algo_param.ef_search\": 50, \"refresh_interval\": -1, \"translog.flush_threshold_size\": \"10gb\",",
"\"index\": { \"knn.algo_param.ef_search\": %d } }''' ef_data = ef_data %",
"\"refresh_interval\": -1, \"translog.flush_threshold_size\": \"10gb\", \"number_of_replicas\": 0 } }, \"mappings\": {",
"response = requests.put(url + '_bulk', data=bulk_data, auth=HTTPBasicAuth('admin', 'I#<PASSWORD>TAHB'), headers=requestHeaders) assert",
"((end - start) / 60.0)) # Unit: min # refresh_url",
"!= 2: # print(\"Type in the efSearch!\") # sys.exit() #",
"#https://stackoverflow.com/questions/17301938/making-a-request-to-a-restful-api-using-python # PUT sift-index data = '''{ \"settings\": { \"index\":",
"assert response.status_code==requests.codes.ok # cluster_url = 'http://127.0.0.1:9200/_cluster/settings' cluster_url = host +",
"%d\" % dim) bulk_data = \"\" start = time.time() for",
"/ (total_time_avg / 1000.0) recall = 1.0 * hits_avg /",
"response.status_code==requests.codes.ok # Bulkload into index bulk_template = '{ \"index\": {",
"neighbors = np.array(hf[\"neighbors\"][:]) # distances = np.array(hf[\"distances\"][:]) num_queries, q_dim =",
"'/tmp/sift-128-euclidean.hdf5.1M' # float dataset # path = '/tmp/sift-128-euclidean.hdf5' # float",
"# tooks.append(int(ele['took'])) for id in range(len(queries)): # Recall neighbor_id_from_result =",
"''' response = requests.put(refresh_url, data=refresh_data, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB')) assert response.status_code==requests.codes.ok",
"'''{ \"persistent\" : { \"knn.algo_param.index_thread_qty\": 16 } } ''' response",
"total_time_avg = mean(total_time_list[2:-1]) hits_avg = mean(hits_list) QPS = 1.0 *",
"bulk_data = \"\" start = time.time() for (id,vector) in enumerate(vectors):",
"statistics import mean # if len(sys.argv) != 2: # print(\"Type",
"headers=requestHeaders) assert response.status_code==requests.codes.ok bulk_data = \"\" end = time.time() print(\"Insert",
"assert len(neighbor_id_from_result)==50 # print(\"neighbor_id_from_result: \") # print(neighbor_id_from_result) neighbor_id_gt = neighbors[id][0:50]",
"path = '/tmp/sift-128-euclidean.hdf5' # float dataset path = '/home/ubuntu/sift-128-euclidean.hdf5' #",
"= requests.put(url + '_settings', data=ef_data, headers=requestHeaders, auth=HTTPBasicAuth('admin', '<PASSWORD>')) assert response.status_code==requests.codes.ok",
"query_template = ''' { \"size\": 50, \"query\": {\"knn\": {\"sift_vector\": {\"vector\":",
"this query with topk=50: %d\" % hits_q) hits += hits_q",
"hf is %s\" % key) #Names of the groups in",
"300] for ef_search in ef_search_list: ef_data = '''{ \"index\": {",
"= \"\" start = time.time() for (id,vector) in enumerate(vectors): assert",
"\"dimension\": 128 } } } }''' # https://medium.com/@kumon/how-to-realize-similarity-search-with-elasticsearch-3dd5641b9adb response =",
"merge_url = 'http://127.0.0.1:9200/sift-index/_forcemerge?max_num_segments=1' merge_url = host + 'sift-index/_forcemerge?max_num_segments=1' merge_response =",
"response.status_code==requests.codes.ok # print(response.text) result = json.loads(response.text) # QPS total_time =",
"query_str += str(num) + ',' query_str = query_str[:-1] # GET",
"#Names of the groups in HDF5 file. vectors = np.array(hf[\"train\"][:])",
"query_data = query_template # print(query_data) response = requests.get(url + '_msearch',",
"hits = 0 # for recall calculation query_template = '''",
"vector_str) bulk_data += single_bulk_done if (id+1) % 100000 == 0:",
"''' single_query = '''{}\\n{\"size\": 50, \"query\": {\"knn\": {\"sift_vector\": {\"vector\": [%s],\"k\":",
"# float dataset # path = '/tmp/sift-128-euclidean.hdf5' # float dataset",
"'/tmp/sift-128-euclidean.hdf5' # float dataset path = '/home/ubuntu/sift-128-euclidean.hdf5' # float dataset",
"# in ms hits = 0 # for recall calculation",
"recall = 1.0 * hits_avg / (nq * 50) print(ef_search,",
"+= single_bulk_done if (id+1) % 100000 == 0: print(str(id+1)) #",
"{ \"properties\": { \"sift_vector\": { \"type\": \"knn_vector\", \"dimension\": 128 }",
"query_str = query_str[:-1] # GET sift-index/_search single_query_done = single_query %",
"1000.0) recall = 1.0 * hits_avg / (nq * 50)",
"0: print(str(id+1)) # POST _bulk response = requests.put(url + '_bulk',",
"= \"\" for num in vector: vector_str += str(num) +",
"print(\"q_dim: %d\" % q_dim) assert q_dim==dim ef_search_list = [50, 100,",
"= '''{ \"settings\": { \"index\": { \"knn\": true, \"knn.space_type\": \"l2\",",
"ef_data = '''{ \"index\": { \"knn.algo_param.ef_search\": %d } }''' ef_data",
"sift-index data = '''{ \"settings\": { \"index\": { \"knn\": true,",
"float dataset path = '/home/ubuntu/sift-128-euclidean.hdf5' # float dataset output_csv =",
"%s\" % key) #Names of the groups in HDF5 file.",
"warmup_response = requests.get(warmup_url, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I<PASSWORD>')) assert warmup_response.status_code==requests.codes.ok # Send",
"= host + 'sift-index/_settings' refresh_data = '''{ \"index\" : {",
"headers=requestHeaders, auth=HTTPBasicAuth('admin', '<PASSWORD>'), stream=True) assert response.status_code==requests.codes.ok # print(response.text) result =",
"in enumerate(vectors): assert len(vector)==dim vector_str = \"\" for num in",
"key) #Names of the groups in HDF5 file. vectors =",
"range(len(queries)): # Recall neighbor_id_from_result = [] for ele in result['responses'][id]['hits']['hits']:",
"& set(neighbor_id_gt))) # print(\"# hits of this query with topk=50:",
"%d\" % hits_q) hits += hits_q total_time_list.append(total_time) hits_list.append(hits) print(total_time_list) total_time_avg",
"for ele in result['responses'][id]['hits']['hits']: neighbor_id_from_result.append(int(ele['_id'])) assert len(neighbor_id_from_result)==50 # print(\"neighbor_id_from_result: \")",
"index bulk_template = '{ \"index\": { \"_index\": \"sift-index\", \"_id\": \"%s\"",
"# tooks = [] # for i in range(len(queries)): #",
"'/home/ubuntu/sift-128-euclidean.hdf5' # float dataset output_csv = '/tmp/sift-es.csv' # url =",
"with topk=50: %d\" % hits_q) hits += hits_q total_time_list.append(total_time) hits_list.append(hits)",
"\"knn.algo_param.ef_construction\": 50, \"knn.algo_param.ef_search\": 50, \"refresh_interval\": -1, \"translog.flush_threshold_size\": \"10gb\", \"number_of_replicas\": 0",
"total_time_list.append(total_time) hits_list.append(hits) print(total_time_list) total_time_avg = mean(total_time_list[2:-1]) hits_avg = mean(hits_list) QPS",
"'sift-index/_settings' refresh_data = '''{ \"index\" : { \"refresh_interval\": \"1s\" }",
"for num in query: query_str += str(num) + ',' query_str",
"mean # if len(sys.argv) != 2: # print(\"Type in the",
"print(\"# hits of this query with topk=50: %d\" % hits_q)",
"(id,vector) in enumerate(vectors): assert len(vector)==dim vector_str = \"\" for num",
"'I#vu7bTAHB'), headers=requestHeaders) assert response.status_code==requests.codes.ok # Bulkload into index bulk_template =",
"50}}}}\\n''' for (id,query) in enumerate(queries): assert len(query)==dim query_str = \"\"",
"}\\n{ \"sift_vector\": [%s] }\\n' hf = h5py.File(path, 'r') for key",
"response.status_code==requests.codes.ok total_time_list = [] hits_list = [] for count in",
"{\"sift_vector\": {\"vector\": [%s],\"k\": 50}}} } ''' queries = np.array(hf[\"test\"][:]) nq",
"Index Setting: efSearch response = requests.put(url + '_settings', data=ef_data, headers=requestHeaders,",
"response = requests.get(url + '_msearch', data=query_data, headers=requestHeaders, auth=HTTPBasicAuth('admin', '<PASSWORD>'), stream=True)",
"in HDF5 file. vectors = np.array(hf[\"train\"][:]) num_vectors, dim = vectors.shape",
"host + 'sift-index/_forcemerge?max_num_segments=1' merge_response = requests.post(merge_url, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#<PASSWORD>'), timeout=600)",
"topK=50 # print(\"neighbor_id_gt\") # print(neighbor_id_gt) hits_q = len(list(set(neighbor_id_from_result) & set(neighbor_id_gt)))",
"= '/home/ubuntu/sift-128-euclidean.hdf5' # float dataset output_csv = '/tmp/sift-es.csv' # url",
"headers=requestHeaders) # assert response.status_code==requests.codes.ok # merge_url = 'http://127.0.0.1:9200/sift-index/_forcemerge?max_num_segments=1' merge_url =",
"headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB')) # response = requests.put(url, data=data, verify=False, headers=requestHeaders,",
"# https://docs.aws.amazon.com/opensearch-service/latest/developerguide/knn.html import sys import requests import h5py import numpy",
"str(num) + ',' vector_str = vector_str[:-1] id_str = str(id) single_bulk_done",
"requests.put(url + '_settings', data=ef_data, headers=requestHeaders, auth=HTTPBasicAuth('admin', '<PASSWORD>')) assert response.status_code==requests.codes.ok total_time_list",
"range(5): total_time = 0 # in ms hits = 0",
"num in vector: vector_str += str(num) + ',' vector_str =",
"num_queries) print(\"q_dim: %d\" % q_dim) assert q_dim==dim ef_search_list = [50,",
"result['took'] # tooks = [] # for i in range(len(queries)):",
"in result['responses']: # tooks.append(int(ele['took'])) for id in range(len(queries)): # Recall",
"= np.array(hf[\"train\"][:]) num_vectors, dim = vectors.shape print(\"num_vectors: %d\" % num_vectors)",
"''' response = requests.put(cluster_url, data=cluster_data, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB'), headers=requestHeaders) assert response.status_code==requests.codes.ok",
"data=bulk_data, auth=HTTPBasicAuth('admin', 'I#<PASSWORD>TAHB'), headers=requestHeaders) assert response.status_code==requests.codes.ok bulk_data = \"\" end",
"'http://127.0.0.1:9200/sift-index/_forcemerge?max_num_segments=1' merge_url = host + 'sift-index/_forcemerge?max_num_segments=1' merge_response = requests.post(merge_url, headers=requestHeaders,",
"ef_search_list: ef_data = '''{ \"index\": { \"knn.algo_param.ef_search\": %d } }'''",
"* nq / (total_time_avg / 1000.0) recall = 1.0 *",
"import httpx from requests.auth import HTTPBasicAuth from statistics import mean",
"key in hf.keys(): print(\"A key of hf is %s\" %",
"queries = np.array(hf[\"test\"][:]) nq = len(queries) neighbors = np.array(hf[\"neighbors\"][:]) #",
"count in range(5): total_time = 0 # in ms hits",
"len(list(set(neighbor_id_from_result) & set(neighbor_id_gt))) # print(\"# hits of this query with",
"h5py.File(path, 'r') for key in hf.keys(): print(\"A key of hf",
"result['responses'][id]['hits']['hits']: neighbor_id_from_result.append(int(ele['_id'])) assert len(neighbor_id_from_result)==50 # print(\"neighbor_id_from_result: \") # print(neighbor_id_from_result) neighbor_id_gt",
"\"sift_vector\": { \"type\": \"knn_vector\", \"dimension\": 128 } } } }'''",
"= requests.post(merge_url, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#<PASSWORD>'), timeout=600) assert merge_response.status_code==requests.codes.ok # warmup_url",
"for recall calculation query_template = ''' { \"size\": 50, \"query\":",
"[] # for i in range(len(queries)): # for ele in",
"host = 'https://vpc-....ap-southeast-1.es.amazonaws.com/' # two nodes url = host +",
"# Send queries total_time = 0 # in ms hits",
"# refresh_url = 'http://127.0.0.1:9200/sift-index/_settings' refresh_url = host + 'sift-index/_settings' refresh_data",
"= HTTPBasicAuth('admin', '<PASSWORD>') # Build an index #https://stackoverflow.com/questions/17301938/making-a-request-to-a-restful-api-using-python # PUT",
"response.status_code==requests.codes.ok bulk_data = \"\" end = time.time() print(\"Insert Time: %d",
"200, 250, 300] for ef_search in ef_search_list: ef_data = '''{",
"import time import httpx from requests.auth import HTTPBasicAuth from statistics",
"assert response.status_code==requests.codes.ok # print(response.text) result = json.loads(response.text) # QPS total_time",
"[%s] }\\n' hf = h5py.File(path, 'r') for key in hf.keys():",
"merge_response = requests.post(merge_url, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#<PASSWORD>'), timeout=600) assert merge_response.status_code==requests.codes.ok #",
"GET sift-index/_search single_query_done = single_query % (query_str) query_template += single_query_done",
"hf = h5py.File(path, 'r') for key in hf.keys(): print(\"A key",
"\"\" for num in query: query_str += str(num) + ','",
"ef_data = ef_data % ef_search ### Update Index Setting: efSearch",
"{\"knn\": {\"sift_vector\": {\"vector\": [%s],\"k\": 50}}}}\\n''' for (id,query) in enumerate(queries): assert",
"assert response.status_code==requests.codes.ok bulk_data = \"\" end = time.time() print(\"Insert Time:",
"ms hits = 0 # for recall calculation query_template =",
"} } }''' # https://medium.com/@kumon/how-to-realize-similarity-search-with-elasticsearch-3dd5641b9adb response = requests.put(url, data=data, headers=requestHeaders,",
"= host + '_opendistro/_knn/warmup/sift-index' warmup_response = requests.get(warmup_url, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I<PASSWORD>'))",
"# for ele in result['responses']: # tooks.append(int(ele['took'])) for id in",
"bulk_data = \"\" end = time.time() print(\"Insert Time: %d mins\"",
"} } } }''' # https://medium.com/@kumon/how-to-realize-similarity-search-with-elasticsearch-3dd5641b9adb response = requests.put(url, data=data,",
"host + '_opendistro/_knn/warmup/sift-index' warmup_response = requests.get(warmup_url, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I<PASSWORD>')) assert",
"Update Index Setting: efSearch response = requests.put(url + '_settings', data=ef_data,",
"headers=requestHeaders) assert response.status_code==requests.codes.ok # Bulkload into index bulk_template = '{",
"= requests.put(url + '_bulk', data=bulk_data, auth=HTTPBasicAuth('admin', 'I#<PASSWORD>TAHB'), headers=requestHeaders) assert response.status_code==requests.codes.ok",
"https://medium.com/@kumon/how-to-realize-similarity-search-with-elasticsearch-3dd5641b9adb response = requests.put(url, data=data, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB')) # response",
"= vectors.shape print(\"num_vectors: %d\" % num_vectors) print(\"dim: %d\" % dim)",
"= [50, 100, 150, 200, 250, 300] for ef_search in",
"tooks = [] # for i in range(len(queries)): # for",
"neighbor_id_gt = neighbors[id][0:50] # topK=50 # print(\"neighbor_id_gt\") # print(neighbor_id_gt) hits_q",
"print(query_data) response = requests.get(url + '_msearch', data=query_data, headers=requestHeaders, auth=HTTPBasicAuth('admin', '<PASSWORD>'),",
"= np.array(hf[\"neighbors\"][:]) # distances = np.array(hf[\"distances\"][:]) num_queries, q_dim = queries.shape",
"distances = np.array(hf[\"distances\"][:]) num_queries, q_dim = queries.shape print(\"num_queries: %d\" %",
"verify=False, headers=requestHeaders, auth=auth) assert response.status_code==requests.codes.ok # cluster_url = 'http://127.0.0.1:9200/_cluster/settings' cluster_url",
"requests.put(refresh_url, data=refresh_data, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB')) assert response.status_code==requests.codes.ok # response =",
"assert merge_response.status_code==requests.codes.ok # warmup_url = 'http://127.0.0.1:9200/_opendistro/_knn/warmup/sift-index' warmup_url = host +",
"mean(total_time_list[2:-1]) hits_avg = mean(hits_list) QPS = 1.0 * nq /",
"250, 300] for ef_search in ef_search_list: ef_data = '''{ \"index\":",
"path = '/home/ubuntu/sift-128-euclidean.hdf5' # float dataset output_csv = '/tmp/sift-es.csv' #",
"{ \"index\": { \"knn\": true, \"knn.space_type\": \"l2\", \"knn.algo_param.m\": 6, \"knn.algo_param.ef_construction\":",
"recall calculation query_template = ''' ''' single_query = '''{}\\n{\"size\": 50,",
"QPS = 1.0 * nq / (total_time_avg / 1000.0) recall",
"+ 'sift-index/_forcemerge?max_num_segments=1' merge_response = requests.post(merge_url, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#<PASSWORD>'), timeout=600) assert",
"(id+1) % 100000 == 0: print(str(id+1)) # POST _bulk response",
"# merge_url = 'http://127.0.0.1:9200/sift-index/_forcemerge?max_num_segments=1' merge_url = host + 'sift-index/_forcemerge?max_num_segments=1' merge_response",
"# print(neighbor_id_from_result) neighbor_id_gt = neighbors[id][0:50] # topK=50 # print(\"neighbor_id_gt\") #",
"numpy as np import json import aiohttp import asyncio import",
"query with topk=50: %d\" % hits_q) hits += hits_q total_time_list.append(total_time)",
"\"translog.flush_threshold_size\": \"10gb\", \"number_of_replicas\": 0 } }, \"mappings\": { \"properties\": {",
"[50, 100, 150, 200, 250, 300] for ef_search in ef_search_list:",
"# if len(sys.argv) != 2: # print(\"Type in the efSearch!\")",
"nq = len(queries) neighbors = np.array(hf[\"neighbors\"][:]) # distances = np.array(hf[\"distances\"][:])",
"}\\n' hf = h5py.File(path, 'r') for key in hf.keys(): print(\"A",
"0 # for recall calculation query_template = ''' ''' single_query",
"dataset path = '/home/ubuntu/sift-128-euclidean.hdf5' # float dataset output_csv = '/tmp/sift-es.csv'",
"import HTTPBasicAuth from statistics import mean # if len(sys.argv) !=",
"response.status_code==requests.codes.ok # response = requests.post('http://127.0.0.1:9200/sift-index/_refresh', verify=False, headers=requestHeaders) # assert response.status_code==requests.codes.ok",
"= neighbors[id][0:50] # topK=50 # print(\"neighbor_id_gt\") # print(neighbor_id_gt) hits_q =",
"efSearch response = requests.put(url + '_settings', data=ef_data, headers=requestHeaders, auth=HTTPBasicAuth('admin', '<PASSWORD>'))",
"128 } } } }''' # https://medium.com/@kumon/how-to-realize-similarity-search-with-elasticsearch-3dd5641b9adb response = requests.put(url,",
"100, 150, 200, 250, 300] for ef_search in ef_search_list: ef_data",
"''' queries = np.array(hf[\"test\"][:]) nq = len(queries) neighbors = np.array(hf[\"neighbors\"][:])",
"= 0 # for recall calculation query_template = ''' '''",
"host = 'https://vpc-....ap-southeast-1.es.amazonaws.com/' # single node # host = 'https://vpc-....ap-southeast-1.es.amazonaws.com/'",
"% key) #Names of the groups in HDF5 file. vectors",
"'http://127.0.0.1:9200/sift-index/_settings' refresh_url = host + 'sift-index/_settings' refresh_data = '''{ \"index\"",
"= queries.shape print(\"num_queries: %d\" % num_queries) print(\"q_dim: %d\" % q_dim)",
"[] hits_list = [] for count in range(5): total_time =",
"in the efSearch!\") # sys.exit() # path = '/tmp/sift-128-euclidean.hdf5.1M' #",
"timeout=600) assert merge_response.status_code==requests.codes.ok # warmup_url = 'http://127.0.0.1:9200/_opendistro/_knn/warmup/sift-index' warmup_url = host",
"auth=HTTPBasicAuth('admin', 'I#vu7bTAHB'), headers=requestHeaders) assert response.status_code==requests.codes.ok # Bulkload into index bulk_template",
"{\"vector\": [%s],\"k\": 50}}} } ''' queries = np.array(hf[\"test\"][:]) nq =",
"# float dataset output_csv = '/tmp/sift-es.csv' # url = 'http://127.0.0.1:9200/sift-index/'",
"Setting: efSearch response = requests.put(url + '_settings', data=ef_data, headers=requestHeaders, auth=HTTPBasicAuth('admin',",
"- start) / 60.0)) # Unit: min # refresh_url =",
"url = host + 'sift-index/' requestHeaders = {'content-type': 'application/json'} #",
"\"index\" : { \"refresh_interval\": \"1s\" } } ''' response =",
"result = json.loads(response.text) # QPS total_time = result['took'] # tooks",
"\"knn.algo_param.index_thread_qty\": 16 } } ''' response = requests.put(cluster_url, data=cluster_data, auth=HTTPBasicAuth('admin',",
"query_template # print(query_data) response = requests.get(url + '_msearch', data=query_data, headers=requestHeaders,",
"queries total_time = 0 # in ms hits = 0",
"requestHeaders = {'content-type': 'application/json'} # https://stackoverflow.com/questions/51378099/content-type-header-not-supported auth = HTTPBasicAuth('admin', '<PASSWORD>')",
"query_str[:-1] # GET sift-index/_search single_query_done = single_query % (query_str) query_template",
"response.status_code==requests.codes.ok # merge_url = 'http://127.0.0.1:9200/sift-index/_forcemerge?max_num_segments=1' merge_url = host + 'sift-index/_forcemerge?max_num_segments=1'",
"from statistics import mean # if len(sys.argv) != 2: #",
"set(neighbor_id_gt))) # print(\"# hits of this query with topk=50: %d\"",
"in hf.keys(): print(\"A key of hf is %s\" % key)",
"topk=50: %d\" % hits_q) hits += hits_q total_time_list.append(total_time) hits_list.append(hits) print(total_time_list)",
"\"type\": \"knn_vector\", \"dimension\": 128 } } } }''' # https://medium.com/@kumon/how-to-realize-similarity-search-with-elasticsearch-3dd5641b9adb",
"str(num) + ',' query_str = query_str[:-1] # GET sift-index/_search single_query_done",
"\"1s\" } } ''' response = requests.put(refresh_url, data=refresh_data, headers=requestHeaders, auth=HTTPBasicAuth('admin',",
"len(sys.argv) != 2: # print(\"Type in the efSearch!\") # sys.exit()",
"np import json import aiohttp import asyncio import time import",
"dataset output_csv = '/tmp/sift-es.csv' # url = 'http://127.0.0.1:9200/sift-index/' host =",
"start = time.time() for (id,vector) in enumerate(vectors): assert len(vector)==dim vector_str",
"in range(len(queries)): # Recall neighbor_id_from_result = [] for ele in",
"print(\"neighbor_id_from_result: \") # print(neighbor_id_from_result) neighbor_id_gt = neighbors[id][0:50] # topK=50 #",
"= len(list(set(neighbor_id_from_result) & set(neighbor_id_gt))) # print(\"# hits of this query",
"float dataset output_csv = '/tmp/sift-es.csv' # url = 'http://127.0.0.1:9200/sift-index/' host",
"# single node # host = 'https://vpc-....ap-southeast-1.es.amazonaws.com/' # two nodes",
"# print(\"neighbor_id_from_result: \") # print(neighbor_id_from_result) neighbor_id_gt = neighbors[id][0:50] # topK=50",
"\"\" end = time.time() print(\"Insert Time: %d mins\" % ((end",
"HDF5 file. vectors = np.array(hf[\"train\"][:]) num_vectors, dim = vectors.shape print(\"num_vectors:",
"{ \"type\": \"knn_vector\", \"dimension\": 128 } } } }''' #",
"= ef_data % ef_search ### Update Index Setting: efSearch response",
"in enumerate(queries): assert len(query)==dim query_str = \"\" for num in",
"= requests.get(url + '_msearch', data=query_data, headers=requestHeaders, auth=HTTPBasicAuth('admin', '<PASSWORD>'), stream=True) assert",
"/ 60.0)) # Unit: min # refresh_url = 'http://127.0.0.1:9200/sift-index/_settings' refresh_url",
"= 'http://127.0.0.1:9200/sift-index/_forcemerge?max_num_segments=1' merge_url = host + 'sift-index/_forcemerge?max_num_segments=1' merge_response = requests.post(merge_url,",
"'''{}\\n{\"size\": 50, \"query\": {\"knn\": {\"sift_vector\": {\"vector\": [%s],\"k\": 50}}}}\\n''' for (id,query)",
"data=query_data, headers=requestHeaders, auth=HTTPBasicAuth('admin', '<PASSWORD>'), stream=True) assert response.status_code==requests.codes.ok # print(response.text) result",
"import numpy as np import json import aiohttp import asyncio",
"mean(hits_list) QPS = 1.0 * nq / (total_time_avg / 1000.0)",
"}''' # https://medium.com/@kumon/how-to-realize-similarity-search-with-elasticsearch-3dd5641b9adb response = requests.put(url, data=data, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB'))",
"'_opendistro/_knn/warmup/sift-index' warmup_response = requests.get(warmup_url, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I<PASSWORD>')) assert warmup_response.status_code==requests.codes.ok #",
"sift-index/_search single_query_done = single_query % (query_str) query_template += single_query_done query_data",
"HTTPBasicAuth from statistics import mean # if len(sys.argv) != 2:",
"range(len(queries)): # for ele in result['responses']: # tooks.append(int(ele['took'])) for id",
"# print(query_data) response = requests.get(url + '_msearch', data=query_data, headers=requestHeaders, auth=HTTPBasicAuth('admin',",
"%d mins\" % ((end - start) / 60.0)) # Unit:",
"response = requests.put(url, data=data, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB')) # response =",
"result['responses']: # tooks.append(int(ele['took'])) for id in range(len(queries)): # Recall neighbor_id_from_result",
"auth=HTTPBasicAuth('admin', 'I#vu7bTAHB')) # response = requests.put(url, data=data, verify=False, headers=requestHeaders, auth=auth)",
"response = requests.post('http://127.0.0.1:9200/sift-index/_refresh', verify=False, headers=requestHeaders) # assert response.status_code==requests.codes.ok # merge_url",
"into index bulk_template = '{ \"index\": { \"_index\": \"sift-index\", \"_id\":",
"len(vector)==dim vector_str = \"\" for num in vector: vector_str +=",
"recall calculation query_template = ''' { \"size\": 50, \"query\": {\"knn\":",
"num_queries, q_dim = queries.shape print(\"num_queries: %d\" % num_queries) print(\"q_dim: %d\"",
"time import httpx from requests.auth import HTTPBasicAuth from statistics import",
"+ '_settings', data=ef_data, headers=requestHeaders, auth=HTTPBasicAuth('admin', '<PASSWORD>')) assert response.status_code==requests.codes.ok total_time_list =",
"for (id,query) in enumerate(queries): assert len(query)==dim query_str = \"\" for",
"refresh_data = '''{ \"index\" : { \"refresh_interval\": \"1s\" } }",
"num_vectors, dim = vectors.shape print(\"num_vectors: %d\" % num_vectors) print(\"dim: %d\"",
"\"mappings\": { \"properties\": { \"sift_vector\": { \"type\": \"knn_vector\", \"dimension\": 128",
"https://medium.com/@kumon/how-to-realize-similarity-search-with-elasticsearch-3dd5641b9adb # https://docs.aws.amazon.com/opensearch-service/latest/developerguide/knn.html import sys import requests import h5py import",
"# print(response.text) result = json.loads(response.text) # QPS total_time = result['took']",
"+ '_cluster/settings' cluster_data = '''{ \"persistent\" : { \"knn.algo_param.index_thread_qty\": 16",
"'_settings', data=ef_data, headers=requestHeaders, auth=HTTPBasicAuth('admin', '<PASSWORD>')) assert response.status_code==requests.codes.ok total_time_list = []",
"'<PASSWORD>')) assert response.status_code==requests.codes.ok total_time_list = [] hits_list = [] for",
"data=cluster_data, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB'), headers=requestHeaders) assert response.status_code==requests.codes.ok # Bulkload into index",
"'''{ \"index\": { \"knn.algo_param.ef_search\": %d } }''' ef_data = ef_data",
"# PUT sift-index data = '''{ \"settings\": { \"index\": {",
"query: query_str += str(num) + ',' query_str = query_str[:-1] #",
"= 'https://vpc-....ap-southeast-1.es.amazonaws.com/' # single node # host = 'https://vpc-....ap-southeast-1.es.amazonaws.com/' #",
"host + 'sift-index/' requestHeaders = {'content-type': 'application/json'} # https://stackoverflow.com/questions/51378099/content-type-header-not-supported auth",
"+ '_opendistro/_knn/warmup/sift-index' warmup_response = requests.get(warmup_url, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I<PASSWORD>')) assert warmup_response.status_code==requests.codes.ok",
"# response = requests.post('http://127.0.0.1:9200/sift-index/_refresh', verify=False, headers=requestHeaders) # assert response.status_code==requests.codes.ok #",
"= single_query % (query_str) query_template += single_query_done query_data = query_template",
"\"knn\": true, \"knn.space_type\": \"l2\", \"knn.algo_param.m\": 6, \"knn.algo_param.ef_construction\": 50, \"knn.algo_param.ef_search\": 50,",
"{\"sift_vector\": {\"vector\": [%s],\"k\": 50}}}}\\n''' for (id,query) in enumerate(queries): assert len(query)==dim",
"\"knn.space_type\": \"l2\", \"knn.algo_param.m\": 6, \"knn.algo_param.ef_construction\": 50, \"knn.algo_param.ef_search\": 50, \"refresh_interval\": -1,",
"auth=HTTPBasicAuth('admin', 'I<PASSWORD>')) assert warmup_response.status_code==requests.codes.ok # Send queries total_time = 0",
"efSearch!\") # sys.exit() # path = '/tmp/sift-128-euclidean.hdf5.1M' # float dataset",
"import aiohttp import asyncio import time import httpx from requests.auth",
"host + '_cluster/settings' cluster_data = '''{ \"persistent\" : { \"knn.algo_param.index_thread_qty\":",
"Bulkload into index bulk_template = '{ \"index\": { \"_index\": \"sift-index\","
] |
[
"specified in the # environment options CIBW_MANYLINUX1_*_IMAGE if \"linux\" in",
"# also check that we got the right wheels built",
"setup_py_add=textwrap.dedent(r''' import os, sys # check that we're running in",
"options CIBW_MANYLINUX1_*_IMAGE if \"linux\" in sys.platform and not os.path.exists(\"/dockcross\"): raise",
"the correct docker image?\" ) ''') ) def test(tmp_path): if",
"!= 'linux': pytest.skip('the test is only relevant to the linux",
"not in ['x86_64', 'i686']: pytest.skip('this test is currently only possible",
"linux build') if platform.machine() not in ['x86_64', 'i686']: pytest.skip('this test",
"'dockcross/manylinux2010-x86', 'CIBW_SKIP': 'pp* cp39-*', }) # also check that we",
"in w and '-cp39-' not in w] assert set(actual_wheels) ==",
"utils.platform != 'linux': pytest.skip('the test is only relevant to the",
"/ 'project' dockcross_only_project.generate(project_dir) actual_wheels = utils.cibuildwheel_run(project_dir, add_env={ 'CIBW_MANYLINUX_X86_64_IMAGE': 'dockcross/manylinux2010-x64', 'CIBW_MANYLINUX_I686_IMAGE':",
"x86_64/i686 due to availability of alternative images') project_dir = tmp_path",
"= [w for w in utils.expected_wheels('spam', '0.1.0') if '-pp' not",
"pytest.skip('the test is only relevant to the linux build') if",
"test(tmp_path): if utils.platform != 'linux': pytest.skip('the test is only relevant",
"'project' dockcross_only_project.generate(project_dir) actual_wheels = utils.cibuildwheel_run(project_dir, add_env={ 'CIBW_MANYLINUX_X86_64_IMAGE': 'dockcross/manylinux2010-x64', 'CIBW_MANYLINUX_I686_IMAGE': 'dockcross/manylinux2010-x86',",
"the correct docker image as specified in the # environment",
"add_env={ 'CIBW_MANYLINUX_X86_64_IMAGE': 'dockcross/manylinux2010-x64', 'CIBW_MANYLINUX_I686_IMAGE': 'dockcross/manylinux2010-x86', 'CIBW_SKIP': 'pp* cp39-*', }) #",
"not in w and '-cp39-' not in w] assert set(actual_wheels)",
"tmp_path / 'project' dockcross_only_project.generate(project_dir) actual_wheels = utils.cibuildwheel_run(project_dir, add_env={ 'CIBW_MANYLINUX_X86_64_IMAGE': 'dockcross/manylinux2010-x64',",
"dockcross_only_project.generate(project_dir) actual_wheels = utils.cibuildwheel_run(project_dir, add_env={ 'CIBW_MANYLINUX_X86_64_IMAGE': 'dockcross/manylinux2010-x64', 'CIBW_MANYLINUX_I686_IMAGE': 'dockcross/manylinux2010-x86', 'CIBW_SKIP':",
"platform import textwrap import pytest from . import test_projects, utils",
"os.path.exists(\"/dockcross\"): raise Exception( \"/dockcross directory not found. Is this test",
"project_dir = tmp_path / 'project' dockcross_only_project.generate(project_dir) actual_wheels = utils.cibuildwheel_run(project_dir, add_env={",
"for w in utils.expected_wheels('spam', '0.1.0') if '-pp' not in w",
"image as specified in the # environment options CIBW_MANYLINUX1_*_IMAGE if",
") ''') ) def test(tmp_path): if utils.platform != 'linux': pytest.skip('the",
"<reponame>bauerj/cibuildwheel import platform import textwrap import pytest from . import",
"right wheels built expected_wheels = [w for w in utils.expected_wheels('spam',",
"pytest from . import test_projects, utils dockcross_only_project = test_projects.new_c_project( setup_py_add=textwrap.dedent(r'''",
"test_projects.new_c_project( setup_py_add=textwrap.dedent(r''' import os, sys # check that we're running",
"test is only relevant to the linux build') if platform.machine()",
"Is this test running in the correct docker image?\" )",
"if \"linux\" in sys.platform and not os.path.exists(\"/dockcross\"): raise Exception( \"/dockcross",
"not os.path.exists(\"/dockcross\"): raise Exception( \"/dockcross directory not found. Is this",
"images') project_dir = tmp_path / 'project' dockcross_only_project.generate(project_dir) actual_wheels = utils.cibuildwheel_run(project_dir,",
"currently only possible on x86_64/i686 due to availability of alternative",
"correct docker image as specified in the # environment options",
"in the correct docker image as specified in the #",
"utils.cibuildwheel_run(project_dir, add_env={ 'CIBW_MANYLINUX_X86_64_IMAGE': 'dockcross/manylinux2010-x64', 'CIBW_MANYLINUX_I686_IMAGE': 'dockcross/manylinux2010-x86', 'CIBW_SKIP': 'pp* cp39-*', })",
"also check that we got the right wheels built expected_wheels",
"import platform import textwrap import pytest from . import test_projects,",
"environment options CIBW_MANYLINUX1_*_IMAGE if \"linux\" in sys.platform and not os.path.exists(\"/dockcross\"):",
"check that we got the right wheels built expected_wheels =",
"'CIBW_MANYLINUX_X86_64_IMAGE': 'dockcross/manylinux2010-x64', 'CIBW_MANYLINUX_I686_IMAGE': 'dockcross/manylinux2010-x86', 'CIBW_SKIP': 'pp* cp39-*', }) # also",
"'pp* cp39-*', }) # also check that we got the",
"sys # check that we're running in the correct docker",
"import pytest from . import test_projects, utils dockcross_only_project = test_projects.new_c_project(",
"import os, sys # check that we're running in the",
"this test running in the correct docker image?\" ) ''')",
"running in the correct docker image as specified in the",
"platform.machine() not in ['x86_64', 'i686']: pytest.skip('this test is currently only",
"\"/dockcross directory not found. Is this test running in the",
"on x86_64/i686 due to availability of alternative images') project_dir =",
"'0.1.0') if '-pp' not in w and '-cp39-' not in",
"found. Is this test running in the correct docker image?\"",
"the # environment options CIBW_MANYLINUX1_*_IMAGE if \"linux\" in sys.platform and",
"\"linux\" in sys.platform and not os.path.exists(\"/dockcross\"): raise Exception( \"/dockcross directory",
"utils dockcross_only_project = test_projects.new_c_project( setup_py_add=textwrap.dedent(r''' import os, sys # check",
"is currently only possible on x86_64/i686 due to availability of",
"expected_wheels = [w for w in utils.expected_wheels('spam', '0.1.0') if '-pp'",
"import test_projects, utils dockcross_only_project = test_projects.new_c_project( setup_py_add=textwrap.dedent(r''' import os, sys",
"relevant to the linux build') if platform.machine() not in ['x86_64',",
"alternative images') project_dir = tmp_path / 'project' dockcross_only_project.generate(project_dir) actual_wheels =",
"from . import test_projects, utils dockcross_only_project = test_projects.new_c_project( setup_py_add=textwrap.dedent(r''' import",
"to availability of alternative images') project_dir = tmp_path / 'project'",
"import textwrap import pytest from . import test_projects, utils dockcross_only_project",
"we're running in the correct docker image as specified in",
"in sys.platform and not os.path.exists(\"/dockcross\"): raise Exception( \"/dockcross directory not",
"check that we're running in the correct docker image as",
"of alternative images') project_dir = tmp_path / 'project' dockcross_only_project.generate(project_dir) actual_wheels",
"running in the correct docker image?\" ) ''') ) def",
"'dockcross/manylinux2010-x64', 'CIBW_MANYLINUX_I686_IMAGE': 'dockcross/manylinux2010-x86', 'CIBW_SKIP': 'pp* cp39-*', }) # also check",
"actual_wheels = utils.cibuildwheel_run(project_dir, add_env={ 'CIBW_MANYLINUX_X86_64_IMAGE': 'dockcross/manylinux2010-x64', 'CIBW_MANYLINUX_I686_IMAGE': 'dockcross/manylinux2010-x86', 'CIBW_SKIP': 'pp*",
"= utils.cibuildwheel_run(project_dir, add_env={ 'CIBW_MANYLINUX_X86_64_IMAGE': 'dockcross/manylinux2010-x64', 'CIBW_MANYLINUX_I686_IMAGE': 'dockcross/manylinux2010-x86', 'CIBW_SKIP': 'pp* cp39-*',",
"only relevant to the linux build') if platform.machine() not in",
"that we got the right wheels built expected_wheels = [w",
"w in utils.expected_wheels('spam', '0.1.0') if '-pp' not in w and",
"w and '-cp39-' not in w] assert set(actual_wheels) == set(expected_wheels)",
"utils.expected_wheels('spam', '0.1.0') if '-pp' not in w and '-cp39-' not",
"in ['x86_64', 'i686']: pytest.skip('this test is currently only possible on",
"'linux': pytest.skip('the test is only relevant to the linux build')",
"['x86_64', 'i686']: pytest.skip('this test is currently only possible on x86_64/i686",
"= tmp_path / 'project' dockcross_only_project.generate(project_dir) actual_wheels = utils.cibuildwheel_run(project_dir, add_env={ 'CIBW_MANYLINUX_X86_64_IMAGE':",
"textwrap import pytest from . import test_projects, utils dockcross_only_project =",
"test running in the correct docker image?\" ) ''') )",
"is only relevant to the linux build') if platform.machine() not",
"'i686']: pytest.skip('this test is currently only possible on x86_64/i686 due",
"we got the right wheels built expected_wheels = [w for",
"and not os.path.exists(\"/dockcross\"): raise Exception( \"/dockcross directory not found. Is",
"'CIBW_SKIP': 'pp* cp39-*', }) # also check that we got",
"image?\" ) ''') ) def test(tmp_path): if utils.platform != 'linux':",
"sys.platform and not os.path.exists(\"/dockcross\"): raise Exception( \"/dockcross directory not found.",
"correct docker image?\" ) ''') ) def test(tmp_path): if utils.platform",
"possible on x86_64/i686 due to availability of alternative images') project_dir",
"test is currently only possible on x86_64/i686 due to availability",
"[w for w in utils.expected_wheels('spam', '0.1.0') if '-pp' not in",
"pytest.skip('this test is currently only possible on x86_64/i686 due to",
") def test(tmp_path): if utils.platform != 'linux': pytest.skip('the test is",
"only possible on x86_64/i686 due to availability of alternative images')",
"os, sys # check that we're running in the correct",
"# environment options CIBW_MANYLINUX1_*_IMAGE if \"linux\" in sys.platform and not",
"# check that we're running in the correct docker image",
"the right wheels built expected_wheels = [w for w in",
"to the linux build') if platform.machine() not in ['x86_64', 'i686']:",
"availability of alternative images') project_dir = tmp_path / 'project' dockcross_only_project.generate(project_dir)",
"test_projects, utils dockcross_only_project = test_projects.new_c_project( setup_py_add=textwrap.dedent(r''' import os, sys #",
"directory not found. Is this test running in the correct",
"docker image as specified in the # environment options CIBW_MANYLINUX1_*_IMAGE",
". import test_projects, utils dockcross_only_project = test_projects.new_c_project( setup_py_add=textwrap.dedent(r''' import os,",
"}) # also check that we got the right wheels",
"dockcross_only_project = test_projects.new_c_project( setup_py_add=textwrap.dedent(r''' import os, sys # check that",
"that we're running in the correct docker image as specified",
"as specified in the # environment options CIBW_MANYLINUX1_*_IMAGE if \"linux\"",
"in utils.expected_wheels('spam', '0.1.0') if '-pp' not in w and '-cp39-'",
"def test(tmp_path): if utils.platform != 'linux': pytest.skip('the test is only",
"got the right wheels built expected_wheels = [w for w",
"CIBW_MANYLINUX1_*_IMAGE if \"linux\" in sys.platform and not os.path.exists(\"/dockcross\"): raise Exception(",
"in the correct docker image?\" ) ''') ) def test(tmp_path):",
"if '-pp' not in w and '-cp39-' not in w]",
"if platform.machine() not in ['x86_64', 'i686']: pytest.skip('this test is currently",
"build') if platform.machine() not in ['x86_64', 'i686']: pytest.skip('this test is",
"wheels built expected_wheels = [w for w in utils.expected_wheels('spam', '0.1.0')",
"built expected_wheels = [w for w in utils.expected_wheels('spam', '0.1.0') if",
"Exception( \"/dockcross directory not found. Is this test running in",
"cp39-*', }) # also check that we got the right",
"not found. Is this test running in the correct docker",
"'-pp' not in w and '-cp39-' not in w] assert",
"''') ) def test(tmp_path): if utils.platform != 'linux': pytest.skip('the test",
"'CIBW_MANYLINUX_I686_IMAGE': 'dockcross/manylinux2010-x86', 'CIBW_SKIP': 'pp* cp39-*', }) # also check that",
"docker image?\" ) ''') ) def test(tmp_path): if utils.platform !=",
"= test_projects.new_c_project( setup_py_add=textwrap.dedent(r''' import os, sys # check that we're",
"if utils.platform != 'linux': pytest.skip('the test is only relevant to",
"the linux build') if platform.machine() not in ['x86_64', 'i686']: pytest.skip('this",
"in the # environment options CIBW_MANYLINUX1_*_IMAGE if \"linux\" in sys.platform",
"due to availability of alternative images') project_dir = tmp_path /",
"raise Exception( \"/dockcross directory not found. Is this test running"
] |
[
"returned json str\") print(e) if ret is None or ret[\"success\"]",
"be checked self.last_checked_transaction_id = last_transaction_id_in_this_frame print(\"last_checked_transaction_id = \", self.last_checked_transaction_id) print(\"self.exist_close_order_info_list\",",
"= cur_created_at continue # this position cannot be grouped. make",
"is_position_transaction: # check close orders # 漏れがあるとまずい(cancelしなくなる)ので、とりあえずあるだけリンクしておく position_id_to_sellids[transaction_id] = []",
"None decide_make_ret = self.price_decide_algorithm.decide_make_position_order(chart) if len(decide_make_ret) == 3: (position_type, target_value,",
"self._cancel_order(exist_order_info[\"id\"]) self.exist_order_info_list = None return False # round to possible",
"False # check minimum btc min_qty = self.api.order.min_create_amount(self.pair) if possible_qty",
"position & order status def update_status(self, valid_position_info, valid_transaction_info, valid_order_info): #",
"= True if position_type == \"long\": is_close_long = True if",
"created_time if is_position_transaction: # check close orders # 漏れがあるとまずい(cancelしなくなる)ので、とりあえずあるだけリンクしておく position_id_to_sellids[transaction_id]",
"# レバレッジ用 if not self.use_leverage: return \"\"\" position example (array",
"update_new_orders(self, chart, do_not_create_new_order=False): assert (self.price_decide_algorithm is not None) position_type =",
"\"sell\" if abs(float(rate)-float(target_value)) < 0.00001 and \\ abs(float(amount)-float(sell_qty)) < 0.00001",
"if failed_to_cancel: return False return True # target_value: sashine value.",
"position_id_to_sellids[pos_id] self.positioned_price_base = positioned_value_in_base self.positioned_value_in_qty = positioned_value_in_qty self.position_id_to_sellids = position_id_to_sellids",
"is not None: for exist_order_info in self.exist_order_info_list: self._cancel_order(exist_order_info[\"id\"]) self.exist_order_info_list =",
"# round very small value if abs(positioned_value_in_qty) < self.api.order.min_create_amount(self.pair)*0.1: positioned_value_in_qty",
"cur_stoploss = exist_order_info[\"stop_loss_rate\"] if \"stop_loss_rate\" in exist_order_info else None cur_stoploss_float_or_none",
"# notice: this method should be called after update_status def",
"self.exist_close_order_info_list) if self.exist_close_order_info_list is not None: for pos_i, position in",
"if abs(float(cur_rate)-float(target_value)) < 0.00001 and \\ abs(float(cur_amount)-float(possible_qty)) < 0.00001 and",
"print(ret_str) except Exception as e: print(\"failed to print returned error",
"that is self.order_id: new_order = position[\"new_order\"] if new_order[\"status\"] == \"cancel\":",
"= position_id_to_sellids self.positions = valid_positions print(\"position_count=%d, positioned_%s=%f, positioned_%s=%f\" % (len(self.positions),",
"== \"leverage_buy\": order_type = \"long\" if exist_order_info[\"order_type\"] == \"sell\" or",
"== \"buy\": position_type = \"long\" if position_type == \"sell\": position_type",
"None if stop_loss_rate is not None: target_stoploss_float_or_none = float(stop_loss_rate) cur_amount",
"ret[\"success\"] is not True or \"id\" not in ret: print(\"Failed",
"+= float(o[\"pending_amount\"]) * float(o[\"rate\"]) # returns: (is_success, is_new_order_created) def _update_or_create_order(self,",
"if abs((cur_created_at - prev_created_at).total_seconds()) <= self.timelimit_to_grouping_transaction: # can group prev_created_at",
"as e: print(\"failed to print returned error json\") print(e) if",
"is not ignored\") #continue new_order_id = new_order[\"id\"] if new_order_id in",
"to algorithm # notice: this method should be called after",
"amount possible_make_total_price_base_cur = self.get_max_total_position_price_of_base_currency() - self.positioned_price_base possible_make_total_price_base_cur = min(possible_make_total_price_base_cur, self.max_free_margin_of_base_currency)",
"parse positions #### self.positions = [] self.position_id_to_sellids = {} all_positions",
"self.positioned_value_in_qty = positioned_value_in_qty self.position_id_to_sellids = position_id_to_sellids self.positions = valid_positions print(\"position_count=%d,",
"def _cancel_order(self, order_id): # call apis for current orders if",
"contracted and remain is canceled. this position is not ignored\")",
"state\" % (exist_order_info[\"id\"],)) failed_to_cancel = True del self.exist_order_info_list[exist_order_i] else: exist_order_i",
"order_id): # call apis for current orders if order_id is",
"amount else: position[\"amount\"] = remain_qty remain_qty = 0 valid_positions.append(position) total_base",
"new positions according to algorithm # notice: this method should",
"ret str\") try: print(ret_str) except Exception as e: print(\"failed to",
"position[\"status\"] if status != \"open\": continue pair = position[\"pair\"] if",
"= valid_transaction_info positioned_value_in_qty = self.positioned_value_in_qty qty_cur = self.get_qty_currency() base_cur =",
"== 0: self.exist_order_info_list = None if failed_to_cancel: return False return",
"CoinCheck self.use_leverage = use_leverage self.timelimit_to_grouping_transaction = 2 # 約定時刻がこの秒数以下なら同一ポジションとみなす(use_leverage ==",
"= position[\"created_at_datetime\"] target_value = None if self.price_decide_algorithm.market_sell_decide_algorithm(chart, open_rate, created_time, current_time_timezone_aware)",
"# this \"stop_loss_rate\" means: if a value >= stop_loss_rate, sashine",
"is_close_long: print(\"normal order cannot make short position!\") print(\"you passed close",
"exist_order_info[\"stop_loss_rate\"] if \"stop_loss_rate\" in exist_order_info else None cur_stoploss_float_or_none = None",
"= {} for position in valid_positions: pos_id = position[\"id\"] self.position_id_to_sellids[pos_id]",
"== is_cur_close_long: # completely same!! print(\"requested close order is already",
"to parse cancel order ret str\") try: print(ret_str) except Exception",
"order close pass else: target_value = self.price_decide_algorithm.sell_price_decide_algorithm(open_rate) target_value = adjust_price_to_tick(target_value,",
"= %f, you requested = %f\" % (qty_cur, min_qty, sell_qty,))",
"* possible_make_total_price_base_cur / target_value possible_amount = adjust_amount_to_tick(possible_amount,amount_tick) print(\"possible_create_in_base = %f,",
"requested = %f\" % (min_qty, possible_qty,)) return False, False #",
"self.position_id_to_sellids: return False sell_qty = float(position[\"amount\"]) sell_ids = self.position_id_to_sellids[position_id] position_type",
"= None if stop_loss_rate is not None: target_stoploss_float_or_none = float(stop_loss_rate)",
"created by the new_order that is self.order_id: new_order_id = int(transaction[\"order_id\"])",
"status def update_status(self, valid_position_info, valid_transaction_info, valid_order_info): # update position/order status",
"is self.order_id: new_order_id = int(transaction[\"order_id\"]) transaction[\"order_id\"] = new_order_id is_position_transaction =",
"= \", self.last_checked_transaction_id) print(\"self.exist_close_order_info_list\", self.exist_close_order_info_list) if self.exist_close_order_info_list is not None:",
"# if o[\"order_type\"] == \"buy\": # self.other_reserved_base += float(o[\"pending_amount\"]) *",
"0 while exist_order_i < len(self.exist_order_info_list): exist_order_info = self.exist_order_info_list[exist_order_i] if self._cancel_order(exist_order_info[\"id\"])",
"0 # total maximum position size in base currency self.positioned_price_base",
"= None decide_make_ret = self.price_decide_algorithm.decide_make_position_order(chart) if len(decide_make_ret) == 3: (position_type,",
"this class should be called after update_status def update_close_orders(self, chart,",
"__init__(self, price_decide_algorithm, api, pair=\"btc_jpy\", use_leverage = True): self.max_total_position_price_base = 0",
"ret_pos[\"open_rate\"] = total_jpy / total_amount return ret_pos concat_start_index = 0",
"\"short\" is_close_long = True if position_type == \"long\": is_close_long =",
"= 1.0 * possible_make_total_price_base_cur / target_value possible_amount = adjust_amount_to_tick(possible_amount,amount_tick) print(\"possible_create_in_base",
"in exist_order_info else None cur_stoploss_float_or_none = None if cur_stoploss is",
"= False exist_order_i = 0 while exist_order_i < len(self.exist_order_info_list): exist_order_info",
"(positioned)) def set_max_total_position_price_base(self, p): self.set_max_total_position_price_of_base_currency(p) def set_max_total_position_price_of_base_currency(self, p): self.max_total_position_price_base =",
"result\") try: print(ret_str) except Exception as e: print(\"failed to print",
"\"id\": 202835, \"order_type\": \"buy\", \"rate\": 26890, \"pair\": \"btc_jpy\", \"pending_amount\": \"0.5527\",",
"float(o[\"rate\"]) # returns: (is_success, is_new_order_created) def _update_or_create_order(self, position_type, target_value, possible_qty,",
"def _remain_non_closed_transactions(self, target_transactions, positioned_value_in_qty): valid_positions = [] remain_qty = positioned_value_in_qty",
"\\ list(map(lambda x:x[\"id\"], filter(lambda x:x[\"status\"] != \"cancel\", position[\"close_orders\"]))) self.positioned_price_base =",
"= self.api.order.tick_amount(self.pair) possible_amount = 1.0 * possible_make_total_price_base_cur / target_value possible_amount",
"= { 'amount': '%.8f' % BitcoinUtil.roundBTCby1satoshi(sell_qty), 'position_id': position_id, 'order_type': 'close_long'",
"position[\"id\"] position_id_to_sellids[transaction_id] = list(map(lambda x:x[\"id\"], self.exist_close_order_info_list)) position[\"close_orders\"] = self.exist_close_order_info_list for",
"stop_loss_rate ret_str = self.api.order.create(order) ret = None if ret_str is",
"self.timelimit_to_grouping_transaction = 2 # 約定時刻がこの秒数以下なら同一ポジションとみなす(use_leverage == False の場合のみ) self.__pair =",
"not ignored\") #continue new_order_id = new_order[\"id\"] if new_order_id in self.got_all_order_ids:",
"algorithm says this instance should not make order. cancel all",
"%f, others = %f\" % (self.get_max_total_position_price_of_base_currency(), self.positioned_price_base, self.other_reserved_base,)) #print(\"target_value =",
"= remain_qty remain_qty = 0 valid_positions.append(position) total_base += position[\"amount\"] *",
"possible_amount)) return False if not do_not_create_new_order: success, new_order_created = self._update_or_create_order(position_type,",
"same order. do nothing print(\"You already ordered this order: rate=%.1f,",
"order in enumerate(valid_order_info): order_id = order[\"id\"] order_pair = order[\"pair\"] is_added",
"str(target_value), str(amount), str(is_cur_close_long),)) return True min_qty = self.api.order.min_create_amount(self.pair) if sell_qty",
"returns: (is_success, is_new_order_created) def _update_or_create_order(self, position_type, target_value, possible_qty, stop_loss_rate =",
"amount: amount = all_amount position[\"amount\"] = position[\"all_amount\"] = amount self.positions.append(position)",
"{} if self.use_leverage: order = { 'amount': '%.8f' % BitcoinUtil.roundBTCby1satoshi(sell_qty),",
"= valid_positions print(\"position_count=%d, positioned_%s=%f, positioned_%s=%f\" % (len(self.positions), base_cur, self.positioned_price_base, qty_cur,",
"self.exist_close_order_info_list for i, order in enumerate(position[\"close_orders\"]): order[\"status\"] = \"open\" order[\"side\"]",
"[ { \"id\": 10, \"pair\": \"btc_jpy\", \"status\": \"open\", \"created_at\": \"2015-12-02T05:27:53.000Z\",",
"transaction_id means position_id transaction[\"id\"] = transaction_id # check only new",
"\"long\" order_type = 'leverage_buy' if is_long else 'leverage_sell' if not",
"and all_amount < amount: amount = all_amount position[\"amount\"] = position[\"all_amount\"]",
"cur_stoploss_float_or_none = float(cur_stoploss) target_stoploss_float_or_none = None if stop_loss_rate is not",
"= self.price_decide_algorithm.sell_price_decide_algorithm(open_rate) target_value = adjust_price_to_tick(target_value, self.api.order.tick_price(self.pair)) self._update_or_create_close_order(position, target_value) # interface",
"\"orders\": [ { \"id\": 202835, \"order_type\": \"buy\", \"rate\": 26890, \"pair\":",
"desced_position_array: total_amount += p[\"amount\"] total_jpy += p[\"amount\"] * p[\"open_rate\"] ret_pos[\"amount\"]",
"position[\"id\"] # check position that is created by the new_order",
"not None and all_amount < amount: amount = all_amount position[\"amount\"]",
"qty_amount = float(transaction[\"funds\"][qty_cur]) transaction[\"amount\"] = transaction[\"amount\"] = qty_amount transaction[\"open_rate\"] =",
"sashine value. if None, market-make def _update_or_create_close_order(self, position, target_value): position_id",
"(qty_cur, min_qty, sell_qty,)) return False # cancel all for sell_id",
"% possible_qty, 'order_type': order_type, 'pair': self.pair } # not correct",
"float(transaction[\"rate\"]) open_rate = float(transaction[\"open_rate\"]) positioned_value_in_qty += float(qty_amount) created_time = dateutil.parser.parse(transaction[\"created_at\"])",
"is already ordered on server:\") print(\" position id:%s, target_value:%s, amount:%s,",
"def adjust_price_to_tick(price, tick): return price - math.fmod(price, tick) def adjust_amount_to_tick(amount,",
"api # api: e.g. instance of CoinCheck self.use_leverage = use_leverage",
"do_not_create_new_order=False): assert (self.price_decide_algorithm is not None) position_type = None target_value",
"'pair': self.pair, } if target_value is None: # market_sell order['order_type']",
"= cur_created_at # remain positioned not be grouped grouped_positions.append(grouping(positions[concat_start_index:])) return",
"print(\"valid_close_order count = %d\" % len(valid_close_orders)) if len(valid_close_orders) == 1",
"p def get_max_total_position_price_base(self): return self.get_max_total_position_price_of_base_currency() def get_max_total_position_price_of_base_currency(self): return self.max_total_position_price_base def",
"instance of CoinCheck self.use_leverage = use_leverage self.timelimit_to_grouping_transaction = 2 #",
"placed at \"rate\" if stop_loss_rate is not None: order[\"stop_loss_rate\"] =",
"= True exist_close_orders.append(order) if not is_added: other_orders.append(order) print(\"exist_create_orders\", exist_orders) print(\"exist_close_orders\",",
"= %f, possible_base = %f\" % (target_value, possible_make_total_price_base_cur,)) if possible_amount",
"len(self.got_all_order_ids) > 500: self.got_all_order_ids = self.got_all_order_ids[-500:] print(\"order success!\", ret_str) return",
"def _group_near_transactions(self, target_transactions): grouped_positions = [] positions = target_transactions if",
"get current stoploss cur_stoploss = exist_order_info[\"stop_loss_rate\"] if \"stop_loss_rate\" in exist_order_info",
"as e: print(\"failed to print error\") print(e) if ret is",
"\"%.8f\" % target_value, 'amount': \"%.8f\" % possible_qty, 'order_type': order_type, 'pair':",
"(is_success, is_new_order_created) def _update_or_create_order(self, position_type, target_value, possible_qty, stop_loss_rate = None):",
"\"buy\": position_type = \"long\" if position_type == \"sell\": position_type =",
"tick): return price - math.fmod(price, tick) def adjust_amount_to_tick(amount, tick): return",
"= \"open\" order[\"side\"] = order[\"order_type\"] if \"amount\" not in order:",
"#print(grouped_positions[-1]) concat_start_index = idx prev_created_at = cur_created_at # remain positioned",
"remain_qty -= amount else: position[\"amount\"] = remain_qty remain_qty = 0",
"# coding: utf-8 import math import dateutil import dateutil.parser import",
"exist_order_info in self.exist_order_info_list: self._cancel_order(exist_order_info[\"id\"]) self.exist_order_info_list = None return False #",
"should not make order. cancel all if self.exist_order_info_list is not",
"not None: if abs(float(cur_rate)-float(target_value)) < 0.00001 and \\ abs(float(cur_amount)-float(possible_qty)) <",
"= None target_value = None stoploss_rate = None decide_make_ret =",
"very old orders if len(self.got_all_order_ids) > 500: self.got_all_order_ids = self.got_all_order_ids[-500:]",
"# check close orders # 漏れがあるとまずい(cancelしなくなる)ので、とりあえずあるだけリンクしておく position_id_to_sellids[transaction_id] = [] transaction[\"close_orders\"]",
"order['rate'] = target_value ret = self.api.order.create(order) ret_str = ret if",
"is not None: # check the same value or not",
"close order is always \"sell\" if not is_close_long: print(\"normal order",
"for current orders if order_id is None: print(\"order is already",
"already ordered on server:\") print(\" position id:%s, target_value:%s, amount:%s, close_long:%s\"",
"if not do_not_create_new_order: success, new_order_created = self._update_or_create_order(position_type, target_value, possible_amount, stop_loss_rate=stoploss_rate)",
"order but DO_NOT_CREATE_NEW flag = true\") return False # update",
"cannot use orders that exceed this margin self.positions = []",
"this order: rate=%.1f, amount=%f, stoploss_rate=%s, position_type=%s\" % (target_value, possible_qty, str(stop_loss_rate),",
"def get_max_total_position_price_of_base_currency(self): return self.max_total_position_price_base def get_positioned_price_base(self): return self.positioned_price_base def set_timelimit_to_grouping_transaction(self,",
"qty_cur not in transaction[\"funds\"] or base_cur not in transaction[\"funds\"]: continue",
"#print(\"target_value = %f, possible_base = %f\" % (target_value, possible_make_total_price_base_cur,)) if",
"valid_position_info): # apply real positions status to this instance #",
"order order = {} if self.use_leverage: order = { 'amount':",
"0 # max free margin. we cannot use orders that",
"self.positioned_price_base, possible_make_total_price_base_cur, possible_amount)) #print(\"base_cur = %f, positioned = %f, others",
"self.position_id_to_sellids[position_id] = \\ list(map(lambda x:x[\"id\"], filter(lambda x:x[\"status\"] != \"cancel\", position[\"close_orders\"])))",
"return self.max_total_position_price_base def get_positioned_price_base(self): return self.positioned_price_base def set_timelimit_to_grouping_transaction(self, timelimit_to_grouping_transaction): self.timelimit_to_grouping_transaction",
"#### self.positions = [] self.position_id_to_sellids = {} all_positions = valid_position_info",
"in enumerate(positions): transaction_id = position[\"id\"] position_id_to_sellids[transaction_id] = list(map(lambda x:x[\"id\"], self.exist_close_order_info_list))",
"e: print(\"failed to print error\") print(e) return False sell_ids =",
"position_id_to_sellids self.position_id_to_sellids = {} for position in valid_positions: pos_id =",
"positioned = %f, others = %f\" % (self.get_max_total_position_price_of_base_currency(), self.positioned_price_base, self.other_reserved_base,))",
"target_stoploss_float_or_none = float(stop_loss_rate) cur_amount = None if \"amount\" in exist_order_info:",
"not None: cur_stoploss_float_or_none = float(cur_stoploss) target_stoploss_float_or_none = None if stop_loss_rate",
"\"stop_loss_rate\": null, \"pair\": \"btc_jpy\", \"created_at\": \"2015-01-10T05:55:38.000Z\" \"\"\" is_long = position_type",
"to create a new order but DO_NOT_CREATE_NEW flag = true\")",
"reserved_margin + (positioned)) def set_max_total_position_price_base(self, p): self.set_max_total_position_price_of_base_currency(p) def set_max_total_position_price_of_base_currency(self, p):",
"= None return False # round to possible price tick",
"canceled. this position is not ignored\") #continue new_order_id = new_order[\"id\"]",
">= amount: remain_qty -= amount else: position[\"amount\"] = remain_qty remain_qty",
"make new order order = {} if self.use_leverage: order =",
"ret is not None: try: ret = json.loads(ret) except: print(\"failed",
"self.price_decide_algorithm = price_decide_algorithm print(\"PositionTrader: inst=\" + str(self) + \", pair=\"",
"cur_rate is not None and cur_amount is not None and",
"False # update close orders according to current positions #",
"created by this class's order created_time = dateutil.parser.parse(position[\"created_at\"]) position[\"created_at_datetime\"] =",
"transaction_id > self.last_checked_transaction_id will be checked self.last_checked_transaction_id = last_transaction_id_in_this_frame print(\"last_checked_transaction_id",
"\"rate\": 26990, \"pair\": \"btc_jpy\", \"pending_amount\": \"0.77\", \"pending_market_buy_amount\": null, \"stop_loss_rate\": null,",
"cancel all if self.exist_order_info_list is not None: for exist_order_info in",
"def grouping(desced_position_array): ret_pos = dict(desced_position_array[0]) total_amount = 0 total_jpy =",
">= stop_loss_rate, sashine will be placed at \"rate\" if stop_loss_rate",
"open_rate = position[\"open_rate\"] positioned_value_in_base += float(amount) * float(open_rate) # check",
"(position_type, target_value, stoploss_rate) = decide_make_ret else: (position_type, target_value) = decide_make_ret",
"False sell_ids = [ret[\"id\"]] self.position_id_to_sellids[position_id] = sell_ids self.got_close_order_ids.append(ret[\"id\"]) if len(self.got_close_order_ids)",
"= created_time amount = position[\"amount\"] all_amount = position[\"all_amount\"] if all_amount",
"= None if ret_str is not None: try: ret =",
"if not leverage order, close order is always \"sell\" if",
"near created_at transactions grouped_positions = self._group_near_transactions(positions) # remove closed position",
"abs(float(amount)-float(sell_qty)) < 0.00001 and \\ is_close_long == is_cur_close_long: # completely",
"else: # if not leverage order, close order is always",
"position[\"created_at_datetime\"] target_value = None if self.price_decide_algorithm.market_sell_decide_algorithm(chart, open_rate, created_time, current_time_timezone_aware) is",
"self.got_close_order_ids.append(ret[\"id\"]) if len(self.got_close_order_ids) > 500: self.got_close_order_ids = self.got_close_order_ids[-500:] return True",
"a class for one position class OnePositionTrader(object): def __init__(self, price_decide_algorithm,",
"valid_positions: pos_id = position[\"id\"] self.position_id_to_sellids[pos_id] = position_id_to_sellids[pos_id] self.positioned_price_base = positioned_value_in_base",
"{} all_positions = valid_position_info positioned_value_in_base = 0 for position in",
"# not correct # this \"stop_loss_rate\" means: if a value",
"self.got_all_order_ids is_close_transaction = new_order_id in self.got_close_order_ids if not is_position_transaction and",
"\"2015-01-10T05:55:38.000Z\" }, { \"id\": 38632107, \"order_type\": \"buy\", \"rate\": null, \"pair\":",
"\"\"\" position example (array of \"data\" will be passed) {",
"str\") print(e) if ret is None or ret[\"success\"] is not",
"used only for genbutsu self.max_free_margin_of_base_currency = 0 # max free",
"in exist_order_info else None # get current stoploss cur_stoploss =",
"for genbutsu self.max_free_margin_of_base_currency = 0 # max free margin. we",
"0 # merge position_id_to_sellids self.position_id_to_sellids = {} for position in",
"be placed at \"rate\" if stop_loss_rate is not None: order[\"stop_loss_rate\"]",
"1 and target_value is not None: # check the order",
"{ \"id\": 23104033, \"side\": \"sell\", \"rate\": null, \"amount\": null, \"pending_amount\":",
"class should be called after update_status def update_close_orders(self, chart, current_time_timezone_aware):",
"for one position class OnePositionTrader(object): def __init__(self, price_decide_algorithm, api, pair=\"btc_jpy\",",
"is_cur_close_long = False if \"side\" in valid_close_order: is_cur_close_long = valid_close_order[\"side\"]",
"\"2015-12-02T05:27:53.000Z\", \"closed_at\": null, \"open_rate\": \"43553.0\", \"closed_rate\": null, \"amount\": \"1.51347797\", \"all_amount\":",
"False exist_order_i = 0 while exist_order_i < len(self.exist_order_info_list): exist_order_info =",
"# in next frame, only transaction_id > self.last_checked_transaction_id will be",
"close したかどうか、残っているポジション残量を計算するのに、全て遡らないといけないのは現実的ではない # 既にこの段階で解決できるポジション状態(close order id見て、それがあれば反対売買が成立している) # を用い、↑で貯めたpositionsから、反対売買済みのものを(amount基準で)消していき(前回フレームで残っていたpositionも含めて)、残ったpositionだけを生きているポジションとし、1つに集約する(現物用なので、idが分かれている意味はない) # その残ったpositionID,",
"try: ret = json.loads(ret_str) except: print(\"failed to parse cancel order",
"None if failed_to_cancel: return False return True # target_value: sashine",
"too few btc print(\"want to make (price,amount) = (%f,%f) but",
"position in target_transactions: if remain_qty <= 0: break amount =",
"close_transactions.append(transaction) # in next frame, only transaction_id > self.last_checked_transaction_id will",
"is not None: target_stoploss_float_or_none = float(stop_loss_rate) cur_amount = None if",
"\"rate\": \"30010.0\", \"amount\": \"1.3\", \"order_type\": \"sell\", \"stop_loss_rate\": null, \"pair\": \"btc_jpy\",",
"self.positioned_price_base, qty_cur, self.positioned_value_in_qty,)) # close したかどうか、残っているポジション残量を計算するのに、全て遡らないといけないのは現実的ではない # 既にこの段階で解決できるポジション状態(close order id見て、それがあれば反対売買が成立している)",
"\"btc_jpy\", \"pending_amount\": \"0.77\", \"pending_market_buy_amount\": null, \"stop_loss_rate\": null, \"created_at\": \"2015-01-10T05:55:38.000Z\" },",
"order %s: %s\" % (str(order_id), str(ret_str),)) return False return True",
"in valid_close_order: is_cur_close_long = valid_close_order[\"order_type\"] == \"sell\" if abs(float(rate)-float(target_value)) <",
"and \\ is_close_long == is_cur_close_long: # completely same!! print(\"requested close",
"valid_order_info): # update position/order status (assume: pagenations are already cleared)",
"abs(float(rate)-float(target_value)) < 0.00001 and \\ abs(float(amount)-float(sell_qty)) < 0.00001 and \\",
"order is already ordered on server:\") print(\" position id:%s, target_value:%s,",
"exist_orders.append(order) elif order_id in self.got_close_order_ids: is_added = True exist_close_orders.append(order) if",
"true, \"id\": 12345, \"rate\": \"30010.0\", \"amount\": \"1.3\", \"order_type\": \"sell\", \"stop_loss_rate\":",
"amount - math.fmod(amount, tick) # a class for one position",
"result\") try: print(ret_str) except Exception as e: print(\"failed to show",
"success, new_order_created = self._update_or_create_order(position_type, target_value, possible_amount, stop_loss_rate=stoploss_rate) return new_order_created else:",
"order. cancel all if self.exist_order_info_list is not None: for exist_order_info",
"\"closed_at\": null, \"open_rate\": \"43553.0\", \"closed_rate\": null, \"amount\": \"1.51347797\", \"all_amount\": \"1.51045705\",",
"transactions grouped_positions = self._group_near_transactions(positions) # remove closed position & update",
"this instance # レバレッジ用 if not self.use_leverage: return \"\"\" position",
"None: print(\"sell order canceled but failed to create new sell",
"= None self.last_checked_transaction_id = 0 self.api = api # api:",
"# make new order order = {} if self.use_leverage: order",
"return False sell_ids = [ret[\"id\"]] self.position_id_to_sellids[position_id] = sell_ids self.got_close_order_ids.append(ret[\"id\"]) if",
"grouping(desced_position_array): ret_pos = dict(desced_position_array[0]) total_amount = 0 total_jpy = 0",
"or ret[\"success\"] is not True or \"id\" not in ret:",
"# something error happened!! print(\"order cancel failed %d even if",
"500: self.got_close_order_ids = self.got_close_order_ids[-500:] return True def _cancel_order(self, order_id): #",
"\"stop_loss_rate\" in exist_order_info else None cur_stoploss_float_or_none = None if cur_stoploss",
"= 0 # total position price in base currency (actually",
"# round to possible price tick = self.api.order.tick_price(self.pair) target_value =",
"status != \"open\": continue pair = position[\"pair\"] if pair !=",
"order_type = 'buy' if is_long else 'sell' order = {",
"str(is_cur_close_long),)) return True min_qty = self.api.order.min_create_amount(self.pair) if sell_qty < min_qty:",
"dateutil.parser.parse(transaction[\"created_at\"]) transaction[\"created_at_datetime\"] = created_time if is_position_transaction: # check close orders",
"# total maximum position size in base currency self.positioned_price_base =",
"True): self.max_total_position_price_base = 0 # total maximum position size in",
"\"success\": true, \"id\": 12345, \"rate\": \"30010.0\", \"amount\": \"1.3\", \"order_type\": \"sell\",",
"ret: print(\"Failed to cancel order %s: %s\" % (str(order_id), str(ret_str),))",
"merge position_id_to_sellids self.position_id_to_sellids = {} for position in valid_positions: pos_id",
"+ str(new_order[\"id\"]) + \" state is 'cancel'. probably partially contracted",
"concat_start_index = 0 prev_created_at = positions[0][\"created_at_datetime\"] for idx, pos in",
"print(e) return False, False self.exist_order_info_list = [ret] self.got_all_order_ids.append(ret[\"id\"]) # remove",
"self.pair}) ret = None if ret_str is not None: try:",
"stop_loss_rate, sashine will be placed at \"rate\" if stop_loss_rate is",
"\"short\" if cur_rate is not None and cur_amount is not",
"close orders self.position_id_to_sellids[position_id] = \\ list(map(lambda x:x[\"id\"], filter(lambda x:x[\"status\"] !=",
"failed_to_cancel = True del self.exist_order_info_list[exist_order_i] else: exist_order_i += 1 if",
"requested = %f\" % (qty_cur, min_qty, sell_qty,)) return False #",
"_cancel_order(self, order_id): # call apis for current orders if order_id",
"stop_loss_rate = None): assert (self.api is not None) # order",
"is not None: stoploss_rate = adjust_price_to_tick(stoploss_rate, tick) # !!round to",
"print(\"requested close order is already ordered on server:\") print(\" position",
"not None and order_type is not None: if abs(float(cur_rate)-float(target_value)) <",
"{ 'amount': '%.8f' % BitcoinUtil.roundBTCby1satoshi(sell_qty), 'order_type': 'sell', 'pair': self.pair, }",
"class's order created_time = dateutil.parser.parse(position[\"created_at\"]) position[\"created_at_datetime\"] = created_time amount =",
"transaction[\"created_at_datetime\"] = created_time if is_position_transaction: # check close orders #",
"}, { \"id\": 202836, \"order_type\": \"sell\", \"rate\": 26990, \"pair\": \"btc_jpy\",",
"\"sell\": position_type = \"short\" is_close_long = True if position_type ==",
"\"cancel\", \"created_at\": \"2015-12-05T05:03:56.000Z\" } ] } ] } \"\"\" ####",
"\"pending_amount\": \"0.5527\", \"pending_market_buy_amount\": null, \"stop_loss_rate\": null, \"created_at\": \"2015-01-10T05:55:38.000Z\" }, {",
"= [ret[\"id\"]] self.position_id_to_sellids[position_id] = sell_ids self.got_close_order_ids.append(ret[\"id\"]) if len(self.got_close_order_ids) > 500:",
"update internal position & order status def update_status(self, valid_position_info, valid_transaction_info,",
"is_close_transaction: continue # other pair if qty_cur not in transaction[\"funds\"]",
"# check the order is already created on exchanger valid_close_order",
"float(position[\"open_rate\"]) amount = float(position[\"amount\"]) created_time = position[\"created_at_datetime\"] target_value = None",
"= \"market_sell\" else: order['rate'] = target_value ret = self.api.order.create(order) ret_str",
"check only new id if self.last_checked_transaction_id >= transaction_id: continue last_transaction_id_in_this_frame",
"(self.get_max_total_position_price_of_base_currency() - self.positioned_price_base, possible_make_total_price_base_cur, possible_amount)) #print(\"base_cur = %f, positioned =",
"= idx prev_created_at = cur_created_at # remain positioned not be",
"self.max_free_margin_of_base_currency = 0 # max free margin. we cannot use",
"OnePositionTrader(object): def __init__(self, price_decide_algorithm, api, pair=\"btc_jpy\", use_leverage = True): self.max_total_position_price_base",
"new_order_id is_position_transaction = new_order_id in self.got_all_order_ids is_close_transaction = new_order_id in",
"is canceled. this position is not ignored\") #continue new_order_id =",
"if possible_qty < min_qty: print(\"Minimum order btc = %f, you",
"= [ret] self.got_all_order_ids.append(ret[\"id\"]) # remove very old orders if len(self.got_all_order_ids)",
"pair=\"btc_jpy\", use_leverage = True): self.max_total_position_price_base = 0 # total maximum",
"not None: # check the order is already created on",
"open_rate, created_time, current_time_timezone_aware) is True: # market order close pass",
"not self.use_leverage: return \"\"\" position example (array of \"data\" will",
"not None) # order list は現物とleverageで変わらない if self.exist_order_info_list is not",
"\\ is_close_long == is_cur_close_long: # completely same!! print(\"requested close order",
"created by the new_order that is self.order_id: new_order = position[\"new_order\"]",
"current positions # this class should be called after update_status",
"pair=\" + str(pair)) @property def pair(self): return self.__pair def get_base_currency(self):",
"only new id if self.last_checked_transaction_id >= transaction_id: continue last_transaction_id_in_this_frame =",
"= self.api.order.tick_price(self.pair) target_value = adjust_price_to_tick(target_value, tick) if stoploss_rate is not",
"約定時刻がこの秒数以下なら同一ポジションとみなす(use_leverage == False の場合のみ) self.__pair = pair self.price_decide_algorithm = price_decide_algorithm",
"position_type=%s\" % (target_value, possible_qty, str(stop_loss_rate), position_type,)) return True, False #",
"not make order. cancel all if self.exist_order_info_list is not None:",
"self.positioned_value_in_qty,)) # close したかどうか、残っているポジション残量を計算するのに、全て遡らないといけないのは現実的ではない # 既にこの段階で解決できるポジション状態(close order id見て、それがあれば反対売買が成立している) # を用い、↑で貯めたpositionsから、反対売買済みのものを(amount基準で)消していき(前回フレームで残っていたpositionも含めて)、残ったpositionだけを生きているポジションとし、1つに集約する(現物用なので、idが分かれている意味はない)",
"self.exist_order_info_list[0] cur_rate = exist_order_info[\"rate\"] if \"rate\" in exist_order_info else None",
"stoploss_rate = None decide_make_ret = self.price_decide_algorithm.decide_make_position_order(chart) if len(decide_make_ret) == 3:",
"self.position_id_to_sellids[position_id] position_type = position[\"side\"] # convert position type name if",
"\"rate\": null, \"amount\": null, \"pending_amount\": \"0\", \"status\": \"complete\", \"created_at\": \"2015-12-02T05:27:52.000Z\"",
"positioned_value_in_base = 0 # merge position_id_to_sellids self.position_id_to_sellids = {} for",
"total_amount ret_pos[\"open_rate\"] = total_jpy / total_amount return ret_pos concat_start_index =",
"# this position is created by this class's order qty_amount",
"self.use_leverage: self._update_position_status(valid_position_info) else: self._update_transaction_status(valid_transaction_info) def _update_position_status(self, valid_position_info): # apply real",
"remain_qty = 0 valid_positions.append(position) total_base += position[\"amount\"] * position[\"open_rate\"] return",
"<= self.timelimit_to_grouping_transaction: # can group prev_created_at = cur_created_at continue #",
"= exist_order_info[\"rate\"] if \"rate\" in exist_order_info else None # get",
"'order_type': 'sell', 'pair': self.pair, } if target_value is None: #",
"return True, True def _cancel_exist_all_buy_orders(self): failed_to_cancel = False exist_order_i =",
"if self.exist_order_info_list is not None: for exist_order_info in self.exist_order_info_list: self._cancel_order(exist_order_info[\"id\"])",
"is None: print(\"sell order canceled but failed to create new",
"create new sell order!!: position id: %s\" % (str(position_id),)) try:",
"order: rate=%f, amount=%f\" % (target_value, sell_qty,)) print(\"valid_close_order[0]:\") print(valid_close_order) rate =",
"btc print(\"want to make (price,amount) = (%f,%f) but too few",
"is False: # something error happened!! print(\"order cancel failed %d",
"}, \"close_orders\": [ { \"id\": 23755132, \"side\": \"buy\", \"rate\": \"10000.0\",",
"# set usable jpy (available_margin + reserved_margin + (positioned)) def",
"position_type = None target_value = None stoploss_rate = None decide_make_ret",
"まだcloseされていないtransactionだけを残す def _remain_non_closed_transactions(self, target_transactions, positioned_value_in_qty): valid_positions = [] remain_qty =",
"else 'sell' order = { 'rate': \"%.8f\" % target_value, 'amount':",
"= False # check exist sell-orders. if target value and",
"'pair': 'btc_jpy', } if target_value is not None: order['rate'] =",
"null, \"pending_market_buy_amount\": \"10000.0\", \"stop_loss_rate\": \"50000.0\", \"created_at\": \"2016-02-23T12:14:50.000Z\" } ] }",
"= 0 while exist_order_i < len(self.exist_order_info_list): exist_order_info = self.exist_order_info_list[exist_order_i] if",
"float(transaction[\"open_rate\"]) positioned_value_in_qty += float(qty_amount) created_time = dateutil.parser.parse(transaction[\"created_at\"]) transaction[\"created_at_datetime\"] = created_time",
"= float(order[\"pending_amount\"]) position[\"close_orders\"][i] = order positions[pos_i] = position # round",
"= %f\" % (qty_cur, min_qty, sell_qty,)) return False # cancel",
"print returned error json\") print(e) if ret is None or",
"\"btc_jpy\", \"created_at\": \"2015-01-10T05:55:38.000Z\" \"\"\" is_long = position_type == \"long\" order_type",
"if position_type == \"long\": is_close_long = True if position_type ==",
"= True if position_type == \"short\": is_close_long = False #",
"\"long\" if position_type == \"sell\": position_type = \"short\" is_close_long =",
"not is_close_transaction: continue # other pair if qty_cur not in",
"% (target_value, possible_amount)) return False if not do_not_create_new_order: success, new_order_created",
"else None # get current stoploss cur_stoploss = exist_order_info[\"stop_loss_rate\"] if",
"paired currency) self.positioned_value_in_qty = 0 # used only for genbutsu",
"is_position_transaction = new_order_id in self.got_all_order_ids is_close_transaction = new_order_id in self.got_close_order_ids",
"possible amount = %f\" % (self.get_max_total_position_price_of_base_currency() - self.positioned_price_base, possible_make_total_price_base_cur, possible_amount))",
"if qty_cur not in transaction[\"funds\"] or base_cur not in transaction[\"funds\"]:",
"else: order['rate'] = target_value ret = self.api.order.create(order) ret_str = ret",
"position[\"amount\"] * position[\"open_rate\"] return valid_positions, total_base def _update_order_id_status(self, valid_order_info): ####",
"exist_order_info[\"amount\"] elif \"pending_amount\" in exist_order_info: cur_amount = exist_order_info[\"pending_amount\"] order_type =",
"self.pair.split(\"_\")[0].lower() # set usable jpy (available_margin + reserved_margin + (positioned))",
"be called after update_status def update_new_orders(self, chart, do_not_create_new_order=False): assert (self.price_decide_algorithm",
"and \\ order_type == position_type: # same order. do nothing",
"'pair': self.pair } # not correct # this \"stop_loss_rate\" means:",
"except: print(\"failed to parse cancel order ret str\") try: print(ret_str)",
"self.use_leverage: return \"\"\" position example (array of \"data\" will be",
"transaction[\"close_orders\"] = [] positions.append(transaction) else: close_transactions.append(transaction) # in next frame,",
"if new_order_id in self.got_all_order_ids: # this position is created by",
"valid_order_info)) exist_orders = [] exist_close_orders = [] other_orders = []",
"= self.position_id_to_sellids close_transactions = [] all_transactions = valid_transaction_info positioned_value_in_qty =",
"print(\"failed to print error\") print(e) if ret is None or",
"return False return True # target_value: sashine value. if None,",
"orders self.position_id_to_sellids[position_id] = \\ list(map(lambda x:x[\"id\"], filter(lambda x:x[\"status\"] != \"cancel\",",
"* position[\"open_rate\"] return valid_positions, total_base def _update_order_id_status(self, valid_order_info): #### #",
"= 0 valid_positions.append(position) total_base += position[\"amount\"] * position[\"open_rate\"] return valid_positions,",
"= json.loads(ret_str) except: print(\"failed to parse api.order.create result\") try: print(ret_str)",
"id: %s\" % (str(position_id),)) try: print(ret_str) except Exception as e:",
"\"buy\": # self.other_reserved_base += float(o[\"pending_amount\"]) * float(o[\"rate\"]) # returns: (is_success,",
"cur_stoploss_float_or_none = None if cur_stoploss is not None: cur_stoploss_float_or_none =",
"order in enumerate(position[\"close_orders\"]): order[\"status\"] = \"open\" order[\"side\"] = order[\"order_type\"] if",
"現物用。transactionの結果からポジションの状態を解析. 基本的にupdate_position_statusと挙動は同じ。parseするjsonが異なる # * ただし、前フレームからの情報を引き継ぐところがupdate_position_statusと違う (現物にはpositionという概念が無い) positions = self.positions position_id_to_sellids",
"return amount - math.fmod(amount, tick) # a class for one",
"return False # round to possible price tick = self.api.order.tick_price(self.pair)",
"target_stoploss_float_or_none and \\ order_type == position_type: # same order. do",
"# cancel all for sell_id in sell_ids: self._cancel_order(sell_id) self.position_id_to_sellids[position_id] =",
"%f, want to make amount in base = %f, possible",
"ただし、ずっと続けると計算誤差がたまるので、jpyもしくはbtcベースでその合計値が極めて小さくなったら丸めてノーポジ扱いにする # うーん...現物とレバレッジで管理が結構変わるから同じクラスにするのはまずかった?ごちゃごちゃしてきてしまった # 時間的に約定時刻が近いpositionをまとめる def _group_near_transactions(self, target_transactions): grouped_positions =",
"[] # make new order order = {} if self.use_leverage:",
"= order[\"order_type\"] if \"amount\" not in order: order[\"amount\"] = float(order[\"pending_amount\"])",
"return False order = { 'amount': '%.8f' % BitcoinUtil.roundBTCby1satoshi(sell_qty), 'order_type':",
"= position[\"status\"] if status != \"open\": continue pair = position[\"pair\"]",
"state is 'cancel'. probably partially contracted and remain is canceled.",
"positioned_value_in_qty) if abs(positioned_value_in_base) < self.api.order.tick_price(self.pair) * self.api.order.min_create_amount(self.pair) * 0.1: positioned_value_in_base",
"update_status def update_new_orders(self, chart, do_not_create_new_order=False): assert (self.price_decide_algorithm is not None)",
"currency (actually paired currency) self.positioned_value_in_qty = 0 # used only",
"% (self.get_max_total_position_price_of_base_currency(), self.positioned_price_base, self.other_reserved_base,)) #print(\"target_value = %f, possible_base = %f\"",
"in sell_ids: self._cancel_order(sell_id) self.position_id_to_sellids[position_id] = [] # make new order",
"else: (position_type, target_value) = decide_make_ret if target_value is None or",
"except Exception as e: print(\"failed to print error\") print(e) if",
"cur_amount = exist_order_info[\"amount\"] elif \"pending_amount\" in exist_order_info: cur_amount = exist_order_info[\"pending_amount\"]",
"pair if qty_cur not in transaction[\"funds\"] or base_cur not in",
"new order order = {} if self.use_leverage: order = {",
"possible_base = %f\" % (target_value, possible_make_total_price_base_cur,)) if possible_amount <= 0.000001:",
"amount\" % (target_value, possible_amount)) return False if not do_not_create_new_order: success,",
"json str\") print(e) if ret is None or ret[\"success\"] is",
"return price - math.fmod(price, tick) def adjust_amount_to_tick(amount, tick): return amount",
"not None) position_type = None target_value = None stoploss_rate =",
"# order by desc # concat very near created_at transactions",
"amount in base = %f, possible amount = %f\" %",
"\"pair\": \"btc_jpy\", \"pending_amount\": \"0.5527\", \"pending_market_buy_amount\": null, \"stop_loss_rate\": null, \"created_at\": \"2015-01-10T05:55:38.000Z\"",
"\"created_at\": \"2015-01-10T05:55:38.000Z\" }, { \"id\": 202836, \"order_type\": \"sell\", \"rate\": 26990,",
"order[\"status\"] = \"open\" order[\"side\"] = order[\"order_type\"] if \"amount\" not in",
"nothing print(\"You already ordered this order: rate=%.1f, amount=%f, stoploss_rate=%s, position_type=%s\"",
"= self.position_id_to_sellids[position_id] position_type = position[\"side\"] # convert position type name",
"} ] } \"\"\" #### # parse positions #### self.positions",
"return \"\"\" position example (array of \"data\" will be passed)",
"amount: remain_qty -= amount else: position[\"amount\"] = remain_qty remain_qty =",
"if is_position_transaction: # check close orders # 漏れがあるとまずい(cancelしなくなる)ので、とりあえずあるだけリンクしておく position_id_to_sellids[transaction_id] =",
"if this_pair != self.pair: continue # check position that is",
"self.pair: if order_id in self.got_all_order_ids: is_added = True exist_orders.append(order) elif",
"= self.got_all_order_ids[-500:] print(\"order success!\", ret_str) return True, True def _cancel_exist_all_buy_orders(self):",
"print(e) if ret is None or ret[\"success\"] is not True",
"= position[\"id\"] if position_id not in self.position_id_to_sellids: return False sell_qty",
"target_value = None stoploss_rate = None decide_make_ret = self.price_decide_algorithm.decide_make_position_order(chart) if",
"orders that exceed this margin self.positions = [] self.position_id_to_sellids =",
"null, \"created_at\": \"2015-01-10T05:55:38.000Z\" }, { \"id\": 202836, \"order_type\": \"sell\", \"rate\":",
"new_order[\"id\"] if new_order_id in self.got_all_order_ids: # this position is created",
"float(cur_stoploss) target_stoploss_float_or_none = None if stop_loss_rate is not None: target_stoploss_float_or_none",
"parse api.order.create result\") try: print(ret_str) except Exception as e: print(\"failed",
"return self.__pair def get_base_currency(self): return self.pair.split(\"_\")[1].lower() def get_qty_currency(self): return self.pair.split(\"_\")[0].lower()",
"qty_amount transaction[\"open_rate\"] = float(transaction[\"rate\"]) open_rate = float(transaction[\"open_rate\"]) positioned_value_in_qty += float(qty_amount)",
"None cur_stoploss_float_or_none = None if cur_stoploss is not None: cur_stoploss_float_or_none",
"order = {} if self.use_leverage: order = { 'amount': '%.8f'",
"order is already created on exchanger valid_close_order = valid_close_orders[0] print(\"your",
"\"buy\", \"rate\": null, \"pair\": \"btc_jpy\", \"pending_amount\": null, \"pending_market_buy_amount\": \"10000.0\", \"stop_loss_rate\":",
"self.pair } # not correct # this \"stop_loss_rate\" means: if",
"this position is created by this class's order qty_amount =",
"0 valid_positions.append(position) total_base += position[\"amount\"] * position[\"open_rate\"] return valid_positions, total_base",
"if is_long else 'sell' order = { 'rate': \"%.8f\" %",
"return self.pair.split(\"_\")[0].lower() # set usable jpy (available_margin + reserved_margin +",
"try: print(ret_str) except Exception as e: print(\"failed to print returned",
"%f\" % (self.get_max_total_position_price_of_base_currency() - self.positioned_price_base, possible_make_total_price_base_cur, possible_amount)) #print(\"base_cur = %f,",
"if len(decide_make_ret) == 3: (position_type, target_value, stoploss_rate) = decide_make_ret else:",
"= self.api.order.min_create_amount(self.pair) if possible_qty < min_qty: print(\"Minimum order btc =",
"min_qty = self.api.order.min_create_amount(self.pair) if sell_qty < min_qty: qty_cur = self.get_qty_currency()",
"= { 'amount': '%.8f' % BitcoinUtil.roundBTCby1satoshi(sell_qty), 'order_type': 'sell', 'pair': self.pair,",
"False, False self.exist_order_info_list = [ret] self.got_all_order_ids.append(ret[\"id\"]) # remove very old",
"== \"long\" order_type = 'leverage_buy' if is_long else 'leverage_sell' if",
"0 else None #self.other_reserved_base = 0 #if not self.use_leverage: #",
"possible_make_total_price_base_cur / target_value possible_amount = adjust_amount_to_tick(possible_amount,amount_tick) print(\"possible_create_in_base = %f, want",
"= (%f,%f) but too few amount\" % (target_value, possible_amount)) return",
"else: self._update_transaction_status(valid_transaction_info) def _update_position_status(self, valid_position_info): # apply real positions status",
"if abs(positioned_value_in_base) < self.api.order.tick_price(self.pair) * self.api.order.min_create_amount(self.pair) * 0.1: positioned_value_in_base =",
"valid_transaction_info, valid_order_info): # update position/order status (assume: pagenations are already",
"\"id\" not in ret: print(\"Failed to cancel order %s: %s\"",
"all if self.exist_order_info_list is not None: for exist_order_info in self.exist_order_info_list:",
"= positioned_value_in_qty total_base = 0 for position in target_transactions: if",
"valid_order_info): #### # parse orders #### \"\"\" orders example (array",
"x:x[\"id\"], filter(lambda x:x[\"status\"] != \"cancel\", position[\"close_orders\"]))) self.positioned_price_base = positioned_value_in_base def",
"= [] self.position_id_to_sellids = {} all_positions = valid_position_info positioned_value_in_base =",
"same, do not pass new order valid_close_orders = list(filter(lambda x:x[\"status\"]",
"(array of \"orders\" will be passed) { \"success\": true, \"orders\":",
"[] other_orders = [] for idx, order in enumerate(valid_order_info): order_id",
"can group prev_created_at = cur_created_at continue # this position cannot",
"else None self.exist_close_order_info_list = exist_close_orders if len(exist_close_orders) > 0 else",
"cur_rate = exist_order_info[\"rate\"] if \"rate\" in exist_order_info else None #",
"for transaction in all_transactions: transaction_id = int(transaction[\"id\"]) # transaction_id means",
"order status def update_status(self, valid_position_info, valid_transaction_info, valid_order_info): # update position/order",
"= [] self.position_id_to_sellids = {} self.got_all_order_ids = [] self.got_close_order_ids =",
"self.positions position_id_to_sellids = self.position_id_to_sellids close_transactions = [] all_transactions = valid_transaction_info",
"if self._cancel_order(exist_order_info[\"id\"]) is False: # something error happened!! print(\"order cancel",
"other_orders.append(order) print(\"exist_create_orders\", exist_orders) print(\"exist_close_orders\", exist_close_orders) self.exist_order_info_list = exist_orders if len(exist_orders)",
"order_id in self.got_all_order_ids: is_added = True exist_orders.append(order) elif order_id in",
"error\") print(e) return False sell_ids = [ret[\"id\"]] self.position_id_to_sellids[position_id] = sell_ids",
"sell order!!: position id: %s\" % (str(position_id),)) try: print(ret_str) except",
"self.max_total_position_price_base def get_positioned_price_base(self): return self.positioned_price_base def set_timelimit_to_grouping_transaction(self, timelimit_to_grouping_transaction): self.timelimit_to_grouping_transaction =",
"= 0 #if not self.use_leverage: # for o in other_orders:",
"#exist_order_ids = list(map(lambda x:x[\"id\"], valid_order_info)) exist_orders = [] exist_close_orders =",
"return False, False # make new order \"\"\" ret val",
"self.position_id_to_sellids[position_id] = [] # make new order order = {}",
"possible_qty, 'order_type': order_type, 'pair': self.pair } # not correct #",
"= self.api.order.create(order) ret = None if ret_str is not None:",
"is already canceled\") return True # do something ret_str =",
"in internal state\" % (exist_order_info[\"id\"],)) failed_to_cancel = True del self.exist_order_info_list[exist_order_i]",
"enumerate(position[\"close_orders\"]): order[\"status\"] = \"open\" order[\"side\"] = order[\"order_type\"] if \"amount\" not",
"else 'close_short', 'pair': 'btc_jpy', } if target_value is not None:",
"@property def pair(self): return self.__pair def get_base_currency(self): return self.pair.split(\"_\")[1].lower() def",
"possible price tick = self.api.order.tick_price(self.pair) target_value = adjust_price_to_tick(target_value, tick) if",
"valid_close_order[\"amount\"] is_cur_close_long = False if \"side\" in valid_close_order: is_cur_close_long =",
"possible_make_total_price_base_cur = min(possible_make_total_price_base_cur, self.max_free_margin_of_base_currency) amount_tick = self.api.order.tick_amount(self.pair) possible_amount = 1.0",
"\"\"\" #exist_order_ids = list(map(lambda x:x[\"id\"], valid_order_info)) exist_orders = [] exist_close_orders",
"is 'cancel'. probably partially contracted and remain is canceled. this",
"continue # check position that is created by the new_order",
"position class OnePositionTrader(object): def __init__(self, price_decide_algorithm, api, pair=\"btc_jpy\", use_leverage =",
"valid_positions = [] remain_qty = positioned_value_in_qty total_base = 0 for",
"None) # order list は現物とleverageで変わらない if self.exist_order_info_list is not None:",
"remain_qty <= 0: break amount = position[\"amount\"] if remain_qty >=",
"not in self.position_id_to_sellids: return False sell_qty = float(position[\"amount\"]) sell_ids =",
"self._update_transaction_status(valid_transaction_info) def _update_position_status(self, valid_position_info): # apply real positions status to",
"#continue new_order_id = new_order[\"id\"] if new_order_id in self.got_all_order_ids: # this",
"# self.other_reserved_base += float(o[\"pending_amount\"]) * float(o[\"rate\"]) # returns: (is_success, is_new_order_created)",
"{ \"id\": 202835, \"order_type\": \"buy\", \"rate\": 26890, \"pair\": \"btc_jpy\", \"pending_amount\":",
"self.exist_order_info_list = [ret] self.got_all_order_ids.append(ret[\"id\"]) # remove very old orders if",
"current status and make new positions according to algorithm #",
"after update_status def update_close_orders(self, chart, current_time_timezone_aware): for position in self.positions:",
"[] transaction[\"close_orders\"] = [] positions.append(transaction) else: close_transactions.append(transaction) # in next",
"in enumerate(position[\"close_orders\"]): order[\"status\"] = \"open\" order[\"side\"] = order[\"order_type\"] if \"amount\"",
"= positioned_value_in_base def _update_transaction_status(self, valid_transaction_info): if self.use_leverage: return # 現物用。transactionの結果からポジションの状態を解析.",
"elif \"order_type\" in valid_close_order: is_cur_close_long = valid_close_order[\"order_type\"] == \"sell\" if",
"!= \"cancel\" and x[\"id\"] in sell_ids, position[\"close_orders\"])) print(\"valid_close_order count =",
"False self.exist_order_info_list = [ret] self.got_all_order_ids.append(ret[\"id\"]) # remove very old orders",
"\"rate\" in exist_order_info else None # get current stoploss cur_stoploss",
"\"short\": is_close_long = False # check exist sell-orders. if target",
"print(\"You already ordered this order: rate=%.1f, amount=%f, stoploss_rate=%s, position_type=%s\" %",
"or not if len(self.exist_order_info_list) == 1: exist_order_info = self.exist_order_info_list[0] cur_rate",
"print(\"failed to print error\") print(e) return False sell_ids = [ret[\"id\"]]",
"stoploss_rate=%s, position_type=%s\" % (target_value, possible_qty, str(stop_loss_rate), position_type,)) return True, False",
"in enumerate(positions): cur_created_at = pos[\"created_at_datetime\"] if abs((cur_created_at - prev_created_at).total_seconds()) <=",
"= target_value else: # if not leverage order, close order",
"position[\"id\"] if position_id not in self.position_id_to_sellids: return False sell_qty =",
"order result\") try: print(ret_str) except Exception as e: print(\"failed to",
"will be passed) { \"success\": true, \"orders\": [ { \"id\":",
"and amount are completely same, do not pass new order",
"\" state is 'cancel'. probably partially contracted and remain is",
"transaction[\"amount\"] = qty_amount transaction[\"open_rate\"] = float(transaction[\"rate\"]) open_rate = float(transaction[\"open_rate\"]) positioned_value_in_qty",
"self.last_checked_transaction_id = last_transaction_id_in_this_frame print(\"last_checked_transaction_id = \", self.last_checked_transaction_id) print(\"self.exist_close_order_info_list\", self.exist_close_order_info_list) if",
"self.pair, } if target_value is None: # market_sell order['order_type'] =",
"rate = None if \"rate\" in valid_close_order: rate = float(valid_close_order[\"rate\"])",
"%s = %f, you requested = %f\" % (qty_cur, min_qty,",
"get_base_currency(self): return self.pair.split(\"_\")[1].lower() def get_qty_currency(self): return self.pair.split(\"_\")[0].lower() # set usable",
"positioned_value_in_base def _update_transaction_status(self, valid_transaction_info): if self.use_leverage: return # 現物用。transactionの結果からポジションの状態を解析. 基本的にupdate_position_statusと挙動は同じ。parseするjsonが異なる",
"there is a valid order in internal state\" % (exist_order_info[\"id\"],))",
"= %f, others = %f\" % (self.get_max_total_position_price_of_base_currency(), self.positioned_price_base, self.other_reserved_base,)) #print(\"target_value",
"\\ abs(float(cur_amount)-float(possible_qty)) < 0.00001 and \\ cur_stoploss_float_or_none == target_stoploss_float_or_none and",
"market-make def _update_or_create_close_order(self, position, target_value): position_id = position[\"id\"] if position_id",
"this position is not ignored\") #continue new_order_id = new_order[\"id\"] if",
"null, \"pair\": \"btc_jpy\", \"pending_amount\": null, \"pending_market_buy_amount\": \"10000.0\", \"stop_loss_rate\": \"50000.0\", \"created_at\":",
"\"closed_rate\": null, \"amount\": \"1.51347797\", \"all_amount\": \"1.51045705\", \"side\": \"sell\", \"pl\": \"-8490.81029287\",",
"len(self.exist_order_info_list) == 0: self.exist_order_info_list = None if failed_to_cancel: return False",
"be grouped grouped_positions.append(grouping(positions[concat_start_index:])) return grouped_positions # まだcloseされていないtransactionだけを残す def _remain_non_closed_transactions(self, target_transactions,",
"valid_position_info positioned_value_in_base = 0 for position in all_positions: status =",
"\"pair\": \"btc_jpy\", \"status\": \"open\", \"created_at\": \"2015-12-02T05:27:53.000Z\", \"closed_at\": null, \"open_rate\": \"43553.0\",",
"= price_decide_algorithm print(\"PositionTrader: inst=\" + str(self) + \", pair=\" +",
"order canceled but failed to create new sell order!!: position",
"dateutil import dateutil.parser import json from ChartBars import Chart from",
"exist_close_orders.append(order) if not is_added: other_orders.append(order) print(\"exist_create_orders\", exist_orders) print(\"exist_close_orders\", exist_close_orders) self.exist_order_info_list",
"return grouped_positions # まだcloseされていないtransactionだけを残す def _remain_non_closed_transactions(self, target_transactions, positioned_value_in_qty): valid_positions =",
"= 0 positions = sorted(positions, key=lambda x:-x[\"id\"]) # order by",
"remain_qty = positioned_value_in_qty total_base = 0 for position in target_transactions:",
"valid_close_order = valid_close_orders[0] print(\"your order: rate=%f, amount=%f\" % (target_value, sell_qty,))",
"> 0 else None #self.other_reserved_base = 0 #if not self.use_leverage:",
"all_amount is not None and all_amount < amount: amount =",
"self.got_all_order_ids: is_added = True exist_orders.append(order) elif order_id in self.got_close_order_ids: is_added",
"orders if order_id is None: print(\"order is already canceled\") return",
"position that is created by the new_order that is self.order_id:",
"== position_type: # same order. do nothing print(\"You already ordered",
"possible_qty,)) return False, False # make new order \"\"\" ret",
"/ target_value possible_amount = adjust_amount_to_tick(possible_amount,amount_tick) print(\"possible_create_in_base = %f, want to",
"positions.append(transaction) else: close_transactions.append(transaction) # in next frame, only transaction_id >",
"+= 1 if len(self.exist_order_info_list) == 0: self.exist_order_info_list = None if",
"self.max_total_position_price_base = p def set_max_free_margin_of_base_currency(self, p): self.max_free_margin_of_base_currency = p def",
"prev_created_at = positions[0][\"created_at_datetime\"] for idx, pos in enumerate(positions): cur_created_at =",
"do nothing print(\"You already ordered this order: rate=%.1f, amount=%f, stoploss_rate=%s,",
"is always \"sell\" if not is_close_long: print(\"normal order cannot make",
"for position in all_positions: status = position[\"status\"] if status !=",
"= [] positions = target_transactions if len(positions) > 0: def",
"= self.exist_order_info_list[exist_order_i] if self._cancel_order(exist_order_info[\"id\"]) is False: # something error happened!!",
"\"pair\": \"btc_jpy\", \"pending_amount\": \"0.77\", \"pending_market_buy_amount\": null, \"stop_loss_rate\": null, \"created_at\": \"2015-01-10T05:55:38.000Z\"",
"float(open_rate) # check close orders self.position_id_to_sellids[position_id] = \\ list(map(lambda x:x[\"id\"],",
"= position[\"amount\"] all_amount = position[\"all_amount\"] if all_amount is not None",
"< self.api.order.min_create_amount(self.pair)*0.1: positioned_value_in_qty = 0 positions = sorted(positions, key=lambda x:-x[\"id\"])",
"exceed this margin self.positions = [] self.position_id_to_sellids = {} self.got_all_order_ids",
"decide_make_ret else: (position_type, target_value) = decide_make_ret if target_value is None",
"pos_id = position[\"id\"] self.position_id_to_sellids[pos_id] = position_id_to_sellids[pos_id] self.positioned_price_base = positioned_value_in_base self.positioned_value_in_qty",
"_update_transaction_status(self, valid_transaction_info): if self.use_leverage: return # 現物用。transactionの結果からポジションの状態を解析. 基本的にupdate_position_statusと挙動は同じ。parseするjsonが異なる # *",
"\"id\": 23104033, \"side\": \"sell\", \"rate\": null, \"amount\": null, \"pending_amount\": \"0\",",
"self.__pair def get_base_currency(self): return self.pair.split(\"_\")[1].lower() def get_qty_currency(self): return self.pair.split(\"_\")[0].lower() #",
"position_type == \"sell\": position_type = \"short\" is_close_long = True if",
"Exception as e: print(\"failed to print returned error json\") print(e)",
"if self.exist_order_info_list is not None: # check the same value",
"* self.api.order.min_create_amount(self.pair) * 0.1: positioned_value_in_base = 0 # merge position_id_to_sellids",
"is already created on exchanger valid_close_order = valid_close_orders[0] print(\"your order:",
"self.got_all_order_ids = self.got_all_order_ids[-500:] print(\"order success!\", ret_str) return True, True def",
"check exist sell-orders. if target value and amount are completely",
"example (array of \"orders\" will be passed) { \"success\": true,",
"self.positions = [] self.position_id_to_sellids = {} all_positions = valid_position_info positioned_value_in_base",
"self.got_close_order_ids = self.got_close_order_ids[-500:] return True def _cancel_order(self, order_id): # call",
"in self.got_close_order_ids: is_added = True exist_close_orders.append(order) if not is_added: other_orders.append(order)",
"# too few btc print(\"want to make (price,amount) = (%f,%f)",
"instance # レバレッジ用 if not self.use_leverage: return \"\"\" position example",
"= self.exist_close_order_info_list for i, order in enumerate(position[\"close_orders\"]): order[\"status\"] = \"open\"",
"closed position & update positioned_value_in_jpy valid_positions, positioned_value_in_base = self._remain_non_closed_transactions(grouped_positions, positioned_value_in_qty)",
"1.0 * possible_make_total_price_base_cur / target_value possible_amount = adjust_amount_to_tick(possible_amount,amount_tick) print(\"possible_create_in_base =",
"new_order that is self.order_id: new_order = position[\"new_order\"] if new_order[\"status\"] ==",
"self._update_or_create_order(position_type, target_value, possible_amount, stop_loss_rate=stoploss_rate) return new_order_created else: self._cancel_exist_all_buy_orders() print(\"algorithm wants",
"\"order_type\": \"buy\", \"rate\": 26890, \"pair\": \"btc_jpy\", \"pending_amount\": \"0.5527\", \"pending_market_buy_amount\": null,",
"ChartBars import Chart from ChartUpdaterByCCWebsocket import ChartUpdaterByCoincheckWS from Util import",
"return False, False self.exist_order_info_list = [ret] self.got_all_order_ids.append(ret[\"id\"]) # remove very",
"'buy' if is_long else 'sell' order = { 'rate': \"%.8f\"",
"position in enumerate(positions): transaction_id = position[\"id\"] position_id_to_sellids[transaction_id] = list(map(lambda x:x[\"id\"],",
"def _update_transaction_status(self, valid_transaction_info): if self.use_leverage: return # 現物用。transactionの結果からポジションの状態を解析. 基本的にupdate_position_statusと挙動は同じ。parseするjsonが異なる #",
"else None #self.other_reserved_base = 0 #if not self.use_leverage: # for",
"position cannot be grouped. make a new group from pos[start_index]",
"None if \"amount\" in exist_order_info: cur_amount = exist_order_info[\"amount\"] elif \"pending_amount\"",
"= None if failed_to_cancel: return False return True # target_value:",
"new_order_created else: self._cancel_exist_all_buy_orders() print(\"algorithm wants to create a new order",
"# other pair if qty_cur not in transaction[\"funds\"] or base_cur",
"(%f,%f) but too few amount\" % (target_value, possible_amount)) return False",
"positioned_value_in_base = 0 for position in all_positions: status = position[\"status\"]",
"order\") return False order = { 'amount': '%.8f' % BitcoinUtil.roundBTCby1satoshi(sell_qty),",
"0 prev_created_at = positions[0][\"created_at_datetime\"] for idx, pos in enumerate(positions): cur_created_at",
"p): self.max_total_position_price_base = p def set_max_free_margin_of_base_currency(self, p): self.max_free_margin_of_base_currency = p",
"print(\"last_checked_transaction_id = \", self.last_checked_transaction_id) print(\"self.exist_close_order_info_list\", self.exist_close_order_info_list) if self.exist_close_order_info_list is not",
"one position class OnePositionTrader(object): def __init__(self, price_decide_algorithm, api, pair=\"btc_jpy\", use_leverage",
"self._cancel_exist_all_buy_orders(): return False, False # check minimum btc min_qty =",
"exist_order_info[\"order_type\"] == \"buy\" or\\ exist_order_info[\"order_type\"] == \"leverage_buy\": order_type = \"long\"",
"currency self.positioned_price_base = 0 # total position price in base",
"is not None and cur_amount is not None and order_type",
"= \"short\" is_close_long = True if position_type == \"long\": is_close_long",
"None: order['rate'] = target_value else: # if not leverage order,",
"target_value): position_id = position[\"id\"] if position_id not in self.position_id_to_sellids: return",
"def _update_order_id_status(self, valid_order_info): #### # parse orders #### \"\"\" orders",
"success!\", ret_str) return True, True def _cancel_exist_all_buy_orders(self): failed_to_cancel = False",
"消費した反対売買IDのIDを持っておき、次回からはそれより新しいIDのみを反映する # ただし、ずっと続けると計算誤差がたまるので、jpyもしくはbtcベースでその合計値が極めて小さくなったら丸めてノーポジ扱いにする # うーん...現物とレバレッジで管理が結構変わるから同じクラスにするのはまずかった?ごちゃごちゃしてきてしまった # 時間的に約定時刻が近いpositionをまとめる def _group_near_transactions(self, target_transactions):",
"print(e) return False sell_ids = [ret[\"id\"]] self.position_id_to_sellids[position_id] = sell_ids self.got_close_order_ids.append(ret[\"id\"])",
"ordered this order: rate=%.1f, amount=%f, stoploss_rate=%s, position_type=%s\" % (target_value, possible_qty,",
"True if position_type == \"long\": is_close_long = True if position_type",
"str(pair)) @property def pair(self): return self.__pair def get_base_currency(self): return self.pair.split(\"_\")[1].lower()",
"sell-orders. if target value and amount are completely same, do",
"\\ abs(float(amount)-float(sell_qty)) < 0.00001 and \\ is_close_long == is_cur_close_long: #",
"\"status\": \"open\", \"created_at\": \"2015-12-02T05:27:53.000Z\", \"closed_at\": null, \"open_rate\": \"43553.0\", \"closed_rate\": null,",
"None if ret_str is not None: try: ret = json.loads(ret_str)",
"= dateutil.parser.parse(transaction[\"created_at\"]) transaction[\"created_at_datetime\"] = created_time if is_position_transaction: # check close",
"== \"buy\" or\\ exist_order_info[\"order_type\"] == \"leverage_buy\": order_type = \"long\" if",
"null, \"pair\": \"btc_jpy\", \"created_at\": \"2015-01-10T05:55:38.000Z\" \"\"\" is_long = position_type ==",
"cancel failed %d even if there is a valid order",
"<= 0: break amount = position[\"amount\"] if remain_qty >= amount:",
"idx, order in enumerate(valid_order_info): order_id = order[\"id\"] order_pair = order[\"pair\"]",
"position[\"all_amount\"] if all_amount is not None and all_amount < amount:",
"e.g. instance of CoinCheck self.use_leverage = use_leverage self.timelimit_to_grouping_transaction = 2",
"= decide_make_ret else: (position_type, target_value) = decide_make_ret if target_value is",
"# !!round to possible amount possible_make_total_price_base_cur = self.get_max_total_position_price_of_base_currency() - self.positioned_price_base",
"make new order \"\"\" ret val example \"success\": true, \"id\":",
"exist_close_orders if len(exist_close_orders) > 0 else None #self.other_reserved_base = 0",
"break amount = position[\"amount\"] if remain_qty >= amount: remain_qty -=",
"example (array of \"data\" will be passed) { \"data\": [",
"def pair(self): return self.__pair def get_base_currency(self): return self.pair.split(\"_\")[1].lower() def get_qty_currency(self):",
">= transaction_id: continue last_transaction_id_in_this_frame = max(last_transaction_id_in_this_frame, transaction_id) # check pair",
"transaction[\"funds\"] or base_cur not in transaction[\"funds\"]: continue # this position",
"= [] transaction[\"close_orders\"] = [] positions.append(transaction) else: close_transactions.append(transaction) # in",
"\"1.51045705\", \"side\": \"sell\", \"pl\": \"-8490.81029287\", \"new_order\": { \"id\": 23104033, \"side\":",
"will be placed at \"rate\" if stop_loss_rate is not None:",
"既にこの段階で解決できるポジション状態(close order id見て、それがあれば反対売買が成立している) # を用い、↑で貯めたpositionsから、反対売買済みのものを(amount基準で)消していき(前回フレームで残っていたpositionも含めて)、残ったpositionだけを生きているポジションとし、1つに集約する(現物用なので、idが分かれている意味はない) # その残ったpositionID, 消費した反対売買IDのIDを持っておき、次回からはそれより新しいIDのみを反映する # ただし、ずっと続けると計算誤差がたまるので、jpyもしくはbtcベースでその合計値が極めて小さくなったら丸めてノーポジ扱いにする",
"False if not do_not_create_new_order: success, new_order_created = self._update_or_create_order(position_type, target_value, possible_amount,",
"return # 現物用。transactionの結果からポジションの状態を解析. 基本的にupdate_position_statusと挙動は同じ。parseするjsonが異なる # * ただし、前フレームからの情報を引き継ぐところがupdate_position_statusと違う (現物にはpositionという概念が無い) positions =",
"order btc = %f, you requested = %f\" % (min_qty,",
"in valid_close_order: is_cur_close_long = valid_close_order[\"side\"] == \"sell\" elif \"order_type\" in",
"order by desc # concat very near created_at transactions grouped_positions",
"possible_amount, stop_loss_rate=stoploss_rate) return new_order_created else: self._cancel_exist_all_buy_orders() print(\"algorithm wants to create",
"= [] positions.append(transaction) else: close_transactions.append(transaction) # in next frame, only",
"%f, possible amount = %f\" % (self.get_max_total_position_price_of_base_currency() - self.positioned_price_base, possible_make_total_price_base_cur,",
"= pair self.price_decide_algorithm = price_decide_algorithm print(\"PositionTrader: inst=\" + str(self) +",
"base currency (actually paired currency) self.positioned_value_in_qty = 0 # used",
"x:x[\"status\"] != \"cancel\" and x[\"id\"] in sell_ids, position[\"close_orders\"])) print(\"valid_close_order count",
"type name if position_type == \"buy\": position_type = \"long\" if",
"this class's order qty_amount = float(transaction[\"funds\"][qty_cur]) transaction[\"amount\"] = transaction[\"amount\"] =",
"tick) def adjust_amount_to_tick(amount, tick): return amount - math.fmod(amount, tick) #",
"== \"buy\": # self.other_reserved_base += float(o[\"pending_amount\"]) * float(o[\"rate\"]) # returns:",
"{ \"data\": [ { \"id\": 10, \"pair\": \"btc_jpy\", \"status\": \"open\",",
"order['order_type'] = \"market_sell\" else: order['rate'] = target_value ret = self.api.order.create(order)",
"cancel all exist orders if not self._cancel_exist_all_buy_orders(): return False, False",
"example \"success\": true, \"id\": 12345, \"rate\": \"30010.0\", \"amount\": \"1.3\", \"order_type\":",
"all_positions = valid_position_info positioned_value_in_base = 0 for position in all_positions:",
"\"pending_amount\": \"0\", \"status\": \"complete\", \"created_at\": \"2015-12-02T05:27:52.000Z\" }, \"close_orders\": [ {",
"position[\"all_amount\"] = amount self.positions.append(position) open_rate = position[\"open_rate\"] positioned_value_in_base += float(amount)",
"failed %d even if there is a valid order in",
"= self.got_close_order_ids[-500:] return True def _cancel_order(self, order_id): # call apis",
"= amount self.positions.append(position) open_rate = position[\"open_rate\"] positioned_value_in_base += float(amount) *",
"created by this class's order qty_amount = float(transaction[\"funds\"][qty_cur]) transaction[\"amount\"] =",
"\"data\" will be passed) { \"data\": [ { \"id\": 10,",
"self.got_close_order_ids[-500:] return True def _cancel_order(self, order_id): # call apis for",
"parse cancel order ret str\") try: print(ret_str) except Exception as",
"return self.positioned_price_base def set_timelimit_to_grouping_transaction(self, timelimit_to_grouping_transaction): self.timelimit_to_grouping_transaction = timelimit_to_grouping_transaction # check",
"current orders if order_id is None: print(\"order is already canceled\")",
"to this instance # レバレッジ用 if not self.use_leverage: return \"\"\"",
"in valid_positions: pos_id = position[\"id\"] self.position_id_to_sellids[pos_id] = position_id_to_sellids[pos_id] self.positioned_price_base =",
"\"created_at\": \"2016-02-23T12:14:50.000Z\" } ] } \"\"\" #exist_order_ids = list(map(lambda x:x[\"id\"],",
"= float(position[\"amount\"]) created_time = position[\"created_at_datetime\"] target_value = None if self.price_decide_algorithm.market_sell_decide_algorithm(chart,",
"stop_loss_rate=stoploss_rate) return new_order_created else: self._cancel_exist_all_buy_orders() print(\"algorithm wants to create a",
"value >= stop_loss_rate, sashine will be placed at \"rate\" if",
"target_value, possible_amount, stop_loss_rate=stoploss_rate) return new_order_created else: self._cancel_exist_all_buy_orders() print(\"algorithm wants to",
"amount are completely same, do not pass new order valid_close_orders",
"\"stop_loss_rate\": null, \"created_at\": \"2015-01-10T05:55:38.000Z\" }, { \"id\": 38632107, \"order_type\": \"buy\",",
"stoploss_rate = adjust_price_to_tick(stoploss_rate, tick) # !!round to possible amount possible_make_total_price_base_cur",
"== \"sell\" or \\ exist_order_info[\"order_type\"] == \"leverage_sell\": order_type = \"short\"",
"qty_cur = self.get_qty_currency() base_cur = self.get_base_currency() last_transaction_id_in_this_frame = self.last_checked_transaction_id for",
"and x[\"id\"] in sell_ids, position[\"close_orders\"])) print(\"valid_close_order count = %d\" %",
"base_cur = self.get_base_currency() last_transaction_id_in_this_frame = self.last_checked_transaction_id for transaction in all_transactions:",
"return False, False # check minimum btc min_qty = self.api.order.min_create_amount(self.pair)",
"enumerate(positions): cur_created_at = pos[\"created_at_datetime\"] if abs((cur_created_at - prev_created_at).total_seconds()) <= self.timelimit_to_grouping_transaction:",
"\"market_sell\" else: order['rate'] = target_value ret = self.api.order.create(order) ret_str =",
"position & update positioned_value_in_jpy valid_positions, positioned_value_in_base = self._remain_non_closed_transactions(grouped_positions, positioned_value_in_qty) if",
"cleared) self._update_order_id_status(valid_order_info) if self.use_leverage: self._update_position_status(valid_position_info) else: self._update_transaction_status(valid_transaction_info) def _update_position_status(self, valid_position_info):",
"concat very near created_at transactions grouped_positions = self._group_near_transactions(positions) # remove",
"\"\"\" is_long = position_type == \"long\" order_type = 'leverage_buy' if",
"positioned_value_in_jpy valid_positions, positioned_value_in_base = self._remain_non_closed_transactions(grouped_positions, positioned_value_in_qty) if abs(positioned_value_in_base) < self.api.order.tick_price(self.pair)",
"float(valid_close_order[\"rate\"]) amount = valid_close_order[\"amount\"] is_cur_close_long = False if \"side\" in",
"returned json str\") print(e) return False, False self.exist_order_info_list = [ret]",
"self.got_all_order_ids[-500:] print(\"order success!\", ret_str) return True, True def _cancel_exist_all_buy_orders(self): failed_to_cancel",
"list は現物とleverageで変わらない if self.exist_order_info_list is not None: # check the",
"(target_value, possible_make_total_price_base_cur,)) if possible_amount <= 0.000001: # too few btc",
"# if not leverage order, close order is always \"sell\"",
"update_close_orders(self, chart, current_time_timezone_aware): for position in self.positions: open_rate = float(position[\"open_rate\"])",
"p in desced_position_array: total_amount += p[\"amount\"] total_jpy += p[\"amount\"] *",
"continue position_id = position[\"id\"] # check position that is created",
"sell_qty < min_qty: qty_cur = self.get_qty_currency() print(\"Minimum order %s =",
"self.exist_order_info_list: self._cancel_order(exist_order_info[\"id\"]) self.exist_order_info_list = None return False # round to",
"== 1 and target_value is not None: # check the",
"return False sell_qty = float(position[\"amount\"]) sell_ids = self.position_id_to_sellids[position_id] position_type =",
"\"amount\": \"1.0\", \"pending_amount\": \"0.0\", \"status\": \"cancel\", \"created_at\": \"2015-12-05T05:03:56.000Z\" } ]",
"self.got_all_order_ids: # this position is created by this class's order",
"target_value:%s, amount:%s, close_long:%s\" % (str(position_id), str(target_value), str(amount), str(is_cur_close_long),)) return True",
"target_value ret = self.api.order.create(order) ret_str = ret if ret is",
"self.use_leverage: # for o in other_orders: # if o[\"order_type\"] ==",
"prev_created_at = cur_created_at continue # this position cannot be grouped.",
"int(transaction[\"order_id\"]) transaction[\"order_id\"] = new_order_id is_position_transaction = new_order_id in self.got_all_order_ids is_close_transaction",
"== self.pair: if order_id in self.got_all_order_ids: is_added = True exist_orders.append(order)",
"\"10000.0\", \"amount\": \"1.0\", \"pending_amount\": \"0.0\", \"status\": \"cancel\", \"created_at\": \"2015-12-05T05:03:56.000Z\" }",
"not correct # this \"stop_loss_rate\" means: if a value >=",
"close_long order result\") try: print(ret_str) except Exception as e: print(\"failed",
"is not None: order[\"stop_loss_rate\"] = stop_loss_rate ret_str = self.api.order.create(order) ret",
"and make new positions according to algorithm # notice: this",
"self.got_all_order_ids.append(ret[\"id\"]) # remove very old orders if len(self.got_all_order_ids) > 500:",
"== \"long\": is_close_long = True if position_type == \"short\": is_close_long",
"apply real positions status to this instance # レバレッジ用 if",
"position[\"amount\"] if remain_qty >= amount: remain_qty -= amount else: position[\"amount\"]",
"None: # check the order is already created on exchanger",
"import dateutil.parser import json from ChartBars import Chart from ChartUpdaterByCCWebsocket",
"self.api.order.tick_price(self.pair)) self._update_or_create_close_order(position, target_value) # interface to update internal position &",
"%f\" % (self.get_max_total_position_price_of_base_currency(), self.positioned_price_base, self.other_reserved_base,)) #print(\"target_value = %f, possible_base =",
"for pos_i, position in enumerate(positions): transaction_id = position[\"id\"] position_id_to_sellids[transaction_id] =",
"return ret_pos concat_start_index = 0 prev_created_at = positions[0][\"created_at_datetime\"] for idx,",
"\"sell\" or \\ exist_order_info[\"order_type\"] == \"leverage_sell\": order_type = \"short\" if",
"'btc_jpy', } if target_value is not None: order['rate'] = target_value",
"return False # cancel all for sell_id in sell_ids: self._cancel_order(sell_id)",
"check close orders # 漏れがあるとまずい(cancelしなくなる)ので、とりあえずあるだけリンクしておく position_id_to_sellids[transaction_id] = [] transaction[\"close_orders\"] =",
"that is created by the new_order that is self.order_id: new_order",
"to parse api.order.create result\") try: print(ret_str) except Exception as e:",
"!= self.pair: continue # check position that is created by",
"len(decide_make_ret) == 3: (position_type, target_value, stoploss_rate) = decide_make_ret else: (position_type,",
"print(\"self.exist_close_order_info_list\", self.exist_close_order_info_list) if self.exist_close_order_info_list is not None: for pos_i, position",
"= %f\" % (min_qty, possible_qty,)) return False, False # make",
"continue # this position cannot be grouped. make a new",
"'amount': '%.8f' % BitcoinUtil.roundBTCby1satoshi(sell_qty), 'order_type': 'sell', 'pair': self.pair, } if",
"\"id\" not in ret or ret[\"id\"] is None: print(\"sell order",
"positioned_%s=%f, positioned_%s=%f\" % (len(self.positions), base_cur, self.positioned_price_base, qty_cur, self.positioned_value_in_qty,)) # close",
"if abs(positioned_value_in_qty) < self.api.order.min_create_amount(self.pair)*0.1: positioned_value_in_qty = 0 positions = sorted(positions,",
"self.api.order.tick_price(self.pair) target_value = adjust_price_to_tick(target_value, tick) if stoploss_rate is not None:",
"12345, \"rate\": \"30010.0\", \"amount\": \"1.3\", \"order_type\": \"sell\", \"stop_loss_rate\": null, \"pair\":",
"e: print(\"failed to show returned json str\") print(e) return False,",
"for exist_order_info in self.exist_order_info_list: self._cancel_order(exist_order_info[\"id\"]) self.exist_order_info_list = None return False",
"not leverage order, close order is always \"sell\" if not",
"error happened!! print(\"order cancel failed %d even if there is",
"1 if len(self.exist_order_info_list) == 0: self.exist_order_info_list = None if failed_to_cancel:",
"+ (positioned)) def set_max_total_position_price_base(self, p): self.set_max_total_position_price_of_base_currency(p) def set_max_total_position_price_of_base_currency(self, p): self.max_total_position_price_base",
"True exist_orders.append(order) elif order_id in self.got_close_order_ids: is_added = True exist_close_orders.append(order)",
"next frame, only transaction_id > self.last_checked_transaction_id will be checked self.last_checked_transaction_id",
"if \"amount\" in exist_order_info: cur_amount = exist_order_info[\"amount\"] elif \"pending_amount\" in",
"True def _cancel_order(self, order_id): # call apis for current orders",
"self.position_id_to_sellids = position_id_to_sellids self.positions = valid_positions print(\"position_count=%d, positioned_%s=%f, positioned_%s=%f\" %",
"cannot be grouped. make a new group from pos[start_index] -",
"not self.use_leverage: # for o in other_orders: # if o[\"order_type\"]",
"in exist_order_info: cur_amount = exist_order_info[\"amount\"] elif \"pending_amount\" in exist_order_info: cur_amount",
"update position/order status (assume: pagenations are already cleared) self._update_order_id_status(valid_order_info) if",
"# * ただし、前フレームからの情報を引き継ぐところがupdate_position_statusと違う (現物にはpositionという概念が無い) positions = self.positions position_id_to_sellids = self.position_id_to_sellids",
"flag = true\") return False # update close orders according",
"False # check exist sell-orders. if target value and amount",
"\"long\": is_close_long = True if position_type == \"short\": is_close_long =",
"Exception as e: print(\"failed to print error\") print(e) if ret",
"0 positions = sorted(positions, key=lambda x:-x[\"id\"]) # order by desc",
"None): assert (self.api is not None) # order list は現物とleverageで変わらない",
"(target_value, possible_qty, str(stop_loss_rate), position_type,)) return True, False # cancel all",
"(assume: pagenations are already cleared) self._update_order_id_status(valid_order_info) if self.use_leverage: self._update_position_status(valid_position_info) else:",
"grouped_positions = self._group_near_transactions(positions) # remove closed position & update positioned_value_in_jpy",
"self.positioned_price_base, self.other_reserved_base,)) #print(\"target_value = %f, possible_base = %f\" % (target_value,",
"\"1.3\", \"order_type\": \"sell\", \"stop_loss_rate\": null, \"pair\": \"btc_jpy\", \"created_at\": \"2015-01-10T05:55:38.000Z\" \"\"\"",
"the new_order that is self.order_id: new_order = position[\"new_order\"] if new_order[\"status\"]",
"def set_timelimit_to_grouping_transaction(self, timelimit_to_grouping_transaction): self.timelimit_to_grouping_transaction = timelimit_to_grouping_transaction # check current status",
"'leverage_sell' if not self.use_leverage: order_type = 'buy' if is_long else",
"return True min_qty = self.api.order.min_create_amount(self.pair) if sell_qty < min_qty: qty_cur",
"500: self.got_all_order_ids = self.got_all_order_ids[-500:] print(\"order success!\", ret_str) return True, True",
"print(\"order success!\", ret_str) return True, True def _cancel_exist_all_buy_orders(self): failed_to_cancel =",
"want to make amount in base = %f, possible amount",
"not in ret: print(\"Failed to cancel order %s: %s\" %",
"- self.positioned_price_base possible_make_total_price_base_cur = min(possible_make_total_price_base_cur, self.max_free_margin_of_base_currency) amount_tick = self.api.order.tick_amount(self.pair) possible_amount",
"# 約定時刻がこの秒数以下なら同一ポジションとみなす(use_leverage == False の場合のみ) self.__pair = pair self.price_decide_algorithm =",
"= [] # make new order order = {} if",
"in ret: print(\"Failed to cancel order %s: %s\" % (str(order_id),",
"position is created by this class's order created_time = dateutil.parser.parse(position[\"created_at\"])",
"is not True or \"id\" not in ret: print(\"Failed to",
"\"id\": 23755132, \"side\": \"buy\", \"rate\": \"10000.0\", \"amount\": \"1.0\", \"pending_amount\": \"0.0\",",
"key=lambda x:-x[\"id\"]) # order by desc # concat very near",
"False, False # make new order \"\"\" ret val example",
"* float(open_rate) # check close orders self.position_id_to_sellids[position_id] = \\ list(map(lambda",
"= False if \"side\" in valid_close_order: is_cur_close_long = valid_close_order[\"side\"] ==",
"total position price in base currency (actually paired currency) self.positioned_value_in_qty",
"float(amount) * float(open_rate) # check close orders self.position_id_to_sellids[position_id] = \\",
"valid_close_order[\"side\"] == \"sell\" elif \"order_type\" in valid_close_order: is_cur_close_long = valid_close_order[\"order_type\"]",
"maximum position size in base currency self.positioned_price_base = 0 #",
"print(valid_close_order) rate = None if \"rate\" in valid_close_order: rate =",
"or ret[\"success\"] is not True or \"id\" not in ret",
"(exist_order_info[\"id\"],)) failed_to_cancel = True del self.exist_order_info_list[exist_order_i] else: exist_order_i += 1",
"position_type == \"long\" order_type = 'leverage_buy' if is_long else 'leverage_sell'",
"is created by this class's order created_time = dateutil.parser.parse(position[\"created_at\"]) position[\"created_at_datetime\"]",
"wants to create a new order but DO_NOT_CREATE_NEW flag =",
"but too few amount\" % (target_value, possible_amount)) return False if",
"'rate': \"%.8f\" % target_value, 'amount': \"%.8f\" % possible_qty, 'order_type': order_type,",
"== 1: exist_order_info = self.exist_order_info_list[0] cur_rate = exist_order_info[\"rate\"] if \"rate\"",
"completely same!! print(\"requested close order is already ordered on server:\")",
"\"orders\" will be passed) { \"success\": true, \"orders\": [ {",
"decide_make_ret if target_value is None or position_type is None: #",
"self.got_all_order_ids = [] self.got_close_order_ids = [] self.exist_order_info_list = None self.exist_close_order_info_list",
"def set_max_total_position_price_of_base_currency(self, p): self.max_total_position_price_base = p def set_max_free_margin_of_base_currency(self, p): self.max_free_margin_of_base_currency",
"not None: order[\"stop_loss_rate\"] = stop_loss_rate ret_str = self.api.order.create(order) ret =",
"dateutil.parser.parse(position[\"created_at\"]) position[\"created_at_datetime\"] = created_time amount = position[\"amount\"] all_amount = position[\"all_amount\"]",
"if self.use_leverage: return # 現物用。transactionの結果からポジションの状態を解析. 基本的にupdate_position_statusと挙動は同じ。parseするjsonが異なる # * ただし、前フレームからの情報を引き継ぐところがupdate_position_statusと違う (現物にはpositionという概念が無い)",
"position is created by this class's order qty_amount = float(transaction[\"funds\"][qty_cur])",
"= 0 for position in all_positions: status = position[\"status\"] if",
"valid_positions.append(position) total_base += position[\"amount\"] * position[\"open_rate\"] return valid_positions, total_base def",
"= [] remain_qty = positioned_value_in_qty total_base = 0 for position",
"x:x[\"status\"] != \"cancel\", position[\"close_orders\"]))) self.positioned_price_base = positioned_value_in_base def _update_transaction_status(self, valid_transaction_info):",
"id見て、それがあれば反対売買が成立している) # を用い、↑で貯めたpositionsから、反対売買済みのものを(amount基準で)消していき(前回フレームで残っていたpositionも含めて)、残ったpositionだけを生きているポジションとし、1つに集約する(現物用なので、idが分かれている意味はない) # その残ったpositionID, 消費した反対売買IDのIDを持っておき、次回からはそれより新しいIDのみを反映する # ただし、ずっと続けると計算誤差がたまるので、jpyもしくはbtcベースでその合計値が極めて小さくなったら丸めてノーポジ扱いにする # うーん...現物とレバレッジで管理が結構変わるから同じクラスにするのはまずかった?ごちゃごちゃしてきてしまった",
"value and amount are completely same, do not pass new",
"adjust_price_to_tick(price, tick): return price - math.fmod(price, tick) def adjust_amount_to_tick(amount, tick):",
"is_position_transaction and not is_close_transaction: continue # other pair if qty_cur",
"order id見て、それがあれば反対売買が成立している) # を用い、↑で貯めたpositionsから、反対売買済みのものを(amount基準で)消していき(前回フレームで残っていたpositionも含めて)、残ったpositionだけを生きているポジションとし、1つに集約する(現物用なので、idが分かれている意味はない) # その残ったpositionID, 消費した反対売買IDのIDを持っておき、次回からはそれより新しいIDのみを反映する # ただし、ずっと続けると計算誤差がたまるので、jpyもしくはbtcベースでその合計値が極めて小さくなったら丸めてノーポジ扱いにする #",
"= None self.exist_close_order_info_list = None self.last_checked_transaction_id = 0 self.api =",
"amount = float(position[\"amount\"]) created_time = position[\"created_at_datetime\"] target_value = None if",
"= float(position[\"amount\"]) sell_ids = self.position_id_to_sellids[position_id] position_type = position[\"side\"] # convert",
"use orders that exceed this margin self.positions = [] self.position_id_to_sellids",
"基本的にupdate_position_statusと挙動は同じ。parseするjsonが異なる # * ただし、前フレームからの情報を引き継ぐところがupdate_position_statusと違う (現物にはpositionという概念が無い) positions = self.positions position_id_to_sellids =",
"exist_close_orders) self.exist_order_info_list = exist_orders if len(exist_orders) > 0 else None",
"# その残ったpositionID, 消費した反対売買IDのIDを持っておき、次回からはそれより新しいIDのみを反映する # ただし、ずっと続けると計算誤差がたまるので、jpyもしくはbtcベースでその合計値が極めて小さくなったら丸めてノーポジ扱いにする # うーん...現物とレバレッジで管理が結構変わるから同じクラスにするのはまずかった?ごちゃごちゃしてきてしまった # 時間的に約定時刻が近いpositionをまとめる def",
"elif order_id in self.got_close_order_ids: is_added = True exist_close_orders.append(order) if not",
"to print error\") print(e) return False sell_ids = [ret[\"id\"]] self.position_id_to_sellids[position_id]",
"positions[0][\"created_at_datetime\"] for idx, pos in enumerate(positions): cur_created_at = pos[\"created_at_datetime\"] if",
"= stop_loss_rate ret_str = self.api.order.create(order) ret = None if ret_str",
"order[\"side\"] = order[\"order_type\"] if \"amount\" not in order: order[\"amount\"] =",
"0: break amount = position[\"amount\"] if remain_qty >= amount: remain_qty",
"False if \"side\" in valid_close_order: is_cur_close_long = valid_close_order[\"side\"] == \"sell\"",
"new_order that is self.order_id: new_order_id = int(transaction[\"order_id\"]) transaction[\"order_id\"] = new_order_id",
"\"amount\" not in order: order[\"amount\"] = float(order[\"pending_amount\"]) position[\"close_orders\"][i] = order",
"= self.api.order.min_create_amount(self.pair) if sell_qty < min_qty: qty_cur = self.get_qty_currency() print(\"Minimum",
"failed_to_cancel = False exist_order_i = 0 while exist_order_i < len(self.exist_order_info_list):",
"is None or ret[\"success\"] is not True or \"id\" not",
"transaction[\"id\"] = transaction_id # check only new id if self.last_checked_transaction_id",
"order, close order is always \"sell\" if not is_close_long: print(\"normal",
"exist_close_orders = [] other_orders = [] for idx, order in",
"\"0.77\", \"pending_market_buy_amount\": null, \"stop_loss_rate\": null, \"created_at\": \"2015-01-10T05:55:38.000Z\" }, { \"id\":",
"is created by the new_order that is self.order_id: new_order_id =",
"new_order_created = self._update_or_create_order(position_type, target_value, possible_amount, stop_loss_rate=stoploss_rate) return new_order_created else: self._cancel_exist_all_buy_orders()",
"remain_qty >= amount: remain_qty -= amount else: position[\"amount\"] = remain_qty",
"print(ret_str) except Exception as e: print(\"failed to print error\") print(e)",
"but failed to create new sell order!!: position id: %s\"",
"# this position is created by this class's order created_time",
"= qty_amount transaction[\"open_rate\"] = float(transaction[\"rate\"]) open_rate = float(transaction[\"open_rate\"]) positioned_value_in_qty +=",
"self.exist_close_order_info_list = None self.last_checked_transaction_id = 0 self.api = api #",
"completely same, do not pass new order valid_close_orders = list(filter(lambda",
"valid_transaction_info): if self.use_leverage: return # 現物用。transactionの結果からポジションの状態を解析. 基本的にupdate_position_statusと挙動は同じ。parseするjsonが異なる # * ただし、前フレームからの情報を引き継ぐところがupdate_position_statusと違う",
"= {} if self.use_leverage: order = { 'amount': '%.8f' %",
"and not is_close_transaction: continue # other pair if qty_cur not",
"if pair != self.pair: continue position_id = position[\"id\"] # check",
"self.api.order.create(order) ret = None if ret_str is not None: try:",
"= self.get_qty_currency() print(\"Minimum order %s = %f, you requested =",
"if all_amount is not None and all_amount < amount: amount",
"grouped. make a new group from pos[start_index] - pos[idx-1] grouped_positions.append(grouping(positions[concat_start_index:idx]))",
"according to algorithm # notice: this method should be called",
"parse close_long order result\") try: print(ret_str) except Exception as e:",
"\"43553.0\", \"closed_rate\": null, \"amount\": \"1.51347797\", \"all_amount\": \"1.51045705\", \"side\": \"sell\", \"pl\":",
"# close したかどうか、残っているポジション残量を計算するのに、全て遡らないといけないのは現実的ではない # 既にこの段階で解決できるポジション状態(close order id見て、それがあれば反対売買が成立している) # を用い、↑で貯めたpositionsから、反対売買済みのものを(amount基準で)消していき(前回フレームで残っていたpositionも含めて)、残ったpositionだけを生きているポジションとし、1つに集約する(現物用なので、idが分かれている意味はない) #",
"pair this_pair = transaction[\"pair\"] if this_pair != self.pair: continue #",
"= 0 prev_created_at = positions[0][\"created_at_datetime\"] for idx, pos in enumerate(positions):",
"= ret if ret is not None: try: ret =",
"parse orders #### \"\"\" orders example (array of \"orders\" will",
"= list(map(lambda x:x[\"id\"], valid_order_info)) exist_orders = [] exist_close_orders = []",
"sell_ids = [ret[\"id\"]] self.position_id_to_sellids[position_id] = sell_ids self.got_close_order_ids.append(ret[\"id\"]) if len(self.got_close_order_ids) >",
"= self.api.order.create(order) ret_str = ret if ret is not None:",
"to cancel order %s: %s\" % (str(order_id), str(ret_str),)) return False",
"Exception as e: print(\"failed to print error\") print(e) return False",
"order[\"amount\"] = float(order[\"pending_amount\"]) position[\"close_orders\"][i] = order positions[pos_i] = position #",
"print(\"want to make (price,amount) = (%f,%f) but too few amount\"",
"-= amount else: position[\"amount\"] = remain_qty remain_qty = 0 valid_positions.append(position)",
"> 0: def grouping(desced_position_array): ret_pos = dict(desced_position_array[0]) total_amount = 0",
"not None: order['rate'] = target_value else: # if not leverage",
"order_id in self.got_close_order_ids: is_added = True exist_close_orders.append(order) if not is_added:",
"self.exist_order_info_list = None if failed_to_cancel: return False return True #",
"= transaction[\"amount\"] = qty_amount transaction[\"open_rate\"] = float(transaction[\"rate\"]) open_rate = float(transaction[\"open_rate\"])",
"if self.use_leverage: order = { 'amount': '%.8f' % BitcoinUtil.roundBTCby1satoshi(sell_qty), 'position_id':",
"positions #### self.positions = [] self.position_id_to_sellids = {} all_positions =",
"position size in base currency self.positioned_price_base = 0 # total",
"do_not_create_new_order: success, new_order_created = self._update_or_create_order(position_type, target_value, possible_amount, stop_loss_rate=stoploss_rate) return new_order_created",
"\"leverage_buy\": order_type = \"long\" if exist_order_info[\"order_type\"] == \"sell\" or \\",
"print(\"new order: \" + str(new_order[\"id\"]) + \" state is 'cancel'.",
"in transaction[\"funds\"]: continue # this position is created by this",
"target_value, 'amount': \"%.8f\" % possible_qty, 'order_type': order_type, 'pair': self.pair }",
"prev_created_at = cur_created_at # remain positioned not be grouped grouped_positions.append(grouping(positions[concat_start_index:]))",
"if target_value is not None: order['rate'] = target_value else: #",
"adjust_amount_to_tick(amount, tick): return amount - math.fmod(amount, tick) # a class",
"return True def _cancel_order(self, order_id): # call apis for current",
"self.position_id_to_sellids close_transactions = [] all_transactions = valid_transaction_info positioned_value_in_qty = self.positioned_value_in_qty",
"self.timelimit_to_grouping_transaction = timelimit_to_grouping_transaction # check current status and make new",
"} ] } ] } \"\"\" #### # parse positions",
"positioned_value_in_qty = 0 positions = sorted(positions, key=lambda x:-x[\"id\"]) # order",
"return True # target_value: sashine value. if None, market-make def",
"transaction_id: continue last_transaction_id_in_this_frame = max(last_transaction_id_in_this_frame, transaction_id) # check pair this_pair",
"try: ret = json.loads(ret) except: print(\"failed to parse close_long order",
"is None: # algorithm says this instance should not make",
"are already cleared) self._update_order_id_status(valid_order_info) if self.use_leverage: self._update_position_status(valid_position_info) else: self._update_transaction_status(valid_transaction_info) def",
"exist_order_i = 0 while exist_order_i < len(self.exist_order_info_list): exist_order_info = self.exist_order_info_list[exist_order_i]",
"if status != \"open\": continue pair = position[\"pair\"] if pair",
"False return True # target_value: sashine value. if None, market-make",
"\"\"\" #### # parse positions #### self.positions = [] self.position_id_to_sellids",
"in self.got_all_order_ids: # this position is created by this class's",
"is not None) position_type = None target_value = None stoploss_rate",
"\"id\": 10, \"pair\": \"btc_jpy\", \"status\": \"open\", \"created_at\": \"2015-12-02T05:27:53.000Z\", \"closed_at\": null,",
"is_cur_close_long = valid_close_order[\"order_type\"] == \"sell\" if abs(float(rate)-float(target_value)) < 0.00001 and",
"= dict(desced_position_array[0]) total_amount = 0 total_jpy = 0 for p",
"self.other_reserved_base += float(o[\"pending_amount\"]) * float(o[\"rate\"]) # returns: (is_success, is_new_order_created) def",
"says this instance should not make order. cancel all if",
"= %f\" % (self.get_max_total_position_price_of_base_currency(), self.positioned_price_base, self.other_reserved_base,)) #print(\"target_value = %f, possible_base",
"# parse positions #### self.positions = [] self.position_id_to_sellids = {}",
"len(positions) > 0: def grouping(desced_position_array): ret_pos = dict(desced_position_array[0]) total_amount =",
"_update_order_id_status(self, valid_order_info): #### # parse orders #### \"\"\" orders example",
"ret if ret is not None: try: ret = json.loads(ret)",
"this \"stop_loss_rate\" means: if a value >= stop_loss_rate, sashine will",
"positions = sorted(positions, key=lambda x:-x[\"id\"]) # order by desc #",
"False の場合のみ) self.__pair = pair self.price_decide_algorithm = price_decide_algorithm print(\"PositionTrader: inst=\"",
"= None if \"rate\" in valid_close_order: rate = float(valid_close_order[\"rate\"]) amount",
"use_leverage self.timelimit_to_grouping_transaction = 2 # 約定時刻がこの秒数以下なら同一ポジションとみなす(use_leverage == False の場合のみ) self.__pair",
"_update_position_status(self, valid_position_info): # apply real positions status to this instance",
"tick): return amount - math.fmod(amount, tick) # a class for",
"frame, only transaction_id > self.last_checked_transaction_id will be checked self.last_checked_transaction_id =",
"return True, False # cancel all exist orders if not",
"cancel all for sell_id in sell_ids: self._cancel_order(sell_id) self.position_id_to_sellids[position_id] = []",
"failed to create new sell order!!: position id: %s\" %",
"# 時間的に約定時刻が近いpositionをまとめる def _group_near_transactions(self, target_transactions): grouped_positions = [] positions =",
"api.order.create result\") try: print(ret_str) except Exception as e: print(\"failed to",
"ChartUpdaterByCCWebsocket import ChartUpdaterByCoincheckWS from Util import BitcoinUtil def adjust_price_to_tick(price, tick):",
"\"side\": \"sell\", \"pl\": \"-8490.81029287\", \"new_order\": { \"id\": 23104033, \"side\": \"sell\",",
"- self.positioned_price_base, possible_make_total_price_base_cur, possible_amount)) #print(\"base_cur = %f, positioned = %f,",
"[ret[\"id\"]] self.position_id_to_sellids[position_id] = sell_ids self.got_close_order_ids.append(ret[\"id\"]) if len(self.got_close_order_ids) > 500: self.got_close_order_ids",
"\"pending_market_buy_amount\": null, \"stop_loss_rate\": null, \"created_at\": \"2015-01-10T05:55:38.000Z\" }, { \"id\": 202836,",
"self.exist_order_info_list = None self.exist_close_order_info_list = None self.last_checked_transaction_id = 0 self.api",
"(target_value, sell_qty,)) print(\"valid_close_order[0]:\") print(valid_close_order) rate = None if \"rate\" in",
"positioned_value_in_base self.positioned_value_in_qty = positioned_value_in_qty self.position_id_to_sellids = position_id_to_sellids self.positions = valid_positions",
"null, \"amount\": \"1.51347797\", \"all_amount\": \"1.51045705\", \"side\": \"sell\", \"pl\": \"-8490.81029287\", \"new_order\":",
"algorithm # notice: this method should be called after update_status",
"position, target_value): position_id = position[\"id\"] if position_id not in self.position_id_to_sellids:",
"{ \"success\": true, \"orders\": [ { \"id\": 202835, \"order_type\": \"buy\",",
"dict(desced_position_array[0]) total_amount = 0 total_jpy = 0 for p in",
"id if self.last_checked_transaction_id >= transaction_id: continue last_transaction_id_in_this_frame = max(last_transaction_id_in_this_frame, transaction_id)",
"= valid_close_orders[0] print(\"your order: rate=%f, amount=%f\" % (target_value, sell_qty,)) print(\"valid_close_order[0]:\")",
"probably partially contracted and remain is canceled. this position is",
"self.api.order.min_create_amount(self.pair)*0.1: positioned_value_in_qty = 0 positions = sorted(positions, key=lambda x:-x[\"id\"]) #",
"as e: print(\"failed to print error\") print(e) return False sell_ids",
"= exist_order_info[\"stop_loss_rate\"] if \"stop_loss_rate\" in exist_order_info else None cur_stoploss_float_or_none =",
"list(map(lambda x:x[\"id\"], self.exist_close_order_info_list)) position[\"close_orders\"] = self.exist_close_order_info_list for i, order in",
"\"1.0\", \"pending_amount\": \"0.0\", \"status\": \"cancel\", \"created_at\": \"2015-12-05T05:03:56.000Z\" } ] }",
"= new_order_id in self.got_close_order_ids if not is_position_transaction and not is_close_transaction:",
"amount=%f\" % (target_value, sell_qty,)) print(\"valid_close_order[0]:\") print(valid_close_order) rate = None if",
"del self.exist_order_info_list[exist_order_i] else: exist_order_i += 1 if len(self.exist_order_info_list) == 0:",
"possible_qty, str(stop_loss_rate), position_type,)) return True, False # cancel all exist",
"if is_long else 'leverage_sell' if not self.use_leverage: order_type = 'buy'",
"self.set_max_total_position_price_of_base_currency(p) def set_max_total_position_price_of_base_currency(self, p): self.max_total_position_price_base = p def set_max_free_margin_of_base_currency(self, p):",
"order \"\"\" ret val example \"success\": true, \"id\": 12345, \"rate\":",
"in exist_order_info: if exist_order_info[\"order_type\"] == \"buy\" or\\ exist_order_info[\"order_type\"] == \"leverage_buy\":",
"is_added = False if order_pair == self.pair: if order_id in",
"= %f, possible amount = %f\" % (self.get_max_total_position_price_of_base_currency() - self.positioned_price_base,",
"prev_created_at).total_seconds()) <= self.timelimit_to_grouping_transaction: # can group prev_created_at = cur_created_at continue",
"amount self.positions.append(position) open_rate = position[\"open_rate\"] positioned_value_in_base += float(amount) * float(open_rate)",
"target_transactions, positioned_value_in_qty): valid_positions = [] remain_qty = positioned_value_in_qty total_base =",
"sell_qty,)) print(\"valid_close_order[0]:\") print(valid_close_order) rate = None if \"rate\" in valid_close_order:",
"new order but DO_NOT_CREATE_NEW flag = true\") return False #",
"# うーん...現物とレバレッジで管理が結構変わるから同じクラスにするのはまずかった?ごちゃごちゃしてきてしまった # 時間的に約定時刻が近いpositionをまとめる def _group_near_transactions(self, target_transactions): grouped_positions = []",
"23755132, \"side\": \"buy\", \"rate\": \"10000.0\", \"amount\": \"1.0\", \"pending_amount\": \"0.0\", \"status\":",
"0.00001 and \\ abs(float(cur_amount)-float(possible_qty)) < 0.00001 and \\ cur_stoploss_float_or_none ==",
"= transaction[\"pair\"] if this_pair != self.pair: continue # check position",
"\"status\": \"cancel\", \"created_at\": \"2015-12-05T05:03:56.000Z\" } ] } ] } \"\"\"",
"x[\"id\"] in sell_ids, position[\"close_orders\"])) print(\"valid_close_order count = %d\" % len(valid_close_orders))",
"base_cur not in transaction[\"funds\"]: continue # this position is created",
"if position_type == \"buy\": position_type = \"long\" if position_type ==",
"target_value = self.price_decide_algorithm.sell_price_decide_algorithm(open_rate) target_value = adjust_price_to_tick(target_value, self.api.order.tick_price(self.pair)) self._update_or_create_close_order(position, target_value) #",
"self.positions.append(position) open_rate = position[\"open_rate\"] positioned_value_in_base += float(amount) * float(open_rate) #",
"abs(positioned_value_in_base) < self.api.order.tick_price(self.pair) * self.api.order.min_create_amount(self.pair) * 0.1: positioned_value_in_base = 0",
"print(\"sell order canceled but failed to create new sell order!!:",
"is_new_order_created) def _update_or_create_order(self, position_type, target_value, possible_qty, stop_loss_rate = None): assert",
"position_type is None: # algorithm says this instance should not",
"# merge position_id_to_sellids self.position_id_to_sellids = {} for position in valid_positions:",
"order!!\") try: print(ret_str) except Exception as e: print(\"failed to show",
"new_order = position[\"new_order\"] if new_order[\"status\"] == \"cancel\": print(\"new order: \"",
"ChartUpdaterByCoincheckWS from Util import BitcoinUtil def adjust_price_to_tick(price, tick): return price",
"True # target_value: sashine value. if None, market-make def _update_or_create_close_order(self,",
"that is self.order_id: new_order_id = int(transaction[\"order_id\"]) transaction[\"order_id\"] = new_order_id is_position_transaction",
"do something ret_str = self.api.order.cancel({\"id\": order_id, \"pair\": self.pair}) ret =",
"(self.get_max_total_position_price_of_base_currency(), self.positioned_price_base, self.other_reserved_base,)) #print(\"target_value = %f, possible_base = %f\" %",
"\"sell\" elif \"order_type\" in valid_close_order: is_cur_close_long = valid_close_order[\"order_type\"] == \"sell\"",
"failed_to_cancel: return False return True # target_value: sashine value. if",
"# target_value: sashine value. if None, market-make def _update_or_create_close_order(self, position,",
"False: # something error happened!! print(\"order cancel failed %d even",
"target_value: sashine value. if None, market-make def _update_or_create_close_order(self, position, target_value):",
"apis for current orders if order_id is None: print(\"order is",
"\"-8490.81029287\", \"new_order\": { \"id\": 23104033, \"side\": \"sell\", \"rate\": null, \"amount\":",
"not self.use_leverage: order_type = 'buy' if is_long else 'sell' order",
"pos_i, position in enumerate(positions): transaction_id = position[\"id\"] position_id_to_sellids[transaction_id] = list(map(lambda",
"possible_make_total_price_base_cur = self.get_max_total_position_price_of_base_currency() - self.positioned_price_base possible_make_total_price_base_cur = min(possible_make_total_price_base_cur, self.max_free_margin_of_base_currency) amount_tick",
"return self.pair.split(\"_\")[1].lower() def get_qty_currency(self): return self.pair.split(\"_\")[0].lower() # set usable jpy",
"[] all_transactions = valid_transaction_info positioned_value_in_qty = self.positioned_value_in_qty qty_cur = self.get_qty_currency()",
"'order_type': order_type, 'pair': self.pair } # not correct # this",
"is_close_long = True if position_type == \"short\": is_close_long = False",
"None return False # round to possible price tick =",
"transaction_id = position[\"id\"] position_id_to_sellids[transaction_id] = list(map(lambda x:x[\"id\"], self.exist_close_order_info_list)) position[\"close_orders\"] =",
"positioned_value_in_base += float(amount) * float(open_rate) # check close orders self.position_id_to_sellids[position_id]",
"check the same value or not if len(self.exist_order_info_list) == 1:",
"very near created_at transactions grouped_positions = self._group_near_transactions(positions) # remove closed",
"return new_order_created else: self._cancel_exist_all_buy_orders() print(\"algorithm wants to create a new",
"\"side\": \"sell\", \"rate\": null, \"amount\": null, \"pending_amount\": \"0\", \"status\": \"complete\",",
"== \"cancel\": print(\"new order: \" + str(new_order[\"id\"]) + \" state",
"in exist_order_info: cur_amount = exist_order_info[\"pending_amount\"] order_type = None if \"order_type\"",
"} \"\"\" #exist_order_ids = list(map(lambda x:x[\"id\"], valid_order_info)) exist_orders = []",
"'%.8f' % BitcoinUtil.roundBTCby1satoshi(sell_qty), 'position_id': position_id, 'order_type': 'close_long' if is_close_long else",
"in order: order[\"amount\"] = float(order[\"pending_amount\"]) position[\"close_orders\"][i] = order positions[pos_i] =",
"not True or \"id\" not in ret: print(\"Failed to create",
"if \"stop_loss_rate\" in exist_order_info else None cur_stoploss_float_or_none = None if",
"= %d\" % len(valid_close_orders)) if len(valid_close_orders) == 1 and target_value",
"target_value) = decide_make_ret if target_value is None or position_type is",
"value or not if len(self.exist_order_info_list) == 1: exist_order_info = self.exist_order_info_list[0]",
"ret[\"id\"] is None: print(\"sell order canceled but failed to create",
"= self._update_or_create_order(position_type, target_value, possible_amount, stop_loss_rate=stoploss_rate) return new_order_created else: self._cancel_exist_all_buy_orders() print(\"algorithm",
"orders according to current positions # this class should be",
"created_time amount = position[\"amount\"] all_amount = position[\"all_amount\"] if all_amount is",
"p[\"amount\"] * p[\"open_rate\"] ret_pos[\"amount\"] = total_amount ret_pos[\"open_rate\"] = total_jpy /",
"self.use_leverage: order = { 'amount': '%.8f' % BitcoinUtil.roundBTCby1satoshi(sell_qty), 'position_id': position_id,",
"by desc # concat very near created_at transactions grouped_positions =",
"の場合のみ) self.__pair = pair self.price_decide_algorithm = price_decide_algorithm print(\"PositionTrader: inst=\" +",
"in self.exist_order_info_list: self._cancel_order(exist_order_info[\"id\"]) self.exist_order_info_list = None return False # round",
"None: # check the same value or not if len(self.exist_order_info_list)",
"order = { 'amount': '%.8f' % BitcoinUtil.roundBTCby1satoshi(sell_qty), 'order_type': 'sell', 'pair':",
"if \"rate\" in exist_order_info else None # get current stoploss",
"sell_ids, position[\"close_orders\"])) print(\"valid_close_order count = %d\" % len(valid_close_orders)) if len(valid_close_orders)",
"positions # this class should be called after update_status def",
"round to possible price tick = self.api.order.tick_price(self.pair) target_value = adjust_price_to_tick(target_value,",
"positioned not be grouped grouped_positions.append(grouping(positions[concat_start_index:])) return grouped_positions # まだcloseされていないtransactionだけを残す def",
"transaction_id # check only new id if self.last_checked_transaction_id >= transaction_id:",
"\\ cur_stoploss_float_or_none == target_stoploss_float_or_none and \\ order_type == position_type: #",
"None) position_type = None target_value = None stoploss_rate = None",
"for idx, pos in enumerate(positions): cur_created_at = pos[\"created_at_datetime\"] if abs((cur_created_at",
"{ \"id\": 10, \"pair\": \"btc_jpy\", \"status\": \"open\", \"created_at\": \"2015-12-02T05:27:53.000Z\", \"closed_at\":",
"# check current status and make new positions according to",
"self.last_checked_transaction_id >= transaction_id: continue last_transaction_id_in_this_frame = max(last_transaction_id_in_this_frame, transaction_id) # check",
"'sell', 'pair': self.pair, } if target_value is None: # market_sell",
"adjust_amount_to_tick(possible_amount,amount_tick) print(\"possible_create_in_base = %f, want to make amount in base",
"(array of \"data\" will be passed) { \"data\": [ {",
"None: for pos_i, position in enumerate(positions): transaction_id = position[\"id\"] position_id_to_sellids[transaction_id]",
"sell_id in sell_ids: self._cancel_order(sell_id) self.position_id_to_sellids[position_id] = [] # make new",
"def update_close_orders(self, chart, current_time_timezone_aware): for position in self.positions: open_rate =",
"} ] } \"\"\" #exist_order_ids = list(map(lambda x:x[\"id\"], valid_order_info)) exist_orders",
"order. do nothing print(\"You already ordered this order: rate=%.1f, amount=%f,",
"p): self.max_free_margin_of_base_currency = p def get_max_total_position_price_base(self): return self.get_max_total_position_price_of_base_currency() def get_max_total_position_price_of_base_currency(self):",
"< 0.00001 and \\ cur_stoploss_float_or_none == target_stoploss_float_or_none and \\ order_type",
"for position in self.positions: open_rate = float(position[\"open_rate\"]) amount = float(position[\"amount\"])",
"# this class should be called after update_status def update_close_orders(self,",
"transaction_id = int(transaction[\"id\"]) # transaction_id means position_id transaction[\"id\"] = transaction_id",
"positioned_value_in_qty): valid_positions = [] remain_qty = positioned_value_in_qty total_base = 0",
"exist_order_i < len(self.exist_order_info_list): exist_order_info = self.exist_order_info_list[exist_order_i] if self._cancel_order(exist_order_info[\"id\"]) is False:",
"print(\"failed to show returned json str\") print(e) if ret is",
"% (min_qty, possible_qty,)) return False, False # make new order",
"min(possible_make_total_price_base_cur, self.max_free_margin_of_base_currency) amount_tick = self.api.order.tick_amount(self.pair) possible_amount = 1.0 * possible_make_total_price_base_cur",
"= \"long\" if position_type == \"sell\": position_type = \"short\" is_close_long",
"is not None: for pos_i, position in enumerate(positions): transaction_id =",
"[] remain_qty = positioned_value_in_qty total_base = 0 for position in",
"set usable jpy (available_margin + reserved_margin + (positioned)) def set_max_total_position_price_base(self,",
"+ \" state is 'cancel'. probably partially contracted and remain",
"< min_qty: print(\"Minimum order btc = %f, you requested =",
"[] exist_close_orders = [] other_orders = [] for idx, order",
"self.get_base_currency() last_transaction_id_in_this_frame = self.last_checked_transaction_id for transaction in all_transactions: transaction_id =",
"False # cancel all exist orders if not self._cancel_exist_all_buy_orders(): return",
"= 'leverage_buy' if is_long else 'leverage_sell' if not self.use_leverage: order_type",
"[] positions = target_transactions if len(positions) > 0: def grouping(desced_position_array):",
"= order[\"pair\"] is_added = False if order_pair == self.pair: if",
"* 0.1: positioned_value_in_base = 0 # merge position_id_to_sellids self.position_id_to_sellids =",
"self.positions = valid_positions print(\"position_count=%d, positioned_%s=%f, positioned_%s=%f\" % (len(self.positions), base_cur, self.positioned_price_base,",
"[] self.position_id_to_sellids = {} self.got_all_order_ids = [] self.got_close_order_ids = []",
"you requested = %f\" % (min_qty, possible_qty,)) return False, False",
"usable jpy (available_margin + reserved_margin + (positioned)) def set_max_total_position_price_base(self, p):",
"= p def set_max_free_margin_of_base_currency(self, p): self.max_free_margin_of_base_currency = p def get_max_total_position_price_base(self):",
"] } \"\"\" #exist_order_ids = list(map(lambda x:x[\"id\"], valid_order_info)) exist_orders =",
"sorted(positions, key=lambda x:-x[\"id\"]) # order by desc # concat very",
"be called after update_status def update_close_orders(self, chart, current_time_timezone_aware): for position",
"# can group prev_created_at = cur_created_at continue # this position",
"on exchanger valid_close_order = valid_close_orders[0] print(\"your order: rate=%f, amount=%f\" %",
"len(self.exist_order_info_list) == 1: exist_order_info = self.exist_order_info_list[0] cur_rate = exist_order_info[\"rate\"] if",
"= position_type == \"long\" order_type = 'leverage_buy' if is_long else",
"= \\ list(map(lambda x:x[\"id\"], filter(lambda x:x[\"status\"] != \"cancel\", position[\"close_orders\"]))) self.positioned_price_base",
"margin self.positions = [] self.position_id_to_sellids = {} self.got_all_order_ids = []",
"in target_transactions: if remain_qty <= 0: break amount = position[\"amount\"]",
"== \"sell\" elif \"order_type\" in valid_close_order: is_cur_close_long = valid_close_order[\"order_type\"] ==",
"= adjust_amount_to_tick(possible_amount,amount_tick) print(\"possible_create_in_base = %f, want to make amount in",
"small value if abs(positioned_value_in_qty) < self.api.order.min_create_amount(self.pair)*0.1: positioned_value_in_qty = 0 positions",
"position_type = \"long\" if position_type == \"sell\": position_type = \"short\"",
"price - math.fmod(price, tick) def adjust_amount_to_tick(amount, tick): return amount -",
"total maximum position size in base currency self.positioned_price_base = 0",
"= position[\"id\"] position_id_to_sellids[transaction_id] = list(map(lambda x:x[\"id\"], self.exist_close_order_info_list)) position[\"close_orders\"] = self.exist_close_order_info_list",
"# check minimum btc min_qty = self.api.order.min_create_amount(self.pair) if possible_qty <",
"(position_type, target_value) = decide_make_ret if target_value is None or position_type",
"current_time_timezone_aware) is True: # market order close pass else: target_value",
"cur_stoploss is not None: cur_stoploss_float_or_none = float(cur_stoploss) target_stoploss_float_or_none = None",
"except Exception as e: print(\"failed to print returned error json\")",
"= float(valid_close_order[\"rate\"]) amount = valid_close_order[\"amount\"] is_cur_close_long = False if \"side\"",
"= position[\"all_amount\"] = amount self.positions.append(position) open_rate = position[\"open_rate\"] positioned_value_in_base +=",
"filter(lambda x:x[\"status\"] != \"cancel\", position[\"close_orders\"]))) self.positioned_price_base = positioned_value_in_base def _update_transaction_status(self,",
"print(\"order is already canceled\") return True # do something ret_str",
"api: e.g. instance of CoinCheck self.use_leverage = use_leverage self.timelimit_to_grouping_transaction =",
"= %f, want to make amount in base = %f,",
"transaction[\"order_id\"] = new_order_id is_position_transaction = new_order_id in self.got_all_order_ids is_close_transaction =",
"except: print(\"failed to parse api.order.create result\") try: print(ret_str) except Exception",
"valid_positions print(\"position_count=%d, positioned_%s=%f, positioned_%s=%f\" % (len(self.positions), base_cur, self.positioned_price_base, qty_cur, self.positioned_value_in_qty,))",
"happened!! print(\"order cancel failed %d even if there is a",
"is a valid order in internal state\" % (exist_order_info[\"id\"],)) failed_to_cancel",
"exist_order_info: if exist_order_info[\"order_type\"] == \"buy\" or\\ exist_order_info[\"order_type\"] == \"leverage_buy\": order_type",
"= 0 for position in target_transactions: if remain_qty <= 0:",
"the same value or not if len(self.exist_order_info_list) == 1: exist_order_info",
"real positions status to this instance # レバレッジ用 if not",
"# 既にこの段階で解決できるポジション状態(close order id見て、それがあれば反対売買が成立している) # を用い、↑で貯めたpositionsから、反対売買済みのものを(amount基準で)消していき(前回フレームで残っていたpositionも含めて)、残ったpositionだけを生きているポジションとし、1つに集約する(現物用なので、idが分かれている意味はない) # その残ったpositionID, 消費した反対売買IDのIDを持っておき、次回からはそれより新しいIDのみを反映する #",
"to make (price,amount) = (%f,%f) but too few amount\" %",
"self.last_checked_transaction_id will be checked self.last_checked_transaction_id = last_transaction_id_in_this_frame print(\"last_checked_transaction_id = \",",
"& update positioned_value_in_jpy valid_positions, positioned_value_in_base = self._remain_non_closed_transactions(grouped_positions, positioned_value_in_qty) if abs(positioned_value_in_base)",
"{ \"id\": 38632107, \"order_type\": \"buy\", \"rate\": null, \"pair\": \"btc_jpy\", \"pending_amount\":",
"'close_long' if is_close_long else 'close_short', 'pair': 'btc_jpy', } if target_value",
"already ordered this order: rate=%.1f, amount=%f, stoploss_rate=%s, position_type=%s\" % (target_value,",
"\"created_at\": \"2015-12-02T05:27:53.000Z\", \"closed_at\": null, \"open_rate\": \"43553.0\", \"closed_rate\": null, \"amount\": \"1.51347797\",",
"= float(position[\"open_rate\"]) amount = float(position[\"amount\"]) created_time = position[\"created_at_datetime\"] target_value =",
"if remain_qty <= 0: break amount = position[\"amount\"] if remain_qty",
"self.get_qty_currency() base_cur = self.get_base_currency() last_transaction_id_in_this_frame = self.last_checked_transaction_id for transaction in",
"\"order_type\": \"sell\", \"stop_loss_rate\": null, \"pair\": \"btc_jpy\", \"created_at\": \"2015-01-10T05:55:38.000Z\" \"\"\" is_long",
"in all_transactions: transaction_id = int(transaction[\"id\"]) # transaction_id means position_id transaction[\"id\"]",
"ret_str) return True, True def _cancel_exist_all_buy_orders(self): failed_to_cancel = False exist_order_i",
"self.max_total_position_price_base = 0 # total maximum position size in base",
"\\ exist_order_info[\"order_type\"] == \"leverage_sell\": order_type = \"short\" if cur_rate is",
"not True or \"id\" not in ret: print(\"Failed to cancel",
"%f, you requested = %f\" % (min_qty, possible_qty,)) return False,",
"[ret] self.got_all_order_ids.append(ret[\"id\"]) # remove very old orders if len(self.got_all_order_ids) >",
"means position_id transaction[\"id\"] = transaction_id # check only new id",
"\"side\": \"buy\", \"rate\": \"10000.0\", \"amount\": \"1.0\", \"pending_amount\": \"0.0\", \"status\": \"cancel\",",
"+ \", pair=\" + str(pair)) @property def pair(self): return self.__pair",
"if self.use_leverage: self._update_position_status(valid_position_info) else: self._update_transaction_status(valid_transaction_info) def _update_position_status(self, valid_position_info): # apply",
"get_max_total_position_price_of_base_currency(self): return self.max_total_position_price_base def get_positioned_price_base(self): return self.positioned_price_base def set_timelimit_to_grouping_transaction(self, timelimit_to_grouping_transaction):",
"position[\"new_order\"] if new_order[\"status\"] == \"cancel\": print(\"new order: \" + str(new_order[\"id\"])",
"order = { 'amount': '%.8f' % BitcoinUtil.roundBTCby1satoshi(sell_qty), 'position_id': position_id, 'order_type':",
"order_id, \"pair\": self.pair}) ret = None if ret_str is not",
"this position cannot be grouped. make a new group from",
"others = %f\" % (self.get_max_total_position_price_of_base_currency(), self.positioned_price_base, self.other_reserved_base,)) #print(\"target_value = %f,",
"exist_orders) print(\"exist_close_orders\", exist_close_orders) self.exist_order_info_list = exist_orders if len(exist_orders) > 0",
"(min_qty, possible_qty,)) return False, False # make new order \"\"\"",
"self.use_leverage: order_type = 'buy' if is_long else 'sell' order =",
"\"amount\": \"1.3\", \"order_type\": \"sell\", \"stop_loss_rate\": null, \"pair\": \"btc_jpy\", \"created_at\": \"2015-01-10T05:55:38.000Z\"",
"idx prev_created_at = cur_created_at # remain positioned not be grouped",
"in base currency (actually paired currency) self.positioned_value_in_qty = 0 #",
"valid_close_order: is_cur_close_long = valid_close_order[\"side\"] == \"sell\" elif \"order_type\" in valid_close_order:",
"all for sell_id in sell_ids: self._cancel_order(sell_id) self.position_id_to_sellids[position_id] = [] #",
"def _update_or_create_order(self, position_type, target_value, possible_qty, stop_loss_rate = None): assert (self.api",
"if new_order[\"status\"] == \"cancel\": print(\"new order: \" + str(new_order[\"id\"]) +",
"self.got_close_order_ids if not is_position_transaction and not is_close_transaction: continue # other",
"is_long = position_type == \"long\" order_type = 'leverage_buy' if is_long",
"possible_make_total_price_base_cur, possible_amount)) #print(\"base_cur = %f, positioned = %f, others =",
"= sell_ids self.got_close_order_ids.append(ret[\"id\"]) if len(self.got_close_order_ids) > 500: self.got_close_order_ids = self.got_close_order_ids[-500:]",
"_cancel_exist_all_buy_orders(self): failed_to_cancel = False exist_order_i = 0 while exist_order_i <",
"p def set_max_free_margin_of_base_currency(self, p): self.max_free_margin_of_base_currency = p def get_max_total_position_price_base(self): return",
"not do_not_create_new_order: success, new_order_created = self._update_or_create_order(position_type, target_value, possible_amount, stop_loss_rate=stoploss_rate) return",
"if cur_stoploss is not None: cur_stoploss_float_or_none = float(cur_stoploss) target_stoploss_float_or_none =",
"if position_id not in self.position_id_to_sellids: return False sell_qty = float(position[\"amount\"])",
"exist_order_info[\"order_type\"] == \"leverage_sell\": order_type = \"short\" if cur_rate is not",
"def update_status(self, valid_position_info, valid_transaction_info, valid_order_info): # update position/order status (assume:",
"True min_qty = self.api.order.min_create_amount(self.pair) if sell_qty < min_qty: qty_cur =",
"is not None: cur_stoploss_float_or_none = float(cur_stoploss) target_stoploss_float_or_none = None if",
"base currency self.positioned_price_base = 0 # total position price in",
"= 0 for p in desced_position_array: total_amount += p[\"amount\"] total_jpy",
"make a new group from pos[start_index] - pos[idx-1] grouped_positions.append(grouping(positions[concat_start_index:idx])) #print(grouped_positions[-1])",
"already canceled\") return True # do something ret_str = self.api.order.cancel({\"id\":",
"possible_amount)) #print(\"base_cur = %f, positioned = %f, others = %f\"",
"self.position_id_to_sellids = {} for position in valid_positions: pos_id = position[\"id\"]",
"'order_type': 'close_long' if is_close_long else 'close_short', 'pair': 'btc_jpy', } if",
"False if order_pair == self.pair: if order_id in self.got_all_order_ids: is_added",
"\"2015-12-05T05:03:56.000Z\" } ] } ] } \"\"\" #### # parse",
"self.position_id_to_sellids = {} all_positions = valid_position_info positioned_value_in_base = 0 for",
"if stop_loss_rate is not None: order[\"stop_loss_rate\"] = stop_loss_rate ret_str =",
"target_value = adjust_price_to_tick(target_value, tick) if stoploss_rate is not None: stoploss_rate",
"= adjust_price_to_tick(target_value, self.api.order.tick_price(self.pair)) self._update_or_create_close_order(position, target_value) # interface to update internal",
"to create new sell order!!: position id: %s\" % (str(position_id),))",
"= position[\"all_amount\"] if all_amount is not None and all_amount <",
"target_value, stoploss_rate) = decide_make_ret else: (position_type, target_value) = decide_make_ret if",
"positioned_value_in_qty self.position_id_to_sellids = position_id_to_sellids self.positions = valid_positions print(\"position_count=%d, positioned_%s=%f, positioned_%s=%f\"",
"positions status to this instance # レバレッジ用 if not self.use_leverage:",
"try: ret = json.loads(ret_str) except: print(\"failed to parse api.order.create result\")",
"valid_positions, positioned_value_in_base = self._remain_non_closed_transactions(grouped_positions, positioned_value_in_qty) if abs(positioned_value_in_base) < self.api.order.tick_price(self.pair) *",
"to make amount in base = %f, possible amount =",
"if len(valid_close_orders) == 1 and target_value is not None: #",
"!= \"cancel\", position[\"close_orders\"]))) self.positioned_price_base = positioned_value_in_base def _update_transaction_status(self, valid_transaction_info): if",
"%d\" % len(valid_close_orders)) if len(valid_close_orders) == 1 and target_value is",
"target value and amount are completely same, do not pass",
"print(\"algorithm wants to create a new order but DO_NOT_CREATE_NEW flag",
"position[\"close_orders\"][i] = order positions[pos_i] = position # round very small",
"passed) { \"data\": [ { \"id\": 10, \"pair\": \"btc_jpy\", \"status\":",
"tick = self.api.order.tick_price(self.pair) target_value = adjust_price_to_tick(target_value, tick) if stoploss_rate is",
"position[\"pair\"] if pair != self.pair: continue position_id = position[\"id\"] #",
"\"id\": 12345, \"rate\": \"30010.0\", \"amount\": \"1.3\", \"order_type\": \"sell\", \"stop_loss_rate\": null,",
"= p def get_max_total_position_price_base(self): return self.get_max_total_position_price_of_base_currency() def get_max_total_position_price_of_base_currency(self): return self.max_total_position_price_base",
"self.exist_order_info_list = None return False # round to possible price",
"valid_transaction_info positioned_value_in_qty = self.positioned_value_in_qty qty_cur = self.get_qty_currency() base_cur = self.get_base_currency()",
"is_close_long = True if position_type == \"long\": is_close_long = True",
"を用い、↑で貯めたpositionsから、反対売買済みのものを(amount基準で)消していき(前回フレームで残っていたpositionも含めて)、残ったpositionだけを生きているポジションとし、1つに集約する(現物用なので、idが分かれている意味はない) # その残ったpositionID, 消費した反対売買IDのIDを持っておき、次回からはそれより新しいIDのみを反映する # ただし、ずっと続けると計算誤差がたまるので、jpyもしくはbtcベースでその合計値が極めて小さくなったら丸めてノーポジ扱いにする # うーん...現物とレバレッジで管理が結構変わるから同じクラスにするのはまずかった?ごちゃごちゃしてきてしまった # 時間的に約定時刻が近いpositionをまとめる",
"a value >= stop_loss_rate, sashine will be placed at \"rate\"",
"sell_ids = self.position_id_to_sellids[position_id] position_type = position[\"side\"] # convert position type",
"= new_order[\"id\"] if new_order_id in self.got_all_order_ids: # this position is",
"transaction[\"pair\"] if this_pair != self.pair: continue # check position that",
"if ret is not None: try: ret = json.loads(ret) except:",
"None: stoploss_rate = adjust_price_to_tick(stoploss_rate, tick) # !!round to possible amount",
"total_jpy / total_amount return ret_pos concat_start_index = 0 prev_created_at =",
"\"\"\" orders example (array of \"orders\" will be passed) {",
"pair self.price_decide_algorithm = price_decide_algorithm print(\"PositionTrader: inst=\" + str(self) + \",",
"json.loads(ret_str) except: print(\"failed to parse api.order.create result\") try: print(ret_str) except",
"self.position_id_to_sellids[position_id] = sell_ids self.got_close_order_ids.append(ret[\"id\"]) if len(self.got_close_order_ids) > 500: self.got_close_order_ids =",
"from pos[start_index] - pos[idx-1] grouped_positions.append(grouping(positions[concat_start_index:idx])) #print(grouped_positions[-1]) concat_start_index = idx prev_created_at",
"None: try: ret = json.loads(ret_str) except: print(\"failed to parse api.order.create",
"self.pair: continue # check position that is created by the",
"= json.loads(ret_str) except: print(\"failed to parse cancel order ret str\")",
"+= float(amount) * float(open_rate) # check close orders self.position_id_to_sellids[position_id] =",
"this position is created by this class's order created_time =",
"if len(exist_orders) > 0 else None self.exist_close_order_info_list = exist_close_orders if",
"open_rate = float(transaction[\"open_rate\"]) positioned_value_in_qty += float(qty_amount) created_time = dateutil.parser.parse(transaction[\"created_at\"]) transaction[\"created_at_datetime\"]",
"\"amount\": null, \"pending_amount\": \"0\", \"status\": \"complete\", \"created_at\": \"2015-12-02T05:27:52.000Z\" }, \"close_orders\":",
"is True: # market order close pass else: target_value =",
"= [] other_orders = [] for idx, order in enumerate(valid_order_info):",
"import BitcoinUtil def adjust_price_to_tick(price, tick): return price - math.fmod(price, tick)",
"= 0 # max free margin. we cannot use orders",
"if None, market-make def _update_or_create_close_order(self, position, target_value): position_id = position[\"id\"]",
"true\") return False # update close orders according to current",
"== \"leverage_sell\": order_type = \"short\" if cur_rate is not None",
"ret val example \"success\": true, \"id\": 12345, \"rate\": \"30010.0\", \"amount\":",
"len(valid_close_orders)) if len(valid_close_orders) == 1 and target_value is not None:",
"# apply real positions status to this instance # レバレッジ用",
"enumerate(positions): transaction_id = position[\"id\"] position_id_to_sellids[transaction_id] = list(map(lambda x:x[\"id\"], self.exist_close_order_info_list)) position[\"close_orders\"]",
"ただし、前フレームからの情報を引き継ぐところがupdate_position_statusと違う (現物にはpositionという概念が無い) positions = self.positions position_id_to_sellids = self.position_id_to_sellids close_transactions =",
"update_status def update_close_orders(self, chart, current_time_timezone_aware): for position in self.positions: open_rate",
"position is not ignored\") #continue new_order_id = new_order[\"id\"] if new_order_id",
"0.00001 and \\ cur_stoploss_float_or_none == target_stoploss_float_or_none and \\ order_type ==",
"and target_value is not None: # check the order is",
"self._cancel_order(sell_id) self.position_id_to_sellids[position_id] = [] # make new order order =",
"= True exist_orders.append(order) elif order_id in self.got_close_order_ids: is_added = True",
"position_type = \"short\" is_close_long = True if position_type == \"long\":",
"or base_cur not in transaction[\"funds\"]: continue # this position is",
"max(last_transaction_id_in_this_frame, transaction_id) # check pair this_pair = transaction[\"pair\"] if this_pair",
"update_status(self, valid_position_info, valid_transaction_info, valid_order_info): # update position/order status (assume: pagenations",
"price in base currency (actually paired currency) self.positioned_value_in_qty = 0",
"\"sell\", \"rate\": 26990, \"pair\": \"btc_jpy\", \"pending_amount\": \"0.77\", \"pending_market_buy_amount\": null, \"stop_loss_rate\":",
"= \"short\" if cur_rate is not None and cur_amount is",
"cur_amount = exist_order_info[\"pending_amount\"] order_type = None if \"order_type\" in exist_order_info:",
"{} for position in valid_positions: pos_id = position[\"id\"] self.position_id_to_sellids[pos_id] =",
"= position[\"new_order\"] if new_order[\"status\"] == \"cancel\": print(\"new order: \" +",
"= total_amount ret_pos[\"open_rate\"] = total_jpy / total_amount return ret_pos concat_start_index",
"= self.price_decide_algorithm.decide_make_position_order(chart) if len(decide_make_ret) == 3: (position_type, target_value, stoploss_rate) =",
"\"pl\": \"-8490.81029287\", \"new_order\": { \"id\": 23104033, \"side\": \"sell\", \"rate\": null,",
"this_pair = transaction[\"pair\"] if this_pair != self.pair: continue # check",
"# check the same value or not if len(self.exist_order_info_list) ==",
"# update close orders according to current positions # this",
"to print error\") print(e) if ret is None or ret[\"success\"]",
"'position_id': position_id, 'order_type': 'close_long' if is_close_long else 'close_short', 'pair': 'btc_jpy',",
"not in transaction[\"funds\"] or base_cur not in transaction[\"funds\"]: continue #",
"possible_make_total_price_base_cur,)) if possible_amount <= 0.000001: # too few btc print(\"want",
"\"rate\": 26890, \"pair\": \"btc_jpy\", \"pending_amount\": \"0.5527\", \"pending_market_buy_amount\": null, \"stop_loss_rate\": null,",
"self.exist_order_info_list is not None: # check the same value or",
"print(\"Minimum order btc = %f, you requested = %f\" %",
"order cannot make short position!\") print(\"you passed close 'short' for",
"a new group from pos[start_index] - pos[idx-1] grouped_positions.append(grouping(positions[concat_start_index:idx])) #print(grouped_positions[-1]) concat_start_index",
"# api: e.g. instance of CoinCheck self.use_leverage = use_leverage self.timelimit_to_grouping_transaction",
"new order \"\"\" ret val example \"success\": true, \"id\": 12345,",
"rate=%f, amount=%f\" % (target_value, sell_qty,)) print(\"valid_close_order[0]:\") print(valid_close_order) rate = None",
"remain positioned not be grouped grouped_positions.append(grouping(positions[concat_start_index:])) return grouped_positions # まだcloseされていないtransactionだけを残す",
"ordered on server:\") print(\" position id:%s, target_value:%s, amount:%s, close_long:%s\" %",
"len(self.exist_order_info_list): exist_order_info = self.exist_order_info_list[exist_order_i] if self._cancel_order(exist_order_info[\"id\"]) is False: # something",
"not None: try: ret = json.loads(ret) except: print(\"failed to parse",
"None # get current stoploss cur_stoploss = exist_order_info[\"stop_loss_rate\"] if \"stop_loss_rate\"",
"position/order status (assume: pagenations are already cleared) self._update_order_id_status(valid_order_info) if self.use_leverage:",
"stop_loss_rate is not None: order[\"stop_loss_rate\"] = stop_loss_rate ret_str = self.api.order.create(order)",
"for sell_id in sell_ids: self._cancel_order(sell_id) self.position_id_to_sellids[position_id] = [] # make",
"position_id transaction[\"id\"] = transaction_id # check only new id if",
"def get_max_total_position_price_base(self): return self.get_max_total_position_price_of_base_currency() def get_max_total_position_price_of_base_currency(self): return self.max_total_position_price_base def get_positioned_price_base(self):",
"import Chart from ChartUpdaterByCCWebsocket import ChartUpdaterByCoincheckWS from Util import BitcoinUtil",
"\"cancel\": print(\"new order: \" + str(new_order[\"id\"]) + \" state is",
"not None: try: ret = json.loads(ret_str) except: print(\"failed to parse",
"this class's order created_time = dateutil.parser.parse(position[\"created_at\"]) position[\"created_at_datetime\"] = created_time amount",
"list(filter(lambda x:x[\"status\"] != \"cancel\" and x[\"id\"] in sell_ids, position[\"close_orders\"])) print(\"valid_close_order",
"2 # 約定時刻がこの秒数以下なら同一ポジションとみなす(use_leverage == False の場合のみ) self.__pair = pair self.price_decide_algorithm",
"= None if self.price_decide_algorithm.market_sell_decide_algorithm(chart, open_rate, created_time, current_time_timezone_aware) is True: #",
"0 self.api = api # api: e.g. instance of CoinCheck",
"close pass else: target_value = self.price_decide_algorithm.sell_price_decide_algorithm(open_rate) target_value = adjust_price_to_tick(target_value, self.api.order.tick_price(self.pair))",
"target_transactions if len(positions) > 0: def grouping(desced_position_array): ret_pos = dict(desced_position_array[0])",
"and \\ abs(float(amount)-float(sell_qty)) < 0.00001 and \\ is_close_long == is_cur_close_long:",
"valid order in internal state\" % (exist_order_info[\"id\"],)) failed_to_cancel = True",
"sell_qty = float(position[\"amount\"]) sell_ids = self.position_id_to_sellids[position_id] position_type = position[\"side\"] #",
"on server:\") print(\" position id:%s, target_value:%s, amount:%s, close_long:%s\" % (str(position_id),",
"# market_sell order['order_type'] = \"market_sell\" else: order['rate'] = target_value ret",
"or position_type is None: # algorithm says this instance should",
"position_id_to_sellids[transaction_id] = [] transaction[\"close_orders\"] = [] positions.append(transaction) else: close_transactions.append(transaction) #",
"exist_order_info: cur_amount = exist_order_info[\"amount\"] elif \"pending_amount\" in exist_order_info: cur_amount =",
"] } \"\"\" #### # parse positions #### self.positions =",
"if target_value is None or position_type is None: # algorithm",
"self.exist_close_order_info_list = exist_close_orders if len(exist_close_orders) > 0 else None #self.other_reserved_base",
"not None: stoploss_rate = adjust_price_to_tick(stoploss_rate, tick) # !!round to possible",
"= positioned_value_in_base self.positioned_value_in_qty = positioned_value_in_qty self.position_id_to_sellids = position_id_to_sellids self.positions =",
"id:%s, target_value:%s, amount:%s, close_long:%s\" % (str(position_id), str(target_value), str(amount), str(is_cur_close_long),)) return",
"market_sell order['order_type'] = \"market_sell\" else: order['rate'] = target_value ret =",
"check the order is already created on exchanger valid_close_order =",
"get_positioned_price_base(self): return self.positioned_price_base def set_timelimit_to_grouping_transaction(self, timelimit_to_grouping_transaction): self.timelimit_to_grouping_transaction = timelimit_to_grouping_transaction #",
"\"10000.0\", \"stop_loss_rate\": \"50000.0\", \"created_at\": \"2016-02-23T12:14:50.000Z\" } ] } \"\"\" #exist_order_ids",
"be passed) { \"data\": [ { \"id\": 10, \"pair\": \"btc_jpy\",",
"%f\" % (qty_cur, min_qty, sell_qty,)) return False # cancel all",
"if not self.use_leverage: order_type = 'buy' if is_long else 'sell'",
"\"order_type\" in exist_order_info: if exist_order_info[\"order_type\"] == \"buy\" or\\ exist_order_info[\"order_type\"] ==",
"price tick = self.api.order.tick_price(self.pair) target_value = adjust_price_to_tick(target_value, tick) if stoploss_rate",
"print(\"Failed to cancel order %s: %s\" % (str(order_id), str(ret_str),)) return",
"after update_status def update_new_orders(self, chart, do_not_create_new_order=False): assert (self.price_decide_algorithm is not",
"dateutil.parser import json from ChartBars import Chart from ChartUpdaterByCCWebsocket import",
"\", pair=\" + str(pair)) @property def pair(self): return self.__pair def",
"\"buy\", \"rate\": \"10000.0\", \"amount\": \"1.0\", \"pending_amount\": \"0.0\", \"status\": \"cancel\", \"created_at\":",
"be passed) { \"success\": true, \"orders\": [ { \"id\": 202835,",
"is_close_long else 'close_short', 'pair': 'btc_jpy', } if target_value is not",
"is created by the new_order that is self.order_id: new_order =",
"new group from pos[start_index] - pos[idx-1] grouped_positions.append(grouping(positions[concat_start_index:idx])) #print(grouped_positions[-1]) concat_start_index =",
"target_value is None or position_type is None: # algorithm says",
"= [] for idx, order in enumerate(valid_order_info): order_id = order[\"id\"]",
"error\") print(e) if ret is None or ret[\"success\"] is not",
"# remove closed position & update positioned_value_in_jpy valid_positions, positioned_value_in_base =",
"set_max_total_position_price_base(self, p): self.set_max_total_position_price_of_base_currency(p) def set_max_total_position_price_of_base_currency(self, p): self.max_total_position_price_base = p def",
"#print(\"base_cur = %f, positioned = %f, others = %f\" %",
"show returned json str\") print(e) if ret is None or",
"stoploss cur_stoploss = exist_order_info[\"stop_loss_rate\"] if \"stop_loss_rate\" in exist_order_info else None",
"self.api.order.min_create_amount(self.pair) if possible_qty < min_qty: print(\"Minimum order btc = %f,",
"will be passed) { \"data\": [ { \"id\": 10, \"pair\":",
"server:\") print(\" position id:%s, target_value:%s, amount:%s, close_long:%s\" % (str(position_id), str(target_value),",
"# check pair this_pair = transaction[\"pair\"] if this_pair != self.pair:",
"exist_order_i += 1 if len(self.exist_order_info_list) == 0: self.exist_order_info_list = None",
"} if target_value is not None: order['rate'] = target_value else:",
"True: # market order close pass else: target_value = self.price_decide_algorithm.sell_price_decide_algorithm(open_rate)",
"\"pending_market_buy_amount\": null, \"stop_loss_rate\": null, \"created_at\": \"2015-01-10T05:55:38.000Z\" }, { \"id\": 38632107,",
"None: order[\"stop_loss_rate\"] = stop_loss_rate ret_str = self.api.order.create(order) ret = None",
"amount = position[\"amount\"] if remain_qty >= amount: remain_qty -= amount",
"value if abs(positioned_value_in_qty) < self.api.order.min_create_amount(self.pair)*0.1: positioned_value_in_qty = 0 positions =",
"amount = position[\"amount\"] all_amount = position[\"all_amount\"] if all_amount is not",
"order is always \"sell\" if not is_close_long: print(\"normal order cannot",
"def update_new_orders(self, chart, do_not_create_new_order=False): assert (self.price_decide_algorithm is not None) position_type",
"if len(self.got_all_order_ids) > 500: self.got_all_order_ids = self.got_all_order_ids[-500:] print(\"order success!\", ret_str)",
"of CoinCheck self.use_leverage = use_leverage self.timelimit_to_grouping_transaction = 2 # 約定時刻がこの秒数以下なら同一ポジションとみなす(use_leverage",
"= new_order_id is_position_transaction = new_order_id in self.got_all_order_ids is_close_transaction = new_order_id",
"position[\"created_at_datetime\"] = created_time amount = position[\"amount\"] all_amount = position[\"all_amount\"] if",
"count = %d\" % len(valid_close_orders)) if len(valid_close_orders) == 1 and",
"return self.get_max_total_position_price_of_base_currency() def get_max_total_position_price_of_base_currency(self): return self.max_total_position_price_base def get_positioned_price_base(self): return self.positioned_price_base",
"pagenations are already cleared) self._update_order_id_status(valid_order_info) if self.use_leverage: self._update_position_status(valid_position_info) else: self._update_transaction_status(valid_transaction_info)",
"json.loads(ret_str) except: print(\"failed to parse cancel order ret str\") try:",
"self._update_order_id_status(valid_order_info) if self.use_leverage: self._update_position_status(valid_position_info) else: self._update_transaction_status(valid_transaction_info) def _update_position_status(self, valid_position_info): #",
"position[\"amount\"] = remain_qty remain_qty = 0 valid_positions.append(position) total_base += position[\"amount\"]",
"True if position_type == \"short\": is_close_long = False # check",
"self._group_near_transactions(positions) # remove closed position & update positioned_value_in_jpy valid_positions, positioned_value_in_base",
"position price in base currency (actually paired currency) self.positioned_value_in_qty =",
"#### # parse orders #### \"\"\" orders example (array of",
"order = { 'rate': \"%.8f\" % target_value, 'amount': \"%.8f\" %",
"new_order_id = new_order[\"id\"] if new_order_id in self.got_all_order_ids: # this position",
"exist_order_info else None cur_stoploss_float_or_none = None if cur_stoploss is not",
"group from pos[start_index] - pos[idx-1] grouped_positions.append(grouping(positions[concat_start_index:idx])) #print(grouped_positions[-1]) concat_start_index = idx",
"status and make new positions according to algorithm # notice:",
"order[\"stop_loss_rate\"] = stop_loss_rate ret_str = self.api.order.create(order) ret = None if",
"= api # api: e.g. instance of CoinCheck self.use_leverage =",
"(target_value, possible_amount)) return False if not do_not_create_new_order: success, new_order_created =",
"#### # parse positions #### self.positions = [] self.position_id_to_sellids =",
"the new_order that is self.order_id: new_order_id = int(transaction[\"order_id\"]) transaction[\"order_id\"] =",
"exchanger valid_close_order = valid_close_orders[0] print(\"your order: rate=%f, amount=%f\" % (target_value,",
"you requested = %f\" % (qty_cur, min_qty, sell_qty,)) return False",
"as e: print(\"failed to show returned json str\") print(e) if",
"# convert position type name if position_type == \"buy\": position_type",
"self.order_id: new_order_id = int(transaction[\"order_id\"]) transaction[\"order_id\"] = new_order_id is_position_transaction = new_order_id",
"ret_pos[\"amount\"] = total_amount ret_pos[\"open_rate\"] = total_jpy / total_amount return ret_pos",
"is_close_long = False # check exist sell-orders. if target value",
"pos[start_index] - pos[idx-1] grouped_positions.append(grouping(positions[concat_start_index:idx])) #print(grouped_positions[-1]) concat_start_index = idx prev_created_at =",
"- prev_created_at).total_seconds()) <= self.timelimit_to_grouping_transaction: # can group prev_created_at = cur_created_at",
"is None or position_type is None: # algorithm says this",
"is_long else 'sell' order = { 'rate': \"%.8f\" % target_value,",
"(str(position_id), str(target_value), str(amount), str(is_cur_close_long),)) return True min_qty = self.api.order.min_create_amount(self.pair) if",
"order_pair = order[\"pair\"] is_added = False if order_pair == self.pair:",
"def adjust_amount_to_tick(amount, tick): return amount - math.fmod(amount, tick) # a",
"= {} all_positions = valid_position_info positioned_value_in_base = 0 for position",
"self.exist_close_order_info_list)) position[\"close_orders\"] = self.exist_close_order_info_list for i, order in enumerate(position[\"close_orders\"]): order[\"status\"]",
"pair(self): return self.__pair def get_base_currency(self): return self.pair.split(\"_\")[1].lower() def get_qty_currency(self): return",
"pos[idx-1] grouped_positions.append(grouping(positions[concat_start_index:idx])) #print(grouped_positions[-1]) concat_start_index = idx prev_created_at = cur_created_at #",
"self.positions: open_rate = float(position[\"open_rate\"]) amount = float(position[\"amount\"]) created_time = position[\"created_at_datetime\"]",
"position!\") print(\"you passed close 'short' for normal order\") return False",
"not True or \"id\" not in ret or ret[\"id\"] is",
"in self.position_id_to_sellids: return False sell_qty = float(position[\"amount\"]) sell_ids = self.position_id_to_sellids[position_id]",
"for o in other_orders: # if o[\"order_type\"] == \"buy\": #",
"> 500: self.got_close_order_ids = self.got_close_order_ids[-500:] return True def _cancel_order(self, order_id):",
"target_value is not None: order['rate'] = target_value else: # if",
"not None: target_stoploss_float_or_none = float(stop_loss_rate) cur_amount = None if \"amount\"",
"order: rate=%.1f, amount=%f, stoploss_rate=%s, position_type=%s\" % (target_value, possible_qty, str(stop_loss_rate), position_type,))",
"import dateutil import dateutil.parser import json from ChartBars import Chart",
"btc = %f, you requested = %f\" % (min_qty, possible_qty,))",
"should be called after update_status def update_new_orders(self, chart, do_not_create_new_order=False): assert",
"is not None and all_amount < amount: amount = all_amount",
"self.position_id_to_sellids[pos_id] = position_id_to_sellids[pos_id] self.positioned_price_base = positioned_value_in_base self.positioned_value_in_qty = positioned_value_in_qty self.position_id_to_sellids",
"is not None) # order list は現物とleverageで変わらない if self.exist_order_info_list is",
"print(\"Minimum order %s = %f, you requested = %f\" %",
"to show returned json str\") print(e) if ret is None",
"self.price_decide_algorithm.decide_make_position_order(chart) if len(decide_make_ret) == 3: (position_type, target_value, stoploss_rate) = decide_make_ret",
"continue pair = position[\"pair\"] if pair != self.pair: continue position_id",
"\"open\", \"created_at\": \"2015-12-02T05:27:53.000Z\", \"closed_at\": null, \"open_rate\": \"43553.0\", \"closed_rate\": null, \"amount\":",
"None or position_type is None: # algorithm says this instance",
"\"btc_jpy\", \"status\": \"open\", \"created_at\": \"2015-12-02T05:27:53.000Z\", \"closed_at\": null, \"open_rate\": \"43553.0\", \"closed_rate\":",
"* ただし、前フレームからの情報を引き継ぐところがupdate_position_statusと違う (現物にはpositionという概念が無い) positions = self.positions position_id_to_sellids = self.position_id_to_sellids close_transactions",
"this instance should not make order. cancel all if self.exist_order_info_list",
"str(new_order[\"id\"]) + \" state is 'cancel'. probably partially contracted and",
"None: for exist_order_info in self.exist_order_info_list: self._cancel_order(exist_order_info[\"id\"]) self.exist_order_info_list = None return",
"None: # algorithm says this instance should not make order.",
"= [] self.got_close_order_ids = [] self.exist_order_info_list = None self.exist_close_order_info_list =",
"= self.get_qty_currency() base_cur = self.get_base_currency() last_transaction_id_in_this_frame = self.last_checked_transaction_id for transaction",
"else: exist_order_i += 1 if len(self.exist_order_info_list) == 0: self.exist_order_info_list =",
"str(stop_loss_rate), position_type,)) return True, False # cancel all exist orders",
"order[\"order_type\"] if \"amount\" not in order: order[\"amount\"] = float(order[\"pending_amount\"]) position[\"close_orders\"][i]",
"last_transaction_id_in_this_frame = max(last_transaction_id_in_this_frame, transaction_id) # check pair this_pair = transaction[\"pair\"]",
"amount=%f, stoploss_rate=%s, position_type=%s\" % (target_value, possible_qty, str(stop_loss_rate), position_type,)) return True,",
"False # cancel all for sell_id in sell_ids: self._cancel_order(sell_id) self.position_id_to_sellids[position_id]",
"elif \"pending_amount\" in exist_order_info: cur_amount = exist_order_info[\"pending_amount\"] order_type = None",
"this_pair != self.pair: continue # check position that is created",
"class's order qty_amount = float(transaction[\"funds\"][qty_cur]) transaction[\"amount\"] = transaction[\"amount\"] = qty_amount",
"if len(self.exist_order_info_list) == 1: exist_order_info = self.exist_order_info_list[0] cur_rate = exist_order_info[\"rate\"]",
"close_long:%s\" % (str(position_id), str(target_value), str(amount), str(is_cur_close_long),)) return True min_qty =",
"timelimit_to_grouping_transaction): self.timelimit_to_grouping_transaction = timelimit_to_grouping_transaction # check current status and make",
"# を用い、↑で貯めたpositionsから、反対売買済みのものを(amount基準で)消していき(前回フレームで残っていたpositionも含めて)、残ったpositionだけを生きているポジションとし、1つに集約する(現物用なので、idが分かれている意味はない) # その残ったpositionID, 消費した反対売買IDのIDを持っておき、次回からはそれより新しいIDのみを反映する # ただし、ずっと続けると計算誤差がたまるので、jpyもしくはbtcベースでその合計値が極めて小さくなったら丸めてノーポジ扱いにする # うーん...現物とレバレッジで管理が結構変わるから同じクラスにするのはまずかった?ごちゃごちゃしてきてしまった #",
"not in ret: print(\"Failed to create order!!\") try: print(ret_str) except",
"ret or ret[\"id\"] is None: print(\"sell order canceled but failed",
"'amount': '%.8f' % BitcoinUtil.roundBTCby1satoshi(sell_qty), 'position_id': position_id, 'order_type': 'close_long' if is_close_long",
"possible_amount <= 0.000001: # too few btc print(\"want to make",
"0: self.exist_order_info_list = None if failed_to_cancel: return False return True",
"rate = float(valid_close_order[\"rate\"]) amount = valid_close_order[\"amount\"] is_cur_close_long = False if",
"in base = %f, possible amount = %f\" % (self.get_max_total_position_price_of_base_currency()",
"remain is canceled. this position is not ignored\") #continue new_order_id",
"% (target_value, sell_qty,)) print(\"valid_close_order[0]:\") print(valid_close_order) rate = None if \"rate\"",
"if not self._cancel_exist_all_buy_orders(): return False, False # check minimum btc",
"\"amount\" in exist_order_info: cur_amount = exist_order_info[\"amount\"] elif \"pending_amount\" in exist_order_info:",
"# check close orders self.position_id_to_sellids[position_id] = \\ list(map(lambda x:x[\"id\"], filter(lambda",
"# returns: (is_success, is_new_order_created) def _update_or_create_order(self, position_type, target_value, possible_qty, stop_loss_rate",
"target_stoploss_float_or_none = None if stop_loss_rate is not None: target_stoploss_float_or_none =",
"order_type = None if \"order_type\" in exist_order_info: if exist_order_info[\"order_type\"] ==",
"set_timelimit_to_grouping_transaction(self, timelimit_to_grouping_transaction): self.timelimit_to_grouping_transaction = timelimit_to_grouping_transaction # check current status and",
"\"\"\" ret val example \"success\": true, \"id\": 12345, \"rate\": \"30010.0\",",
"True def _cancel_exist_all_buy_orders(self): failed_to_cancel = False exist_order_i = 0 while",
"= timelimit_to_grouping_transaction # check current status and make new positions",
"} \"\"\" #### # parse positions #### self.positions = []",
"position[\"amount\"] all_amount = position[\"all_amount\"] if all_amount is not None and",
"not in ret or ret[\"id\"] is None: print(\"sell order canceled",
"cannot make short position!\") print(\"you passed close 'short' for normal",
"position_type = position[\"side\"] # convert position type name if position_type",
"exist_orders = [] exist_close_orders = [] other_orders = [] for",
"= None): assert (self.api is not None) # order list",
"if order_id is None: print(\"order is already canceled\") return True",
"(price,amount) = (%f,%f) but too few amount\" % (target_value, possible_amount))",
"target_value) # interface to update internal position & order status",
"% (str(position_id),)) try: print(ret_str) except Exception as e: print(\"failed to",
"ret_str = self.api.order.cancel({\"id\": order_id, \"pair\": self.pair}) ret = None if",
"genbutsu self.max_free_margin_of_base_currency = 0 # max free margin. we cannot",
"self.positioned_value_in_qty qty_cur = self.get_qty_currency() base_cur = self.get_base_currency() last_transaction_id_in_this_frame = self.last_checked_transaction_id",
"target_value, possible_qty, stop_loss_rate = None): assert (self.api is not None)",
"- math.fmod(price, tick) def adjust_amount_to_tick(amount, tick): return amount - math.fmod(amount,",
"False, False # check minimum btc min_qty = self.api.order.min_create_amount(self.pair) if",
"# get current stoploss cur_stoploss = exist_order_info[\"stop_loss_rate\"] if \"stop_loss_rate\" in",
"{ 'rate': \"%.8f\" % target_value, 'amount': \"%.8f\" % possible_qty, 'order_type':",
"means: if a value >= stop_loss_rate, sashine will be placed",
"make (price,amount) = (%f,%f) but too few amount\" % (target_value,",
"Util import BitcoinUtil def adjust_price_to_tick(price, tick): return price - math.fmod(price,",
"import json from ChartBars import Chart from ChartUpdaterByCCWebsocket import ChartUpdaterByCoincheckWS",
"and \\ cur_stoploss_float_or_none == target_stoploss_float_or_none and \\ order_type == position_type:",
"close 'short' for normal order\") return False order = {",
"amount_tick = self.api.order.tick_amount(self.pair) possible_amount = 1.0 * possible_make_total_price_base_cur / target_value",
"create a new order but DO_NOT_CREATE_NEW flag = true\") return",
"self.positioned_value_in_qty = 0 # used only for genbutsu self.max_free_margin_of_base_currency =",
"e: print(\"failed to show returned json str\") print(e) if ret",
"は現物とleverageで変わらない if self.exist_order_info_list is not None: # check the same",
"= self.api.order.cancel({\"id\": order_id, \"pair\": self.pair}) ret = None if ret_str",
"of \"data\" will be passed) { \"data\": [ { \"id\":",
"= self.positions position_id_to_sellids = self.position_id_to_sellids close_transactions = [] all_transactions =",
"\" + str(new_order[\"id\"]) + \" state is 'cancel'. probably partially",
"self.api.order.create(order) ret_str = ret if ret is not None: try:",
"\"%.8f\" % possible_qty, 'order_type': order_type, 'pair': self.pair } # not",
"except: print(\"failed to parse close_long order result\") try: print(ret_str) except",
"total_amount return ret_pos concat_start_index = 0 prev_created_at = positions[0][\"created_at_datetime\"] for",
"= sorted(positions, key=lambda x:-x[\"id\"]) # order by desc # concat",
"json from ChartBars import Chart from ChartUpdaterByCCWebsocket import ChartUpdaterByCoincheckWS from",
"is_cur_close_long: # completely same!! print(\"requested close order is already ordered",
"math import dateutil import dateutil.parser import json from ChartBars import",
"but DO_NOT_CREATE_NEW flag = true\") return False # update close",
"len(self.got_close_order_ids) > 500: self.got_close_order_ids = self.got_close_order_ids[-500:] return True def _cancel_order(self,",
"amount = %f\" % (self.get_max_total_position_price_of_base_currency() - self.positioned_price_base, possible_make_total_price_base_cur, possible_amount)) #print(\"base_cur",
"26890, \"pair\": \"btc_jpy\", \"pending_amount\": \"0.5527\", \"pending_market_buy_amount\": null, \"stop_loss_rate\": null, \"created_at\":",
"- pos[idx-1] grouped_positions.append(grouping(positions[concat_start_index:idx])) #print(grouped_positions[-1]) concat_start_index = idx prev_created_at = cur_created_at",
"& order status def update_status(self, valid_position_info, valid_transaction_info, valid_order_info): # update",
"even if there is a valid order in internal state\"",
"new id if self.last_checked_transaction_id >= transaction_id: continue last_transaction_id_in_this_frame = max(last_transaction_id_in_this_frame,",
"\"1.51347797\", \"all_amount\": \"1.51045705\", \"side\": \"sell\", \"pl\": \"-8490.81029287\", \"new_order\": { \"id\":",
"print(\"your order: rate=%f, amount=%f\" % (target_value, sell_qty,)) print(\"valid_close_order[0]:\") print(valid_close_order) rate",
"\"pending_amount\": \"0.0\", \"status\": \"cancel\", \"created_at\": \"2015-12-05T05:03:56.000Z\" } ] } ]",
"class for one position class OnePositionTrader(object): def __init__(self, price_decide_algorithm, api,",
"to update internal position & order status def update_status(self, valid_position_info,",
"if len(self.got_close_order_ids) > 500: self.got_close_order_ids = self.got_close_order_ids[-500:] return True def",
"(len(self.positions), base_cur, self.positioned_price_base, qty_cur, self.positioned_value_in_qty,)) # close したかどうか、残っているポジション残量を計算するのに、全て遡らないといけないのは現実的ではない # 既にこの段階で解決できるポジション状態(close",
"in sell_ids, position[\"close_orders\"])) print(\"valid_close_order count = %d\" % len(valid_close_orders)) if",
"tick) # !!round to possible amount possible_make_total_price_base_cur = self.get_max_total_position_price_of_base_currency() -",
"def _cancel_exist_all_buy_orders(self): failed_to_cancel = False exist_order_i = 0 while exist_order_i",
"def set_max_free_margin_of_base_currency(self, p): self.max_free_margin_of_base_currency = p def get_max_total_position_price_base(self): return self.get_max_total_position_price_of_base_currency()",
"0 total_jpy = 0 for p in desced_position_array: total_amount +=",
"remove very old orders if len(self.got_all_order_ids) > 500: self.got_all_order_ids =",
"\"rate\": \"10000.0\", \"amount\": \"1.0\", \"pending_amount\": \"0.0\", \"status\": \"cancel\", \"created_at\": \"2015-12-05T05:03:56.000Z\"",
"new_order[\"status\"] == \"cancel\": print(\"new order: \" + str(new_order[\"id\"]) + \"",
"position[\"amount\"] = position[\"all_amount\"] = amount self.positions.append(position) open_rate = position[\"open_rate\"] positioned_value_in_base",
"= positioned_value_in_qty self.position_id_to_sellids = position_id_to_sellids self.positions = valid_positions print(\"position_count=%d, positioned_%s=%f,",
"position_id_to_sellids = self.position_id_to_sellids close_transactions = [] all_transactions = valid_transaction_info positioned_value_in_qty",
"pair = position[\"pair\"] if pair != self.pair: continue position_id =",
"0 for position in target_transactions: if remain_qty <= 0: break",
"<= 0.000001: # too few btc print(\"want to make (price,amount)",
"exist sell-orders. if target value and amount are completely same,",
"import math import dateutil import dateutil.parser import json from ChartBars",
"or \"id\" not in ret: print(\"Failed to create order!!\") try:",
"= 0 self.api = api # api: e.g. instance of",
"None if cur_stoploss is not None: cur_stoploss_float_or_none = float(cur_stoploss) target_stoploss_float_or_none",
"leverage order, close order is always \"sell\" if not is_close_long:",
"\"2016-02-23T12:14:50.000Z\" } ] } \"\"\" #exist_order_ids = list(map(lambda x:x[\"id\"], valid_order_info))",
"positions according to algorithm # notice: this method should be",
"\"sell\", \"rate\": null, \"amount\": null, \"pending_amount\": \"0\", \"status\": \"complete\", \"created_at\":",
"created_at transactions grouped_positions = self._group_near_transactions(positions) # remove closed position &",
"= None if \"order_type\" in exist_order_info: if exist_order_info[\"order_type\"] == \"buy\"",
"position_id = position[\"id\"] # check position that is created by",
"short position!\") print(\"you passed close 'short' for normal order\") return",
"\"pending_amount\": \"0.77\", \"pending_market_buy_amount\": null, \"stop_loss_rate\": null, \"created_at\": \"2015-01-10T05:55:38.000Z\" }, {",
"passed) { \"success\": true, \"orders\": [ { \"id\": 202835, \"order_type\":",
"== 3: (position_type, target_value, stoploss_rate) = decide_make_ret else: (position_type, target_value)",
"% (self.get_max_total_position_price_of_base_currency() - self.positioned_price_base, possible_make_total_price_base_cur, possible_amount)) #print(\"base_cur = %f, positioned",
"self.api.order.min_create_amount(self.pair) * 0.1: positioned_value_in_base = 0 # merge position_id_to_sellids self.position_id_to_sellids",
"close orders # 漏れがあるとまずい(cancelしなくなる)ので、とりあえずあるだけリンクしておく position_id_to_sellids[transaction_id] = [] transaction[\"close_orders\"] = []",
"\"pending_amount\": null, \"pending_market_buy_amount\": \"10000.0\", \"stop_loss_rate\": \"50000.0\", \"created_at\": \"2016-02-23T12:14:50.000Z\" } ]",
"= 'buy' if is_long else 'sell' order = { 'rate':",
"{ \"id\": 202836, \"order_type\": \"sell\", \"rate\": 26990, \"pair\": \"btc_jpy\", \"pending_amount\":",
"if sell_qty < min_qty: qty_cur = self.get_qty_currency() print(\"Minimum order %s",
"= int(transaction[\"order_id\"]) transaction[\"order_id\"] = new_order_id is_position_transaction = new_order_id in self.got_all_order_ids",
"jpy (available_margin + reserved_margin + (positioned)) def set_max_total_position_price_base(self, p): self.set_max_total_position_price_of_base_currency(p)",
"= valid_close_order[\"side\"] == \"sell\" elif \"order_type\" in valid_close_order: is_cur_close_long =",
"order['rate'] = target_value else: # if not leverage order, close",
"already created on exchanger valid_close_order = valid_close_orders[0] print(\"your order: rate=%f,",
"print(\" position id:%s, target_value:%s, amount:%s, close_long:%s\" % (str(position_id), str(target_value), str(amount),",
"= total_jpy / total_amount return ret_pos concat_start_index = 0 prev_created_at",
"= positions[0][\"created_at_datetime\"] for idx, pos in enumerate(positions): cur_created_at = pos[\"created_at_datetime\"]",
"self.get_qty_currency() print(\"Minimum order %s = %f, you requested = %f\"",
"not in transaction[\"funds\"]: continue # this position is created by",
"position[\"close_orders\"] = self.exist_close_order_info_list for i, order in enumerate(position[\"close_orders\"]): order[\"status\"] =",
"position in all_positions: status = position[\"status\"] if status != \"open\":",
"True exist_close_orders.append(order) if not is_added: other_orders.append(order) print(\"exist_create_orders\", exist_orders) print(\"exist_close_orders\", exist_close_orders)",
"at \"rate\" if stop_loss_rate is not None: order[\"stop_loss_rate\"] = stop_loss_rate",
"abs(positioned_value_in_qty) < self.api.order.min_create_amount(self.pair)*0.1: positioned_value_in_qty = 0 positions = sorted(positions, key=lambda",
"null, \"stop_loss_rate\": null, \"created_at\": \"2015-01-10T05:55:38.000Z\" }, { \"id\": 38632107, \"order_type\":",
"convert position type name if position_type == \"buy\": position_type =",
"called after update_status def update_new_orders(self, chart, do_not_create_new_order=False): assert (self.price_decide_algorithm is",
"by this class's order qty_amount = float(transaction[\"funds\"][qty_cur]) transaction[\"amount\"] = transaction[\"amount\"]",
"# do something ret_str = self.api.order.cancel({\"id\": order_id, \"pair\": self.pair}) ret",
"is not True or \"id\" not in ret or ret[\"id\"]",
"= float(transaction[\"funds\"][qty_cur]) transaction[\"amount\"] = transaction[\"amount\"] = qty_amount transaction[\"open_rate\"] = float(transaction[\"rate\"])",
"status to this instance # レバレッジ用 if not self.use_leverage: return",
"= 0 # total maximum position size in base currency",
"!= \"open\": continue pair = position[\"pair\"] if pair != self.pair:",
"None target_value = None stoploss_rate = None decide_make_ret = self.price_decide_algorithm.decide_make_position_order(chart)",
"status = position[\"status\"] if status != \"open\": continue pair =",
"self.price_decide_algorithm.market_sell_decide_algorithm(chart, open_rate, created_time, current_time_timezone_aware) is True: # market order close",
"False sell_qty = float(position[\"amount\"]) sell_ids = self.position_id_to_sellids[position_id] position_type = position[\"side\"]",
"check position that is created by the new_order that is",
"exist_orders if len(exist_orders) > 0 else None self.exist_close_order_info_list = exist_close_orders",
"e: print(\"failed to print returned error json\") print(e) if ret",
"#### \"\"\" orders example (array of \"orders\" will be passed)",
"0.00001 and \\ abs(float(amount)-float(sell_qty)) < 0.00001 and \\ is_close_long ==",
"position_type == \"long\": is_close_long = True if position_type == \"short\":",
"if self.exist_close_order_info_list is not None: for pos_i, position in enumerate(positions):",
"# update position/order status (assume: pagenations are already cleared) self._update_order_id_status(valid_order_info)",
"all_positions: status = position[\"status\"] if status != \"open\": continue pair",
"# check only new id if self.last_checked_transaction_id >= transaction_id: continue",
"0.000001: # too few btc print(\"want to make (price,amount) =",
"うーん...現物とレバレッジで管理が結構変わるから同じクラスにするのはまずかった?ごちゃごちゃしてきてしまった # 時間的に約定時刻が近いpositionをまとめる def _group_near_transactions(self, target_transactions): grouped_positions = [] positions",
"not pass new order valid_close_orders = list(filter(lambda x:x[\"status\"] != \"cancel\"",
"else: target_value = self.price_decide_algorithm.sell_price_decide_algorithm(open_rate) target_value = adjust_price_to_tick(target_value, self.api.order.tick_price(self.pair)) self._update_or_create_close_order(position, target_value)",
"202835, \"order_type\": \"buy\", \"rate\": 26890, \"pair\": \"btc_jpy\", \"pending_amount\": \"0.5527\", \"pending_market_buy_amount\":",
"if possible_amount <= 0.000001: # too few btc print(\"want to",
"True, True def _cancel_exist_all_buy_orders(self): failed_to_cancel = False exist_order_i = 0",
"order %s = %f, you requested = %f\" % (qty_cur,",
"BitcoinUtil def adjust_price_to_tick(price, tick): return price - math.fmod(price, tick) def",
"False order = { 'amount': '%.8f' % BitcoinUtil.roundBTCby1satoshi(sell_qty), 'order_type': 'sell',",
"= target_transactions if len(positions) > 0: def grouping(desced_position_array): ret_pos =",
"to possible amount possible_make_total_price_base_cur = self.get_max_total_position_price_of_base_currency() - self.positioned_price_base possible_make_total_price_base_cur =",
"\"rate\": null, \"pair\": \"btc_jpy\", \"pending_amount\": null, \"pending_market_buy_amount\": \"10000.0\", \"stop_loss_rate\": \"50000.0\",",
"False # make new order \"\"\" ret val example \"success\":",
"returned error json\") print(e) if ret is None or ret[\"success\"]",
"# same order. do nothing print(\"You already ordered this order:",
"= {} self.got_all_order_ids = [] self.got_close_order_ids = [] self.exist_order_info_list =",
"\"leverage_sell\": order_type = \"short\" if cur_rate is not None and",
"currency) self.positioned_value_in_qty = 0 # used only for genbutsu self.max_free_margin_of_base_currency",
"+= position[\"amount\"] * position[\"open_rate\"] return valid_positions, total_base def _update_order_id_status(self, valid_order_info):",
"= true\") return False # update close orders according to",
"# a class for one position class OnePositionTrader(object): def __init__(self,",
"few amount\" % (target_value, possible_amount)) return False if not do_not_create_new_order:",
"* float(o[\"rate\"]) # returns: (is_success, is_new_order_created) def _update_or_create_order(self, position_type, target_value,",
"else None cur_stoploss_float_or_none = None if cur_stoploss is not None:",
"math.fmod(price, tick) def adjust_amount_to_tick(amount, tick): return amount - math.fmod(amount, tick)",
"checked self.last_checked_transaction_id = last_transaction_id_in_this_frame print(\"last_checked_transaction_id = \", self.last_checked_transaction_id) print(\"self.exist_close_order_info_list\", self.exist_close_order_info_list)",
"print error\") print(e) return False sell_ids = [ret[\"id\"]] self.position_id_to_sellids[position_id] =",
"is None: print(\"order is already canceled\") return True # do",
"called after update_status def update_close_orders(self, chart, current_time_timezone_aware): for position in",
"/ total_amount return ret_pos concat_start_index = 0 prev_created_at = positions[0][\"created_at_datetime\"]",
"position[\"close_orders\"]))) self.positioned_price_base = positioned_value_in_base def _update_transaction_status(self, valid_transaction_info): if self.use_leverage: return",
"= use_leverage self.timelimit_to_grouping_transaction = 2 # 約定時刻がこの秒数以下なら同一ポジションとみなす(use_leverage == False の場合のみ)",
"exist_order_info[\"order_type\"] == \"sell\" or \\ exist_order_info[\"order_type\"] == \"leverage_sell\": order_type =",
"target_value is not None: # check the order is already",
"= all_amount position[\"amount\"] = position[\"all_amount\"] = amount self.positions.append(position) open_rate =",
"# check exist sell-orders. if target value and amount are",
"from Util import BitcoinUtil def adjust_price_to_tick(price, tick): return price -",
"if \"order_type\" in exist_order_info: if exist_order_info[\"order_type\"] == \"buy\" or\\ exist_order_info[\"order_type\"]",
"# used only for genbutsu self.max_free_margin_of_base_currency = 0 # max",
"None self.exist_close_order_info_list = None self.last_checked_transaction_id = 0 self.api = api",
"continue # other pair if qty_cur not in transaction[\"funds\"] or",
"ret = self.api.order.create(order) ret_str = ret if ret is not",
"\"created_at\": \"2015-12-02T05:27:52.000Z\" }, \"close_orders\": [ { \"id\": 23755132, \"side\": \"buy\",",
"stoploss_rate is not None: stoploss_rate = adjust_price_to_tick(stoploss_rate, tick) # !!round",
"not None: # check the same value or not if",
"all_transactions = valid_transaction_info positioned_value_in_qty = self.positioned_value_in_qty qty_cur = self.get_qty_currency() base_cur",
"that is created by the new_order that is self.order_id: new_order_id",
"by the new_order that is self.order_id: new_order_id = int(transaction[\"order_id\"]) transaction[\"order_id\"]",
"self._remain_non_closed_transactions(grouped_positions, positioned_value_in_qty) if abs(positioned_value_in_base) < self.api.order.tick_price(self.pair) * self.api.order.min_create_amount(self.pair) * 0.1:",
"not in order: order[\"amount\"] = float(order[\"pending_amount\"]) position[\"close_orders\"][i] = order positions[pos_i]",
"< self.api.order.tick_price(self.pair) * self.api.order.min_create_amount(self.pair) * 0.1: positioned_value_in_base = 0 #",
"None: target_stoploss_float_or_none = float(stop_loss_rate) cur_amount = None if \"amount\" in",
"is not None and order_type is not None: if abs(float(cur_rate)-float(target_value))",
"order ret str\") try: print(ret_str) except Exception as e: print(\"failed",
"# transaction_id means position_id transaction[\"id\"] = transaction_id # check only",
"ignored\") #continue new_order_id = new_order[\"id\"] if new_order_id in self.got_all_order_ids: #",
"is_close_transaction = new_order_id in self.got_close_order_ids if not is_position_transaction and not",
"too few amount\" % (target_value, possible_amount)) return False if not",
"show returned json str\") print(e) return False, False self.exist_order_info_list =",
"position_id_to_sellids self.positions = valid_positions print(\"position_count=%d, positioned_%s=%f, positioned_%s=%f\" % (len(self.positions), base_cur,",
"def get_positioned_price_base(self): return self.positioned_price_base def set_timelimit_to_grouping_transaction(self, timelimit_to_grouping_transaction): self.timelimit_to_grouping_transaction = timelimit_to_grouping_transaction",
"None or ret[\"success\"] is not True or \"id\" not in",
"\\ order_type == position_type: # same order. do nothing print(\"You",
"(self.price_decide_algorithm is not None) position_type = None target_value = None",
"canceled but failed to create new sell order!!: position id:",
"order: \" + str(new_order[\"id\"]) + \" state is 'cancel'. probably",
"method should be called after update_status def update_new_orders(self, chart, do_not_create_new_order=False):",
"= self.get_max_total_position_price_of_base_currency() - self.positioned_price_base possible_make_total_price_base_cur = min(possible_make_total_price_base_cur, self.max_free_margin_of_base_currency) amount_tick =",
"created_time = position[\"created_at_datetime\"] target_value = None if self.price_decide_algorithm.market_sell_decide_algorithm(chart, open_rate, created_time,",
"< amount: amount = all_amount position[\"amount\"] = position[\"all_amount\"] = amount",
"= transaction_id # check only new id if self.last_checked_transaction_id >=",
"self.last_checked_transaction_id = 0 self.api = api # api: e.g. instance",
"status (assume: pagenations are already cleared) self._update_order_id_status(valid_order_info) if self.use_leverage: self._update_position_status(valid_position_info)",
"= True): self.max_total_position_price_base = 0 # total maximum position size",
"if exist_order_info[\"order_type\"] == \"sell\" or \\ exist_order_info[\"order_type\"] == \"leverage_sell\": order_type",
"%s\" % (str(position_id),)) try: print(ret_str) except Exception as e: print(\"failed",
"group prev_created_at = cur_created_at continue # this position cannot be",
"min_qty = self.api.order.min_create_amount(self.pair) if possible_qty < min_qty: print(\"Minimum order btc",
"new sell order!!: position id: %s\" % (str(position_id),)) try: print(ret_str)",
"\"order_type\": \"sell\", \"rate\": 26990, \"pair\": \"btc_jpy\", \"pending_amount\": \"0.77\", \"pending_market_buy_amount\": null,",
"\"success\": true, \"orders\": [ { \"id\": 202835, \"order_type\": \"buy\", \"rate\":",
"self.get_max_total_position_price_of_base_currency() def get_max_total_position_price_of_base_currency(self): return self.max_total_position_price_base def get_positioned_price_base(self): return self.positioned_price_base def",
"self.max_free_margin_of_base_currency = p def get_max_total_position_price_base(self): return self.get_max_total_position_price_of_base_currency() def get_max_total_position_price_of_base_currency(self): return",
"by this class's order created_time = dateutil.parser.parse(position[\"created_at\"]) position[\"created_at_datetime\"] = created_time",
"target_transactions): grouped_positions = [] positions = target_transactions if len(positions) >",
"漏れがあるとまずい(cancelしなくなる)ので、とりあえずあるだけリンクしておく position_id_to_sellids[transaction_id] = [] transaction[\"close_orders\"] = [] positions.append(transaction) else: close_transactions.append(transaction)",
"and \\ abs(float(cur_amount)-float(possible_qty)) < 0.00001 and \\ cur_stoploss_float_or_none == target_stoploss_float_or_none",
"interface to update internal position & order status def update_status(self,",
"# max free margin. we cannot use orders that exceed",
"if order_id in self.got_all_order_ids: is_added = True exist_orders.append(order) elif order_id",
"is not None: # check the order is already created",
"print(\"valid_close_order[0]:\") print(valid_close_order) rate = None if \"rate\" in valid_close_order: rate",
"other pair if qty_cur not in transaction[\"funds\"] or base_cur not",
"\"all_amount\": \"1.51045705\", \"side\": \"sell\", \"pl\": \"-8490.81029287\", \"new_order\": { \"id\": 23104033,",
"max free margin. we cannot use orders that exceed this",
"set_max_free_margin_of_base_currency(self, p): self.max_free_margin_of_base_currency = p def get_max_total_position_price_base(self): return self.get_max_total_position_price_of_base_currency() def",
"not is_position_transaction and not is_close_transaction: continue # other pair if",
"% (target_value, possible_qty, str(stop_loss_rate), position_type,)) return True, False # cancel",
"0 for p in desced_position_array: total_amount += p[\"amount\"] total_jpy +=",
"continue last_transaction_id_in_this_frame = max(last_transaction_id_in_this_frame, transaction_id) # check pair this_pair =",
"target_value is None: # market_sell order['order_type'] = \"market_sell\" else: order['rate']",
"in all_positions: status = position[\"status\"] if status != \"open\": continue",
"grouped grouped_positions.append(grouping(positions[concat_start_index:])) return grouped_positions # まだcloseされていないtransactionだけを残す def _remain_non_closed_transactions(self, target_transactions, positioned_value_in_qty):",
"DO_NOT_CREATE_NEW flag = true\") return False # update close orders",
"== \"sell\" if abs(float(rate)-float(target_value)) < 0.00001 and \\ abs(float(amount)-float(sell_qty)) <",
"= None if \"amount\" in exist_order_info: cur_amount = exist_order_info[\"amount\"] elif",
"for normal order\") return False order = { 'amount': '%.8f'",
"= 2 # 約定時刻がこの秒数以下なら同一ポジションとみなす(use_leverage == False の場合のみ) self.__pair = pair",
"if self.price_decide_algorithm.market_sell_decide_algorithm(chart, open_rate, created_time, current_time_timezone_aware) is True: # market order",
"'%.8f' % BitcoinUtil.roundBTCby1satoshi(sell_qty), 'order_type': 'sell', 'pair': self.pair, } if target_value",
"def get_qty_currency(self): return self.pair.split(\"_\")[0].lower() # set usable jpy (available_margin +",
"order qty_amount = float(transaction[\"funds\"][qty_cur]) transaction[\"amount\"] = transaction[\"amount\"] = qty_amount transaction[\"open_rate\"]",
"tick) if stoploss_rate is not None: stoploss_rate = adjust_price_to_tick(stoploss_rate, tick)",
"in next frame, only transaction_id > self.last_checked_transaction_id will be checked",
"true, \"orders\": [ { \"id\": 202835, \"order_type\": \"buy\", \"rate\": 26890,",
"self.use_leverage: return # 現物用。transactionの結果からポジションの状態を解析. 基本的にupdate_position_statusと挙動は同じ。parseするjsonが異なる # * ただし、前フレームからの情報を引き継ぐところがupdate_position_statusと違う (現物にはpositionという概念が無い) positions",
"adjust_price_to_tick(target_value, tick) if stoploss_rate is not None: stoploss_rate = adjust_price_to_tick(stoploss_rate,",
"= float(cur_stoploss) target_stoploss_float_or_none = None if stop_loss_rate is not None:",
"sell_ids: self._cancel_order(sell_id) self.position_id_to_sellids[position_id] = [] # make new order order",
"only transaction_id > self.last_checked_transaction_id will be checked self.last_checked_transaction_id = last_transaction_id_in_this_frame",
"order[\"pair\"] is_added = False if order_pair == self.pair: if order_id",
"None if \"order_type\" in exist_order_info: if exist_order_info[\"order_type\"] == \"buy\" or\\",
"0.00001 and \\ is_close_long == is_cur_close_long: # completely same!! print(\"requested",
"is_added: other_orders.append(order) print(\"exist_create_orders\", exist_orders) print(\"exist_close_orders\", exist_close_orders) self.exist_order_info_list = exist_orders if",
"self._cancel_order(exist_order_info[\"id\"]) is False: # something error happened!! print(\"order cancel failed",
"order created_time = dateutil.parser.parse(position[\"created_at\"]) position[\"created_at_datetime\"] = created_time amount = position[\"amount\"]",
"self.got_close_order_ids: is_added = True exist_close_orders.append(order) if not is_added: other_orders.append(order) print(\"exist_create_orders\",",
"always \"sell\" if not is_close_long: print(\"normal order cannot make short",
"create order!!\") try: print(ret_str) except Exception as e: print(\"failed to",
"transaction in all_transactions: transaction_id = int(transaction[\"id\"]) # transaction_id means position_id",
"None self.exist_close_order_info_list = exist_close_orders if len(exist_close_orders) > 0 else None",
"order list は現物とleverageで変わらない if self.exist_order_info_list is not None: # check",
"do not pass new order valid_close_orders = list(filter(lambda x:x[\"status\"] !=",
"position_type: # same order. do nothing print(\"You already ordered this",
"concat_start_index = idx prev_created_at = cur_created_at # remain positioned not",
"# order list は現物とleverageで変わらない if self.exist_order_info_list is not None: #",
"class OnePositionTrader(object): def __init__(self, price_decide_algorithm, api, pair=\"btc_jpy\", use_leverage = True):",
"minimum btc min_qty = self.api.order.min_create_amount(self.pair) if possible_qty < min_qty: print(\"Minimum",
"created_time = dateutil.parser.parse(transaction[\"created_at\"]) transaction[\"created_at_datetime\"] = created_time if is_position_transaction: # check",
"} # not correct # this \"stop_loss_rate\" means: if a",
"print error\") print(e) if ret is None or ret[\"success\"] is",
"assert (self.price_decide_algorithm is not None) position_type = None target_value =",
"print(\"exist_create_orders\", exist_orders) print(\"exist_close_orders\", exist_close_orders) self.exist_order_info_list = exist_orders if len(exist_orders) >",
"close orders according to current positions # this class should",
"position_type,)) return True, False # cancel all exist orders if",
"use_leverage = True): self.max_total_position_price_base = 0 # total maximum position",
"desc # concat very near created_at transactions grouped_positions = self._group_near_transactions(positions)",
"= False if order_pair == self.pair: if order_id in self.got_all_order_ids:",
"pair != self.pair: continue position_id = position[\"id\"] # check position",
"or \"id\" not in ret: print(\"Failed to cancel order %s:",
"not be grouped grouped_positions.append(grouping(positions[concat_start_index:])) return grouped_positions # まだcloseされていないtransactionだけを残す def _remain_non_closed_transactions(self,",
"= %f, positioned = %f, others = %f\" % (self.get_max_total_position_price_of_base_currency(),",
"10, \"pair\": \"btc_jpy\", \"status\": \"open\", \"created_at\": \"2015-12-02T05:27:53.000Z\", \"closed_at\": null, \"open_rate\":",
"position_id = position[\"id\"] if position_id not in self.position_id_to_sellids: return False",
"% target_value, 'amount': \"%.8f\" % possible_qty, 'order_type': order_type, 'pair': self.pair",
"# call apis for current orders if order_id is None:",
"o[\"order_type\"] == \"buy\": # self.other_reserved_base += float(o[\"pending_amount\"]) * float(o[\"rate\"]) #",
"in ret: print(\"Failed to create order!!\") try: print(ret_str) except Exception",
"#if not self.use_leverage: # for o in other_orders: # if",
"to possible price tick = self.api.order.tick_price(self.pair) target_value = adjust_price_to_tick(target_value, tick)",
"= adjust_price_to_tick(stoploss_rate, tick) # !!round to possible amount possible_make_total_price_base_cur =",
"coding: utf-8 import math import dateutil import dateutil.parser import json",
"\"stop_loss_rate\": \"50000.0\", \"created_at\": \"2016-02-23T12:14:50.000Z\" } ] } \"\"\" #exist_order_ids =",
"new_order_id in self.got_all_order_ids is_close_transaction = new_order_id in self.got_close_order_ids if not",
"False # round to possible price tick = self.api.order.tick_price(self.pair) target_value",
"= last_transaction_id_in_this_frame print(\"last_checked_transaction_id = \", self.last_checked_transaction_id) print(\"self.exist_close_order_info_list\", self.exist_close_order_info_list) if self.exist_close_order_info_list",
"\"stop_loss_rate\": null, \"created_at\": \"2015-01-10T05:55:38.000Z\" }, { \"id\": 202836, \"order_type\": \"sell\",",
"margin. we cannot use orders that exceed this margin self.positions",
"None and all_amount < amount: amount = all_amount position[\"amount\"] =",
"print(\"you passed close 'short' for normal order\") return False order",
"valid_position_info, valid_transaction_info, valid_order_info): # update position/order status (assume: pagenations are",
"print(\"exist_close_orders\", exist_close_orders) self.exist_order_info_list = exist_orders if len(exist_orders) > 0 else",
"orders if len(self.got_all_order_ids) > 500: self.got_all_order_ids = self.got_all_order_ids[-500:] print(\"order success!\",",
"\"buy\" or\\ exist_order_info[\"order_type\"] == \"leverage_buy\": order_type = \"long\" if exist_order_info[\"order_type\"]",
"% (len(self.positions), base_cur, self.positioned_price_base, qty_cur, self.positioned_value_in_qty,)) # close したかどうか、残っているポジション残量を計算するのに、全て遡らないといけないのは現実的ではない #",
"open_rate = float(position[\"open_rate\"]) amount = float(position[\"amount\"]) created_time = position[\"created_at_datetime\"] target_value",
"if order_pair == self.pair: if order_id in self.got_all_order_ids: is_added =",
"min_qty: print(\"Minimum order btc = %f, you requested = %f\"",
"print(\"position_count=%d, positioned_%s=%f, positioned_%s=%f\" % (len(self.positions), base_cur, self.positioned_price_base, qty_cur, self.positioned_value_in_qty,)) #",
"positioned_value_in_qty = self.positioned_value_in_qty qty_cur = self.get_qty_currency() base_cur = self.get_base_currency() last_transaction_id_in_this_frame",
"def __init__(self, price_decide_algorithm, api, pair=\"btc_jpy\", use_leverage = True): self.max_total_position_price_base =",
"null, \"amount\": null, \"pending_amount\": \"0\", \"status\": \"complete\", \"created_at\": \"2015-12-02T05:27:52.000Z\" },",
"self.exist_order_info_list is not None: for exist_order_info in self.exist_order_info_list: self._cancel_order(exist_order_info[\"id\"]) self.exist_order_info_list",
"True, False # cancel all exist orders if not self._cancel_exist_all_buy_orders():",
"cancel order %s: %s\" % (str(order_id), str(ret_str),)) return False return",
"self.positions = [] self.position_id_to_sellids = {} self.got_all_order_ids = [] self.got_close_order_ids",
"\"complete\", \"created_at\": \"2015-12-02T05:27:52.000Z\" }, \"close_orders\": [ { \"id\": 23755132, \"side\":",
"total_base += position[\"amount\"] * position[\"open_rate\"] return valid_positions, total_base def _update_order_id_status(self,",
"target_value else: # if not leverage order, close order is",
"positions = target_transactions if len(positions) > 0: def grouping(desced_position_array): ret_pos",
"\"id\": 202836, \"order_type\": \"sell\", \"rate\": 26990, \"pair\": \"btc_jpy\", \"pending_amount\": \"0.77\",",
"in self.got_all_order_ids: is_added = True exist_orders.append(order) elif order_id in self.got_close_order_ids:",
"self.api.order.tick_amount(self.pair) possible_amount = 1.0 * possible_make_total_price_base_cur / target_value possible_amount =",
"if len(self.exist_order_info_list) == 0: self.exist_order_info_list = None if failed_to_cancel: return",
"% BitcoinUtil.roundBTCby1satoshi(sell_qty), 'order_type': 'sell', 'pair': self.pair, } if target_value is",
"% (exist_order_info[\"id\"],)) failed_to_cancel = True del self.exist_order_info_list[exist_order_i] else: exist_order_i +=",
"x:-x[\"id\"]) # order by desc # concat very near created_at",
"min_qty: qty_cur = self.get_qty_currency() print(\"Minimum order %s = %f, you",
"+= p[\"amount\"] total_jpy += p[\"amount\"] * p[\"open_rate\"] ret_pos[\"amount\"] = total_amount",
"json str\") print(e) return False, False self.exist_order_info_list = [ret] self.got_all_order_ids.append(ret[\"id\"])",
"possible_qty < min_qty: print(\"Minimum order btc = %f, you requested",
"order in internal state\" % (exist_order_info[\"id\"],)) failed_to_cancel = True del",
"exist_order_info: cur_amount = exist_order_info[\"pending_amount\"] order_type = None if \"order_type\" in",
"= self._group_near_transactions(positions) # remove closed position & update positioned_value_in_jpy valid_positions,",
"print(\"normal order cannot make short position!\") print(\"you passed close 'short'",
"grouped_positions.append(grouping(positions[concat_start_index:])) return grouped_positions # まだcloseされていないtransactionだけを残す def _remain_non_closed_transactions(self, target_transactions, positioned_value_in_qty): valid_positions",
"# まだcloseされていないtransactionだけを残す def _remain_non_closed_transactions(self, target_transactions, positioned_value_in_qty): valid_positions = [] remain_qty",
"None #self.other_reserved_base = 0 #if not self.use_leverage: # for o",
"None: try: ret = json.loads(ret_str) except: print(\"failed to parse cancel",
"is not None: order['rate'] = target_value else: # if not",
"= position[\"side\"] # convert position type name if position_type ==",
"of \"orders\" will be passed) { \"success\": true, \"orders\": [",
"# concat very near created_at transactions grouped_positions = self._group_near_transactions(positions) #",
"error json\") print(e) if ret is None or ret[\"success\"] is",
"are completely same, do not pass new order valid_close_orders =",
"= order positions[pos_i] = position # round very small value",
"= None if cur_stoploss is not None: cur_stoploss_float_or_none = float(cur_stoploss)",
"0 # used only for genbutsu self.max_free_margin_of_base_currency = 0 #",
"return True # do something ret_str = self.api.order.cancel({\"id\": order_id, \"pair\":",
"if cur_rate is not None and cur_amount is not None",
"if position_type == \"sell\": position_type = \"short\" is_close_long = True",
"ret_str is not None: try: ret = json.loads(ret_str) except: print(\"failed",
"= float(transaction[\"open_rate\"]) positioned_value_in_qty += float(qty_amount) created_time = dateutil.parser.parse(transaction[\"created_at\"]) transaction[\"created_at_datetime\"] =",
"not None: for exist_order_info in self.exist_order_info_list: self._cancel_order(exist_order_info[\"id\"]) self.exist_order_info_list = None",
"make order. cancel all if self.exist_order_info_list is not None: for",
"% BitcoinUtil.roundBTCby1satoshi(sell_qty), 'position_id': position_id, 'order_type': 'close_long' if is_close_long else 'close_short',",
"to create order!!\") try: print(ret_str) except Exception as e: print(\"failed",
"in self.got_close_order_ids if not is_position_transaction and not is_close_transaction: continue #",
"positions = self.positions position_id_to_sellids = self.position_id_to_sellids close_transactions = [] all_transactions",
"= exist_order_info[\"amount\"] elif \"pending_amount\" in exist_order_info: cur_amount = exist_order_info[\"pending_amount\"] order_type",
"utf-8 import math import dateutil import dateutil.parser import json from",
"update positioned_value_in_jpy valid_positions, positioned_value_in_base = self._remain_non_closed_transactions(grouped_positions, positioned_value_in_qty) if abs(positioned_value_in_base) <",
"= json.loads(ret) except: print(\"failed to parse close_long order result\") try:",
"str(self) + \", pair=\" + str(pair)) @property def pair(self): return",
"print(\"failed to print returned error json\") print(e) if ret is",
"\"close_orders\": [ { \"id\": 23755132, \"side\": \"buy\", \"rate\": \"10000.0\", \"amount\":",
"positioned_value_in_base = self._remain_non_closed_transactions(grouped_positions, positioned_value_in_qty) if abs(positioned_value_in_base) < self.api.order.tick_price(self.pair) * self.api.order.min_create_amount(self.pair)",
"= 0 total_jpy = 0 for p in desced_position_array: total_amount",
"= [] exist_close_orders = [] other_orders = [] for idx,",
"json.loads(ret) except: print(\"failed to parse close_long order result\") try: print(ret_str)",
"a valid order in internal state\" % (exist_order_info[\"id\"],)) failed_to_cancel =",
"self._update_position_status(valid_position_info) else: self._update_transaction_status(valid_transaction_info) def _update_position_status(self, valid_position_info): # apply real positions",
"btc min_qty = self.api.order.min_create_amount(self.pair) if possible_qty < min_qty: print(\"Minimum order",
"= max(last_transaction_id_in_this_frame, transaction_id) # check pair this_pair = transaction[\"pair\"] if",
"in self.got_all_order_ids is_close_transaction = new_order_id in self.got_close_order_ids if not is_position_transaction",
"in other_orders: # if o[\"order_type\"] == \"buy\": # self.other_reserved_base +=",
"is_added = True exist_close_orders.append(order) if not is_added: other_orders.append(order) print(\"exist_create_orders\", exist_orders)",
"for i, order in enumerate(position[\"close_orders\"]): order[\"status\"] = \"open\" order[\"side\"] =",
"print(ret_str) except Exception as e: print(\"failed to show returned json",
"= exist_orders if len(exist_orders) > 0 else None self.exist_close_order_info_list =",
"= decide_make_ret if target_value is None or position_type is None:",
"\"open_rate\": \"43553.0\", \"closed_rate\": null, \"amount\": \"1.51347797\", \"all_amount\": \"1.51045705\", \"side\": \"sell\",",
"= float(transaction[\"rate\"]) open_rate = float(transaction[\"open_rate\"]) positioned_value_in_qty += float(qty_amount) created_time =",
"not if len(self.exist_order_info_list) == 1: exist_order_info = self.exist_order_info_list[0] cur_rate =",
"= valid_close_order[\"amount\"] is_cur_close_long = False if \"side\" in valid_close_order: is_cur_close_long",
"None: # market_sell order['order_type'] = \"market_sell\" else: order['rate'] = target_value",
"\"id\" not in ret: print(\"Failed to create order!!\") try: print(ret_str)",
"same value or not if len(self.exist_order_info_list) == 1: exist_order_info =",
"print(\"PositionTrader: inst=\" + str(self) + \", pair=\" + str(pair)) @property",
"= \"long\" if exist_order_info[\"order_type\"] == \"sell\" or \\ exist_order_info[\"order_type\"] ==",
"\"pair\": \"btc_jpy\", \"created_at\": \"2015-01-10T05:55:38.000Z\" \"\"\" is_long = position_type == \"long\"",
"* p[\"open_rate\"] ret_pos[\"amount\"] = total_amount ret_pos[\"open_rate\"] = total_jpy / total_amount",
"assert (self.api is not None) # order list は現物とleverageで変わらない if",
"'close_short', 'pair': 'btc_jpy', } if target_value is not None: order['rate']",
"\"sell\" if not is_close_long: print(\"normal order cannot make short position!\")",
"= position[\"open_rate\"] positioned_value_in_base += float(amount) * float(open_rate) # check close",
"= order[\"id\"] order_pair = order[\"pair\"] is_added = False if order_pair",
"list(map(lambda x:x[\"id\"], filter(lambda x:x[\"status\"] != \"cancel\", position[\"close_orders\"]))) self.positioned_price_base = positioned_value_in_base",
"= [] self.exist_order_info_list = None self.exist_close_order_info_list = None self.last_checked_transaction_id =",
"'cancel'. probably partially contracted and remain is canceled. this position",
"idx, pos in enumerate(positions): cur_created_at = pos[\"created_at_datetime\"] if abs((cur_created_at -",
"'amount': \"%.8f\" % possible_qty, 'order_type': order_type, 'pair': self.pair } #",
"# interface to update internal position & order status def",
"if a value >= stop_loss_rate, sashine will be placed at",
"None self.last_checked_transaction_id = 0 self.api = api # api: e.g.",
"in transaction[\"funds\"] or base_cur not in transaction[\"funds\"]: continue # this",
"= self.get_base_currency() last_transaction_id_in_this_frame = self.last_checked_transaction_id for transaction in all_transactions: transaction_id",
"abs((cur_created_at - prev_created_at).total_seconds()) <= self.timelimit_to_grouping_transaction: # can group prev_created_at =",
"position[\"open_rate\"] return valid_positions, total_base def _update_order_id_status(self, valid_order_info): #### # parse",
"_update_or_create_close_order(self, position, target_value): position_id = position[\"id\"] if position_id not in",
"= exist_close_orders if len(exist_close_orders) > 0 else None #self.other_reserved_base =",
"if ret_str is not None: try: ret = json.loads(ret_str) except:",
"= min(possible_make_total_price_base_cur, self.max_free_margin_of_base_currency) amount_tick = self.api.order.tick_amount(self.pair) possible_amount = 1.0 *",
"レバレッジ用 if not self.use_leverage: return \"\"\" position example (array of",
"int(transaction[\"id\"]) # transaction_id means position_id transaction[\"id\"] = transaction_id # check",
"order[\"id\"] order_pair = order[\"pair\"] is_added = False if order_pair ==",
"get_qty_currency(self): return self.pair.split(\"_\")[0].lower() # set usable jpy (available_margin + reserved_margin",
"positioned_%s=%f\" % (len(self.positions), base_cur, self.positioned_price_base, qty_cur, self.positioned_value_in_qty,)) # close したかどうか、残っているポジション残量を計算するのに、全て遡らないといけないのは現実的ではない",
"38632107, \"order_type\": \"buy\", \"rate\": null, \"pair\": \"btc_jpy\", \"pending_amount\": null, \"pending_market_buy_amount\":",
"] } ] } \"\"\" #### # parse positions ####",
"else 'leverage_sell' if not self.use_leverage: order_type = 'buy' if is_long",
"[] for idx, order in enumerate(valid_order_info): order_id = order[\"id\"] order_pair",
"ret = json.loads(ret_str) except: print(\"failed to parse api.order.create result\") try:",
"0 for position in all_positions: status = position[\"status\"] if status",
"order!!: position id: %s\" % (str(position_id),)) try: print(ret_str) except Exception",
"total_base = 0 for position in target_transactions: if remain_qty <=",
"\"buy\", \"rate\": 26890, \"pair\": \"btc_jpy\", \"pending_amount\": \"0.5527\", \"pending_market_buy_amount\": null, \"stop_loss_rate\":",
"ret_str = self.api.order.create(order) ret = None if ret_str is not",
"is not None: if abs(float(cur_rate)-float(target_value)) < 0.00001 and \\ abs(float(cur_amount)-float(possible_qty))",
"= self.positioned_value_in_qty qty_cur = self.get_qty_currency() base_cur = self.get_base_currency() last_transaction_id_in_this_frame =",
"exist_order_info = self.exist_order_info_list[0] cur_rate = exist_order_info[\"rate\"] if \"rate\" in exist_order_info",
"set_max_total_position_price_of_base_currency(self, p): self.max_total_position_price_base = p def set_max_free_margin_of_base_currency(self, p): self.max_free_margin_of_base_currency =",
"= adjust_price_to_tick(target_value, tick) if stoploss_rate is not None: stoploss_rate =",
"check pair this_pair = transaction[\"pair\"] if this_pair != self.pair: continue",
"in ret or ret[\"id\"] is None: print(\"sell order canceled but",
"valid_close_orders = list(filter(lambda x:x[\"status\"] != \"cancel\" and x[\"id\"] in sell_ids,",
"% (target_value, possible_make_total_price_base_cur,)) if possible_amount <= 0.000001: # too few",
"self.order_id: new_order = position[\"new_order\"] if new_order[\"status\"] == \"cancel\": print(\"new order:",
"as e: print(\"failed to show returned json str\") print(e) return",
"self.other_reserved_base,)) #print(\"target_value = %f, possible_base = %f\" % (target_value, possible_make_total_price_base_cur,))",
"is_close_long == is_cur_close_long: # completely same!! print(\"requested close order is",
"[ { \"id\": 202835, \"order_type\": \"buy\", \"rate\": 26890, \"pair\": \"btc_jpy\",",
"partially contracted and remain is canceled. this position is not",
"self.exist_close_order_info_list is not None: for pos_i, position in enumerate(positions): transaction_id",
"ret is None or ret[\"success\"] is not True or \"id\"",
"null, \"stop_loss_rate\": null, \"created_at\": \"2015-01-10T05:55:38.000Z\" }, { \"id\": 202836, \"order_type\":",
"print(\"Failed to create order!!\") try: print(ret_str) except Exception as e:",
"check minimum btc min_qty = self.api.order.min_create_amount(self.pair) if possible_qty < min_qty:",
"created on exchanger valid_close_order = valid_close_orders[0] print(\"your order: rate=%f, amount=%f\"",
"None: print(\"order is already canceled\") return True # do something",
"if ret is None or ret[\"success\"] is not True or",
"chart, do_not_create_new_order=False): assert (self.price_decide_algorithm is not None) position_type = None",
"self.api.order.tick_price(self.pair) * self.api.order.min_create_amount(self.pair) * 0.1: positioned_value_in_base = 0 # merge",
"all exist orders if not self._cancel_exist_all_buy_orders(): return False, False #",
"ret = json.loads(ret_str) except: print(\"failed to parse cancel order ret",
"inst=\" + str(self) + \", pair=\" + str(pair)) @property def",
"self.get_max_total_position_price_of_base_currency() - self.positioned_price_base possible_make_total_price_base_cur = min(possible_make_total_price_base_cur, self.max_free_margin_of_base_currency) amount_tick = self.api.order.tick_amount(self.pair)",
"market order close pass else: target_value = self.price_decide_algorithm.sell_price_decide_algorithm(open_rate) target_value =",
"remain_qty remain_qty = 0 valid_positions.append(position) total_base += position[\"amount\"] * position[\"open_rate\"]",
"self.position_id_to_sellids = {} self.got_all_order_ids = [] self.got_close_order_ids = [] self.exist_order_info_list",
"not None: for pos_i, position in enumerate(positions): transaction_id = position[\"id\"]",
"\"created_at\": \"2015-01-10T05:55:38.000Z\" \"\"\" is_long = position_type == \"long\" order_type =",
"position_type == \"short\": is_close_long = False # check exist sell-orders.",
"this margin self.positions = [] self.position_id_to_sellids = {} self.got_all_order_ids =",
"is created by this class's order qty_amount = float(transaction[\"funds\"][qty_cur]) transaction[\"amount\"]",
"order_id = order[\"id\"] order_pair = order[\"pair\"] is_added = False if",
"and order_type is not None: if abs(float(cur_rate)-float(target_value)) < 0.00001 and",
"valid_close_orders[0] print(\"your order: rate=%f, amount=%f\" % (target_value, sell_qty,)) print(\"valid_close_order[0]:\") print(valid_close_order)",
"'short' for normal order\") return False order = { 'amount':",
"_remain_non_closed_transactions(self, target_transactions, positioned_value_in_qty): valid_positions = [] remain_qty = positioned_value_in_qty total_base",
"position_type, target_value, possible_qty, stop_loss_rate = None): assert (self.api is not",
"# make new order \"\"\" ret val example \"success\": true,",
"_update_or_create_order(self, position_type, target_value, possible_qty, stop_loss_rate = None): assert (self.api is",
"0 else None self.exist_close_order_info_list = exist_close_orders if len(exist_close_orders) > 0",
"# check position that is created by the new_order that",
"したかどうか、残っているポジション残量を計算するのに、全て遡らないといけないのは現実的ではない # 既にこの段階で解決できるポジション状態(close order id見て、それがあれば反対売買が成立している) # を用い、↑で貯めたpositionsから、反対売買済みのものを(amount基準で)消していき(前回フレームで残っていたpositionも含めて)、残ったpositionだけを生きているポジションとし、1つに集約する(現物用なので、idが分かれている意味はない) # その残ったpositionID, 消費した反対売買IDのIDを持っておき、次回からはそれより新しいIDのみを反映する",
"< min_qty: qty_cur = self.get_qty_currency() print(\"Minimum order %s = %f,",
"= list(map(lambda x:x[\"id\"], self.exist_close_order_info_list)) position[\"close_orders\"] = self.exist_close_order_info_list for i, order",
"return False # update close orders according to current positions",
"if len(positions) > 0: def grouping(desced_position_array): ret_pos = dict(desced_position_array[0]) total_amount",
"[] self.exist_order_info_list = None self.exist_close_order_info_list = None self.last_checked_transaction_id = 0",
"\"sell\", \"stop_loss_rate\": null, \"pair\": \"btc_jpy\", \"created_at\": \"2015-01-10T05:55:38.000Z\" \"\"\" is_long =",
"call apis for current orders if order_id is None: print(\"order",
"= %f\" % (target_value, possible_make_total_price_base_cur,)) if possible_amount <= 0.000001: #",
"}, { \"id\": 38632107, \"order_type\": \"buy\", \"rate\": null, \"pair\": \"btc_jpy\",",
"val example \"success\": true, \"id\": 12345, \"rate\": \"30010.0\", \"amount\": \"1.3\",",
"cur_created_at = pos[\"created_at_datetime\"] if abs((cur_created_at - prev_created_at).total_seconds()) <= self.timelimit_to_grouping_transaction: #",
"ret = json.loads(ret) except: print(\"failed to parse close_long order result\")",
"print(\"failed to parse close_long order result\") try: print(ret_str) except Exception",
"position[\"close_orders\"])) print(\"valid_close_order count = %d\" % len(valid_close_orders)) if len(valid_close_orders) ==",
"check close orders self.position_id_to_sellids[position_id] = \\ list(map(lambda x:x[\"id\"], filter(lambda x:x[\"status\"]",
"position[\"open_rate\"] positioned_value_in_base += float(amount) * float(open_rate) # check close orders",
"base_cur, self.positioned_price_base, qty_cur, self.positioned_value_in_qty,)) # close したかどうか、残っているポジション残量を計算するのに、全て遡らないといけないのは現実的ではない # 既にこの段階で解決できるポジション状態(close order",
"position_id_to_sellids[transaction_id] = list(map(lambda x:x[\"id\"], self.exist_close_order_info_list)) position[\"close_orders\"] = self.exist_close_order_info_list for i,",
"cancel order ret str\") try: print(ret_str) except Exception as e:",
"\"data\": [ { \"id\": 10, \"pair\": \"btc_jpy\", \"status\": \"open\", \"created_at\":",
"self.positioned_price_base = 0 # total position price in base currency",
"cur_amount is not None and order_type is not None: if",
"close order is already ordered on server:\") print(\" position id:%s,",
"\"order_type\" in valid_close_order: is_cur_close_long = valid_close_order[\"order_type\"] == \"sell\" if abs(float(rate)-float(target_value))",
"\"stop_loss_rate\" means: if a value >= stop_loss_rate, sashine will be",
"def get_base_currency(self): return self.pair.split(\"_\")[1].lower() def get_qty_currency(self): return self.pair.split(\"_\")[0].lower() # set",
"else: close_transactions.append(transaction) # in next frame, only transaction_id > self.last_checked_transaction_id",
"\"0\", \"status\": \"complete\", \"created_at\": \"2015-12-02T05:27:52.000Z\" }, \"close_orders\": [ { \"id\":",
"by the new_order that is self.order_id: new_order = position[\"new_order\"] if",
"= %f\" % (self.get_max_total_position_price_of_base_currency() - self.positioned_price_base, possible_make_total_price_base_cur, possible_amount)) #print(\"base_cur =",
"= None stoploss_rate = None decide_make_ret = self.price_decide_algorithm.decide_make_position_order(chart) if len(decide_make_ret)",
"if exist_order_info[\"order_type\"] == \"buy\" or\\ exist_order_info[\"order_type\"] == \"leverage_buy\": order_type =",
"= position_id_to_sellids[pos_id] self.positioned_price_base = positioned_value_in_base self.positioned_value_in_qty = positioned_value_in_qty self.position_id_to_sellids =",
"is not None: try: ret = json.loads(ret_str) except: print(\"failed to",
"= valid_position_info positioned_value_in_base = 0 for position in all_positions: status",
"# 現物用。transactionの結果からポジションの状態を解析. 基本的にupdate_position_statusと挙動は同じ。parseするjsonが異なる # * ただし、前フレームからの情報を引き継ぐところがupdate_position_statusと違う (現物にはpositionという概念が無い) positions = self.positions",
"normal order\") return False order = { 'amount': '%.8f' %",
"3: (position_type, target_value, stoploss_rate) = decide_make_ret else: (position_type, target_value) =",
"self.got_close_order_ids = [] self.exist_order_info_list = None self.exist_close_order_info_list = None self.last_checked_transaction_id",
"if not self.use_leverage: return \"\"\" position example (array of \"data\"",
"orders #### \"\"\" orders example (array of \"orders\" will be",
"\"50000.0\", \"created_at\": \"2016-02-23T12:14:50.000Z\" } ] } \"\"\" #exist_order_ids = list(map(lambda",
"0.1: positioned_value_in_base = 0 # merge position_id_to_sellids self.position_id_to_sellids = {}",
"list(map(lambda x:x[\"id\"], valid_order_info)) exist_orders = [] exist_close_orders = [] other_orders",
"for idx, order in enumerate(valid_order_info): order_id = order[\"id\"] order_pair =",
"possible_qty, stop_loss_rate = None): assert (self.api is not None) #",
"if o[\"order_type\"] == \"buy\": # self.other_reserved_base += float(o[\"pending_amount\"]) * float(o[\"rate\"])",
"23104033, \"side\": \"sell\", \"rate\": null, \"amount\": null, \"pending_amount\": \"0\", \"status\":",
"\"0.0\", \"status\": \"cancel\", \"created_at\": \"2015-12-05T05:03:56.000Z\" } ] } ] }",
"= position[\"id\"] self.position_id_to_sellids[pos_id] = position_id_to_sellids[pos_id] self.positioned_price_base = positioned_value_in_base self.positioned_value_in_qty =",
"def set_max_total_position_price_base(self, p): self.set_max_total_position_price_of_base_currency(p) def set_max_total_position_price_of_base_currency(self, p): self.max_total_position_price_base = p",
"for p in desced_position_array: total_amount += p[\"amount\"] total_jpy += p[\"amount\"]",
"float(qty_amount) created_time = dateutil.parser.parse(transaction[\"created_at\"]) transaction[\"created_at_datetime\"] = created_time if is_position_transaction: #",
"\"cancel\" and x[\"id\"] in sell_ids, position[\"close_orders\"])) print(\"valid_close_order count = %d\"",
"check current status and make new positions according to algorithm",
"if target value and amount are completely same, do not",
"!!round to possible amount possible_make_total_price_base_cur = self.get_max_total_position_price_of_base_currency() - self.positioned_price_base possible_make_total_price_base_cur",
"None if self.price_decide_algorithm.market_sell_decide_algorithm(chart, open_rate, created_time, current_time_timezone_aware) is True: # market",
"grouped_positions.append(grouping(positions[concat_start_index:idx])) #print(grouped_positions[-1]) concat_start_index = idx prev_created_at = cur_created_at # remain",
"202836, \"order_type\": \"sell\", \"rate\": 26990, \"pair\": \"btc_jpy\", \"pending_amount\": \"0.77\", \"pending_market_buy_amount\":",
"for position in valid_positions: pos_id = position[\"id\"] self.position_id_to_sellids[pos_id] = position_id_to_sellids[pos_id]",
"not is_close_long: print(\"normal order cannot make short position!\") print(\"you passed",
"order_type = \"short\" if cur_rate is not None and cur_amount",
"null, \"pending_amount\": \"0\", \"status\": \"complete\", \"created_at\": \"2015-12-02T05:27:52.000Z\" }, \"close_orders\": [",
"very small value if abs(positioned_value_in_qty) < self.api.order.min_create_amount(self.pair)*0.1: positioned_value_in_qty = 0",
"ret_pos = dict(desced_position_array[0]) total_amount = 0 total_jpy = 0 for",
"(現物にはpositionという概念が無い) positions = self.positions position_id_to_sellids = self.position_id_to_sellids close_transactions = []",
"= new_order_id in self.got_all_order_ids is_close_transaction = new_order_id in self.got_close_order_ids if",
"== target_stoploss_float_or_none and \\ order_type == position_type: # same order.",
"\"new_order\": { \"id\": 23104033, \"side\": \"sell\", \"rate\": null, \"amount\": null,",
"last_transaction_id_in_this_frame = self.last_checked_transaction_id for transaction in all_transactions: transaction_id = int(transaction[\"id\"])",
"is None: # market_sell order['order_type'] = \"market_sell\" else: order['rate'] =",
"\"pending_market_buy_amount\": \"10000.0\", \"stop_loss_rate\": \"50000.0\", \"created_at\": \"2016-02-23T12:14:50.000Z\" } ] } \"\"\"",
"# remain positioned not be grouped grouped_positions.append(grouping(positions[concat_start_index:])) return grouped_positions #",
"%d even if there is a valid order in internal",
"make amount in base = %f, possible amount = %f\"",
"is_added = True exist_orders.append(order) elif order_id in self.got_close_order_ids: is_added =",
"pass else: target_value = self.price_decide_algorithm.sell_price_decide_algorithm(open_rate) target_value = adjust_price_to_tick(target_value, self.api.order.tick_price(self.pair)) self._update_or_create_close_order(position,",
"return valid_positions, total_base def _update_order_id_status(self, valid_order_info): #### # parse orders",
"> self.last_checked_transaction_id will be checked self.last_checked_transaction_id = last_transaction_id_in_this_frame print(\"last_checked_transaction_id =",
"== False の場合のみ) self.__pair = pair self.price_decide_algorithm = price_decide_algorithm print(\"PositionTrader:",
"cur_created_at continue # this position cannot be grouped. make a",
"position id: %s\" % (str(position_id),)) try: print(ret_str) except Exception as",
"total_jpy = 0 for p in desced_position_array: total_amount += p[\"amount\"]",
"< 0.00001 and \\ abs(float(cur_amount)-float(possible_qty)) < 0.00001 and \\ cur_stoploss_float_or_none",
"print(\"possible_create_in_base = %f, want to make amount in base =",
"self.api.order.min_create_amount(self.pair) if sell_qty < min_qty: qty_cur = self.get_qty_currency() print(\"Minimum order",
"= exist_order_info[\"pending_amount\"] order_type = None if \"order_type\" in exist_order_info: if",
"or \\ exist_order_info[\"order_type\"] == \"leverage_sell\": order_type = \"short\" if cur_rate",
"\"status\": \"complete\", \"created_at\": \"2015-12-02T05:27:52.000Z\" }, \"close_orders\": [ { \"id\": 23755132,",
"%f\" % (min_qty, possible_qty,)) return False, False # make new",
"all_amount < amount: amount = all_amount position[\"amount\"] = position[\"all_amount\"] =",
"the order is already created on exchanger valid_close_order = valid_close_orders[0]",
"is_cur_close_long = valid_close_order[\"side\"] == \"sell\" elif \"order_type\" in valid_close_order: is_cur_close_long",
"= valid_close_order[\"order_type\"] == \"sell\" if abs(float(rate)-float(target_value)) < 0.00001 and \\",
"%f, possible_base = %f\" % (target_value, possible_make_total_price_base_cur,)) if possible_amount <=",
"self.positioned_price_base = positioned_value_in_base self.positioned_value_in_qty = positioned_value_in_qty self.position_id_to_sellids = position_id_to_sellids self.positions",
"order_type == position_type: # same order. do nothing print(\"You already",
"%f\" % (target_value, possible_make_total_price_base_cur,)) if possible_amount <= 0.000001: # too",
"[] self.got_close_order_ids = [] self.exist_order_info_list = None self.exist_close_order_info_list = None",
"if remain_qty >= amount: remain_qty -= amount else: position[\"amount\"] =",
"in valid_close_order: rate = float(valid_close_order[\"rate\"]) amount = valid_close_order[\"amount\"] is_cur_close_long =",
"only for genbutsu self.max_free_margin_of_base_currency = 0 # max free margin.",
"= position[\"id\"] # check position that is created by the",
"= int(transaction[\"id\"]) # transaction_id means position_id transaction[\"id\"] = transaction_id #",
"\"open\": continue pair = position[\"pair\"] if pair != self.pair: continue",
"or\\ exist_order_info[\"order_type\"] == \"leverage_buy\": order_type = \"long\" if exist_order_info[\"order_type\"] ==",
"free margin. we cannot use orders that exceed this margin",
"\"sell\", \"pl\": \"-8490.81029287\", \"new_order\": { \"id\": 23104033, \"side\": \"sell\", \"rate\":",
"self.api = api # api: e.g. instance of CoinCheck self.use_leverage",
"price_decide_algorithm print(\"PositionTrader: inst=\" + str(self) + \", pair=\" + str(pair))",
"> 500: self.got_all_order_ids = self.got_all_order_ids[-500:] print(\"order success!\", ret_str) return True,",
"valid_positions, total_base def _update_order_id_status(self, valid_order_info): #### # parse orders ####",
"= position[\"pair\"] if pair != self.pair: continue position_id = position[\"id\"]",
"} if target_value is None: # market_sell order['order_type'] = \"market_sell\"",
"p[\"amount\"] total_jpy += p[\"amount\"] * p[\"open_rate\"] ret_pos[\"amount\"] = total_amount ret_pos[\"open_rate\"]",
"instance should not make order. cancel all if self.exist_order_info_list is",
"[ { \"id\": 23755132, \"side\": \"buy\", \"rate\": \"10000.0\", \"amount\": \"1.0\",",
"adjust_price_to_tick(target_value, self.api.order.tick_price(self.pair)) self._update_or_create_close_order(position, target_value) # interface to update internal position",
"transaction[\"amount\"] = transaction[\"amount\"] = qty_amount transaction[\"open_rate\"] = float(transaction[\"rate\"]) open_rate =",
"%f, positioned = %f, others = %f\" % (self.get_max_total_position_price_of_base_currency(), self.positioned_price_base,",
"print(\"failed to parse cancel order ret str\") try: print(ret_str) except",
"\"2015-12-02T05:27:52.000Z\" }, \"close_orders\": [ { \"id\": 23755132, \"side\": \"buy\", \"rate\":",
"adjust_price_to_tick(stoploss_rate, tick) # !!round to possible amount possible_make_total_price_base_cur = self.get_max_total_position_price_of_base_currency()",
"according to current positions # this class should be called",
"size in base currency self.positioned_price_base = 0 # total position",
"self.use_leverage = use_leverage self.timelimit_to_grouping_transaction = 2 # 約定時刻がこの秒数以下なら同一ポジションとみなす(use_leverage == False",
"if self.last_checked_transaction_id >= transaction_id: continue last_transaction_id_in_this_frame = max(last_transaction_id_in_this_frame, transaction_id) #",
"target_value = adjust_price_to_tick(target_value, self.api.order.tick_price(self.pair)) self._update_or_create_close_order(position, target_value) # interface to update",
"\"pair\": \"btc_jpy\", \"pending_amount\": null, \"pending_market_buy_amount\": \"10000.0\", \"stop_loss_rate\": \"50000.0\", \"created_at\": \"2016-02-23T12:14:50.000Z\"",
"= dateutil.parser.parse(position[\"created_at\"]) position[\"created_at_datetime\"] = created_time amount = position[\"amount\"] all_amount =",
"print(\"failed to show returned json str\") print(e) return False, False",
"timelimit_to_grouping_transaction # check current status and make new positions according",
"= position[\"amount\"] if remain_qty >= amount: remain_qty -= amount else:",
"new_order_id = int(transaction[\"order_id\"]) transaction[\"order_id\"] = new_order_id is_position_transaction = new_order_id in",
"will be checked self.last_checked_transaction_id = last_transaction_id_in_this_frame print(\"last_checked_transaction_id = \", self.last_checked_transaction_id)",
"str(amount), str(is_cur_close_long),)) return True min_qty = self.api.order.min_create_amount(self.pair) if sell_qty <",
"all_amount = position[\"all_amount\"] if all_amount is not None and all_amount",
"transaction_id) # check pair this_pair = transaction[\"pair\"] if this_pair !=",
"== \"sell\": position_type = \"short\" is_close_long = True if position_type",
"total_base def _update_order_id_status(self, valid_order_info): #### # parse orders #### \"\"\"",
"positioned_value_in_qty += float(qty_amount) created_time = dateutil.parser.parse(transaction[\"created_at\"]) transaction[\"created_at_datetime\"] = created_time if",
"self.api.order.cancel({\"id\": order_id, \"pair\": self.pair}) ret = None if ret_str is",
"# remove very old orders if len(self.got_all_order_ids) > 500: self.got_all_order_ids",
"[] self.position_id_to_sellids = {} all_positions = valid_position_info positioned_value_in_base = 0",
"True del self.exist_order_info_list[exist_order_i] else: exist_order_i += 1 if len(self.exist_order_info_list) ==",
"+= p[\"amount\"] * p[\"open_rate\"] ret_pos[\"amount\"] = total_amount ret_pos[\"open_rate\"] = total_jpy",
"from ChartUpdaterByCCWebsocket import ChartUpdaterByCoincheckWS from Util import BitcoinUtil def adjust_price_to_tick(price,",
"= { 'rate': \"%.8f\" % target_value, 'amount': \"%.8f\" % possible_qty,",
"\"pending_amount\" in exist_order_info: cur_amount = exist_order_info[\"pending_amount\"] order_type = None if",
"valid_close_order: rate = float(valid_close_order[\"rate\"]) amount = valid_close_order[\"amount\"] is_cur_close_long = False",
"same!! print(\"requested close order is already ordered on server:\") print(\"",
"\"0.5527\", \"pending_market_buy_amount\": null, \"stop_loss_rate\": null, \"created_at\": \"2015-01-10T05:55:38.000Z\" }, { \"id\":",
"other_orders: # if o[\"order_type\"] == \"buy\": # self.other_reserved_base += float(o[\"pending_amount\"])",
"and cur_amount is not None and order_type is not None:",
"\"long\" if exist_order_info[\"order_type\"] == \"sell\" or \\ exist_order_info[\"order_type\"] == \"leverage_sell\":",
"+ str(pair)) @property def pair(self): return self.__pair def get_base_currency(self): return",
"correct # this \"stop_loss_rate\" means: if a value >= stop_loss_rate,",
"something error happened!! print(\"order cancel failed %d even if there",
"# for o in other_orders: # if o[\"order_type\"] == \"buy\":",
"str\") print(e) return False, False self.exist_order_info_list = [ret] self.got_all_order_ids.append(ret[\"id\"]) #",
"pass new order valid_close_orders = list(filter(lambda x:x[\"status\"] != \"cancel\" and",
"self.__pair = pair self.price_decide_algorithm = price_decide_algorithm print(\"PositionTrader: inst=\" + str(self)",
"rate=%.1f, amount=%f, stoploss_rate=%s, position_type=%s\" % (target_value, possible_qty, str(stop_loss_rate), position_type,)) return",
"self.positioned_price_base def set_timelimit_to_grouping_transaction(self, timelimit_to_grouping_transaction): self.timelimit_to_grouping_transaction = timelimit_to_grouping_transaction # check current",
"0: def grouping(desced_position_array): ret_pos = dict(desced_position_array[0]) total_amount = 0 total_jpy",
"already cleared) self._update_order_id_status(valid_order_info) if self.use_leverage: self._update_position_status(valid_position_info) else: self._update_transaction_status(valid_transaction_info) def _update_position_status(self,",
"make short position!\") print(\"you passed close 'short' for normal order\")",
"exist_order_info[\"order_type\"] == \"leverage_buy\": order_type = \"long\" if exist_order_info[\"order_type\"] == \"sell\"",
"chart, current_time_timezone_aware): for position in self.positions: open_rate = float(position[\"open_rate\"]) amount",
"self.pair.split(\"_\")[1].lower() def get_qty_currency(self): return self.pair.split(\"_\")[0].lower() # set usable jpy (available_margin",
"order_id is None: print(\"order is already canceled\") return True #",
"not self._cancel_exist_all_buy_orders(): return False, False # check minimum btc min_qty",
"new_order_id in self.got_all_order_ids: # this position is created by this",
"notice: this method should be called after update_status def update_new_orders(self,",
"in self.positions: open_rate = float(position[\"open_rate\"]) amount = float(position[\"amount\"]) created_time =",
"if \"amount\" not in order: order[\"amount\"] = float(order[\"pending_amount\"]) position[\"close_orders\"][i] =",
"null, \"created_at\": \"2015-01-10T05:55:38.000Z\" }, { \"id\": 38632107, \"order_type\": \"buy\", \"rate\":",
"possible amount possible_make_total_price_base_cur = self.get_max_total_position_price_of_base_currency() - self.positioned_price_base possible_make_total_price_base_cur = min(possible_make_total_price_base_cur,",
"get_max_total_position_price_base(self): return self.get_max_total_position_price_of_base_currency() def get_max_total_position_price_of_base_currency(self): return self.max_total_position_price_base def get_positioned_price_base(self): return",
"stoploss_rate) = decide_make_ret else: (position_type, target_value) = decide_make_ret if target_value",
"None and order_type is not None: if abs(float(cur_rate)-float(target_value)) < 0.00001",
"abs(float(cur_amount)-float(possible_qty)) < 0.00001 and \\ cur_stoploss_float_or_none == target_stoploss_float_or_none and \\",
"to parse close_long order result\") try: print(ret_str) except Exception as",
"= True del self.exist_order_info_list[exist_order_i] else: exist_order_i += 1 if len(self.exist_order_info_list)",
"grouped_positions = [] positions = target_transactions if len(positions) > 0:",
"%f, you requested = %f\" % (qty_cur, min_qty, sell_qty,)) return",
"self.exist_order_info_list[exist_order_i] else: exist_order_i += 1 if len(self.exist_order_info_list) == 0: self.exist_order_info_list",
"True or \"id\" not in ret or ret[\"id\"] is None:",
"math.fmod(amount, tick) # a class for one position class OnePositionTrader(object):",
"float(stop_loss_rate) cur_amount = None if \"amount\" in exist_order_info: cur_amount =",
"26990, \"pair\": \"btc_jpy\", \"pending_amount\": \"0.77\", \"pending_market_buy_amount\": null, \"stop_loss_rate\": null, \"created_at\":",
"tick) # a class for one position class OnePositionTrader(object): def",
"pos in enumerate(positions): cur_created_at = pos[\"created_at_datetime\"] if abs((cur_created_at - prev_created_at).total_seconds())",
"= self.last_checked_transaction_id for transaction in all_transactions: transaction_id = int(transaction[\"id\"]) #",
"# 漏れがあるとまずい(cancelしなくなる)ので、とりあえずあるだけリンクしておく position_id_to_sellids[transaction_id] = [] transaction[\"close_orders\"] = [] positions.append(transaction) else:",
"時間的に約定時刻が近いpositionをまとめる def _group_near_transactions(self, target_transactions): grouped_positions = [] positions = target_transactions",
"\"created_at\": \"2015-01-10T05:55:38.000Z\" }, { \"id\": 38632107, \"order_type\": \"buy\", \"rate\": null,",
"few btc print(\"want to make (price,amount) = (%f,%f) but too",
"= float(stop_loss_rate) cur_amount = None if \"amount\" in exist_order_info: cur_amount",
"self.pair: continue position_id = position[\"id\"] # check position that is",
"amount = valid_close_order[\"amount\"] is_cur_close_long = False if \"side\" in valid_close_order:",
"from ChartBars import Chart from ChartUpdaterByCCWebsocket import ChartUpdaterByCoincheckWS from Util",
"(self.api is not None) # order list は現物とleverageで変わらない if self.exist_order_info_list",
"None, market-make def _update_or_create_close_order(self, position, target_value): position_id = position[\"id\"] if",
"#self.other_reserved_base = 0 #if not self.use_leverage: # for o in",
"grouped_positions # まだcloseされていないtransactionだけを残す def _remain_non_closed_transactions(self, target_transactions, positioned_value_in_qty): valid_positions = []",
"cur_stoploss_float_or_none == target_stoploss_float_or_none and \\ order_type == position_type: # same",
"orders if not self._cancel_exist_all_buy_orders(): return False, False # check minimum",
"json\") print(e) if ret is None or ret[\"success\"] is not",
"_group_near_transactions(self, target_transactions): grouped_positions = [] positions = target_transactions if len(positions)",
"update close orders according to current positions # this class",
"enumerate(valid_order_info): order_id = order[\"id\"] order_pair = order[\"pair\"] is_added = False",
"transaction[\"funds\"]: continue # this position is created by this class's",
"amount:%s, close_long:%s\" % (str(position_id), str(target_value), str(amount), str(is_cur_close_long),)) return True min_qty",
"valid_close_order[\"order_type\"] == \"sell\" if abs(float(rate)-float(target_value)) < 0.00001 and \\ abs(float(amount)-float(sell_qty))",
"None if \"rate\" in valid_close_order: rate = float(valid_close_order[\"rate\"]) amount =",
"# algorithm says this instance should not make order. cancel",
"and remain is canceled. this position is not ignored\") #continue",
"o in other_orders: # if o[\"order_type\"] == \"buy\": # self.other_reserved_base",
"< 0.00001 and \\ is_close_long == is_cur_close_long: # completely same!!",
"BitcoinUtil.roundBTCby1satoshi(sell_qty), 'order_type': 'sell', 'pair': self.pair, } if target_value is None:",
"make new positions according to algorithm # notice: this method",
"cur_created_at # remain positioned not be grouped grouped_positions.append(grouping(positions[concat_start_index:])) return grouped_positions",
"x:x[\"id\"], self.exist_close_order_info_list)) position[\"close_orders\"] = self.exist_close_order_info_list for i, order in enumerate(position[\"close_orders\"]):",
"or \"id\" not in ret or ret[\"id\"] is None: print(\"sell",
"True # do something ret_str = self.api.order.cancel({\"id\": order_id, \"pair\": self.pair})",
"exist_order_info[\"rate\"] if \"rate\" in exist_order_info else None # get current",
"order valid_close_orders = list(filter(lambda x:x[\"status\"] != \"cancel\" and x[\"id\"] in",
"float(position[\"amount\"]) created_time = position[\"created_at_datetime\"] target_value = None if self.price_decide_algorithm.market_sell_decide_algorithm(chart, open_rate,",
"order_type is not None: if abs(float(cur_rate)-float(target_value)) < 0.00001 and \\",
"possible_amount = 1.0 * possible_make_total_price_base_cur / target_value possible_amount = adjust_amount_to_tick(possible_amount,amount_tick)",
"{ 'amount': '%.8f' % BitcoinUtil.roundBTCby1satoshi(sell_qty), 'position_id': position_id, 'order_type': 'close_long' if",
"str\") try: print(ret_str) except Exception as e: print(\"failed to print",
"= self.exist_order_info_list[0] cur_rate = exist_order_info[\"rate\"] if \"rate\" in exist_order_info else",
"null, \"open_rate\": \"43553.0\", \"closed_rate\": null, \"amount\": \"1.51347797\", \"all_amount\": \"1.51045705\", \"side\":",
"\"amount\": \"1.51347797\", \"all_amount\": \"1.51045705\", \"side\": \"sell\", \"pl\": \"-8490.81029287\", \"new_order\": {",
"if is_close_long else 'close_short', 'pair': 'btc_jpy', } if target_value is",
"# total position price in base currency (actually paired currency)",
"target_transactions: if remain_qty <= 0: break amount = position[\"amount\"] if",
"should be called after update_status def update_close_orders(self, chart, current_time_timezone_aware): for",
"total_amount += p[\"amount\"] total_jpy += p[\"amount\"] * p[\"open_rate\"] ret_pos[\"amount\"] =",
"except Exception as e: print(\"failed to print error\") print(e) return",
"positioned_value_in_qty total_base = 0 for position in target_transactions: if remain_qty",
"new order valid_close_orders = list(filter(lambda x:x[\"status\"] != \"cancel\" and x[\"id\"]",
"while exist_order_i < len(self.exist_order_info_list): exist_order_info = self.exist_order_info_list[exist_order_i] if self._cancel_order(exist_order_info[\"id\"]) is",
"order: order[\"amount\"] = float(order[\"pending_amount\"]) position[\"close_orders\"][i] = order positions[pos_i] = position",
"Chart from ChartUpdaterByCCWebsocket import ChartUpdaterByCoincheckWS from Util import BitcoinUtil def",
"= 0 # used only for genbutsu self.max_free_margin_of_base_currency = 0",
"{ \"id\": 23755132, \"side\": \"buy\", \"rate\": \"10000.0\", \"amount\": \"1.0\", \"pending_amount\":",
"in desced_position_array: total_amount += p[\"amount\"] total_jpy += p[\"amount\"] * p[\"open_rate\"]",
"abs(float(cur_rate)-float(target_value)) < 0.00001 and \\ abs(float(cur_amount)-float(possible_qty)) < 0.00001 and \\",
"close_transactions = [] all_transactions = valid_transaction_info positioned_value_in_qty = self.positioned_value_in_qty qty_cur",
"float(transaction[\"funds\"][qty_cur]) transaction[\"amount\"] = transaction[\"amount\"] = qty_amount transaction[\"open_rate\"] = float(transaction[\"rate\"]) open_rate",
"= pos[\"created_at_datetime\"] if abs((cur_created_at - prev_created_at).total_seconds()) <= self.timelimit_to_grouping_transaction: # can",
"continue # this position is created by this class's order",
"ret = None if ret_str is not None: try: ret",
"self.positioned_price_base = positioned_value_in_base def _update_transaction_status(self, valid_transaction_info): if self.use_leverage: return #",
"+= float(qty_amount) created_time = dateutil.parser.parse(transaction[\"created_at\"]) transaction[\"created_at_datetime\"] = created_time if is_position_transaction:",
"price_decide_algorithm, api, pair=\"btc_jpy\", use_leverage = True): self.max_total_position_price_base = 0 #",
"\"2015-01-10T05:55:38.000Z\" }, { \"id\": 202836, \"order_type\": \"sell\", \"rate\": 26990, \"pair\":",
"p[\"open_rate\"] ret_pos[\"amount\"] = total_amount ret_pos[\"open_rate\"] = total_jpy / total_amount return",
"print(\"order cancel failed %d even if there is a valid",
"else: self._cancel_exist_all_buy_orders() print(\"algorithm wants to create a new order but",
"cur_amount = None if \"amount\" in exist_order_info: cur_amount = exist_order_info[\"amount\"]",
"or ret[\"id\"] is None: print(\"sell order canceled but failed to",
"ret: print(\"Failed to create order!!\") try: print(ret_str) except Exception as",
"self.exist_order_info_list[exist_order_i] if self._cancel_order(exist_order_info[\"id\"]) is False: # something error happened!! print(\"order",
"we cannot use orders that exceed this margin self.positions =",
"True or \"id\" not in ret: print(\"Failed to create order!!\")",
"this method should be called after update_status def update_new_orders(self, chart,",
"float(o[\"pending_amount\"]) * float(o[\"rate\"]) # returns: (is_success, is_new_order_created) def _update_or_create_order(self, position_type,",
"'sell' order = { 'rate': \"%.8f\" % target_value, 'amount': \"%.8f\"",
"'leverage_buy' if is_long else 'leverage_sell' if not self.use_leverage: order_type =",
"True or \"id\" not in ret: print(\"Failed to cancel order",
"old orders if len(self.got_all_order_ids) > 500: self.got_all_order_ids = self.got_all_order_ids[-500:] print(\"order",
"qty_cur, self.positioned_value_in_qty,)) # close したかどうか、残っているポジション残量を計算するのに、全て遡らないといけないのは現実的ではない # 既にこの段階で解決できるポジション状態(close order id見て、それがあれば反対売買が成立している) #",
"\"open\" order[\"side\"] = order[\"order_type\"] if \"amount\" not in order: order[\"amount\"]",
"orders # 漏れがあるとまずい(cancelしなくなる)ので、とりあえずあるだけリンクしておく position_id_to_sellids[transaction_id] = [] transaction[\"close_orders\"] = [] positions.append(transaction)",
"to show returned json str\") print(e) return False, False self.exist_order_info_list",
"# market order close pass else: target_value = self.price_decide_algorithm.sell_price_decide_algorithm(open_rate) target_value",
"in base currency self.positioned_price_base = 0 # total position price",
"transaction[\"open_rate\"] = float(transaction[\"rate\"]) open_rate = float(transaction[\"open_rate\"]) positioned_value_in_qty += float(qty_amount) created_time",
"position # round very small value if abs(positioned_value_in_qty) < self.api.order.min_create_amount(self.pair)*0.1:",
"if not is_added: other_orders.append(order) print(\"exist_create_orders\", exist_orders) print(\"exist_close_orders\", exist_close_orders) self.exist_order_info_list =",
"position type name if position_type == \"buy\": position_type = \"long\"",
"in enumerate(valid_order_info): order_id = order[\"id\"] order_pair = order[\"pair\"] is_added =",
"\"pair\": self.pair}) ret = None if ret_str is not None:",
"self._cancel_exist_all_buy_orders() print(\"algorithm wants to create a new order but DO_NOT_CREATE_NEW",
"i, order in enumerate(position[\"close_orders\"]): order[\"status\"] = \"open\" order[\"side\"] = order[\"order_type\"]",
"order_type, 'pair': self.pair } # not correct # this \"stop_loss_rate\"",
"qty_cur = self.get_qty_currency() print(\"Minimum order %s = %f, you requested",
"\"rate\" in valid_close_order: rate = float(valid_close_order[\"rate\"]) amount = valid_close_order[\"amount\"] is_cur_close_long",
"position_id, 'order_type': 'close_long' if is_close_long else 'close_short', 'pair': 'btc_jpy', }",
"if abs(float(rate)-float(target_value)) < 0.00001 and \\ abs(float(amount)-float(sell_qty)) < 0.00001 and",
"not None and cur_amount is not None and order_type is",
"\"btc_jpy\", \"pending_amount\": null, \"pending_market_buy_amount\": \"10000.0\", \"stop_loss_rate\": \"50000.0\", \"created_at\": \"2016-02-23T12:14:50.000Z\" }",
"if not is_close_long: print(\"normal order cannot make short position!\") print(\"you",
"return False if not do_not_create_new_order: success, new_order_created = self._update_or_create_order(position_type, target_value,",
"print(\"failed to parse api.order.create result\") try: print(ret_str) except Exception as",
"current_time_timezone_aware): for position in self.positions: open_rate = float(position[\"open_rate\"]) amount =",
"position example (array of \"data\" will be passed) { \"data\":",
"if stoploss_rate is not None: stoploss_rate = adjust_price_to_tick(stoploss_rate, tick) #",
"# parse orders #### \"\"\" orders example (array of \"orders\"",
"None: cur_stoploss_float_or_none = float(cur_stoploss) target_stoploss_float_or_none = None if stop_loss_rate is",
"canceled\") return True # do something ret_str = self.api.order.cancel({\"id\": order_id,",
"self.price_decide_algorithm.sell_price_decide_algorithm(open_rate) target_value = adjust_price_to_tick(target_value, self.api.order.tick_price(self.pair)) self._update_or_create_close_order(position, target_value) # interface to",
"その残ったpositionID, 消費した反対売買IDのIDを持っておき、次回からはそれより新しいIDのみを反映する # ただし、ずっと続けると計算誤差がたまるので、jpyもしくはbtcベースでその合計値が極めて小さくなったら丸めてノーポジ扱いにする # うーん...現物とレバレッジで管理が結構変わるから同じクラスにするのはまずかった?ごちゃごちゃしてきてしまった # 時間的に約定時刻が近いpositionをまとめる def _group_near_transactions(self,",
"created_time, current_time_timezone_aware) is True: # market order close pass else:",
"value. if None, market-make def _update_or_create_close_order(self, position, target_value): position_id =",
"total_amount = 0 total_jpy = 0 for p in desced_position_array:",
"min_qty, sell_qty,)) return False # cancel all for sell_id in",
"order_type = \"long\" if exist_order_info[\"order_type\"] == \"sell\" or \\ exist_order_info[\"order_type\"]",
"orders example (array of \"orders\" will be passed) { \"success\":",
"something ret_str = self.api.order.cancel({\"id\": order_id, \"pair\": self.pair}) ret = None",
"is not None: try: ret = json.loads(ret) except: print(\"failed to",
"% len(valid_close_orders)) if len(valid_close_orders) == 1 and target_value is not",
"e: print(\"failed to print error\") print(e) if ret is None",
"try: print(ret_str) except Exception as e: print(\"failed to print error\")",
"possible_amount = adjust_amount_to_tick(possible_amount,amount_tick) print(\"possible_create_in_base = %f, want to make amount",
"[] positions.append(transaction) else: close_transactions.append(transaction) # in next frame, only transaction_id",
"= %f, you requested = %f\" % (min_qty, possible_qty,)) return",
"position id:%s, target_value:%s, amount:%s, close_long:%s\" % (str(position_id), str(target_value), str(amount), str(is_cur_close_long),))",
"BitcoinUtil.roundBTCby1satoshi(sell_qty), 'position_id': position_id, 'order_type': 'close_long' if is_close_long else 'close_short', 'pair':",
"that exceed this margin self.positions = [] self.position_id_to_sellids = {}",
"1: exist_order_info = self.exist_order_info_list[0] cur_rate = exist_order_info[\"rate\"] if \"rate\" in",
"= list(filter(lambda x:x[\"status\"] != \"cancel\" and x[\"id\"] in sell_ids, position[\"close_orders\"]))",
"!= self.pair: continue position_id = position[\"id\"] # check position that",
"def _update_position_status(self, valid_position_info): # apply real positions status to this",
"order positions[pos_i] = position # round very small value if",
"is self.order_id: new_order = position[\"new_order\"] if new_order[\"status\"] == \"cancel\": print(\"new",
"if there is a valid order in internal state\" %",
"internal state\" % (exist_order_info[\"id\"],)) failed_to_cancel = True del self.exist_order_info_list[exist_order_i] else:",
"self.last_checked_transaction_id for transaction in all_transactions: transaction_id = int(transaction[\"id\"]) # transaction_id",
"None: if abs(float(cur_rate)-float(target_value)) < 0.00001 and \\ abs(float(cur_amount)-float(possible_qty)) < 0.00001",
"= self._remain_non_closed_transactions(grouped_positions, positioned_value_in_qty) if abs(positioned_value_in_base) < self.api.order.tick_price(self.pair) * self.api.order.min_create_amount(self.pair) *",
"= created_time if is_position_transaction: # check close orders # 漏れがあるとまずい(cancelしなくなる)ので、とりあえずあるだけリンクしておく",
"current stoploss cur_stoploss = exist_order_info[\"stop_loss_rate\"] if \"stop_loss_rate\" in exist_order_info else",
"float(position[\"amount\"]) sell_ids = self.position_id_to_sellids[position_id] position_type = position[\"side\"] # convert position",
"stop_loss_rate is not None: target_stoploss_float_or_none = float(stop_loss_rate) cur_amount = None",
"if \"side\" in valid_close_order: is_cur_close_long = valid_close_order[\"side\"] == \"sell\" elif",
"all_transactions: transaction_id = int(transaction[\"id\"]) # transaction_id means position_id transaction[\"id\"] =",
"round very small value if abs(positioned_value_in_qty) < self.api.order.min_create_amount(self.pair)*0.1: positioned_value_in_qty =",
"% (qty_cur, min_qty, sell_qty,)) return False # cancel all for",
"position[\"side\"] # convert position type name if position_type == \"buy\":",
"self.positioned_price_base possible_make_total_price_base_cur = min(possible_make_total_price_base_cur, self.max_free_margin_of_base_currency) amount_tick = self.api.order.tick_amount(self.pair) possible_amount =",
"+ reserved_margin + (positioned)) def set_max_total_position_price_base(self, p): self.set_max_total_position_price_of_base_currency(p) def set_max_total_position_price_of_base_currency(self,",
"except Exception as e: print(\"failed to show returned json str\")",
"# completely same!! print(\"requested close order is already ordered on",
"= [] all_transactions = valid_transaction_info positioned_value_in_qty = self.positioned_value_in_qty qty_cur =",
"# ただし、ずっと続けると計算誤差がたまるので、jpyもしくはbtcベースでその合計値が極めて小さくなったら丸めてノーポジ扱いにする # うーん...現物とレバレッジで管理が結構変わるから同じクラスにするのはまずかった?ごちゃごちゃしてきてしまった # 時間的に約定時刻が近いpositionをまとめる def _group_near_transactions(self, target_transactions): grouped_positions",
"\"id\": 38632107, \"order_type\": \"buy\", \"rate\": null, \"pair\": \"btc_jpy\", \"pending_amount\": null,",
"+ str(self) + \", pair=\" + str(pair)) @property def pair(self):",
"last_transaction_id_in_this_frame print(\"last_checked_transaction_id = \", self.last_checked_transaction_id) print(\"self.exist_close_order_info_list\", self.exist_close_order_info_list) if self.exist_close_order_info_list is",
"positions[pos_i] = position # round very small value if abs(positioned_value_in_qty)",
"< 0.00001 and \\ abs(float(amount)-float(sell_qty)) < 0.00001 and \\ is_close_long",
"api, pair=\"btc_jpy\", use_leverage = True): self.max_total_position_price_base = 0 # total",
"decide_make_ret = self.price_decide_algorithm.decide_make_position_order(chart) if len(decide_make_ret) == 3: (position_type, target_value, stoploss_rate)",
"remove closed position & update positioned_value_in_jpy valid_positions, positioned_value_in_base = self._remain_non_closed_transactions(grouped_positions,",
"created_time = dateutil.parser.parse(position[\"created_at\"]) position[\"created_at_datetime\"] = created_time amount = position[\"amount\"] all_amount",
"amount = all_amount position[\"amount\"] = position[\"all_amount\"] = amount self.positions.append(position) open_rate",
"if not is_position_transaction and not is_close_transaction: continue # other pair",
"order_pair == self.pair: if order_id in self.got_all_order_ids: is_added = True",
"len(exist_orders) > 0 else None self.exist_close_order_info_list = exist_close_orders if len(exist_close_orders)",
"position in self.positions: open_rate = float(position[\"open_rate\"]) amount = float(position[\"amount\"]) created_time",
"\"btc_jpy\", \"pending_amount\": \"0.5527\", \"pending_market_buy_amount\": null, \"stop_loss_rate\": null, \"created_at\": \"2015-01-10T05:55:38.000Z\" },",
"valid_close_order: is_cur_close_long = valid_close_order[\"order_type\"] == \"sell\" if abs(float(rate)-float(target_value)) < 0.00001",
"= 0 # merge position_id_to_sellids self.position_id_to_sellids = {} for position",
"is_long else 'leverage_sell' if not self.use_leverage: order_type = 'buy' if",
"import ChartUpdaterByCoincheckWS from Util import BitcoinUtil def adjust_price_to_tick(price, tick): return",
"not is_added: other_orders.append(order) print(\"exist_create_orders\", exist_orders) print(\"exist_close_orders\", exist_close_orders) self.exist_order_info_list = exist_orders",
"None and cur_amount is not None and order_type is not",
"exist_order_info else None # get current stoploss cur_stoploss = exist_order_info[\"stop_loss_rate\"]",
"\"order_type\": \"buy\", \"rate\": null, \"pair\": \"btc_jpy\", \"pending_amount\": null, \"pending_market_buy_amount\": \"10000.0\",",
"x:x[\"id\"], valid_order_info)) exist_orders = [] exist_close_orders = [] other_orders =",
"target_value = None if self.price_decide_algorithm.market_sell_decide_algorithm(chart, open_rate, created_time, current_time_timezone_aware) is True:",
"if stop_loss_rate is not None: target_stoploss_float_or_none = float(stop_loss_rate) cur_amount =",
"exist_order_info[\"pending_amount\"] order_type = None if \"order_type\" in exist_order_info: if exist_order_info[\"order_type\"]",
"position_type == \"buy\": position_type = \"long\" if position_type == \"sell\":",
"> 0 else None self.exist_close_order_info_list = exist_close_orders if len(exist_close_orders) >",
"pos[\"created_at_datetime\"] if abs((cur_created_at - prev_created_at).total_seconds()) <= self.timelimit_to_grouping_transaction: # can group",
"p): self.set_max_total_position_price_of_base_currency(p) def set_max_total_position_price_of_base_currency(self, p): self.max_total_position_price_base = p def set_max_free_margin_of_base_currency(self,",
"float(order[\"pending_amount\"]) position[\"close_orders\"][i] = order positions[pos_i] = position # round very",
"\"30010.0\", \"amount\": \"1.3\", \"order_type\": \"sell\", \"stop_loss_rate\": null, \"pair\": \"btc_jpy\", \"created_at\":",
"\"cancel\", position[\"close_orders\"]))) self.positioned_price_base = positioned_value_in_base def _update_transaction_status(self, valid_transaction_info): if self.use_leverage:",
"0 #if not self.use_leverage: # for o in other_orders: #",
"exist_order_info = self.exist_order_info_list[exist_order_i] if self._cancel_order(exist_order_info[\"id\"]) is False: # something error",
"ret[\"success\"] is not True or \"id\" not in ret or",
"internal position & order status def update_status(self, valid_position_info, valid_transaction_info, valid_order_info):",
"(available_margin + reserved_margin + (positioned)) def set_max_total_position_price_base(self, p): self.set_max_total_position_price_of_base_currency(p) def",
"self.last_checked_transaction_id) print(\"self.exist_close_order_info_list\", self.exist_close_order_info_list) if self.exist_close_order_info_list is not None: for pos_i,",
"< len(self.exist_order_info_list): exist_order_info = self.exist_order_info_list[exist_order_i] if self._cancel_order(exist_order_info[\"id\"]) is False: #",
"- math.fmod(amount, tick) # a class for one position class",
"# cancel all exist orders if not self._cancel_exist_all_buy_orders(): return False,",
"order_type = 'leverage_buy' if is_long else 'leverage_sell' if not self.use_leverage:",
"\", self.last_checked_transaction_id) print(\"self.exist_close_order_info_list\", self.exist_close_order_info_list) if self.exist_close_order_info_list is not None: for",
"\"created_at\": \"2015-12-05T05:03:56.000Z\" } ] } ] } \"\"\" #### #",
"sell_ids self.got_close_order_ids.append(ret[\"id\"]) if len(self.got_close_order_ids) > 500: self.got_close_order_ids = self.got_close_order_ids[-500:] return",
"self.max_free_margin_of_base_currency) amount_tick = self.api.order.tick_amount(self.pair) possible_amount = 1.0 * possible_make_total_price_base_cur /",
"\"2015-01-10T05:55:38.000Z\" \"\"\" is_long = position_type == \"long\" order_type = 'leverage_buy'",
"self._update_or_create_close_order(position, target_value) # interface to update internal position & order",
"for position in target_transactions: if remain_qty <= 0: break amount",
"to current positions # this class should be called after",
"== \"short\": is_close_long = False # check exist sell-orders. if",
"position[\"id\"] self.position_id_to_sellids[pos_id] = position_id_to_sellids[pos_id] self.positioned_price_base = positioned_value_in_base self.positioned_value_in_qty = positioned_value_in_qty",
"name if position_type == \"buy\": position_type = \"long\" if position_type",
"None stoploss_rate = None decide_make_ret = self.price_decide_algorithm.decide_make_position_order(chart) if len(decide_make_ret) ==",
"other_orders = [] for idx, order in enumerate(valid_order_info): order_id =",
"Exception as e: print(\"failed to show returned json str\") print(e)",
"None: try: ret = json.loads(ret) except: print(\"failed to parse close_long",
"len(exist_close_orders) > 0 else None #self.other_reserved_base = 0 #if not",
"try: print(ret_str) except Exception as e: print(\"failed to show returned",
"(str(position_id),)) try: print(ret_str) except Exception as e: print(\"failed to print",
"else: position[\"amount\"] = remain_qty remain_qty = 0 valid_positions.append(position) total_base +=",
"sashine will be placed at \"rate\" if stop_loss_rate is not",
"if len(exist_close_orders) > 0 else None #self.other_reserved_base = 0 #if",
"self.timelimit_to_grouping_transaction: # can group prev_created_at = cur_created_at continue # this",
"be grouped. make a new group from pos[start_index] - pos[idx-1]",
"all_amount position[\"amount\"] = position[\"all_amount\"] = amount self.positions.append(position) open_rate = position[\"open_rate\"]",
"ret_pos concat_start_index = 0 prev_created_at = positions[0][\"created_at_datetime\"] for idx, pos",
"sell_qty,)) return False # cancel all for sell_id in sell_ids:",
"self.exist_order_info_list = exist_orders if len(exist_orders) > 0 else None self.exist_close_order_info_list",
"\"rate\" if stop_loss_rate is not None: order[\"stop_loss_rate\"] = stop_loss_rate ret_str",
"exist orders if not self._cancel_exist_all_buy_orders(): return False, False # check",
"to print returned error json\") print(e) if ret is None",
"ret_str = ret if ret is not None: try: ret",
"position in valid_positions: pos_id = position[\"id\"] self.position_id_to_sellids[pos_id] = position_id_to_sellids[pos_id] self.positioned_price_base",
"def _update_or_create_close_order(self, position, target_value): position_id = position[\"id\"] if position_id not",
"new_order_id in self.got_close_order_ids if not is_position_transaction and not is_close_transaction: continue",
"if \"rate\" in valid_close_order: rate = float(valid_close_order[\"rate\"]) amount = valid_close_order[\"amount\"]",
"= target_value ret = self.api.order.create(order) ret_str = ret if ret",
"base = %f, possible amount = %f\" % (self.get_max_total_position_price_of_base_currency() -",
"position_id not in self.position_id_to_sellids: return False sell_qty = float(position[\"amount\"]) sell_ids",
"len(valid_close_orders) == 1 and target_value is not None: # check",
"a new order but DO_NOT_CREATE_NEW flag = true\") return False",
"0 # total position price in base currency (actually paired",
"target_value possible_amount = adjust_amount_to_tick(possible_amount,amount_tick) print(\"possible_create_in_base = %f, want to make",
"= position # round very small value if abs(positioned_value_in_qty) <",
"{} self.got_all_order_ids = [] self.got_close_order_ids = [] self.exist_order_info_list = None",
"if position_type == \"short\": is_close_long = False # check exist",
"total_jpy += p[\"amount\"] * p[\"open_rate\"] ret_pos[\"amount\"] = total_amount ret_pos[\"open_rate\"] =",
"# this position cannot be grouped. make a new group",
"\"side\" in valid_close_order: is_cur_close_long = valid_close_order[\"side\"] == \"sell\" elif \"order_type\"",
"passed close 'short' for normal order\") return False order =",
"% (str(position_id), str(target_value), str(amount), str(is_cur_close_long),)) return True min_qty = self.api.order.min_create_amount(self.pair)",
"(actually paired currency) self.positioned_value_in_qty = 0 # used only for",
"if target_value is None: # market_sell order['order_type'] = \"market_sell\" else:"
] |
[
"Relay(\"RELAY8\") r1.off() r2.off() r3.off() r4.off() r5.off() r6.off() r7.off() r8.off() r1.on()",
"time.sleep(0.5) r1.off() time.sleep(0.5) r2.on() time.sleep(0.5) r2.off() time.sleep(0.5) r3.on() time.sleep(0.5) r3.off()",
"= Relay(\"RELAY2\") r3 = Relay(\"RELAY3\") r4 = Relay(\"RELAY4\") r5 =",
"Relay(\"RELAY2\") r3 = Relay(\"RELAY3\") r4 = Relay(\"RELAY4\") r5 = Relay(\"RELAY5\")",
"r7.off() r8.off() r1.on() time.sleep(0.5) r1.off() time.sleep(0.5) r2.on() time.sleep(0.5) r2.off() time.sleep(0.5)",
"time.sleep(0.5) r6.on() time.sleep(0.5) r6.off() time.sleep(0.5) r7.on() time.sleep(0.5) r7.off() time.sleep(0.5) r8.on()",
"time.sleep(0.5) r6.off() time.sleep(0.5) r7.on() time.sleep(0.5) r7.off() time.sleep(0.5) r8.on() time.sleep(0.5) r8.off()",
"= Relay(\"RELAY4\") r5 = Relay(\"RELAY5\") r6 = Relay(\"RELAY6\") r7 =",
"r3.off() r4.off() r5.off() r6.off() r7.off() r8.off() r1.on() time.sleep(0.5) r1.off() time.sleep(0.5)",
"r3 = Relay(\"RELAY3\") r4 = Relay(\"RELAY4\") r5 = Relay(\"RELAY5\") r6",
"r7 = Relay(\"RELAY7\") r8 = Relay(\"RELAY8\") r1.off() r2.off() r3.off() r4.off()",
"r2 = Relay(\"RELAY2\") r3 = Relay(\"RELAY3\") r4 = Relay(\"RELAY4\") r5",
"time.sleep(0.5) r5.on() time.sleep(0.5) r5.off() time.sleep(0.5) r6.on() time.sleep(0.5) r6.off() time.sleep(0.5) r7.on()",
"r1.on() time.sleep(0.5) r1.off() time.sleep(0.5) r2.on() time.sleep(0.5) r2.off() time.sleep(0.5) r3.on() time.sleep(0.5)",
"import time r1 = Relay(\"RELAY1\") r2 = Relay(\"RELAY2\") r3 =",
"r2.off() r3.off() r4.off() r5.off() r6.off() r7.off() r8.off() r1.on() time.sleep(0.5) r1.off()",
"r6 = Relay(\"RELAY6\") r7 = Relay(\"RELAY7\") r8 = Relay(\"RELAY8\") r1.off()",
"r5.on() time.sleep(0.5) r5.off() time.sleep(0.5) r6.on() time.sleep(0.5) r6.off() time.sleep(0.5) r7.on() time.sleep(0.5)",
"r4.off() time.sleep(0.5) r5.on() time.sleep(0.5) r5.off() time.sleep(0.5) r6.on() time.sleep(0.5) r6.off() time.sleep(0.5)",
"time.sleep(0.5) r3.off() time.sleep(0.5) r4.on() time.sleep(0.5) r4.off() time.sleep(0.5) r5.on() time.sleep(0.5) r5.off()",
"= Relay(\"RELAY7\") r8 = Relay(\"RELAY8\") r1.off() r2.off() r3.off() r4.off() r5.off()",
"time.sleep(0.5) r4.off() time.sleep(0.5) r5.on() time.sleep(0.5) r5.off() time.sleep(0.5) r6.on() time.sleep(0.5) r6.off()",
"time.sleep(0.5) r2.on() time.sleep(0.5) r2.off() time.sleep(0.5) r3.on() time.sleep(0.5) r3.off() time.sleep(0.5) r4.on()",
"import Relay import time r1 = Relay(\"RELAY1\") r2 = Relay(\"RELAY2\")",
"r5.off() time.sleep(0.5) r6.on() time.sleep(0.5) r6.off() time.sleep(0.5) r7.on() time.sleep(0.5) r7.off() time.sleep(0.5)",
"r5.off() r6.off() r7.off() r8.off() r1.on() time.sleep(0.5) r1.off() time.sleep(0.5) r2.on() time.sleep(0.5)",
"r4.off() r5.off() r6.off() r7.off() r8.off() r1.on() time.sleep(0.5) r1.off() time.sleep(0.5) r2.on()",
"r4 = Relay(\"RELAY4\") r5 = Relay(\"RELAY5\") r6 = Relay(\"RELAY6\") r7",
"r6.on() time.sleep(0.5) r6.off() time.sleep(0.5) r7.on() time.sleep(0.5) r7.off() time.sleep(0.5) r8.on() time.sleep(0.5)",
"= Relay(\"RELAY1\") r2 = Relay(\"RELAY2\") r3 = Relay(\"RELAY3\") r4 =",
"time r1 = Relay(\"RELAY1\") r2 = Relay(\"RELAY2\") r3 = Relay(\"RELAY3\")",
"time.sleep(0.5) r2.off() time.sleep(0.5) r3.on() time.sleep(0.5) r3.off() time.sleep(0.5) r4.on() time.sleep(0.5) r4.off()",
"= Relay(\"RELAY8\") r1.off() r2.off() r3.off() r4.off() r5.off() r6.off() r7.off() r8.off()",
"PiRelay8 import Relay import time r1 = Relay(\"RELAY1\") r2 =",
"Relay(\"RELAY4\") r5 = Relay(\"RELAY5\") r6 = Relay(\"RELAY6\") r7 = Relay(\"RELAY7\")",
"from PiRelay8 import Relay import time r1 = Relay(\"RELAY1\") r2",
"time.sleep(0.5) r4.on() time.sleep(0.5) r4.off() time.sleep(0.5) r5.on() time.sleep(0.5) r5.off() time.sleep(0.5) r6.on()",
"= Relay(\"RELAY5\") r6 = Relay(\"RELAY6\") r7 = Relay(\"RELAY7\") r8 =",
"Relay(\"RELAY5\") r6 = Relay(\"RELAY6\") r7 = Relay(\"RELAY7\") r8 = Relay(\"RELAY8\")",
"Relay(\"RELAY3\") r4 = Relay(\"RELAY4\") r5 = Relay(\"RELAY5\") r6 = Relay(\"RELAY6\")",
"Relay import time r1 = Relay(\"RELAY1\") r2 = Relay(\"RELAY2\") r3",
"r3.on() time.sleep(0.5) r3.off() time.sleep(0.5) r4.on() time.sleep(0.5) r4.off() time.sleep(0.5) r5.on() time.sleep(0.5)",
"r6.off() r7.off() r8.off() r1.on() time.sleep(0.5) r1.off() time.sleep(0.5) r2.on() time.sleep(0.5) r2.off()",
"Relay(\"RELAY6\") r7 = Relay(\"RELAY7\") r8 = Relay(\"RELAY8\") r1.off() r2.off() r3.off()",
"= Relay(\"RELAY3\") r4 = Relay(\"RELAY4\") r5 = Relay(\"RELAY5\") r6 =",
"r8 = Relay(\"RELAY8\") r1.off() r2.off() r3.off() r4.off() r5.off() r6.off() r7.off()",
"time.sleep(0.5) r3.on() time.sleep(0.5) r3.off() time.sleep(0.5) r4.on() time.sleep(0.5) r4.off() time.sleep(0.5) r5.on()",
"<reponame>sbcshop/PiRelay-8<filename>test.py<gh_stars>1-10 from PiRelay8 import Relay import time r1 = Relay(\"RELAY1\")",
"r2.on() time.sleep(0.5) r2.off() time.sleep(0.5) r3.on() time.sleep(0.5) r3.off() time.sleep(0.5) r4.on() time.sleep(0.5)",
"r8.off() r1.on() time.sleep(0.5) r1.off() time.sleep(0.5) r2.on() time.sleep(0.5) r2.off() time.sleep(0.5) r3.on()",
"r5 = Relay(\"RELAY5\") r6 = Relay(\"RELAY6\") r7 = Relay(\"RELAY7\") r8",
"time.sleep(0.5) r5.off() time.sleep(0.5) r6.on() time.sleep(0.5) r6.off() time.sleep(0.5) r7.on() time.sleep(0.5) r7.off()",
"r1.off() r2.off() r3.off() r4.off() r5.off() r6.off() r7.off() r8.off() r1.on() time.sleep(0.5)",
"r1 = Relay(\"RELAY1\") r2 = Relay(\"RELAY2\") r3 = Relay(\"RELAY3\") r4",
"r4.on() time.sleep(0.5) r4.off() time.sleep(0.5) r5.on() time.sleep(0.5) r5.off() time.sleep(0.5) r6.on() time.sleep(0.5)",
"= Relay(\"RELAY6\") r7 = Relay(\"RELAY7\") r8 = Relay(\"RELAY8\") r1.off() r2.off()",
"r1.off() time.sleep(0.5) r2.on() time.sleep(0.5) r2.off() time.sleep(0.5) r3.on() time.sleep(0.5) r3.off() time.sleep(0.5)",
"Relay(\"RELAY7\") r8 = Relay(\"RELAY8\") r1.off() r2.off() r3.off() r4.off() r5.off() r6.off()",
"r2.off() time.sleep(0.5) r3.on() time.sleep(0.5) r3.off() time.sleep(0.5) r4.on() time.sleep(0.5) r4.off() time.sleep(0.5)",
"r6.off() time.sleep(0.5) r7.on() time.sleep(0.5) r7.off() time.sleep(0.5) r8.on() time.sleep(0.5) r8.off() time.sleep(0.5)",
"Relay(\"RELAY1\") r2 = Relay(\"RELAY2\") r3 = Relay(\"RELAY3\") r4 = Relay(\"RELAY4\")",
"r3.off() time.sleep(0.5) r4.on() time.sleep(0.5) r4.off() time.sleep(0.5) r5.on() time.sleep(0.5) r5.off() time.sleep(0.5)"
] |
[
"'Captain': self.bot.setting.clan_settings['Captain']['Emoji'], 'General': self.bot.setting.clan_settings['General']['Emoji'], } ranks_embed = discord.Embed( title=\"__Ranks a",
"125_000_000 elif clan.lower() == 'argus': exp_general = 500_000_000 exp_captain =",
"if player.private_profile: clan_info_embed.add_field( name=total_exp_header, value=private_profile_header, inline=False ) else: clan_info_embed.add_field( name=total_exp_header,",
"clan_info_embed.add_field( name=total_exp_header, value=private_profile_header, inline=False ) else: clan_info_embed.add_field( name=total_exp_header, value=f\"{player.exp:,}\" )",
"Argus' else: return await ctx.send('Clã não reconhecido.') rank_emoji = {",
"'Owner': clan_leader = member.name clan_url = clan.name.replace(' ', '%20') clan_embed",
"rs3clans.Clan(name=clan_name, set_exp=True) except ConnectionError: return await ctx.send(f\"Houve um erro ao",
">= 20: await ctx.send('Muitos ranks a serem atualizados, enviando apenas",
"clan: if member.rank == 'Owner': clan_leader = member.name clan_url =",
"{player.name}\" user_url_name = player.name.replace(\" \", \"%20\") user_url_clan = player.clan.replace(\" \",",
") if player.private_profile: clan_info_embed.add_field( name=total_exp_header, value=private_profile_header, inline=False ) else: clan_info_embed.add_field(",
"'Sergeant': self.bot.setting.clan_settings['Sergeant']['Emoji'], 'Lieutenant': self.bot.setting.clan_settings['Lieutenant']['Emoji'], 'Captain': self.bot.setting.clan_settings['Captain']['Emoji'], 'General': self.bot.setting.clan_settings['General']['Emoji'], } ranks_embed",
"import commands from bot.bot_client import Bot from bot.utils.tools import separator",
"os 20 primeiros.') break if member.exp >= exp_corporal and member.rank",
"value=f\"Tenente {rank_emoji['Lieutenant']} ❯ Capitão {rank_emoji['Captain']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found =",
"atualizado no momento :)\", value=separator, inline=False ) return await ctx.send(embed=ranks_embed)",
"and member.rank == 'Captain': ranks_embed.add_field( name=member.name, value=f\"Capitão {rank_emoji['Captain']} ❯ General",
"= 500_000_000 exp_seargent = 250_000_000 exp_corporal = 125_000_000 elif clan.lower()",
"= True elif member.exp >= exp_general and member.rank == 'Captain':",
"str): try: clan = rs3clans.Clan(name=clan_name, set_exp=True) except ConnectionError: return await",
"rank_emoji = { 'Recruit': self.bot.setting.clan_settings['Recruit']['Emoji'], 'Corporal': self.bot.setting.clan_settings['Corporal']['Emoji'], 'Sergeant': self.bot.setting.clan_settings['Sergeant']['Emoji'], 'Lieutenant':",
"await ctx.send(f\"Houve um erro ao tentar conectar a API da",
"inline=False) found = True elif member.exp >= exp_lieutenant and member.rank",
"❯ Capitão {rank_emoji['Captain']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found = True elif",
"= 30_000_000 clan = 'Atlantis Argus' else: return await ctx.send('Clã",
"\"__Exp Total__\" private_profile_header = \"Indisponível - Perfil Privado\" rank_emoji =",
"found = True elif member.exp >= exp_lieutenant and member.rank ==",
"{ 'Recruit': self.bot.setting.clan_settings['Recruit']['Emoji'], 'Corporal': self.bot.setting.clan_settings['Corporal']['Emoji'], 'Sergeant': self.bot.setting.clan_settings['Sergeant']['Emoji'], 'Lieutenant': self.bot.setting.clan_settings['Lieutenant']['Emoji'], 'Captain':",
"= True elif member.exp >= exp_lieutenant and member.rank == 'Sergeant':",
"❯ Cabo {rank_emoji['Corporal']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found = True elif",
"ctx.send(f\"Jogador '{player.name}' não existe.\") if not player.clan: return await ctx.send(f\"Jogador",
"ranks_embed.add_field( name=member.name, value=f\"Capitão {rank_emoji['Captain']} ❯ General {rank_emoji['General']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False)",
"from bot.utils.tools import separator from bot.utils.context import Context class Clan(commands.Cog):",
"not player.exists: return await ctx.send(f\"Jogador '{player.name}' não existe.\") if not",
"'rank']) async def ranks(self, ctx: Context, *, clan: str =",
"exp_general = 500_000_000 exp_captain = 250_000_000 exp_lieutenant = 125_000_000 exp_seargent",
"description=\"\", color=discord.Colour.dark_blue(), url=runeclan_url, ) clan_info_embed.set_author( icon_url=icon_url, name=display_username ) clan_info_embed.set_thumbnail( url=clan_banner_url",
"clan = rs3clans.Clan(name=clan_name, set_exp=True) except ConnectionError: return await ctx.send(f\"Houve um",
"Atualizar__\", description=\" \", ) found = False clan = rs3clans.Clan(clan,",
"return await ctx.send('Clã não reconhecido.') rank_emoji = { 'Recruit': self.bot.setting.clan_settings['Recruit']['Emoji'],",
"member.rank == 'Corporal': ranks_embed.add_field( name=member.name, value=f\"Cabo {rank_emoji['Corporal']} ❯ Sargento {rank_emoji['Sergeant']}\\n\"",
") found = False clan = rs3clans.Clan(clan, set_exp=False) clan_members =",
"Context, *, clan: str = 'Atlantis'): if clan.lower() == 'atlantis",
"for member in clan]) member: rs3clans.ClanMember for member in clan_members:",
"Clã__\" total_exp_header = \"__Exp Total__\" private_profile_header = \"Indisponível - Perfil",
"f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found = True elif member.exp >= exp_general",
"ctx: Context, *, username: str): try: player = rs3clans.Player(name=username, runemetrics=True)",
"<gh_stars>0 import rs3clans import discord from discord.ext import commands from",
"*, clan_name: str): try: clan = rs3clans.Clan(name=clan_name, set_exp=True) except ConnectionError:",
"member.rank == 'Recruit': ranks_embed.add_field( name=member.name, value=f\"Recruta {rank_emoji['Recruit']} ❯ Cabo {rank_emoji['Corporal']}\\n\"",
">= exp_lieutenant and member.rank == 'Sergeant': ranks_embed.add_field( name=member.name, value=f\"Sargento {rank_emoji['Sergeant']}",
"self.bot.setting.show_titles: if player.suffix: display_username = f\"{player.name} {player.title}\" else: display_username =",
"'Corporal': self.bot.setting.clan_settings['Corporal']['Emoji'], 'Sergeant': self.bot.setting.clan_settings['Sergeant']['Emoji'], 'Lieutenant': self.bot.setting.clan_settings['Lieutenant']['Emoji'], 'Captain': self.bot.setting.clan_settings['Captain']['Emoji'], 'General': self.bot.setting.clan_settings['General']['Emoji'],",
"name=total_exp_header, value=f\"{player.exp:,}\" ) return await ctx.send(content=None, embed=clan_info_embed) @commands.cooldown(1, 5, commands.BucketType.user)",
") clan_info_embed.set_thumbnail( url=clan_banner_url ) clan_info_embed.add_field( name=clan_header, value=player.clan ) clan_info_embed.add_field( name=rank_header,",
"'General': self.bot.setting.clan_settings['General']['Emoji'], } ranks_embed = discord.Embed( title=\"__Ranks a Atualizar__\", description=\"",
"user_clan_exp = member.exp user_rank = member.rank display_username = player.name if",
"- Perfil Privado\" rank_emoji = self.bot.setting.clan_settings[user_rank]['Emoji'] user_rank = self.bot.setting.clan_settings[user_rank]['Translation'] clan_info_embed",
"250_000_000 exp_lieutenant = 125_000_000 exp_seargent = 60_000_000 exp_corporal = 30_000_000",
"'argus': exp_general = 500_000_000 exp_captain = 250_000_000 exp_lieutenant = 125_000_000",
"found = True elif member.exp >= exp_seargent and member.rank ==",
"'Atlantis Argus' else: return await ctx.send('Clã não reconhecido.') rank_emoji =",
"'clãinfo']) async def clan_user_info(self, ctx: Context, *, username: str): try:",
"elif member.exp >= exp_lieutenant and member.rank == 'Sergeant': ranks_embed.add_field( name=member.name,",
"user_rank = member.rank display_username = player.name if self.bot.setting.show_titles: if player.suffix:",
"value=private_profile_header, inline=False ) else: clan_info_embed.add_field( name=total_exp_header, value=f\"{player.exp:,}\" ) return await",
"'Lieutenant': ranks_embed.add_field( name=member.name, value=f\"Tenente {rank_emoji['Lieutenant']} ❯ Capitão {rank_emoji['Captain']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\",",
"Jagex. Tente novamente mais tarde.\") except rs3clans.ClanNotFoundError: return await ctx.send(f\"O",
"= self.bot.setting.clan_settings[user_rank]['Emoji'] user_rank = self.bot.setting.clan_settings[user_rank]['Translation'] clan_info_embed = discord.Embed( title=embed_title, description=\"\",",
"novamente mais tarde.\") except rs3clans.ClanNotFoundError: return await ctx.send(f\"O clã '{clan_name}'",
"member: rs3clans.ClanMember for member in clan_members: if len(ranks_embed.fields) >= 20:",
"ranks_embed.add_field( name=member.name, value=f\"Sargento {rank_emoji['Sergeant']} ❯ Tenente {rank_emoji['Lieutenant']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False)",
"irmão') elif clan.lower() == 'atlantis': exp_general = 2_000_000_000 exp_captain =",
"player.suffix: display_username = f\"{player.name} {player.title}\" else: display_username = f\"{player.title} {player.name}\"",
"@commands.command(aliases=['clan']) async def clan_detail_info(self, ctx: Context, *, clan_name: str): try:",
"= 'Atlantis Argus' else: return await ctx.send('Clã não reconhecido.') rank_emoji",
"await ctx.send(f\"O clã '{clan_name}' não existe.\") clan_leader = None for",
"exp_captain = 1_000_000_000 exp_lieutenant = 500_000_000 exp_seargent = 250_000_000 exp_corporal",
"= { 'Recruit': self.bot.setting.clan_settings['Recruit']['Emoji'], 'Corporal': self.bot.setting.clan_settings['Corporal']['Emoji'], 'Sergeant': self.bot.setting.clan_settings['Sergeant']['Emoji'], 'Lieutenant': self.bot.setting.clan_settings['Lieutenant']['Emoji'],",
"ranks(self, ctx: Context, *, clan: str = 'Atlantis'): if clan.lower()",
"member.rank == 'Lieutenant': ranks_embed.add_field( name=member.name, value=f\"Tenente {rank_emoji['Lieutenant']} ❯ Capitão {rank_emoji['Captain']}\\n\"",
"return await ctx.send('`!rank argus` irmão') elif clan.lower() == 'atlantis': exp_general",
") clan_info_embed.add_field( name=exp_header, value=f\"{user_clan_exp:,}\" ) if player.private_profile: clan_info_embed.add_field( name=total_exp_header, value=private_profile_header,",
"125_000_000 exp_seargent = 60_000_000 exp_corporal = 30_000_000 clan = 'Atlantis",
"= self.bot.setting.clan_settings[user_rank]['Translation'] clan_info_embed = discord.Embed( title=embed_title, description=\"\", color=discord.Colour.dark_blue(), url=runeclan_url, )",
"player = rs3clans.Player(name=username, runemetrics=True) except ConnectionError: return await ctx.send(f\"Houve um",
"tarde.\") if not player.exists: return await ctx.send(f\"Jogador '{player.name}' não existe.\")",
"Clan(commands.Cog): def __init__(self, bot: Bot): self.bot = bot @commands.cooldown(1, 5,",
"clan_info_embed.add_field( name=total_exp_header, value=f\"{player.exp:,}\" ) return await ctx.send(content=None, embed=clan_info_embed) @commands.cooldown(1, 5,",
"existe.\") if not player.clan: return await ctx.send(f\"Jogador '{player.name}' não está",
"ctx.send(f\"Jogador '{player.name}' não está em um clã.\") user_clan = rs3clans.Clan(name=player.clan)",
"set_exp=False) clan_members = reversed([member for member in clan]) member: rs3clans.ClanMember",
"clan_banner_url = f\"http://services.runescape.com/m=avatar-rs/l=3/a=869/{user_url_clan}/clanmotif.png\" embed_title = \"RuneClan\" rank_header = \"__Rank__\" clan_header",
"rs3clans.ClanNotFoundError: return await ctx.send(f\"O clã '{clan_name}' não existe.\") clan_leader =",
"inline=False ) else: clan_info_embed.add_field( name=total_exp_header, value=f\"{player.exp:,}\" ) return await ctx.send(content=None,",
"if clan.lower() == 'atlantis argus': return await ctx.send('`!rank argus` irmão')",
"ctx.send(content=None, embed=clan_info_embed) @commands.cooldown(1, 5, commands.BucketType.user) @commands.bot_has_permissions(embed_links=True) @commands.command(aliases=['ranksupdate', 'upranks', 'rank']) async",
"clan_embed.set_thumbnail(url=f'http://services.runescape.com/m=avatar-rs/{clan_url}/clanmotif.png') clan_embed.add_field(name=\"Exp Total\", value=f'{clan.exp:,}') clan_embed.add_field(name=\"Membros\", value=str(clan.count)) clan_embed.add_field(name=\"Líder\", value=clan_leader) clan_embed.add_field(name=\"Exp Média",
"novamente mais tarde.\") if not player.exists: return await ctx.send(f\"Jogador '{player.name}'",
"Sargento {rank_emoji['Sergeant']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found = True if not",
"color=discord.Colour.dark_blue(), url=runeclan_url, ) clan_info_embed.set_author( icon_url=icon_url, name=display_username ) clan_info_embed.set_thumbnail( url=clan_banner_url )",
"if len(ranks_embed.fields) >= 20: await ctx.send('Muitos ranks a serem atualizados,",
"name=member.name, value=f\"Tenente {rank_emoji['Lieutenant']} ❯ Capitão {rank_emoji['Captain']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found",
"== 'Captain': ranks_embed.add_field( name=member.name, value=f\"Capitão {rank_emoji['Captain']} ❯ General {rank_emoji['General']}\\n\" f\"**__Exp:__**",
"\"%20\") icon_url = f\"https://secure.runescape.com/m=avatar-rs/{user_url_name}/chat.png\" runeclan_url = f\"https://runeclan.com/user/{user_url_name}\" clan_banner_url = f\"http://services.runescape.com/m=avatar-rs/l=3/a=869/{user_url_clan}/clanmotif.png\"",
"await ctx.send(f\"Jogador '{player.name}' não está em um clã.\") user_clan =",
"20: await ctx.send('Muitos ranks a serem atualizados, enviando apenas os",
"rs3clans.Player(name=username, runemetrics=True) except ConnectionError: return await ctx.send(f\"Houve um erro ao",
"from bot.bot_client import Bot from bot.utils.tools import separator from bot.utils.context",
"commands.BucketType.user) @commands.bot_has_permissions(embed_links=True) @commands.command(aliases=['clan']) async def clan_detail_info(self, ctx: Context, *, clan_name:",
"found = False clan = rs3clans.Clan(clan, set_exp=False) clan_members = reversed([member",
"title=\"__Ranks a Atualizar__\", description=\" \", ) found = False clan",
"except rs3clans.ClanNotFoundError: return await ctx.send(f\"O clã '{clan_name}' não existe.\") clan_leader",
"description=\" \", ) found = False clan = rs3clans.Clan(clan, set_exp=False)",
"member.rank == 'Sergeant': ranks_embed.add_field( name=member.name, value=f\"Sargento {rank_emoji['Sergeant']} ❯ Tenente {rank_emoji['Lieutenant']}\\n\"",
"display_username = f\"{player.name} {player.title}\" else: display_username = f\"{player.title} {player.name}\" user_url_name",
"a API da Jagex. Tente novamente mais tarde.\") if not",
"clan_members: if len(ranks_embed.fields) >= 20: await ctx.send('Muitos ranks a serem",
"found: ranks_embed.add_field( name=\"Nenhum Rank a ser atualizado no momento :)\",",
"self.bot.setting.clan_settings['Lieutenant']['Emoji'], 'Captain': self.bot.setting.clan_settings['Captain']['Emoji'], 'General': self.bot.setting.clan_settings['General']['Emoji'], } ranks_embed = discord.Embed( title=\"__Ranks",
"return await ctx.send(content=None, embed=clan_info_embed) @commands.cooldown(1, 5, commands.BucketType.user) @commands.bot_has_permissions(embed_links=True) @commands.command(aliases=['ranksupdate', 'upranks',",
"a API da Jagex. Tente novamente mais tarde.\") except rs3clans.ClanNotFoundError:",
"clã '{clan_name}' não existe.\") clan_leader = None for member in",
"\"%20\") user_url_clan = player.clan.replace(\" \", \"%20\") icon_url = f\"https://secure.runescape.com/m=avatar-rs/{user_url_name}/chat.png\" runeclan_url",
"= f\"http://services.runescape.com/m=avatar-rs/l=3/a=869/{user_url_clan}/clanmotif.png\" embed_title = \"RuneClan\" rank_header = \"__Rank__\" clan_header =",
"async def ranks(self, ctx: Context, *, clan: str = 'Atlantis'):",
"await ctx.send('Clã não reconhecido.') rank_emoji = { 'Recruit': self.bot.setting.clan_settings['Recruit']['Emoji'], 'Corporal':",
"len(ranks_embed.fields) >= 20: await ctx.send('Muitos ranks a serem atualizados, enviando",
"@commands.bot_has_permissions(embed_links=True) @commands.command(aliases=['clan']) async def clan_detail_info(self, ctx: Context, *, clan_name: str):",
"for member in clan: if member.rank == 'Owner': clan_leader =",
"❯ General {rank_emoji['General']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found = True elif",
"name=total_exp_header, value=private_profile_header, inline=False ) else: clan_info_embed.add_field( name=total_exp_header, value=f\"{player.exp:,}\" ) return",
"username: str): try: player = rs3clans.Player(name=username, runemetrics=True) except ConnectionError: return",
"{rank_emoji['Recruit']} ❯ Cabo {rank_emoji['Corporal']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found = True",
"user_clan = rs3clans.Clan(name=player.clan) member = user_clan.get_member(username) user_clan_exp = member.exp user_rank",
"str = 'Atlantis'): if clan.lower() == 'atlantis argus': return await",
"atualizados, enviando apenas os 20 primeiros.') break if member.exp >=",
"Tenente {rank_emoji['Lieutenant']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found = True elif member.exp",
"ser atualizado no momento :)\", value=separator, inline=False ) return await",
"and member.rank == 'Recruit': ranks_embed.add_field( name=member.name, value=f\"Recruta {rank_emoji['Recruit']} ❯ Cabo",
"member.exp user_rank = member.rank display_username = player.name if self.bot.setting.show_titles: if",
"import rs3clans import discord from discord.ext import commands from bot.bot_client",
"{rank_emoji['Sergeant']} ❯ Tenente {rank_emoji['Lieutenant']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found = True",
"title=clan.name, color=discord.Color.green(), url=f'http://services.runescape.com/m=clan-home/clan/{clan_url}' ) clan_embed.set_author(name='RuneClan', url=f'https://runeclan.com/clan/{clan_url}') clan_embed.set_thumbnail(url=f'http://services.runescape.com/m=avatar-rs/{clan_url}/clanmotif.png') clan_embed.add_field(name=\"Exp Total\", value=f'{clan.exp:,}')",
"class Clan(commands.Cog): def __init__(self, bot: Bot): self.bot = bot @commands.cooldown(1,",
"bot.utils.tools import separator from bot.utils.context import Context class Clan(commands.Cog): def",
"clan_info_embed = discord.Embed( title=embed_title, description=\"\", color=discord.Colour.dark_blue(), url=runeclan_url, ) clan_info_embed.set_author( icon_url=icon_url,",
"await ctx.send('Muitos ranks a serem atualizados, enviando apenas os 20",
"ao tentar conectar a API da Jagex. Tente novamente mais",
"value=f'{clan.exp:,}') clan_embed.add_field(name=\"Membros\", value=str(clan.count)) clan_embed.add_field(name=\"Líder\", value=clan_leader) clan_embed.add_field(name=\"Exp Média por Membro\", value=f'{clan.avg_exp:,.0f}')",
"clan_embed.add_field(name=\"Exp Total\", value=f'{clan.exp:,}') clan_embed.add_field(name=\"Membros\", value=str(clan.count)) clan_embed.add_field(name=\"Líder\", value=clan_leader) clan_embed.add_field(name=\"Exp Média por",
"player.private_profile: clan_info_embed.add_field( name=total_exp_header, value=private_profile_header, inline=False ) else: clan_info_embed.add_field( name=total_exp_header, value=f\"{player.exp:,}\"",
"player.name if self.bot.setting.show_titles: if player.suffix: display_username = f\"{player.name} {player.title}\" else:",
":)\", value=separator, inline=False ) return await ctx.send(embed=ranks_embed) def setup(bot): bot.add_cog(Clan(bot))",
"exp_lieutenant = 500_000_000 exp_seargent = 250_000_000 exp_corporal = 125_000_000 elif",
"clan_embed.set_author(name='RuneClan', url=f'https://runeclan.com/clan/{clan_url}') clan_embed.set_thumbnail(url=f'http://services.runescape.com/m=avatar-rs/{clan_url}/clanmotif.png') clan_embed.add_field(name=\"Exp Total\", value=f'{clan.exp:,}') clan_embed.add_field(name=\"Membros\", value=str(clan.count)) clan_embed.add_field(name=\"Líder\", value=clan_leader)",
"250_000_000 exp_corporal = 125_000_000 elif clan.lower() == 'argus': exp_general =",
"== 'argus': exp_general = 500_000_000 exp_captain = 250_000_000 exp_lieutenant =",
"= discord.Embed( title=embed_title, description=\"\", color=discord.Colour.dark_blue(), url=runeclan_url, ) clan_info_embed.set_author( icon_url=icon_url, name=display_username",
"exp_corporal = 125_000_000 elif clan.lower() == 'argus': exp_general = 500_000_000",
"serem atualizados, enviando apenas os 20 primeiros.') break if member.exp",
") else: clan_info_embed.add_field( name=total_exp_header, value=f\"{player.exp:,}\" ) return await ctx.send(content=None, embed=clan_info_embed)",
"not found: ranks_embed.add_field( name=\"Nenhum Rank a ser atualizado no momento",
"{member.exp:,}\\n{separator}\", inline=False) found = True elif member.exp >= exp_general and",
"member in clan]) member: rs3clans.ClanMember for member in clan_members: if",
"ConnectionError: return await ctx.send(f\"Houve um erro ao tentar conectar a",
"separator from bot.utils.context import Context class Clan(commands.Cog): def __init__(self, bot:",
"Perfil Privado\" rank_emoji = self.bot.setting.clan_settings[user_rank]['Emoji'] user_rank = self.bot.setting.clan_settings[user_rank]['Translation'] clan_info_embed =",
"if member.exp >= exp_corporal and member.rank == 'Recruit': ranks_embed.add_field( name=member.name,",
"API da Jagex. Tente novamente mais tarde.\") except rs3clans.ClanNotFoundError: return",
"clan_info_embed.add_field( name=rank_header, value=f\"{user_rank} {rank_emoji}\" ) clan_info_embed.add_field( name=exp_header, value=f\"{user_clan_exp:,}\" ) if",
"Média por Membro\", value=f'{clan.avg_exp:,.0f}') return await ctx.send(embed=clan_embed) @commands.cooldown(1, 5, commands.BucketType.user)",
"clan = 'Atlantis Argus' else: return await ctx.send('Clã não reconhecido.')",
"else: display_username = f\"{player.title} {player.name}\" user_url_name = player.name.replace(\" \", \"%20\")",
"clan_embed.add_field(name=\"Líder\", value=clan_leader) clan_embed.add_field(name=\"Exp Média por Membro\", value=f'{clan.avg_exp:,.0f}') return await ctx.send(embed=clan_embed)",
") clan_info_embed.set_author( icon_url=icon_url, name=display_username ) clan_info_embed.set_thumbnail( url=clan_banner_url ) clan_info_embed.add_field( name=clan_header,",
"else: clan_info_embed.add_field( name=total_exp_header, value=f\"{player.exp:,}\" ) return await ctx.send(content=None, embed=clan_info_embed) @commands.cooldown(1,",
"ranks_embed.add_field( name=member.name, value=f\"Cabo {rank_emoji['Corporal']} ❯ Sargento {rank_emoji['Sergeant']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False)",
"clan_leader = member.name clan_url = clan.name.replace(' ', '%20') clan_embed =",
"and member.rank == 'Sergeant': ranks_embed.add_field( name=member.name, value=f\"Sargento {rank_emoji['Sergeant']} ❯ Tenente",
"return await ctx.send(f\"Houve um erro ao tentar conectar a API",
"Cabo {rank_emoji['Corporal']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found = True elif member.exp",
"clan_name: str): try: clan = rs3clans.Clan(name=clan_name, set_exp=True) except ConnectionError: return",
"momento :)\", value=separator, inline=False ) return await ctx.send(embed=ranks_embed) def setup(bot):",
"'upranks', 'rank']) async def ranks(self, ctx: Context, *, clan: str",
"argus': return await ctx.send('`!rank argus` irmão') elif clan.lower() == 'atlantis':",
"if not player.exists: return await ctx.send(f\"Jogador '{player.name}' não existe.\") if",
"= True elif member.exp >= exp_seargent and member.rank == 'Corporal':",
"from bot.utils.context import Context class Clan(commands.Cog): def __init__(self, bot: Bot):",
"no Clã__\" total_exp_header = \"__Exp Total__\" private_profile_header = \"Indisponível -",
"self.bot.setting.clan_settings[user_rank]['Emoji'] user_rank = self.bot.setting.clan_settings[user_rank]['Translation'] clan_info_embed = discord.Embed( title=embed_title, description=\"\", color=discord.Colour.dark_blue(),",
"a Atualizar__\", description=\" \", ) found = False clan =",
"in clan]) member: rs3clans.ClanMember for member in clan_members: if len(ranks_embed.fields)",
"value=f\"{user_clan_exp:,}\" ) if player.private_profile: clan_info_embed.add_field( name=total_exp_header, value=private_profile_header, inline=False ) else:",
"import Bot from bot.utils.tools import separator from bot.utils.context import Context",
"name=clan_header, value=player.clan ) clan_info_embed.add_field( name=rank_header, value=f\"{user_rank} {rank_emoji}\" ) clan_info_embed.add_field( name=exp_header,",
"try: clan = rs3clans.Clan(name=clan_name, set_exp=True) except ConnectionError: return await ctx.send(f\"Houve",
"name=rank_header, value=f\"{user_rank} {rank_emoji}\" ) clan_info_embed.add_field( name=exp_header, value=f\"{user_clan_exp:,}\" ) if player.private_profile:",
"user_url_name = player.name.replace(\" \", \"%20\") user_url_clan = player.clan.replace(\" \", \"%20\")",
"self.bot.setting.clan_settings['General']['Emoji'], } ranks_embed = discord.Embed( title=\"__Ranks a Atualizar__\", description=\" \",",
"member in clan_members: if len(ranks_embed.fields) >= 20: await ctx.send('Muitos ranks",
"elif clan.lower() == 'argus': exp_general = 500_000_000 exp_captain = 250_000_000",
"\"Indisponível - Perfil Privado\" rank_emoji = self.bot.setting.clan_settings[user_rank]['Emoji'] user_rank = self.bot.setting.clan_settings[user_rank]['Translation']",
"True elif member.exp >= exp_captain and member.rank == 'Lieutenant': ranks_embed.add_field(",
"{rank_emoji['Corporal']} ❯ Sargento {rank_emoji['Sergeant']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found = True",
"discord.Embed( title=\"__Ranks a Atualizar__\", description=\" \", ) found = False",
"Tente novamente mais tarde.\") if not player.exists: return await ctx.send(f\"Jogador",
"= f\"{player.name} {player.title}\" else: display_username = f\"{player.title} {player.name}\" user_url_name =",
"General {rank_emoji['General']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found = True elif member.exp",
"await ctx.send(f\"Jogador '{player.name}' não existe.\") if not player.clan: return await",
"exp_seargent and member.rank == 'Corporal': ranks_embed.add_field( name=member.name, value=f\"Cabo {rank_emoji['Corporal']} ❯",
"True elif member.exp >= exp_lieutenant and member.rank == 'Sergeant': ranks_embed.add_field(",
"user_clan.get_member(username) user_clan_exp = member.exp user_rank = member.rank display_username = player.name",
"inline=False) found = True elif member.exp >= exp_seargent and member.rank",
"= player.name.replace(\" \", \"%20\") user_url_clan = player.clan.replace(\" \", \"%20\") icon_url",
"discord.ext import commands from bot.bot_client import Bot from bot.utils.tools import",
") clan_embed.set_author(name='RuneClan', url=f'https://runeclan.com/clan/{clan_url}') clan_embed.set_thumbnail(url=f'http://services.runescape.com/m=avatar-rs/{clan_url}/clanmotif.png') clan_embed.add_field(name=\"Exp Total\", value=f'{clan.exp:,}') clan_embed.add_field(name=\"Membros\", value=str(clan.count)) clan_embed.add_field(name=\"Líder\",",
"value=f\"Recruta {rank_emoji['Recruit']} ❯ Cabo {rank_emoji['Corporal']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found =",
"= \"RuneClan\" rank_header = \"__Rank__\" clan_header = \"__Clã__\" exp_header =",
"{rank_emoji['Corporal']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found = True elif member.exp >=",
"mais tarde.\") if not player.exists: return await ctx.send(f\"Jogador '{player.name}' não",
"member = user_clan.get_member(username) user_clan_exp = member.exp user_rank = member.rank display_username",
"= discord.Embed( title=\"__Ranks a Atualizar__\", description=\" \", ) found =",
"\"__Rank__\" clan_header = \"__Clã__\" exp_header = \"__Exp no Clã__\" total_exp_header",
"ctx.send(f\"O clã '{clan_name}' não existe.\") clan_leader = None for member",
"Rank a ser atualizado no momento :)\", value=separator, inline=False )",
"clan_members = reversed([member for member in clan]) member: rs3clans.ClanMember for",
"@commands.bot_has_permissions(embed_links=True) @commands.command(aliases=['claninfo', 'clanexp', 'claexp', 'clainfo', 'clãexp', 'clãinfo']) async def clan_user_info(self,",
"@commands.cooldown(1, 5, commands.BucketType.user) @commands.bot_has_permissions(embed_links=True) @commands.command(aliases=['clan']) async def clan_detail_info(self, ctx: Context,",
"ctx.send('Clã não reconhecido.') rank_emoji = { 'Recruit': self.bot.setting.clan_settings['Recruit']['Emoji'], 'Corporal': self.bot.setting.clan_settings['Corporal']['Emoji'],",
"== 'atlantis argus': return await ctx.send('`!rank argus` irmão') elif clan.lower()",
"True if not found: ranks_embed.add_field( name=\"Nenhum Rank a ser atualizado",
"= reversed([member for member in clan]) member: rs3clans.ClanMember for member",
"'Recruit': ranks_embed.add_field( name=member.name, value=f\"Recruta {rank_emoji['Recruit']} ❯ Cabo {rank_emoji['Corporal']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\",",
"elif member.exp >= exp_captain and member.rank == 'Lieutenant': ranks_embed.add_field( name=member.name,",
"await ctx.send('`!rank argus` irmão') elif clan.lower() == 'atlantis': exp_general =",
"clan_embed.add_field(name=\"Exp Média por Membro\", value=f'{clan.avg_exp:,.0f}') return await ctx.send(embed=clan_embed) @commands.cooldown(1, 5,",
"def __init__(self, bot: Bot): self.bot = bot @commands.cooldown(1, 5, commands.BucketType.user)",
"None for member in clan: if member.rank == 'Owner': clan_leader",
"{rank_emoji['Captain']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found = True elif member.exp >=",
"'atlantis argus': return await ctx.send('`!rank argus` irmão') elif clan.lower() ==",
"await ctx.send(embed=clan_embed) @commands.cooldown(1, 5, commands.BucketType.user) @commands.bot_has_permissions(embed_links=True) @commands.command(aliases=['claninfo', 'clanexp', 'claexp', 'clainfo',",
"import separator from bot.utils.context import Context class Clan(commands.Cog): def __init__(self,",
"clan_info_embed.set_author( icon_url=icon_url, name=display_username ) clan_info_embed.set_thumbnail( url=clan_banner_url ) clan_info_embed.add_field( name=clan_header, value=player.clan",
"found = True elif member.exp >= exp_general and member.rank ==",
"and member.rank == 'Lieutenant': ranks_embed.add_field( name=member.name, value=f\"Tenente {rank_emoji['Lieutenant']} ❯ Capitão",
"url=runeclan_url, ) clan_info_embed.set_author( icon_url=icon_url, name=display_username ) clan_info_embed.set_thumbnail( url=clan_banner_url ) clan_info_embed.add_field(",
"name=member.name, value=f\"Capitão {rank_emoji['Captain']} ❯ General {rank_emoji['General']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found",
"elif member.exp >= exp_seargent and member.rank == 'Corporal': ranks_embed.add_field( name=member.name,",
"ctx.send(embed=clan_embed) @commands.cooldown(1, 5, commands.BucketType.user) @commands.bot_has_permissions(embed_links=True) @commands.command(aliases=['claninfo', 'clanexp', 'claexp', 'clainfo', 'clãexp',",
"commands.BucketType.user) @commands.bot_has_permissions(embed_links=True) @commands.command(aliases=['claninfo', 'clanexp', 'claexp', 'clainfo', 'clãexp', 'clãinfo']) async def",
"exp_captain = 250_000_000 exp_lieutenant = 125_000_000 exp_seargent = 60_000_000 exp_corporal",
"❯ Sargento {rank_emoji['Sergeant']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found = True if",
"await ctx.send(content=None, embed=clan_info_embed) @commands.cooldown(1, 5, commands.BucketType.user) @commands.bot_has_permissions(embed_links=True) @commands.command(aliases=['ranksupdate', 'upranks', 'rank'])",
">= exp_captain and member.rank == 'Lieutenant': ranks_embed.add_field( name=member.name, value=f\"Tenente {rank_emoji['Lieutenant']}",
"discord.Embed( title=embed_title, description=\"\", color=discord.Colour.dark_blue(), url=runeclan_url, ) clan_info_embed.set_author( icon_url=icon_url, name=display_username )",
"Capitão {rank_emoji['Captain']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found = True elif member.exp",
"= 500_000_000 exp_captain = 250_000_000 exp_lieutenant = 125_000_000 exp_seargent =",
"= 125_000_000 exp_seargent = 60_000_000 exp_corporal = 30_000_000 clan =",
"'{player.name}' não está em um clã.\") user_clan = rs3clans.Clan(name=player.clan) member",
"return await ctx.send(f\"Jogador '{player.name}' não está em um clã.\") user_clan",
"title=embed_title, description=\"\", color=discord.Colour.dark_blue(), url=runeclan_url, ) clan_info_embed.set_author( icon_url=icon_url, name=display_username ) clan_info_embed.set_thumbnail(",
"clan.lower() == 'argus': exp_general = 500_000_000 exp_captain = 250_000_000 exp_lieutenant",
"5, commands.BucketType.user) @commands.bot_has_permissions(embed_links=True) @commands.command(aliases=['ranksupdate', 'upranks', 'rank']) async def ranks(self, ctx:",
"ctx.send('`!rank argus` irmão') elif clan.lower() == 'atlantis': exp_general = 2_000_000_000",
"5, commands.BucketType.user) @commands.bot_has_permissions(embed_links=True) @commands.command(aliases=['claninfo', 'clanexp', 'claexp', 'clainfo', 'clãexp', 'clãinfo']) async",
"return await ctx.send(embed=clan_embed) @commands.cooldown(1, 5, commands.BucketType.user) @commands.bot_has_permissions(embed_links=True) @commands.command(aliases=['claninfo', 'clanexp', 'claexp',",
"if self.bot.setting.show_titles: if player.suffix: display_username = f\"{player.name} {player.title}\" else: display_username",
"clan_embed = discord.Embed( title=clan.name, color=discord.Color.green(), url=f'http://services.runescape.com/m=clan-home/clan/{clan_url}' ) clan_embed.set_author(name='RuneClan', url=f'https://runeclan.com/clan/{clan_url}') clan_embed.set_thumbnail(url=f'http://services.runescape.com/m=avatar-rs/{clan_url}/clanmotif.png')",
"'claexp', 'clainfo', 'clãexp', 'clãinfo']) async def clan_user_info(self, ctx: Context, *,",
"bot @commands.cooldown(1, 5, commands.BucketType.user) @commands.bot_has_permissions(embed_links=True) @commands.command(aliases=['clan']) async def clan_detail_info(self, ctx:",
"'Corporal': ranks_embed.add_field( name=member.name, value=f\"Cabo {rank_emoji['Corporal']} ❯ Sargento {rank_emoji['Sergeant']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\",",
"ranks a serem atualizados, enviando apenas os 20 primeiros.') break",
"import Context class Clan(commands.Cog): def __init__(self, bot: Bot): self.bot =",
"= rs3clans.Clan(clan, set_exp=False) clan_members = reversed([member for member in clan])",
"\", ) found = False clan = rs3clans.Clan(clan, set_exp=False) clan_members",
"member.exp >= exp_lieutenant and member.rank == 'Sergeant': ranks_embed.add_field( name=member.name, value=f\"Sargento",
") clan_info_embed.add_field( name=rank_header, value=f\"{user_rank} {rank_emoji}\" ) clan_info_embed.add_field( name=exp_header, value=f\"{user_clan_exp:,}\" )",
"member.rank == 'Captain': ranks_embed.add_field( name=member.name, value=f\"Capitão {rank_emoji['Captain']} ❯ General {rank_emoji['General']}\\n\"",
"clan_info_embed.add_field( name=exp_header, value=f\"{user_clan_exp:,}\" ) if player.private_profile: clan_info_embed.add_field( name=total_exp_header, value=private_profile_header, inline=False",
"❯ Tenente {rank_emoji['Lieutenant']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found = True elif",
"def clan_detail_info(self, ctx: Context, *, clan_name: str): try: clan =",
"@commands.command(aliases=['claninfo', 'clanexp', 'claexp', 'clainfo', 'clãexp', 'clãinfo']) async def clan_user_info(self, ctx:",
"da Jagex. Tente novamente mais tarde.\") except rs3clans.ClanNotFoundError: return await",
">= exp_corporal and member.rank == 'Recruit': ranks_embed.add_field( name=member.name, value=f\"Recruta {rank_emoji['Recruit']}",
"= 60_000_000 exp_corporal = 30_000_000 clan = 'Atlantis Argus' else:",
"@commands.command(aliases=['ranksupdate', 'upranks', 'rank']) async def ranks(self, ctx: Context, *, clan:",
"== 'Sergeant': ranks_embed.add_field( name=member.name, value=f\"Sargento {rank_emoji['Sergeant']} ❯ Tenente {rank_emoji['Lieutenant']}\\n\" f\"**__Exp:__**",
"ctx: Context, *, clan_name: str): try: clan = rs3clans.Clan(name=clan_name, set_exp=True)",
"found = True elif member.exp >= exp_captain and member.rank ==",
"Membro\", value=f'{clan.avg_exp:,.0f}') return await ctx.send(embed=clan_embed) @commands.cooldown(1, 5, commands.BucketType.user) @commands.bot_has_permissions(embed_links=True) @commands.command(aliases=['claninfo',",
"= 250_000_000 exp_corporal = 125_000_000 elif clan.lower() == 'argus': exp_general",
"== 'atlantis': exp_general = 2_000_000_000 exp_captain = 1_000_000_000 exp_lieutenant =",
"} ranks_embed = discord.Embed( title=\"__Ranks a Atualizar__\", description=\" \", )",
"value=f\"{player.exp:,}\" ) return await ctx.send(content=None, embed=clan_info_embed) @commands.cooldown(1, 5, commands.BucketType.user) @commands.bot_has_permissions(embed_links=True)",
"if player.suffix: display_username = f\"{player.name} {player.title}\" else: display_username = f\"{player.title}",
"\", \"%20\") icon_url = f\"https://secure.runescape.com/m=avatar-rs/{user_url_name}/chat.png\" runeclan_url = f\"https://runeclan.com/user/{user_url_name}\" clan_banner_url =",
"found = True if not found: ranks_embed.add_field( name=\"Nenhum Rank a",
"display_username = player.name if self.bot.setting.show_titles: if player.suffix: display_username = f\"{player.name}",
"self.bot.setting.clan_settings['Corporal']['Emoji'], 'Sergeant': self.bot.setting.clan_settings['Sergeant']['Emoji'], 'Lieutenant': self.bot.setting.clan_settings['Lieutenant']['Emoji'], 'Captain': self.bot.setting.clan_settings['Captain']['Emoji'], 'General': self.bot.setting.clan_settings['General']['Emoji'], }",
"= \"__Exp Total__\" private_profile_header = \"Indisponível - Perfil Privado\" rank_emoji",
"ranks_embed.add_field( name=member.name, value=f\"Tenente {rank_emoji['Lieutenant']} ❯ Capitão {rank_emoji['Captain']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False)",
"\"RuneClan\" rank_header = \"__Rank__\" clan_header = \"__Clã__\" exp_header = \"__Exp",
"= 1_000_000_000 exp_lieutenant = 500_000_000 exp_seargent = 250_000_000 exp_corporal =",
"player.clan: return await ctx.send(f\"Jogador '{player.name}' não está em um clã.\")",
"display_username = f\"{player.title} {player.name}\" user_url_name = player.name.replace(\" \", \"%20\") user_url_clan",
"= clan.name.replace(' ', '%20') clan_embed = discord.Embed( title=clan.name, color=discord.Color.green(), url=f'http://services.runescape.com/m=clan-home/clan/{clan_url}'",
"a ser atualizado no momento :)\", value=separator, inline=False ) return",
">= exp_general and member.rank == 'Captain': ranks_embed.add_field( name=member.name, value=f\"Capitão {rank_emoji['Captain']}",
"member in clan: if member.rank == 'Owner': clan_leader = member.name",
"= None for member in clan: if member.rank == 'Owner':",
"= 'Atlantis'): if clan.lower() == 'atlantis argus': return await ctx.send('`!rank",
"\"__Exp no Clã__\" total_exp_header = \"__Exp Total__\" private_profile_header = \"Indisponível",
"elif member.exp >= exp_general and member.rank == 'Captain': ranks_embed.add_field( name=member.name,",
"url=clan_banner_url ) clan_info_embed.add_field( name=clan_header, value=player.clan ) clan_info_embed.add_field( name=rank_header, value=f\"{user_rank} {rank_emoji}\"",
"if not found: ranks_embed.add_field( name=\"Nenhum Rank a ser atualizado no",
"1_000_000_000 exp_lieutenant = 500_000_000 exp_seargent = 250_000_000 exp_corporal = 125_000_000",
"rank_header = \"__Rank__\" clan_header = \"__Clã__\" exp_header = \"__Exp no",
"name=\"Nenhum Rank a ser atualizado no momento :)\", value=separator, inline=False",
"= rs3clans.Clan(name=player.clan) member = user_clan.get_member(username) user_clan_exp = member.exp user_rank =",
"tarde.\") except rs3clans.ClanNotFoundError: return await ctx.send(f\"O clã '{clan_name}' não existe.\")",
"self.bot = bot @commands.cooldown(1, 5, commands.BucketType.user) @commands.bot_has_permissions(embed_links=True) @commands.command(aliases=['clan']) async def",
"= \"__Rank__\" clan_header = \"__Clã__\" exp_header = \"__Exp no Clã__\"",
"f\"http://services.runescape.com/m=avatar-rs/l=3/a=869/{user_url_clan}/clanmotif.png\" embed_title = \"RuneClan\" rank_header = \"__Rank__\" clan_header = \"__Clã__\"",
"icon_url = f\"https://secure.runescape.com/m=avatar-rs/{user_url_name}/chat.png\" runeclan_url = f\"https://runeclan.com/user/{user_url_name}\" clan_banner_url = f\"http://services.runescape.com/m=avatar-rs/l=3/a=869/{user_url_clan}/clanmotif.png\" embed_title",
"clan_info_embed.set_thumbnail( url=clan_banner_url ) clan_info_embed.add_field( name=clan_header, value=player.clan ) clan_info_embed.add_field( name=rank_header, value=f\"{user_rank}",
"bot.utils.context import Context class Clan(commands.Cog): def __init__(self, bot: Bot): self.bot",
"Context, *, clan_name: str): try: clan = rs3clans.Clan(name=clan_name, set_exp=True) except",
"rs3clans.Clan(name=player.clan) member = user_clan.get_member(username) user_clan_exp = member.exp user_rank = member.rank",
"'{player.name}' não existe.\") if not player.clan: return await ctx.send(f\"Jogador '{player.name}'",
"'clanexp', 'claexp', 'clainfo', 'clãexp', 'clãinfo']) async def clan_user_info(self, ctx: Context,",
"= user_clan.get_member(username) user_clan_exp = member.exp user_rank = member.rank display_username =",
"break if member.exp >= exp_corporal and member.rank == 'Recruit': ranks_embed.add_field(",
"não reconhecido.') rank_emoji = { 'Recruit': self.bot.setting.clan_settings['Recruit']['Emoji'], 'Corporal': self.bot.setting.clan_settings['Corporal']['Emoji'], 'Sergeant':",
"user_url_clan = player.clan.replace(\" \", \"%20\") icon_url = f\"https://secure.runescape.com/m=avatar-rs/{user_url_name}/chat.png\" runeclan_url =",
"enviando apenas os 20 primeiros.') break if member.exp >= exp_corporal",
"commands from bot.bot_client import Bot from bot.utils.tools import separator from",
"clan: str = 'Atlantis'): if clan.lower() == 'atlantis argus': return",
"Total\", value=f'{clan.exp:,}') clan_embed.add_field(name=\"Membros\", value=str(clan.count)) clan_embed.add_field(name=\"Líder\", value=clan_leader) clan_embed.add_field(name=\"Exp Média por Membro\",",
"por Membro\", value=f'{clan.avg_exp:,.0f}') return await ctx.send(embed=clan_embed) @commands.cooldown(1, 5, commands.BucketType.user) @commands.bot_has_permissions(embed_links=True)",
"else: return await ctx.send('Clã não reconhecido.') rank_emoji = { 'Recruit':",
"'clãexp', 'clãinfo']) async def clan_user_info(self, ctx: Context, *, username: str):",
"bot.bot_client import Bot from bot.utils.tools import separator from bot.utils.context import",
"{rank_emoji['Lieutenant']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found = True elif member.exp >=",
"= True if not found: ranks_embed.add_field( name=\"Nenhum Rank a ser",
"erro ao tentar conectar a API da Jagex. Tente novamente",
"= \"__Clã__\" exp_header = \"__Exp no Clã__\" total_exp_header = \"__Exp",
"value=f\"Capitão {rank_emoji['Captain']} ❯ General {rank_emoji['General']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found =",
"clan_header = \"__Clã__\" exp_header = \"__Exp no Clã__\" total_exp_header =",
"= 125_000_000 elif clan.lower() == 'argus': exp_general = 500_000_000 exp_captain",
"conectar a API da Jagex. Tente novamente mais tarde.\") if",
"runemetrics=True) except ConnectionError: return await ctx.send(f\"Houve um erro ao tentar",
"import discord from discord.ext import commands from bot.bot_client import Bot",
"= f\"{player.title} {player.name}\" user_url_name = player.name.replace(\" \", \"%20\") user_url_clan =",
"ranks_embed.add_field( name=\"Nenhum Rank a ser atualizado no momento :)\", value=separator,",
"exp_captain and member.rank == 'Lieutenant': ranks_embed.add_field( name=member.name, value=f\"Tenente {rank_emoji['Lieutenant']} ❯",
"60_000_000 exp_corporal = 30_000_000 clan = 'Atlantis Argus' else: return",
"__init__(self, bot: Bot): self.bot = bot @commands.cooldown(1, 5, commands.BucketType.user) @commands.bot_has_permissions(embed_links=True)",
"20 primeiros.') break if member.exp >= exp_corporal and member.rank ==",
"inline=False) found = True elif member.exp >= exp_general and member.rank",
"{member.exp:,}\\n{separator}\", inline=False) found = True elif member.exp >= exp_lieutenant and",
"{rank_emoji['Captain']} ❯ General {rank_emoji['General']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found = True",
"existe.\") clan_leader = None for member in clan: if member.rank",
"ctx.send('Muitos ranks a serem atualizados, enviando apenas os 20 primeiros.')",
"tentar conectar a API da Jagex. Tente novamente mais tarde.\")",
"em um clã.\") user_clan = rs3clans.Clan(name=player.clan) member = user_clan.get_member(username) user_clan_exp",
"Context class Clan(commands.Cog): def __init__(self, bot: Bot): self.bot = bot",
"async def clan_detail_info(self, ctx: Context, *, clan_name: str): try: clan",
"{member.exp:,}\\n{separator}\", inline=False) found = True if not found: ranks_embed.add_field( name=\"Nenhum",
"\", \"%20\") user_url_clan = player.clan.replace(\" \", \"%20\") icon_url = f\"https://secure.runescape.com/m=avatar-rs/{user_url_name}/chat.png\"",
"argus` irmão') elif clan.lower() == 'atlantis': exp_general = 2_000_000_000 exp_captain",
"== 'Owner': clan_leader = member.name clan_url = clan.name.replace(' ', '%20')",
"name=member.name, value=f\"Sargento {rank_emoji['Sergeant']} ❯ Tenente {rank_emoji['Lieutenant']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found",
"value=str(clan.count)) clan_embed.add_field(name=\"Líder\", value=clan_leader) clan_embed.add_field(name=\"Exp Média por Membro\", value=f'{clan.avg_exp:,.0f}') return await",
"inline=False) found = True elif member.exp >= exp_captain and member.rank",
"player.exists: return await ctx.send(f\"Jogador '{player.name}' não existe.\") if not player.clan:",
"= False clan = rs3clans.Clan(clan, set_exp=False) clan_members = reversed([member for",
"= f\"https://secure.runescape.com/m=avatar-rs/{user_url_name}/chat.png\" runeclan_url = f\"https://runeclan.com/user/{user_url_name}\" clan_banner_url = f\"http://services.runescape.com/m=avatar-rs/l=3/a=869/{user_url_clan}/clanmotif.png\" embed_title =",
"@commands.cooldown(1, 5, commands.BucketType.user) @commands.bot_has_permissions(embed_links=True) @commands.command(aliases=['claninfo', 'clanexp', 'claexp', 'clainfo', 'clãexp', 'clãinfo'])",
"member.rank == 'Owner': clan_leader = member.name clan_url = clan.name.replace(' ',",
"a serem atualizados, enviando apenas os 20 primeiros.') break if",
"True elif member.exp >= exp_general and member.rank == 'Captain': ranks_embed.add_field(",
">= exp_seargent and member.rank == 'Corporal': ranks_embed.add_field( name=member.name, value=f\"Cabo {rank_emoji['Corporal']}",
"clan]) member: rs3clans.ClanMember for member in clan_members: if len(ranks_embed.fields) >=",
"ranks_embed.add_field( name=member.name, value=f\"Recruta {rank_emoji['Recruit']} ❯ Cabo {rank_emoji['Corporal']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False)",
"self.bot.setting.clan_settings[user_rank]['Translation'] clan_info_embed = discord.Embed( title=embed_title, description=\"\", color=discord.Colour.dark_blue(), url=runeclan_url, ) clan_info_embed.set_author(",
"Jagex. Tente novamente mais tarde.\") if not player.exists: return await",
"Bot): self.bot = bot @commands.cooldown(1, 5, commands.BucketType.user) @commands.bot_has_permissions(embed_links=True) @commands.command(aliases=['clan']) async",
"= True elif member.exp >= exp_captain and member.rank == 'Lieutenant':",
"clan.name.replace(' ', '%20') clan_embed = discord.Embed( title=clan.name, color=discord.Color.green(), url=f'http://services.runescape.com/m=clan-home/clan/{clan_url}' )",
"name=member.name, value=f\"Cabo {rank_emoji['Corporal']} ❯ Sargento {rank_emoji['Sergeant']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found",
"{member.exp:,}\\n{separator}\", inline=False) found = True elif member.exp >= exp_seargent and",
"Bot from bot.utils.tools import separator from bot.utils.context import Context class",
"value=f'{clan.avg_exp:,.0f}') return await ctx.send(embed=clan_embed) @commands.cooldown(1, 5, commands.BucketType.user) @commands.bot_has_permissions(embed_links=True) @commands.command(aliases=['claninfo', 'clanexp',",
"{player.title}\" else: display_username = f\"{player.title} {player.name}\" user_url_name = player.name.replace(\" \",",
"'Recruit': self.bot.setting.clan_settings['Recruit']['Emoji'], 'Corporal': self.bot.setting.clan_settings['Corporal']['Emoji'], 'Sergeant': self.bot.setting.clan_settings['Sergeant']['Emoji'], 'Lieutenant': self.bot.setting.clan_settings['Lieutenant']['Emoji'], 'Captain': self.bot.setting.clan_settings['Captain']['Emoji'],",
"= 2_000_000_000 exp_captain = 1_000_000_000 exp_lieutenant = 500_000_000 exp_seargent =",
"exp_lieutenant = 125_000_000 exp_seargent = 60_000_000 exp_corporal = 30_000_000 clan",
"clan_user_info(self, ctx: Context, *, username: str): try: player = rs3clans.Player(name=username,",
"== 'Corporal': ranks_embed.add_field( name=member.name, value=f\"Cabo {rank_emoji['Corporal']} ❯ Sargento {rank_emoji['Sergeant']}\\n\" f\"**__Exp:__**",
"= rs3clans.Clan(name=clan_name, set_exp=True) except ConnectionError: return await ctx.send(f\"Houve um erro",
"*, username: str): try: player = rs3clans.Player(name=username, runemetrics=True) except ConnectionError:",
"discord.Embed( title=clan.name, color=discord.Color.green(), url=f'http://services.runescape.com/m=clan-home/clan/{clan_url}' ) clan_embed.set_author(name='RuneClan', url=f'https://runeclan.com/clan/{clan_url}') clan_embed.set_thumbnail(url=f'http://services.runescape.com/m=avatar-rs/{clan_url}/clanmotif.png') clan_embed.add_field(name=\"Exp Total\",",
"return await ctx.send(f\"O clã '{clan_name}' não existe.\") clan_leader = None",
"value=f\"{user_rank} {rank_emoji}\" ) clan_info_embed.add_field( name=exp_header, value=f\"{user_clan_exp:,}\" ) if player.private_profile: clan_info_embed.add_field(",
"'{clan_name}' não existe.\") clan_leader = None for member in clan:",
"value=player.clan ) clan_info_embed.add_field( name=rank_header, value=f\"{user_rank} {rank_emoji}\" ) clan_info_embed.add_field( name=exp_header, value=f\"{user_clan_exp:,}\"",
"apenas os 20 primeiros.') break if member.exp >= exp_corporal and",
"True elif member.exp >= exp_seargent and member.rank == 'Corporal': ranks_embed.add_field(",
"in clan_members: if len(ranks_embed.fields) >= 20: await ctx.send('Muitos ranks a",
"clan_url = clan.name.replace(' ', '%20') clan_embed = discord.Embed( title=clan.name, color=discord.Color.green(),",
"da Jagex. Tente novamente mais tarde.\") if not player.exists: return",
"não está em um clã.\") user_clan = rs3clans.Clan(name=player.clan) member =",
"url=f'https://runeclan.com/clan/{clan_url}') clan_embed.set_thumbnail(url=f'http://services.runescape.com/m=avatar-rs/{clan_url}/clanmotif.png') clan_embed.add_field(name=\"Exp Total\", value=f'{clan.exp:,}') clan_embed.add_field(name=\"Membros\", value=str(clan.count)) clan_embed.add_field(name=\"Líder\", value=clan_leader) clan_embed.add_field(name=\"Exp",
"exp_general = 2_000_000_000 exp_captain = 1_000_000_000 exp_lieutenant = 500_000_000 exp_seargent",
"rank_emoji = self.bot.setting.clan_settings[user_rank]['Emoji'] user_rank = self.bot.setting.clan_settings[user_rank]['Translation'] clan_info_embed = discord.Embed( title=embed_title,",
"500_000_000 exp_captain = 250_000_000 exp_lieutenant = 125_000_000 exp_seargent = 60_000_000",
"color=discord.Color.green(), url=f'http://services.runescape.com/m=clan-home/clan/{clan_url}' ) clan_embed.set_author(name='RuneClan', url=f'https://runeclan.com/clan/{clan_url}') clan_embed.set_thumbnail(url=f'http://services.runescape.com/m=avatar-rs/{clan_url}/clanmotif.png') clan_embed.add_field(name=\"Exp Total\", value=f'{clan.exp:,}') clan_embed.add_field(name=\"Membros\",",
"rs3clans.Clan(clan, set_exp=False) clan_members = reversed([member for member in clan]) member:",
"clan.lower() == 'atlantis': exp_general = 2_000_000_000 exp_captain = 1_000_000_000 exp_lieutenant",
"member.rank display_username = player.name if self.bot.setting.show_titles: if player.suffix: display_username =",
"runeclan_url = f\"https://runeclan.com/user/{user_url_name}\" clan_banner_url = f\"http://services.runescape.com/m=avatar-rs/l=3/a=869/{user_url_clan}/clanmotif.png\" embed_title = \"RuneClan\" rank_header",
"self.bot.setting.clan_settings['Captain']['Emoji'], 'General': self.bot.setting.clan_settings['General']['Emoji'], } ranks_embed = discord.Embed( title=\"__Ranks a Atualizar__\",",
"{rank_emoji['General']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found = True elif member.exp >=",
"def clan_user_info(self, ctx: Context, *, username: str): try: player =",
"player.name.replace(\" \", \"%20\") user_url_clan = player.clan.replace(\" \", \"%20\") icon_url =",
"está em um clã.\") user_clan = rs3clans.Clan(name=player.clan) member = user_clan.get_member(username)",
"embed_title = \"RuneClan\" rank_header = \"__Rank__\" clan_header = \"__Clã__\" exp_header",
"exp_corporal and member.rank == 'Recruit': ranks_embed.add_field( name=member.name, value=f\"Recruta {rank_emoji['Recruit']} ❯",
"'%20') clan_embed = discord.Embed( title=clan.name, color=discord.Color.green(), url=f'http://services.runescape.com/m=clan-home/clan/{clan_url}' ) clan_embed.set_author(name='RuneClan', url=f'https://runeclan.com/clan/{clan_url}')",
"clan_leader = None for member in clan: if member.rank ==",
"False clan = rs3clans.Clan(clan, set_exp=False) clan_members = reversed([member for member",
"'Sergeant': ranks_embed.add_field( name=member.name, value=f\"Sargento {rank_emoji['Sergeant']} ❯ Tenente {rank_emoji['Lieutenant']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\",",
"try: player = rs3clans.Player(name=username, runemetrics=True) except ConnectionError: return await ctx.send(f\"Houve",
"elif clan.lower() == 'atlantis': exp_general = 2_000_000_000 exp_captain = 1_000_000_000",
"{rank_emoji['Sergeant']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found = True if not found:",
"= f\"https://runeclan.com/user/{user_url_name}\" clan_banner_url = f\"http://services.runescape.com/m=avatar-rs/l=3/a=869/{user_url_clan}/clanmotif.png\" embed_title = \"RuneClan\" rank_header =",
"{rank_emoji}\" ) clan_info_embed.add_field( name=exp_header, value=f\"{user_clan_exp:,}\" ) if player.private_profile: clan_info_embed.add_field( name=total_exp_header,",
") clan_info_embed.add_field( name=clan_header, value=player.clan ) clan_info_embed.add_field( name=rank_header, value=f\"{user_rank} {rank_emoji}\" )",
"= \"__Exp no Clã__\" total_exp_header = \"__Exp Total__\" private_profile_header =",
"member.exp >= exp_seargent and member.rank == 'Corporal': ranks_embed.add_field( name=member.name, value=f\"Cabo",
"embed=clan_info_embed) @commands.cooldown(1, 5, commands.BucketType.user) @commands.bot_has_permissions(embed_links=True) @commands.command(aliases=['ranksupdate', 'upranks', 'rank']) async def",
"clan_embed.add_field(name=\"Membros\", value=str(clan.count)) clan_embed.add_field(name=\"Líder\", value=clan_leader) clan_embed.add_field(name=\"Exp Média por Membro\", value=f'{clan.avg_exp:,.0f}') return",
"player.clan.replace(\" \", \"%20\") icon_url = f\"https://secure.runescape.com/m=avatar-rs/{user_url_name}/chat.png\" runeclan_url = f\"https://runeclan.com/user/{user_url_name}\" clan_banner_url",
"= member.name clan_url = clan.name.replace(' ', '%20') clan_embed = discord.Embed(",
"f\"{player.title} {player.name}\" user_url_name = player.name.replace(\" \", \"%20\") user_url_clan = player.clan.replace(\"",
"= player.name if self.bot.setting.show_titles: if player.suffix: display_username = f\"{player.name} {player.title}\"",
"clan = rs3clans.Clan(clan, set_exp=False) clan_members = reversed([member for member in",
"self.bot.setting.clan_settings['Recruit']['Emoji'], 'Corporal': self.bot.setting.clan_settings['Corporal']['Emoji'], 'Sergeant': self.bot.setting.clan_settings['Sergeant']['Emoji'], 'Lieutenant': self.bot.setting.clan_settings['Lieutenant']['Emoji'], 'Captain': self.bot.setting.clan_settings['Captain']['Emoji'], 'General':",
"um clã.\") user_clan = rs3clans.Clan(name=player.clan) member = user_clan.get_member(username) user_clan_exp =",
"member.exp >= exp_corporal and member.rank == 'Recruit': ranks_embed.add_field( name=member.name, value=f\"Recruta",
"conectar a API da Jagex. Tente novamente mais tarde.\") except",
"for member in clan_members: if len(ranks_embed.fields) >= 20: await ctx.send('Muitos",
"{member.exp:,}\\n{separator}\", inline=False) found = True elif member.exp >= exp_captain and",
"no momento :)\", value=separator, inline=False ) return await ctx.send(embed=ranks_embed) def",
"and member.rank == 'Corporal': ranks_embed.add_field( name=member.name, value=f\"Cabo {rank_emoji['Corporal']} ❯ Sargento",
"clan_info_embed.add_field( name=clan_header, value=player.clan ) clan_info_embed.add_field( name=rank_header, value=f\"{user_rank} {rank_emoji}\" ) clan_info_embed.add_field(",
"5, commands.BucketType.user) @commands.bot_has_permissions(embed_links=True) @commands.command(aliases=['clan']) async def clan_detail_info(self, ctx: Context, *,",
"def ranks(self, ctx: Context, *, clan: str = 'Atlantis'): if",
"exp_general and member.rank == 'Captain': ranks_embed.add_field( name=member.name, value=f\"Capitão {rank_emoji['Captain']} ❯",
"f\"https://secure.runescape.com/m=avatar-rs/{user_url_name}/chat.png\" runeclan_url = f\"https://runeclan.com/user/{user_url_name}\" clan_banner_url = f\"http://services.runescape.com/m=avatar-rs/l=3/a=869/{user_url_clan}/clanmotif.png\" embed_title = \"RuneClan\"",
"== 'Recruit': ranks_embed.add_field( name=member.name, value=f\"Recruta {rank_emoji['Recruit']} ❯ Cabo {rank_emoji['Corporal']}\\n\" f\"**__Exp:__**",
"private_profile_header = \"Indisponível - Perfil Privado\" rank_emoji = self.bot.setting.clan_settings[user_rank]['Emoji'] user_rank",
"mais tarde.\") except rs3clans.ClanNotFoundError: return await ctx.send(f\"O clã '{clan_name}' não",
"bot: Bot): self.bot = bot @commands.cooldown(1, 5, commands.BucketType.user) @commands.bot_has_permissions(embed_links=True) @commands.command(aliases=['clan'])",
"ctx: Context, *, clan: str = 'Atlantis'): if clan.lower() ==",
"inline=False) found = True if not found: ranks_embed.add_field( name=\"Nenhum Rank",
"url=f'http://services.runescape.com/m=clan-home/clan/{clan_url}' ) clan_embed.set_author(name='RuneClan', url=f'https://runeclan.com/clan/{clan_url}') clan_embed.set_thumbnail(url=f'http://services.runescape.com/m=avatar-rs/{clan_url}/clanmotif.png') clan_embed.add_field(name=\"Exp Total\", value=f'{clan.exp:,}') clan_embed.add_field(name=\"Membros\", value=str(clan.count))",
"ranks_embed = discord.Embed( title=\"__Ranks a Atualizar__\", description=\" \", ) found",
"Privado\" rank_emoji = self.bot.setting.clan_settings[user_rank]['Emoji'] user_rank = self.bot.setting.clan_settings[user_rank]['Translation'] clan_info_embed = discord.Embed(",
"= member.exp user_rank = member.rank display_username = player.name if self.bot.setting.show_titles:",
"commands.BucketType.user) @commands.bot_has_permissions(embed_links=True) @commands.command(aliases=['ranksupdate', 'upranks', 'rank']) async def ranks(self, ctx: Context,",
"member.exp >= exp_captain and member.rank == 'Lieutenant': ranks_embed.add_field( name=member.name, value=f\"Tenente",
"um erro ao tentar conectar a API da Jagex. Tente",
"Context, *, username: str): try: player = rs3clans.Player(name=username, runemetrics=True) except",
"exp_header = \"__Exp no Clã__\" total_exp_header = \"__Exp Total__\" private_profile_header",
"rs3clans import discord from discord.ext import commands from bot.bot_client import",
"não existe.\") if not player.clan: return await ctx.send(f\"Jogador '{player.name}' não",
"if not player.clan: return await ctx.send(f\"Jogador '{player.name}' não está em",
"@commands.bot_has_permissions(embed_links=True) @commands.command(aliases=['ranksupdate', 'upranks', 'rank']) async def ranks(self, ctx: Context, *,",
"{rank_emoji['Lieutenant']} ❯ Capitão {rank_emoji['Captain']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found = True",
"2_000_000_000 exp_captain = 1_000_000_000 exp_lieutenant = 500_000_000 exp_seargent = 250_000_000",
"exp_lieutenant and member.rank == 'Sergeant': ranks_embed.add_field( name=member.name, value=f\"Sargento {rank_emoji['Sergeant']} ❯",
"= member.rank display_username = player.name if self.bot.setting.show_titles: if player.suffix: display_username",
"exp_seargent = 250_000_000 exp_corporal = 125_000_000 elif clan.lower() == 'argus':",
"f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found = True elif member.exp >= exp_captain",
"member.name clan_url = clan.name.replace(' ', '%20') clan_embed = discord.Embed( title=clan.name,",
"f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found = True elif member.exp >= exp_lieutenant",
"'Captain': ranks_embed.add_field( name=member.name, value=f\"Capitão {rank_emoji['Captain']} ❯ General {rank_emoji['General']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\",",
"name=member.name, value=f\"Recruta {rank_emoji['Recruit']} ❯ Cabo {rank_emoji['Corporal']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found",
"= 250_000_000 exp_lieutenant = 125_000_000 exp_seargent = 60_000_000 exp_corporal =",
"self.bot.setting.clan_settings['Sergeant']['Emoji'], 'Lieutenant': self.bot.setting.clan_settings['Lieutenant']['Emoji'], 'Captain': self.bot.setting.clan_settings['Captain']['Emoji'], 'General': self.bot.setting.clan_settings['General']['Emoji'], } ranks_embed =",
"not player.clan: return await ctx.send(f\"Jogador '{player.name}' não está em um",
"clan.lower() == 'atlantis argus': return await ctx.send('`!rank argus` irmão') elif",
"== 'Lieutenant': ranks_embed.add_field( name=member.name, value=f\"Tenente {rank_emoji['Lieutenant']} ❯ Capitão {rank_emoji['Captain']}\\n\" f\"**__Exp:__**",
"= discord.Embed( title=clan.name, color=discord.Color.green(), url=f'http://services.runescape.com/m=clan-home/clan/{clan_url}' ) clan_embed.set_author(name='RuneClan', url=f'https://runeclan.com/clan/{clan_url}') clan_embed.set_thumbnail(url=f'http://services.runescape.com/m=avatar-rs/{clan_url}/clanmotif.png') clan_embed.add_field(name=\"Exp",
"icon_url=icon_url, name=display_username ) clan_info_embed.set_thumbnail( url=clan_banner_url ) clan_info_embed.add_field( name=clan_header, value=player.clan )",
"não existe.\") clan_leader = None for member in clan: if",
"Total__\" private_profile_header = \"Indisponível - Perfil Privado\" rank_emoji = self.bot.setting.clan_settings[user_rank]['Emoji']",
"exp_corporal = 30_000_000 clan = 'Atlantis Argus' else: return await",
"*, clan: str = 'Atlantis'): if clan.lower() == 'atlantis argus':",
"from discord.ext import commands from bot.bot_client import Bot from bot.utils.tools",
"return await ctx.send(f\"Jogador '{player.name}' não existe.\") if not player.clan: return",
"except ConnectionError: return await ctx.send(f\"Houve um erro ao tentar conectar",
"500_000_000 exp_seargent = 250_000_000 exp_corporal = 125_000_000 elif clan.lower() ==",
"value=f\"Sargento {rank_emoji['Sergeant']} ❯ Tenente {rank_emoji['Lieutenant']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found =",
"name=exp_header, value=f\"{user_clan_exp:,}\" ) if player.private_profile: clan_info_embed.add_field( name=total_exp_header, value=private_profile_header, inline=False )",
"if member.rank == 'Owner': clan_leader = member.name clan_url = clan.name.replace('",
"discord from discord.ext import commands from bot.bot_client import Bot from",
") return await ctx.send(content=None, embed=clan_info_embed) @commands.cooldown(1, 5, commands.BucketType.user) @commands.bot_has_permissions(embed_links=True) @commands.command(aliases=['ranksupdate',",
"f\"{player.name} {player.title}\" else: display_username = f\"{player.title} {player.name}\" user_url_name = player.name.replace(\"",
"'clainfo', 'clãexp', 'clãinfo']) async def clan_user_info(self, ctx: Context, *, username:",
"str): try: player = rs3clans.Player(name=username, runemetrics=True) except ConnectionError: return await",
"in clan: if member.rank == 'Owner': clan_leader = member.name clan_url",
"exp_seargent = 60_000_000 exp_corporal = 30_000_000 clan = 'Atlantis Argus'",
"', '%20') clan_embed = discord.Embed( title=clan.name, color=discord.Color.green(), url=f'http://services.runescape.com/m=clan-home/clan/{clan_url}' ) clan_embed.set_author(name='RuneClan',",
"= rs3clans.Player(name=username, runemetrics=True) except ConnectionError: return await ctx.send(f\"Houve um erro",
"API da Jagex. Tente novamente mais tarde.\") if not player.exists:",
"Tente novamente mais tarde.\") except rs3clans.ClanNotFoundError: return await ctx.send(f\"O clã",
"rs3clans.ClanMember for member in clan_members: if len(ranks_embed.fields) >= 20: await",
"= player.clan.replace(\" \", \"%20\") icon_url = f\"https://secure.runescape.com/m=avatar-rs/{user_url_name}/chat.png\" runeclan_url = f\"https://runeclan.com/user/{user_url_name}\"",
"total_exp_header = \"__Exp Total__\" private_profile_header = \"Indisponível - Perfil Privado\"",
"f\"https://runeclan.com/user/{user_url_name}\" clan_banner_url = f\"http://services.runescape.com/m=avatar-rs/l=3/a=869/{user_url_clan}/clanmotif.png\" embed_title = \"RuneClan\" rank_header = \"__Rank__\"",
"set_exp=True) except ConnectionError: return await ctx.send(f\"Houve um erro ao tentar",
"@commands.cooldown(1, 5, commands.BucketType.user) @commands.bot_has_permissions(embed_links=True) @commands.command(aliases=['ranksupdate', 'upranks', 'rank']) async def ranks(self,",
"'atlantis': exp_general = 2_000_000_000 exp_captain = 1_000_000_000 exp_lieutenant = 500_000_000",
"f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found = True if not found: ranks_embed.add_field(",
"= bot @commands.cooldown(1, 5, commands.BucketType.user) @commands.bot_has_permissions(embed_links=True) @commands.command(aliases=['clan']) async def clan_detail_info(self,",
"member.exp >= exp_general and member.rank == 'Captain': ranks_embed.add_field( name=member.name, value=f\"Capitão",
"'Lieutenant': self.bot.setting.clan_settings['Lieutenant']['Emoji'], 'Captain': self.bot.setting.clan_settings['Captain']['Emoji'], 'General': self.bot.setting.clan_settings['General']['Emoji'], } ranks_embed = discord.Embed(",
"primeiros.') break if member.exp >= exp_corporal and member.rank == 'Recruit':",
"30_000_000 clan = 'Atlantis Argus' else: return await ctx.send('Clã não",
"value=f\"Cabo {rank_emoji['Corporal']} ❯ Sargento {rank_emoji['Sergeant']}\\n\" f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found =",
"reconhecido.') rank_emoji = { 'Recruit': self.bot.setting.clan_settings['Recruit']['Emoji'], 'Corporal': self.bot.setting.clan_settings['Corporal']['Emoji'], 'Sergeant': self.bot.setting.clan_settings['Sergeant']['Emoji'],",
"clã.\") user_clan = rs3clans.Clan(name=player.clan) member = user_clan.get_member(username) user_clan_exp = member.exp",
"\"__Clã__\" exp_header = \"__Exp no Clã__\" total_exp_header = \"__Exp Total__\"",
"user_rank = self.bot.setting.clan_settings[user_rank]['Translation'] clan_info_embed = discord.Embed( title=embed_title, description=\"\", color=discord.Colour.dark_blue(), url=runeclan_url,",
"ctx.send(f\"Houve um erro ao tentar conectar a API da Jagex.",
"'Atlantis'): if clan.lower() == 'atlantis argus': return await ctx.send('`!rank argus`",
"value=clan_leader) clan_embed.add_field(name=\"Exp Média por Membro\", value=f'{clan.avg_exp:,.0f}') return await ctx.send(embed=clan_embed) @commands.cooldown(1,",
"clan_detail_info(self, ctx: Context, *, clan_name: str): try: clan = rs3clans.Clan(name=clan_name,",
"async def clan_user_info(self, ctx: Context, *, username: str): try: player",
"reversed([member for member in clan]) member: rs3clans.ClanMember for member in",
"f\"**__Exp:__** {member.exp:,}\\n{separator}\", inline=False) found = True elif member.exp >= exp_seargent",
"name=display_username ) clan_info_embed.set_thumbnail( url=clan_banner_url ) clan_info_embed.add_field( name=clan_header, value=player.clan ) clan_info_embed.add_field(",
"= \"Indisponível - Perfil Privado\" rank_emoji = self.bot.setting.clan_settings[user_rank]['Emoji'] user_rank ="
] |
[
"self.openstack('vpc peering delete {}'.format(self.PEERING_ID)) def _create_routers(self): local_router = json.loads(self.openstack( 'router",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR",
"may obtain # a copy of the License at #",
"agreed to in writing, software # distributed under the License",
"base class VpcTestCase(base.TestCase): \"\"\"Common functional test bits for VPC commands\"\"\"",
"Unless required by applicable law or agreed to in writing,",
"def _delete_routers(self): self.openstack( 'router delete {} {}'.format( self.LOCAL_ROUTER_ID, self.PEER_ROUTER_ID ))",
"distributed under the License is distributed on an \"AS IS\"",
"uuid from datetime import datetime from openstackclient.tests.functional import base class",
"= peer_router['id'] def _delete_routers(self): self.openstack( 'router delete {} {}'.format( self.LOCAL_ROUTER_ID,",
"import datetime from openstackclient.tests.functional import base class VpcTestCase(base.TestCase): \"\"\"Common functional",
"= json.loads(self.openstack( 'router create -f json ' + self.LOCAL_ROUTER_NAME ))",
"None self.PEER_ROUTER_ID = None self.PEERING_ID = None def create_vpc_peering(self, name=None):",
"= None def create_vpc_peering(self, name=None): self._create_routers() name = name or",
"= 'test-local-router-otce-cli' + UUID self.PEER_ROUTER_NAME = 'test-peer-router-otce-cli' + UUID self.PEERING_NAME",
"' + self.LOCAL_ROUTER_NAME )) self.LOCAL_ROUTER_ID = local_router['id'] peer_router = json.loads(self.openstack(",
"UUID = uuid.uuid4().hex[:8] self.LOCAL_ROUTER_NAME = 'test-local-router-otce-cli' + UUID self.PEER_ROUTER_NAME =",
"'test-local-router-otce-cli' + UUID self.PEER_ROUTER_NAME = 'test-peer-router-otce-cli' + UUID self.PEERING_NAME =",
"License, Version 2.0 (the \"License\"); you may # not use",
"CONDITIONS OF ANY KIND, either express or implied. See the",
"self._create_routers() name = name or self.PEERING_NAME json_output = json.loads(self.openstack( 'vpc",
"def delete_vpc_peering(self): self.addCleanup(self._delete_routers) self.openstack('vpc peering delete {}'.format(self.PEERING_ID)) def _create_routers(self): local_router",
"create -f json ' + self.PEER_ROUTER_NAME )) self.PEER_ROUTER_ID = peer_router['id']",
"obtain # a copy of the License at # #",
"name = name or self.PEERING_NAME json_output = json.loads(self.openstack( 'vpc peering",
"applicable law or agreed to in writing, software # distributed",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"= name or self.PEERING_NAME json_output = json.loads(self.openstack( 'vpc peering create",
"json ' + self.LOCAL_ROUTER_NAME )) self.LOCAL_ROUTER_ID = local_router['id'] peer_router =",
"Version 2.0 (the \"License\"); you may # not use this",
"setUp(self): super(VpcTestCase, self).setUp() UUID = uuid.uuid4().hex[:8] self.LOCAL_ROUTER_NAME = 'test-local-router-otce-cli' +",
"specific language governing permissions and limitations # under the License.",
"create -f json ' + self.LOCAL_ROUTER_NAME )) self.LOCAL_ROUTER_ID = local_router['id']",
"json_output = json.loads(self.openstack( 'vpc peering create ' '{name} ' '--local-router-id",
"# not use this file except in compliance with the",
"not use this file except in compliance with the License.",
"OF ANY KIND, either express or implied. See the #",
"= uuid.uuid4().hex[:8] self.LOCAL_ROUTER_NAME = 'test-local-router-otce-cli' + UUID self.PEER_ROUTER_NAME = 'test-peer-router-otce-cli'",
"create ' '{name} ' '--local-router-id \"{local_router_id}\" ' '--peer-router-id \"{peer_router_id}\" '",
"self.addCleanup(self._delete_routers) self.openstack('vpc peering delete {}'.format(self.PEERING_ID)) def _create_routers(self): local_router = json.loads(self.openstack(",
"import json import uuid from datetime import datetime from openstackclient.tests.functional",
"writing, software # distributed under the License is distributed on",
"peering create ' '{name} ' '--local-router-id \"{local_router_id}\" ' '--peer-router-id \"{peer_router_id}\"",
"WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"in writing, software # distributed under the License is distributed",
"json ' + self.PEER_ROUTER_NAME )) self.PEER_ROUTER_ID = peer_router['id'] def _delete_routers(self):",
"in compliance with the License. You may obtain # a",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"License for the specific language governing permissions and limitations #",
"self.LOCAL_ROUTER_NAME = 'test-local-router-otce-cli' + UUID self.PEER_ROUTER_NAME = 'test-peer-router-otce-cli' + UUID",
"from datetime import datetime from openstackclient.tests.functional import base class VpcTestCase(base.TestCase):",
"or self.PEERING_NAME json_output = json.loads(self.openstack( 'vpc peering create ' '{name}",
"the License. You may obtain # a copy of the",
"'--local-router-id \"{local_router_id}\" ' '--peer-router-id \"{peer_router_id}\" ' '-f json'.format( name=name, local_router_id=self.LOCAL_ROUTER_ID,",
"an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF",
"on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS",
"use this file except in compliance with the License. You",
"= 'test-peer-router-otce-cli' + UUID self.PEERING_NAME = 'test-peering-otce-cli-' + UUID self.LOCAL_ROUTER_ID",
"You may obtain # a copy of the License at",
"self.PEERING_ID = None def create_vpc_peering(self, name=None): self._create_routers() name = name",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"+ self.PEER_ROUTER_NAME )) self.PEER_ROUTER_ID = peer_router['id'] def _delete_routers(self): self.openstack( 'router",
"-f json ' + self.PEER_ROUTER_NAME )) self.PEER_ROUTER_ID = peer_router['id'] def",
"name=None): self._create_routers() name = name or self.PEERING_NAME json_output = json.loads(self.openstack(",
"License. # import json import uuid from datetime import datetime",
"\"{local_router_id}\" ' '--peer-router-id \"{peer_router_id}\" ' '-f json'.format( name=name, local_router_id=self.LOCAL_ROUTER_ID, peer_router_id=self.PEER_ROUTER_ID)",
"+ UUID self.LOCAL_ROUTER_ID = None self.PEER_ROUTER_ID = None self.PEERING_ID =",
"{}'.format(self.PEERING_ID)) def _create_routers(self): local_router = json.loads(self.openstack( 'router create -f json",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"local_router_id=self.LOCAL_ROUTER_ID, peer_router_id=self.PEER_ROUTER_ID) )) self.assertIsNotNone(json_output) self.PEERING_ID = json_output['id'] return json_output def",
"None self.PEERING_ID = None def create_vpc_peering(self, name=None): self._create_routers() name =",
"for VPC commands\"\"\" CURR_TIME = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S.%f\") def setUp(self): super(VpcTestCase,",
"either express or implied. See the # License for the",
"super(VpcTestCase, self).setUp() UUID = uuid.uuid4().hex[:8] self.LOCAL_ROUTER_NAME = 'test-local-router-otce-cli' + UUID",
"functional test bits for VPC commands\"\"\" CURR_TIME = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S.%f\")",
"openstackclient.tests.functional import base class VpcTestCase(base.TestCase): \"\"\"Common functional test bits for",
"VpcTestCase(base.TestCase): \"\"\"Common functional test bits for VPC commands\"\"\" CURR_TIME =",
"under the License is distributed on an \"AS IS\" BASIS,",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
")) self.PEER_ROUTER_ID = peer_router['id'] def _delete_routers(self): self.openstack( 'router delete {}",
"Licensed under the Apache License, Version 2.0 (the \"License\"); you",
"'{name} ' '--local-router-id \"{local_router_id}\" ' '--peer-router-id \"{peer_router_id}\" ' '-f json'.format(",
"'router create -f json ' + self.LOCAL_ROUTER_NAME )) self.LOCAL_ROUTER_ID =",
"json import uuid from datetime import datetime from openstackclient.tests.functional import",
"may # not use this file except in compliance with",
"commands\"\"\" CURR_TIME = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S.%f\") def setUp(self): super(VpcTestCase, self).setUp() UUID",
"under the License. # import json import uuid from datetime",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"name or self.PEERING_NAME json_output = json.loads(self.openstack( 'vpc peering create '",
"_create_routers(self): local_router = json.loads(self.openstack( 'router create -f json ' +",
"' + self.PEER_ROUTER_NAME )) self.PEER_ROUTER_ID = peer_router['id'] def _delete_routers(self): self.openstack(",
"License is distributed on an \"AS IS\" BASIS, WITHOUT #",
"with the License. You may obtain # a copy of",
"KIND, either express or implied. See the # License for",
"# License for the specific language governing permissions and limitations",
"delete_vpc_peering(self): self.addCleanup(self._delete_routers) self.openstack('vpc peering delete {}'.format(self.PEERING_ID)) def _create_routers(self): local_router =",
"self.PEER_ROUTER_NAME = 'test-peer-router-otce-cli' + UUID self.PEERING_NAME = 'test-peering-otce-cli-' + UUID",
"you may # not use this file except in compliance",
"governing permissions and limitations # under the License. # import",
"\"License\"); you may # not use this file except in",
"'vpc peering create ' '{name} ' '--local-router-id \"{local_router_id}\" ' '--peer-router-id",
"json_output['id'] return json_output def delete_vpc_peering(self): self.addCleanup(self._delete_routers) self.openstack('vpc peering delete {}'.format(self.PEERING_ID))",
"and limitations # under the License. # import json import",
"IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,",
"self).setUp() UUID = uuid.uuid4().hex[:8] self.LOCAL_ROUTER_NAME = 'test-local-router-otce-cli' + UUID self.PEER_ROUTER_NAME",
"'test-peer-router-otce-cli' + UUID self.PEERING_NAME = 'test-peering-otce-cli-' + UUID self.LOCAL_ROUTER_ID =",
"delete {}'.format(self.PEERING_ID)) def _create_routers(self): local_router = json.loads(self.openstack( 'router create -f",
"peer_router['id'] def _delete_routers(self): self.openstack( 'router delete {} {}'.format( self.LOCAL_ROUTER_ID, self.PEER_ROUTER_ID",
"express or implied. See the # License for the specific",
"datetime import datetime from openstackclient.tests.functional import base class VpcTestCase(base.TestCase): \"\"\"Common",
"this file except in compliance with the License. You may",
"= 'test-peering-otce-cli-' + UUID self.LOCAL_ROUTER_ID = None self.PEER_ROUTER_ID = None",
"# under the License. # import json import uuid from",
"compliance with the License. You may obtain # a copy",
"return json_output def delete_vpc_peering(self): self.addCleanup(self._delete_routers) self.openstack('vpc peering delete {}'.format(self.PEERING_ID)) def",
"the Apache License, Version 2.0 (the \"License\"); you may #",
"+ UUID self.PEERING_NAME = 'test-peering-otce-cli-' + UUID self.LOCAL_ROUTER_ID = None",
"+ UUID self.PEER_ROUTER_NAME = 'test-peer-router-otce-cli' + UUID self.PEERING_NAME = 'test-peering-otce-cli-'",
"peer_router = json.loads(self.openstack( 'router create -f json ' + self.PEER_ROUTER_NAME",
"self.PEER_ROUTER_NAME )) self.PEER_ROUTER_ID = peer_router['id'] def _delete_routers(self): self.openstack( 'router delete",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"UUID self.LOCAL_ROUTER_ID = None self.PEER_ROUTER_ID = None self.PEERING_ID = None",
"' '--local-router-id \"{local_router_id}\" ' '--peer-router-id \"{peer_router_id}\" ' '-f json'.format( name=name,",
"language governing permissions and limitations # under the License. #",
"local_router['id'] peer_router = json.loads(self.openstack( 'router create -f json ' +",
"# WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"self.PEER_ROUTER_ID = None self.PEERING_ID = None def create_vpc_peering(self, name=None): self._create_routers()",
"+ self.LOCAL_ROUTER_NAME )) self.LOCAL_ROUTER_ID = local_router['id'] peer_router = json.loads(self.openstack( 'router",
"def create_vpc_peering(self, name=None): self._create_routers() name = name or self.PEERING_NAME json_output",
"See the # License for the specific language governing permissions",
"software # distributed under the License is distributed on an",
"(the \"License\"); you may # not use this file except",
")) self.assertIsNotNone(json_output) self.PEERING_ID = json_output['id'] return json_output def delete_vpc_peering(self): self.addCleanup(self._delete_routers)",
"self.PEERING_NAME json_output = json.loads(self.openstack( 'vpc peering create ' '{name} '",
"peering delete {}'.format(self.PEERING_ID)) def _create_routers(self): local_router = json.loads(self.openstack( 'router create",
"the License is distributed on an \"AS IS\" BASIS, WITHOUT",
"the # License for the specific language governing permissions and",
"= json_output['id'] return json_output def delete_vpc_peering(self): self.addCleanup(self._delete_routers) self.openstack('vpc peering delete",
"# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"# # Unless required by applicable law or agreed to",
"local_router = json.loads(self.openstack( 'router create -f json ' + self.LOCAL_ROUTER_NAME",
"class VpcTestCase(base.TestCase): \"\"\"Common functional test bits for VPC commands\"\"\" CURR_TIME",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"self.PEER_ROUTER_ID = peer_router['id'] def _delete_routers(self): self.openstack( 'router delete {} {}'.format(",
"json_output def delete_vpc_peering(self): self.addCleanup(self._delete_routers) self.openstack('vpc peering delete {}'.format(self.PEERING_ID)) def _create_routers(self):",
"file except in compliance with the License. You may obtain",
"= local_router['id'] peer_router = json.loads(self.openstack( 'router create -f json '",
"'--peer-router-id \"{peer_router_id}\" ' '-f json'.format( name=name, local_router_id=self.LOCAL_ROUTER_ID, peer_router_id=self.PEER_ROUTER_ID) )) self.assertIsNotNone(json_output)",
"VPC commands\"\"\" CURR_TIME = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S.%f\") def setUp(self): super(VpcTestCase, self).setUp()",
"for the specific language governing permissions and limitations # under",
"law or agreed to in writing, software # distributed under",
"OR CONDITIONS OF ANY KIND, either express or implied. See",
"the specific language governing permissions and limitations # under the",
"%H:%M:%S.%f\") def setUp(self): super(VpcTestCase, self).setUp() UUID = uuid.uuid4().hex[:8] self.LOCAL_ROUTER_NAME =",
"bits for VPC commands\"\"\" CURR_TIME = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S.%f\") def setUp(self):",
"CURR_TIME = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S.%f\") def setUp(self): super(VpcTestCase, self).setUp() UUID =",
"self.LOCAL_ROUTER_ID = None self.PEER_ROUTER_ID = None self.PEERING_ID = None def",
"limitations # under the License. # import json import uuid",
"test bits for VPC commands\"\"\" CURR_TIME = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S.%f\") def",
"\"{peer_router_id}\" ' '-f json'.format( name=name, local_router_id=self.LOCAL_ROUTER_ID, peer_router_id=self.PEER_ROUTER_ID) )) self.assertIsNotNone(json_output) self.PEERING_ID",
"under the Apache License, Version 2.0 (the \"License\"); you may",
"import uuid from datetime import datetime from openstackclient.tests.functional import base",
"except in compliance with the License. You may obtain #",
"2.0 (the \"License\"); you may # not use this file",
"None def create_vpc_peering(self, name=None): self._create_routers() name = name or self.PEERING_NAME",
"implied. See the # License for the specific language governing",
"UUID self.PEERING_NAME = 'test-peering-otce-cli-' + UUID self.LOCAL_ROUTER_ID = None self.PEER_ROUTER_ID",
"def _create_routers(self): local_router = json.loads(self.openstack( 'router create -f json '",
"'-f json'.format( name=name, local_router_id=self.LOCAL_ROUTER_ID, peer_router_id=self.PEER_ROUTER_ID) )) self.assertIsNotNone(json_output) self.PEERING_ID = json_output['id']",
"= json.loads(self.openstack( 'vpc peering create ' '{name} ' '--local-router-id \"{local_router_id}\"",
"' '{name} ' '--local-router-id \"{local_router_id}\" ' '--peer-router-id \"{peer_router_id}\" ' '-f",
"License. You may obtain # a copy of the License",
"= datetime.now().strftime(\"%Y-%m-%d %H:%M:%S.%f\") def setUp(self): super(VpcTestCase, self).setUp() UUID = uuid.uuid4().hex[:8]",
"def setUp(self): super(VpcTestCase, self).setUp() UUID = uuid.uuid4().hex[:8] self.LOCAL_ROUTER_NAME = 'test-local-router-otce-cli'",
"by applicable law or agreed to in writing, software #",
"# distributed under the License is distributed on an \"AS",
"ANY KIND, either express or implied. See the # License",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY",
"'test-peering-otce-cli-' + UUID self.LOCAL_ROUTER_ID = None self.PEER_ROUTER_ID = None self.PEERING_ID",
"self.PEERING_NAME = 'test-peering-otce-cli-' + UUID self.LOCAL_ROUTER_ID = None self.PEER_ROUTER_ID =",
"name=name, local_router_id=self.LOCAL_ROUTER_ID, peer_router_id=self.PEER_ROUTER_ID) )) self.assertIsNotNone(json_output) self.PEERING_ID = json_output['id'] return json_output",
"# Unless required by applicable law or agreed to in",
"self.PEERING_ID = json_output['id'] return json_output def delete_vpc_peering(self): self.addCleanup(self._delete_routers) self.openstack('vpc peering",
"json.loads(self.openstack( 'router create -f json ' + self.LOCAL_ROUTER_NAME )) self.LOCAL_ROUTER_ID",
"= None self.PEER_ROUTER_ID = None self.PEERING_ID = None def create_vpc_peering(self,",
"peer_router_id=self.PEER_ROUTER_ID) )) self.assertIsNotNone(json_output) self.PEERING_ID = json_output['id'] return json_output def delete_vpc_peering(self):",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
")) self.LOCAL_ROUTER_ID = local_router['id'] peer_router = json.loads(self.openstack( 'router create -f",
"datetime.now().strftime(\"%Y-%m-%d %H:%M:%S.%f\") def setUp(self): super(VpcTestCase, self).setUp() UUID = uuid.uuid4().hex[:8] self.LOCAL_ROUTER_NAME",
"'router create -f json ' + self.PEER_ROUTER_NAME )) self.PEER_ROUTER_ID =",
"to in writing, software # distributed under the License is",
"is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES",
"= json.loads(self.openstack( 'router create -f json ' + self.PEER_ROUTER_NAME ))",
"# import json import uuid from datetime import datetime from",
"BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either",
"datetime from openstackclient.tests.functional import base class VpcTestCase(base.TestCase): \"\"\"Common functional test",
"self.assertIsNotNone(json_output) self.PEERING_ID = json_output['id'] return json_output def delete_vpc_peering(self): self.addCleanup(self._delete_routers) self.openstack('vpc",
"<filename>otcextensions/tests/functional/osclient/vpc/v2/common.py # Licensed under the Apache License, Version 2.0 (the",
"or agreed to in writing, software # distributed under the",
"= None self.PEERING_ID = None def create_vpc_peering(self, name=None): self._create_routers() name",
"json.loads(self.openstack( 'vpc peering create ' '{name} ' '--local-router-id \"{local_router_id}\" '",
"from openstackclient.tests.functional import base class VpcTestCase(base.TestCase): \"\"\"Common functional test bits",
"required by applicable law or agreed to in writing, software",
"self.LOCAL_ROUTER_ID = local_router['id'] peer_router = json.loads(self.openstack( 'router create -f json",
"self.LOCAL_ROUTER_NAME )) self.LOCAL_ROUTER_ID = local_router['id'] peer_router = json.loads(self.openstack( 'router create",
"' '--peer-router-id \"{peer_router_id}\" ' '-f json'.format( name=name, local_router_id=self.LOCAL_ROUTER_ID, peer_router_id=self.PEER_ROUTER_ID) ))",
"json'.format( name=name, local_router_id=self.LOCAL_ROUTER_ID, peer_router_id=self.PEER_ROUTER_ID) )) self.assertIsNotNone(json_output) self.PEERING_ID = json_output['id'] return",
"UUID self.PEER_ROUTER_NAME = 'test-peer-router-otce-cli' + UUID self.PEERING_NAME = 'test-peering-otce-cli-' +",
"uuid.uuid4().hex[:8] self.LOCAL_ROUTER_NAME = 'test-local-router-otce-cli' + UUID self.PEER_ROUTER_NAME = 'test-peer-router-otce-cli' +",
"\"\"\"Common functional test bits for VPC commands\"\"\" CURR_TIME = datetime.now().strftime(\"%Y-%m-%d",
"create_vpc_peering(self, name=None): self._create_routers() name = name or self.PEERING_NAME json_output =",
"' '-f json'.format( name=name, local_router_id=self.LOCAL_ROUTER_ID, peer_router_id=self.PEER_ROUTER_ID) )) self.assertIsNotNone(json_output) self.PEERING_ID =",
"the License. # import json import uuid from datetime import",
"import base class VpcTestCase(base.TestCase): \"\"\"Common functional test bits for VPC",
"json.loads(self.openstack( 'router create -f json ' + self.PEER_ROUTER_NAME )) self.PEER_ROUTER_ID",
"-f json ' + self.LOCAL_ROUTER_NAME )) self.LOCAL_ROUTER_ID = local_router['id'] peer_router",
"or implied. See the # License for the specific language",
"Apache License, Version 2.0 (the \"License\"); you may # not",
"permissions and limitations # under the License. # import json"
] |
[
"self.users_table.update_field( key_value=TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}.{{itemKeyChild}}', query_kwargs={'itemKey': random_parent_key, 'itemKeyChild': random_child_key}, value_to_set=True ) self.assertTrue(update_success)",
"str): super().__init__(methodName=method_name) self.users_table = PlaygroundDynamoDBBasicTable(data_model=TableModel) def test_nested_dict_dict_structure(self): random_parent_key = f\"parentKey_{uuid4()}\"",
"self.users_table.remove_field( key_value=TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}', query_kwargs={'itemKey': random_parent_key} ) self.assertEqual(removed_item, {'itemKeyChild': True}) retrieved_expected_none_item",
"query_kwargs={'itemKey': random_parent_key} ) self.assertEqual(removed_item, {'itemKeyChild': True}) retrieved_expected_none_item = self.users_table.get_field( TEST_ACCOUNT_ID,",
"True}) retrieved_expected_none_item = self.users_table.get_field( TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}', query_kwargs={'itemKey': random_parent_key} ) self.assertIsNone(retrieved_expected_none_item)",
"BaseField(field_type=Dict[str, Set[str]], required=False) class TestsNestedStructuresInsideStructureValues(unittest.TestCase): def __init__(self, method_name: str): super().__init__(methodName=method_name)",
"TableDataModel from tests.components.playground_table_clients import PlaygroundDynamoDBBasicTable, TEST_ACCOUNT_ID class TableModel(TableDataModel): accountId =",
"# todo: implement pass def test_nested_dict_set_structure(self): # todo: implement pass",
"def test_nested_dict_set_structure(self): # todo: implement pass if __name__ == '__main__':",
"= BaseField(field_type=str, required=True) nestedDictDictStructure = BaseField(field_type=Dict[str, Dict[str, bool]], required=False, key_name='itemKey')",
"test_nested_dict_set_structure(self): # todo: implement pass if __name__ == '__main__': unittest.main()",
"query_kwargs={'itemKey': random_parent_key} ) self.assertEqual(retrieved_item, {'itemKeyChild': True}) removed_item = self.users_table.remove_field( key_value=TEST_ACCOUNT_ID,",
"TableModel(TableDataModel): accountId = BaseField(field_type=str, required=True) nestedDictDictStructure = BaseField(field_type=Dict[str, Dict[str, bool]],",
"key_value=TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}.{{itemKeyChild}}', query_kwargs={'itemKey': random_parent_key, 'itemKeyChild': random_child_key}, value_to_set=True ) self.assertTrue(update_success) retrieved_item",
"key_value=TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}', query_kwargs={'itemKey': random_parent_key} ) self.assertEqual(retrieved_item, {'itemKeyChild': True}) removed_item =",
"super().__init__(methodName=method_name) self.users_table = PlaygroundDynamoDBBasicTable(data_model=TableModel) def test_nested_dict_dict_structure(self): random_parent_key = f\"parentKey_{uuid4()}\" random_child_key",
"random_parent_key = f\"parentKey_{uuid4()}\" random_child_key = f\"childKey_{uuid4()}\" keys_fields_switch = list(self.users_table.fields_switch.keys()) self.assertIn('nestedDictDictStructure.{{itemKey}}.{{itemKeyChild}}',",
"random_child_key = f\"childKey_{uuid4()}\" keys_fields_switch = list(self.users_table.fields_switch.keys()) self.assertIn('nestedDictDictStructure.{{itemKey}}.{{itemKeyChild}}', keys_fields_switch) update_success =",
"def __init__(self, method_name: str): super().__init__(methodName=method_name) self.users_table = PlaygroundDynamoDBBasicTable(data_model=TableModel) def test_nested_dict_dict_structure(self):",
"def test_nested_dict_list_structure(self): # todo: implement pass def test_nested_dict_set_structure(self): # todo:",
"test_nested_dict_dict_structure(self): random_parent_key = f\"parentKey_{uuid4()}\" random_child_key = f\"childKey_{uuid4()}\" keys_fields_switch = list(self.users_table.fields_switch.keys())",
"update_success = self.users_table.update_field( key_value=TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}.{{itemKeyChild}}', query_kwargs={'itemKey': random_parent_key, 'itemKeyChild': random_child_key}, value_to_set=True",
"import unittest from typing import Set, Optional, Dict, List from",
"True}) removed_item = self.users_table.remove_field( key_value=TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}', query_kwargs={'itemKey': random_parent_key} ) self.assertEqual(removed_item,",
"list(self.users_table.fields_switch.keys()) self.assertIn('nestedDictDictStructure.{{itemKey}}.{{itemKeyChild}}', keys_fields_switch) update_success = self.users_table.update_field( key_value=TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}.{{itemKeyChild}}', query_kwargs={'itemKey': random_parent_key,",
"BaseField(field_type=str, required=True) nestedDictDictStructure = BaseField(field_type=Dict[str, Dict[str, bool]], required=False, key_name='itemKey') #",
"uuid4 from StructNoSQL import BaseField, MapModel, TableDataModel from tests.components.playground_table_clients import",
"= self.users_table.remove_field( key_value=TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}', query_kwargs={'itemKey': random_parent_key} ) self.assertEqual(removed_item, {'itemKeyChild': True})",
"Set[str]], required=False) class TestsNestedStructuresInsideStructureValues(unittest.TestCase): def __init__(self, method_name: str): super().__init__(methodName=method_name) self.users_table",
"import PlaygroundDynamoDBBasicTable, TEST_ACCOUNT_ID class TableModel(TableDataModel): accountId = BaseField(field_type=str, required=True) nestedDictDictStructure",
"nestedDictListStructure = BaseField(field_type=Dict[str, List[str]], required=False) # nestedDictSetStructure = BaseField(field_type=Dict[str, Set[str]],",
"implement pass def test_nested_dict_set_structure(self): # todo: implement pass if __name__",
"'itemKeyChild': random_child_key}, value_to_set=True ) self.assertTrue(update_success) retrieved_item = self.users_table.get_field( key_value=TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}',",
"keys_fields_switch = list(self.users_table.fields_switch.keys()) self.assertIn('nestedDictDictStructure.{{itemKey}}.{{itemKeyChild}}', keys_fields_switch) update_success = self.users_table.update_field( key_value=TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}.{{itemKeyChild}}',",
"Dict, List from uuid import uuid4 from StructNoSQL import BaseField,",
"Dict[str, bool]], required=False, key_name='itemKey') # nestedDictListStructure = BaseField(field_type=Dict[str, List[str]], required=False)",
"Optional, Dict, List from uuid import uuid4 from StructNoSQL import",
"TestsNestedStructuresInsideStructureValues(unittest.TestCase): def __init__(self, method_name: str): super().__init__(methodName=method_name) self.users_table = PlaygroundDynamoDBBasicTable(data_model=TableModel) def",
"random_parent_key} ) self.assertEqual(retrieved_item, {'itemKeyChild': True}) removed_item = self.users_table.remove_field( key_value=TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}',",
"self.assertIn('nestedDictDictStructure.{{itemKey}}.{{itemKeyChild}}', keys_fields_switch) update_success = self.users_table.update_field( key_value=TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}.{{itemKeyChild}}', query_kwargs={'itemKey': random_parent_key, 'itemKeyChild':",
"required=True) nestedDictDictStructure = BaseField(field_type=Dict[str, Dict[str, bool]], required=False, key_name='itemKey') # nestedDictListStructure",
"uuid import uuid4 from StructNoSQL import BaseField, MapModel, TableDataModel from",
"MapModel, TableDataModel from tests.components.playground_table_clients import PlaygroundDynamoDBBasicTable, TEST_ACCOUNT_ID class TableModel(TableDataModel): accountId",
"required=False) class TestsNestedStructuresInsideStructureValues(unittest.TestCase): def __init__(self, method_name: str): super().__init__(methodName=method_name) self.users_table =",
"def test_nested_dict_dict_structure(self): random_parent_key = f\"parentKey_{uuid4()}\" random_child_key = f\"childKey_{uuid4()}\" keys_fields_switch =",
"<reponame>Robinson04/StructNoSQL import unittest from typing import Set, Optional, Dict, List",
"self.users_table.get_field( key_value=TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}', query_kwargs={'itemKey': random_parent_key} ) self.assertEqual(retrieved_item, {'itemKeyChild': True}) removed_item",
"BaseField(field_type=Dict[str, Dict[str, bool]], required=False, key_name='itemKey') # nestedDictListStructure = BaseField(field_type=Dict[str, List[str]],",
"random_parent_key} ) self.assertEqual(removed_item, {'itemKeyChild': True}) retrieved_expected_none_item = self.users_table.get_field( TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}',",
"PlaygroundDynamoDBBasicTable(data_model=TableModel) def test_nested_dict_dict_structure(self): random_parent_key = f\"parentKey_{uuid4()}\" random_child_key = f\"childKey_{uuid4()}\" keys_fields_switch",
") self.assertTrue(update_success) retrieved_item = self.users_table.get_field( key_value=TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}', query_kwargs={'itemKey': random_parent_key} )",
"retrieved_expected_none_item = self.users_table.get_field( TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}', query_kwargs={'itemKey': random_parent_key} ) self.assertIsNone(retrieved_expected_none_item) def",
"random_parent_key, 'itemKeyChild': random_child_key}, value_to_set=True ) self.assertTrue(update_success) retrieved_item = self.users_table.get_field( key_value=TEST_ACCOUNT_ID,",
") self.assertEqual(retrieved_item, {'itemKeyChild': True}) removed_item = self.users_table.remove_field( key_value=TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}', query_kwargs={'itemKey':",
"key_name='itemKey') # nestedDictListStructure = BaseField(field_type=Dict[str, List[str]], required=False) # nestedDictSetStructure =",
"from StructNoSQL import BaseField, MapModel, TableDataModel from tests.components.playground_table_clients import PlaygroundDynamoDBBasicTable,",
"random_parent_key} ) self.assertIsNone(retrieved_expected_none_item) def test_nested_dict_list_structure(self): # todo: implement pass def",
"from typing import Set, Optional, Dict, List from uuid import",
"keys_fields_switch) update_success = self.users_table.update_field( key_value=TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}.{{itemKeyChild}}', query_kwargs={'itemKey': random_parent_key, 'itemKeyChild': random_child_key},",
") self.assertEqual(removed_item, {'itemKeyChild': True}) retrieved_expected_none_item = self.users_table.get_field( TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}', query_kwargs={'itemKey':",
"test_nested_dict_list_structure(self): # todo: implement pass def test_nested_dict_set_structure(self): # todo: implement",
"StructNoSQL import BaseField, MapModel, TableDataModel from tests.components.playground_table_clients import PlaygroundDynamoDBBasicTable, TEST_ACCOUNT_ID",
"= list(self.users_table.fields_switch.keys()) self.assertIn('nestedDictDictStructure.{{itemKey}}.{{itemKeyChild}}', keys_fields_switch) update_success = self.users_table.update_field( key_value=TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}.{{itemKeyChild}}', query_kwargs={'itemKey':",
"= self.users_table.get_field( TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}', query_kwargs={'itemKey': random_parent_key} ) self.assertIsNone(retrieved_expected_none_item) def test_nested_dict_list_structure(self):",
"BaseField(field_type=Dict[str, List[str]], required=False) # nestedDictSetStructure = BaseField(field_type=Dict[str, Set[str]], required=False) class",
"retrieved_item = self.users_table.get_field( key_value=TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}', query_kwargs={'itemKey': random_parent_key} ) self.assertEqual(retrieved_item, {'itemKeyChild':",
"= BaseField(field_type=Dict[str, Set[str]], required=False) class TestsNestedStructuresInsideStructureValues(unittest.TestCase): def __init__(self, method_name: str):",
"self.assertIsNone(retrieved_expected_none_item) def test_nested_dict_list_structure(self): # todo: implement pass def test_nested_dict_set_structure(self): #",
"{'itemKeyChild': True}) retrieved_expected_none_item = self.users_table.get_field( TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}', query_kwargs={'itemKey': random_parent_key} )",
"List from uuid import uuid4 from StructNoSQL import BaseField, MapModel,",
"# nestedDictListStructure = BaseField(field_type=Dict[str, List[str]], required=False) # nestedDictSetStructure = BaseField(field_type=Dict[str,",
"TEST_ACCOUNT_ID class TableModel(TableDataModel): accountId = BaseField(field_type=str, required=True) nestedDictDictStructure = BaseField(field_type=Dict[str,",
"self.assertEqual(retrieved_item, {'itemKeyChild': True}) removed_item = self.users_table.remove_field( key_value=TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}', query_kwargs={'itemKey': random_parent_key}",
"class TableModel(TableDataModel): accountId = BaseField(field_type=str, required=True) nestedDictDictStructure = BaseField(field_type=Dict[str, Dict[str,",
"__init__(self, method_name: str): super().__init__(methodName=method_name) self.users_table = PlaygroundDynamoDBBasicTable(data_model=TableModel) def test_nested_dict_dict_structure(self): random_parent_key",
"self.users_table = PlaygroundDynamoDBBasicTable(data_model=TableModel) def test_nested_dict_dict_structure(self): random_parent_key = f\"parentKey_{uuid4()}\" random_child_key =",
"removed_item = self.users_table.remove_field( key_value=TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}', query_kwargs={'itemKey': random_parent_key} ) self.assertEqual(removed_item, {'itemKeyChild':",
"unittest from typing import Set, Optional, Dict, List from uuid",
"method_name: str): super().__init__(methodName=method_name) self.users_table = PlaygroundDynamoDBBasicTable(data_model=TableModel) def test_nested_dict_dict_structure(self): random_parent_key =",
"BaseField, MapModel, TableDataModel from tests.components.playground_table_clients import PlaygroundDynamoDBBasicTable, TEST_ACCOUNT_ID class TableModel(TableDataModel):",
"self.users_table.get_field( TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}', query_kwargs={'itemKey': random_parent_key} ) self.assertIsNone(retrieved_expected_none_item) def test_nested_dict_list_structure(self): #",
"bool]], required=False, key_name='itemKey') # nestedDictListStructure = BaseField(field_type=Dict[str, List[str]], required=False) #",
"required=False) # nestedDictSetStructure = BaseField(field_type=Dict[str, Set[str]], required=False) class TestsNestedStructuresInsideStructureValues(unittest.TestCase): def",
"pass def test_nested_dict_set_structure(self): # todo: implement pass if __name__ ==",
"= PlaygroundDynamoDBBasicTable(data_model=TableModel) def test_nested_dict_dict_structure(self): random_parent_key = f\"parentKey_{uuid4()}\" random_child_key = f\"childKey_{uuid4()}\"",
"PlaygroundDynamoDBBasicTable, TEST_ACCOUNT_ID class TableModel(TableDataModel): accountId = BaseField(field_type=str, required=True) nestedDictDictStructure =",
"query_kwargs={'itemKey': random_parent_key, 'itemKeyChild': random_child_key}, value_to_set=True ) self.assertTrue(update_success) retrieved_item = self.users_table.get_field(",
"random_child_key}, value_to_set=True ) self.assertTrue(update_success) retrieved_item = self.users_table.get_field( key_value=TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}', query_kwargs={'itemKey':",
"field_path='nestedDictDictStructure.{{itemKey}}', query_kwargs={'itemKey': random_parent_key} ) self.assertEqual(retrieved_item, {'itemKeyChild': True}) removed_item = self.users_table.remove_field(",
"required=False, key_name='itemKey') # nestedDictListStructure = BaseField(field_type=Dict[str, List[str]], required=False) # nestedDictSetStructure",
"= self.users_table.get_field( key_value=TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}', query_kwargs={'itemKey': random_parent_key} ) self.assertEqual(retrieved_item, {'itemKeyChild': True})",
"typing import Set, Optional, Dict, List from uuid import uuid4",
"class TestsNestedStructuresInsideStructureValues(unittest.TestCase): def __init__(self, method_name: str): super().__init__(methodName=method_name) self.users_table = PlaygroundDynamoDBBasicTable(data_model=TableModel)",
"import Set, Optional, Dict, List from uuid import uuid4 from",
"query_kwargs={'itemKey': random_parent_key} ) self.assertIsNone(retrieved_expected_none_item) def test_nested_dict_list_structure(self): # todo: implement pass",
"self.assertEqual(removed_item, {'itemKeyChild': True}) retrieved_expected_none_item = self.users_table.get_field( TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}', query_kwargs={'itemKey': random_parent_key}",
"todo: implement pass def test_nested_dict_set_structure(self): # todo: implement pass if",
"accountId = BaseField(field_type=str, required=True) nestedDictDictStructure = BaseField(field_type=Dict[str, Dict[str, bool]], required=False,",
"= BaseField(field_type=Dict[str, List[str]], required=False) # nestedDictSetStructure = BaseField(field_type=Dict[str, Set[str]], required=False)",
"Set, Optional, Dict, List from uuid import uuid4 from StructNoSQL",
"TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}', query_kwargs={'itemKey': random_parent_key} ) self.assertIsNone(retrieved_expected_none_item) def test_nested_dict_list_structure(self): # todo:",
"from uuid import uuid4 from StructNoSQL import BaseField, MapModel, TableDataModel",
"from tests.components.playground_table_clients import PlaygroundDynamoDBBasicTable, TEST_ACCOUNT_ID class TableModel(TableDataModel): accountId = BaseField(field_type=str,",
"List[str]], required=False) # nestedDictSetStructure = BaseField(field_type=Dict[str, Set[str]], required=False) class TestsNestedStructuresInsideStructureValues(unittest.TestCase):",
"nestedDictDictStructure = BaseField(field_type=Dict[str, Dict[str, bool]], required=False, key_name='itemKey') # nestedDictListStructure =",
"= self.users_table.update_field( key_value=TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}.{{itemKeyChild}}', query_kwargs={'itemKey': random_parent_key, 'itemKeyChild': random_child_key}, value_to_set=True )",
"{'itemKeyChild': True}) removed_item = self.users_table.remove_field( key_value=TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}', query_kwargs={'itemKey': random_parent_key} )",
"nestedDictSetStructure = BaseField(field_type=Dict[str, Set[str]], required=False) class TestsNestedStructuresInsideStructureValues(unittest.TestCase): def __init__(self, method_name:",
"# nestedDictSetStructure = BaseField(field_type=Dict[str, Set[str]], required=False) class TestsNestedStructuresInsideStructureValues(unittest.TestCase): def __init__(self,",
"= BaseField(field_type=Dict[str, Dict[str, bool]], required=False, key_name='itemKey') # nestedDictListStructure = BaseField(field_type=Dict[str,",
") self.assertIsNone(retrieved_expected_none_item) def test_nested_dict_list_structure(self): # todo: implement pass def test_nested_dict_set_structure(self):",
"tests.components.playground_table_clients import PlaygroundDynamoDBBasicTable, TEST_ACCOUNT_ID class TableModel(TableDataModel): accountId = BaseField(field_type=str, required=True)",
"= f\"childKey_{uuid4()}\" keys_fields_switch = list(self.users_table.fields_switch.keys()) self.assertIn('nestedDictDictStructure.{{itemKey}}.{{itemKeyChild}}', keys_fields_switch) update_success = self.users_table.update_field(",
"key_value=TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}', query_kwargs={'itemKey': random_parent_key} ) self.assertEqual(removed_item, {'itemKeyChild': True}) retrieved_expected_none_item =",
"f\"childKey_{uuid4()}\" keys_fields_switch = list(self.users_table.fields_switch.keys()) self.assertIn('nestedDictDictStructure.{{itemKey}}.{{itemKeyChild}}', keys_fields_switch) update_success = self.users_table.update_field( key_value=TEST_ACCOUNT_ID,",
"value_to_set=True ) self.assertTrue(update_success) retrieved_item = self.users_table.get_field( key_value=TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}', query_kwargs={'itemKey': random_parent_key}",
"= f\"parentKey_{uuid4()}\" random_child_key = f\"childKey_{uuid4()}\" keys_fields_switch = list(self.users_table.fields_switch.keys()) self.assertIn('nestedDictDictStructure.{{itemKey}}.{{itemKeyChild}}', keys_fields_switch)",
"field_path='nestedDictDictStructure.{{itemKey}}.{{itemKeyChild}}', query_kwargs={'itemKey': random_parent_key, 'itemKeyChild': random_child_key}, value_to_set=True ) self.assertTrue(update_success) retrieved_item =",
"import BaseField, MapModel, TableDataModel from tests.components.playground_table_clients import PlaygroundDynamoDBBasicTable, TEST_ACCOUNT_ID class",
"self.assertTrue(update_success) retrieved_item = self.users_table.get_field( key_value=TEST_ACCOUNT_ID, field_path='nestedDictDictStructure.{{itemKey}}', query_kwargs={'itemKey': random_parent_key} ) self.assertEqual(retrieved_item,",
"f\"parentKey_{uuid4()}\" random_child_key = f\"childKey_{uuid4()}\" keys_fields_switch = list(self.users_table.fields_switch.keys()) self.assertIn('nestedDictDictStructure.{{itemKey}}.{{itemKeyChild}}', keys_fields_switch) update_success",
"field_path='nestedDictDictStructure.{{itemKey}}', query_kwargs={'itemKey': random_parent_key} ) self.assertEqual(removed_item, {'itemKeyChild': True}) retrieved_expected_none_item = self.users_table.get_field(",
"import uuid4 from StructNoSQL import BaseField, MapModel, TableDataModel from tests.components.playground_table_clients",
"field_path='nestedDictDictStructure.{{itemKey}}', query_kwargs={'itemKey': random_parent_key} ) self.assertIsNone(retrieved_expected_none_item) def test_nested_dict_list_structure(self): # todo: implement"
] |
[
"eq(base64.b32encode('ab'), 'MFRA====') eq(base64.b32encode('abc'), 'MFRGG===') eq(base64.b32encode('abcd'), 'MFRGGZA=') eq(base64.b32encode('abcde'), 'MFRGGZDF') # Non-bytes",
"eq(base64.b16decode('00'), '\\x00') # Lower case is not allowed without a",
"\"\") eq(base64.b64encode(\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\"), \"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Test",
"Test standard alphabet eq(base64.standard_b64decode(\"d3d3LnB5dGhvbi5vcmc=\"), \"www.python.org\") eq(base64.standard_b64decode(\"YQ==\"), \"a\") eq(base64.standard_b64decode(\"YWI=\"), \"ab\") eq(base64.standard_b64decode(\"YWJj\"),",
"StringIO infp = StringIO('d3d3LnB5dGhvbi5vcmc=') outfp = StringIO() base64.decode(infp, outfp) self.assertEqual(outfp.getvalue(),",
"\"\") eq(base64.encodestring(\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\"), \"<KEY>\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\") # Non-bytes",
"eq = self.assertEqual eq(base64.decodestring(\"d3d3LnB5dGhvbi5vcmc=\\n\"), \"www.python.org\") eq(base64.decodestring(\"YQ==\\n\"), \"a\") eq(base64.decodestring(\"YWI=\\n\"), \"ab\") eq(base64.decodestring(\"YWJj\\n\"),",
"\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Test with arbitrary alternative characters eq(base64.b64encode('\\xd3V\\xbeo\\xf7\\x1d',",
"from cStringIO import StringIO infp = StringIO('abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' '0123456789!@#0^&*();:<>,. []{}')",
"self.assertEqual from cStringIO import StringIO infp = StringIO('abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' '0123456789!@#0^&*();:<>,.",
"StringIO infp = StringIO('abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' '0123456789!@#0^&*();:<>,. []{}') outfp = StringIO()",
"eq(base64.b64encode(\"abc\"), \"YWJj\") eq(base64.b64encode(\"\"), \"\") eq(base64.b64encode(\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\"), \"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\"",
"characters eq(base64.urlsafe_b64encode('\\xd3V\\xbeo\\xf7\\x1d'), '01a-b_cd') # Non-bytes eq(base64.urlsafe_b64encode(bytearray('\\xd3V\\xbeo\\xf7\\x1d')), '01a-b_cd') def test_b64decode(self): eq",
"eq(base64.b64decode(\"d3d3LnB5dGhvbi5vcmc=\"), \"www.python.org\") eq(base64.b64decode('AA=='), '\\x00') eq(base64.b64decode(\"YQ==\"), \"a\") eq(base64.b64decode(\"YWI=\"), \"ab\") eq(base64.b64decode(\"YWJj\"), \"abc\")",
"eq = self.assertEqual eq(base64.b32decode('', True), '') eq(base64.b32decode('ME======', True), 'a') eq(base64.b32decode('MFRA====',",
"self.assertEqual eq(base64.b32decode(''), '') eq(base64.b32decode('AA======'), '\\x00') eq(base64.b32decode('ME======'), 'a') eq(base64.b32decode('MFRA===='), 'ab') eq(base64.b32decode('MFRGG==='),",
"Non-bytes eq(base64.b32encode(bytearray('abcd')), 'MFRGGZA=') def test_b32decode(self): eq = self.assertEqual eq(base64.b32decode(''), '')",
"Non-bytes eq(base64.standard_b64decode(bytearray(\"YWJj\")), \"abc\") # Test with 'URL safe' alternative characters",
"\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\") # Non-bytes eq(base64.encodestring(bytearray('abc')), 'YWJj\\n') def test_decodestring(self): eq = self.assertEqual",
"# Lower case is not allowed without a flag self.assertRaises(TypeError,",
"eq(base64.b16encode('\\x01\\x02\\xab\\xcd\\xef'), '0102ABCDEF') eq(base64.b16encode('\\x00'), '00') # Non-bytes eq(base64.b16encode(bytearray('\\x01\\x02\\xab\\xcd\\xef')), '0102ABCDEF') def test_b16decode(self):",
"eq(base64.b32decode('MFRA====', True), 'ab') eq(base64.b32decode('MFRGG===', True), 'abc') eq(base64.b32decode('MFRGGZA=', True), 'abcd') eq(base64.b32decode('MFRGGZDF',",
"'') eq(base64.b32decode('AA======'), '\\x00') eq(base64.b32decode('ME======'), 'a') eq(base64.b32decode('MFRA===='), 'ab') eq(base64.b32decode('MFRGG==='), 'abc') eq(base64.b32decode('MFRGGZA='),",
"eq(base64.standard_b64encode(\"\"), \"\") eq(base64.standard_b64encode(\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\"), \"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") #",
"with arbitrary alternative characters eq(base64.b64encode('\\xd3V\\xbeo\\xf7\\x1d', altchars='*$'), '01a*b$cd') # Non-bytes eq(base64.b64encode(bytearray('abcd')),",
"base64.b16decode, '0102abcdef') # Case fold eq(base64.b16decode('0102abcdef', True), '\\x01\\x02\\xab\\xcd\\xef') # Non-bytes",
"eq(base64.standard_b64encode(\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\"), \"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Non-bytes eq(base64.standard_b64encode(bytearray('abcd')),",
"Non-bytes eq(base64.b16decode(bytearray(\"0102ABCDEF\")), '\\x01\\x02\\xab\\xcd\\xef') def test_main(): test_support.run_unittest(__name__) if __name__ == '__main__':",
"'YWJjZA==') self.assertRaises(TypeError, base64.b64encode, '\\xd3V\\xbeo\\xf7\\x1d', altchars=bytearray('*$')) # Test standard alphabet eq(base64.standard_b64encode(\"www.python.org\"),",
"class LegacyBase64TestCase(unittest.TestCase): def test_encodestring(self): eq = self.assertEqual eq(base64.encodestring(\"www.python.org\"), \"d3d3LnB5dGhvbi5vcmc=\\n\") eq(base64.encodestring(\"a\"),",
"arbitrary alternative characters eq(base64.b64encode('\\xd3V\\xbeo\\xf7\\x1d', altchars='*$'), '01a*b$cd') # Non-bytes eq(base64.b64encode(bytearray('abcd')), 'YWJjZA==')",
"exceptions self.assertRaises(TypeError, base64.b32decode, 'me======') # Mapping zero and one eq(base64.b32decode('MLO23456'),",
"\"www.python.org\") eq(base64.decodestring(\"YQ==\\n\"), \"a\") eq(base64.decodestring(\"YWI=\\n\"), \"ab\") eq(base64.decodestring(\"YWJj\\n\"), \"abc\") eq(base64.decodestring(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\"),",
"def test_b32decode_casefold(self): eq = self.assertEqual eq(base64.b32decode('', True), '') eq(base64.b32decode('ME======', True),",
"and one eq(base64.b32decode('MLO23456'), 'b\\xdd\\xad\\xf3\\xbe') eq(base64.b32decode('M1023456', map01='L'), 'b\\xdd\\xad\\xf3\\xbe') eq(base64.b32decode('M1023456', map01='I'), 'b\\x1d\\xad\\xf3\\xbe')",
"test import test_support import base64 class LegacyBase64TestCase(unittest.TestCase): def test_encodestring(self): eq",
"\"abc\") eq(base64.b64decode(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\"), \"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\") eq(base64.b64decode(''), '')",
"\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\"), \"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\") eq(base64.b64decode(''), '') # Test with",
"# Test standard alphabet eq(base64.standard_b64decode(\"d3d3LnB5dGhvbi5vcmc=\"), \"www.python.org\") eq(base64.standard_b64decode(\"YQ==\"), \"a\") eq(base64.standard_b64decode(\"YWI=\"), \"ab\")",
"eq(base64.b16encode(bytearray('\\x01\\x02\\xab\\xcd\\xef')), '0102ABCDEF') def test_b16decode(self): eq = self.assertEqual eq(base64.b16decode('0102ABCDEF'), '\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode('00'),",
"# Test with 'URL safe' alternative characters eq(base64.urlsafe_b64decode('01a-b_cd'), '\\xd3V\\xbeo\\xf7\\x1d') #",
"eq(base64.b64encode(\"ab\"), \"YWI=\") eq(base64.b64encode(\"abc\"), \"YWJj\") eq(base64.b64encode(\"\"), \"\") eq(base64.b64encode(\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\"),",
"'') eq(base64.b32encode('\\x00'), 'AA======') eq(base64.b32encode('a'), 'ME======') eq(base64.b32encode('ab'), 'MFRA====') eq(base64.b32encode('abc'), 'MFRGG===') eq(base64.b32encode('abcd'),",
"\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Non-bytes eq(base64.standard_b64encode(bytearray('abcd')), 'YWJjZA==') # Test with 'URL safe'",
"eq(base64.b32decode('MFRGGZA=', True), 'abcd') eq(base64.b32decode('MFRGGZDF', True), 'abcde') # Lower cases eq(base64.b32decode('me======',",
"def test_b64decode_error(self): self.assertRaises(TypeError, base64.b64decode, 'abc') def test_b32encode(self): eq = self.assertEqual",
"eq(base64.b16decode('0102abcdef', True), '\\x01\\x02\\xab\\xcd\\xef') # Non-bytes eq(base64.b16decode(bytearray(\"0102ABCDEF\")), '\\x01\\x02\\xab\\xcd\\xef') def test_main(): test_support.run_unittest(__name__)",
"base64.b64decode, 'abc') def test_b32encode(self): eq = self.assertEqual eq(base64.b32encode(''), '') eq(base64.b32encode('\\x00'),",
"base64.b64encode, '\\xd3V\\xbeo\\xf7\\x1d', altchars=bytearray('*$')) # Test standard alphabet eq(base64.standard_b64encode(\"www.python.org\"), \"d3d3LnB5dGhvbi5vcmc=\") eq(base64.standard_b64encode(\"a\"),",
"default alphabet eq(base64.b64encode(\"www.python.org\"), \"d3d3LnB5dGhvbi5vcmc=\") eq(base64.b64encode('\\x00'), 'AA==') eq(base64.b64encode(\"a\"), \"YQ==\") eq(base64.b64encode(\"ab\"), \"YWI=\")",
"eq(base64.b64decode(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\"), \"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\") eq(base64.b64decode(''), '') #",
"eq(base64.b32encode('abcde'), 'MFRGGZDF') # Non-bytes eq(base64.b32encode(bytearray('abcd')), 'MFRGGZA=') def test_b32decode(self): eq =",
"# Test default alphabet eq(base64.b64encode(\"www.python.org\"), \"d3d3LnB5dGhvbi5vcmc=\") eq(base64.b64encode('\\x00'), 'AA==') eq(base64.b64encode(\"a\"), \"YQ==\")",
"Non-bytes eq(base64.standard_b64encode(bytearray('abcd')), 'YWJjZA==') # Test with 'URL safe' alternative characters",
"self.assertEqual eq(base64.b32encode(''), '') eq(base64.b32encode('\\x00'), 'AA======') eq(base64.b32encode('a'), 'ME======') eq(base64.b32encode('ab'), 'MFRA====') eq(base64.b32encode('abc'),",
"def test_decodestring(self): eq = self.assertEqual eq(base64.decodestring(\"d3d3LnB5dGhvbi5vcmc=\\n\"), \"www.python.org\") eq(base64.decodestring(\"YQ==\\n\"), \"a\") eq(base64.decodestring(\"YWI=\\n\"),",
"Test with 'URL safe' alternative characters eq(base64.urlsafe_b64encode('\\xd3V\\xbeo\\xf7\\x1d'), '01a-b_cd') # Non-bytes",
"Non-bytes eq(base64.decodestring(bytearray(\"YWJj\\n\")), \"abc\") def test_encode(self): eq = self.assertEqual from cStringIO",
"\"d3d3LnB5dGhvbi5vcmc=\\n\") eq(base64.encodestring(\"a\"), \"YQ==\\n\") eq(base64.encodestring(\"ab\"), \"YWI=\\n\") eq(base64.encodestring(\"abc\"), \"YWJj\\n\") eq(base64.encodestring(\"\"), \"\") eq(base64.encodestring(\"abcdefghijklmnopqrstuvwxyz\"",
"'AA======') eq(base64.b32encode('a'), 'ME======') eq(base64.b32encode('ab'), 'MFRA====') eq(base64.b32encode('abc'), 'MFRGG===') eq(base64.b32encode('abcd'), 'MFRGGZA=') eq(base64.b32encode('abcde'),",
"eq(base64.b32decode('mfrggza=', True), 'abcd') eq(base64.b32decode('mfrggzdf', True), 'abcde') # Expected exceptions self.assertRaises(TypeError,",
"eq(base64.b32decode('MFRGGZDF', True), 'abcde') # Lower cases eq(base64.b32decode('me======', True), 'a') eq(base64.b32decode('mfra====',",
"def test_b32encode(self): eq = self.assertEqual eq(base64.b32encode(''), '') eq(base64.b32encode('\\x00'), 'AA======') eq(base64.b32encode('a'),",
"\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\"), \"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\") # Non-bytes eq(base64.standard_b64decode(bytearray(\"YWJj\")), \"abc\")",
"eq(base64.b64encode(\"\"), \"\") eq(base64.b64encode(\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\"), \"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") #",
"altchars='*$'), '01a*b$cd') # Non-bytes eq(base64.b64encode(bytearray('abcd')), 'YWJjZA==') self.assertRaises(TypeError, base64.b64encode, '\\xd3V\\xbeo\\xf7\\x1d', altchars=bytearray('*$'))",
"\"abc\") eq(base64.decodestring(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\"), \"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\") eq(base64.decodestring(''), '')",
"base64.decode(infp, outfp) self.assertEqual(outfp.getvalue(), 'www.python.org') class BaseXYTestCase(unittest.TestCase): def test_b64encode(self): eq =",
"cases eq(base64.b32decode('me======', True), 'a') eq(base64.b32decode('mfra====', True), 'ab') eq(base64.b32decode('mfrgg===', True), 'abc')",
"eq(base64.b64decode('01a*b$cd', altchars='*$'), '\\xd3V\\xbeo\\xf7\\x1d') # Non-bytes eq(base64.b64decode(bytearray(\"YWJj\")), \"abc\") # Test standard",
"eq = self.assertEqual eq(base64.b64decode(\"d3d3LnB5dGhvbi5vcmc=\"), \"www.python.org\") eq(base64.b64decode('AA=='), '\\x00') eq(base64.b64decode(\"YQ==\"), \"a\") eq(base64.b64decode(\"YWI=\"),",
"\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\") eq(base64.b64decode(''), '') # Test with arbitrary alternative",
"eq(base64.b32decode('MLO23456'), 'b\\xdd\\xad\\xf3\\xbe') eq(base64.b32decode('M1023456', map01='L'), 'b\\xdd\\xad\\xf3\\xbe') eq(base64.b32decode('M1023456', map01='I'), 'b\\x1d\\xad\\xf3\\xbe') def test_b32decode_error(self):",
"self.assertRaises(TypeError, base64.b32decode, 'me======') # Mapping zero and one eq(base64.b32decode('MLO23456'), 'b\\xdd\\xad\\xf3\\xbe')",
"'01a-b_cd') # Non-bytes eq(base64.urlsafe_b64encode(bytearray('\\xd3V\\xbeo\\xf7\\x1d')), '01a-b_cd') def test_b64decode(self): eq = self.assertEqual",
"# Non-bytes eq(base64.b16decode(bytearray(\"0102ABCDEF\")), '\\x01\\x02\\xab\\xcd\\xef') def test_main(): test_support.run_unittest(__name__) if __name__ ==",
"def test_encodestring(self): eq = self.assertEqual eq(base64.encodestring(\"www.python.org\"), \"d3d3LnB5dGhvbi5vcmc=\\n\") eq(base64.encodestring(\"a\"), \"YQ==\\n\") eq(base64.encodestring(\"ab\"),",
"alternative characters eq(base64.urlsafe_b64encode('\\xd3V\\xbeo\\xf7\\x1d'), '01a-b_cd') # Non-bytes eq(base64.urlsafe_b64encode(bytearray('\\xd3V\\xbeo\\xf7\\x1d')), '01a-b_cd') def test_b64decode(self):",
"eq = self.assertEqual eq(base64.b32encode(''), '') eq(base64.b32encode('\\x00'), 'AA======') eq(base64.b32encode('a'), 'ME======') eq(base64.b32encode('ab'),",
"# Mapping zero and one eq(base64.b32decode('MLO23456'), 'b\\xdd\\xad\\xf3\\xbe') eq(base64.b32decode('M1023456', map01='L'), 'b\\xdd\\xad\\xf3\\xbe')",
"fold eq(base64.b16decode('0102abcdef', True), '\\x01\\x02\\xab\\xcd\\xef') # Non-bytes eq(base64.b16decode(bytearray(\"0102ABCDEF\")), '\\x01\\x02\\xab\\xcd\\xef') def test_main():",
"= self.assertEqual from cStringIO import StringIO infp = StringIO('abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'",
"\"a\") eq(base64.standard_b64decode(\"YWI=\"), \"ab\") eq(base64.standard_b64decode(\"YWJj\"), \"abc\") eq(base64.standard_b64decode(\"\"), \"\") eq(base64.standard_b64decode(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\"),",
"Mapping zero and one eq(base64.b32decode('MLO23456'), 'b\\xdd\\xad\\xf3\\xbe') eq(base64.b32decode('M1023456', map01='L'), 'b\\xdd\\xad\\xf3\\xbe') eq(base64.b32decode('M1023456',",
"Lower cases eq(base64.b32decode('me======', True), 'a') eq(base64.b32decode('mfra====', True), 'ab') eq(base64.b32decode('mfrgg===', True),",
"base64.b32decode, bytearray('MFRGG===')) def test_b32decode_casefold(self): eq = self.assertEqual eq(base64.b32decode('', True), '')",
"# Test standard alphabet eq(base64.standard_b64encode(\"www.python.org\"), \"d3d3LnB5dGhvbi5vcmc=\") eq(base64.standard_b64encode(\"a\"), \"YQ==\") eq(base64.standard_b64encode(\"ab\"), \"YWI=\")",
"eq(base64.b16decode('0102ABCDEF'), '\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode('00'), '\\x00') # Lower case is not allowed",
"eq(base64.b32decode('MFRA===='), 'ab') eq(base64.b32decode('MFRGG==='), 'abc') eq(base64.b32decode('MFRGGZA='), 'abcd') eq(base64.b32decode('MFRGGZDF'), 'abcde') # Non-bytes",
"# Non-bytes eq(base64.b32encode(bytearray('abcd')), 'MFRGGZA=') def test_b32decode(self): eq = self.assertEqual eq(base64.b32decode(''),",
"eq(base64.encodestring(\"abc\"), \"YWJj\\n\") eq(base64.encodestring(\"\"), \"\") eq(base64.encodestring(\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\"), \"<KEY>\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\"",
"eq(base64.decodestring(\"YQ==\\n\"), \"a\") eq(base64.decodestring(\"YWI=\\n\"), \"ab\") eq(base64.decodestring(\"YWJj\\n\"), \"abc\") eq(base64.decodestring(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\"), \"abcdefghijklmnopqrstuvwxyz\"",
"Test standard alphabet eq(base64.standard_b64encode(\"www.python.org\"), \"d3d3LnB5dGhvbi5vcmc=\") eq(base64.standard_b64encode(\"a\"), \"YQ==\") eq(base64.standard_b64encode(\"ab\"), \"YWI=\") eq(base64.standard_b64encode(\"abc\"),",
"map01='I'), 'b\\x1d\\xad\\xf3\\xbe') def test_b32decode_error(self): self.assertRaises(TypeError, base64.b32decode, 'abc') self.assertRaises(TypeError, base64.b32decode, 'ABCDEF==')",
"'00') # Non-bytes eq(base64.b16encode(bytearray('\\x01\\x02\\xab\\xcd\\xef')), '0102ABCDEF') def test_b16decode(self): eq = self.assertEqual",
"eq(base64.decodestring(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\"), \"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\") eq(base64.decodestring(''), '') #",
"eq(base64.b32decode('MFRGGZA='), 'abcd') eq(base64.b32decode('MFRGGZDF'), 'abcde') # Non-bytes self.assertRaises(TypeError, base64.b32decode, bytearray('MFRGG===')) def",
"\"0123456789!@#0^&*();:<>,. []{}\") eq(base64.b64decode(''), '') # Test with arbitrary alternative characters",
"arbitrary alternative characters eq(base64.b64decode('01a*b$cd', altchars='*$'), '\\xd3V\\xbeo\\xf7\\x1d') # Non-bytes eq(base64.b64decode(bytearray(\"YWJj\")), \"abc\")",
"Non-bytes eq(base64.encodestring(bytearray('abc')), 'YWJj\\n') def test_decodestring(self): eq = self.assertEqual eq(base64.decodestring(\"d3d3LnB5dGhvbi5vcmc=\\n\"), \"www.python.org\")",
"eq = self.assertEqual eq(base64.b16encode('\\x01\\x02\\xab\\xcd\\xef'), '0102ABCDEF') eq(base64.b16encode('\\x00'), '00') # Non-bytes eq(base64.b16encode(bytearray('\\x01\\x02\\xab\\xcd\\xef')),",
"self.assertRaises(TypeError, base64.b16decode, '0102abcdef') # Case fold eq(base64.b16decode('0102abcdef', True), '\\x01\\x02\\xab\\xcd\\xef') #",
"StringIO('abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' '0123456789!@#0^&*();:<>,. []{}') outfp = StringIO() base64.encode(infp, outfp) eq(outfp.getvalue(),",
"self.assertEqual eq(base64.b32decode('', True), '') eq(base64.b32decode('ME======', True), 'a') eq(base64.b32decode('MFRA====', True), 'ab')",
"\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\"), \"<KEY>\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\") # Non-bytes eq(base64.encodestring(bytearray('abc')), 'YWJj\\n')",
"eq = self.assertEqual eq(base64.encodestring(\"www.python.org\"), \"d3d3LnB5dGhvbi5vcmc=\\n\") eq(base64.encodestring(\"a\"), \"YQ==\\n\") eq(base64.encodestring(\"ab\"), \"YWI=\\n\") eq(base64.encodestring(\"abc\"),",
"'MFRGGZA=') def test_b32decode(self): eq = self.assertEqual eq(base64.b32decode(''), '') eq(base64.b32decode('AA======'), '\\x00')",
"'abcde') # Expected exceptions self.assertRaises(TypeError, base64.b32decode, 'me======') # Mapping zero",
"infp = StringIO('d3d3LnB5dGhvbi5vcmc=') outfp = StringIO() base64.decode(infp, outfp) self.assertEqual(outfp.getvalue(), 'www.python.org')",
"True), 'a') eq(base64.b32decode('MFRA====', True), 'ab') eq(base64.b32decode('MFRGG===', True), 'abc') eq(base64.b32decode('MFRGGZA=', True),",
"eq(base64.b32decode('me======', True), 'a') eq(base64.b32decode('mfra====', True), 'ab') eq(base64.b32decode('mfrgg===', True), 'abc') eq(base64.b32decode('mfrggza=',",
"with 'URL safe' alternative characters eq(base64.urlsafe_b64decode('01a-b_cd'), '\\xd3V\\xbeo\\xf7\\x1d') # Non-bytes eq(base64.urlsafe_b64decode(bytearray('01a-b_cd')),",
"\"a\") eq(base64.decodestring(\"YWI=\\n\"), \"ab\") eq(base64.decodestring(\"YWJj\\n\"), \"abc\") eq(base64.decodestring(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\"), \"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"",
"self.assertEqual eq(base64.b16decode('0102ABCDEF'), '\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode('00'), '\\x00') # Lower case is not",
"StringIO('d3d3LnB5dGhvbi5vcmc=') outfp = StringIO() base64.decode(infp, outfp) self.assertEqual(outfp.getvalue(), 'www.python.org') class BaseXYTestCase(unittest.TestCase):",
"'ABCDEFGHIJKLMNOPQRSTUVWXYZ' '0123456789!@#0^&*();:<>,. []{}') outfp = StringIO() base64.encode(infp, outfp) eq(outfp.getvalue(), 'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE'",
"zero and one eq(base64.b32decode('MLO23456'), 'b\\xdd\\xad\\xf3\\xbe') eq(base64.b32decode('M1023456', map01='L'), 'b\\xdd\\xad\\xf3\\xbe') eq(base64.b32decode('M1023456', map01='I'),",
"cStringIO import StringIO infp = StringIO('abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' '0123456789!@#0^&*();:<>,. []{}') outfp",
"\"d3d3LnB5dGhvbi5vcmc=\") eq(base64.standard_b64encode(\"a\"), \"YQ==\") eq(base64.standard_b64encode(\"ab\"), \"YWI=\") eq(base64.standard_b64encode(\"abc\"), \"YWJj\") eq(base64.standard_b64encode(\"\"), \"\") eq(base64.standard_b64encode(\"abcdefghijklmnopqrstuvwxyz\"",
"flag self.assertRaises(TypeError, base64.b16decode, '0102abcdef') # Case fold eq(base64.b16decode('0102abcdef', True), '\\x01\\x02\\xab\\xcd\\xef')",
"= StringIO('d3d3LnB5dGhvbi5vcmc=') outfp = StringIO() base64.decode(infp, outfp) self.assertEqual(outfp.getvalue(), 'www.python.org') class",
"eq(base64.b64encode(\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\"), \"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Test with",
"\"YQ==\\n\") eq(base64.encodestring(\"ab\"), \"YWI=\\n\") eq(base64.encodestring(\"abc\"), \"YWJj\\n\") eq(base64.encodestring(\"\"), \"\") eq(base64.encodestring(\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,.",
"'\\x00') # Lower case is not allowed without a flag",
"test_b16encode(self): eq = self.assertEqual eq(base64.b16encode('\\x01\\x02\\xab\\xcd\\xef'), '0102ABCDEF') eq(base64.b16encode('\\x00'), '00') # Non-bytes",
"eq(base64.urlsafe_b64decode('01a-b_cd'), '\\xd3V\\xbeo\\xf7\\x1d') # Non-bytes eq(base64.urlsafe_b64decode(bytearray('01a-b_cd')), '\\xd3V\\xbeo\\xf7\\x1d') def test_b64decode_error(self): self.assertRaises(TypeError, base64.b64decode,",
"eq = self.assertEqual # Test default alphabet eq(base64.b64encode(\"www.python.org\"), \"d3d3LnB5dGhvbi5vcmc=\") eq(base64.b64encode('\\x00'),",
"eq = self.assertEqual eq(base64.b16decode('0102ABCDEF'), '\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode('00'), '\\x00') # Lower case",
"True), 'ab') eq(base64.b32decode('mfrgg===', True), 'abc') eq(base64.b32decode('mfrggza=', True), 'abcd') eq(base64.b32decode('mfrggzdf', True),",
"test_encodestring(self): eq = self.assertEqual eq(base64.encodestring(\"www.python.org\"), \"d3d3LnB5dGhvbi5vcmc=\\n\") eq(base64.encodestring(\"a\"), \"YQ==\\n\") eq(base64.encodestring(\"ab\"), \"YWI=\\n\")",
"eq(base64.b32decode('AA======'), '\\x00') eq(base64.b32decode('ME======'), 'a') eq(base64.b32decode('MFRA===='), 'ab') eq(base64.b32decode('MFRGG==='), 'abc') eq(base64.b32decode('MFRGGZA='), 'abcd')",
"\"abc\") def test_encode(self): eq = self.assertEqual from cStringIO import StringIO",
"\"\") eq(base64.standard_b64decode(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\"), \"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\") # Non-bytes",
"\"www.python.org\") eq(base64.b64decode('AA=='), '\\x00') eq(base64.b64decode(\"YQ==\"), \"a\") eq(base64.b64decode(\"YWI=\"), \"ab\") eq(base64.b64decode(\"YWJj\"), \"abc\") eq(base64.b64decode(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\"",
"# Non-bytes eq(base64.b16encode(bytearray('\\x01\\x02\\xab\\xcd\\xef')), '0102ABCDEF') def test_b16decode(self): eq = self.assertEqual eq(base64.b16decode('0102ABCDEF'),",
"self.assertRaises(TypeError, base64.b32decode, 'ABCDEF==') def test_b16encode(self): eq = self.assertEqual eq(base64.b16encode('\\x01\\x02\\xab\\xcd\\xef'), '0102ABCDEF')",
"eq(base64.standard_b64decode(bytearray(\"YWJj\")), \"abc\") # Test with 'URL safe' alternative characters eq(base64.urlsafe_b64decode('01a-b_cd'),",
"import base64 class LegacyBase64TestCase(unittest.TestCase): def test_encodestring(self): eq = self.assertEqual eq(base64.encodestring(\"www.python.org\"),",
"True), 'ab') eq(base64.b32decode('MFRGG===', True), 'abc') eq(base64.b32decode('MFRGGZA=', True), 'abcd') eq(base64.b32decode('MFRGGZDF', True),",
"alternative characters eq(base64.b64encode('\\xd3V\\xbeo\\xf7\\x1d', altchars='*$'), '01a*b$cd') # Non-bytes eq(base64.b64encode(bytearray('abcd')), 'YWJjZA==') self.assertRaises(TypeError,",
"'abc') self.assertRaises(TypeError, base64.b32decode, 'ABCDEF==') def test_b16encode(self): eq = self.assertEqual eq(base64.b16encode('\\x01\\x02\\xab\\xcd\\xef'),",
"eq(base64.b32decode('ME======', True), 'a') eq(base64.b32decode('MFRA====', True), 'ab') eq(base64.b32decode('MFRGG===', True), 'abc') eq(base64.b32decode('MFRGGZA=',",
"self.assertRaises(TypeError, base64.b32decode, 'abc') self.assertRaises(TypeError, base64.b32decode, 'ABCDEF==') def test_b16encode(self): eq =",
"# Test with 'URL safe' alternative characters eq(base64.urlsafe_b64encode('\\xd3V\\xbeo\\xf7\\x1d'), '01a-b_cd') #",
"[]{}\") eq(base64.decodestring(''), '') # Non-bytes eq(base64.decodestring(bytearray(\"YWJj\\n\")), \"abc\") def test_encode(self): eq",
"def test_b64decode(self): eq = self.assertEqual eq(base64.b64decode(\"d3d3LnB5dGhvbi5vcmc=\"), \"www.python.org\") eq(base64.b64decode('AA=='), '\\x00') eq(base64.b64decode(\"YQ==\"),",
"Non-bytes eq(base64.b64decode(bytearray(\"YWJj\")), \"abc\") # Test standard alphabet eq(base64.standard_b64decode(\"d3d3LnB5dGhvbi5vcmc=\"), \"www.python.org\") eq(base64.standard_b64decode(\"YQ==\"),",
"Non-bytes self.assertRaises(TypeError, base64.b32decode, bytearray('MFRGG===')) def test_b32decode_casefold(self): eq = self.assertEqual eq(base64.b32decode('',",
"Lower case is not allowed without a flag self.assertRaises(TypeError, base64.b16decode,",
"unittest from test import test_support import base64 class LegacyBase64TestCase(unittest.TestCase): def",
"eq(base64.b64encode('\\xd3V\\xbeo\\xf7\\x1d', altchars='*$'), '01a*b$cd') # Non-bytes eq(base64.b64encode(bytearray('abcd')), 'YWJjZA==') self.assertRaises(TypeError, base64.b64encode, '\\xd3V\\xbeo\\xf7\\x1d',",
"import StringIO infp = StringIO('d3d3LnB5dGhvbi5vcmc=') outfp = StringIO() base64.decode(infp, outfp)",
"'abcde') # Lower cases eq(base64.b32decode('me======', True), 'a') eq(base64.b32decode('mfra====', True), 'ab')",
"\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\"), \"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\") # Non-bytes eq(base64.standard_b64decode(bytearray(\"YWJj\")), \"abc\") #",
"\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\") eq(base64.decodestring(''), '') # Non-bytes eq(base64.decodestring(bytearray(\"YWJj\\n\")), \"abc\") def",
"\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\") eq(base64.b64decode(''), '') # Test with arbitrary",
"[]{}\") eq(base64.b64decode(''), '') # Test with arbitrary alternative characters eq(base64.b64decode('01a*b$cd',",
"[]{}\"), \"<KEY>\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\") # Non-bytes eq(base64.encodestring(bytearray('abc')), 'YWJj\\n') def test_decodestring(self):",
"\"ab\") eq(base64.b64decode(\"YWJj\"), \"abc\") eq(base64.b64decode(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\"), \"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\")",
"alphabet eq(base64.standard_b64decode(\"d3d3LnB5dGhvbi5vcmc=\"), \"www.python.org\") eq(base64.standard_b64decode(\"YQ==\"), \"a\") eq(base64.standard_b64decode(\"YWI=\"), \"ab\") eq(base64.standard_b64decode(\"YWJj\"), \"abc\") eq(base64.standard_b64decode(\"\"),",
"'\\xd3V\\xbeo\\xf7\\x1d') def test_b64decode_error(self): self.assertRaises(TypeError, base64.b64decode, 'abc') def test_b32encode(self): eq =",
"'b\\xdd\\xad\\xf3\\xbe') eq(base64.b32decode('M1023456', map01='I'), 'b\\x1d\\xad\\xf3\\xbe') def test_b32decode_error(self): self.assertRaises(TypeError, base64.b32decode, 'abc') self.assertRaises(TypeError,",
"eq(base64.encodestring(\"\"), \"\") eq(base64.encodestring(\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\"), \"<KEY>\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\") #",
"'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n') def test_decode(self): from cStringIO import StringIO infp = StringIO('d3d3LnB5dGhvbi5vcmc=')",
"'abcde') # Non-bytes self.assertRaises(TypeError, base64.b32decode, bytearray('MFRGG===')) def test_b32decode_casefold(self): eq =",
"cStringIO import StringIO infp = StringIO('d3d3LnB5dGhvbi5vcmc=') outfp = StringIO() base64.decode(infp,",
"eq(base64.encodestring(\"a\"), \"YQ==\\n\") eq(base64.encodestring(\"ab\"), \"YWI=\\n\") eq(base64.encodestring(\"abc\"), \"YWJj\\n\") eq(base64.encodestring(\"\"), \"\") eq(base64.encodestring(\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"",
"eq(base64.b64decode(\"YWI=\"), \"ab\") eq(base64.b64decode(\"YWJj\"), \"abc\") eq(base64.b64decode(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\"), \"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,.",
"'\\x00') eq(base64.b64decode(\"YQ==\"), \"a\") eq(base64.b64decode(\"YWI=\"), \"ab\") eq(base64.b64decode(\"YWJj\"), \"abc\") eq(base64.b64decode(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\"),",
"'a') eq(base64.b32decode('mfra====', True), 'ab') eq(base64.b32decode('mfrgg===', True), 'abc') eq(base64.b32decode('mfrggza=', True), 'abcd')",
"self.assertRaises(TypeError, base64.b32decode, bytearray('MFRGG===')) def test_b32decode_casefold(self): eq = self.assertEqual eq(base64.b32decode('', True),",
"is not allowed without a flag self.assertRaises(TypeError, base64.b16decode, '0102abcdef') #",
"test_decodestring(self): eq = self.assertEqual eq(base64.decodestring(\"d3d3LnB5dGhvbi5vcmc=\\n\"), \"www.python.org\") eq(base64.decodestring(\"YQ==\\n\"), \"a\") eq(base64.decodestring(\"YWI=\\n\"), \"ab\")",
"import unittest from test import test_support import base64 class LegacyBase64TestCase(unittest.TestCase):",
"eq(outfp.getvalue(), 'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE' 'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT' 'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n') def test_decode(self): from cStringIO import StringIO",
"'www.python.org') class BaseXYTestCase(unittest.TestCase): def test_b64encode(self): eq = self.assertEqual # Test",
"\"YWI=\") eq(base64.b64encode(\"abc\"), \"YWJj\") eq(base64.b64encode(\"\"), \"\") eq(base64.b64encode(\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\"), \"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\"",
"characters eq(base64.urlsafe_b64decode('01a-b_cd'), '\\xd3V\\xbeo\\xf7\\x1d') # Non-bytes eq(base64.urlsafe_b64decode(bytearray('01a-b_cd')), '\\xd3V\\xbeo\\xf7\\x1d') def test_b64decode_error(self): self.assertRaises(TypeError,",
"self.assertEqual eq(base64.encodestring(\"www.python.org\"), \"d3d3LnB5dGhvbi5vcmc=\\n\") eq(base64.encodestring(\"a\"), \"YQ==\\n\") eq(base64.encodestring(\"ab\"), \"YWI=\\n\") eq(base64.encodestring(\"abc\"), \"YWJj\\n\") eq(base64.encodestring(\"\"),",
"import StringIO infp = StringIO('abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' '0123456789!@#0^&*();:<>,. []{}') outfp =",
"eq(base64.b64decode(''), '') # Test with arbitrary alternative characters eq(base64.b64decode('01a*b$cd', altchars='*$'),",
"\"0123456789!@#0^&*();:<>,. []{}\"), \"<KEY>\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\") # Non-bytes eq(base64.encodestring(bytearray('abc')), 'YWJj\\n') def",
"\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\"), \"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Test with arbitrary",
"\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\"), \"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Non-bytes eq(base64.standard_b64encode(bytearray('abcd')), 'YWJjZA==')",
"\"YQ==\") eq(base64.standard_b64encode(\"ab\"), \"YWI=\") eq(base64.standard_b64encode(\"abc\"), \"YWJj\") eq(base64.standard_b64encode(\"\"), \"\") eq(base64.standard_b64encode(\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,.",
"eq(base64.b64encode(bytearray('abcd')), 'YWJjZA==') self.assertRaises(TypeError, base64.b64encode, '\\xd3V\\xbeo\\xf7\\x1d', altchars=bytearray('*$')) # Test standard alphabet",
"eq(base64.encodestring(\"www.python.org\"), \"d3d3LnB5dGhvbi5vcmc=\\n\") eq(base64.encodestring(\"a\"), \"YQ==\\n\") eq(base64.encodestring(\"ab\"), \"YWI=\\n\") eq(base64.encodestring(\"abc\"), \"YWJj\\n\") eq(base64.encodestring(\"\"), \"\")",
"# Test with arbitrary alternative characters eq(base64.b64decode('01a*b$cd', altchars='*$'), '\\xd3V\\xbeo\\xf7\\x1d') #",
"'abc') eq(base64.b32decode('mfrggza=', True), 'abcd') eq(base64.b32decode('mfrggzdf', True), 'abcde') # Expected exceptions",
"= self.assertEqual # Test default alphabet eq(base64.b64encode(\"www.python.org\"), \"d3d3LnB5dGhvbi5vcmc=\") eq(base64.b64encode('\\x00'), 'AA==')",
"= self.assertEqual eq(base64.b32decode('', True), '') eq(base64.b32decode('ME======', True), 'a') eq(base64.b32decode('MFRA====', True),",
"eq(base64.b32decode('mfrggzdf', True), 'abcde') # Expected exceptions self.assertRaises(TypeError, base64.b32decode, 'me======') #",
"eq(base64.encodestring(\"ab\"), \"YWI=\\n\") eq(base64.encodestring(\"abc\"), \"YWJj\\n\") eq(base64.encodestring(\"\"), \"\") eq(base64.encodestring(\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\"),",
"eq(base64.b32decode('mfrgg===', True), 'abc') eq(base64.b32decode('mfrggza=', True), 'abcd') eq(base64.b32decode('mfrggzdf', True), 'abcde') #",
"def test_b32decode(self): eq = self.assertEqual eq(base64.b32decode(''), '') eq(base64.b32decode('AA======'), '\\x00') eq(base64.b32decode('ME======'),",
"# Non-bytes self.assertRaises(TypeError, base64.b32decode, bytearray('MFRGG===')) def test_b32decode_casefold(self): eq = self.assertEqual",
"'b\\x1d\\xad\\xf3\\xbe') def test_b32decode_error(self): self.assertRaises(TypeError, base64.b32decode, 'abc') self.assertRaises(TypeError, base64.b32decode, 'ABCDEF==') def",
"'ME======') eq(base64.b32encode('ab'), 'MFRA====') eq(base64.b32encode('abc'), 'MFRGG===') eq(base64.b32encode('abcd'), 'MFRGGZA=') eq(base64.b32encode('abcde'), 'MFRGGZDF') #",
"\"www.python.org\") eq(base64.standard_b64decode(\"YQ==\"), \"a\") eq(base64.standard_b64decode(\"YWI=\"), \"ab\") eq(base64.standard_b64decode(\"YWJj\"), \"abc\") eq(base64.standard_b64decode(\"\"), \"\") eq(base64.standard_b64decode(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\"",
"'0123456789!@#0^&*();:<>,. []{}') outfp = StringIO() base64.encode(infp, outfp) eq(outfp.getvalue(), 'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE' 'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT'",
"LegacyBase64TestCase(unittest.TestCase): def test_encodestring(self): eq = self.assertEqual eq(base64.encodestring(\"www.python.org\"), \"d3d3LnB5dGhvbi5vcmc=\\n\") eq(base64.encodestring(\"a\"), \"YQ==\\n\")",
"def test_b64encode(self): eq = self.assertEqual # Test default alphabet eq(base64.b64encode(\"www.python.org\"),",
"\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\") # Non-bytes eq(base64.standard_b64decode(bytearray(\"YWJj\")), \"abc\") # Test with",
"'\\x00') eq(base64.b32decode('ME======'), 'a') eq(base64.b32decode('MFRA===='), 'ab') eq(base64.b32decode('MFRGG==='), 'abc') eq(base64.b32decode('MFRGGZA='), 'abcd') eq(base64.b32decode('MFRGGZDF'),",
"Test with 'URL safe' alternative characters eq(base64.urlsafe_b64decode('01a-b_cd'), '\\xd3V\\xbeo\\xf7\\x1d') # Non-bytes",
"base64 class LegacyBase64TestCase(unittest.TestCase): def test_encodestring(self): eq = self.assertEqual eq(base64.encodestring(\"www.python.org\"), \"d3d3LnB5dGhvbi5vcmc=\\n\")",
"= self.assertEqual eq(base64.b16encode('\\x01\\x02\\xab\\xcd\\xef'), '0102ABCDEF') eq(base64.b16encode('\\x00'), '00') # Non-bytes eq(base64.b16encode(bytearray('\\x01\\x02\\xab\\xcd\\xef')), '0102ABCDEF')",
"eq(base64.b16decode(bytearray(\"0102ABCDEF\")), '\\x01\\x02\\xab\\xcd\\xef') def test_main(): test_support.run_unittest(__name__) if __name__ == '__main__': test_main()",
"test_b32decode_error(self): self.assertRaises(TypeError, base64.b32decode, 'abc') self.assertRaises(TypeError, base64.b32decode, 'ABCDEF==') def test_b16encode(self): eq",
"eq(base64.b16encode('\\x00'), '00') # Non-bytes eq(base64.b16encode(bytearray('\\x01\\x02\\xab\\xcd\\xef')), '0102ABCDEF') def test_b16decode(self): eq =",
"test_b64decode_error(self): self.assertRaises(TypeError, base64.b64decode, 'abc') def test_b32encode(self): eq = self.assertEqual eq(base64.b32encode(''),",
"safe' alternative characters eq(base64.urlsafe_b64encode('\\xd3V\\xbeo\\xf7\\x1d'), '01a-b_cd') # Non-bytes eq(base64.urlsafe_b64encode(bytearray('\\xd3V\\xbeo\\xf7\\x1d')), '01a-b_cd') def",
"eq(base64.b32decode('MFRGGZDF'), 'abcde') # Non-bytes self.assertRaises(TypeError, base64.b32decode, bytearray('MFRGG===')) def test_b32decode_casefold(self): eq",
"\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Non-bytes eq(base64.standard_b64encode(bytearray('abcd')), 'YWJjZA==') # Test with 'URL",
"True), 'abcde') # Expected exceptions self.assertRaises(TypeError, base64.b32decode, 'me======') # Mapping",
"eq(base64.standard_b64decode(\"d3d3LnB5dGhvbi5vcmc=\"), \"www.python.org\") eq(base64.standard_b64decode(\"YQ==\"), \"a\") eq(base64.standard_b64decode(\"YWI=\"), \"ab\") eq(base64.standard_b64decode(\"YWJj\"), \"abc\") eq(base64.standard_b64decode(\"\"), \"\")",
"\"0123456789!@#0^&*();:<>,. []{}\"), \"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Test with arbitrary alternative",
"# Expected exceptions self.assertRaises(TypeError, base64.b32decode, 'me======') # Mapping zero and",
"from test import test_support import base64 class LegacyBase64TestCase(unittest.TestCase): def test_encodestring(self):",
"test_b64encode(self): eq = self.assertEqual # Test default alphabet eq(base64.b64encode(\"www.python.org\"), \"d3d3LnB5dGhvbi5vcmc=\")",
"characters eq(base64.b64decode('01a*b$cd', altchars='*$'), '\\xd3V\\xbeo\\xf7\\x1d') # Non-bytes eq(base64.b64decode(bytearray(\"YWJj\")), \"abc\") # Test",
"'0102abcdef') # Case fold eq(base64.b16decode('0102abcdef', True), '\\x01\\x02\\xab\\xcd\\xef') # Non-bytes eq(base64.b16decode(bytearray(\"0102ABCDEF\")),",
"'') # Test with arbitrary alternative characters eq(base64.b64decode('01a*b$cd', altchars='*$'), '\\xd3V\\xbeo\\xf7\\x1d')",
"\"YWJj\") eq(base64.standard_b64encode(\"\"), \"\") eq(base64.standard_b64encode(\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\"), \"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\")",
"map01='L'), 'b\\xdd\\xad\\xf3\\xbe') eq(base64.b32decode('M1023456', map01='I'), 'b\\x1d\\xad\\xf3\\xbe') def test_b32decode_error(self): self.assertRaises(TypeError, base64.b32decode, 'abc')",
"def test_b16decode(self): eq = self.assertEqual eq(base64.b16decode('0102ABCDEF'), '\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode('00'), '\\x00') #",
"# Non-bytes eq(base64.urlsafe_b64decode(bytearray('01a-b_cd')), '\\xd3V\\xbeo\\xf7\\x1d') def test_b64decode_error(self): self.assertRaises(TypeError, base64.b64decode, 'abc') def",
"eq(base64.standard_b64decode(\"YWJj\"), \"abc\") eq(base64.standard_b64decode(\"\"), \"\") eq(base64.standard_b64decode(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\"), \"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,.",
"case is not allowed without a flag self.assertRaises(TypeError, base64.b16decode, '0102abcdef')",
"self.assertEqual eq(base64.b16encode('\\x01\\x02\\xab\\xcd\\xef'), '0102ABCDEF') eq(base64.b16encode('\\x00'), '00') # Non-bytes eq(base64.b16encode(bytearray('\\x01\\x02\\xab\\xcd\\xef')), '0102ABCDEF') def",
"'01a*b$cd') # Non-bytes eq(base64.b64encode(bytearray('abcd')), 'YWJjZA==') self.assertRaises(TypeError, base64.b64encode, '\\xd3V\\xbeo\\xf7\\x1d', altchars=bytearray('*$')) #",
"eq(base64.standard_b64encode(\"a\"), \"YQ==\") eq(base64.standard_b64encode(\"ab\"), \"YWI=\") eq(base64.standard_b64encode(\"abc\"), \"YWJj\") eq(base64.standard_b64encode(\"\"), \"\") eq(base64.standard_b64encode(\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"",
"Expected exceptions self.assertRaises(TypeError, base64.b32decode, 'me======') # Mapping zero and one",
"self.assertRaises(TypeError, base64.b64decode, 'abc') def test_b32encode(self): eq = self.assertEqual eq(base64.b32encode(''), '')",
"one eq(base64.b32decode('MLO23456'), 'b\\xdd\\xad\\xf3\\xbe') eq(base64.b32decode('M1023456', map01='L'), 'b\\xdd\\xad\\xf3\\xbe') eq(base64.b32decode('M1023456', map01='I'), 'b\\x1d\\xad\\xf3\\xbe') def",
"eq(base64.standard_b64encode(\"abc\"), \"YWJj\") eq(base64.standard_b64encode(\"\"), \"\") eq(base64.standard_b64encode(\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\"), \"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\"",
"\"YWI=\\n\") eq(base64.encodestring(\"abc\"), \"YWJj\\n\") eq(base64.encodestring(\"\"), \"\") eq(base64.encodestring(\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\"), \"<KEY>\"",
"eq(base64.b64decode(\"YQ==\"), \"a\") eq(base64.b64decode(\"YWI=\"), \"ab\") eq(base64.b64decode(\"YWJj\"), \"abc\") eq(base64.b64decode(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\"), \"abcdefghijklmnopqrstuvwxyz\"",
"# Lower cases eq(base64.b32decode('me======', True), 'a') eq(base64.b32decode('mfra====', True), 'ab') eq(base64.b32decode('mfrgg===',",
"Test with arbitrary alternative characters eq(base64.b64encode('\\xd3V\\xbeo\\xf7\\x1d', altchars='*$'), '01a*b$cd') # Non-bytes",
"'01a-b_cd') def test_b64decode(self): eq = self.assertEqual eq(base64.b64decode(\"d3d3LnB5dGhvbi5vcmc=\"), \"www.python.org\") eq(base64.b64decode('AA=='), '\\x00')",
"eq(base64.decodestring(''), '') # Non-bytes eq(base64.decodestring(bytearray(\"YWJj\\n\")), \"abc\") def test_encode(self): eq =",
"eq(base64.standard_b64decode(\"\"), \"\") eq(base64.standard_b64decode(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\"), \"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\") #",
"\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\"), \"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\") eq(base64.b64decode(''), '') # Test",
"self.assertEqual # Test default alphabet eq(base64.b64encode(\"www.python.org\"), \"d3d3LnB5dGhvbi5vcmc=\") eq(base64.b64encode('\\x00'), 'AA==') eq(base64.b64encode(\"a\"),",
"# Non-bytes eq(base64.b64encode(bytearray('abcd')), 'YWJjZA==') self.assertRaises(TypeError, base64.b64encode, '\\xd3V\\xbeo\\xf7\\x1d', altchars=bytearray('*$')) # Test",
"eq(base64.b64encode('\\x00'), 'AA==') eq(base64.b64encode(\"a\"), \"YQ==\") eq(base64.b64encode(\"ab\"), \"YWI=\") eq(base64.b64encode(\"abc\"), \"YWJj\") eq(base64.b64encode(\"\"), \"\")",
"Non-bytes eq(base64.urlsafe_b64encode(bytearray('\\xd3V\\xbeo\\xf7\\x1d')), '01a-b_cd') def test_b64decode(self): eq = self.assertEqual eq(base64.b64decode(\"d3d3LnB5dGhvbi5vcmc=\"), \"www.python.org\")",
"= self.assertEqual eq(base64.b16decode('0102ABCDEF'), '\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode('00'), '\\x00') # Lower case is",
"eq(base64.urlsafe_b64encode(bytearray('\\xd3V\\xbeo\\xf7\\x1d')), '01a-b_cd') def test_b64decode(self): eq = self.assertEqual eq(base64.b64decode(\"d3d3LnB5dGhvbi5vcmc=\"), \"www.python.org\") eq(base64.b64decode('AA=='),",
"outfp) self.assertEqual(outfp.getvalue(), 'www.python.org') class BaseXYTestCase(unittest.TestCase): def test_b64encode(self): eq = self.assertEqual",
"# Test with arbitrary alternative characters eq(base64.b64encode('\\xd3V\\xbeo\\xf7\\x1d', altchars='*$'), '01a*b$cd') #",
"eq(base64.b32encode(bytearray('abcd')), 'MFRGGZA=') def test_b32decode(self): eq = self.assertEqual eq(base64.b32decode(''), '') eq(base64.b32decode('AA======'),",
"eq = self.assertEqual eq(base64.b32decode(''), '') eq(base64.b32decode('AA======'), '\\x00') eq(base64.b32decode('ME======'), 'a') eq(base64.b32decode('MFRA===='),",
"'') eq(base64.b32decode('ME======', True), 'a') eq(base64.b32decode('MFRA====', True), 'ab') eq(base64.b32decode('MFRGG===', True), 'abc')",
"def test_encode(self): eq = self.assertEqual from cStringIO import StringIO infp",
"# Non-bytes eq(base64.standard_b64decode(bytearray(\"YWJj\")), \"abc\") # Test with 'URL safe' alternative",
"\"YWI=\") eq(base64.standard_b64encode(\"abc\"), \"YWJj\") eq(base64.standard_b64encode(\"\"), \"\") eq(base64.standard_b64encode(\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\"), \"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\"",
"'ab') eq(base64.b32decode('mfrgg===', True), 'abc') eq(base64.b32decode('mfrggza=', True), 'abcd') eq(base64.b32decode('mfrggzdf', True), 'abcde')",
"eq(base64.b64decode(\"YWJj\"), \"abc\") eq(base64.b64decode(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\"), \"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\") eq(base64.b64decode(''),",
"= StringIO() base64.decode(infp, outfp) self.assertEqual(outfp.getvalue(), 'www.python.org') class BaseXYTestCase(unittest.TestCase): def test_b64encode(self):",
"\"\") eq(base64.standard_b64encode(\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\"), \"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Non-bytes",
"eq = self.assertEqual from cStringIO import StringIO infp = StringIO('abcdefghijklmnopqrstuvwxyz'",
"test_b32decode_casefold(self): eq = self.assertEqual eq(base64.b32decode('', True), '') eq(base64.b32decode('ME======', True), 'a')",
"outfp = StringIO() base64.encode(infp, outfp) eq(outfp.getvalue(), 'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE' 'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT' 'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n') def",
"Test with arbitrary alternative characters eq(base64.b64decode('01a*b$cd', altchars='*$'), '\\xd3V\\xbeo\\xf7\\x1d') # Non-bytes",
"class BaseXYTestCase(unittest.TestCase): def test_b64encode(self): eq = self.assertEqual # Test default",
"[]{}\"), \"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Test with arbitrary alternative characters",
"\"a\") eq(base64.b64decode(\"YWI=\"), \"ab\") eq(base64.b64decode(\"YWJj\"), \"abc\") eq(base64.b64decode(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\"), \"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"",
"\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\") # Non-bytes eq(base64.standard_b64decode(bytearray(\"YWJj\")), \"abc\") # Test",
"'0102ABCDEF') eq(base64.b16encode('\\x00'), '00') # Non-bytes eq(base64.b16encode(bytearray('\\x01\\x02\\xab\\xcd\\xef')), '0102ABCDEF') def test_b16decode(self): eq",
"eq(base64.b64encode(\"www.python.org\"), \"d3d3LnB5dGhvbi5vcmc=\") eq(base64.b64encode('\\x00'), 'AA==') eq(base64.b64encode(\"a\"), \"YQ==\") eq(base64.b64encode(\"ab\"), \"YWI=\") eq(base64.b64encode(\"abc\"), \"YWJj\")",
"= self.assertEqual eq(base64.decodestring(\"d3d3LnB5dGhvbi5vcmc=\\n\"), \"www.python.org\") eq(base64.decodestring(\"YQ==\\n\"), \"a\") eq(base64.decodestring(\"YWI=\\n\"), \"ab\") eq(base64.decodestring(\"YWJj\\n\"), \"abc\")",
"eq(base64.urlsafe_b64encode('\\xd3V\\xbeo\\xf7\\x1d'), '01a-b_cd') # Non-bytes eq(base64.urlsafe_b64encode(bytearray('\\xd3V\\xbeo\\xf7\\x1d')), '01a-b_cd') def test_b64decode(self): eq =",
"'MFRGGZDF') # Non-bytes eq(base64.b32encode(bytearray('abcd')), 'MFRGGZA=') def test_b32decode(self): eq = self.assertEqual",
"eq(base64.encodestring(\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\"), \"<KEY>\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\") # Non-bytes eq(base64.encodestring(bytearray('abc')),",
"test_b32encode(self): eq = self.assertEqual eq(base64.b32encode(''), '') eq(base64.b32encode('\\x00'), 'AA======') eq(base64.b32encode('a'), 'ME======')",
"= StringIO('abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' '0123456789!@#0^&*();:<>,. []{}') outfp = StringIO() base64.encode(infp, outfp)",
"standard alphabet eq(base64.standard_b64decode(\"d3d3LnB5dGhvbi5vcmc=\"), \"www.python.org\") eq(base64.standard_b64decode(\"YQ==\"), \"a\") eq(base64.standard_b64decode(\"YWI=\"), \"ab\") eq(base64.standard_b64decode(\"YWJj\"), \"abc\")",
"allowed without a flag self.assertRaises(TypeError, base64.b16decode, '0102abcdef') # Case fold",
"alternative characters eq(base64.b64decode('01a*b$cd', altchars='*$'), '\\xd3V\\xbeo\\xf7\\x1d') # Non-bytes eq(base64.b64decode(bytearray(\"YWJj\")), \"abc\") #",
"\"d3d3LnB5dGhvbi5vcmc=\") eq(base64.b64encode('\\x00'), 'AA==') eq(base64.b64encode(\"a\"), \"YQ==\") eq(base64.b64encode(\"ab\"), \"YWI=\") eq(base64.b64encode(\"abc\"), \"YWJj\") eq(base64.b64encode(\"\"),",
"'YWJjZA==') # Test with 'URL safe' alternative characters eq(base64.urlsafe_b64encode('\\xd3V\\xbeo\\xf7\\x1d'), '01a-b_cd')",
"'a') eq(base64.b32decode('MFRA====', True), 'ab') eq(base64.b32decode('MFRGG===', True), 'abc') eq(base64.b32decode('MFRGGZA=', True), 'abcd')",
"'URL safe' alternative characters eq(base64.urlsafe_b64encode('\\xd3V\\xbeo\\xf7\\x1d'), '01a-b_cd') # Non-bytes eq(base64.urlsafe_b64encode(bytearray('\\xd3V\\xbeo\\xf7\\x1d')), '01a-b_cd')",
"'\\xd3V\\xbeo\\xf7\\x1d') # Non-bytes eq(base64.urlsafe_b64decode(bytearray('01a-b_cd')), '\\xd3V\\xbeo\\xf7\\x1d') def test_b64decode_error(self): self.assertRaises(TypeError, base64.b64decode, 'abc')",
"def test_b32decode_error(self): self.assertRaises(TypeError, base64.b32decode, 'abc') self.assertRaises(TypeError, base64.b32decode, 'ABCDEF==') def test_b16encode(self):",
"# Non-bytes eq(base64.b64decode(bytearray(\"YWJj\")), \"abc\") # Test standard alphabet eq(base64.standard_b64decode(\"d3d3LnB5dGhvbi5vcmc=\"), \"www.python.org\")",
"eq(base64.b32encode('abcd'), 'MFRGGZA=') eq(base64.b32encode('abcde'), 'MFRGGZDF') # Non-bytes eq(base64.b32encode(bytearray('abcd')), 'MFRGGZA=') def test_b32decode(self):",
"test_b16decode(self): eq = self.assertEqual eq(base64.b16decode('0102ABCDEF'), '\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode('00'), '\\x00') # Lower",
"'ab') eq(base64.b32decode('MFRGG==='), 'abc') eq(base64.b32decode('MFRGGZA='), 'abcd') eq(base64.b32decode('MFRGGZDF'), 'abcde') # Non-bytes self.assertRaises(TypeError,",
"test_b32decode(self): eq = self.assertEqual eq(base64.b32decode(''), '') eq(base64.b32decode('AA======'), '\\x00') eq(base64.b32decode('ME======'), 'a')",
"test_support import base64 class LegacyBase64TestCase(unittest.TestCase): def test_encodestring(self): eq = self.assertEqual",
"'ab') eq(base64.b32decode('MFRGG===', True), 'abc') eq(base64.b32decode('MFRGGZA=', True), 'abcd') eq(base64.b32decode('MFRGGZDF', True), 'abcde')",
"altchars=bytearray('*$')) # Test standard alphabet eq(base64.standard_b64encode(\"www.python.org\"), \"d3d3LnB5dGhvbi5vcmc=\") eq(base64.standard_b64encode(\"a\"), \"YQ==\") eq(base64.standard_b64encode(\"ab\"),",
"Non-bytes eq(base64.b64encode(bytearray('abcd')), 'YWJjZA==') self.assertRaises(TypeError, base64.b64encode, '\\xd3V\\xbeo\\xf7\\x1d', altchars=bytearray('*$')) # Test standard",
"eq(base64.encodestring(bytearray('abc')), 'YWJj\\n') def test_decodestring(self): eq = self.assertEqual eq(base64.decodestring(\"d3d3LnB5dGhvbi5vcmc=\\n\"), \"www.python.org\") eq(base64.decodestring(\"YQ==\\n\"),",
"Test default alphabet eq(base64.b64encode(\"www.python.org\"), \"d3d3LnB5dGhvbi5vcmc=\") eq(base64.b64encode('\\x00'), 'AA==') eq(base64.b64encode(\"a\"), \"YQ==\") eq(base64.b64encode(\"ab\"),",
"bytearray('MFRGG===')) def test_b32decode_casefold(self): eq = self.assertEqual eq(base64.b32decode('', True), '') eq(base64.b32decode('ME======',",
"self.assertRaises(TypeError, base64.b64encode, '\\xd3V\\xbeo\\xf7\\x1d', altchars=bytearray('*$')) # Test standard alphabet eq(base64.standard_b64encode(\"www.python.org\"), \"d3d3LnB5dGhvbi5vcmc=\")",
"\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\") # Non-bytes eq(base64.encodestring(bytearray('abc')), 'YWJj\\n') def test_decodestring(self): eq =",
"eq(base64.decodestring(bytearray(\"YWJj\\n\")), \"abc\") def test_encode(self): eq = self.assertEqual from cStringIO import",
"'b\\xdd\\xad\\xf3\\xbe') eq(base64.b32decode('M1023456', map01='L'), 'b\\xdd\\xad\\xf3\\xbe') eq(base64.b32decode('M1023456', map01='I'), 'b\\x1d\\xad\\xf3\\xbe') def test_b32decode_error(self): self.assertRaises(TypeError,",
"= self.assertEqual eq(base64.b32encode(''), '') eq(base64.b32encode('\\x00'), 'AA======') eq(base64.b32encode('a'), 'ME======') eq(base64.b32encode('ab'), 'MFRA====')",
"True), '\\x01\\x02\\xab\\xcd\\xef') # Non-bytes eq(base64.b16decode(bytearray(\"0102ABCDEF\")), '\\x01\\x02\\xab\\xcd\\xef') def test_main(): test_support.run_unittest(__name__) if",
"eq(base64.b32decode('', True), '') eq(base64.b32decode('ME======', True), 'a') eq(base64.b32decode('MFRA====', True), 'ab') eq(base64.b32decode('MFRGG===',",
"'MFRGG===') eq(base64.b32encode('abcd'), 'MFRGGZA=') eq(base64.b32encode('abcde'), 'MFRGGZDF') # Non-bytes eq(base64.b32encode(bytearray('abcd')), 'MFRGGZA=') def",
"base64.b32decode, 'ABCDEF==') def test_b16encode(self): eq = self.assertEqual eq(base64.b16encode('\\x01\\x02\\xab\\xcd\\xef'), '0102ABCDEF') eq(base64.b16encode('\\x00'),",
"= self.assertEqual eq(base64.b64decode(\"d3d3LnB5dGhvbi5vcmc=\"), \"www.python.org\") eq(base64.b64decode('AA=='), '\\x00') eq(base64.b64decode(\"YQ==\"), \"a\") eq(base64.b64decode(\"YWI=\"), \"ab\")",
"alphabet eq(base64.b64encode(\"www.python.org\"), \"d3d3LnB5dGhvbi5vcmc=\") eq(base64.b64encode('\\x00'), 'AA==') eq(base64.b64encode(\"a\"), \"YQ==\") eq(base64.b64encode(\"ab\"), \"YWI=\") eq(base64.b64encode(\"abc\"),",
"# Non-bytes eq(base64.decodestring(bytearray(\"YWJj\\n\")), \"abc\") def test_encode(self): eq = self.assertEqual from",
"not allowed without a flag self.assertRaises(TypeError, base64.b16decode, '0102abcdef') # Case",
"eq(base64.standard_b64decode(\"YQ==\"), \"a\") eq(base64.standard_b64decode(\"YWI=\"), \"ab\") eq(base64.standard_b64decode(\"YWJj\"), \"abc\") eq(base64.standard_b64decode(\"\"), \"\") eq(base64.standard_b64decode(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\"",
"eq(base64.decodestring(\"YWI=\\n\"), \"ab\") eq(base64.decodestring(\"YWJj\\n\"), \"abc\") eq(base64.decodestring(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\"), \"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,.",
"base64.b32decode, 'abc') self.assertRaises(TypeError, base64.b32decode, 'ABCDEF==') def test_b16encode(self): eq = self.assertEqual",
"standard alphabet eq(base64.standard_b64encode(\"www.python.org\"), \"d3d3LnB5dGhvbi5vcmc=\") eq(base64.standard_b64encode(\"a\"), \"YQ==\") eq(base64.standard_b64encode(\"ab\"), \"YWI=\") eq(base64.standard_b64encode(\"abc\"), \"YWJj\")",
"eq(base64.standard_b64decode(\"YWI=\"), \"ab\") eq(base64.standard_b64decode(\"YWJj\"), \"abc\") eq(base64.standard_b64decode(\"\"), \"\") eq(base64.standard_b64decode(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\"), \"abcdefghijklmnopqrstuvwxyz\"",
"\"abc\") # Test standard alphabet eq(base64.standard_b64decode(\"d3d3LnB5dGhvbi5vcmc=\"), \"www.python.org\") eq(base64.standard_b64decode(\"YQ==\"), \"a\") eq(base64.standard_b64decode(\"YWI=\"),",
"eq(base64.b32decode('M1023456', map01='L'), 'b\\xdd\\xad\\xf3\\xbe') eq(base64.b32decode('M1023456', map01='I'), 'b\\x1d\\xad\\xf3\\xbe') def test_b32decode_error(self): self.assertRaises(TypeError, base64.b32decode,",
"eq(base64.b32decode('M1023456', map01='I'), 'b\\x1d\\xad\\xf3\\xbe') def test_b32decode_error(self): self.assertRaises(TypeError, base64.b32decode, 'abc') self.assertRaises(TypeError, base64.b32decode,",
"'me======') # Mapping zero and one eq(base64.b32decode('MLO23456'), 'b\\xdd\\xad\\xf3\\xbe') eq(base64.b32decode('M1023456', map01='L'),",
"\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\"), \"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\") eq(base64.decodestring(''), '') # Non-bytes",
"\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Non-bytes eq(base64.standard_b64encode(bytearray('abcd')), 'YWJjZA==') # Test with",
"from cStringIO import StringIO infp = StringIO('d3d3LnB5dGhvbi5vcmc=') outfp = StringIO()",
"Case fold eq(base64.b16decode('0102abcdef', True), '\\x01\\x02\\xab\\xcd\\xef') # Non-bytes eq(base64.b16decode(bytearray(\"0102ABCDEF\")), '\\x01\\x02\\xab\\xcd\\xef') def",
"'\\xd3V\\xbeo\\xf7\\x1d') # Non-bytes eq(base64.b64decode(bytearray(\"YWJj\")), \"abc\") # Test standard alphabet eq(base64.standard_b64decode(\"d3d3LnB5dGhvbi5vcmc=\"),",
"eq(base64.b32encode(''), '') eq(base64.b32encode('\\x00'), 'AA======') eq(base64.b32encode('a'), 'ME======') eq(base64.b32encode('ab'), 'MFRA====') eq(base64.b32encode('abc'), 'MFRGG===')",
"eq(base64.b32decode('MFRGG==='), 'abc') eq(base64.b32decode('MFRGGZA='), 'abcd') eq(base64.b32decode('MFRGGZDF'), 'abcde') # Non-bytes self.assertRaises(TypeError, base64.b32decode,",
"'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT' 'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n') def test_decode(self): from cStringIO import StringIO infp =",
"\"0123456789!@#0^&*();:<>,. []{}\") # Non-bytes eq(base64.standard_b64decode(bytearray(\"YWJj\")), \"abc\") # Test with 'URL",
"# Case fold eq(base64.b16decode('0102abcdef', True), '\\x01\\x02\\xab\\xcd\\xef') # Non-bytes eq(base64.b16decode(bytearray(\"0102ABCDEF\")), '\\x01\\x02\\xab\\xcd\\xef')",
"characters eq(base64.b64encode('\\xd3V\\xbeo\\xf7\\x1d', altchars='*$'), '01a*b$cd') # Non-bytes eq(base64.b64encode(bytearray('abcd')), 'YWJjZA==') self.assertRaises(TypeError, base64.b64encode,",
"'\\xd3V\\xbeo\\xf7\\x1d', altchars=bytearray('*$')) # Test standard alphabet eq(base64.standard_b64encode(\"www.python.org\"), \"d3d3LnB5dGhvbi5vcmc=\") eq(base64.standard_b64encode(\"a\"), \"YQ==\")",
"alphabet eq(base64.standard_b64encode(\"www.python.org\"), \"d3d3LnB5dGhvbi5vcmc=\") eq(base64.standard_b64encode(\"a\"), \"YQ==\") eq(base64.standard_b64encode(\"ab\"), \"YWI=\") eq(base64.standard_b64encode(\"abc\"), \"YWJj\") eq(base64.standard_b64encode(\"\"),",
"[]{}\") # Non-bytes eq(base64.standard_b64decode(bytearray(\"YWJj\")), \"abc\") # Test with 'URL safe'",
"\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Test with arbitrary alternative characters eq(base64.b64encode('\\xd3V\\xbeo\\xf7\\x1d', altchars='*$'), '01a*b$cd')",
"test_decode(self): from cStringIO import StringIO infp = StringIO('d3d3LnB5dGhvbi5vcmc=') outfp =",
"# Non-bytes eq(base64.standard_b64encode(bytearray('abcd')), 'YWJjZA==') # Test with 'URL safe' alternative",
"True), 'a') eq(base64.b32decode('mfra====', True), 'ab') eq(base64.b32decode('mfrgg===', True), 'abc') eq(base64.b32decode('mfrggza=', True),",
"eq(base64.standard_b64decode(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\"), \"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\") # Non-bytes eq(base64.standard_b64decode(bytearray(\"YWJj\")),",
"eq(base64.standard_b64encode(\"ab\"), \"YWI=\") eq(base64.standard_b64encode(\"abc\"), \"YWJj\") eq(base64.standard_b64encode(\"\"), \"\") eq(base64.standard_b64encode(\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\"),",
"'abc') eq(base64.b32decode('MFRGGZA=', True), 'abcd') eq(base64.b32decode('MFRGGZDF', True), 'abcde') # Lower cases",
"self.assertEqual eq(base64.decodestring(\"d3d3LnB5dGhvbi5vcmc=\\n\"), \"www.python.org\") eq(base64.decodestring(\"YQ==\\n\"), \"a\") eq(base64.decodestring(\"YWI=\\n\"), \"ab\") eq(base64.decodestring(\"YWJj\\n\"), \"abc\") eq(base64.decodestring(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\"",
"a flag self.assertRaises(TypeError, base64.b16decode, '0102abcdef') # Case fold eq(base64.b16decode('0102abcdef', True),",
"\"abc\") # Test with 'URL safe' alternative characters eq(base64.urlsafe_b64decode('01a-b_cd'), '\\xd3V\\xbeo\\xf7\\x1d')",
"def test_decode(self): from cStringIO import StringIO infp = StringIO('d3d3LnB5dGhvbi5vcmc=') outfp",
"'\\x01\\x02\\xab\\xcd\\xef') # Non-bytes eq(base64.b16decode(bytearray(\"0102ABCDEF\")), '\\x01\\x02\\xab\\xcd\\xef') def test_main(): test_support.run_unittest(__name__) if __name__",
"base64.b32decode, 'me======') # Mapping zero and one eq(base64.b32decode('MLO23456'), 'b\\xdd\\xad\\xf3\\xbe') eq(base64.b32decode('M1023456',",
"'0102ABCDEF') def test_b16decode(self): eq = self.assertEqual eq(base64.b16decode('0102ABCDEF'), '\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode('00'), '\\x00')",
"'ABCDEF==') def test_b16encode(self): eq = self.assertEqual eq(base64.b16encode('\\x01\\x02\\xab\\xcd\\xef'), '0102ABCDEF') eq(base64.b16encode('\\x00'), '00')",
"eq(base64.decodestring(\"d3d3LnB5dGhvbi5vcmc=\\n\"), \"www.python.org\") eq(base64.decodestring(\"YQ==\\n\"), \"a\") eq(base64.decodestring(\"YWI=\\n\"), \"ab\") eq(base64.decodestring(\"YWJj\\n\"), \"abc\") eq(base64.decodestring(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\"",
"'') # Non-bytes eq(base64.decodestring(bytearray(\"YWJj\\n\")), \"abc\") def test_encode(self): eq = self.assertEqual",
"True), 'abcd') eq(base64.b32decode('mfrggzdf', True), 'abcde') # Expected exceptions self.assertRaises(TypeError, base64.b32decode,",
"eq(base64.b64encode(\"a\"), \"YQ==\") eq(base64.b64encode(\"ab\"), \"YWI=\") eq(base64.b64encode(\"abc\"), \"YWJj\") eq(base64.b64encode(\"\"), \"\") eq(base64.b64encode(\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"",
"base64.encode(infp, outfp) eq(outfp.getvalue(), 'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE' 'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT' 'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n') def test_decode(self): from cStringIO",
"altchars='*$'), '\\xd3V\\xbeo\\xf7\\x1d') # Non-bytes eq(base64.b64decode(bytearray(\"YWJj\")), \"abc\") # Test standard alphabet",
"'URL safe' alternative characters eq(base64.urlsafe_b64decode('01a-b_cd'), '\\xd3V\\xbeo\\xf7\\x1d') # Non-bytes eq(base64.urlsafe_b64decode(bytearray('01a-b_cd')), '\\xd3V\\xbeo\\xf7\\x1d')",
"eq(base64.b32decode(''), '') eq(base64.b32decode('AA======'), '\\x00') eq(base64.b32decode('ME======'), 'a') eq(base64.b32decode('MFRA===='), 'ab') eq(base64.b32decode('MFRGG==='), 'abc')",
"\"0123456789!@#0^&*();:<>,. []{}\") eq(base64.decodestring(''), '') # Non-bytes eq(base64.decodestring(bytearray(\"YWJj\\n\")), \"abc\") def test_encode(self):",
"Non-bytes eq(base64.b16encode(bytearray('\\x01\\x02\\xab\\xcd\\xef')), '0102ABCDEF') def test_b16decode(self): eq = self.assertEqual eq(base64.b16decode('0102ABCDEF'), '\\x01\\x02\\xab\\xcd\\xef')",
"\"0123456789!@#0^&*();:<>,. []{}\"), \"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Non-bytes eq(base64.standard_b64encode(bytearray('abcd')), 'YWJjZA==') #",
"\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Test with arbitrary alternative characters eq(base64.b64encode('\\xd3V\\xbeo\\xf7\\x1d', altchars='*$'),",
"= StringIO() base64.encode(infp, outfp) eq(outfp.getvalue(), 'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE' 'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT' 'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n') def test_decode(self):",
"'YWJj\\n') def test_decodestring(self): eq = self.assertEqual eq(base64.decodestring(\"d3d3LnB5dGhvbi5vcmc=\\n\"), \"www.python.org\") eq(base64.decodestring(\"YQ==\\n\"), \"a\")",
"eq(base64.standard_b64encode(\"www.python.org\"), \"d3d3LnB5dGhvbi5vcmc=\") eq(base64.standard_b64encode(\"a\"), \"YQ==\") eq(base64.standard_b64encode(\"ab\"), \"YWI=\") eq(base64.standard_b64encode(\"abc\"), \"YWJj\") eq(base64.standard_b64encode(\"\"), \"\")",
"'abc') def test_b32encode(self): eq = self.assertEqual eq(base64.b32encode(''), '') eq(base64.b32encode('\\x00'), 'AA======')",
"safe' alternative characters eq(base64.urlsafe_b64decode('01a-b_cd'), '\\xd3V\\xbeo\\xf7\\x1d') # Non-bytes eq(base64.urlsafe_b64decode(bytearray('01a-b_cd')), '\\xd3V\\xbeo\\xf7\\x1d') def",
"= self.assertEqual eq(base64.b32decode(''), '') eq(base64.b32decode('AA======'), '\\x00') eq(base64.b32decode('ME======'), 'a') eq(base64.b32decode('MFRA===='), 'ab')",
"eq(base64.b64decode(bytearray(\"YWJj\")), \"abc\") # Test standard alphabet eq(base64.standard_b64decode(\"d3d3LnB5dGhvbi5vcmc=\"), \"www.python.org\") eq(base64.standard_b64decode(\"YQ==\"), \"a\")",
"import test_support import base64 class LegacyBase64TestCase(unittest.TestCase): def test_encodestring(self): eq =",
"eq(base64.b32decode('ME======'), 'a') eq(base64.b32decode('MFRA===='), 'ab') eq(base64.b32decode('MFRGG==='), 'abc') eq(base64.b32decode('MFRGGZA='), 'abcd') eq(base64.b32decode('MFRGGZDF'), 'abcde')",
"[]{}') outfp = StringIO() base64.encode(infp, outfp) eq(outfp.getvalue(), 'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE' 'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT' 'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n')",
"StringIO() base64.encode(infp, outfp) eq(outfp.getvalue(), 'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE' 'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT' 'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n') def test_decode(self): from",
"infp = StringIO('abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' '0123456789!@#0^&*();:<>,. []{}') outfp = StringIO() base64.encode(infp,",
"outfp) eq(outfp.getvalue(), 'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE' 'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT' 'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n') def test_decode(self): from cStringIO import",
"'abcd') eq(base64.b32decode('MFRGGZDF', True), 'abcde') # Lower cases eq(base64.b32decode('me======', True), 'a')",
"Non-bytes eq(base64.urlsafe_b64decode(bytearray('01a-b_cd')), '\\xd3V\\xbeo\\xf7\\x1d') def test_b64decode_error(self): self.assertRaises(TypeError, base64.b64decode, 'abc') def test_b32encode(self):",
"eq(base64.standard_b64encode(bytearray('abcd')), 'YWJjZA==') # Test with 'URL safe' alternative characters eq(base64.urlsafe_b64encode('\\xd3V\\xbeo\\xf7\\x1d'),",
"with 'URL safe' alternative characters eq(base64.urlsafe_b64encode('\\xd3V\\xbeo\\xf7\\x1d'), '01a-b_cd') # Non-bytes eq(base64.urlsafe_b64encode(bytearray('\\xd3V\\xbeo\\xf7\\x1d')),",
"test_b64decode(self): eq = self.assertEqual eq(base64.b64decode(\"d3d3LnB5dGhvbi5vcmc=\"), \"www.python.org\") eq(base64.b64decode('AA=='), '\\x00') eq(base64.b64decode(\"YQ==\"), \"a\")",
"eq(base64.b64decode('AA=='), '\\x00') eq(base64.b64decode(\"YQ==\"), \"a\") eq(base64.b64decode(\"YWI=\"), \"ab\") eq(base64.b64decode(\"YWJj\"), \"abc\") eq(base64.b64decode(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\"",
"= self.assertEqual eq(base64.encodestring(\"www.python.org\"), \"d3d3LnB5dGhvbi5vcmc=\\n\") eq(base64.encodestring(\"a\"), \"YQ==\\n\") eq(base64.encodestring(\"ab\"), \"YWI=\\n\") eq(base64.encodestring(\"abc\"), \"YWJj\\n\")",
"eq(base64.decodestring(\"YWJj\\n\"), \"abc\") eq(base64.decodestring(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\"), \"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\") eq(base64.decodestring(''),",
"eq(base64.b32decode('MFRGG===', True), 'abc') eq(base64.b32decode('MFRGGZA=', True), 'abcd') eq(base64.b32decode('MFRGGZDF', True), 'abcde') #",
"'abcd') eq(base64.b32decode('MFRGGZDF'), 'abcde') # Non-bytes self.assertRaises(TypeError, base64.b32decode, bytearray('MFRGG===')) def test_b32decode_casefold(self):",
"eq(base64.b32decode('mfra====', True), 'ab') eq(base64.b32decode('mfrgg===', True), 'abc') eq(base64.b32decode('mfrggza=', True), 'abcd') eq(base64.b32decode('mfrggzdf',",
"True), 'abc') eq(base64.b32decode('MFRGGZA=', True), 'abcd') eq(base64.b32decode('MFRGGZDF', True), 'abcde') # Lower",
"\"ab\") eq(base64.decodestring(\"YWJj\\n\"), \"abc\") eq(base64.decodestring(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\"), \"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\")",
"eq(base64.b32encode('a'), 'ME======') eq(base64.b32encode('ab'), 'MFRA====') eq(base64.b32encode('abc'), 'MFRGG===') eq(base64.b32encode('abcd'), 'MFRGGZA=') eq(base64.b32encode('abcde'), 'MFRGGZDF')",
"# Non-bytes eq(base64.urlsafe_b64encode(bytearray('\\xd3V\\xbeo\\xf7\\x1d')), '01a-b_cd') def test_b64decode(self): eq = self.assertEqual eq(base64.b64decode(\"d3d3LnB5dGhvbi5vcmc=\"),",
"\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\") eq(base64.decodestring(''), '') # Non-bytes eq(base64.decodestring(bytearray(\"YWJj\\n\")), \"abc\")",
"test_encode(self): eq = self.assertEqual from cStringIO import StringIO infp =",
"'abcd') eq(base64.b32decode('mfrggzdf', True), 'abcde') # Expected exceptions self.assertRaises(TypeError, base64.b32decode, 'me======')",
"self.assertEqual eq(base64.b64decode(\"d3d3LnB5dGhvbi5vcmc=\"), \"www.python.org\") eq(base64.b64decode('AA=='), '\\x00') eq(base64.b64decode(\"YQ==\"), \"a\") eq(base64.b64decode(\"YWI=\"), \"ab\") eq(base64.b64decode(\"YWJj\"),",
"'a') eq(base64.b32decode('MFRA===='), 'ab') eq(base64.b32decode('MFRGG==='), 'abc') eq(base64.b32decode('MFRGGZA='), 'abcd') eq(base64.b32decode('MFRGGZDF'), 'abcde') #",
"'MFRGGZA=') eq(base64.b32encode('abcde'), 'MFRGGZDF') # Non-bytes eq(base64.b32encode(bytearray('abcd')), 'MFRGGZA=') def test_b32decode(self): eq",
"BaseXYTestCase(unittest.TestCase): def test_b64encode(self): eq = self.assertEqual # Test default alphabet",
"\"<KEY>\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\") # Non-bytes eq(base64.encodestring(bytearray('abc')), 'YWJj\\n') def test_decodestring(self): eq",
"\"YWJj\") eq(base64.b64encode(\"\"), \"\") eq(base64.b64encode(\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\"), \"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\")",
"\"YWJj\\n\") eq(base64.encodestring(\"\"), \"\") eq(base64.encodestring(\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\"), \"<KEY>\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\")",
"# Non-bytes eq(base64.encodestring(bytearray('abc')), 'YWJj\\n') def test_decodestring(self): eq = self.assertEqual eq(base64.decodestring(\"d3d3LnB5dGhvbi5vcmc=\\n\"),",
"True), 'abcd') eq(base64.b32decode('MFRGGZDF', True), 'abcde') # Lower cases eq(base64.b32decode('me======', True),",
"'AA==') eq(base64.b64encode(\"a\"), \"YQ==\") eq(base64.b64encode(\"ab\"), \"YWI=\") eq(base64.b64encode(\"abc\"), \"YWJj\") eq(base64.b64encode(\"\"), \"\") eq(base64.b64encode(\"abcdefghijklmnopqrstuvwxyz\"",
"'abc') eq(base64.b32decode('MFRGGZA='), 'abcd') eq(base64.b32decode('MFRGGZDF'), 'abcde') # Non-bytes self.assertRaises(TypeError, base64.b32decode, bytearray('MFRGG==='))",
"\"YQ==\") eq(base64.b64encode(\"ab\"), \"YWI=\") eq(base64.b64encode(\"abc\"), \"YWJj\") eq(base64.b64encode(\"\"), \"\") eq(base64.b64encode(\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,.",
"StringIO() base64.decode(infp, outfp) self.assertEqual(outfp.getvalue(), 'www.python.org') class BaseXYTestCase(unittest.TestCase): def test_b64encode(self): eq",
"True), '') eq(base64.b32decode('ME======', True), 'a') eq(base64.b32decode('MFRA====', True), 'ab') eq(base64.b32decode('MFRGG===', True),",
"'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode('00'), '\\x00') # Lower case is not allowed without",
"'MFRA====') eq(base64.b32encode('abc'), 'MFRGG===') eq(base64.b32encode('abcd'), 'MFRGGZA=') eq(base64.b32encode('abcde'), 'MFRGGZDF') # Non-bytes eq(base64.b32encode(bytearray('abcd')),",
"True), 'abc') eq(base64.b32decode('mfrggza=', True), 'abcd') eq(base64.b32decode('mfrggzdf', True), 'abcde') # Expected",
"True), 'abcde') # Lower cases eq(base64.b32decode('me======', True), 'a') eq(base64.b32decode('mfra====', True),",
"alternative characters eq(base64.urlsafe_b64decode('01a-b_cd'), '\\xd3V\\xbeo\\xf7\\x1d') # Non-bytes eq(base64.urlsafe_b64decode(bytearray('01a-b_cd')), '\\xd3V\\xbeo\\xf7\\x1d') def test_b64decode_error(self):",
"'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE' 'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT' 'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n') def test_decode(self): from cStringIO import StringIO infp",
"\"abc\") eq(base64.standard_b64decode(\"\"), \"\") eq(base64.standard_b64decode(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\"), \"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\")",
"def test_b16encode(self): eq = self.assertEqual eq(base64.b16encode('\\x01\\x02\\xab\\xcd\\xef'), '0102ABCDEF') eq(base64.b16encode('\\x00'), '00') #",
"outfp = StringIO() base64.decode(infp, outfp) self.assertEqual(outfp.getvalue(), 'www.python.org') class BaseXYTestCase(unittest.TestCase): def",
"\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\"), \"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789!@#0^&*();:<>,. []{}\") eq(base64.decodestring(''), '') # Non-bytes eq(base64.decodestring(bytearray(\"YWJj\\n\")),",
"eq(base64.urlsafe_b64decode(bytearray('01a-b_cd')), '\\xd3V\\xbeo\\xf7\\x1d') def test_b64decode_error(self): self.assertRaises(TypeError, base64.b64decode, 'abc') def test_b32encode(self): eq",
"eq(base64.b32encode('abc'), 'MFRGG===') eq(base64.b32encode('abcd'), 'MFRGGZA=') eq(base64.b32encode('abcde'), 'MFRGGZDF') # Non-bytes eq(base64.b32encode(bytearray('abcd')), 'MFRGGZA=')",
"\"ab\") eq(base64.standard_b64decode(\"YWJj\"), \"abc\") eq(base64.standard_b64decode(\"\"), \"\") eq(base64.standard_b64decode(\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\"), \"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"",
"eq(base64.b32encode('\\x00'), 'AA======') eq(base64.b32encode('a'), 'ME======') eq(base64.b32encode('ab'), 'MFRA====') eq(base64.b32encode('abc'), 'MFRGG===') eq(base64.b32encode('abcd'), 'MFRGGZA=')",
"self.assertEqual(outfp.getvalue(), 'www.python.org') class BaseXYTestCase(unittest.TestCase): def test_b64encode(self): eq = self.assertEqual #",
"without a flag self.assertRaises(TypeError, base64.b16decode, '0102abcdef') # Case fold eq(base64.b16decode('0102abcdef',",
"with arbitrary alternative characters eq(base64.b64decode('01a*b$cd', altchars='*$'), '\\xd3V\\xbeo\\xf7\\x1d') # Non-bytes eq(base64.b64decode(bytearray(\"YWJj\")),",
"[]{}\"), \"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" \"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" \"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Non-bytes eq(base64.standard_b64encode(bytearray('abcd')), 'YWJjZA==') # Test"
] |
[
"if self.rotation != 'Pio è un figo': glBindVertexArray(self.xpatharray) glUseProgram(self.xpath_shader) modelLocation",
"c_void_p(0)) #setting xline bufer self.zpatharray = glGenVertexArrays(1) glBindVertexArray(self.zpatharray) self.zlineBuffer =",
"glDisableVertexAttribArray(0) # rendering the ylines glBindVertexArray(self.ypatharray) glUseProgram(self.ypath_shader) modelLocation = glGetUniformLocation(self.ypath_shader,",
"GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * 4, c_void_p(0)) #setting",
"rendering the ylines glBindVertexArray(self.ypatharray) glUseProgram(self.ypath_shader) modelLocation = glGetUniformLocation(self.ypath_shader, 'model') viewLocation",
"rotation=None): self.loadPath(position) if rotation: assert len(position) == len(rotation) * 3",
"buffer self.ypatharray = glGenVertexArrays(1) glBindVertexArray(self.ypatharray) self.ylineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.ylineBuffer)",
"rotation # compiling shader self.xpath_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\xpathfrag.glsl').shaderProgram self.ypath_shader =",
"'src\\\\shaders\\\\path\\\\zpathfrag.glsl').shaderProgram # setting versors self.xvertices = [] self.yvertices = []",
"0), versor) r_versor = np.dot(get_rot(self.rotation[index][1], 1), r_versor) r_versor = np.dot(get_rot(self.rotation[index][2],",
"y1, z1, ..., xn, yn, zn] ; rotation = [[Rx1,",
"pos) yversor = self.getVersorAtTime(np.array([0, 1, 0, 1], dtype='float32'), pos) zversor",
"glGetUniformLocation(self.path_shader, 'view') projectionLocation = glGetUniformLocation(self.path_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model)",
"in range(len(rotation)): xversor = self.getVersorAtTime(np.array([1, 0, 0, 1], dtype='float32'), pos)",
"from .Shader import Shader from .transforms import * from OpenGL.GL",
"= glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.lineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.vertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3,",
"= self.getVersorAtTime(np.array([0, 0, 1, 1], dtype='float32'), pos) pos = [self.vertices[pos*3],",
"viewLocation = glGetUniformLocation(self.xpath_shader, 'view') projectionLocation = glGetUniformLocation(self.xpath_shader, 'projection') glUniformMatrix4fv(modelLocation, 1,",
"3 * 4, c_void_p(0)) def loadRotation(self, rotation): self.rotation = rotation",
"= [] self.yvertices = [] self.zvertices = [] for pos",
"self.getVersorAtTime(np.array([0, 0, 1, 1], dtype='float32'), pos) pos = [self.vertices[pos*3], self.vertices[pos*3",
"self.rotation = 'Pio è un figo' def loadPath(self, position): #",
"* class Path: # position=[x1, y1, z1, ..., xn, yn,",
"r_versor) r_versor = np.dot(get_rot(self.rotation[index][2], 2), r_versor) t_versor = np.dot(get_traslation(self.vertices[index*3], self.vertices[index*3",
"self.yvertices.extend([yversor[0], yversor[1], yversor[2]]) self.zvertices.extend(pos) self.zvertices.extend([zversor[0], zversor[1], zversor[2]]) #setting xline bufer",
"index): r_versor = np.dot(get_rot(self.rotation[index][0], 0), versor) r_versor = np.dot(get_rot(self.rotation[index][1], 1),",
"self.patharray = glGenVertexArrays(1) glBindVertexArray(self.patharray) self.lineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.lineBuffer) glBufferData(GL_ARRAY_BUFFER,",
"path glBindVertexArray(self.patharray) glUseProgram(self.path_shader) modelLocation = glGetUniformLocation(self.path_shader, 'model') viewLocation = glGetUniformLocation(self.path_shader,",
"un figo': glBindVertexArray(self.xpatharray) glUseProgram(self.xpath_shader) modelLocation = glGetUniformLocation(self.xpath_shader, 'model') viewLocation =",
"1], dtype='float32'), pos) pos = [self.vertices[pos*3], self.vertices[pos*3 + 1], self.vertices[pos*3",
"= glGetUniformLocation(self.zpath_shader, 'model') viewLocation = glGetUniformLocation(self.zpath_shader, 'view') projectionLocation = glGetUniformLocation(self.zpath_shader,",
"'view') projectionLocation = glGetUniformLocation(self.zpath_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model) glUniformMatrix4fv(viewLocation,",
"glBindVertexArray(self.xpatharray) glUseProgram(self.xpath_shader) modelLocation = glGetUniformLocation(self.xpath_shader, 'model') viewLocation = glGetUniformLocation(self.xpath_shader, 'view')",
"= np.dot(get_rot(self.rotation[index][2], 2), r_versor) t_versor = np.dot(get_traslation(self.vertices[index*3], self.vertices[index*3 + 1],",
"self.loadRotation(rotation) else: self.rotation = 'Pio è un figo' def loadPath(self,",
"zn] ; rotation = [[Rx1, Ry1, Rz1], ..., [Rxn, Ryn,",
"Ryn, Rzn]] def __init__(self, position, rotation=None): self.loadPath(position) if rotation: assert",
"glGetUniformLocation(self.path_shader, 'model') viewLocation = glGetUniformLocation(self.path_shader, 'view') projectionLocation = glGetUniformLocation(self.path_shader, 'projection')",
"the ylines glBindVertexArray(self.ypatharray) glUseProgram(self.ypath_shader) modelLocation = glGetUniformLocation(self.ypath_shader, 'model') viewLocation =",
"zlines glBindVertexArray(self.zpatharray) glUseProgram(self.zpath_shader) modelLocation = glGetUniformLocation(self.zpath_shader, 'model') viewLocation = glGetUniformLocation(self.zpath_shader,",
"np from ctypes import c_void_p from .Shader import Shader from",
"= glGenVertexArrays(1) glBindVertexArray(self.patharray) self.lineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.lineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.vertices,",
"GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * 4, c_void_p(0)) def",
"Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\zpathfrag.glsl').shaderProgram # setting versors self.xvertices = [] self.yvertices =",
"rotation): self.rotation = rotation # compiling shader self.xpath_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl',",
"glEnableVertexAttribArray(0) glDrawArrays(GL_LINE_STRIP, 0, int(len(self.vertices)/3)) glDisableVertexAttribArray(0) # rendering the xlines if",
"glGenVertexArrays(1) glBindVertexArray(self.xpatharray) self.xlineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.xlineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.xvertices, dtype='float32'),",
"GL_TRUE, view) glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, proj) glEnableVertexAttribArray(0) glDrawArrays(GL_LINES, 0, int(len(self.xvertices)/3))",
"= glGetUniformLocation(self.ypath_shader, 'view') projectionLocation = glGetUniformLocation(self.ypath_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE,",
"[[Rx1, Ry1, Rz1], ..., [Rxn, Ryn, Rzn]] def __init__(self, position,",
"# compiling shader self.xpath_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\xpathfrag.glsl').shaderProgram self.ypath_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl',",
".transforms import * from OpenGL.GL import * class Path: #",
"glGenVertexArrays(1) glBindVertexArray(self.ypatharray) self.ylineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.ylineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.yvertices, dtype='float32'),",
"self.vertices[pos*3 + 2]] self.xvertices.extend(pos) self.xvertices.extend([xversor[0], xversor[1], xversor[2]]) self.yvertices.extend(pos) self.yvertices.extend([yversor[0], yversor[1],",
"* 4, c_void_p(0)) def getVersorAtTime(self, versor, index): r_versor = np.dot(get_rot(self.rotation[index][0],",
"modelLocation = glGetUniformLocation(self.zpath_shader, 'model') viewLocation = glGetUniformLocation(self.zpath_shader, 'view') projectionLocation =",
"model = np.identity(4) view = camera.view proj = camera.proj #",
".Shader import Shader from .transforms import * from OpenGL.GL import",
"else: self.rotation = 'Pio è un figo' def loadPath(self, position):",
"int(len(self.xvertices)/3)) glDisableVertexAttribArray(0) # rendering the ylines glBindVertexArray(self.ypatharray) glUseProgram(self.ypath_shader) modelLocation =",
"'src\\\\shaders\\\\path\\\\pathfrag.glsl').shaderProgram # setting path buffer self.vertices = position self.patharray =",
"viewLocation = glGetUniformLocation(self.ypath_shader, 'view') projectionLocation = glGetUniformLocation(self.ypath_shader, 'projection') glUniformMatrix4fv(modelLocation, 1,",
"class Path: # position=[x1, y1, z1, ..., xn, yn, zn]",
"è un figo' def loadPath(self, position): # compiling shader self.path_shader",
"def __init__(self, position, rotation=None): self.loadPath(position) if rotation: assert len(position) ==",
"def loadRotation(self, rotation): self.rotation = rotation # compiling shader self.xpath_shader",
"glGetUniformLocation(self.path_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model) glUniformMatrix4fv(viewLocation, 1, GL_TRUE, view)",
"'model') viewLocation = glGetUniformLocation(self.zpath_shader, 'view') projectionLocation = glGetUniformLocation(self.zpath_shader, 'projection') glUniformMatrix4fv(modelLocation,",
"glBindVertexArray(self.ypatharray) glUseProgram(self.ypath_shader) modelLocation = glGetUniformLocation(self.ypath_shader, 'model') viewLocation = glGetUniformLocation(self.ypath_shader, 'view')",
"glBindBuffer(GL_ARRAY_BUFFER, self.zlineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.zvertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE,",
"# rendering the ylines glBindVertexArray(self.ypatharray) glUseProgram(self.ypath_shader) modelLocation = glGetUniformLocation(self.ypath_shader, 'model')",
"1], self.vertices[pos*3 + 2]] self.xvertices.extend(pos) self.xvertices.extend([xversor[0], xversor[1], xversor[2]]) self.yvertices.extend(pos) self.yvertices.extend([yversor[0],",
"GL_FALSE, 3 * 4, c_void_p(0)) #setting xline bufer self.zpatharray =",
"glGetUniformLocation(self.xpath_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model) glUniformMatrix4fv(viewLocation, 1, GL_TRUE, view)",
"len(position) == len(rotation) * 3 self.loadRotation(rotation) else: self.rotation = 'Pio",
"3 * 4, c_void_p(0)) #setting xline bufer self.zpatharray = glGenVertexArrays(1)",
"if rotation: assert len(position) == len(rotation) * 3 self.loadRotation(rotation) else:",
"; rotation = [[Rx1, Ry1, Rz1], ..., [Rxn, Ryn, Rzn]]",
"getVersorAtTime(self, versor, index): r_versor = np.dot(get_rot(self.rotation[index][0], 0), versor) r_versor =",
"= self.getVersorAtTime(np.array([1, 0, 0, 1], dtype='float32'), pos) yversor = self.getVersorAtTime(np.array([0,",
"= glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.zlineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.zvertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3,",
"glBufferData(GL_ARRAY_BUFFER, np.array(self.xvertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 *",
"zversor[2]]) #setting xline bufer self.xpatharray = glGenVertexArrays(1) glBindVertexArray(self.xpatharray) self.xlineBuffer =",
"GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * 4, c_void_p(0)) #",
"GL_FALSE, 3 * 4, c_void_p(0)) # setting yline buffer self.ypatharray",
"4, c_void_p(0)) # setting yline buffer self.ypatharray = glGenVertexArrays(1) glBindVertexArray(self.ypatharray)",
"bufer self.zpatharray = glGenVertexArrays(1) glBindVertexArray(self.zpatharray) self.zlineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.zlineBuffer)",
"[Rxn, Ryn, Rzn]] def __init__(self, position, rotation=None): self.loadPath(position) if rotation:",
"= [self.vertices[pos*3], self.vertices[pos*3 + 1], self.vertices[pos*3 + 2]] self.xvertices.extend(pos) self.xvertices.extend([xversor[0],",
"3 self.loadRotation(rotation) else: self.rotation = 'Pio è un figo' def",
"'view') projectionLocation = glGetUniformLocation(self.path_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model) glUniformMatrix4fv(viewLocation,",
"for pos in range(len(rotation)): xversor = self.getVersorAtTime(np.array([1, 0, 0, 1],",
"position=[x1, y1, z1, ..., xn, yn, zn] ; rotation =",
"self.getVersorAtTime(np.array([1, 0, 0, 1], dtype='float32'), pos) yversor = self.getVersorAtTime(np.array([0, 1,",
"'model') viewLocation = glGetUniformLocation(self.ypath_shader, 'view') projectionLocation = glGetUniformLocation(self.ypath_shader, 'projection') glUniformMatrix4fv(modelLocation,",
"int(len(self.vertices)/3)) glDisableVertexAttribArray(0) # rendering the xlines if self.rotation != 'Pio",
"1, GL_TRUE, model) glUniformMatrix4fv(viewLocation, 1, GL_TRUE, view) glUniformMatrix4fv(projectionLocation, 1, GL_FALSE,",
"3, GL_FLOAT, GL_FALSE, 3 * 4, c_void_p(0)) #setting xline bufer",
"1, 0, 1], dtype='float32'), pos) zversor = self.getVersorAtTime(np.array([0, 0, 1,",
"self.vertices[pos*3 + 1], self.vertices[pos*3 + 2]] self.xvertices.extend(pos) self.xvertices.extend([xversor[0], xversor[1], xversor[2]])",
"np.identity(4) view = camera.view proj = camera.proj # rendering the",
"glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * 4, c_void_p(0)) # setting",
"self.yvertices.extend(pos) self.yvertices.extend([yversor[0], yversor[1], yversor[2]]) self.zvertices.extend(pos) self.zvertices.extend([zversor[0], zversor[1], zversor[2]]) #setting xline",
"Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\pathfrag.glsl').shaderProgram # setting path buffer self.vertices = position self.patharray",
"4, c_void_p(0)) #setting xline bufer self.zpatharray = glGenVertexArrays(1) glBindVertexArray(self.zpatharray) self.zlineBuffer",
"= np.identity(4) view = camera.view proj = camera.proj # rendering",
"# rendering the zlines glBindVertexArray(self.zpatharray) glUseProgram(self.zpath_shader) modelLocation = glGetUniformLocation(self.zpath_shader, 'model')",
"rendering the zlines glBindVertexArray(self.zpatharray) glUseProgram(self.zpath_shader) modelLocation = glGetUniformLocation(self.zpath_shader, 'model') viewLocation",
"np.dot(get_rot(self.rotation[index][1], 1), r_versor) r_versor = np.dot(get_rot(self.rotation[index][2], 2), r_versor) t_versor =",
"renderPath(self, camera): model = np.identity(4) view = camera.view proj =",
"c_void_p(0)) # setting yline buffer self.ypatharray = glGenVertexArrays(1) glBindVertexArray(self.ypatharray) self.ylineBuffer",
"figo' def loadPath(self, position): # compiling shader self.path_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl',",
"dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * 4, c_void_p(0))",
"1, GL_FALSE, proj) glEnableVertexAttribArray(0) glDrawArrays(GL_LINES, 0, int(len(self.xvertices)/3)) glDisableVertexAttribArray(0) # rendering",
"def loadPath(self, position): # compiling shader self.path_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\pathfrag.glsl').shaderProgram",
"..., [Rxn, Ryn, Rzn]] def __init__(self, position, rotation=None): self.loadPath(position) if",
"position): # compiling shader self.path_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\pathfrag.glsl').shaderProgram # setting",
"glBindBuffer(GL_ARRAY_BUFFER, self.ylineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.yvertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE,",
"GL_TRUE, view) glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, proj) glEnableVertexAttribArray(0) glDrawArrays(GL_LINE_STRIP, 0, int(len(self.vertices)/3))",
"the zlines glBindVertexArray(self.zpatharray) glUseProgram(self.zpath_shader) modelLocation = glGetUniformLocation(self.zpath_shader, 'model') viewLocation =",
"compiling shader self.xpath_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\xpathfrag.glsl').shaderProgram self.ypath_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\ypathfrag.glsl').shaderProgram",
"loadPath(self, position): # compiling shader self.path_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\pathfrag.glsl').shaderProgram #",
"modelLocation = glGetUniformLocation(self.ypath_shader, 'model') viewLocation = glGetUniformLocation(self.ypath_shader, 'view') projectionLocation =",
"viewLocation = glGetUniformLocation(self.path_shader, 'view') projectionLocation = glGetUniformLocation(self.path_shader, 'projection') glUniformMatrix4fv(modelLocation, 1,",
"projectionLocation = glGetUniformLocation(self.path_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model) glUniformMatrix4fv(viewLocation, 1,",
"0, 1, 1], dtype='float32'), pos) pos = [self.vertices[pos*3], self.vertices[pos*3 +",
"1, 1], dtype='float32'), pos) pos = [self.vertices[pos*3], self.vertices[pos*3 + 1],",
"assert len(position) == len(rotation) * 3 self.loadRotation(rotation) else: self.rotation =",
"projectionLocation = glGetUniformLocation(self.xpath_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model) glUniformMatrix4fv(viewLocation, 1,",
"len(rotation) * 3 self.loadRotation(rotation) else: self.rotation = 'Pio è un",
"glBindVertexArray(self.xpatharray) self.xlineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.xlineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.xvertices, dtype='float32'), GL_STATIC_DRAW)",
"glBindVertexArray(self.patharray) glUseProgram(self.path_shader) modelLocation = glGetUniformLocation(self.path_shader, 'model') viewLocation = glGetUniformLocation(self.path_shader, 'view')",
"1], self.vertices[index*3 + 2]), r_versor) return t_versor def renderPath(self, camera):",
"= glGetUniformLocation(self.ypath_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model) glUniformMatrix4fv(viewLocation, 1, GL_TRUE,",
"proj = camera.proj # rendering the path glBindVertexArray(self.patharray) glUseProgram(self.path_shader) modelLocation",
"self.zvertices.extend(pos) self.zvertices.extend([zversor[0], zversor[1], zversor[2]]) #setting xline bufer self.xpatharray = glGenVertexArrays(1)",
"3 * 4, c_void_p(0)) def getVersorAtTime(self, versor, index): r_versor =",
"self.xlineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.xlineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.xvertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0,",
"= glGetUniformLocation(self.ypath_shader, 'model') viewLocation = glGetUniformLocation(self.ypath_shader, 'view') projectionLocation = glGetUniformLocation(self.ypath_shader,",
"glGetUniformLocation(self.ypath_shader, 'view') projectionLocation = glGetUniformLocation(self.ypath_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model)",
"= np.dot(get_rot(self.rotation[index][1], 1), r_versor) r_versor = np.dot(get_rot(self.rotation[index][2], 2), r_versor) t_versor",
"GL_FALSE, 3 * 4, c_void_p(0)) def loadRotation(self, rotation): self.rotation =",
"xline bufer self.zpatharray = glGenVertexArrays(1) glBindVertexArray(self.zpatharray) self.zlineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER,",
"glUniformMatrix4fv(viewLocation, 1, GL_TRUE, view) glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, proj) glEnableVertexAttribArray(0) glDrawArrays(GL_LINES,",
"* 4, c_void_p(0)) def loadRotation(self, rotation): self.rotation = rotation #",
"glGetUniformLocation(self.zpath_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model) glUniformMatrix4fv(viewLocation, 1, GL_TRUE, view)",
"np.array(self.yvertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * 4,",
"def renderPath(self, camera): model = np.identity(4) view = camera.view proj",
"glBufferData(GL_ARRAY_BUFFER, np.array(self.zvertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 *",
"compiling shader self.path_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\pathfrag.glsl').shaderProgram # setting path buffer",
"glBindBuffer(GL_ARRAY_BUFFER, self.lineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.vertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE,",
"= Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\zpathfrag.glsl').shaderProgram # setting versors self.xvertices = [] self.yvertices",
"t_versor def renderPath(self, camera): model = np.identity(4) view = camera.view",
"position, rotation=None): self.loadPath(position) if rotation: assert len(position) == len(rotation) *",
"self.xvertices.extend([xversor[0], xversor[1], xversor[2]]) self.yvertices.extend(pos) self.yvertices.extend([yversor[0], yversor[1], yversor[2]]) self.zvertices.extend(pos) self.zvertices.extend([zversor[0], zversor[1],",
"np.array(self.zvertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * 4,",
"1], dtype='float32'), pos) zversor = self.getVersorAtTime(np.array([0, 0, 1, 1], dtype='float32'),",
"[] self.zvertices = [] for pos in range(len(rotation)): xversor =",
"= glGetUniformLocation(self.xpath_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model) glUniformMatrix4fv(viewLocation, 1, GL_TRUE,",
"self.loadPath(position) if rotation: assert len(position) == len(rotation) * 3 self.loadRotation(rotation)",
"glDisableVertexAttribArray(0) # rendering the zlines glBindVertexArray(self.zpatharray) glUseProgram(self.zpath_shader) modelLocation = glGetUniformLocation(self.zpath_shader,",
"Ry1, Rz1], ..., [Rxn, Ryn, Rzn]] def __init__(self, position, rotation=None):",
"glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.zlineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.zvertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT,",
"glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * 4, c_void_p(0)) #setting xline",
"self.zpatharray = glGenVertexArrays(1) glBindVertexArray(self.zpatharray) self.zlineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.zlineBuffer) glBufferData(GL_ARRAY_BUFFER,",
"self.ylineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.ylineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.yvertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0,",
"== len(rotation) * 3 self.loadRotation(rotation) else: self.rotation = 'Pio è",
"= glGetUniformLocation(self.zpath_shader, 'view') projectionLocation = glGetUniformLocation(self.zpath_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE,",
"= glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.xlineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.xvertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3,",
"glUseProgram(self.xpath_shader) modelLocation = glGetUniformLocation(self.xpath_shader, 'model') viewLocation = glGetUniformLocation(self.xpath_shader, 'view') projectionLocation",
"buffer self.vertices = position self.patharray = glGenVertexArrays(1) glBindVertexArray(self.patharray) self.lineBuffer =",
"glBufferData(GL_ARRAY_BUFFER, np.array(self.yvertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 *",
"glBindVertexArray(self.zpatharray) glUseProgram(self.zpath_shader) modelLocation = glGetUniformLocation(self.zpath_shader, 'model') viewLocation = glGetUniformLocation(self.zpath_shader, 'view')",
"'src\\\\shaders\\\\path\\\\ypathfrag.glsl').shaderProgram self.zpath_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\zpathfrag.glsl').shaderProgram # setting versors self.xvertices =",
"self.vertices[index*3 + 1], self.vertices[index*3 + 2]), r_versor) return t_versor def",
"= camera.proj # rendering the path glBindVertexArray(self.patharray) glUseProgram(self.path_shader) modelLocation =",
"# setting path buffer self.vertices = position self.patharray = glGenVertexArrays(1)",
"OpenGL.GL import * class Path: # position=[x1, y1, z1, ...,",
"= Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\xpathfrag.glsl').shaderProgram self.ypath_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\ypathfrag.glsl').shaderProgram self.zpath_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl',",
"projectionLocation = glGetUniformLocation(self.zpath_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model) glUniformMatrix4fv(viewLocation, 1,",
"dtype='float32'), pos) pos = [self.vertices[pos*3], self.vertices[pos*3 + 1], self.vertices[pos*3 +",
"import numpy as np from ctypes import c_void_p from .Shader",
"1, GL_TRUE, view) glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, proj) glEnableVertexAttribArray(0) glDrawArrays(GL_LINE_STRIP, 0,",
"= glGetUniformLocation(self.path_shader, 'view') projectionLocation = glGetUniformLocation(self.path_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE,",
"= self.getVersorAtTime(np.array([0, 1, 0, 1], dtype='float32'), pos) zversor = self.getVersorAtTime(np.array([0,",
"self.xvertices.extend(pos) self.xvertices.extend([xversor[0], xversor[1], xversor[2]]) self.yvertices.extend(pos) self.yvertices.extend([yversor[0], yversor[1], yversor[2]]) self.zvertices.extend(pos) self.zvertices.extend([zversor[0],",
"t_versor = np.dot(get_traslation(self.vertices[index*3], self.vertices[index*3 + 1], self.vertices[index*3 + 2]), r_versor)",
"[] self.yvertices = [] self.zvertices = [] for pos in",
"self.zpath_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\zpathfrag.glsl').shaderProgram # setting versors self.xvertices = []",
"the path glBindVertexArray(self.patharray) glUseProgram(self.path_shader) modelLocation = glGetUniformLocation(self.path_shader, 'model') viewLocation =",
"glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.ylineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.yvertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT,",
"glGetUniformLocation(self.xpath_shader, 'model') viewLocation = glGetUniformLocation(self.xpath_shader, 'view') projectionLocation = glGetUniformLocation(self.xpath_shader, 'projection')",
"+ 2]] self.xvertices.extend(pos) self.xvertices.extend([xversor[0], xversor[1], xversor[2]]) self.yvertices.extend(pos) self.yvertices.extend([yversor[0], yversor[1], yversor[2]])",
"GL_FLOAT, GL_FALSE, 3 * 4, c_void_p(0)) # setting yline buffer",
"glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * 4, c_void_p(0)) def loadRotation(self,",
"modelLocation = glGetUniformLocation(self.path_shader, 'model') viewLocation = glGetUniformLocation(self.path_shader, 'view') projectionLocation =",
"modelLocation = glGetUniformLocation(self.xpath_shader, 'model') viewLocation = glGetUniformLocation(self.xpath_shader, 'view') projectionLocation =",
"self.ypath_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\ypathfrag.glsl').shaderProgram self.zpath_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\zpathfrag.glsl').shaderProgram # setting",
"viewLocation = glGetUniformLocation(self.zpath_shader, 'view') projectionLocation = glGetUniformLocation(self.zpath_shader, 'projection') glUniformMatrix4fv(modelLocation, 1,",
"np.array(self.xvertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * 4,",
"3, GL_FLOAT, GL_FALSE, 3 * 4, c_void_p(0)) def loadRotation(self, rotation):",
"versor) r_versor = np.dot(get_rot(self.rotation[index][1], 1), r_versor) r_versor = np.dot(get_rot(self.rotation[index][2], 2),",
"GL_FALSE, proj) glEnableVertexAttribArray(0) glDrawArrays(GL_LINE_STRIP, 0, int(len(self.vertices)/3)) glDisableVertexAttribArray(0) # rendering the",
"0, 0, 1], dtype='float32'), pos) yversor = self.getVersorAtTime(np.array([0, 1, 0,",
"Rz1], ..., [Rxn, Ryn, Rzn]] def __init__(self, position, rotation=None): self.loadPath(position)",
"glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.lineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.vertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT,",
"1, GL_FALSE, proj) glEnableVertexAttribArray(0) glDrawArrays(GL_LINE_STRIP, 0, int(len(self.vertices)/3)) glDisableVertexAttribArray(0) # rendering",
"proj) glEnableVertexAttribArray(0) glDrawArrays(GL_LINE_STRIP, 0, int(len(self.vertices)/3)) glDisableVertexAttribArray(0) # rendering the xlines",
"'view') projectionLocation = glGetUniformLocation(self.xpath_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model) glUniformMatrix4fv(viewLocation,",
"self.path_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\pathfrag.glsl').shaderProgram # setting path buffer self.vertices =",
"pos = [self.vertices[pos*3], self.vertices[pos*3 + 1], self.vertices[pos*3 + 2]] self.xvertices.extend(pos)",
"range(len(rotation)): xversor = self.getVersorAtTime(np.array([1, 0, 0, 1], dtype='float32'), pos) yversor",
"self.ylineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.yvertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3",
"Path: # position=[x1, y1, z1, ..., xn, yn, zn] ;",
"setting path buffer self.vertices = position self.patharray = glGenVertexArrays(1) glBindVertexArray(self.patharray)",
"figo': glBindVertexArray(self.xpatharray) glUseProgram(self.xpath_shader) modelLocation = glGetUniformLocation(self.xpath_shader, 'model') viewLocation = glGetUniformLocation(self.xpath_shader,",
"import c_void_p from .Shader import Shader from .transforms import *",
"0, int(len(self.xvertices)/3)) glDisableVertexAttribArray(0) # rendering the ylines glBindVertexArray(self.ypatharray) glUseProgram(self.ypath_shader) modelLocation",
"self.zvertices.extend([zversor[0], zversor[1], zversor[2]]) #setting xline bufer self.xpatharray = glGenVertexArrays(1) glBindVertexArray(self.xpatharray)",
"0, int(len(self.xvertices)/3)) glDisableVertexAttribArray(0) # rendering the zlines glBindVertexArray(self.zpatharray) glUseProgram(self.zpath_shader) modelLocation",
"4, c_void_p(0)) def loadRotation(self, rotation): self.rotation = rotation # compiling",
"glBindBuffer(GL_ARRAY_BUFFER, self.xlineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.xvertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE,",
"= np.dot(get_traslation(self.vertices[index*3], self.vertices[index*3 + 1], self.vertices[index*3 + 2]), r_versor) return",
"ylines glBindVertexArray(self.ypatharray) glUseProgram(self.ypath_shader) modelLocation = glGetUniformLocation(self.ypath_shader, 'model') viewLocation = glGetUniformLocation(self.ypath_shader,",
"loadRotation(self, rotation): self.rotation = rotation # compiling shader self.xpath_shader =",
"1, GL_TRUE, view) glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, proj) glEnableVertexAttribArray(0) glDrawArrays(GL_LINES, 0,",
"= glGenVertexArrays(1) glBindVertexArray(self.ypatharray) self.ylineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.ylineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.yvertices,",
"glBindVertexArray(self.patharray) self.lineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.lineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.vertices, dtype='float32'), GL_STATIC_DRAW)",
"glUseProgram(self.path_shader) modelLocation = glGetUniformLocation(self.path_shader, 'model') viewLocation = glGetUniformLocation(self.path_shader, 'view') projectionLocation",
"ctypes import c_void_p from .Shader import Shader from .transforms import",
"glUseProgram(self.zpath_shader) modelLocation = glGetUniformLocation(self.zpath_shader, 'model') viewLocation = glGetUniformLocation(self.zpath_shader, 'view') projectionLocation",
"+ 2]), r_versor) return t_versor def renderPath(self, camera): model =",
"= glGetUniformLocation(self.path_shader, 'model') viewLocation = glGetUniformLocation(self.path_shader, 'view') projectionLocation = glGetUniformLocation(self.path_shader,",
"from OpenGL.GL import * class Path: # position=[x1, y1, z1,",
"'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model) glUniformMatrix4fv(viewLocation, 1, GL_TRUE, view) glUniformMatrix4fv(projectionLocation,",
"camera): model = np.identity(4) view = camera.view proj = camera.proj",
"from ctypes import c_void_p from .Shader import Shader from .transforms",
"glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model) glUniformMatrix4fv(viewLocation, 1, GL_TRUE, view) glUniformMatrix4fv(projectionLocation, 1,",
"= [] self.zvertices = [] for pos in range(len(rotation)): xversor",
"Shader from .transforms import * from OpenGL.GL import * class",
"2]), r_versor) return t_versor def renderPath(self, camera): model = np.identity(4)",
"zversor[1], zversor[2]]) #setting xline bufer self.xpatharray = glGenVertexArrays(1) glBindVertexArray(self.xpatharray) self.xlineBuffer",
"self.ypatharray = glGenVertexArrays(1) glBindVertexArray(self.ypatharray) self.ylineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.ylineBuffer) glBufferData(GL_ARRAY_BUFFER,",
"numpy as np from ctypes import c_void_p from .Shader import",
"= glGenVertexArrays(1) glBindVertexArray(self.zpatharray) self.zlineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.zlineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.zvertices,",
"glEnableVertexAttribArray(0) glDrawArrays(GL_LINES, 0, int(len(self.xvertices)/3)) glDisableVertexAttribArray(0) # rendering the zlines glBindVertexArray(self.zpatharray)",
"self.zlineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.zvertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3",
"glDrawArrays(GL_LINES, 0, int(len(self.xvertices)/3)) glDisableVertexAttribArray(0) # rendering the ylines glBindVertexArray(self.ypatharray) glUseProgram(self.ypath_shader)",
"np.array(self.vertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * 4,",
"1), r_versor) r_versor = np.dot(get_rot(self.rotation[index][2], 2), r_versor) t_versor = np.dot(get_traslation(self.vertices[index*3],",
"GL_FALSE, proj) glEnableVertexAttribArray(0) glDrawArrays(GL_LINES, 0, int(len(self.xvertices)/3)) glDisableVertexAttribArray(0) # rendering the",
"z1, ..., xn, yn, zn] ; rotation = [[Rx1, Ry1,",
"# setting versors self.xvertices = [] self.yvertices = [] self.zvertices",
"# compiling shader self.path_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\pathfrag.glsl').shaderProgram # setting path",
"= glGetUniformLocation(self.path_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model) glUniformMatrix4fv(viewLocation, 1, GL_TRUE,",
"pos) zversor = self.getVersorAtTime(np.array([0, 0, 1, 1], dtype='float32'), pos) pos",
"= [[Rx1, Ry1, Rz1], ..., [Rxn, Ryn, Rzn]] def __init__(self,",
"self.xlineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.xvertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3",
"3 * 4, c_void_p(0)) # setting yline buffer self.ypatharray =",
"rendering the path glBindVertexArray(self.patharray) glUseProgram(self.path_shader) modelLocation = glGetUniformLocation(self.path_shader, 'model') viewLocation",
"* 3 self.loadRotation(rotation) else: self.rotation = 'Pio è un figo'",
"dtype='float32'), pos) zversor = self.getVersorAtTime(np.array([0, 0, 1, 1], dtype='float32'), pos)",
"'Pio è un figo' def loadPath(self, position): # compiling shader",
"= camera.view proj = camera.proj # rendering the path glBindVertexArray(self.patharray)",
"self.vertices[index*3 + 2]), r_versor) return t_versor def renderPath(self, camera): model",
"..., xn, yn, zn] ; rotation = [[Rx1, Ry1, Rz1],",
"model) glUniformMatrix4fv(viewLocation, 1, GL_TRUE, view) glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, proj) glEnableVertexAttribArray(0)",
"# position=[x1, y1, z1, ..., xn, yn, zn] ; rotation",
"= glGetUniformLocation(self.zpath_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model) glUniformMatrix4fv(viewLocation, 1, GL_TRUE,",
"c_void_p(0)) def getVersorAtTime(self, versor, index): r_versor = np.dot(get_rot(self.rotation[index][0], 0), versor)",
"versor, index): r_versor = np.dot(get_rot(self.rotation[index][0], 0), versor) r_versor = np.dot(get_rot(self.rotation[index][1],",
"glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * 4, c_void_p(0)) def getVersorAtTime(self,",
"# rendering the path glBindVertexArray(self.patharray) glUseProgram(self.path_shader) modelLocation = glGetUniformLocation(self.path_shader, 'model')",
"è un figo': glBindVertexArray(self.xpatharray) glUseProgram(self.xpath_shader) modelLocation = glGetUniformLocation(self.xpath_shader, 'model') viewLocation",
"self.yvertices = [] self.zvertices = [] for pos in range(len(rotation)):",
"2]] self.xvertices.extend(pos) self.xvertices.extend([xversor[0], xversor[1], xversor[2]]) self.yvertices.extend(pos) self.yvertices.extend([yversor[0], yversor[1], yversor[2]]) self.zvertices.extend(pos)",
"pos) pos = [self.vertices[pos*3], self.vertices[pos*3 + 1], self.vertices[pos*3 + 2]]",
"import * from OpenGL.GL import * class Path: # position=[x1,",
"'model') viewLocation = glGetUniformLocation(self.xpath_shader, 'view') projectionLocation = glGetUniformLocation(self.xpath_shader, 'projection') glUniformMatrix4fv(modelLocation,",
"= glGetUniformLocation(self.xpath_shader, 'view') projectionLocation = glGetUniformLocation(self.xpath_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE,",
"glGetUniformLocation(self.ypath_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model) glUniformMatrix4fv(viewLocation, 1, GL_TRUE, view)",
"un figo' def loadPath(self, position): # compiling shader self.path_shader =",
"glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, proj) glEnableVertexAttribArray(0) glDrawArrays(GL_LINE_STRIP, 0, int(len(self.vertices)/3)) glDisableVertexAttribArray(0) #",
"glUseProgram(self.ypath_shader) modelLocation = glGetUniformLocation(self.ypath_shader, 'model') viewLocation = glGetUniformLocation(self.ypath_shader, 'view') projectionLocation",
"glGenVertexArrays(1) glBindVertexArray(self.patharray) self.lineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.lineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.vertices, dtype='float32'),",
"versors self.xvertices = [] self.yvertices = [] self.zvertices = []",
"# setting yline buffer self.ypatharray = glGenVertexArrays(1) glBindVertexArray(self.ypatharray) self.ylineBuffer =",
"path buffer self.vertices = position self.patharray = glGenVertexArrays(1) glBindVertexArray(self.patharray) self.lineBuffer",
"glGetUniformLocation(self.ypath_shader, 'model') viewLocation = glGetUniformLocation(self.ypath_shader, 'view') projectionLocation = glGetUniformLocation(self.ypath_shader, 'projection')",
"self.rotation != 'Pio è un figo': glBindVertexArray(self.xpatharray) glUseProgram(self.xpath_shader) modelLocation =",
"import Shader from .transforms import * from OpenGL.GL import *",
"self.vertices = position self.patharray = glGenVertexArrays(1) glBindVertexArray(self.patharray) self.lineBuffer = glGenBuffers(1)",
"!= 'Pio è un figo': glBindVertexArray(self.xpatharray) glUseProgram(self.xpath_shader) modelLocation = glGetUniformLocation(self.xpath_shader,",
"return t_versor def renderPath(self, camera): model = np.identity(4) view =",
"view) glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, proj) glEnableVertexAttribArray(0) glDrawArrays(GL_LINE_STRIP, 0, int(len(self.vertices)/3)) glDisableVertexAttribArray(0)",
"self.xpatharray = glGenVertexArrays(1) glBindVertexArray(self.xpatharray) self.xlineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.xlineBuffer) glBufferData(GL_ARRAY_BUFFER,",
"as np from ctypes import c_void_p from .Shader import Shader",
"np.dot(get_rot(self.rotation[index][0], 0), versor) r_versor = np.dot(get_rot(self.rotation[index][1], 1), r_versor) r_versor =",
"view) glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, proj) glEnableVertexAttribArray(0) glDrawArrays(GL_LINES, 0, int(len(self.xvertices)/3)) glDisableVertexAttribArray(0)",
"yversor = self.getVersorAtTime(np.array([0, 1, 0, 1], dtype='float32'), pos) zversor =",
"self.lineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.lineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.vertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0,",
"= glGenVertexArrays(1) glBindVertexArray(self.xpatharray) self.xlineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.xlineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.xvertices,",
"= position self.patharray = glGenVertexArrays(1) glBindVertexArray(self.patharray) self.lineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER,",
"def getVersorAtTime(self, versor, index): r_versor = np.dot(get_rot(self.rotation[index][0], 0), versor) r_versor",
"'model') viewLocation = glGetUniformLocation(self.path_shader, 'view') projectionLocation = glGetUniformLocation(self.path_shader, 'projection') glUniformMatrix4fv(modelLocation,",
"__init__(self, position, rotation=None): self.loadPath(position) if rotation: assert len(position) == len(rotation)",
"glGenVertexArrays(1) glBindVertexArray(self.zpatharray) self.zlineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.zlineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.zvertices, dtype='float32'),",
"shader self.path_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\pathfrag.glsl').shaderProgram # setting path buffer self.vertices",
"xversor[1], xversor[2]]) self.yvertices.extend(pos) self.yvertices.extend([yversor[0], yversor[1], yversor[2]]) self.zvertices.extend(pos) self.zvertices.extend([zversor[0], zversor[1], zversor[2]])",
"= Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\ypathfrag.glsl').shaderProgram self.zpath_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\zpathfrag.glsl').shaderProgram # setting versors",
"* 4, c_void_p(0)) #setting xline bufer self.zpatharray = glGenVertexArrays(1) glBindVertexArray(self.zpatharray)",
"= glGetUniformLocation(self.xpath_shader, 'model') viewLocation = glGetUniformLocation(self.xpath_shader, 'view') projectionLocation = glGetUniformLocation(self.xpath_shader,",
"r_versor) t_versor = np.dot(get_traslation(self.vertices[index*3], self.vertices[index*3 + 1], self.vertices[index*3 + 2]),",
"glEnableVertexAttribArray(0) glDrawArrays(GL_LINES, 0, int(len(self.xvertices)/3)) glDisableVertexAttribArray(0) # rendering the ylines glBindVertexArray(self.ypatharray)",
"camera.proj # rendering the path glBindVertexArray(self.patharray) glUseProgram(self.path_shader) modelLocation = glGetUniformLocation(self.path_shader,",
"glGetUniformLocation(self.zpath_shader, 'view') projectionLocation = glGetUniformLocation(self.zpath_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model)",
"self.lineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.vertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3",
"0, int(len(self.vertices)/3)) glDisableVertexAttribArray(0) # rendering the xlines if self.rotation !=",
"= 'Pio è un figo' def loadPath(self, position): # compiling",
"c_void_p(0)) def loadRotation(self, rotation): self.rotation = rotation # compiling shader",
"= glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.ylineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.yvertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3,",
"proj) glEnableVertexAttribArray(0) glDrawArrays(GL_LINES, 0, int(len(self.xvertices)/3)) glDisableVertexAttribArray(0) # rendering the ylines",
"yversor[1], yversor[2]]) self.zvertices.extend(pos) self.zvertices.extend([zversor[0], zversor[1], zversor[2]]) #setting xline bufer self.xpatharray",
"xversor[2]]) self.yvertices.extend(pos) self.yvertices.extend([yversor[0], yversor[1], yversor[2]]) self.zvertices.extend(pos) self.zvertices.extend([zversor[0], zversor[1], zversor[2]]) #setting",
"* 4, c_void_p(0)) # setting yline buffer self.ypatharray = glGenVertexArrays(1)",
"from .transforms import * from OpenGL.GL import * class Path:",
"xlines if self.rotation != 'Pio è un figo': glBindVertexArray(self.xpatharray) glUseProgram(self.xpath_shader)",
"2), r_versor) t_versor = np.dot(get_traslation(self.vertices[index*3], self.vertices[index*3 + 1], self.vertices[index*3 +",
"1], dtype='float32'), pos) yversor = self.getVersorAtTime(np.array([0, 1, 0, 1], dtype='float32'),",
"the xlines if self.rotation != 'Pio è un figo': glBindVertexArray(self.xpatharray)",
"Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\xpathfrag.glsl').shaderProgram self.ypath_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\ypathfrag.glsl').shaderProgram self.zpath_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\zpathfrag.glsl').shaderProgram",
"rendering the xlines if self.rotation != 'Pio è un figo':",
"import * class Path: # position=[x1, y1, z1, ..., xn,",
"glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.xlineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.xvertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT,",
"GL_FLOAT, GL_FALSE, 3 * 4, c_void_p(0)) def getVersorAtTime(self, versor, index):",
"= np.dot(get_rot(self.rotation[index][0], 0), versor) r_versor = np.dot(get_rot(self.rotation[index][1], 1), r_versor) r_versor",
"self.zvertices = [] for pos in range(len(rotation)): xversor = self.getVersorAtTime(np.array([1,",
"np.dot(get_rot(self.rotation[index][2], 2), r_versor) t_versor = np.dot(get_traslation(self.vertices[index*3], self.vertices[index*3 + 1], self.vertices[index*3",
"yline buffer self.ypatharray = glGenVertexArrays(1) glBindVertexArray(self.ypatharray) self.ylineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER,",
"int(len(self.xvertices)/3)) glDisableVertexAttribArray(0) # rendering the zlines glBindVertexArray(self.zpatharray) glUseProgram(self.zpath_shader) modelLocation =",
"* from OpenGL.GL import * class Path: # position=[x1, y1,",
"self.rotation = rotation # compiling shader self.xpath_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\xpathfrag.glsl').shaderProgram",
"'view') projectionLocation = glGetUniformLocation(self.ypath_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model) glUniformMatrix4fv(viewLocation,",
"projectionLocation = glGetUniformLocation(self.ypath_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model) glUniformMatrix4fv(viewLocation, 1,",
"#setting xline bufer self.zpatharray = glGenVertexArrays(1) glBindVertexArray(self.zpatharray) self.zlineBuffer = glGenBuffers(1)",
"glGetUniformLocation(self.zpath_shader, 'model') viewLocation = glGetUniformLocation(self.zpath_shader, 'view') projectionLocation = glGetUniformLocation(self.zpath_shader, 'projection')",
"np.dot(get_traslation(self.vertices[index*3], self.vertices[index*3 + 1], self.vertices[index*3 + 2]), r_versor) return t_versor",
"glDrawArrays(GL_LINES, 0, int(len(self.xvertices)/3)) glDisableVertexAttribArray(0) # rendering the zlines glBindVertexArray(self.zpatharray) glUseProgram(self.zpath_shader)",
"glDisableVertexAttribArray(0) # rendering the xlines if self.rotation != 'Pio è",
"glGetUniformLocation(self.xpath_shader, 'view') projectionLocation = glGetUniformLocation(self.xpath_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model)",
"xversor = self.getVersorAtTime(np.array([1, 0, 0, 1], dtype='float32'), pos) yversor =",
"rotation = [[Rx1, Ry1, Rz1], ..., [Rxn, Ryn, Rzn]] def",
"glBindVertexArray(self.zpatharray) self.zlineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.zlineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.zvertices, dtype='float32'), GL_STATIC_DRAW)",
"4, c_void_p(0)) def getVersorAtTime(self, versor, index): r_versor = np.dot(get_rot(self.rotation[index][0], 0),",
"xn, yn, zn] ; rotation = [[Rx1, Ry1, Rz1], ...,",
"proj) glEnableVertexAttribArray(0) glDrawArrays(GL_LINES, 0, int(len(self.xvertices)/3)) glDisableVertexAttribArray(0) # rendering the zlines",
"Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\ypathfrag.glsl').shaderProgram self.zpath_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\zpathfrag.glsl').shaderProgram # setting versors self.xvertices",
"r_versor) return t_versor def renderPath(self, camera): model = np.identity(4) view",
"'src\\\\shaders\\\\path\\\\xpathfrag.glsl').shaderProgram self.ypath_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\ypathfrag.glsl').shaderProgram self.zpath_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\zpathfrag.glsl').shaderProgram #",
"yversor[2]]) self.zvertices.extend(pos) self.zvertices.extend([zversor[0], zversor[1], zversor[2]]) #setting xline bufer self.xpatharray =",
"glDrawArrays(GL_LINE_STRIP, 0, int(len(self.vertices)/3)) glDisableVertexAttribArray(0) # rendering the xlines if self.rotation",
"[] for pos in range(len(rotation)): xversor = self.getVersorAtTime(np.array([1, 0, 0,",
"# rendering the xlines if self.rotation != 'Pio è un",
"glBufferData(GL_ARRAY_BUFFER, np.array(self.vertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 *",
"GL_TRUE, model) glUniformMatrix4fv(viewLocation, 1, GL_TRUE, view) glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, proj)",
"rotation: assert len(position) == len(rotation) * 3 self.loadRotation(rotation) else: self.rotation",
"Rzn]] def __init__(self, position, rotation=None): self.loadPath(position) if rotation: assert len(position)",
"r_versor = np.dot(get_rot(self.rotation[index][0], 0), versor) r_versor = np.dot(get_rot(self.rotation[index][1], 1), r_versor)",
"+ 1], self.vertices[index*3 + 2]), r_versor) return t_versor def renderPath(self,",
"self.xpath_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\xpathfrag.glsl').shaderProgram self.ypath_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\ypathfrag.glsl').shaderProgram self.zpath_shader =",
"yn, zn] ; rotation = [[Rx1, Ry1, Rz1], ..., [Rxn,",
"glUniformMatrix4fv(viewLocation, 1, GL_TRUE, view) glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, proj) glEnableVertexAttribArray(0) glDrawArrays(GL_LINE_STRIP,",
"3, GL_FLOAT, GL_FALSE, 3 * 4, c_void_p(0)) def getVersorAtTime(self, versor,",
"= rotation # compiling shader self.xpath_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\xpathfrag.glsl').shaderProgram self.ypath_shader",
"shader self.xpath_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\xpathfrag.glsl').shaderProgram self.ypath_shader = Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\ypathfrag.glsl').shaderProgram self.zpath_shader",
"setting yline buffer self.ypatharray = glGenVertexArrays(1) glBindVertexArray(self.ypatharray) self.ylineBuffer = glGenBuffers(1)",
"= Shader('src\\\\shaders\\\\path\\\\pathvert.glsl', 'src\\\\shaders\\\\path\\\\pathfrag.glsl').shaderProgram # setting path buffer self.vertices = position",
"glBindVertexArray(self.ypatharray) self.ylineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.ylineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.yvertices, dtype='float32'), GL_STATIC_DRAW)",
"GL_FLOAT, GL_FALSE, 3 * 4, c_void_p(0)) def loadRotation(self, rotation): self.rotation",
"position self.patharray = glGenVertexArrays(1) glBindVertexArray(self.patharray) self.lineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.lineBuffer)",
"zversor = self.getVersorAtTime(np.array([0, 0, 1, 1], dtype='float32'), pos) pos =",
"+ 1], self.vertices[pos*3 + 2]] self.xvertices.extend(pos) self.xvertices.extend([xversor[0], xversor[1], xversor[2]]) self.yvertices.extend(pos)",
"self.xvertices = [] self.yvertices = [] self.zvertices = [] for",
"= [] for pos in range(len(rotation)): xversor = self.getVersorAtTime(np.array([1, 0,",
"self.getVersorAtTime(np.array([0, 1, 0, 1], dtype='float32'), pos) zversor = self.getVersorAtTime(np.array([0, 0,",
"pos in range(len(rotation)): xversor = self.getVersorAtTime(np.array([1, 0, 0, 1], dtype='float32'),",
"3, GL_FLOAT, GL_FALSE, 3 * 4, c_void_p(0)) # setting yline",
"'Pio è un figo': glBindVertexArray(self.xpatharray) glUseProgram(self.xpath_shader) modelLocation = glGetUniformLocation(self.xpath_shader, 'model')",
"r_versor = np.dot(get_rot(self.rotation[index][2], 2), r_versor) t_versor = np.dot(get_traslation(self.vertices[index*3], self.vertices[index*3 +",
"0, 1], dtype='float32'), pos) yversor = self.getVersorAtTime(np.array([0, 1, 0, 1],",
"setting versors self.xvertices = [] self.yvertices = [] self.zvertices =",
"dtype='float32'), pos) yversor = self.getVersorAtTime(np.array([0, 1, 0, 1], dtype='float32'), pos)",
"0, 1], dtype='float32'), pos) zversor = self.getVersorAtTime(np.array([0, 0, 1, 1],",
"c_void_p from .Shader import Shader from .transforms import * from",
"[self.vertices[pos*3], self.vertices[pos*3 + 1], self.vertices[pos*3 + 2]] self.xvertices.extend(pos) self.xvertices.extend([xversor[0], xversor[1],",
"#setting xline bufer self.xpatharray = glGenVertexArrays(1) glBindVertexArray(self.xpatharray) self.xlineBuffer = glGenBuffers(1)",
"glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, proj) glEnableVertexAttribArray(0) glDrawArrays(GL_LINES, 0, int(len(self.xvertices)/3)) glDisableVertexAttribArray(0) #",
"GL_FLOAT, GL_FALSE, 3 * 4, c_void_p(0)) #setting xline bufer self.zpatharray",
"GL_FALSE, 3 * 4, c_void_p(0)) def getVersorAtTime(self, versor, index): r_versor",
"xline bufer self.xpatharray = glGenVertexArrays(1) glBindVertexArray(self.xpatharray) self.xlineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER,",
"view = camera.view proj = camera.proj # rendering the path",
"camera.view proj = camera.proj # rendering the path glBindVertexArray(self.patharray) glUseProgram(self.path_shader)",
"r_versor = np.dot(get_rot(self.rotation[index][1], 1), r_versor) r_versor = np.dot(get_rot(self.rotation[index][2], 2), r_versor)",
"bufer self.xpatharray = glGenVertexArrays(1) glBindVertexArray(self.xpatharray) self.xlineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.xlineBuffer)",
"self.zlineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.zlineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.zvertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0,"
] |
[
"parser.add_argument( 'init_tset', type=str, help='Path to a .tsv file containing initial",
"default=DEFAULT_OUTPUT_FOLDER, help=('Output folder to write output files' f' (default: {DEFAULT_OUTPUT_FOLDER})')",
"parser.add_argument( 'cfps', type=str, help='Path to a .tsv file containing CFPS",
"description): parser = ArgumentParser( program, description, ) parser = add_arguments(parser)",
"( ArgumentParser ) from os import getcwd as os_getcwd DEFAULT_OUTPUT_FOLDER",
"CFPS parameters and features', ) parser.add_argument( 'init_tset', type=str, help='Path to",
"to a .tsv file containing normalizer set', ) parser.add_argument( 'autofluo_set',",
"'norm_set', type=str, help='Path to a .tsv file containing normalizer set',",
"help=('Output folder to write output files' f' (default: {DEFAULT_OUTPUT_FOLDER})') )",
") parser.add_argument( 'autofluo_set', type=str, help='Path to a .tsv file containing",
"well in nL' f' (default: {DEFAULT_SAMPLE_VOLUME})') ) parser.add_argument( '-of', '--output-folder',",
"parameters and features', ) parser.add_argument( 'init_tset', type=str, help='Path to a",
"= 10000 def build_args_parser( program, description): parser = ArgumentParser( program,",
"help=('Final sample volume in each well in nL' f' (default:",
"type=str, help='Path to a .tsv file containing initial training set',",
"type=str, default=DEFAULT_OUTPUT_FOLDER, help=('Output folder to write output files' f' (default:",
"program, description, ) parser = add_arguments(parser) return parser def add_arguments(parser):",
"parser.add_argument( '-of', '--output-folder', type=str, default=DEFAULT_OUTPUT_FOLDER, help=('Output folder to write output",
"type=str, help='Path to a .tsv file containing autofluorescence set', )",
"type=int, default=DEFAULT_SAMPLE_VOLUME, help=('Final sample volume in each well in nL'",
"argparse import ( ArgumentParser ) from os import getcwd as",
"'init_tset', type=str, help='Path to a .tsv file containing initial training",
"parser.add_argument( 'autofluo_set', type=str, help='Path to a .tsv file containing autofluorescence",
"help='Path to a .tsv file containing normalizer set', ) parser.add_argument(",
") parser = add_arguments(parser) return parser def add_arguments(parser): parser.add_argument( 'cfps',",
"type=str, help='Path to a .tsv file containing normalizer set', )",
"folder to write output files' f' (default: {DEFAULT_OUTPUT_FOLDER})') ) return",
"description, ) parser = add_arguments(parser) return parser def add_arguments(parser): parser.add_argument(",
"in nL' f' (default: {DEFAULT_SAMPLE_VOLUME})') ) parser.add_argument( '-of', '--output-folder', type=str,",
"add_arguments(parser): parser.add_argument( 'cfps', type=str, help='Path to a .tsv file containing",
"autofluorescence set', ) parser.add_argument( '-v', '--sample_volume', type=int, default=DEFAULT_SAMPLE_VOLUME, help=('Final sample",
"= os_getcwd() DEFAULT_SAMPLE_VOLUME = 10000 def build_args_parser( program, description): parser",
"a .tsv file containing initial training set', ) parser.add_argument( 'norm_set',",
"from os import getcwd as os_getcwd DEFAULT_OUTPUT_FOLDER = os_getcwd() DEFAULT_SAMPLE_VOLUME",
"volume in each well in nL' f' (default: {DEFAULT_SAMPLE_VOLUME})') )",
"parser.add_argument( 'norm_set', type=str, help='Path to a .tsv file containing normalizer",
"initial training set', ) parser.add_argument( 'norm_set', type=str, help='Path to a",
"containing initial training set', ) parser.add_argument( 'norm_set', type=str, help='Path to",
"(default: {DEFAULT_SAMPLE_VOLUME})') ) parser.add_argument( '-of', '--output-folder', type=str, default=DEFAULT_OUTPUT_FOLDER, help=('Output folder",
"ArgumentParser ) from os import getcwd as os_getcwd DEFAULT_OUTPUT_FOLDER =",
"and features', ) parser.add_argument( 'init_tset', type=str, help='Path to a .tsv",
"help='Path to a .tsv file containing initial training set', )",
"a .tsv file containing autofluorescence set', ) parser.add_argument( '-v', '--sample_volume',",
"containing CFPS parameters and features', ) parser.add_argument( 'init_tset', type=str, help='Path",
"file containing normalizer set', ) parser.add_argument( 'autofluo_set', type=str, help='Path to",
"to a .tsv file containing CFPS parameters and features', )",
"'autofluo_set', type=str, help='Path to a .tsv file containing autofluorescence set',",
"from argparse import ( ArgumentParser ) from os import getcwd",
"containing autofluorescence set', ) parser.add_argument( '-v', '--sample_volume', type=int, default=DEFAULT_SAMPLE_VOLUME, help=('Final",
".tsv file containing initial training set', ) parser.add_argument( 'norm_set', type=str,",
"nL' f' (default: {DEFAULT_SAMPLE_VOLUME})') ) parser.add_argument( '-of', '--output-folder', type=str, default=DEFAULT_OUTPUT_FOLDER,",
") from os import getcwd as os_getcwd DEFAULT_OUTPUT_FOLDER = os_getcwd()",
"program, description): parser = ArgumentParser( program, description, ) parser =",
"in each well in nL' f' (default: {DEFAULT_SAMPLE_VOLUME})') ) parser.add_argument(",
"file containing autofluorescence set', ) parser.add_argument( '-v', '--sample_volume', type=int, default=DEFAULT_SAMPLE_VOLUME,",
"parser = ArgumentParser( program, description, ) parser = add_arguments(parser) return",
"set', ) parser.add_argument( 'norm_set', type=str, help='Path to a .tsv file",
"import getcwd as os_getcwd DEFAULT_OUTPUT_FOLDER = os_getcwd() DEFAULT_SAMPLE_VOLUME = 10000",
"a .tsv file containing CFPS parameters and features', ) parser.add_argument(",
"help='Path to a .tsv file containing autofluorescence set', ) parser.add_argument(",
"parser def add_arguments(parser): parser.add_argument( 'cfps', type=str, help='Path to a .tsv",
"add_arguments(parser) return parser def add_arguments(parser): parser.add_argument( 'cfps', type=str, help='Path to",
"training set', ) parser.add_argument( 'norm_set', type=str, help='Path to a .tsv",
"to a .tsv file containing autofluorescence set', ) parser.add_argument( '-v',",
"to a .tsv file containing initial training set', ) parser.add_argument(",
"os_getcwd() DEFAULT_SAMPLE_VOLUME = 10000 def build_args_parser( program, description): parser =",
".tsv file containing CFPS parameters and features', ) parser.add_argument( 'init_tset',",
"features', ) parser.add_argument( 'init_tset', type=str, help='Path to a .tsv file",
") parser.add_argument( 'norm_set', type=str, help='Path to a .tsv file containing",
"= ArgumentParser( program, description, ) parser = add_arguments(parser) return parser",
"parser.add_argument( '-v', '--sample_volume', type=int, default=DEFAULT_SAMPLE_VOLUME, help=('Final sample volume in each",
"each well in nL' f' (default: {DEFAULT_SAMPLE_VOLUME})') ) parser.add_argument( '-of',",
"file containing initial training set', ) parser.add_argument( 'norm_set', type=str, help='Path",
"os import getcwd as os_getcwd DEFAULT_OUTPUT_FOLDER = os_getcwd() DEFAULT_SAMPLE_VOLUME =",
") parser.add_argument( 'init_tset', type=str, help='Path to a .tsv file containing",
") parser.add_argument( '-of', '--output-folder', type=str, default=DEFAULT_OUTPUT_FOLDER, help=('Output folder to write",
".tsv file containing normalizer set', ) parser.add_argument( 'autofluo_set', type=str, help='Path",
"ArgumentParser( program, description, ) parser = add_arguments(parser) return parser def",
"'--output-folder', type=str, default=DEFAULT_OUTPUT_FOLDER, help=('Output folder to write output files' f'",
"parser = add_arguments(parser) return parser def add_arguments(parser): parser.add_argument( 'cfps', type=str,",
"10000 def build_args_parser( program, description): parser = ArgumentParser( program, description,",
"help='Path to a .tsv file containing CFPS parameters and features',",
"set', ) parser.add_argument( 'autofluo_set', type=str, help='Path to a .tsv file",
"'cfps', type=str, help='Path to a .tsv file containing CFPS parameters",
"'-of', '--output-folder', type=str, default=DEFAULT_OUTPUT_FOLDER, help=('Output folder to write output files'",
"containing normalizer set', ) parser.add_argument( 'autofluo_set', type=str, help='Path to a",
"sample volume in each well in nL' f' (default: {DEFAULT_SAMPLE_VOLUME})')",
"a .tsv file containing normalizer set', ) parser.add_argument( 'autofluo_set', type=str,",
"set', ) parser.add_argument( '-v', '--sample_volume', type=int, default=DEFAULT_SAMPLE_VOLUME, help=('Final sample volume",
"default=DEFAULT_SAMPLE_VOLUME, help=('Final sample volume in each well in nL' f'",
"to write output files' f' (default: {DEFAULT_OUTPUT_FOLDER})') ) return parser",
"as os_getcwd DEFAULT_OUTPUT_FOLDER = os_getcwd() DEFAULT_SAMPLE_VOLUME = 10000 def build_args_parser(",
"type=str, help='Path to a .tsv file containing CFPS parameters and",
"DEFAULT_SAMPLE_VOLUME = 10000 def build_args_parser( program, description): parser = ArgumentParser(",
"import ( ArgumentParser ) from os import getcwd as os_getcwd",
"file containing CFPS parameters and features', ) parser.add_argument( 'init_tset', type=str,",
"'-v', '--sample_volume', type=int, default=DEFAULT_SAMPLE_VOLUME, help=('Final sample volume in each well",
"normalizer set', ) parser.add_argument( 'autofluo_set', type=str, help='Path to a .tsv",
".tsv file containing autofluorescence set', ) parser.add_argument( '-v', '--sample_volume', type=int,",
"'--sample_volume', type=int, default=DEFAULT_SAMPLE_VOLUME, help=('Final sample volume in each well in",
"DEFAULT_OUTPUT_FOLDER = os_getcwd() DEFAULT_SAMPLE_VOLUME = 10000 def build_args_parser( program, description):",
"return parser def add_arguments(parser): parser.add_argument( 'cfps', type=str, help='Path to a",
"def add_arguments(parser): parser.add_argument( 'cfps', type=str, help='Path to a .tsv file",
"build_args_parser( program, description): parser = ArgumentParser( program, description, ) parser",
"def build_args_parser( program, description): parser = ArgumentParser( program, description, )",
"= add_arguments(parser) return parser def add_arguments(parser): parser.add_argument( 'cfps', type=str, help='Path",
") parser.add_argument( '-v', '--sample_volume', type=int, default=DEFAULT_SAMPLE_VOLUME, help=('Final sample volume in",
"getcwd as os_getcwd DEFAULT_OUTPUT_FOLDER = os_getcwd() DEFAULT_SAMPLE_VOLUME = 10000 def",
"f' (default: {DEFAULT_SAMPLE_VOLUME})') ) parser.add_argument( '-of', '--output-folder', type=str, default=DEFAULT_OUTPUT_FOLDER, help=('Output",
"{DEFAULT_SAMPLE_VOLUME})') ) parser.add_argument( '-of', '--output-folder', type=str, default=DEFAULT_OUTPUT_FOLDER, help=('Output folder to",
"os_getcwd DEFAULT_OUTPUT_FOLDER = os_getcwd() DEFAULT_SAMPLE_VOLUME = 10000 def build_args_parser( program,"
] |
[
"x = float(input()) prop_2 = -(x**2) / math.factorial(2) prop_3 =",
"= float(1 + prop_2 + prop_3 + prop_4) print(prop_2) print(prop_3)",
"math.factorial(2) prop_3 = (x**4) / math.factorial(4) prop_4 = -(x**6) /",
"/ math.factorial(2) prop_3 = (x**4) / math.factorial(4) prop_4 = -(x**6)",
"+ prop_2 + prop_3 + prop_4) print(prop_2) print(prop_3) print(prop_4) print(cos_x)",
"prop_2 = -(x**2) / math.factorial(2) prop_3 = (x**4) / math.factorial(4)",
"= -(x**6) / math.factorial(6) cos_x = float(1 + prop_2 +",
"= float(input()) prop_2 = -(x**2) / math.factorial(2) prop_3 = (x**4)",
"math x = float(input()) prop_2 = -(x**2) / math.factorial(2) prop_3",
"math.factorial(6) cos_x = float(1 + prop_2 + prop_3 + prop_4)",
"prop_3 = (x**4) / math.factorial(4) prop_4 = -(x**6) / math.factorial(6)",
"import math x = float(input()) prop_2 = -(x**2) / math.factorial(2)",
"/ math.factorial(4) prop_4 = -(x**6) / math.factorial(6) cos_x = float(1",
"prop_4 = -(x**6) / math.factorial(6) cos_x = float(1 + prop_2",
"= (x**4) / math.factorial(4) prop_4 = -(x**6) / math.factorial(6) cos_x",
"= -(x**2) / math.factorial(2) prop_3 = (x**4) / math.factorial(4) prop_4",
"-(x**2) / math.factorial(2) prop_3 = (x**4) / math.factorial(4) prop_4 =",
"(x**4) / math.factorial(4) prop_4 = -(x**6) / math.factorial(6) cos_x =",
"cos_x = float(1 + prop_2 + prop_3 + prop_4) print(prop_2)",
"-(x**6) / math.factorial(6) cos_x = float(1 + prop_2 + prop_3",
"float(input()) prop_2 = -(x**2) / math.factorial(2) prop_3 = (x**4) /",
"float(1 + prop_2 + prop_3 + prop_4) print(prop_2) print(prop_3) print(prop_4)",
"math.factorial(4) prop_4 = -(x**6) / math.factorial(6) cos_x = float(1 +",
"/ math.factorial(6) cos_x = float(1 + prop_2 + prop_3 +"
] |
[
"test_valid_operations( self, icat_query, operation, value, expected_condition_value, ): test_filter = PythonICATWhereFilter(\"id\",",
"test_valid_internal_icat_value(self, icat_query): \"\"\"Check that values that point to other values",
"than\"), pytest.param(\"lte\", 5, [\"%s <= '5'\"], id=\"less than or equal\"),",
"class TestICATWhereFilter: @pytest.mark.parametrize( \"operation, value, expected_condition_value\", [ pytest.param(\"eq\", 5, [\"%s",
"id=\"not ilike\", ), pytest.param(\"lt\", 5, [\"%s < '5'\"], id=\"less than\"),",
"[\"%s >= '5'\"], id=\"greater than or equal\"), pytest.param(\"in\", [1, 2,",
"test_filter.apply_filter(icat_query) def test_valid_internal_icat_value(self, icat_query): \"\"\"Check that values that point to",
"test_filter.apply_filter(icat_query) assert icat_query.conditions == {\"title\": [\"%s = 'Investigation Title'\"]} def",
"[\"%s <= '5'\"], id=\"less than or equal\"), pytest.param(\"gt\", 5, [\"%s",
"assert icat_query.conditions == {\"title\": [\"%s = 'Investigation Title'\"]} def test_invalid_field(self,",
"icat_query.conditions == {\"title\": [\"%s = 'Investigation Title'\"]} def test_invalid_field(self, icat_query):",
"5, [\"%s not like '%%5%%'\"], id=\"not like\"), pytest.param( \"nilike\", 5,",
"to other values in the schema are applied\"\"\" test_filter =",
"'%%5%%'\"], id=\"like\"), pytest.param(\"ilike\", 5, [\"UPPER(%s) like UPPER('%%5%%')\"], id=\"ilike\"), pytest.param(\"nlike\", 5,",
"like\"), pytest.param( \"nilike\", 5, [\"UPPER(%s) not like UPPER('%%5%%')\"], id=\"not ilike\",",
"icat_query): \"\"\"Check that values that point to other values in",
"\"lt\") test_filter.apply_filter(icat_query) assert icat_query.conditions == {\"startDate\": [\"%s < o.endDate\"]} def",
"that values that point to other values in the schema",
"icat_query.conditions == {\"id\": expected_condition_value} def test_invalid_in_operation(self, icat_query): with pytest.raises(BadRequestError): PythonICATWhereFilter(\"id\",",
"<= '5'\"], id=\"less than or equal\"), pytest.param(\"gt\", 5, [\"%s >",
"5, [\"%s < '5'\"], id=\"less than\"), pytest.param(\"lte\", 5, [\"%s <=",
"'5'\"], id=\"less than\"), pytest.param(\"lte\", 5, [\"%s <= '5'\"], id=\"less than",
"id=\"not equal\"), pytest.param(\"like\", 5, [\"%s like '%%5%%'\"], id=\"like\"), pytest.param(\"ilike\", 5,",
"PythonICATWhereFilter(\"id\", 10, \"lt\") gt_filter = PythonICATWhereFilter(\"id\", 5, \"gt\") filter_handler =",
"[\"%s = '5'\"], id=\"equal\"), pytest.param(\"ne\", 5, [\"%s != 5\"], id=\"not",
"= PythonICATWhereFilter(\"title\", \"Investigation Title\", \"eq\") test_filter.apply_filter(icat_query) assert icat_query.conditions == {\"title\":",
"are applied\"\"\" test_filter = PythonICATWhereFilter(\"startDate\", \"o.endDate\", \"lt\") test_filter.apply_filter(icat_query) assert icat_query.conditions",
"FilterOrderHandler from datagateway_api.src.datagateway_api.icat.filters import PythonICATWhereFilter class TestICATWhereFilter: @pytest.mark.parametrize( \"operation, value,",
"equal\"), pytest.param(\"in\", [1, 2, 3, 4], [\"%s in (1, 2,",
"id=\"in a list\"), pytest.param(\"in\", [], [\"%s in (NULL)\"], id=\"empty list\"),",
"pytest.param(\"eq\", 5, [\"%s = '5'\"], id=\"equal\"), pytest.param(\"ne\", 5, [\"%s !=",
"list\"), ], ) def test_valid_operations( self, icat_query, operation, value, expected_condition_value,",
"{\"startDate\": [\"%s < o.endDate\"]} def test_valid_field(self, icat_query): test_filter = PythonICATWhereFilter(\"title\",",
"like '%%5%%'\"], id=\"like\"), pytest.param(\"ilike\", 5, [\"UPPER(%s) like UPPER('%%5%%')\"], id=\"ilike\"), pytest.param(\"nlike\",",
"PythonICATWhereFilter(\"id\", 10, \"non\") with pytest.raises(FilterError): test_filter.apply_filter(icat_query) def test_valid_internal_icat_value(self, icat_query): \"\"\"Check",
"5, [\"%s >= '5'\"], id=\"greater than or equal\"), pytest.param(\"in\", [1,",
"= FilterOrderHandler() filter_handler.add_filters([lt_filter, gt_filter]) filter_handler.apply_filters(icat_query) assert icat_query.conditions == {\"id\": [\"%s",
"a list\"), pytest.param(\"in\", [], [\"%s in (NULL)\"], id=\"empty list\"), ],",
"import pytest from datagateway_api.src.common.exceptions import BadRequestError, FilterError from datagateway_api.src.datagateway_api.filter_order_handler import",
"pytest.param(\"lt\", 5, [\"%s < '5'\"], id=\"less than\"), pytest.param(\"lte\", 5, [\"%s",
"value, expected_condition_value, ): test_filter = PythonICATWhereFilter(\"id\", value, operation) test_filter.apply_filter(icat_query) assert",
"'5'\"], id=\"greater than\"), pytest.param(\"gte\", 5, [\"%s >= '5'\"], id=\"greater than",
"): test_filter = PythonICATWhereFilter(\"id\", value, operation) test_filter.apply_filter(icat_query) assert icat_query.conditions ==",
"expected_condition_value\", [ pytest.param(\"eq\", 5, [\"%s = '5'\"], id=\"equal\"), pytest.param(\"ne\", 5,",
"\"Investigation Title\", \"eq\") test_filter.apply_filter(icat_query) assert icat_query.conditions == {\"title\": [\"%s =",
"10, \"non\") with pytest.raises(FilterError): test_filter.apply_filter(icat_query) def test_valid_internal_icat_value(self, icat_query): \"\"\"Check that",
"expected_condition_value} def test_invalid_in_operation(self, icat_query): with pytest.raises(BadRequestError): PythonICATWhereFilter(\"id\", \"1, 2, 3,",
"pytest.raises(FilterError): test_filter.apply_filter(icat_query) def test_valid_internal_icat_value(self, icat_query): \"\"\"Check that values that point",
"TestICATWhereFilter: @pytest.mark.parametrize( \"operation, value, expected_condition_value\", [ pytest.param(\"eq\", 5, [\"%s =",
"5, [\"%s > '5'\"], id=\"greater than\"), pytest.param(\"gte\", 5, [\"%s >=",
"datagateway_api.src.common.exceptions import BadRequestError, FilterError from datagateway_api.src.datagateway_api.filter_order_handler import FilterOrderHandler from datagateway_api.src.datagateway_api.icat.filters",
"from datagateway_api.src.datagateway_api.filter_order_handler import FilterOrderHandler from datagateway_api.src.datagateway_api.icat.filters import PythonICATWhereFilter class TestICATWhereFilter:",
"id=\"greater than or equal\"), pytest.param(\"in\", [1, 2, 3, 4], [\"%s",
"that point to other values in the schema are applied\"\"\"",
"than\"), pytest.param(\"gte\", 5, [\"%s >= '5'\"], id=\"greater than or equal\"),",
"PythonICATWhereFilter(\"title\", \"Investigation Title\", \"eq\") test_filter.apply_filter(icat_query) assert icat_query.conditions == {\"title\": [\"%s",
"'5'\"], id=\"equal\"), pytest.param(\"ne\", 5, [\"%s != 5\"], id=\"not equal\"), pytest.param(\"like\",",
"o.endDate\"]} def test_valid_field(self, icat_query): test_filter = PythonICATWhereFilter(\"title\", \"Investigation Title\", \"eq\")",
"= PythonICATWhereFilter(\"random_field\", \"my_value\", \"eq\") with pytest.raises(FilterError): test_filter.apply_filter(icat_query) def test_multiple_conditions_per_field(self, icat_query):",
"test_filter.apply_filter(icat_query) assert icat_query.conditions == {\"startDate\": [\"%s < o.endDate\"]} def test_valid_field(self,",
"filter_handler = FilterOrderHandler() filter_handler.add_filters([lt_filter, gt_filter]) filter_handler.apply_filters(icat_query) assert icat_query.conditions == {\"id\":",
"> '5'\"], id=\"greater than\"), pytest.param(\"gte\", 5, [\"%s >= '5'\"], id=\"greater",
"id=\"not like\"), pytest.param( \"nilike\", 5, [\"UPPER(%s) not like UPPER('%%5%%')\"], id=\"not",
"4], [\"%s in (1, 2, 3, 4)\"], id=\"in a list\"),",
"5, [\"%s <= '5'\"], id=\"less than or equal\"), pytest.param(\"gt\", 5,",
"value, operation) test_filter.apply_filter(icat_query) assert icat_query.conditions == {\"id\": expected_condition_value} def test_invalid_in_operation(self,",
"id=\"ilike\"), pytest.param(\"nlike\", 5, [\"%s not like '%%5%%'\"], id=\"not like\"), pytest.param(",
"{\"id\": expected_condition_value} def test_invalid_in_operation(self, icat_query): with pytest.raises(BadRequestError): PythonICATWhereFilter(\"id\", \"1, 2,",
"@pytest.mark.parametrize( \"operation, value, expected_condition_value\", [ pytest.param(\"eq\", 5, [\"%s = '5'\"],",
"equal\"), pytest.param(\"like\", 5, [\"%s like '%%5%%'\"], id=\"like\"), pytest.param(\"ilike\", 5, [\"UPPER(%s)",
"pytest.param( \"nilike\", 5, [\"UPPER(%s) not like UPPER('%%5%%')\"], id=\"not ilike\", ),",
"= PythonICATWhereFilter(\"id\", 10, \"non\") with pytest.raises(FilterError): test_filter.apply_filter(icat_query) def test_valid_internal_icat_value(self, icat_query):",
"[\"UPPER(%s) not like UPPER('%%5%%')\"], id=\"not ilike\", ), pytest.param(\"lt\", 5, [\"%s",
"3, 4, 5\", \"in\") def test_invalid_operation(self, icat_query): test_filter = PythonICATWhereFilter(\"id\",",
"def test_valid_operations( self, icat_query, operation, value, expected_condition_value, ): test_filter =",
"point to other values in the schema are applied\"\"\" test_filter",
"== {\"startDate\": [\"%s < o.endDate\"]} def test_valid_field(self, icat_query): test_filter =",
"id=\"greater than\"), pytest.param(\"gte\", 5, [\"%s >= '5'\"], id=\"greater than or",
"from datagateway_api.src.common.exceptions import BadRequestError, FilterError from datagateway_api.src.datagateway_api.filter_order_handler import FilterOrderHandler from",
") def test_valid_operations( self, icat_query, operation, value, expected_condition_value, ): test_filter",
"than or equal\"), pytest.param(\"gt\", 5, [\"%s > '5'\"], id=\"greater than\"),",
"< '5'\"], id=\"less than\"), pytest.param(\"lte\", 5, [\"%s <= '5'\"], id=\"less",
"or equal\"), pytest.param(\"gt\", 5, [\"%s > '5'\"], id=\"greater than\"), pytest.param(\"gte\",",
"id=\"like\"), pytest.param(\"ilike\", 5, [\"UPPER(%s) like UPPER('%%5%%')\"], id=\"ilike\"), pytest.param(\"nlike\", 5, [\"%s",
"test_multiple_conditions_per_field(self, icat_query): lt_filter = PythonICATWhereFilter(\"id\", 10, \"lt\") gt_filter = PythonICATWhereFilter(\"id\",",
"operation, value, expected_condition_value, ): test_filter = PythonICATWhereFilter(\"id\", value, operation) test_filter.apply_filter(icat_query)",
"def test_valid_field(self, icat_query): test_filter = PythonICATWhereFilter(\"title\", \"Investigation Title\", \"eq\") test_filter.apply_filter(icat_query)",
"= PythonICATWhereFilter(\"id\", 5, \"gt\") filter_handler = FilterOrderHandler() filter_handler.add_filters([lt_filter, gt_filter]) filter_handler.apply_filters(icat_query)",
"\"operation, value, expected_condition_value\", [ pytest.param(\"eq\", 5, [\"%s = '5'\"], id=\"equal\"),",
"with pytest.raises(FilterError): test_filter.apply_filter(icat_query) def test_valid_internal_icat_value(self, icat_query): \"\"\"Check that values that",
"Title\", \"eq\") test_filter.apply_filter(icat_query) assert icat_query.conditions == {\"title\": [\"%s = 'Investigation",
"PythonICATWhereFilter(\"id\", \"1, 2, 3, 4, 5\", \"in\") def test_invalid_operation(self, icat_query):",
"self, icat_query, operation, value, expected_condition_value, ): test_filter = PythonICATWhereFilter(\"id\", value,",
"pytest.param(\"nlike\", 5, [\"%s not like '%%5%%'\"], id=\"not like\"), pytest.param( \"nilike\",",
"icat_query): test_filter = PythonICATWhereFilter(\"id\", 10, \"non\") with pytest.raises(FilterError): test_filter.apply_filter(icat_query) def",
"not like '%%5%%'\"], id=\"not like\"), pytest.param( \"nilike\", 5, [\"UPPER(%s) not",
"[ pytest.param(\"eq\", 5, [\"%s = '5'\"], id=\"equal\"), pytest.param(\"ne\", 5, [\"%s",
"3, 4], [\"%s in (1, 2, 3, 4)\"], id=\"in a",
"not like UPPER('%%5%%')\"], id=\"not ilike\", ), pytest.param(\"lt\", 5, [\"%s <",
"{\"title\": [\"%s = 'Investigation Title'\"]} def test_invalid_field(self, icat_query): test_filter =",
"equal\"), pytest.param(\"gt\", 5, [\"%s > '5'\"], id=\"greater than\"), pytest.param(\"gte\", 5,",
">= '5'\"], id=\"greater than or equal\"), pytest.param(\"in\", [1, 2, 3,",
"def test_valid_internal_icat_value(self, icat_query): \"\"\"Check that values that point to other",
"pytest.param(\"in\", [1, 2, 3, 4], [\"%s in (1, 2, 3,",
"datagateway_api.src.datagateway_api.filter_order_handler import FilterOrderHandler from datagateway_api.src.datagateway_api.icat.filters import PythonICATWhereFilter class TestICATWhereFilter: @pytest.mark.parametrize(",
"< o.endDate\"]} def test_valid_field(self, icat_query): test_filter = PythonICATWhereFilter(\"title\", \"Investigation Title\",",
"assert icat_query.conditions == {\"id\": [\"%s < '10'\", \"%s > '5'\"]}",
"5, [\"%s != 5\"], id=\"not equal\"), pytest.param(\"like\", 5, [\"%s like",
"icat_query): test_filter = PythonICATWhereFilter(\"title\", \"Investigation Title\", \"eq\") test_filter.apply_filter(icat_query) assert icat_query.conditions",
"\"eq\") with pytest.raises(FilterError): test_filter.apply_filter(icat_query) def test_multiple_conditions_per_field(self, icat_query): lt_filter = PythonICATWhereFilter(\"id\",",
"\"in\") def test_invalid_operation(self, icat_query): test_filter = PythonICATWhereFilter(\"id\", 10, \"non\") with",
"\"eq\") test_filter.apply_filter(icat_query) assert icat_query.conditions == {\"title\": [\"%s = 'Investigation Title'\"]}",
"pytest.param(\"ilike\", 5, [\"UPPER(%s) like UPPER('%%5%%')\"], id=\"ilike\"), pytest.param(\"nlike\", 5, [\"%s not",
"icat_query): test_filter = PythonICATWhereFilter(\"random_field\", \"my_value\", \"eq\") with pytest.raises(FilterError): test_filter.apply_filter(icat_query) def",
"with pytest.raises(FilterError): test_filter.apply_filter(icat_query) def test_multiple_conditions_per_field(self, icat_query): lt_filter = PythonICATWhereFilter(\"id\", 10,",
"test_filter.apply_filter(icat_query) def test_multiple_conditions_per_field(self, icat_query): lt_filter = PythonICATWhereFilter(\"id\", 10, \"lt\") gt_filter",
"= PythonICATWhereFilter(\"id\", 10, \"lt\") gt_filter = PythonICATWhereFilter(\"id\", 5, \"gt\") filter_handler",
"id=\"empty list\"), ], ) def test_valid_operations( self, icat_query, operation, value,",
"lt_filter = PythonICATWhereFilter(\"id\", 10, \"lt\") gt_filter = PythonICATWhereFilter(\"id\", 5, \"gt\")",
"icat_query, operation, value, expected_condition_value, ): test_filter = PythonICATWhereFilter(\"id\", value, operation)",
"PythonICATWhereFilter class TestICATWhereFilter: @pytest.mark.parametrize( \"operation, value, expected_condition_value\", [ pytest.param(\"eq\", 5,",
"pytest.param(\"ne\", 5, [\"%s != 5\"], id=\"not equal\"), pytest.param(\"like\", 5, [\"%s",
"pytest.param(\"like\", 5, [\"%s like '%%5%%'\"], id=\"like\"), pytest.param(\"ilike\", 5, [\"UPPER(%s) like",
"values that point to other values in the schema are",
"BadRequestError, FilterError from datagateway_api.src.datagateway_api.filter_order_handler import FilterOrderHandler from datagateway_api.src.datagateway_api.icat.filters import PythonICATWhereFilter",
"id=\"less than\"), pytest.param(\"lte\", 5, [\"%s <= '5'\"], id=\"less than or",
"4, 5\", \"in\") def test_invalid_operation(self, icat_query): test_filter = PythonICATWhereFilter(\"id\", 10,",
"FilterError from datagateway_api.src.datagateway_api.filter_order_handler import FilterOrderHandler from datagateway_api.src.datagateway_api.icat.filters import PythonICATWhereFilter class",
"schema are applied\"\"\" test_filter = PythonICATWhereFilter(\"startDate\", \"o.endDate\", \"lt\") test_filter.apply_filter(icat_query) assert",
"3, 4)\"], id=\"in a list\"), pytest.param(\"in\", [], [\"%s in (NULL)\"],",
"import FilterOrderHandler from datagateway_api.src.datagateway_api.icat.filters import PythonICATWhereFilter class TestICATWhereFilter: @pytest.mark.parametrize( \"operation,",
"[\"%s in (1, 2, 3, 4)\"], id=\"in a list\"), pytest.param(\"in\",",
"import PythonICATWhereFilter class TestICATWhereFilter: @pytest.mark.parametrize( \"operation, value, expected_condition_value\", [ pytest.param(\"eq\",",
"ilike\", ), pytest.param(\"lt\", 5, [\"%s < '5'\"], id=\"less than\"), pytest.param(\"lte\",",
"the schema are applied\"\"\" test_filter = PythonICATWhereFilter(\"startDate\", \"o.endDate\", \"lt\") test_filter.apply_filter(icat_query)",
"filter_handler.add_filters([lt_filter, gt_filter]) filter_handler.apply_filters(icat_query) assert icat_query.conditions == {\"id\": [\"%s < '10'\",",
"\"\"\"Check that values that point to other values in the",
"def test_multiple_conditions_per_field(self, icat_query): lt_filter = PythonICATWhereFilter(\"id\", 10, \"lt\") gt_filter =",
"pytest.param(\"gt\", 5, [\"%s > '5'\"], id=\"greater than\"), pytest.param(\"gte\", 5, [\"%s",
"[\"UPPER(%s) like UPPER('%%5%%')\"], id=\"ilike\"), pytest.param(\"nlike\", 5, [\"%s not like '%%5%%'\"],",
"[1, 2, 3, 4], [\"%s in (1, 2, 3, 4)\"],",
"icat_query): with pytest.raises(BadRequestError): PythonICATWhereFilter(\"id\", \"1, 2, 3, 4, 5\", \"in\")",
"PythonICATWhereFilter(\"id\", value, operation) test_filter.apply_filter(icat_query) assert icat_query.conditions == {\"id\": expected_condition_value} def",
"= PythonICATWhereFilter(\"startDate\", \"o.endDate\", \"lt\") test_filter.apply_filter(icat_query) assert icat_query.conditions == {\"startDate\": [\"%s",
"list\"), pytest.param(\"in\", [], [\"%s in (NULL)\"], id=\"empty list\"), ], )",
"'%%5%%'\"], id=\"not like\"), pytest.param( \"nilike\", 5, [\"UPPER(%s) not like UPPER('%%5%%')\"],",
"test_invalid_in_operation(self, icat_query): with pytest.raises(BadRequestError): PythonICATWhereFilter(\"id\", \"1, 2, 3, 4, 5\",",
"assert icat_query.conditions == {\"startDate\": [\"%s < o.endDate\"]} def test_valid_field(self, icat_query):",
"!= 5\"], id=\"not equal\"), pytest.param(\"like\", 5, [\"%s like '%%5%%'\"], id=\"like\"),",
"(NULL)\"], id=\"empty list\"), ], ) def test_valid_operations( self, icat_query, operation,",
"\"1, 2, 3, 4, 5\", \"in\") def test_invalid_operation(self, icat_query): test_filter",
"5\"], id=\"not equal\"), pytest.param(\"like\", 5, [\"%s like '%%5%%'\"], id=\"like\"), pytest.param(\"ilike\",",
"5, [\"UPPER(%s) like UPPER('%%5%%')\"], id=\"ilike\"), pytest.param(\"nlike\", 5, [\"%s not like",
"PythonICATWhereFilter(\"startDate\", \"o.endDate\", \"lt\") test_filter.apply_filter(icat_query) assert icat_query.conditions == {\"startDate\": [\"%s <",
"[\"%s in (NULL)\"], id=\"empty list\"), ], ) def test_valid_operations( self,",
"5, [\"%s = '5'\"], id=\"equal\"), pytest.param(\"ne\", 5, [\"%s != 5\"],",
"'5'\"], id=\"less than or equal\"), pytest.param(\"gt\", 5, [\"%s > '5'\"],",
"test_filter = PythonICATWhereFilter(\"id\", 10, \"non\") with pytest.raises(FilterError): test_filter.apply_filter(icat_query) def test_valid_internal_icat_value(self,",
"id=\"less than or equal\"), pytest.param(\"gt\", 5, [\"%s > '5'\"], id=\"greater",
"gt_filter]) filter_handler.apply_filters(icat_query) assert icat_query.conditions == {\"id\": [\"%s < '10'\", \"%s",
"'Investigation Title'\"]} def test_invalid_field(self, icat_query): test_filter = PythonICATWhereFilter(\"random_field\", \"my_value\", \"eq\")",
"in (1, 2, 3, 4)\"], id=\"in a list\"), pytest.param(\"in\", [],",
"like UPPER('%%5%%')\"], id=\"not ilike\", ), pytest.param(\"lt\", 5, [\"%s < '5'\"],",
"5\", \"in\") def test_invalid_operation(self, icat_query): test_filter = PythonICATWhereFilter(\"id\", 10, \"non\")",
"'5'\"], id=\"greater than or equal\"), pytest.param(\"in\", [1, 2, 3, 4],",
"def test_invalid_field(self, icat_query): test_filter = PythonICATWhereFilter(\"random_field\", \"my_value\", \"eq\") with pytest.raises(FilterError):",
"test_filter = PythonICATWhereFilter(\"random_field\", \"my_value\", \"eq\") with pytest.raises(FilterError): test_filter.apply_filter(icat_query) def test_multiple_conditions_per_field(self,",
"pytest.raises(FilterError): test_filter.apply_filter(icat_query) def test_multiple_conditions_per_field(self, icat_query): lt_filter = PythonICATWhereFilter(\"id\", 10, \"lt\")",
"pytest.param(\"lte\", 5, [\"%s <= '5'\"], id=\"less than or equal\"), pytest.param(\"gt\",",
"datagateway_api.src.datagateway_api.icat.filters import PythonICATWhereFilter class TestICATWhereFilter: @pytest.mark.parametrize( \"operation, value, expected_condition_value\", [",
"assert icat_query.conditions == {\"id\": expected_condition_value} def test_invalid_in_operation(self, icat_query): with pytest.raises(BadRequestError):",
"applied\"\"\" test_filter = PythonICATWhereFilter(\"startDate\", \"o.endDate\", \"lt\") test_filter.apply_filter(icat_query) assert icat_query.conditions ==",
"icat_query.conditions == {\"startDate\": [\"%s < o.endDate\"]} def test_valid_field(self, icat_query): test_filter",
"test_filter = PythonICATWhereFilter(\"startDate\", \"o.endDate\", \"lt\") test_filter.apply_filter(icat_query) assert icat_query.conditions == {\"startDate\":",
"gt_filter = PythonICATWhereFilter(\"id\", 5, \"gt\") filter_handler = FilterOrderHandler() filter_handler.add_filters([lt_filter, gt_filter])",
"or equal\"), pytest.param(\"in\", [1, 2, 3, 4], [\"%s in (1,",
"test_filter = PythonICATWhereFilter(\"id\", value, operation) test_filter.apply_filter(icat_query) assert icat_query.conditions == {\"id\":",
"than or equal\"), pytest.param(\"in\", [1, 2, 3, 4], [\"%s in",
"= PythonICATWhereFilter(\"id\", value, operation) test_filter.apply_filter(icat_query) assert icat_query.conditions == {\"id\": expected_condition_value}",
"[\"%s < o.endDate\"]} def test_valid_field(self, icat_query): test_filter = PythonICATWhereFilter(\"title\", \"Investigation",
"def test_invalid_in_operation(self, icat_query): with pytest.raises(BadRequestError): PythonICATWhereFilter(\"id\", \"1, 2, 3, 4,",
"2, 3, 4)\"], id=\"in a list\"), pytest.param(\"in\", [], [\"%s in",
"\"lt\") gt_filter = PythonICATWhereFilter(\"id\", 5, \"gt\") filter_handler = FilterOrderHandler() filter_handler.add_filters([lt_filter,",
"5, \"gt\") filter_handler = FilterOrderHandler() filter_handler.add_filters([lt_filter, gt_filter]) filter_handler.apply_filters(icat_query) assert icat_query.conditions",
"import BadRequestError, FilterError from datagateway_api.src.datagateway_api.filter_order_handler import FilterOrderHandler from datagateway_api.src.datagateway_api.icat.filters import",
"= '5'\"], id=\"equal\"), pytest.param(\"ne\", 5, [\"%s != 5\"], id=\"not equal\"),",
"5, [\"%s like '%%5%%'\"], id=\"like\"), pytest.param(\"ilike\", 5, [\"UPPER(%s) like UPPER('%%5%%')\"],",
"like UPPER('%%5%%')\"], id=\"ilike\"), pytest.param(\"nlike\", 5, [\"%s not like '%%5%%'\"], id=\"not",
"def test_invalid_operation(self, icat_query): test_filter = PythonICATWhereFilter(\"id\", 10, \"non\") with pytest.raises(FilterError):",
"test_filter.apply_filter(icat_query) assert icat_query.conditions == {\"id\": expected_condition_value} def test_invalid_in_operation(self, icat_query): with",
"pytest.raises(BadRequestError): PythonICATWhereFilter(\"id\", \"1, 2, 3, 4, 5\", \"in\") def test_invalid_operation(self,",
"pytest.param(\"gte\", 5, [\"%s >= '5'\"], id=\"greater than or equal\"), pytest.param(\"in\",",
"[\"%s != 5\"], id=\"not equal\"), pytest.param(\"like\", 5, [\"%s like '%%5%%'\"],",
"PythonICATWhereFilter(\"id\", 5, \"gt\") filter_handler = FilterOrderHandler() filter_handler.add_filters([lt_filter, gt_filter]) filter_handler.apply_filters(icat_query) assert",
"from datagateway_api.src.datagateway_api.icat.filters import PythonICATWhereFilter class TestICATWhereFilter: @pytest.mark.parametrize( \"operation, value, expected_condition_value\",",
"== {\"title\": [\"%s = 'Investigation Title'\"]} def test_invalid_field(self, icat_query): test_filter",
"test_invalid_field(self, icat_query): test_filter = PythonICATWhereFilter(\"random_field\", \"my_value\", \"eq\") with pytest.raises(FilterError): test_filter.apply_filter(icat_query)",
"value, expected_condition_value\", [ pytest.param(\"eq\", 5, [\"%s = '5'\"], id=\"equal\"), pytest.param(\"ne\",",
"[], [\"%s in (NULL)\"], id=\"empty list\"), ], ) def test_valid_operations(",
"], ) def test_valid_operations( self, icat_query, operation, value, expected_condition_value, ):",
"values in the schema are applied\"\"\" test_filter = PythonICATWhereFilter(\"startDate\", \"o.endDate\",",
"Title'\"]} def test_invalid_field(self, icat_query): test_filter = PythonICATWhereFilter(\"random_field\", \"my_value\", \"eq\") with",
"like '%%5%%'\"], id=\"not like\"), pytest.param( \"nilike\", 5, [\"UPPER(%s) not like",
"FilterOrderHandler() filter_handler.add_filters([lt_filter, gt_filter]) filter_handler.apply_filters(icat_query) assert icat_query.conditions == {\"id\": [\"%s <",
"pytest from datagateway_api.src.common.exceptions import BadRequestError, FilterError from datagateway_api.src.datagateway_api.filter_order_handler import FilterOrderHandler",
"[\"%s < '5'\"], id=\"less than\"), pytest.param(\"lte\", 5, [\"%s <= '5'\"],",
"UPPER('%%5%%')\"], id=\"not ilike\", ), pytest.param(\"lt\", 5, [\"%s < '5'\"], id=\"less",
"operation) test_filter.apply_filter(icat_query) assert icat_query.conditions == {\"id\": expected_condition_value} def test_invalid_in_operation(self, icat_query):",
"test_valid_field(self, icat_query): test_filter = PythonICATWhereFilter(\"title\", \"Investigation Title\", \"eq\") test_filter.apply_filter(icat_query) assert",
"filter_handler.apply_filters(icat_query) assert icat_query.conditions == {\"id\": [\"%s < '10'\", \"%s >",
"expected_condition_value, ): test_filter = PythonICATWhereFilter(\"id\", value, operation) test_filter.apply_filter(icat_query) assert icat_query.conditions",
"icat_query): lt_filter = PythonICATWhereFilter(\"id\", 10, \"lt\") gt_filter = PythonICATWhereFilter(\"id\", 5,",
"== {\"id\": expected_condition_value} def test_invalid_in_operation(self, icat_query): with pytest.raises(BadRequestError): PythonICATWhereFilter(\"id\", \"1,",
"test_invalid_operation(self, icat_query): test_filter = PythonICATWhereFilter(\"id\", 10, \"non\") with pytest.raises(FilterError): test_filter.apply_filter(icat_query)",
"in the schema are applied\"\"\" test_filter = PythonICATWhereFilter(\"startDate\", \"o.endDate\", \"lt\")",
"10, \"lt\") gt_filter = PythonICATWhereFilter(\"id\", 5, \"gt\") filter_handler = FilterOrderHandler()",
"UPPER('%%5%%')\"], id=\"ilike\"), pytest.param(\"nlike\", 5, [\"%s not like '%%5%%'\"], id=\"not like\"),",
"PythonICATWhereFilter(\"random_field\", \"my_value\", \"eq\") with pytest.raises(FilterError): test_filter.apply_filter(icat_query) def test_multiple_conditions_per_field(self, icat_query): lt_filter",
"[\"%s = 'Investigation Title'\"]} def test_invalid_field(self, icat_query): test_filter = PythonICATWhereFilter(\"random_field\",",
"\"gt\") filter_handler = FilterOrderHandler() filter_handler.add_filters([lt_filter, gt_filter]) filter_handler.apply_filters(icat_query) assert icat_query.conditions ==",
"with pytest.raises(BadRequestError): PythonICATWhereFilter(\"id\", \"1, 2, 3, 4, 5\", \"in\") def",
"test_filter = PythonICATWhereFilter(\"title\", \"Investigation Title\", \"eq\") test_filter.apply_filter(icat_query) assert icat_query.conditions ==",
"\"nilike\", 5, [\"UPPER(%s) not like UPPER('%%5%%')\"], id=\"not ilike\", ), pytest.param(\"lt\",",
"[\"%s not like '%%5%%'\"], id=\"not like\"), pytest.param( \"nilike\", 5, [\"UPPER(%s)",
"<filename>test/datagateway_api/icat/filters/test_where_filter.py import pytest from datagateway_api.src.common.exceptions import BadRequestError, FilterError from datagateway_api.src.datagateway_api.filter_order_handler",
"(1, 2, 3, 4)\"], id=\"in a list\"), pytest.param(\"in\", [], [\"%s",
"in (NULL)\"], id=\"empty list\"), ], ) def test_valid_operations( self, icat_query,",
"[\"%s > '5'\"], id=\"greater than\"), pytest.param(\"gte\", 5, [\"%s >= '5'\"],",
"\"my_value\", \"eq\") with pytest.raises(FilterError): test_filter.apply_filter(icat_query) def test_multiple_conditions_per_field(self, icat_query): lt_filter =",
"= 'Investigation Title'\"]} def test_invalid_field(self, icat_query): test_filter = PythonICATWhereFilter(\"random_field\", \"my_value\",",
"), pytest.param(\"lt\", 5, [\"%s < '5'\"], id=\"less than\"), pytest.param(\"lte\", 5,",
"[\"%s like '%%5%%'\"], id=\"like\"), pytest.param(\"ilike\", 5, [\"UPPER(%s) like UPPER('%%5%%')\"], id=\"ilike\"),",
"\"non\") with pytest.raises(FilterError): test_filter.apply_filter(icat_query) def test_valid_internal_icat_value(self, icat_query): \"\"\"Check that values",
"pytest.param(\"in\", [], [\"%s in (NULL)\"], id=\"empty list\"), ], ) def",
"\"o.endDate\", \"lt\") test_filter.apply_filter(icat_query) assert icat_query.conditions == {\"startDate\": [\"%s < o.endDate\"]}",
"id=\"equal\"), pytest.param(\"ne\", 5, [\"%s != 5\"], id=\"not equal\"), pytest.param(\"like\", 5,",
"5, [\"UPPER(%s) not like UPPER('%%5%%')\"], id=\"not ilike\", ), pytest.param(\"lt\", 5,",
"other values in the schema are applied\"\"\" test_filter = PythonICATWhereFilter(\"startDate\",",
"4)\"], id=\"in a list\"), pytest.param(\"in\", [], [\"%s in (NULL)\"], id=\"empty",
"2, 3, 4], [\"%s in (1, 2, 3, 4)\"], id=\"in",
"2, 3, 4, 5\", \"in\") def test_invalid_operation(self, icat_query): test_filter ="
] |
[
"define the fields for your item here like: # #",
"import scrapy from scrapy.loader import ItemLoader from scrapy.loader.processors import TakeFirst",
"import ItemLoader from scrapy.loader.processors import TakeFirst # class SpiderItem(scrapy.Item): #",
"ItemLoader from scrapy.loader.processors import TakeFirst # class SpiderItem(scrapy.Item): # #",
"for your item here like: # name = scrapy.Field() code",
"here like: # # name = scrapy.Field() # pass #",
"scrapy.loader.processors import TakeFirst # class SpiderItem(scrapy.Item): # # define the",
"define the fields for your item here like: # name",
"# 涨跌额 chg_ratio_5min = scrapy.Field() # 5分钟涨幅 volumn = scrapy.Field()",
"# url = scrapy.Field() # name = scrapy.Field() # description",
"= scrapy.Field() # 5分钟涨幅 volumn = scrapy.Field() # 成交量 turn_over",
"description = scrapy.Field() # size = scrapy.Field() # # import",
"# class TorrentItem(scrapy.Item): # url = scrapy.Field() # name =",
"# import scrapy class StockstarItemLoader(ItemLoader): # 自定义itemloader,用于存储爬虫所抓取的字段内容 default_output_processor = TakeFirst()",
"coding: utf-8 -*- # Define here the models for your",
"name = scrapy.Field() # description = scrapy.Field() # size =",
"import scrapy class StockstarItemLoader(ItemLoader): # 自定义itemloader,用于存储爬虫所抓取的字段内容 default_output_processor = TakeFirst() class",
"自定义itemloader,用于存储爬虫所抓取的字段内容 default_output_processor = TakeFirst() class StockstarItem(scrapy.Item): # 建立相应的字段 # define",
"your item here like: # name = scrapy.Field() code =",
"for your item here like: # # name = scrapy.Field()",
"items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy",
"StockstarItemLoader(ItemLoader): # 自定义itemloader,用于存储爬虫所抓取的字段内容 default_output_processor = TakeFirst() class StockstarItem(scrapy.Item): # 建立相应的字段",
"scrapy.Field() # 涨跌幅 chg_amt = scrapy.Field() # 涨跌额 chg_ratio_5min =",
"default_output_processor = TakeFirst() class StockstarItem(scrapy.Item): # 建立相应的字段 # define the",
"= scrapy.Field() # 股票简称 last_trade = scrapy.Field() # 最新价 chg_ratio",
"like: # # name = scrapy.Field() # pass # #",
"# 股票简称 last_trade = scrapy.Field() # 最新价 chg_ratio = scrapy.Field()",
"import TakeFirst # class SpiderItem(scrapy.Item): # # define the fields",
"建立相应的字段 # define the fields for your item here like:",
"item here like: # name = scrapy.Field() code = scrapy.Field()",
"= scrapy.Field() # 最新价 chg_ratio = scrapy.Field() # 涨跌幅 chg_amt",
"pass # # # # class TorrentItem(scrapy.Item): # url =",
"TakeFirst # class SpiderItem(scrapy.Item): # # define the fields for",
"scrapy.Field() # 最新价 chg_ratio = scrapy.Field() # 涨跌幅 chg_amt =",
"from scrapy.loader.processors import TakeFirst # class SpiderItem(scrapy.Item): # # define",
"= scrapy.Field() # 涨跌幅 chg_amt = scrapy.Field() # 涨跌额 chg_ratio_5min",
"= scrapy.Field() # size = scrapy.Field() # # import scrapy",
"股票简称 last_trade = scrapy.Field() # 最新价 chg_ratio = scrapy.Field() #",
"last_trade = scrapy.Field() # 最新价 chg_ratio = scrapy.Field() # 涨跌幅",
"name = scrapy.Field() # pass # # # # class",
"涨跌幅 chg_amt = scrapy.Field() # 涨跌额 chg_ratio_5min = scrapy.Field() #",
"class StockstarItem(scrapy.Item): # 建立相应的字段 # define the fields for your",
"See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy from scrapy.loader import",
"scrapy.Field() # # import scrapy class StockstarItemLoader(ItemLoader): # 自定义itemloader,用于存储爬虫所抓取的字段内容 default_output_processor",
"here the models for your scraped items # # See",
"scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import",
"your item here like: # # name = scrapy.Field() #",
"# 最新价 chg_ratio = scrapy.Field() # 涨跌幅 chg_amt = scrapy.Field()",
"# # # class TorrentItem(scrapy.Item): # url = scrapy.Field() #",
"scrapy.Field() # 涨跌额 chg_ratio_5min = scrapy.Field() # 5分钟涨幅 volumn =",
"chg_ratio_5min = scrapy.Field() # 5分钟涨幅 volumn = scrapy.Field() # 成交量",
"= scrapy.Field() # # import scrapy class StockstarItemLoader(ItemLoader): # 自定义itemloader,用于存储爬虫所抓取的字段内容",
"in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy from scrapy.loader import ItemLoader from",
"your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html",
"https://doc.scrapy.org/en/latest/topics/items.html import scrapy from scrapy.loader import ItemLoader from scrapy.loader.processors import",
"the fields for your item here like: # name =",
"for your scraped items # # See documentation in: #",
"# # class TorrentItem(scrapy.Item): # url = scrapy.Field() # name",
"= scrapy.Field() # pass # # # # class TorrentItem(scrapy.Item):",
"scrapy from scrapy.loader import ItemLoader from scrapy.loader.processors import TakeFirst #",
"# # import scrapy class StockstarItemLoader(ItemLoader): # 自定义itemloader,用于存储爬虫所抓取的字段内容 default_output_processor =",
"utf-8 -*- # Define here the models for your scraped",
"scrapy.Field() # name = scrapy.Field() # description = scrapy.Field() #",
"size = scrapy.Field() # # import scrapy class StockstarItemLoader(ItemLoader): #",
"the fields for your item here like: # # name",
"StockstarItem(scrapy.Item): # 建立相应的字段 # define the fields for your item",
"# 股票代码 abbr = scrapy.Field() # 股票简称 last_trade = scrapy.Field()",
"documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy from scrapy.loader import ItemLoader",
"# pass # # # # class TorrentItem(scrapy.Item): # url",
"abbr = scrapy.Field() # 股票简称 last_trade = scrapy.Field() # 最新价",
"# class SpiderItem(scrapy.Item): # # define the fields for your",
"# name = scrapy.Field() code = scrapy.Field() # 股票代码 abbr",
"scrapy.Field() # pass # # # # class TorrentItem(scrapy.Item): #",
"= scrapy.Field() # description = scrapy.Field() # size = scrapy.Field()",
"item here like: # # name = scrapy.Field() # pass",
"# # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy from",
"= scrapy.Field() # 股票代码 abbr = scrapy.Field() # 股票简称 last_trade",
"class SpiderItem(scrapy.Item): # # define the fields for your item",
"# Define here the models for your scraped items #",
"class TorrentItem(scrapy.Item): # url = scrapy.Field() # name = scrapy.Field()",
"TorrentItem(scrapy.Item): # url = scrapy.Field() # name = scrapy.Field() #",
"SpiderItem(scrapy.Item): # # define the fields for your item here",
"code = scrapy.Field() # 股票代码 abbr = scrapy.Field() # 股票简称",
"# # name = scrapy.Field() # pass # # #",
"# define the fields for your item here like: #",
"url = scrapy.Field() # name = scrapy.Field() # description =",
"like: # name = scrapy.Field() code = scrapy.Field() # 股票代码",
"= TakeFirst() class StockstarItem(scrapy.Item): # 建立相应的字段 # define the fields",
"scrapy class StockstarItemLoader(ItemLoader): # 自定义itemloader,用于存储爬虫所抓取的字段内容 default_output_processor = TakeFirst() class StockstarItem(scrapy.Item):",
"class StockstarItemLoader(ItemLoader): # 自定义itemloader,用于存储爬虫所抓取的字段内容 default_output_processor = TakeFirst() class StockstarItem(scrapy.Item): #",
"= scrapy.Field() code = scrapy.Field() # 股票代码 abbr = scrapy.Field()",
"scrapy.Field() # 股票代码 abbr = scrapy.Field() # 股票简称 last_trade =",
"# 5分钟涨幅 volumn = scrapy.Field() # 成交量 turn_over = scrapy.Field()",
"models for your scraped items # # See documentation in:",
"scrapy.Field() code = scrapy.Field() # 股票代码 abbr = scrapy.Field() #",
"# https://doc.scrapy.org/en/latest/topics/items.html import scrapy from scrapy.loader import ItemLoader from scrapy.loader.processors",
"股票代码 abbr = scrapy.Field() # 股票简称 last_trade = scrapy.Field() #",
"-*- coding: utf-8 -*- # Define here the models for",
"# # # # class TorrentItem(scrapy.Item): # url = scrapy.Field()",
"= scrapy.Field() # 涨跌额 chg_ratio_5min = scrapy.Field() # 5分钟涨幅 volumn",
"最新价 chg_ratio = scrapy.Field() # 涨跌幅 chg_amt = scrapy.Field() #",
"# size = scrapy.Field() # # import scrapy class StockstarItemLoader(ItemLoader):",
"fields for your item here like: # # name =",
"here like: # name = scrapy.Field() code = scrapy.Field() #",
"Define here the models for your scraped items # #",
"# 建立相应的字段 # define the fields for your item here",
"# description = scrapy.Field() # size = scrapy.Field() # #",
"chg_ratio = scrapy.Field() # 涨跌幅 chg_amt = scrapy.Field() # 涨跌额",
"# -*- coding: utf-8 -*- # Define here the models",
"chg_amt = scrapy.Field() # 涨跌额 chg_ratio_5min = scrapy.Field() # 5分钟涨幅",
"volumn = scrapy.Field() # 成交量 turn_over = scrapy.Field() # 成交额",
"scrapy.Field() # description = scrapy.Field() # size = scrapy.Field() #",
"scrapy.Field() # size = scrapy.Field() # # import scrapy class",
"= scrapy.Field() # name = scrapy.Field() # description = scrapy.Field()",
"# name = scrapy.Field() # pass # # # #",
"5分钟涨幅 volumn = scrapy.Field() # 成交量 turn_over = scrapy.Field() #",
"# See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy from scrapy.loader",
"scrapy.loader import ItemLoader from scrapy.loader.processors import TakeFirst # class SpiderItem(scrapy.Item):",
"scrapy.Field() # 股票简称 last_trade = scrapy.Field() # 最新价 chg_ratio =",
"scrapy.Field() # 5分钟涨幅 volumn = scrapy.Field() # 成交量 turn_over =",
"# 自定义itemloader,用于存储爬虫所抓取的字段内容 default_output_processor = TakeFirst() class StockstarItem(scrapy.Item): # 建立相应的字段 #",
"涨跌额 chg_ratio_5min = scrapy.Field() # 5分钟涨幅 volumn = scrapy.Field() #",
"name = scrapy.Field() code = scrapy.Field() # 股票代码 abbr =",
"# 涨跌幅 chg_amt = scrapy.Field() # 涨跌额 chg_ratio_5min = scrapy.Field()",
"-*- # Define here the models for your scraped items",
"TakeFirst() class StockstarItem(scrapy.Item): # 建立相应的字段 # define the fields for",
"the models for your scraped items # # See documentation",
"from scrapy.loader import ItemLoader from scrapy.loader.processors import TakeFirst # class",
"# # define the fields for your item here like:",
"fields for your item here like: # name = scrapy.Field()",
"# name = scrapy.Field() # description = scrapy.Field() # size"
] |
[
"modified = [key] c[key] = value else: modified = []",
"Str, Undefined, Supports, adapt, provides, on_trait_change) from .data_context import DataContext,",
"DictMixin's get method over HasTraits'. get = DictMixin.get def __str__(self):",
"Bool(True) def __init__(self, *subcontexts, **traits): subcontexts = list(subcontexts) super(MultiContext, self).__init__(subcontexts=subcontexts,",
"= True break elif key in c: # Record this",
"default string subcontext_str = '[%s]' % ', '.join([str(x) for x",
"len(list(self.keys())) def __contains__(self, key): for c in self.subcontexts: if key",
"if key in c: added = [] current_value = c[key]",
"\"\"\" for c in self.subcontexts: try: del c[key] return except",
"= context.shallow_copy() copy[key] is context[key] for key in context.keys() These",
"__str__(self): # Maybe a good default string subcontext_str = '[%s]'",
"open source software distributed according to the terms in #",
"key/value pair will get it. If an earlier subcontext has",
"subcontexts list. \"\"\" added = [] removed = [] #",
"purposes. Returns ------- copy : IContext \"\"\" copy = self.clone_traits()",
"will be shallowly copied:: copy = context.shallow_copy() copy[key] is context[key]",
"if is_modified: modified = [key] c[key] = value else: modified",
"key, value): \"\"\" Set item with [] access. The first",
"raise KeyError(key) def __setitem__(self, key, value): \"\"\" Set item with",
"IRestrictedContext from .utils import safe_repr @provides(IDataContext) class MultiContext(ListenableMixin, PersistableMixin, DictMixin):",
"Str(\"multidummy\") #: The underlying dictionary. subcontexts = List(Supports(IRestrictedContext, factory=DataContext)) #:",
"events veto_subcontext_modified = Bool(True) def __init__(self, *subcontexts, **traits): subcontexts =",
"all blocking instances. for c in blocking_contexts: del c[key] if",
"a good default representation return '%s(name=%r)' % (type(self).__name__, self.name) ####",
"KeyError: continue raise KeyError(key) def __getitem__(self, key): for c in",
"\"\"\" copy = self.clone_traits() new_subcontexts = [] for context in",
"if not set: if c.allows(value, key): if key in c:",
"not allow the assignment, then that key will be deleted.",
"try: del c[key] return except KeyError: continue raise KeyError(key) def",
"set = True break elif key in c: # Record",
"in self.subcontexts: if key in c: return True return False",
"context in event.added: added.extend(list(context.keys())) # Add to the list of",
"of the context. name = Str(\"multidummy\") #: The underlying dictionary.",
"safe_repr(value))) def keys(self): return list(set(chain(*[list(c.keys()) for c in self.subcontexts]))) #",
"self.subcontexts]))) # Expose DictMixin's get method over HasTraits'. get =",
"not self.allows(value, key): raise ValueError('Disallowed mapping: %s = %s' %",
"self.subcontexts: try: return c[key] except KeyError: continue raise KeyError(key) def",
"added = [key] modified = [] c[key] = value set",
"# # This file is open source software distributed according",
"in c: return True return False def __delitem__(self, key): \"\"\"",
"def __repr__(self): # Maybe a good default representation return '%s(name=%r)'",
"__init__(self, *subcontexts, **traits): subcontexts = list(subcontexts) super(MultiContext, self).__init__(subcontexts=subcontexts, **traits) ####",
"the context. Technically, this is actually a fairly deep copy.",
"is open source software distributed according to the terms in",
"\"\"\" Context holding multiple subcontexts. \"\"\" from __future__ import absolute_import",
"IContext interface #################################################### def __iter__(self): return iter(self.keys()) def __len__(self): return",
"return iter(self.keys()) def __len__(self): return len(list(self.keys())) def __contains__(self, key): for",
"subtypes dictate compatibility independently of contained contexts if not self.allows(value,",
"not available in the context. \"\"\" for c in self.subcontexts:",
"return event.veto = self.veto_subcontext_modified self._fire_event(added=event.added, removed=event.removed, modified=event.modified, context=event.context) def _subcontexts_items_changed(self,",
"# This file is open source software distributed according to",
"self.allows(value, key): raise ValueError('Disallowed mapping: %s = %s' % (key,",
"assigned that value. \"\"\" # Let subtypes dictate compatibility independently",
"subcontext which allows the key/value pair will get it. If",
"is_modified: modified = [key] c[key] = value else: modified =",
"key): if key in c: added = [] current_value =",
"value. blocking_contexts.append(c) # Remove all blocking instances. for c in",
"The underlying dictionary. subcontexts = List(Supports(IRestrictedContext, factory=DataContext)) #: Suppress subcontext",
"% (type(self).__name__, self.name, subcontext_str) def __repr__(self): # Maybe a good",
"iter(self.keys()) def __len__(self): return len(list(self.keys())) def __contains__(self, key): for c",
"access to the final # location of the value. blocking_contexts.append(c)",
"current_value = c[key] try: is_modified = bool(current_value != value) except",
"to be assigned that value. \"\"\" # Let subtypes dictate",
"= value set = True break elif key in c:",
"object Raises ------ ValueError if the key is not permitted",
"% (key, safe_repr(value))) def keys(self): return list(set(chain(*[list(c.keys()) for c in",
"---------- key : str value : object Raises ------ ValueError",
"key. Parameters ---------- key : str Raises ------ KeyError if",
"safe_repr(value))) set = False blocking_contexts = [] for c in",
"the value. blocking_contexts.append(c) # Remove all blocking instances. for c",
"the first instance of the key. Parameters ---------- key :",
"MutableMapping as DictMixin from traits.api import (Bool, List, Str, Undefined,",
"context.shallow_copy() copy[key] is context[key] for key in context.keys() These semantics",
"str Raises ------ KeyError if the kew is not available",
"self.subcontexts: if c.allows(value, name=name): return True return False #### Trait",
"earlier subcontext has the key, but does not allow the",
"take place. Parameters ---------- key : str value : object",
"value, name=None): for c in self.subcontexts: if c.allows(value, name=name): return",
"% (key, safe_repr(value))) set = False blocking_contexts = [] for",
"= [] # Add to the list of items added",
"__setitem__(self, key, value): \"\"\" Set item with [] access. The",
"the final # location of the value. blocking_contexts.append(c) # Remove",
"[] for context in self.subcontexts: checkpointable_subcontext = adapt(context, ICheckpointable) new_subcontexts.append(checkpointable_subcontext.checkpoint())",
"return len(list(self.keys())) def __contains__(self, key): for c in self.subcontexts: if",
"self.name) #### IRestrictedContext interface ########################################## def allows(self, value, name=None): for",
"the key/value pair will get it. If an earlier subcontext",
"Make a shallow copy of the context. Technically, this is",
"try: is_modified = bool(current_value != value) except Exception: is_modified =",
"for key in context.keys() These semantics are useful for saving",
"# # (C) Copyright 2013 Enthought, Inc., Austin, TX #",
"over HasTraits'. get = DictMixin.get def __str__(self): # Maybe a",
"kew is not available in the context. \"\"\" for c",
"a fairly deep copy. All of the object structure should",
"item with [] access. The first subcontext which allows the",
"context.keys() These semantics are useful for saving out checkpointed versions",
"to the list of items removed if len(event.removed): for context",
"items of subcontexts list. \"\"\" added = [] removed =",
"Maybe a good default string subcontext_str = '[%s]' % ',",
"event.added: added.extend(list(context.keys())) # Add to the list of items removed",
"self.veto_subcontext_modified self._fire_event(added=event.added, removed=event.removed, modified=event.modified, context=event.context) def _subcontexts_items_changed(self, event): \"\"\" Trait",
"return True return False def __delitem__(self, key): \"\"\" Remove the",
"but does not allow the assignment, then that key will",
"*subcontexts, **traits): subcontexts = list(subcontexts) super(MultiContext, self).__init__(subcontexts=subcontexts, **traits) #### IContext",
"with [] access. Only deletes the first instance of the",
"(key, safe_repr(value))) def keys(self): return list(set(chain(*[list(c.keys()) for c in self.subcontexts])))",
"Remove the given key with [] access. Only deletes the",
"subcontexts = list(subcontexts) super(MultiContext, self).__init__(subcontexts=subcontexts, **traits) #### IContext interface ####################################################",
": object Raises ------ ValueError if the key is not",
"continue raise KeyError(key) def __getitem__(self, key): for c in self.subcontexts:",
"return except KeyError: continue raise KeyError(key) def __getitem__(self, key): for",
"name = Str(\"multidummy\") #: The underlying dictionary. subcontexts = List(Supports(IRestrictedContext,",
"from .utils import safe_repr @provides(IDataContext) class MultiContext(ListenableMixin, PersistableMixin, DictMixin): \"\"\"",
"set = False blocking_contexts = [] for c in self.subcontexts:",
"This file is open source software distributed according to the",
"True return False #### Trait Event Handlers ################################################## @on_trait_change('subcontexts:items_modified') def",
"c in self.subcontexts: try: del c[key] return except KeyError: continue",
"this is actually a fairly deep copy. All of the",
"= %s' % (key, safe_repr(value))) set = False blocking_contexts =",
"Returns ------- copy : IContext \"\"\" copy = self.clone_traits() new_subcontexts",
"from __future__ import absolute_import from itertools import chain from collections",
"TX # All right reserved. # # This file is",
"ValueError('Disallowed mapping: %s = %s' % (key, safe_repr(value))) set =",
"the key/value pair cannot be assigned to anything, no deletion",
"event): \"\"\" Trait listener for items of subcontexts list. \"\"\"",
"checkpointed versions of the context for implementing an undo/redo stack.",
"context for implementing an undo/redo stack. They may not be",
"return '%s(name=%r)' % (type(self).__name__, self.name) #### IRestrictedContext interface ########################################## def",
"added = [] removed = [] # Add to the",
"\"\"\" added = [] removed = [] # Add to",
"has the key, but does not allow the assignment, then",
"Nothing to do. return event.veto = self.veto_subcontext_modified self._fire_event(added=event.added, removed=event.removed, modified=event.modified,",
"# Add to the list of items added if len(event.added):",
"False def __delitem__(self, key): \"\"\" Remove the given key with",
"%s' % (key, safe_repr(value))) set = False blocking_contexts = []",
"versions of the context for implementing an undo/redo stack. They",
"[] else: added = [key] modified = [] c[key] =",
"def __init__(self, *subcontexts, **traits): subcontexts = list(subcontexts) super(MultiContext, self).__init__(subcontexts=subcontexts, **traits)",
"= [] current_value = c[key] try: is_modified = bool(current_value !=",
"in c: added = [] current_value = c[key] try: is_modified",
"from collections import MutableMapping as DictMixin from traits.api import (Bool,",
"Pass events up. \"\"\" if event is Undefined: # Nothing",
"[] for c in self.subcontexts: if not set: if c.allows(value,",
"keys(self): return list(set(chain(*[list(c.keys()) for c in self.subcontexts]))) # Expose DictMixin's",
"of the key. Parameters ---------- key : str Raises ------",
"Trait Event Handlers ################################################## @on_trait_change('subcontexts:items_modified') def subcontexts_items_modified(self, event): \"\"\" Pass",
"shallowly copied:: copy = context.shallow_copy() copy[key] is context[key] for key",
"key): for c in self.subcontexts: if key in c: return",
"c.allows(value, key): if key in c: added = [] current_value",
"added if len(event.added): for context in event.added: added.extend(list(context.keys())) # Add",
"but the actual dictionary storage will be shallowly copied:: copy",
"def subcontexts_items_modified(self, event): \"\"\" Pass events up. \"\"\" if event",
"Trait listener for items of subcontexts list. \"\"\" added =",
"---------- key : str Raises ------ KeyError if the kew",
"removed=removed) #### ICheckpointable interface ############################################ def checkpoint(self): \"\"\" Make a",
"2013 Enthought, Inc., Austin, TX # All right reserved. #",
"instance of the key. Parameters ---------- key : str Raises",
"Let subtypes dictate compatibility independently of contained contexts if not",
"#: The name of the context. name = Str(\"multidummy\") #:",
"deletion will take place. Parameters ---------- key : str value",
"%s = %s' % (key, safe_repr(value))) def keys(self): return list(set(chain(*[list(c.keys())",
"place. Parameters ---------- key : str value : object Raises",
"modified events veto_subcontext_modified = Bool(True) def __init__(self, *subcontexts, **traits): subcontexts",
".i_context import ICheckpointable, IDataContext, IRestrictedContext from .utils import safe_repr @provides(IDataContext)",
"for implementing an undo/redo stack. They may not be useful",
"All right reserved. # # This file is open source",
"\"\"\" #: The name of the context. name = Str(\"multidummy\")",
"string subcontext_str = '[%s]' % ', '.join([str(x) for x in",
"self.subcontexts]) return '%s(name=%r, subcontexts=%s)' % (type(self).__name__, self.name, subcontext_str) def __repr__(self):",
"object structure should be replicated, but the actual dictionary storage",
"c in self.subcontexts: if c.allows(value, name=name): return True return False",
"semantics are useful for saving out checkpointed versions of the",
"in self.subcontexts: try: del c[key] return except KeyError: continue raise",
"context. Technically, this is actually a fairly deep copy. All",
"key : str value : object Raises ------ ValueError if",
"good default string subcontext_str = '[%s]' % ', '.join([str(x) for",
"several subcontexts. \"\"\" #: The name of the context. name",
"useful for saving out checkpointed versions of the context for",
"#################################################### def __iter__(self): return iter(self.keys()) def __len__(self): return len(list(self.keys())) def",
"for context in event.added: added.extend(list(context.keys())) # Add to the list",
"current_value is not value if is_modified: modified = [key] c[key]",
"#: The underlying dictionary. subcontexts = List(Supports(IRestrictedContext, factory=DataContext)) #: Suppress",
"elif key in c: # Record this context as blocking",
"events up. \"\"\" if event is Undefined: # Nothing to",
"checkpointable_subcontext = adapt(context, ICheckpointable) new_subcontexts.append(checkpointable_subcontext.checkpoint()) copy.subcontexts = new_subcontexts return copy",
"dictionary storage will be shallowly copied:: copy = context.shallow_copy() copy[key]",
"c: # Record this context as blocking access to the",
"c[key] = value else: modified = [] else: added =",
"event.removed: removed.extend(list(context.keys())) self._fire_event(added=added, removed=removed) #### ICheckpointable interface ############################################ def checkpoint(self):",
"import DataContext, ListenableMixin, PersistableMixin from .i_context import ICheckpointable, IDataContext, IRestrictedContext",
"Raises ------ KeyError if the kew is not available in",
"may not be useful for other purposes. Returns ------- copy",
"\"\"\" Pass events up. \"\"\" if event is Undefined: #",
"out checkpointed versions of the context for implementing an undo/redo",
"a shallow copy of the context. Technically, this is actually",
"############################################ def checkpoint(self): \"\"\" Make a shallow copy of the",
"def allows(self, value, name=None): for c in self.subcontexts: if c.allows(value,",
"then that key will be deleted. Later contexts with the",
"subcontexts_items_modified(self, event): \"\"\" Pass events up. \"\"\" if event is",
"True return False def __delitem__(self, key): \"\"\" Remove the given",
"terms in # LICENSE.txt # \"\"\" Context holding multiple subcontexts.",
"no deletion will take place. Parameters ---------- key : str",
"be untouched. If the key/value pair cannot be assigned to",
"deletes the first instance of the key. Parameters ---------- key",
"in self.subcontexts: if not set: if c.allows(value, key): if key",
"%s' % (key, safe_repr(value))) def keys(self): return list(set(chain(*[list(c.keys()) for c",
"__delitem__(self, key): \"\"\" Remove the given key with [] access.",
"stack. They may not be useful for other purposes. Returns",
"def _subcontexts_items_changed(self, event): \"\"\" Trait listener for items of subcontexts",
"for items of subcontexts list. \"\"\" added = [] removed",
"Only deletes the first instance of the key. Parameters ----------",
"key in c: # Record this context as blocking access",
"Wrap several subcontexts. \"\"\" #: The name of the context.",
"IContext \"\"\" copy = self.clone_traits() new_subcontexts = [] for context",
"key with [] access. Only deletes the first instance of",
"dictionary. subcontexts = List(Supports(IRestrictedContext, factory=DataContext)) #: Suppress subcontext modified events",
"if the key is not permitted to be assigned that",
"is not value if is_modified: modified = [key] c[key] =",
"on_trait_change) from .data_context import DataContext, ListenableMixin, PersistableMixin from .i_context import",
"raise KeyError(key) def __getitem__(self, key): for c in self.subcontexts: try:",
"event.veto = self.veto_subcontext_modified self._fire_event(added=event.added, removed=event.removed, modified=event.modified, context=event.context) def _subcontexts_items_changed(self, event):",
"key : str Raises ------ KeyError if the kew is",
"key/value pair cannot be assigned to anything, no deletion will",
"be assigned that value. \"\"\" # Let subtypes dictate compatibility",
"= bool(current_value != value) except Exception: is_modified = current_value is",
"Inc., Austin, TX # All right reserved. # # This",
"Context holding multiple subcontexts. \"\"\" from __future__ import absolute_import from",
"adapt, provides, on_trait_change) from .data_context import DataContext, ListenableMixin, PersistableMixin from",
"useful for other purposes. Returns ------- copy : IContext \"\"\"",
"is not permitted to be assigned that value. \"\"\" #",
"given key with [] access. Only deletes the first instance",
"if not set: raise ValueError('Disallowed mapping: %s = %s' %",
"copied:: copy = context.shallow_copy() copy[key] is context[key] for key in",
"################################################## @on_trait_change('subcontexts:items_modified') def subcontexts_items_modified(self, event): \"\"\" Pass events up. \"\"\"",
"of the context. Technically, this is actually a fairly deep",
"\"\"\" Remove the given key with [] access. Only deletes",
"# All right reserved. # # This file is open",
"be shallowly copied:: copy = context.shallow_copy() copy[key] is context[key] for",
"= [] else: added = [key] modified = [] c[key]",
"context as blocking access to the final # location of",
"subcontexts = List(Supports(IRestrictedContext, factory=DataContext)) #: Suppress subcontext modified events veto_subcontext_modified",
"[key] c[key] = value else: modified = [] else: added",
"LICENSE.txt # \"\"\" Context holding multiple subcontexts. \"\"\" from __future__",
"copy = context.shallow_copy() copy[key] is context[key] for key in context.keys()",
"context. name = Str(\"multidummy\") #: The underlying dictionary. subcontexts =",
"def __contains__(self, key): for c in self.subcontexts: if key in",
"be useful for other purposes. Returns ------- copy : IContext",
"collections import MutableMapping as DictMixin from traits.api import (Bool, List,",
"the key is not permitted to be assigned that value.",
"interface ########################################## def allows(self, value, name=None): for c in self.subcontexts:",
"########################################## def allows(self, value, name=None): for c in self.subcontexts: if",
"return True return False #### Trait Event Handlers ################################################## @on_trait_change('subcontexts:items_modified')",
"of subcontexts list. \"\"\" added = [] removed = []",
"DictMixin): \"\"\" Wrap several subcontexts. \"\"\" #: The name of",
"modified=event.modified, context=event.context) def _subcontexts_items_changed(self, event): \"\"\" Trait listener for items",
"for context in event.removed: removed.extend(list(context.keys())) self._fire_event(added=added, removed=removed) #### ICheckpointable interface",
"subcontexts. \"\"\" #: The name of the context. name =",
".data_context import DataContext, ListenableMixin, PersistableMixin from .i_context import ICheckpointable, IDataContext,",
"not be useful for other purposes. Returns ------- copy :",
"context in event.removed: removed.extend(list(context.keys())) self._fire_event(added=added, removed=removed) #### ICheckpointable interface ############################################",
"first instance of the key. Parameters ---------- key : str",
"list. \"\"\" added = [] removed = [] # Add",
"% (type(self).__name__, self.name) #### IRestrictedContext interface ########################################## def allows(self, value,",
"the context for implementing an undo/redo stack. They may not",
"to anything, no deletion will take place. Parameters ---------- key",
"is not available in the context. \"\"\" for c in",
"self).__init__(subcontexts=subcontexts, **traits) #### IContext interface #################################################### def __iter__(self): return iter(self.keys())",
"not set: if c.allows(value, key): if key in c: added",
"name=name): return True return False #### Trait Event Handlers ##################################################",
"should be replicated, but the actual dictionary storage will be",
"do. return event.veto = self.veto_subcontext_modified self._fire_event(added=event.added, removed=event.removed, modified=event.modified, context=event.context) def",
"blocking instances. for c in blocking_contexts: del c[key] if not",
"def __iter__(self): return iter(self.keys()) def __len__(self): return len(list(self.keys())) def __contains__(self,",
"c: added = [] current_value = c[key] try: is_modified =",
"continue raise KeyError(key) def __setitem__(self, key, value): \"\"\" Set item",
"import ICheckpointable, IDataContext, IRestrictedContext from .utils import safe_repr @provides(IDataContext) class",
"of contained contexts if not self.allows(value, key): raise ValueError('Disallowed mapping:",
"final # location of the value. blocking_contexts.append(c) # Remove all",
"= Str(\"multidummy\") #: The underlying dictionary. subcontexts = List(Supports(IRestrictedContext, factory=DataContext))",
"__future__ import absolute_import from itertools import chain from collections import",
"the kew is not available in the context. \"\"\" for",
"source software distributed according to the terms in # LICENSE.txt",
"if len(event.removed): for context in event.removed: removed.extend(list(context.keys())) self._fire_event(added=added, removed=removed) ####",
"for other purposes. Returns ------- copy : IContext \"\"\" copy",
"value if is_modified: modified = [key] c[key] = value else:",
"file is open source software distributed according to the terms",
"= [key] modified = [] c[key] = value set =",
"blocking access to the final # location of the value.",
"__repr__(self): # Maybe a good default representation return '%s(name=%r)' %",
"from .i_context import ICheckpointable, IDataContext, IRestrictedContext from .utils import safe_repr",
"KeyError: continue raise KeyError(key) def __setitem__(self, key, value): \"\"\" Set",
"event is Undefined: # Nothing to do. return event.veto =",
"self.subcontexts: try: del c[key] return except KeyError: continue raise KeyError(key)",
"(type(self).__name__, self.name) #### IRestrictedContext interface ########################################## def allows(self, value, name=None):",
"self.subcontexts: if key in c: return True return False def",
"actually a fairly deep copy. All of the object structure",
"according to the terms in # LICENSE.txt # \"\"\" Context",
"(Bool, List, Str, Undefined, Supports, adapt, provides, on_trait_change) from .data_context",
"Maybe a good default representation return '%s(name=%r)' % (type(self).__name__, self.name)",
"self.clone_traits() new_subcontexts = [] for context in self.subcontexts: checkpointable_subcontext =",
"Event Handlers ################################################## @on_trait_change('subcontexts:items_modified') def subcontexts_items_modified(self, event): \"\"\" Pass events",
"c: return True return False def __delitem__(self, key): \"\"\" Remove",
"permitted to be assigned that value. \"\"\" # Let subtypes",
"**traits) #### IContext interface #################################################### def __iter__(self): return iter(self.keys()) def",
"[key] modified = [] c[key] = value set = True",
"= value else: modified = [] else: added = [key]",
"in c: # Record this context as blocking access to",
"list of items added if len(event.added): for context in event.added:",
"\"\"\" if event is Undefined: # Nothing to do. return",
"reserved. # # This file is open source software distributed",
"'.join([str(x) for x in self.subcontexts]) return '%s(name=%r, subcontexts=%s)' % (type(self).__name__,",
"name=None): for c in self.subcontexts: if c.allows(value, name=name): return True",
"def __delitem__(self, key): \"\"\" Remove the given key with []",
"veto_subcontext_modified = Bool(True) def __init__(self, *subcontexts, **traits): subcontexts = list(subcontexts)",
"location of the value. blocking_contexts.append(c) # Remove all blocking instances.",
"'%s(name=%r, subcontexts=%s)' % (type(self).__name__, self.name, subcontext_str) def __repr__(self): # Maybe",
"for context in self.subcontexts: checkpointable_subcontext = adapt(context, ICheckpointable) new_subcontexts.append(checkpointable_subcontext.checkpoint()) copy.subcontexts",
"in event.removed: removed.extend(list(context.keys())) self._fire_event(added=added, removed=removed) #### ICheckpointable interface ############################################ def",
"in blocking_contexts: del c[key] if not set: raise ValueError('Disallowed mapping:",
"key in c: added = [] current_value = c[key] try:",
"modified = [] c[key] = value set = True break",
"(C) Copyright 2013 Enthought, Inc., Austin, TX # All right",
"c in blocking_contexts: del c[key] if not set: raise ValueError('Disallowed",
"copy. All of the object structure should be replicated, but",
"\"\"\" Make a shallow copy of the context. Technically, this",
"len(event.added): for context in event.added: added.extend(list(context.keys())) # Add to the",
"items removed if len(event.removed): for context in event.removed: removed.extend(list(context.keys())) self._fire_event(added=added,",
"assignment, then that key will be deleted. Later contexts with",
"import chain from collections import MutableMapping as DictMixin from traits.api",
"If an earlier subcontext has the key, but does not",
"# Maybe a good default string subcontext_str = '[%s]' %",
"for c in self.subcontexts: if c.allows(value, name=name): return True return",
"MultiContext(ListenableMixin, PersistableMixin, DictMixin): \"\"\" Wrap several subcontexts. \"\"\" #: The",
"key in c: return True return False def __delitem__(self, key):",
"compatibility independently of contained contexts if not self.allows(value, key): raise",
"is Undefined: # Nothing to do. return event.veto = self.veto_subcontext_modified",
"except KeyError: continue raise KeyError(key) def __getitem__(self, key): for c",
"Raises ------ ValueError if the key is not permitted to",
"str value : object Raises ------ ValueError if the key",
"fairly deep copy. All of the object structure should be",
"itertools import chain from collections import MutableMapping as DictMixin from",
"be deleted. Later contexts with the key will be untouched.",
"subcontexts. \"\"\" from __future__ import absolute_import from itertools import chain",
"in self.subcontexts: try: return c[key] except KeyError: continue raise KeyError(key)",
"mapping: %s = %s' % (key, safe_repr(value))) set = False",
"interface ############################################ def checkpoint(self): \"\"\" Make a shallow copy of",
"removed = [] # Add to the list of items",
"Set item with [] access. The first subcontext which allows",
"up. \"\"\" if event is Undefined: # Nothing to do.",
"del c[key] if not set: raise ValueError('Disallowed mapping: %s =",
"(type(self).__name__, self.name, subcontext_str) def __repr__(self): # Maybe a good default",
"key): raise ValueError('Disallowed mapping: %s = %s' % (key, safe_repr(value)))",
"[] access. Only deletes the first instance of the key.",
"# Let subtypes dictate compatibility independently of contained contexts if",
"\"\"\" Wrap several subcontexts. \"\"\" #: The name of the",
"representation return '%s(name=%r)' % (type(self).__name__, self.name) #### IRestrictedContext interface ##########################################",
"Remove all blocking instances. for c in blocking_contexts: del c[key]",
"DataContext, ListenableMixin, PersistableMixin from .i_context import ICheckpointable, IDataContext, IRestrictedContext from",
"except Exception: is_modified = current_value is not value if is_modified:",
"in self.subcontexts]) return '%s(name=%r, subcontexts=%s)' % (type(self).__name__, self.name, subcontext_str) def",
"of items removed if len(event.removed): for context in event.removed: removed.extend(list(context.keys()))",
"undo/redo stack. They may not be useful for other purposes.",
"= %s' % (key, safe_repr(value))) def keys(self): return list(set(chain(*[list(c.keys()) for",
"key in context.keys() These semantics are useful for saving out",
"traits.api import (Bool, List, Str, Undefined, Supports, adapt, provides, on_trait_change)",
"Undefined: # Nothing to do. return event.veto = self.veto_subcontext_modified self._fire_event(added=event.added,",
"it. If an earlier subcontext has the key, but does",
"= List(Supports(IRestrictedContext, factory=DataContext)) #: Suppress subcontext modified events veto_subcontext_modified =",
"List(Supports(IRestrictedContext, factory=DataContext)) #: Suppress subcontext modified events veto_subcontext_modified = Bool(True)",
"list(set(chain(*[list(c.keys()) for c in self.subcontexts]))) # Expose DictMixin's get method",
"interface #################################################### def __iter__(self): return iter(self.keys()) def __len__(self): return len(list(self.keys()))",
"the context. name = Str(\"multidummy\") #: The underlying dictionary. subcontexts",
"an earlier subcontext has the key, but does not allow",
"return False def __delitem__(self, key): \"\"\" Remove the given key",
": str value : object Raises ------ ValueError if the",
"good default representation return '%s(name=%r)' % (type(self).__name__, self.name) #### IRestrictedContext",
"return '%s(name=%r, subcontexts=%s)' % (type(self).__name__, self.name, subcontext_str) def __repr__(self): #",
"subcontexts=%s)' % (type(self).__name__, self.name, subcontext_str) def __repr__(self): # Maybe a",
"ICheckpointable, IDataContext, IRestrictedContext from .utils import safe_repr @provides(IDataContext) class MultiContext(ListenableMixin,",
"value) except Exception: is_modified = current_value is not value if",
"anything, no deletion will take place. Parameters ---------- key :",
"name of the context. name = Str(\"multidummy\") #: The underlying",
"Exception: is_modified = current_value is not value if is_modified: modified",
"raise ValueError('Disallowed mapping: %s = %s' % (key, safe_repr(value))) def",
"the list of items added if len(event.added): for context in",
"for c in self.subcontexts: try: del c[key] return except KeyError:",
"DictMixin.get def __str__(self): # Maybe a good default string subcontext_str",
"Enthought, Inc., Austin, TX # All right reserved. # #",
"if c.allows(value, key): if key in c: added = []",
"will take place. Parameters ---------- key : str value :",
"# Nothing to do. return event.veto = self.veto_subcontext_modified self._fire_event(added=event.added, removed=event.removed,",
"**traits): subcontexts = list(subcontexts) super(MultiContext, self).__init__(subcontexts=subcontexts, **traits) #### IContext interface",
"value : object Raises ------ ValueError if the key is",
"added = [] current_value = c[key] try: is_modified = bool(current_value",
"List, Str, Undefined, Supports, adapt, provides, on_trait_change) from .data_context import",
"default representation return '%s(name=%r)' % (type(self).__name__, self.name) #### IRestrictedContext interface",
"ValueError('Disallowed mapping: %s = %s' % (key, safe_repr(value))) def keys(self):",
"the context. \"\"\" for c in self.subcontexts: try: del c[key]",
"super(MultiContext, self).__init__(subcontexts=subcontexts, **traits) #### IContext interface #################################################### def __iter__(self): return",
"except KeyError: continue raise KeyError(key) def __setitem__(self, key, value): \"\"\"",
"subcontext_str) def __repr__(self): # Maybe a good default representation return",
"return False #### Trait Event Handlers ################################################## @on_trait_change('subcontexts:items_modified') def subcontexts_items_modified(self,",
"cannot be assigned to anything, no deletion will take place.",
"list(subcontexts) super(MultiContext, self).__init__(subcontexts=subcontexts, **traits) #### IContext interface #################################################### def __iter__(self):",
"self._fire_event(added=event.added, removed=event.removed, modified=event.modified, context=event.context) def _subcontexts_items_changed(self, event): \"\"\" Trait listener",
"__getitem__(self, key): for c in self.subcontexts: try: return c[key] except",
"pair cannot be assigned to anything, no deletion will take",
"not permitted to be assigned that value. \"\"\" # Let",
"= [] for c in self.subcontexts: if not set: if",
"[] current_value = c[key] try: is_modified = bool(current_value != value)",
"IRestrictedContext interface ########################################## def allows(self, value, name=None): for c in",
"\"\"\" Trait listener for items of subcontexts list. \"\"\" added",
"DictMixin from traits.api import (Bool, List, Str, Undefined, Supports, adapt,",
"contexts if not self.allows(value, key): raise ValueError('Disallowed mapping: %s =",
"implementing an undo/redo stack. They may not be useful for",
"copy : IContext \"\"\" copy = self.clone_traits() new_subcontexts = []",
"import safe_repr @provides(IDataContext) class MultiContext(ListenableMixin, PersistableMixin, DictMixin): \"\"\" Wrap several",
"key): \"\"\" Remove the given key with [] access. Only",
"set: raise ValueError('Disallowed mapping: %s = %s' % (key, safe_repr(value)))",
"get method over HasTraits'. get = DictMixin.get def __str__(self): #",
"KeyError(key) def __setitem__(self, key, value): \"\"\" Set item with []",
"bool(current_value != value) except Exception: is_modified = current_value is not",
"[] access. The first subcontext which allows the key/value pair",
"They may not be useful for other purposes. Returns -------",
"removed.extend(list(context.keys())) self._fire_event(added=added, removed=removed) #### ICheckpointable interface ############################################ def checkpoint(self): \"\"\"",
"import MutableMapping as DictMixin from traits.api import (Bool, List, Str,",
"= False blocking_contexts = [] for c in self.subcontexts: if",
"key, but does not allow the assignment, then that key",
"access. Only deletes the first instance of the key. Parameters",
"IDataContext, IRestrictedContext from .utils import safe_repr @provides(IDataContext) class MultiContext(ListenableMixin, PersistableMixin,",
"method over HasTraits'. get = DictMixin.get def __str__(self): # Maybe",
"the object structure should be replicated, but the actual dictionary",
"copy[key] is context[key] for key in context.keys() These semantics are",
"absolute_import from itertools import chain from collections import MutableMapping as",
"added.extend(list(context.keys())) # Add to the list of items removed if",
"subcontext_str = '[%s]' % ', '.join([str(x) for x in self.subcontexts])",
"as DictMixin from traits.api import (Bool, List, Str, Undefined, Supports,",
"import (Bool, List, Str, Undefined, Supports, adapt, provides, on_trait_change) from",
"c in self.subcontexts: try: return c[key] except KeyError: continue raise",
"#### Trait Event Handlers ################################################## @on_trait_change('subcontexts:items_modified') def subcontexts_items_modified(self, event): \"\"\"",
"copy = self.clone_traits() new_subcontexts = [] for context in self.subcontexts:",
"if event is Undefined: # Nothing to do. return event.veto",
"that value. \"\"\" # Let subtypes dictate compatibility independently of",
"factory=DataContext)) #: Suppress subcontext modified events veto_subcontext_modified = Bool(True) def",
"is context[key] for key in context.keys() These semantics are useful",
"ValueError if the key is not permitted to be assigned",
"else: modified = [] else: added = [key] modified =",
"contexts with the key will be untouched. If the key/value",
"with the key will be untouched. If the key/value pair",
"[] removed = [] # Add to the list of",
"for c in self.subcontexts: if key in c: return True",
"PersistableMixin, DictMixin): \"\"\" Wrap several subcontexts. \"\"\" #: The name",
"subcontext has the key, but does not allow the assignment,",
"checkpoint(self): \"\"\" Make a shallow copy of the context. Technically,",
"These semantics are useful for saving out checkpointed versions of",
"% ', '.join([str(x) for x in self.subcontexts]) return '%s(name=%r, subcontexts=%s)'",
"= [] removed = [] # Add to the list",
"'[%s]' % ', '.join([str(x) for x in self.subcontexts]) return '%s(name=%r,",
"with [] access. The first subcontext which allows the key/value",
"KeyError if the kew is not available in the context.",
"------ ValueError if the key is not permitted to be",
"# Add to the list of items removed if len(event.removed):",
"def __len__(self): return len(list(self.keys())) def __contains__(self, key): for c in",
"= [] c[key] = value set = True break elif",
"list of items removed if len(event.removed): for context in event.removed:",
"# Maybe a good default representation return '%s(name=%r)' % (type(self).__name__,",
"of items added if len(event.added): for context in event.added: added.extend(list(context.keys()))",
"in context.keys() These semantics are useful for saving out checkpointed",
"from traits.api import (Bool, List, Str, Undefined, Supports, adapt, provides,",
"c[key] return except KeyError: continue raise KeyError(key) def __getitem__(self, key):",
"del c[key] return except KeyError: continue raise KeyError(key) def __getitem__(self,",
"dictate compatibility independently of contained contexts if not self.allows(value, key):",
"the key will be untouched. If the key/value pair cannot",
"[] # Add to the list of items added if",
"raise ValueError('Disallowed mapping: %s = %s' % (key, safe_repr(value))) set",
"chain from collections import MutableMapping as DictMixin from traits.api import",
"other purposes. Returns ------- copy : IContext \"\"\" copy =",
"is_modified = current_value is not value if is_modified: modified =",
"removed if len(event.removed): for context in event.removed: removed.extend(list(context.keys())) self._fire_event(added=added, removed=removed)",
"c[key] = value set = True break elif key in",
"access. The first subcontext which allows the key/value pair will",
"for c in self.subcontexts]))) # Expose DictMixin's get method over",
"@on_trait_change('subcontexts:items_modified') def subcontexts_items_modified(self, event): \"\"\" Pass events up. \"\"\" if",
"c.allows(value, name=name): return True return False #### Trait Event Handlers",
"= '[%s]' % ', '.join([str(x) for x in self.subcontexts]) return",
"if the kew is not available in the context. \"\"\"",
"context[key] for key in context.keys() These semantics are useful for",
"break elif key in c: # Record this context as",
"pair will get it. If an earlier subcontext has the",
"= [key] c[key] = value else: modified = [] else:",
"the given key with [] access. Only deletes the first",
"%s = %s' % (key, safe_repr(value))) set = False blocking_contexts",
"safe_repr @provides(IDataContext) class MultiContext(ListenableMixin, PersistableMixin, DictMixin): \"\"\" Wrap several subcontexts.",
"provides, on_trait_change) from .data_context import DataContext, ListenableMixin, PersistableMixin from .i_context",
"will be deleted. Later contexts with the key will be",
"key is not permitted to be assigned that value. \"\"\"",
"in self.subcontexts: checkpointable_subcontext = adapt(context, ICheckpointable) new_subcontexts.append(checkpointable_subcontext.checkpoint()) copy.subcontexts = new_subcontexts",
"in # LICENSE.txt # \"\"\" Context holding multiple subcontexts. \"\"\"",
"The first subcontext which allows the key/value pair will get",
"deleted. Later contexts with the key will be untouched. If",
"value set = True break elif key in c: #",
"will get it. If an earlier subcontext has the key,",
"blocking_contexts = [] for c in self.subcontexts: if not set:",
"if len(event.added): for context in event.added: added.extend(list(context.keys())) # Add to",
"self._fire_event(added=added, removed=removed) #### ICheckpointable interface ############################################ def checkpoint(self): \"\"\" Make",
"if not self.allows(value, key): raise ValueError('Disallowed mapping: %s = %s'",
"Add to the list of items added if len(event.added): for",
"Copyright 2013 Enthought, Inc., Austin, TX # All right reserved.",
"if key in c: return True return False def __delitem__(self,",
"else: added = [key] modified = [] c[key] = value",
"the actual dictionary storage will be shallowly copied:: copy =",
"# location of the value. blocking_contexts.append(c) # Remove all blocking",
"key): for c in self.subcontexts: try: return c[key] except KeyError:",
"multiple subcontexts. \"\"\" from __future__ import absolute_import from itertools import",
"this context as blocking access to the final # location",
"# Record this context as blocking access to the final",
": IContext \"\"\" copy = self.clone_traits() new_subcontexts = [] for",
"available in the context. \"\"\" for c in self.subcontexts: try:",
"c[key] if not set: raise ValueError('Disallowed mapping: %s = %s'",
": str Raises ------ KeyError if the kew is not",
"allow the assignment, then that key will be deleted. Later",
"modified = [] else: added = [key] modified = []",
"a good default string subcontext_str = '[%s]' % ', '.join([str(x)",
"key will be deleted. Later contexts with the key will",
"the terms in # LICENSE.txt # \"\"\" Context holding multiple",
"ICheckpointable interface ############################################ def checkpoint(self): \"\"\" Make a shallow copy",
"to the final # location of the value. blocking_contexts.append(c) #",
"False blocking_contexts = [] for c in self.subcontexts: if not",
"@provides(IDataContext) class MultiContext(ListenableMixin, PersistableMixin, DictMixin): \"\"\" Wrap several subcontexts. \"\"\"",
"instances. for c in blocking_contexts: del c[key] if not set:",
"Austin, TX # All right reserved. # # This file",
"= Bool(True) def __init__(self, *subcontexts, **traits): subcontexts = list(subcontexts) super(MultiContext,",
"self.subcontexts: checkpointable_subcontext = adapt(context, ICheckpointable) new_subcontexts.append(checkpointable_subcontext.checkpoint()) copy.subcontexts = new_subcontexts return",
"Undefined, Supports, adapt, provides, on_trait_change) from .data_context import DataContext, ListenableMixin,",
"allows the key/value pair will get it. If an earlier",
"value. \"\"\" # Let subtypes dictate compatibility independently of contained",
"an undo/redo stack. They may not be useful for other",
"\"\"\" # Let subtypes dictate compatibility independently of contained contexts",
"from .data_context import DataContext, ListenableMixin, PersistableMixin from .i_context import ICheckpointable,",
"for c in self.subcontexts: try: return c[key] except KeyError: continue",
"', '.join([str(x) for x in self.subcontexts]) return '%s(name=%r, subcontexts=%s)' %",
"to do. return event.veto = self.veto_subcontext_modified self._fire_event(added=event.added, removed=event.removed, modified=event.modified, context=event.context)",
"are useful for saving out checkpointed versions of the context",
"c[key] except KeyError: continue raise KeyError(key) def __setitem__(self, key, value):",
"in self.subcontexts]))) # Expose DictMixin's get method over HasTraits'. get",
"shallow copy of the context. Technically, this is actually a",
"the list of items removed if len(event.removed): for context in",
"value): \"\"\" Set item with [] access. The first subcontext",
"\"\"\" from __future__ import absolute_import from itertools import chain from",
"ListenableMixin, PersistableMixin from .i_context import ICheckpointable, IDataContext, IRestrictedContext from .utils",
"the assignment, then that key will be deleted. Later contexts",
"of the context for implementing an undo/redo stack. They may",
"Parameters ---------- key : str value : object Raises ------",
"False #### Trait Event Handlers ################################################## @on_trait_change('subcontexts:items_modified') def subcontexts_items_modified(self, event):",
"from itertools import chain from collections import MutableMapping as DictMixin",
"assigned to anything, no deletion will take place. Parameters ----------",
"------ KeyError if the kew is not available in the",
"software distributed according to the terms in # LICENSE.txt #",
"def __setitem__(self, key, value): \"\"\" Set item with [] access.",
"c in self.subcontexts: if not set: if c.allows(value, key): if",
"(key, safe_repr(value))) set = False blocking_contexts = [] for c",
"[] c[key] = value set = True break elif key",
"as blocking access to the final # location of the",
"for x in self.subcontexts]) return '%s(name=%r, subcontexts=%s)' % (type(self).__name__, self.name,",
"of the object structure should be replicated, but the actual",
"in event.added: added.extend(list(context.keys())) # Add to the list of items",
"__iter__(self): return iter(self.keys()) def __len__(self): return len(list(self.keys())) def __contains__(self, key):",
"import absolute_import from itertools import chain from collections import MutableMapping",
"If the key/value pair cannot be assigned to anything, no",
"saving out checkpointed versions of the context for implementing an",
"storage will be shallowly copied:: copy = context.shallow_copy() copy[key] is",
"not value if is_modified: modified = [key] c[key] = value",
"c[key] try: is_modified = bool(current_value != value) except Exception: is_modified",
"value else: modified = [] else: added = [key] modified",
"= c[key] try: is_modified = bool(current_value != value) except Exception:",
"return c[key] except KeyError: continue raise KeyError(key) def __setitem__(self, key,",
"The name of the context. name = Str(\"multidummy\") #: The",
"if c.allows(value, name=name): return True return False #### Trait Event",
"untouched. If the key/value pair cannot be assigned to anything,",
"Parameters ---------- key : str Raises ------ KeyError if the",
"the key, but does not allow the assignment, then that",
"holding multiple subcontexts. \"\"\" from __future__ import absolute_import from itertools",
"PersistableMixin from .i_context import ICheckpointable, IDataContext, IRestrictedContext from .utils import",
"the key. Parameters ---------- key : str Raises ------ KeyError",
"distributed according to the terms in # LICENSE.txt # \"\"\"",
"#### ICheckpointable interface ############################################ def checkpoint(self): \"\"\" Make a shallow",
"= list(subcontexts) super(MultiContext, self).__init__(subcontexts=subcontexts, **traits) #### IContext interface #################################################### def",
"Handlers ################################################## @on_trait_change('subcontexts:items_modified') def subcontexts_items_modified(self, event): \"\"\" Pass events up.",
"copy of the context. Technically, this is actually a fairly",
"All of the object structure should be replicated, but the",
"in self.subcontexts: if c.allows(value, name=name): return True return False ####",
"listener for items of subcontexts list. \"\"\" added = []",
"for saving out checkpointed versions of the context for implementing",
"structure should be replicated, but the actual dictionary storage will",
"c in self.subcontexts: if key in c: return True return",
"!= value) except Exception: is_modified = current_value is not value",
"right reserved. # # This file is open source software",
"for c in blocking_contexts: del c[key] if not set: raise",
"set: if c.allows(value, key): if key in c: added =",
"underlying dictionary. subcontexts = List(Supports(IRestrictedContext, factory=DataContext)) #: Suppress subcontext modified",
"in the context. \"\"\" for c in self.subcontexts: try: del",
"return list(set(chain(*[list(c.keys()) for c in self.subcontexts]))) # Expose DictMixin's get",
"__contains__(self, key): for c in self.subcontexts: if key in c:",
"Later contexts with the key will be untouched. If the",
"of the value. blocking_contexts.append(c) # Remove all blocking instances. for",
"c in self.subcontexts]))) # Expose DictMixin's get method over HasTraits'.",
"_subcontexts_items_changed(self, event): \"\"\" Trait listener for items of subcontexts list.",
"be replicated, but the actual dictionary storage will be shallowly",
"__len__(self): return len(list(self.keys())) def __contains__(self, key): for c in self.subcontexts:",
"#: Suppress subcontext modified events veto_subcontext_modified = Bool(True) def __init__(self,",
"= [] for context in self.subcontexts: checkpointable_subcontext = adapt(context, ICheckpointable)",
"be assigned to anything, no deletion will take place. Parameters",
"self.subcontexts: if not set: if c.allows(value, key): if key in",
"True break elif key in c: # Record this context",
"Suppress subcontext modified events veto_subcontext_modified = Bool(True) def __init__(self, *subcontexts,",
"# Expose DictMixin's get method over HasTraits'. get = DictMixin.get",
"to the list of items added if len(event.added): for context",
"Supports, adapt, provides, on_trait_change) from .data_context import DataContext, ListenableMixin, PersistableMixin",
"len(event.removed): for context in event.removed: removed.extend(list(context.keys())) self._fire_event(added=added, removed=removed) #### ICheckpointable",
"= current_value is not value if is_modified: modified = [key]",
"Record this context as blocking access to the final #",
"first subcontext which allows the key/value pair will get it.",
"= self.veto_subcontext_modified self._fire_event(added=event.added, removed=event.removed, modified=event.modified, context=event.context) def _subcontexts_items_changed(self, event): \"\"\"",
"mapping: %s = %s' % (key, safe_repr(value))) def keys(self): return",
"= self.clone_traits() new_subcontexts = [] for context in self.subcontexts: checkpointable_subcontext",
"is_modified = bool(current_value != value) except Exception: is_modified = current_value",
".utils import safe_repr @provides(IDataContext) class MultiContext(ListenableMixin, PersistableMixin, DictMixin): \"\"\" Wrap",
"blocking_contexts.append(c) # Remove all blocking instances. for c in blocking_contexts:",
"HasTraits'. get = DictMixin.get def __str__(self): # Maybe a good",
"actual dictionary storage will be shallowly copied:: copy = context.shallow_copy()",
"removed=event.removed, modified=event.modified, context=event.context) def _subcontexts_items_changed(self, event): \"\"\" Trait listener for",
"# (C) Copyright 2013 Enthought, Inc., Austin, TX # All",
"does not allow the assignment, then that key will be",
"that key will be deleted. Later contexts with the key",
"class MultiContext(ListenableMixin, PersistableMixin, DictMixin): \"\"\" Wrap several subcontexts. \"\"\" #:",
"KeyError(key) def __getitem__(self, key): for c in self.subcontexts: try: return",
"x in self.subcontexts]) return '%s(name=%r, subcontexts=%s)' % (type(self).__name__, self.name, subcontext_str)",
"new_subcontexts = [] for context in self.subcontexts: checkpointable_subcontext = adapt(context,",
"subcontext modified events veto_subcontext_modified = Bool(True) def __init__(self, *subcontexts, **traits):",
"= DictMixin.get def __str__(self): # Maybe a good default string",
"get it. If an earlier subcontext has the key, but",
"context=event.context) def _subcontexts_items_changed(self, event): \"\"\" Trait listener for items of",
"blocking_contexts: del c[key] if not set: raise ValueError('Disallowed mapping: %s",
"#### IContext interface #################################################### def __iter__(self): return iter(self.keys()) def __len__(self):",
"for c in self.subcontexts: if not set: if c.allows(value, key):",
"def keys(self): return list(set(chain(*[list(c.keys()) for c in self.subcontexts]))) # Expose",
"Expose DictMixin's get method over HasTraits'. get = DictMixin.get def",
"------- copy : IContext \"\"\" copy = self.clone_traits() new_subcontexts =",
"key will be untouched. If the key/value pair cannot be",
"def __str__(self): # Maybe a good default string subcontext_str =",
"Add to the list of items removed if len(event.removed): for",
"will be untouched. If the key/value pair cannot be assigned",
"items added if len(event.added): for context in event.added: added.extend(list(context.keys())) #",
"is actually a fairly deep copy. All of the object",
"# \"\"\" Context holding multiple subcontexts. \"\"\" from __future__ import",
"def __getitem__(self, key): for c in self.subcontexts: try: return c[key]",
"get = DictMixin.get def __str__(self): # Maybe a good default",
"contained contexts if not self.allows(value, key): raise ValueError('Disallowed mapping: %s",
"deep copy. All of the object structure should be replicated,",
"replicated, but the actual dictionary storage will be shallowly copied::",
"which allows the key/value pair will get it. If an",
"# LICENSE.txt # \"\"\" Context holding multiple subcontexts. \"\"\" from",
"independently of contained contexts if not self.allows(value, key): raise ValueError('Disallowed",
"context. \"\"\" for c in self.subcontexts: try: del c[key] return",
"'%s(name=%r)' % (type(self).__name__, self.name) #### IRestrictedContext interface ########################################## def allows(self,",
"to the terms in # LICENSE.txt # \"\"\" Context holding",
"# Remove all blocking instances. for c in blocking_contexts: del",
"Technically, this is actually a fairly deep copy. All of",
"def checkpoint(self): \"\"\" Make a shallow copy of the context.",
"context in self.subcontexts: checkpointable_subcontext = adapt(context, ICheckpointable) new_subcontexts.append(checkpointable_subcontext.checkpoint()) copy.subcontexts =",
"\"\"\" Set item with [] access. The first subcontext which",
"not set: raise ValueError('Disallowed mapping: %s = %s' % (key,",
"try: return c[key] except KeyError: continue raise KeyError(key) def __setitem__(self,",
"event): \"\"\" Pass events up. \"\"\" if event is Undefined:",
"#### IRestrictedContext interface ########################################## def allows(self, value, name=None): for c",
"allows(self, value, name=None): for c in self.subcontexts: if c.allows(value, name=name):",
"self.name, subcontext_str) def __repr__(self): # Maybe a good default representation"
] |
[
"> var_two: if var_two*var_three > var_one: return \"blab\" #this happens",
"\"\" #import things import math #define things def some_function(var_one, var_two,",
"test the line_counter performance in python This is a multiline",
"var_one: return \"blab\" #this happens else: return \"blob\" else: return",
"performance in python This is a multiline doctest \"\"\" __author__",
"in python This is a multiline doctest \"\"\" __author__ =",
"var_two*var_three > var_one: return \"blab\" #this happens else: return \"blob\"",
"var_one > var_two: if var_two*var_three > var_one: return \"blab\" #this",
"a multiline doctest \"\"\" __author__ = \"<NAME>\" __copyright__ = \"\"",
"__maintainer__ = \"<NAME>\" __email__ = \"\" __status__ = \"\" #import",
"function that do things\"\"\" if var_one > var_two: if var_two*var_three",
"file to test the line_counter performance in python This is",
"that do things\"\"\" if var_one > var_two: if var_two*var_three >",
"\"<NAME>\" __copyright__ = \"\" __credits__ = [\"<NAME>\"] __license__ = \"MIT\"",
"var_two, var_three): \"\"\"This is a function that do things\"\"\" if",
"def some_function(var_one, var_two, var_three): \"\"\"This is a function that do",
"line_counter performance in python This is a multiline doctest \"\"\"",
"This is a multiline doctest \"\"\" __author__ = \"<NAME>\" __copyright__",
"is a multiline doctest \"\"\" __author__ = \"<NAME>\" __copyright__ =",
"doctest \"\"\" __author__ = \"<NAME>\" __copyright__ = \"\" __credits__ =",
"python This is a multiline doctest \"\"\" __author__ = \"<NAME>\"",
"__author__ = \"<NAME>\" __copyright__ = \"\" __credits__ = [\"<NAME>\"] __license__",
"simple file to test the line_counter performance in python This",
"= \"\" __credits__ = [\"<NAME>\"] __license__ = \"MIT\" __version__ =",
"= \"1.0.1\" __maintainer__ = \"<NAME>\" __email__ = \"\" __status__ =",
"multiline doctest \"\"\" __author__ = \"<NAME>\" __copyright__ = \"\" __credits__",
"#define things def some_function(var_one, var_two, var_three): \"\"\"This is a function",
"var_two: if var_two*var_three > var_one: return \"blab\" #this happens else:",
"some_function(var_one, var_two, var_three): \"\"\"This is a function that do things\"\"\"",
"= [\"<NAME>\"] __license__ = \"MIT\" __version__ = \"1.0.1\" __maintainer__ =",
"import math #define things def some_function(var_one, var_two, var_three): \"\"\"This is",
"__email__ = \"\" __status__ = \"\" #import things import math",
"#import things import math #define things def some_function(var_one, var_two, var_three):",
"= \"\" #import things import math #define things def some_function(var_one,",
"\"\"\" __author__ = \"<NAME>\" __copyright__ = \"\" __credits__ = [\"<NAME>\"]",
"do things\"\"\" if var_one > var_two: if var_two*var_three > var_one:",
"__copyright__ = \"\" __credits__ = [\"<NAME>\"] __license__ = \"MIT\" __version__",
"var_three): \"\"\"This is a function that do things\"\"\" if var_one",
"= \"MIT\" __version__ = \"1.0.1\" __maintainer__ = \"<NAME>\" __email__ =",
"__status__ = \"\" #import things import math #define things def",
"\"\" __status__ = \"\" #import things import math #define things",
"\"MIT\" __version__ = \"1.0.1\" __maintainer__ = \"<NAME>\" __email__ = \"\"",
"things\"\"\" if var_one > var_two: if var_two*var_three > var_one: return",
"\"<NAME>\" __email__ = \"\" __status__ = \"\" #import things import",
"the line_counter performance in python This is a multiline doctest",
"things def some_function(var_one, var_two, var_three): \"\"\"This is a function that",
"is a function that do things\"\"\" if var_one > var_two:",
"__license__ = \"MIT\" __version__ = \"1.0.1\" __maintainer__ = \"<NAME>\" __email__",
"\"1.0.1\" __maintainer__ = \"<NAME>\" __email__ = \"\" __status__ = \"\"",
"= \"<NAME>\" __copyright__ = \"\" __credits__ = [\"<NAME>\"] __license__ =",
"= \"\" __status__ = \"\" #import things import math #define",
"return \"blab\" #this happens else: return \"blob\" else: return \"fish\"",
"to test the line_counter performance in python This is a",
"a function that do things\"\"\" if var_one > var_two: if",
"math #define things def some_function(var_one, var_two, var_three): \"\"\"This is a",
"= \"<NAME>\" __email__ = \"\" __status__ = \"\" #import things",
"if var_one > var_two: if var_two*var_three > var_one: return \"blab\"",
"__version__ = \"1.0.1\" __maintainer__ = \"<NAME>\" __email__ = \"\" __status__",
"\"\"\"This is a function that do things\"\"\" if var_one >",
"\"\"\"A simple file to test the line_counter performance in python",
"[\"<NAME>\"] __license__ = \"MIT\" __version__ = \"1.0.1\" __maintainer__ = \"<NAME>\"",
"things import math #define things def some_function(var_one, var_two, var_three): \"\"\"This",
"> var_one: return \"blab\" #this happens else: return \"blob\" else:",
"if var_two*var_three > var_one: return \"blab\" #this happens else: return",
"\"\" __credits__ = [\"<NAME>\"] __license__ = \"MIT\" __version__ = \"1.0.1\"",
"__credits__ = [\"<NAME>\"] __license__ = \"MIT\" __version__ = \"1.0.1\" __maintainer__"
] |
[
"Continuous elif isinstance(examples[0], float) or isinstance(examples[0], int): example_type = 'continuous'",
"to whether they are \"input\", \"predict\", or \"control\" variables. batch_size:",
"generator over featurized examples. \"\"\" assert isinstance(examples, list), 'examples must",
"ex: float(ex) else: featurizer = lambda ex: ex # Categorical",
"pandas.df. The data we want to iterate over. The columns",
"{ 'control': var_type == 'control', 'name': var_name, 'type': varType, 'vocab':",
"dtype=dtype) feature_names = sorted(featurized_data.keys()) data = TensorDataset(*[to_tensor(name) for name in",
"Maximum length of text sequences. Returns: A generator which yields",
"in feature_names]) dataloader = DataLoader( dataset=data, sampler=RandomSampler(data), collate_fn=lambda batch: [torch.stack(x)",
"to tensors of batched data. \"\"\" def featurize(featurizer): return [featurizer(ex)",
"info about this variable as well as a generator over",
"= 0 def featurizer(example): ids = [] for n in",
"var_type in name_to_type.items(): examples = list(df[var_name]) if var_type == 'input':",
"datatype. batch_size=batch_size) def iterator(): for batch in dataloader: yield dict(zip(feature_names,",
"provide a vocab.' example_type = 'input' vocab = ['UNK', 'PAD']",
"[featurizer(ex) for ex in examples] var_info = defaultdict(lambda: OrderedDict()) featurized_data",
"isinstance(examples[0], str): example_type = 'categorical' if not vocab: vocab =",
"data = TensorDataset(*[to_tensor(name) for name in feature_names]) dataloader = DataLoader(",
"Categorical elif isinstance(examples[0], str): example_type = 'categorical' if not vocab:",
"names to whether they are \"input\", \"predict\", or \"control\" variables.",
"examples] featurizer, _, vocab = get_info(examples, vocab, max_seq_len) var_info[var_name] =",
"'categorical' if not vocab: vocab = ['UNK'] + sorted(list(set(examples))) tok2id",
"torch def get_info(examples, vocab=None, max_seq_len=256): \"\"\"Gathers info on and creats",
"vocab) unk_id = 0 def featurizer(example): ids = [] for",
"= defaultdict(lambda: OrderedDict()) featurized_data = defaultdict(list) for var_name, var_type in",
"example list!' # Text if isinstance(examples[0], list): assert vocab is",
"x in toks] ids = ids[:max_seq_len] padded_ids = ids +",
"and outcomes. Args: vocab: list(str). The vocabulary to use. df:",
"# Text if isinstance(examples[0], list): assert vocab is not None,",
"text or categorical). max_seq_len: int. maximum sequence length for text",
"{ 'control': False, 'name': var_name, 'type': var_type, 'vocab': vocab }",
"in name_to_type.items(): examples = list(df[var_name]) if var_type == 'input': examples",
"vocab = get_info(examples, vocab, max_seq_len) var_info[var_name] = { 'control': False,",
"DataLoader, RandomSampler, SequentialSampler import torch def get_info(examples, vocab=None, max_seq_len=256): \"\"\"Gathers",
"[torch.stack(x) for x in zip(*batch)], # group by datatype. batch_size=batch_size)",
"# 0 is the unk id. else: print(\"ERROR: unrecognized example",
"tok in enumerate(vocab)} ngrams = max(len(x.split()) for x in vocab)",
"examples[0]) quit() return featurizer, example_type, vocab def get_iterator(vocab, df, name_to_type,",
"outcomes. Args: vocab: list(str). The vocabulary to use. df: pandas.df.",
"mapping from variable names to whether they are \"input\", \"predict\",",
"as well as a generator over featurized examples. \"\"\" assert",
"the keys in name_to_type. name_to_type: dict. A mapping from variable",
"['UNK'] + sorted(list(set(examples))) tok2id = {tok: i for i, tok",
"or categorical). max_seq_len: int. maximum sequence length for text examples.",
"= defaultdict(list) for var_name, var_type in name_to_type.items(): examples = list(df[var_name])",
"data we want to iterate over. The columns of these",
"'input' vocab = ['UNK', 'PAD'] + vocab tok2id = {tok:",
"list(str). The vocabulary to use. df: pandas.df. The data we",
"if var_info[var_name]['type'] in {'categorical', 'input'}: dtype = torch.long return torch.tensor(featurized_data[var_name],",
"we want to iterate over. The columns of these data",
"'control': var_type == 'control', 'name': var_name, 'type': varType, 'vocab': vocab",
"0 is the unk id. else: print(\"ERROR: unrecognized example type:",
"= ['N/A'] if isinstance(examples[0], int): featurizer = lambda ex: float(ex)",
"int. The batch size to use. max_seq_len: int. Maximum length",
"in enumerate(vocab)} featurizer = lambda ex: tok2id.get(ex, 0) # 0",
"- len(ids))) # pad idx = 1 return padded_ids #",
"isinstance(examples[0], list): assert vocab is not None, 'ERROR: must provide",
"None, 'ERROR: must provide a vocab.' example_type = 'input' vocab",
"vocab def get_iterator(vocab, df, name_to_type, batch_size=32, max_seq_len=256): \"\"\"Builds a data",
"for name in feature_names]) dataloader = DataLoader( dataset=data, sampler=RandomSampler(data), collate_fn=lambda",
"The batch size to use. max_seq_len: int. Maximum length of",
"= { 'control': var_type == 'control', 'name': var_name, 'type': varType,",
"for x in zip(*batch)], # group by datatype. batch_size=batch_size) def",
"if var_type == 'input': examples = [x.split() for x in",
"idx = 1 return padded_ids # Continuous elif isinstance(examples[0], float)",
"else: featurizer, varType, vocab = get_info(examples) var_info[var_name] = { 'control':",
"for i, tok in enumerate(vocab)} featurizer = lambda ex: tok2id.get(ex,",
"[' '.join(example[i: i + n]) for i in range(len(example) -",
"sorted(list(set(examples))) tok2id = {tok: i for i, tok in enumerate(vocab)}",
"x in vocab) unk_id = 0 def featurizer(example): ids =",
"zip(*batch)], # group by datatype. batch_size=batch_size) def iterator(): for batch",
"['UNK', 'PAD'] + vocab tok2id = {tok: i for i,",
"featurizer = lambda ex: float(ex) else: featurizer = lambda ex:",
"if isinstance(examples[0], list): assert vocab is not None, 'ERROR: must",
"Returns: A generator which yields dictionaries where variable names are",
"assert vocab is not None, 'ERROR: must provide a vocab.'",
"torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler import torch def get_info(examples,",
"featurizer, _, vocab = get_info(examples, vocab, max_seq_len) var_info[var_name] = {",
"sampler=RandomSampler(data), collate_fn=lambda batch: [torch.stack(x) for x in zip(*batch)], # group",
"ex # Categorical elif isinstance(examples[0], str): example_type = 'categorical' if",
"for i in range(len(example) - n + 1)] ids +=",
"lambda ex: ex # Categorical elif isinstance(examples[0], str): example_type =",
"to use. df: pandas.df. The data we want to iterate",
"\"\"\" def featurize(featurizer): return [featurizer(ex) for ex in examples] var_info",
"isinstance(examples[0], float) or isinstance(examples[0], int): example_type = 'continuous' vocab =",
"isinstance(examples[0], int): featurizer = lambda ex: float(ex) else: featurizer =",
"vocab=None, max_seq_len=256): \"\"\"Gathers info on and creats a featurized example",
"discrete datatypes (e.g. text or categorical). max_seq_len: int. maximum sequence",
"int. Maximum length of text sequences. Returns: A generator which",
"dict of info about this variable as well as a",
"be list; got ' + str(type(examples)) assert len(examples) > 0,",
"The vocabulary to use. df: pandas.df. The data we want",
"= get_info(examples) var_info[var_name] = { 'control': var_type == 'control', 'name':",
"= [] for n in range(1, ngrams + 1): toks",
"import torch def get_info(examples, vocab=None, max_seq_len=256): \"\"\"Gathers info on and",
"of text sequences. Returns: A generator which yields dictionaries where",
"+ n]) for i in range(len(example) - n + 1)]",
"varType, vocab = get_info(examples) var_info[var_name] = { 'control': var_type ==",
"[x.split() for x in examples] featurizer, _, vocab = get_info(examples,",
"= get_info(examples, vocab, max_seq_len) var_info[var_name] = { 'control': False, 'name':",
"([1] * (max_seq_len - len(ids))) # pad idx = 1",
"i in range(len(example) - n + 1)] ids += [tok2id.get(x,",
"batch_size=32, max_seq_len=256): \"\"\"Builds a data iterator for text, confounds, and",
"'type': varType, 'vocab': vocab } featurized_data[var_name] = [featurizer(ex) for ex",
"sorted(featurized_data.keys()) data = TensorDataset(*[to_tensor(name) for name in feature_names]) dataloader =",
"DataLoader( dataset=data, sampler=RandomSampler(data), collate_fn=lambda batch: [torch.stack(x) for x in zip(*batch)],",
"are \"input\", \"predict\", or \"control\" variables. batch_size: int. The batch",
"= 1 return padded_ids # Continuous elif isinstance(examples[0], float) or",
"SequentialSampler import torch def get_info(examples, vocab=None, max_seq_len=256): \"\"\"Gathers info on",
"= 'input' vocab = ['UNK', 'PAD'] + vocab tok2id =",
"text sequences. Returns: A generator which yields dictionaries where variable",
"variable names to whether they are \"input\", \"predict\", or \"control\"",
"tqdm import tqdm from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler",
"for discrete datatypes (e.g. text or categorical). max_seq_len: int. maximum",
"unrecognized example type: \", examples[0]) quit() return featurizer, example_type, vocab",
"example_type, vocab def get_iterator(vocab, df, name_to_type, batch_size=32, max_seq_len=256): \"\"\"Builds a",
"generator for. vocab: list(str). A vocabulary for discrete datatypes (e.g.",
"unk id. else: print(\"ERROR: unrecognized example type: \", examples[0]) quit()",
"length of text sequences. Returns: A generator which yields dictionaries",
"= ['UNK', 'PAD'] + vocab tok2id = {tok: i for",
"'examples must be list; got ' + str(type(examples)) assert len(examples)",
"iterate over. The columns of these data should be a",
"> 0, 'Empty example list!' # Text if isinstance(examples[0], list):",
"padded_ids = ids + ([1] * (max_seq_len - len(ids))) #",
"featurizer = lambda ex: tok2id.get(ex, 0) # 0 is the",
"_, vocab = get_info(examples, vocab, max_seq_len) var_info[var_name] = { 'control':",
"a vocab.' example_type = 'input' vocab = ['UNK', 'PAD'] +",
"== 'input': examples = [x.split() for x in examples] featurizer,",
"= lambda ex: float(ex) else: featurizer = lambda ex: ex",
"from variable names to whether they are \"input\", \"predict\", or",
"variable names are mapped to tensors of batched data. \"\"\"",
"i for i, tok in enumerate(vocab)} ngrams = max(len(x.split()) for",
"A vocabulary for discrete datatypes (e.g. text or categorical). max_seq_len:",
"list(str). A vocabulary for discrete datatypes (e.g. text or categorical).",
"featurized example generator for a list of raw examples. Args:",
"these data should be a superset of the keys in",
"'name': var_name, 'type': var_type, 'vocab': vocab } else: featurizer, varType,",
"'.join(example[i: i + n]) for i in range(len(example) - n",
"of these data should be a superset of the keys",
"to use. max_seq_len: int. Maximum length of text sequences. Returns:",
"in toks] ids = ids[:max_seq_len] padded_ids = ids + ([1]",
"toks = [' '.join(example[i: i + n]) for i in",
"var_name, 'type': varType, 'vocab': vocab } featurized_data[var_name] = [featurizer(ex) for",
"Returns: A dict of info about this variable as well",
"data. \"\"\" def featurize(featurizer): return [featurizer(ex) for ex in examples]",
"isinstance(examples[0], int): example_type = 'continuous' vocab = ['N/A'] if isinstance(examples[0],",
"for n in range(1, ngrams + 1): toks = ['",
"' + str(type(examples)) assert len(examples) > 0, 'Empty example list!'",
"over featurized examples. \"\"\" assert isinstance(examples, list), 'examples must be",
"get_info(examples) var_info[var_name] = { 'control': var_type == 'control', 'name': var_name,",
"max(len(x.split()) for x in vocab) unk_id = 0 def featurizer(example):",
"1): toks = [' '.join(example[i: i + n]) for i",
"n + 1)] ids += [tok2id.get(x, 0) for x in",
"ngrams + 1): toks = [' '.join(example[i: i + n])",
"columns of these data should be a superset of the",
"\"predict\", or \"control\" variables. batch_size: int. The batch size to",
"for. vocab: list(str). A vocabulary for discrete datatypes (e.g. text",
"for x in examples] featurizer, _, vocab = get_info(examples, vocab,",
"ex: ex # Categorical elif isinstance(examples[0], str): example_type = 'categorical'",
"name_to_type.items(): examples = list(df[var_name]) if var_type == 'input': examples =",
"int. maximum sequence length for text examples. Returns: A dict",
"{'categorical', 'input'}: dtype = torch.long return torch.tensor(featurized_data[var_name], dtype=dtype) feature_names =",
"tensors of batched data. \"\"\" def featurize(featurizer): return [featurizer(ex) for",
"n]) for i in range(len(example) - n + 1)] ids",
"range(len(example) - n + 1)] ids += [tok2id.get(x, 0) for",
"+ vocab tok2id = {tok: i for i, tok in",
"print(\"ERROR: unrecognized example type: \", examples[0]) quit() return featurizer, example_type,",
"name_to_type, batch_size=32, max_seq_len=256): \"\"\"Builds a data iterator for text, confounds,",
"i for i, tok in enumerate(vocab)} featurizer = lambda ex:",
"var_info[var_name] = { 'control': var_type == 'control', 'name': var_name, 'type':",
"vocab = ['UNK'] + sorted(list(set(examples))) tok2id = {tok: i for",
"text, confounds, and outcomes. Args: vocab: list(str). The vocabulary to",
"featurized examples. \"\"\" assert isinstance(examples, list), 'examples must be list;",
"TensorDataset, DataLoader, RandomSampler, SequentialSampler import torch def get_info(examples, vocab=None, max_seq_len=256):",
"featurized_data[var_name] = [featurizer(ex) for ex in examples] def to_tensor(var_name): dtype",
"if not vocab: vocab = ['UNK'] + sorted(list(set(examples))) tok2id =",
"name_to_type: dict. A mapping from variable names to whether they",
"example generator for a list of raw examples. Args: examples:",
"featurizer, varType, vocab = get_info(examples) var_info[var_name] = { 'control': var_type",
"var_type, 'vocab': vocab } else: featurizer, varType, vocab = get_info(examples)",
"= sorted(featurized_data.keys()) data = TensorDataset(*[to_tensor(name) for name in feature_names]) dataloader",
"= ids[:max_seq_len] padded_ids = ids + ([1] * (max_seq_len -",
"enumerate(vocab)} featurizer = lambda ex: tok2id.get(ex, 0) # 0 is",
"string). Examples to create generator for. vocab: list(str). A vocabulary",
"use. max_seq_len: int. Maximum length of text sequences. Returns: A",
"which yields dictionaries where variable names are mapped to tensors",
"= lambda ex: tok2id.get(ex, 0) # 0 is the unk",
"\"\"\"Builds a data iterator for text, confounds, and outcomes. Args:",
"names are mapped to tensors of batched data. \"\"\" def",
"name in feature_names]) dataloader = DataLoader( dataset=data, sampler=RandomSampler(data), collate_fn=lambda batch:",
"from collections import defaultdict, OrderedDict from tqdm import tqdm from",
"variable as well as a generator over featurized examples. \"\"\"",
"vocab = ['UNK', 'PAD'] + vocab tok2id = {tok: i",
"example type: \", examples[0]) quit() return featurizer, example_type, vocab def",
"of batched data. \"\"\" def featurize(featurizer): return [featurizer(ex) for ex",
"data iterator for text, confounds, and outcomes. Args: vocab: list(str).",
"vocabulary to use. df: pandas.df. The data we want to",
"df: pandas.df. The data we want to iterate over. The",
"get_iterator(vocab, df, name_to_type, batch_size=32, max_seq_len=256): \"\"\"Builds a data iterator for",
"over. The columns of these data should be a superset",
"featurize(featurizer): return [featurizer(ex) for ex in examples] var_info = defaultdict(lambda:",
"yields dictionaries where variable names are mapped to tensors of",
"for text, confounds, and outcomes. Args: vocab: list(str). The vocabulary",
"tqdm from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler import torch",
"is the unk id. else: print(\"ERROR: unrecognized example type: \",",
"+ ([1] * (max_seq_len - len(ids))) # pad idx =",
"ngrams = max(len(x.split()) for x in vocab) unk_id = 0",
"where variable names are mapped to tensors of batched data.",
"= 'continuous' vocab = ['N/A'] if isinstance(examples[0], int): featurizer =",
"var_info[var_name] = { 'control': False, 'name': var_name, 'type': var_type, 'vocab':",
"A dict of info about this variable as well as",
"return padded_ids # Continuous elif isinstance(examples[0], float) or isinstance(examples[0], int):",
"str): example_type = 'categorical' if not vocab: vocab = ['UNK']",
"\"control\" variables. batch_size: int. The batch size to use. max_seq_len:",
"size to use. max_seq_len: int. Maximum length of text sequences.",
"OrderedDict()) featurized_data = defaultdict(list) for var_name, var_type in name_to_type.items(): examples",
"keys in name_to_type. name_to_type: dict. A mapping from variable names",
"max_seq_len=256): \"\"\"Gathers info on and creats a featurized example generator",
"tok2id = {tok: i for i, tok in enumerate(vocab)} featurizer",
"get_info(examples, vocab, max_seq_len) var_info[var_name] = { 'control': False, 'name': var_name,",
"to iterate over. The columns of these data should be",
"\", examples[0]) quit() return featurizer, example_type, vocab def get_iterator(vocab, df,",
"a data iterator for text, confounds, and outcomes. Args: vocab:",
"whether they are \"input\", \"predict\", or \"control\" variables. batch_size: int.",
"'name': var_name, 'type': varType, 'vocab': vocab } featurized_data[var_name] = [featurizer(ex)",
"assert isinstance(examples, list), 'examples must be list; got ' +",
"The data we want to iterate over. The columns of",
"1 return padded_ids # Continuous elif isinstance(examples[0], float) or isinstance(examples[0],",
"iterator for text, confounds, and outcomes. Args: vocab: list(str). The",
"datatypes (e.g. text or categorical). max_seq_len: int. maximum sequence length",
"var_name, 'type': var_type, 'vocab': vocab } else: featurizer, varType, vocab",
"vocab is not None, 'ERROR: must provide a vocab.' example_type",
"False, 'name': var_name, 'type': var_type, 'vocab': vocab } else: featurizer,",
"= ids + ([1] * (max_seq_len - len(ids))) # pad",
"Text if isinstance(examples[0], list): assert vocab is not None, 'ERROR:",
"= 'categorical' if not vocab: vocab = ['UNK'] + sorted(list(set(examples)))",
"ids += [tok2id.get(x, 0) for x in toks] ids =",
"str(type(examples)) assert len(examples) > 0, 'Empty example list!' # Text",
"# pad idx = 1 return padded_ids # Continuous elif",
"return torch.tensor(featurized_data[var_name], dtype=dtype) feature_names = sorted(featurized_data.keys()) data = TensorDataset(*[to_tensor(name) for",
"in vocab) unk_id = 0 def featurizer(example): ids = []",
"def get_info(examples, vocab=None, max_seq_len=256): \"\"\"Gathers info on and creats a",
"dictionaries where variable names are mapped to tensors of batched",
"about this variable as well as a generator over featurized",
"= TensorDataset(*[to_tensor(name) for name in feature_names]) dataloader = DataLoader( dataset=data,",
"'vocab': vocab } else: featurizer, varType, vocab = get_info(examples) var_info[var_name]",
"not vocab: vocab = ['UNK'] + sorted(list(set(examples))) tok2id = {tok:",
"+ 1)] ids += [tok2id.get(x, 0) for x in toks]",
"'control': False, 'name': var_name, 'type': var_type, 'vocab': vocab } else:",
"quit() return featurizer, example_type, vocab def get_iterator(vocab, df, name_to_type, batch_size=32,",
"raw examples. Args: examples: list(list, float, or string). Examples to",
"for text examples. Returns: A dict of info about this",
"vocab tok2id = {tok: i for i, tok in enumerate(vocab)}",
"for x in vocab) unk_id = 0 def featurizer(example): ids",
"1)] ids += [tok2id.get(x, 0) for x in toks] ids",
"generator for a list of raw examples. Args: examples: list(list,",
"mapped to tensors of batched data. \"\"\" def featurize(featurizer): return",
"for batch in dataloader: yield dict(zip(feature_names, batch)) return iterator, var_info",
"'type': var_type, 'vocab': vocab } else: featurizer, varType, vocab =",
"'vocab': vocab } featurized_data[var_name] = [featurizer(ex) for ex in examples]",
"data should be a superset of the keys in name_to_type.",
"The columns of these data should be a superset of",
"this variable as well as a generator over featurized examples.",
"# Categorical elif isinstance(examples[0], str): example_type = 'categorical' if not",
"'continuous' vocab = ['N/A'] if isinstance(examples[0], int): featurizer = lambda",
"ex in examples] var_info = defaultdict(lambda: OrderedDict()) featurized_data = defaultdict(list)",
"+ sorted(list(set(examples))) tok2id = {tok: i for i, tok in",
"sequence length for text examples. Returns: A dict of info",
"for ex in examples] var_info = defaultdict(lambda: OrderedDict()) featurized_data =",
"or \"control\" variables. batch_size: int. The batch size to use.",
"example_type = 'categorical' if not vocab: vocab = ['UNK'] +",
"toks] ids = ids[:max_seq_len] padded_ids = ids + ([1] *",
"vocab: list(str). The vocabulary to use. df: pandas.df. The data",
"for var_name, var_type in name_to_type.items(): examples = list(df[var_name]) if var_type",
"} featurized_data[var_name] = [featurizer(ex) for ex in examples] def to_tensor(var_name):",
"examples. \"\"\" assert isinstance(examples, list), 'examples must be list; got",
"defaultdict, OrderedDict from tqdm import tqdm from torch.utils.data import TensorDataset,",
"list), 'examples must be list; got ' + str(type(examples)) assert",
"== 'control', 'name': var_name, 'type': varType, 'vocab': vocab } featurized_data[var_name]",
"+ str(type(examples)) assert len(examples) > 0, 'Empty example list!' #",
"import tqdm from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler import",
"examples: list(list, float, or string). Examples to create generator for.",
"i + n]) for i in range(len(example) - n +",
"RandomSampler, SequentialSampler import torch def get_info(examples, vocab=None, max_seq_len=256): \"\"\"Gathers info",
"max_seq_len: int. maximum sequence length for text examples. Returns: A",
"x in zip(*batch)], # group by datatype. batch_size=batch_size) def iterator():",
"in enumerate(vocab)} ngrams = max(len(x.split()) for x in vocab) unk_id",
"x in examples] featurizer, _, vocab = get_info(examples, vocab, max_seq_len)",
"sequences. Returns: A generator which yields dictionaries where variable names",
"group by datatype. batch_size=batch_size) def iterator(): for batch in dataloader:",
"well as a generator over featurized examples. \"\"\" assert isinstance(examples,",
"+ 1): toks = [' '.join(example[i: i + n]) for",
"of the keys in name_to_type. name_to_type: dict. A mapping from",
"df, name_to_type, batch_size=32, max_seq_len=256): \"\"\"Builds a data iterator for text,",
"= [featurizer(ex) for ex in examples] def to_tensor(var_name): dtype =",
"list!' # Text if isinstance(examples[0], list): assert vocab is not",
"collections import defaultdict, OrderedDict from tqdm import tqdm from torch.utils.data",
"else: featurizer = lambda ex: ex # Categorical elif isinstance(examples[0],",
"examples] def to_tensor(var_name): dtype = torch.float if var_info[var_name]['type'] in {'categorical',",
"max_seq_len: int. Maximum length of text sequences. Returns: A generator",
"import TensorDataset, DataLoader, RandomSampler, SequentialSampler import torch def get_info(examples, vocab=None,",
"feature_names = sorted(featurized_data.keys()) data = TensorDataset(*[to_tensor(name) for name in feature_names])",
"example_type = 'input' vocab = ['UNK', 'PAD'] + vocab tok2id",
"0 def featurizer(example): ids = [] for n in range(1,",
"a superset of the keys in name_to_type. name_to_type: dict. A",
"variables. batch_size: int. The batch size to use. max_seq_len: int.",
"'input'}: dtype = torch.long return torch.tensor(featurized_data[var_name], dtype=dtype) feature_names = sorted(featurized_data.keys())",
"= DataLoader( dataset=data, sampler=RandomSampler(data), collate_fn=lambda batch: [torch.stack(x) for x in",
"from tqdm import tqdm from torch.utils.data import TensorDataset, DataLoader, RandomSampler,",
"if isinstance(examples[0], int): featurizer = lambda ex: float(ex) else: featurizer",
"pipelines.\"\"\" from collections import defaultdict, OrderedDict from tqdm import tqdm",
"def to_tensor(var_name): dtype = torch.float if var_info[var_name]['type'] in {'categorical', 'input'}:",
"of raw examples. Args: examples: list(list, float, or string). Examples",
"ex: tok2id.get(ex, 0) # 0 is the unk id. else:",
"examples = list(df[var_name]) if var_type == 'input': examples = [x.split()",
"batch_size: int. The batch size to use. max_seq_len: int. Maximum",
"pad idx = 1 return padded_ids # Continuous elif isinstance(examples[0],",
"['N/A'] if isinstance(examples[0], int): featurizer = lambda ex: float(ex) else:",
"= {tok: i for i, tok in enumerate(vocab)} ngrams =",
"= [x.split() for x in examples] featurizer, _, vocab =",
"int): example_type = 'continuous' vocab = ['N/A'] if isinstance(examples[0], int):",
"dataloader = DataLoader( dataset=data, sampler=RandomSampler(data), collate_fn=lambda batch: [torch.stack(x) for x",
"generator which yields dictionaries where variable names are mapped to",
"vocab.' example_type = 'input' vocab = ['UNK', 'PAD'] + vocab",
"'ERROR: must provide a vocab.' example_type = 'input' vocab =",
"'input': examples = [x.split() for x in examples] featurizer, _,",
"featurizer(example): ids = [] for n in range(1, ngrams +",
"(max_seq_len - len(ids))) # pad idx = 1 return padded_ids",
"# Continuous elif isinstance(examples[0], float) or isinstance(examples[0], int): example_type =",
"= lambda ex: ex # Categorical elif isinstance(examples[0], str): example_type",
"the unk id. else: print(\"ERROR: unrecognized example type: \", examples[0])",
"else: print(\"ERROR: unrecognized example type: \", examples[0]) quit() return featurizer,",
"or string). Examples to create generator for. vocab: list(str). A",
"defaultdict(list) for var_name, var_type in name_to_type.items(): examples = list(df[var_name]) if",
"= torch.float if var_info[var_name]['type'] in {'categorical', 'input'}: dtype = torch.long",
"lambda ex: tok2id.get(ex, 0) # 0 is the unk id.",
"must be list; got ' + str(type(examples)) assert len(examples) >",
"var_info = defaultdict(lambda: OrderedDict()) featurized_data = defaultdict(list) for var_name, var_type",
"and creats a featurized example generator for a list of",
"elif isinstance(examples[0], str): example_type = 'categorical' if not vocab: vocab",
"vocab } else: featurizer, varType, vocab = get_info(examples) var_info[var_name] =",
"\"input\", \"predict\", or \"control\" variables. batch_size: int. The batch size",
"in name_to_type. name_to_type: dict. A mapping from variable names to",
"batch size to use. max_seq_len: int. Maximum length of text",
"in examples] def to_tensor(var_name): dtype = torch.float if var_info[var_name]['type'] in",
"example_type = 'continuous' vocab = ['N/A'] if isinstance(examples[0], int): featurizer",
"0) # 0 is the unk id. else: print(\"ERROR: unrecognized",
"batch_size=batch_size) def iterator(): for batch in dataloader: yield dict(zip(feature_names, batch))",
"examples = [x.split() for x in examples] featurizer, _, vocab",
"TensorDataset(*[to_tensor(name) for name in feature_names]) dataloader = DataLoader( dataset=data, sampler=RandomSampler(data),",
"i, tok in enumerate(vocab)} featurizer = lambda ex: tok2id.get(ex, 0)",
"torch.long return torch.tensor(featurized_data[var_name], dtype=dtype) feature_names = sorted(featurized_data.keys()) data = TensorDataset(*[to_tensor(name)",
"i, tok in enumerate(vocab)} ngrams = max(len(x.split()) for x in",
"name_to_type. name_to_type: dict. A mapping from variable names to whether",
"batched data. \"\"\" def featurize(featurizer): return [featurizer(ex) for ex in",
"a featurized example generator for a list of raw examples.",
"dtype = torch.long return torch.tensor(featurized_data[var_name], dtype=dtype) feature_names = sorted(featurized_data.keys()) data",
"examples. Returns: A dict of info about this variable as",
"collate_fn=lambda batch: [torch.stack(x) for x in zip(*batch)], # group by",
"* (max_seq_len - len(ids))) # pad idx = 1 return",
"featurized_data = defaultdict(list) for var_name, var_type in name_to_type.items(): examples =",
"got ' + str(type(examples)) assert len(examples) > 0, 'Empty example",
"vocab, max_seq_len) var_info[var_name] = { 'control': False, 'name': var_name, 'type':",
"enumerate(vocab)} ngrams = max(len(x.split()) for x in vocab) unk_id =",
"to create generator for. vocab: list(str). A vocabulary for discrete",
"list of raw examples. Args: examples: list(list, float, or string).",
"from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler import torch def",
"list(df[var_name]) if var_type == 'input': examples = [x.split() for x",
"\"\"\" assert isinstance(examples, list), 'examples must be list; got '",
"list(list, float, or string). Examples to create generator for. vocab:",
"ex in examples] def to_tensor(var_name): dtype = torch.float if var_info[var_name]['type']",
"featurizer = lambda ex: ex # Categorical elif isinstance(examples[0], str):",
"or isinstance(examples[0], int): example_type = 'continuous' vocab = ['N/A'] if",
"= { 'control': False, 'name': var_name, 'type': var_type, 'vocab': vocab",
"var_type == 'input': examples = [x.split() for x in examples]",
"max_seq_len) var_info[var_name] = { 'control': False, 'name': var_name, 'type': var_type,",
"ids = [] for n in range(1, ngrams + 1):",
"max_seq_len=256): \"\"\"Builds a data iterator for text, confounds, and outcomes.",
"use. df: pandas.df. The data we want to iterate over.",
"0, 'Empty example list!' # Text if isinstance(examples[0], list): assert",
"in examples] var_info = defaultdict(lambda: OrderedDict()) featurized_data = defaultdict(list) for",
"is not None, 'ERROR: must provide a vocab.' example_type =",
"return [featurizer(ex) for ex in examples] var_info = defaultdict(lambda: OrderedDict())",
"not None, 'ERROR: must provide a vocab.' example_type = 'input'",
"are mapped to tensors of batched data. \"\"\" def featurize(featurizer):",
"} else: featurizer, varType, vocab = get_info(examples) var_info[var_name] = {",
"Args: examples: list(list, float, or string). Examples to create generator",
"text examples. Returns: A dict of info about this variable",
"vocabulary for discrete datatypes (e.g. text or categorical). max_seq_len: int.",
"as a generator over featurized examples. \"\"\" assert isinstance(examples, list),",
"{tok: i for i, tok in enumerate(vocab)} featurizer = lambda",
"ids = ids[:max_seq_len] padded_ids = ids + ([1] * (max_seq_len",
"to_tensor(var_name): dtype = torch.float if var_info[var_name]['type'] in {'categorical', 'input'}: dtype",
"Args: vocab: list(str). The vocabulary to use. df: pandas.df. The",
"[featurizer(ex) for ex in examples] def to_tensor(var_name): dtype = torch.float",
"type: \", examples[0]) quit() return featurizer, example_type, vocab def get_iterator(vocab,",
"must provide a vocab.' example_type = 'input' vocab = ['UNK',",
"range(1, ngrams + 1): toks = [' '.join(example[i: i +",
"tok2id = {tok: i for i, tok in enumerate(vocab)} ngrams",
"(e.g. text or categorical). max_seq_len: int. maximum sequence length for",
"tok2id.get(ex, 0) # 0 is the unk id. else: print(\"ERROR:",
"int): featurizer = lambda ex: float(ex) else: featurizer = lambda",
"in {'categorical', 'input'}: dtype = torch.long return torch.tensor(featurized_data[var_name], dtype=dtype) feature_names",
"elif isinstance(examples[0], float) or isinstance(examples[0], int): example_type = 'continuous' vocab",
"by datatype. batch_size=batch_size) def iterator(): for batch in dataloader: yield",
"= {tok: i for i, tok in enumerate(vocab)} featurizer =",
"= list(df[var_name]) if var_type == 'input': examples = [x.split() for",
"def featurizer(example): ids = [] for n in range(1, ngrams",
"OrderedDict from tqdm import tqdm from torch.utils.data import TensorDataset, DataLoader,",
"A mapping from variable names to whether they are \"input\",",
"= ['UNK'] + sorted(list(set(examples))) tok2id = {tok: i for i,",
"vocab } featurized_data[var_name] = [featurizer(ex) for ex in examples] def",
"'Empty example list!' # Text if isinstance(examples[0], list): assert vocab",
"vocab = ['N/A'] if isinstance(examples[0], int): featurizer = lambda ex:",
"of info about this variable as well as a generator",
"iterator(): for batch in dataloader: yield dict(zip(feature_names, batch)) return iterator,",
"create generator for. vocab: list(str). A vocabulary for discrete datatypes",
"list): assert vocab is not None, 'ERROR: must provide a",
"id. else: print(\"ERROR: unrecognized example type: \", examples[0]) quit() return",
"n in range(1, ngrams + 1): toks = [' '.join(example[i:",
"- n + 1)] ids += [tok2id.get(x, 0) for x",
"on and creats a featurized example generator for a list",
"float) or isinstance(examples[0], int): example_type = 'continuous' vocab = ['N/A']",
"isinstance(examples, list), 'examples must be list; got ' + str(type(examples))",
"var_type == 'control', 'name': var_name, 'type': varType, 'vocab': vocab }",
"= [' '.join(example[i: i + n]) for i in range(len(example)",
"0) for x in toks] ids = ids[:max_seq_len] padded_ids =",
"'PAD'] + vocab tok2id = {tok: i for i, tok",
"defaultdict(lambda: OrderedDict()) featurized_data = defaultdict(list) for var_name, var_type in name_to_type.items():",
"'control', 'name': var_name, 'type': varType, 'vocab': vocab } featurized_data[var_name] =",
"they are \"input\", \"predict\", or \"control\" variables. batch_size: int. The",
"varType, 'vocab': vocab } featurized_data[var_name] = [featurizer(ex) for ex in",
"[tok2id.get(x, 0) for x in toks] ids = ids[:max_seq_len] padded_ids",
"# group by datatype. batch_size=batch_size) def iterator(): for batch in",
"tok in enumerate(vocab)} featurizer = lambda ex: tok2id.get(ex, 0) #",
"ids + ([1] * (max_seq_len - len(ids))) # pad idx",
"{tok: i for i, tok in enumerate(vocab)} ngrams = max(len(x.split())",
"info on and creats a featurized example generator for a",
"len(examples) > 0, 'Empty example list!' # Text if isinstance(examples[0],",
"len(ids))) # pad idx = 1 return padded_ids # Continuous",
"dtype = torch.float if var_info[var_name]['type'] in {'categorical', 'input'}: dtype =",
"length for text examples. Returns: A dict of info about",
"get_info(examples, vocab=None, max_seq_len=256): \"\"\"Gathers info on and creats a featurized",
"list; got ' + str(type(examples)) assert len(examples) > 0, 'Empty",
"categorical). max_seq_len: int. maximum sequence length for text examples. Returns:",
"dataset=data, sampler=RandomSampler(data), collate_fn=lambda batch: [torch.stack(x) for x in zip(*batch)], #",
"ids[:max_seq_len] padded_ids = ids + ([1] * (max_seq_len - len(ids)))",
"= torch.long return torch.tensor(featurized_data[var_name], dtype=dtype) feature_names = sorted(featurized_data.keys()) data =",
"a list of raw examples. Args: examples: list(list, float, or",
"Examples to create generator for. vocab: list(str). A vocabulary for",
"a generator over featurized examples. \"\"\" assert isinstance(examples, list), 'examples",
"in zip(*batch)], # group by datatype. batch_size=batch_size) def iterator(): for",
"should be a superset of the keys in name_to_type. name_to_type:",
"dict. A mapping from variable names to whether they are",
"in range(1, ngrams + 1): toks = [' '.join(example[i: i",
"superset of the keys in name_to_type. name_to_type: dict. A mapping",
"feature_names]) dataloader = DataLoader( dataset=data, sampler=RandomSampler(data), collate_fn=lambda batch: [torch.stack(x) for",
"in range(len(example) - n + 1)] ids += [tok2id.get(x, 0)",
"for x in toks] ids = ids[:max_seq_len] padded_ids = ids",
"vocab: vocab = ['UNK'] + sorted(list(set(examples))) tok2id = {tok: i",
"= max(len(x.split()) for x in vocab) unk_id = 0 def",
"return featurizer, example_type, vocab def get_iterator(vocab, df, name_to_type, batch_size=32, max_seq_len=256):",
"torch.float if var_info[var_name]['type'] in {'categorical', 'input'}: dtype = torch.long return",
"padded_ids # Continuous elif isinstance(examples[0], float) or isinstance(examples[0], int): example_type",
"batch: [torch.stack(x) for x in zip(*batch)], # group by datatype.",
"creats a featurized example generator for a list of raw",
"vocab = get_info(examples) var_info[var_name] = { 'control': var_type == 'control',",
"in examples] featurizer, _, vocab = get_info(examples, vocab, max_seq_len) var_info[var_name]",
"lambda ex: float(ex) else: featurizer = lambda ex: ex #",
"\"\"\"Gathers info on and creats a featurized example generator for",
"for i, tok in enumerate(vocab)} ngrams = max(len(x.split()) for x",
"A generator which yields dictionaries where variable names are mapped",
"def iterator(): for batch in dataloader: yield dict(zip(feature_names, batch)) return",
"want to iterate over. The columns of these data should",
"var_info[var_name]['type'] in {'categorical', 'input'}: dtype = torch.long return torch.tensor(featurized_data[var_name], dtype=dtype)",
"be a superset of the keys in name_to_type. name_to_type: dict.",
"confounds, and outcomes. Args: vocab: list(str). The vocabulary to use.",
"float(ex) else: featurizer = lambda ex: ex # Categorical elif",
"examples. Args: examples: list(list, float, or string). Examples to create",
"\"\"\"Data pipelines.\"\"\" from collections import defaultdict, OrderedDict from tqdm import",
"maximum sequence length for text examples. Returns: A dict of",
"import defaultdict, OrderedDict from tqdm import tqdm from torch.utils.data import",
"assert len(examples) > 0, 'Empty example list!' # Text if",
"def featurize(featurizer): return [featurizer(ex) for ex in examples] var_info =",
"[] for n in range(1, ngrams + 1): toks =",
"for ex in examples] def to_tensor(var_name): dtype = torch.float if",
"vocab: list(str). A vocabulary for discrete datatypes (e.g. text or",
"var_name, var_type in name_to_type.items(): examples = list(df[var_name]) if var_type ==",
"torch.tensor(featurized_data[var_name], dtype=dtype) feature_names = sorted(featurized_data.keys()) data = TensorDataset(*[to_tensor(name) for name",
"for a list of raw examples. Args: examples: list(list, float,",
"unk_id = 0 def featurizer(example): ids = [] for n",
"+= [tok2id.get(x, 0) for x in toks] ids = ids[:max_seq_len]",
"float, or string). Examples to create generator for. vocab: list(str).",
"examples] var_info = defaultdict(lambda: OrderedDict()) featurized_data = defaultdict(list) for var_name,",
"def get_iterator(vocab, df, name_to_type, batch_size=32, max_seq_len=256): \"\"\"Builds a data iterator",
"featurizer, example_type, vocab def get_iterator(vocab, df, name_to_type, batch_size=32, max_seq_len=256): \"\"\"Builds"
] |
[
"digits = len(num_str) return digits # Define main function def",
"digits digits = len(num_str) return digits # Define main function",
"num_digits = get_num_digits(number) # Display result print(f'The number of digits",
"return digits # Define main function def main(): # Prompt",
"an integer number = int(input('Enter an integer: ')) # Obtain",
"')) # Obtain number of digits num_digits = get_num_digits(number) #",
"Display result print(f'The number of digits in number {number} is",
"Define main function def main(): # Prompt user for an",
"get_num_digits(number) # Display result print(f'The number of digits in number",
"# Calculate and return number of digits def get_num_digits(num): #",
"<reponame>H2u-Hwng/EVC # Take number, and convert integer to string #",
"of digits def get_num_digits(num): # Convert int to str num_str",
"main function def main(): # Prompt user for an integer",
"of digits num_digits = get_num_digits(number) # Display result print(f'The number",
"and return number of digits def get_num_digits(num): # Convert int",
"digits # Define main function def main(): # Prompt user",
"digits def get_num_digits(num): # Convert int to str num_str =",
"Calculate number of digits digits = len(num_str) return digits #",
"result print(f'The number of digits in number {number} is {num_digits}.')",
"Obtain number of digits num_digits = get_num_digits(number) # Display result",
"main(): # Prompt user for an integer number = int(input('Enter",
"string # Calculate and return number of digits def get_num_digits(num):",
"def main(): # Prompt user for an integer number =",
"of digits digits = len(num_str) return digits # Define main",
"len(num_str) return digits # Define main function def main(): #",
"def get_num_digits(num): # Convert int to str num_str = str(num)",
"str(num) # Calculate number of digits digits = len(num_str) return",
"number, and convert integer to string # Calculate and return",
"str num_str = str(num) # Calculate number of digits digits",
"user for an integer number = int(input('Enter an integer: '))",
"for an integer number = int(input('Enter an integer: ')) #",
"Take number, and convert integer to string # Calculate and",
"# Prompt user for an integer number = int(input('Enter an",
"an integer: ')) # Obtain number of digits num_digits =",
"# Obtain number of digits num_digits = get_num_digits(number) # Display",
"digits num_digits = get_num_digits(number) # Display result print(f'The number of",
"digits in number {number} is {num_digits}.') # Call main function",
"number of digits def get_num_digits(num): # Convert int to str",
"number = int(input('Enter an integer: ')) # Obtain number of",
"to str num_str = str(num) # Calculate number of digits",
"# Calculate number of digits digits = len(num_str) return digits",
"number of digits num_digits = get_num_digits(number) # Display result print(f'The",
"in number {number} is {num_digits}.') # Call main function main()",
"Convert int to str num_str = str(num) # Calculate number",
"number of digits digits = len(num_str) return digits # Define",
"= get_num_digits(number) # Display result print(f'The number of digits in",
"function def main(): # Prompt user for an integer number",
"# Define main function def main(): # Prompt user for",
"int to str num_str = str(num) # Calculate number of",
"# Convert int to str num_str = str(num) # Calculate",
"Prompt user for an integer number = int(input('Enter an integer:",
"integer: ')) # Obtain number of digits num_digits = get_num_digits(number)",
"# Display result print(f'The number of digits in number {number}",
"Calculate and return number of digits def get_num_digits(num): # Convert",
"number of digits in number {number} is {num_digits}.') # Call",
"integer number = int(input('Enter an integer: ')) # Obtain number",
"to string # Calculate and return number of digits def",
"= int(input('Enter an integer: ')) # Obtain number of digits",
"of digits in number {number} is {num_digits}.') # Call main",
"and convert integer to string # Calculate and return number",
"= len(num_str) return digits # Define main function def main():",
"get_num_digits(num): # Convert int to str num_str = str(num) #",
"# Take number, and convert integer to string # Calculate",
"num_str = str(num) # Calculate number of digits digits =",
"int(input('Enter an integer: ')) # Obtain number of digits num_digits",
"print(f'The number of digits in number {number} is {num_digits}.') #",
"convert integer to string # Calculate and return number of",
"return number of digits def get_num_digits(num): # Convert int to",
"= str(num) # Calculate number of digits digits = len(num_str)",
"integer to string # Calculate and return number of digits"
] |
[
"AvatarDialog(BaseDialog): def __init__(self, loc: BaseLocalization, data: FSMContextProxy, d: DepContainer): super().__init__(loc,",
"download_tg_photo(explicit_picture) else: user_pic = await get_userpic(message.from_user) w, h = user_pic.size",
"from aiogram.dispatcher.filters.state import StatesGroup, State from aiogram.dispatcher.storage import FSMContextProxy from",
"from aiogram.types import Message, PhotoSize, ReplyKeyboardRemove, ContentTypes from aiogram.utils.helper import",
"super().__init__(loc, data, d) self._work_lock = asyncio.Lock() def menu_kbd(self): return kbd([",
"message: Message, loc: BaseLocalization, explicit_picture: PhotoSize = None): async with",
"mode = HelperMode.snake_case # fixme: no state handle MAIN =",
"None): async with AsyncExitStack() as stack: stack.enter_async_context(self._work_lock) # POST A",
"user_pic) pic = await combine_frame_and_photo_v2(self.deps.cfg, user_pic) user_id = message.from_user.id pic",
"combine_frame_and_photo_v2(self.deps.cfg, user_pic) user_id = message.from_user.id pic = img_to_bio(pic, name=f'alpha_avatar_{user_id}.png') await",
"pic = await combine_frame_and_photo_v2(self.deps.cfg, user_pic) user_id = message.from_user.id pic =",
"else: await AvatarStates.MAIN.set() await message.answer(self.loc.TEXT_AVA_WELCOME, reply_markup=self.menu_kbd()) @message_handler(state=AvatarStates.MAIN, content_types=ContentTypes.PHOTO) async def",
"<= w <= 4096) and (64 <= h <= 4096)):",
"lib.texts import kbd # todo: accept documents! class AvatarStates(StatesGroup): mode",
"accept documents! class AvatarStates(StatesGroup): mode = HelperMode.snake_case # fixme: no",
"self.loc.BUTTON_AVA_FROM_MY_USERPIC: await self.handle_avatar_picture(message, self.loc) else: await AvatarStates.MAIN.set() await message.answer(self.loc.TEXT_AVA_WELCOME, reply_markup=self.menu_kbd())",
"get_userpic, combine_frame_and_photo_v2, img_to_bio from dialog.base import BaseDialog, message_handler from localization",
"await download_tg_photo(explicit_picture) else: user_pic = await get_userpic(message.from_user) w, h =",
"import kbd # todo: accept documents! class AvatarStates(StatesGroup): mode =",
"<filename>app/dialog/avatar_picture_dialog.py<gh_stars>1-10 import asyncio from contextlib import AsyncExitStack from aiogram.dispatcher.filters.state import",
"localization import BaseLocalization from lib.depcont import DepContainer from lib.texts import",
"async def on_no_state(self, message: Message): await self.on_enter(message) @message_handler(state=AvatarStates.MAIN) async def",
"message: Message): await self.handle_avatar_picture(message, self.loc, explicit_picture=message.photo[0]) async def handle_avatar_picture(self, message:",
"PhotoSize, ReplyKeyboardRemove, ContentTypes from aiogram.utils.helper import HelperMode from dialog.avatar_image_work import",
"data, d) self._work_lock = asyncio.Lock() def menu_kbd(self): return kbd([ self.loc.BUTTON_AVA_FROM_MY_USERPIC,",
"Message): await self.on_enter(message) @message_handler(state=AvatarStates.MAIN) async def on_enter(self, message: Message): if",
"= HelperMode.snake_case # fixme: no state handle MAIN = State()",
"disable_notification=True, reply_markup=ReplyKeyboardRemove()) # CLEAN UP IN THE END stack.push_async_callback(sticker.delete) if",
"fixme: no state handle MAIN = State() class AvatarDialog(BaseDialog): def",
"state handle MAIN = State() class AvatarDialog(BaseDialog): def __init__(self, loc:",
"@message_handler(state=AvatarStates.MAIN, content_types=ContentTypes.PHOTO) async def on_picture(self, message: Message): await self.handle_avatar_picture(message, self.loc,",
"# pic = await combine_frame_and_photo(self.deps.cfg, user_pic) pic = await combine_frame_and_photo_v2(self.deps.cfg,",
"= State() class AvatarDialog(BaseDialog): def __init__(self, loc: BaseLocalization, data: FSMContextProxy,",
"State() class AvatarDialog(BaseDialog): def __init__(self, loc: BaseLocalization, data: FSMContextProxy, d:",
"LOADING STICKER sticker = await message.answer_sticker(self.loc.LOADING_STICKER, disable_notification=True, reply_markup=ReplyKeyboardRemove()) # CLEAN",
"todo: accept documents! class AvatarStates(StatesGroup): mode = HelperMode.snake_case # fixme:",
"await self.handle_avatar_picture(message, self.loc) else: await AvatarStates.MAIN.set() await message.answer(self.loc.TEXT_AVA_WELCOME, reply_markup=self.menu_kbd()) @message_handler(state=AvatarStates.MAIN,",
"with AsyncExitStack() as stack: stack.enter_async_context(self._work_lock) # POST A LOADING STICKER",
"return if not ((64 <= w <= 4096) and (64",
"contextlib import AsyncExitStack from aiogram.dispatcher.filters.state import StatesGroup, State from aiogram.dispatcher.storage",
"dialog.base import BaseDialog, message_handler from localization import BaseLocalization from lib.depcont",
"await AvatarStates.MAIN.set() await message.answer(self.loc.TEXT_AVA_WELCOME, reply_markup=self.menu_kbd()) @message_handler(state=AvatarStates.MAIN, content_types=ContentTypes.PHOTO) async def on_picture(self,",
"message.answer_sticker(self.loc.LOADING_STICKER, disable_notification=True, reply_markup=ReplyKeyboardRemove()) # CLEAN UP IN THE END stack.push_async_callback(sticker.delete)",
"else: user_pic = await get_userpic(message.from_user) w, h = user_pic.size if",
"= await download_tg_photo(explicit_picture) else: user_pic = await get_userpic(message.from_user) w, h",
"user_id = message.from_user.id pic = img_to_bio(pic, name=f'alpha_avatar_{user_id}.png') await message.answer_document(pic, caption=loc.TEXT_AVA_READY,",
"message.answer(loc.TEXT_AVA_ERR_INVALID, reply_markup=self.menu_kbd()) return if not ((64 <= w <= 4096)",
"download_tg_photo, get_userpic, combine_frame_and_photo_v2, img_to_bio from dialog.base import BaseDialog, message_handler from",
"FSMContextProxy from aiogram.types import Message, PhotoSize, ReplyKeyboardRemove, ContentTypes from aiogram.utils.helper",
"self.on_enter(message) @message_handler(state=AvatarStates.MAIN) async def on_enter(self, message: Message): if message.text ==",
"on_picture(self, message: Message): await self.handle_avatar_picture(message, self.loc, explicit_picture=message.photo[0]) async def handle_avatar_picture(self,",
"w or not h: await message.answer(loc.TEXT_AVA_ERR_INVALID, reply_markup=self.menu_kbd()) return if not",
"sticker = await message.answer_sticker(self.loc.LOADING_STICKER, disable_notification=True, reply_markup=ReplyKeyboardRemove()) # CLEAN UP IN",
"BaseDialog, message_handler from localization import BaseLocalization from lib.depcont import DepContainer",
"w <= 4096) and (64 <= h <= 4096)): await",
"await self.handle_avatar_picture(message, self.loc, explicit_picture=message.photo[0]) async def handle_avatar_picture(self, message: Message, loc:",
"ReplyKeyboardRemove, ContentTypes from aiogram.utils.helper import HelperMode from dialog.avatar_image_work import download_tg_photo,",
"<= 4096) and (64 <= h <= 4096)): await message.answer(loc.TEXT_AVA_ERR_SIZE,",
"aiogram.types import Message, PhotoSize, ReplyKeyboardRemove, ContentTypes from aiogram.utils.helper import HelperMode",
"get_userpic(message.from_user) w, h = user_pic.size if not w or not",
"and (64 <= h <= 4096)): await message.answer(loc.TEXT_AVA_ERR_SIZE, reply_markup=self.menu_kbd()) return",
"@message_handler(state=AvatarStates.MAIN) async def on_enter(self, message: Message): if message.text == self.loc.BUTTON_AVA_FROM_MY_USERPIC:",
"from contextlib import AsyncExitStack from aiogram.dispatcher.filters.state import StatesGroup, State from",
"ContentTypes from aiogram.utils.helper import HelperMode from dialog.avatar_image_work import download_tg_photo, get_userpic,",
"from dialog.base import BaseDialog, message_handler from localization import BaseLocalization from",
"BaseLocalization, data: FSMContextProxy, d: DepContainer): super().__init__(loc, data, d) self._work_lock =",
"or not h: await message.answer(loc.TEXT_AVA_ERR_INVALID, reply_markup=self.menu_kbd()) return if not ((64",
"if not w or not h: await message.answer(loc.TEXT_AVA_ERR_INVALID, reply_markup=self.menu_kbd()) return",
"async with AsyncExitStack() as stack: stack.enter_async_context(self._work_lock) # POST A LOADING",
"from aiogram.utils.helper import HelperMode from dialog.avatar_image_work import download_tg_photo, get_userpic, combine_frame_and_photo_v2,",
"loc: BaseLocalization, data: FSMContextProxy, d: DepContainer): super().__init__(loc, data, d) self._work_lock",
"asyncio.Lock() def menu_kbd(self): return kbd([ self.loc.BUTTON_AVA_FROM_MY_USERPIC, ], vert=True) @message_handler(state=None) async",
"StatesGroup, State from aiogram.dispatcher.storage import FSMContextProxy from aiogram.types import Message,",
"kbd([ self.loc.BUTTON_AVA_FROM_MY_USERPIC, ], vert=True) @message_handler(state=None) async def on_no_state(self, message: Message):",
"State from aiogram.dispatcher.storage import FSMContextProxy from aiogram.types import Message, PhotoSize,",
"pic = await combine_frame_and_photo(self.deps.cfg, user_pic) pic = await combine_frame_and_photo_v2(self.deps.cfg, user_pic)",
"4096) and (64 <= h <= 4096)): await message.answer(loc.TEXT_AVA_ERR_SIZE, reply_markup=self.menu_kbd())",
"import DepContainer from lib.texts import kbd # todo: accept documents!",
"await combine_frame_and_photo(self.deps.cfg, user_pic) pic = await combine_frame_and_photo_v2(self.deps.cfg, user_pic) user_id =",
"h = user_pic.size if not w or not h: await",
"async def on_picture(self, message: Message): await self.handle_avatar_picture(message, self.loc, explicit_picture=message.photo[0]) async",
"message_handler from localization import BaseLocalization from lib.depcont import DepContainer from",
"on_no_state(self, message: Message): await self.on_enter(message) @message_handler(state=AvatarStates.MAIN) async def on_enter(self, message:",
"= asyncio.Lock() def menu_kbd(self): return kbd([ self.loc.BUTTON_AVA_FROM_MY_USERPIC, ], vert=True) @message_handler(state=None)",
"Message, loc: BaseLocalization, explicit_picture: PhotoSize = None): async with AsyncExitStack()",
"= message.from_user.id pic = img_to_bio(pic, name=f'alpha_avatar_{user_id}.png') await message.answer_document(pic, caption=loc.TEXT_AVA_READY, reply_markup=self.menu_kbd())",
"AvatarStates.MAIN.set() await message.answer(self.loc.TEXT_AVA_WELCOME, reply_markup=self.menu_kbd()) @message_handler(state=AvatarStates.MAIN, content_types=ContentTypes.PHOTO) async def on_picture(self, message:",
"import StatesGroup, State from aiogram.dispatcher.storage import FSMContextProxy from aiogram.types import",
"menu_kbd(self): return kbd([ self.loc.BUTTON_AVA_FROM_MY_USERPIC, ], vert=True) @message_handler(state=None) async def on_no_state(self,",
"await self.on_enter(message) @message_handler(state=AvatarStates.MAIN) async def on_enter(self, message: Message): if message.text",
"Message, PhotoSize, ReplyKeyboardRemove, ContentTypes from aiogram.utils.helper import HelperMode from dialog.avatar_image_work",
"from lib.texts import kbd # todo: accept documents! class AvatarStates(StatesGroup):",
"if message.text == self.loc.BUTTON_AVA_FROM_MY_USERPIC: await self.handle_avatar_picture(message, self.loc) else: await AvatarStates.MAIN.set()",
"self.handle_avatar_picture(message, self.loc) else: await AvatarStates.MAIN.set() await message.answer(self.loc.TEXT_AVA_WELCOME, reply_markup=self.menu_kbd()) @message_handler(state=AvatarStates.MAIN, content_types=ContentTypes.PHOTO)",
"as stack: stack.enter_async_context(self._work_lock) # POST A LOADING STICKER sticker =",
"class AvatarStates(StatesGroup): mode = HelperMode.snake_case # fixme: no state handle",
"user_pic) user_id = message.from_user.id pic = img_to_bio(pic, name=f'alpha_avatar_{user_id}.png') await message.answer_document(pic,",
"MAIN = State() class AvatarDialog(BaseDialog): def __init__(self, loc: BaseLocalization, data:",
"not None: user_pic = await download_tg_photo(explicit_picture) else: user_pic = await",
"= await message.answer_sticker(self.loc.LOADING_STICKER, disable_notification=True, reply_markup=ReplyKeyboardRemove()) # CLEAN UP IN THE",
"import BaseLocalization from lib.depcont import DepContainer from lib.texts import kbd",
"async def on_enter(self, message: Message): if message.text == self.loc.BUTTON_AVA_FROM_MY_USERPIC: await",
"class AvatarDialog(BaseDialog): def __init__(self, loc: BaseLocalization, data: FSMContextProxy, d: DepContainer):",
"BaseLocalization, explicit_picture: PhotoSize = None): async with AsyncExitStack() as stack:",
"STICKER sticker = await message.answer_sticker(self.loc.LOADING_STICKER, disable_notification=True, reply_markup=ReplyKeyboardRemove()) # CLEAN UP",
"AsyncExitStack from aiogram.dispatcher.filters.state import StatesGroup, State from aiogram.dispatcher.storage import FSMContextProxy",
"== self.loc.BUTTON_AVA_FROM_MY_USERPIC: await self.handle_avatar_picture(message, self.loc) else: await AvatarStates.MAIN.set() await message.answer(self.loc.TEXT_AVA_WELCOME,",
"def menu_kbd(self): return kbd([ self.loc.BUTTON_AVA_FROM_MY_USERPIC, ], vert=True) @message_handler(state=None) async def",
"THE END stack.push_async_callback(sticker.delete) if explicit_picture is not None: user_pic =",
"aiogram.dispatcher.filters.state import StatesGroup, State from aiogram.dispatcher.storage import FSMContextProxy from aiogram.types",
"(64 <= h <= 4096)): await message.answer(loc.TEXT_AVA_ERR_SIZE, reply_markup=self.menu_kbd()) return #",
"data: FSMContextProxy, d: DepContainer): super().__init__(loc, data, d) self._work_lock = asyncio.Lock()",
"import BaseDialog, message_handler from localization import BaseLocalization from lib.depcont import",
"return # pic = await combine_frame_and_photo(self.deps.cfg, user_pic) pic = await",
"from localization import BaseLocalization from lib.depcont import DepContainer from lib.texts",
"dialog.avatar_image_work import download_tg_photo, get_userpic, combine_frame_and_photo_v2, img_to_bio from dialog.base import BaseDialog,",
"message.text == self.loc.BUTTON_AVA_FROM_MY_USERPIC: await self.handle_avatar_picture(message, self.loc) else: await AvatarStates.MAIN.set() await",
"def __init__(self, loc: BaseLocalization, data: FSMContextProxy, d: DepContainer): super().__init__(loc, data,",
"POST A LOADING STICKER sticker = await message.answer_sticker(self.loc.LOADING_STICKER, disable_notification=True, reply_markup=ReplyKeyboardRemove())",
"combine_frame_and_photo(self.deps.cfg, user_pic) pic = await combine_frame_and_photo_v2(self.deps.cfg, user_pic) user_id = message.from_user.id",
"END stack.push_async_callback(sticker.delete) if explicit_picture is not None: user_pic = await",
"w, h = user_pic.size if not w or not h:",
"from aiogram.dispatcher.storage import FSMContextProxy from aiogram.types import Message, PhotoSize, ReplyKeyboardRemove,",
"HelperMode from dialog.avatar_image_work import download_tg_photo, get_userpic, combine_frame_and_photo_v2, img_to_bio from dialog.base",
"reply_markup=ReplyKeyboardRemove()) # CLEAN UP IN THE END stack.push_async_callback(sticker.delete) if explicit_picture",
"await message.answer(loc.TEXT_AVA_ERR_SIZE, reply_markup=self.menu_kbd()) return # pic = await combine_frame_and_photo(self.deps.cfg, user_pic)",
"FSMContextProxy, d: DepContainer): super().__init__(loc, data, d) self._work_lock = asyncio.Lock() def",
"explicit_picture: PhotoSize = None): async with AsyncExitStack() as stack: stack.enter_async_context(self._work_lock)",
"not w or not h: await message.answer(loc.TEXT_AVA_ERR_INVALID, reply_markup=self.menu_kbd()) return if",
"AsyncExitStack() as stack: stack.enter_async_context(self._work_lock) # POST A LOADING STICKER sticker",
"not h: await message.answer(loc.TEXT_AVA_ERR_INVALID, reply_markup=self.menu_kbd()) return if not ((64 <=",
"return kbd([ self.loc.BUTTON_AVA_FROM_MY_USERPIC, ], vert=True) @message_handler(state=None) async def on_no_state(self, message:",
"def on_no_state(self, message: Message): await self.on_enter(message) @message_handler(state=AvatarStates.MAIN) async def on_enter(self,",
"self.loc) else: await AvatarStates.MAIN.set() await message.answer(self.loc.TEXT_AVA_WELCOME, reply_markup=self.menu_kbd()) @message_handler(state=AvatarStates.MAIN, content_types=ContentTypes.PHOTO) async",
"stack.push_async_callback(sticker.delete) if explicit_picture is not None: user_pic = await download_tg_photo(explicit_picture)",
"PhotoSize = None): async with AsyncExitStack() as stack: stack.enter_async_context(self._work_lock) #",
"import Message, PhotoSize, ReplyKeyboardRemove, ContentTypes from aiogram.utils.helper import HelperMode from",
"loc: BaseLocalization, explicit_picture: PhotoSize = None): async with AsyncExitStack() as",
"Message): if message.text == self.loc.BUTTON_AVA_FROM_MY_USERPIC: await self.handle_avatar_picture(message, self.loc) else: await",
"DepContainer from lib.texts import kbd # todo: accept documents! class",
"self.handle_avatar_picture(message, self.loc, explicit_picture=message.photo[0]) async def handle_avatar_picture(self, message: Message, loc: BaseLocalization,",
"<= 4096)): await message.answer(loc.TEXT_AVA_ERR_SIZE, reply_markup=self.menu_kbd()) return # pic = await",
"message.answer(loc.TEXT_AVA_ERR_SIZE, reply_markup=self.menu_kbd()) return # pic = await combine_frame_and_photo(self.deps.cfg, user_pic) pic",
"combine_frame_and_photo_v2, img_to_bio from dialog.base import BaseDialog, message_handler from localization import",
"handle_avatar_picture(self, message: Message, loc: BaseLocalization, explicit_picture: PhotoSize = None): async",
"import AsyncExitStack from aiogram.dispatcher.filters.state import StatesGroup, State from aiogram.dispatcher.storage import",
"h <= 4096)): await message.answer(loc.TEXT_AVA_ERR_SIZE, reply_markup=self.menu_kbd()) return # pic =",
"= None): async with AsyncExitStack() as stack: stack.enter_async_context(self._work_lock) # POST",
"content_types=ContentTypes.PHOTO) async def on_picture(self, message: Message): await self.handle_avatar_picture(message, self.loc, explicit_picture=message.photo[0])",
"# CLEAN UP IN THE END stack.push_async_callback(sticker.delete) if explicit_picture is",
"import asyncio from contextlib import AsyncExitStack from aiogram.dispatcher.filters.state import StatesGroup,",
"aiogram.dispatcher.storage import FSMContextProxy from aiogram.types import Message, PhotoSize, ReplyKeyboardRemove, ContentTypes",
"aiogram.utils.helper import HelperMode from dialog.avatar_image_work import download_tg_photo, get_userpic, combine_frame_and_photo_v2, img_to_bio",
"d) self._work_lock = asyncio.Lock() def menu_kbd(self): return kbd([ self.loc.BUTTON_AVA_FROM_MY_USERPIC, ],",
"user_pic = await download_tg_photo(explicit_picture) else: user_pic = await get_userpic(message.from_user) w,",
"A LOADING STICKER sticker = await message.answer_sticker(self.loc.LOADING_STICKER, disable_notification=True, reply_markup=ReplyKeyboardRemove()) #",
"# todo: accept documents! class AvatarStates(StatesGroup): mode = HelperMode.snake_case #",
"message.answer(self.loc.TEXT_AVA_WELCOME, reply_markup=self.menu_kbd()) @message_handler(state=AvatarStates.MAIN, content_types=ContentTypes.PHOTO) async def on_picture(self, message: Message): await",
"HelperMode.snake_case # fixme: no state handle MAIN = State() class",
"None: user_pic = await download_tg_photo(explicit_picture) else: user_pic = await get_userpic(message.from_user)",
"((64 <= w <= 4096) and (64 <= h <=",
"await get_userpic(message.from_user) w, h = user_pic.size if not w or",
"await combine_frame_and_photo_v2(self.deps.cfg, user_pic) user_id = message.from_user.id pic = img_to_bio(pic, name=f'alpha_avatar_{user_id}.png')",
"__init__(self, loc: BaseLocalization, data: FSMContextProxy, d: DepContainer): super().__init__(loc, data, d)",
"= await get_userpic(message.from_user) w, h = user_pic.size if not w",
"asyncio from contextlib import AsyncExitStack from aiogram.dispatcher.filters.state import StatesGroup, State",
"async def handle_avatar_picture(self, message: Message, loc: BaseLocalization, explicit_picture: PhotoSize =",
"import download_tg_photo, get_userpic, combine_frame_and_photo_v2, img_to_bio from dialog.base import BaseDialog, message_handler",
"message: Message): await self.on_enter(message) @message_handler(state=AvatarStates.MAIN) async def on_enter(self, message: Message):",
"self._work_lock = asyncio.Lock() def menu_kbd(self): return kbd([ self.loc.BUTTON_AVA_FROM_MY_USERPIC, ], vert=True)",
"documents! class AvatarStates(StatesGroup): mode = HelperMode.snake_case # fixme: no state",
"# POST A LOADING STICKER sticker = await message.answer_sticker(self.loc.LOADING_STICKER, disable_notification=True,",
"], vert=True) @message_handler(state=None) async def on_no_state(self, message: Message): await self.on_enter(message)",
"on_enter(self, message: Message): if message.text == self.loc.BUTTON_AVA_FROM_MY_USERPIC: await self.handle_avatar_picture(message, self.loc)",
"<= h <= 4096)): await message.answer(loc.TEXT_AVA_ERR_SIZE, reply_markup=self.menu_kbd()) return # pic",
"DepContainer): super().__init__(loc, data, d) self._work_lock = asyncio.Lock() def menu_kbd(self): return",
"Message): await self.handle_avatar_picture(message, self.loc, explicit_picture=message.photo[0]) async def handle_avatar_picture(self, message: Message,",
"await message.answer(loc.TEXT_AVA_ERR_INVALID, reply_markup=self.menu_kbd()) return if not ((64 <= w <=",
"4096)): await message.answer(loc.TEXT_AVA_ERR_SIZE, reply_markup=self.menu_kbd()) return # pic = await combine_frame_and_photo(self.deps.cfg,",
"@message_handler(state=None) async def on_no_state(self, message: Message): await self.on_enter(message) @message_handler(state=AvatarStates.MAIN) async",
"import HelperMode from dialog.avatar_image_work import download_tg_photo, get_userpic, combine_frame_and_photo_v2, img_to_bio from",
"no state handle MAIN = State() class AvatarDialog(BaseDialog): def __init__(self,",
"stack.enter_async_context(self._work_lock) # POST A LOADING STICKER sticker = await message.answer_sticker(self.loc.LOADING_STICKER,",
"await message.answer_sticker(self.loc.LOADING_STICKER, disable_notification=True, reply_markup=ReplyKeyboardRemove()) # CLEAN UP IN THE END",
"import FSMContextProxy from aiogram.types import Message, PhotoSize, ReplyKeyboardRemove, ContentTypes from",
"def on_enter(self, message: Message): if message.text == self.loc.BUTTON_AVA_FROM_MY_USERPIC: await self.handle_avatar_picture(message,",
"kbd # todo: accept documents! class AvatarStates(StatesGroup): mode = HelperMode.snake_case",
"h: await message.answer(loc.TEXT_AVA_ERR_INVALID, reply_markup=self.menu_kbd()) return if not ((64 <= w",
"BaseLocalization from lib.depcont import DepContainer from lib.texts import kbd #",
"explicit_picture is not None: user_pic = await download_tg_photo(explicit_picture) else: user_pic",
"lib.depcont import DepContainer from lib.texts import kbd # todo: accept",
"if explicit_picture is not None: user_pic = await download_tg_photo(explicit_picture) else:",
"= await combine_frame_and_photo_v2(self.deps.cfg, user_pic) user_id = message.from_user.id pic = img_to_bio(pic,",
"from lib.depcont import DepContainer from lib.texts import kbd # todo:",
"def on_picture(self, message: Message): await self.handle_avatar_picture(message, self.loc, explicit_picture=message.photo[0]) async def",
"= user_pic.size if not w or not h: await message.answer(loc.TEXT_AVA_ERR_INVALID,",
"IN THE END stack.push_async_callback(sticker.delete) if explicit_picture is not None: user_pic",
"reply_markup=self.menu_kbd()) return # pic = await combine_frame_and_photo(self.deps.cfg, user_pic) pic =",
"await message.answer(self.loc.TEXT_AVA_WELCOME, reply_markup=self.menu_kbd()) @message_handler(state=AvatarStates.MAIN, content_types=ContentTypes.PHOTO) async def on_picture(self, message: Message):",
"CLEAN UP IN THE END stack.push_async_callback(sticker.delete) if explicit_picture is not",
"self.loc, explicit_picture=message.photo[0]) async def handle_avatar_picture(self, message: Message, loc: BaseLocalization, explicit_picture:",
"is not None: user_pic = await download_tg_photo(explicit_picture) else: user_pic =",
"reply_markup=self.menu_kbd()) return if not ((64 <= w <= 4096) and",
"d: DepContainer): super().__init__(loc, data, d) self._work_lock = asyncio.Lock() def menu_kbd(self):",
"user_pic = await get_userpic(message.from_user) w, h = user_pic.size if not",
"reply_markup=self.menu_kbd()) @message_handler(state=AvatarStates.MAIN, content_types=ContentTypes.PHOTO) async def on_picture(self, message: Message): await self.handle_avatar_picture(message,",
"handle MAIN = State() class AvatarDialog(BaseDialog): def __init__(self, loc: BaseLocalization,",
"explicit_picture=message.photo[0]) async def handle_avatar_picture(self, message: Message, loc: BaseLocalization, explicit_picture: PhotoSize",
"not ((64 <= w <= 4096) and (64 <= h",
"from dialog.avatar_image_work import download_tg_photo, get_userpic, combine_frame_and_photo_v2, img_to_bio from dialog.base import",
"def handle_avatar_picture(self, message: Message, loc: BaseLocalization, explicit_picture: PhotoSize = None):",
"UP IN THE END stack.push_async_callback(sticker.delete) if explicit_picture is not None:",
"user_pic.size if not w or not h: await message.answer(loc.TEXT_AVA_ERR_INVALID, reply_markup=self.menu_kbd())",
"vert=True) @message_handler(state=None) async def on_no_state(self, message: Message): await self.on_enter(message) @message_handler(state=AvatarStates.MAIN)",
"AvatarStates(StatesGroup): mode = HelperMode.snake_case # fixme: no state handle MAIN",
"# fixme: no state handle MAIN = State() class AvatarDialog(BaseDialog):",
"self.loc.BUTTON_AVA_FROM_MY_USERPIC, ], vert=True) @message_handler(state=None) async def on_no_state(self, message: Message): await",
"stack: stack.enter_async_context(self._work_lock) # POST A LOADING STICKER sticker = await",
"if not ((64 <= w <= 4096) and (64 <=",
"message: Message): if message.text == self.loc.BUTTON_AVA_FROM_MY_USERPIC: await self.handle_avatar_picture(message, self.loc) else:",
"img_to_bio from dialog.base import BaseDialog, message_handler from localization import BaseLocalization",
"= await combine_frame_and_photo(self.deps.cfg, user_pic) pic = await combine_frame_and_photo_v2(self.deps.cfg, user_pic) user_id"
] |
[
"img_name[0][0] print(\"Check the values\" + str(self.images_list)) self.image_store.append(self.images_list.copy()) print(\"Check the images\"",
"db_ops.insert_operations(\"image_store\", values) def request_list_of_images_in_db(self): # images = glob(IMAGE_FOLDER + \"/*\"",
"self.image_store def calculate_hamming_dist(self, uploaded_hash, db_store_hash): i = 0 count =",
"print(values) db_ops.image_store_migrations() # TODO Abstract requests and insert from database",
"= ['png', 'jpg', 'jpeg'] image_store_hash = dict() db_ops = database_migrations()",
"# the 'Mean Squared Error' between the two images is",
"self.images_list = dict() self.image_store = list() def request_image_hashes(self): images =",
"img in images: imgname = ntpath.basename(img) values = imgname, IMAGE_FOLDER,",
"= ssim(uploaded_image, db_store_image) return ssim_index def convert_and_resize_compare(self, uploaded_image, db_store_image): #",
"database db_ops.insert_operations(\"image_store\", values) def request_list_of_images_in_db(self): # images = glob(IMAGE_FOLDER +",
"uploaded_image = cv2.cvtColor(uploaded_image, cv2.COLOR_BGR2GRAY) db_store_image = cv2.cvtColor(db_store_image, cv2.COLOR_BGR2GRAY) mean_sq_error =",
"['png', 'jpg', 'jpeg'] image_store_hash = dict() db_ops = database_migrations() class",
"ALLOWED_EXTENSIONS = ['png', 'jpg', 'jpeg'] image_store_hash = dict() db_ops =",
"0 while (i < len(uploaded_hash)): if (uploaded_hash[i] != db_store_hash[i]): count",
"+ str(self.image_store)) self.images_list[\"image_id\"] = img[0] self.images_list[\"image_name\"] = img[1] print(\"Check the",
"list\" + str(self.image_store)) self.images_list[\"image_id\"] = img[0] self.images_list[\"image_name\"] = img[1] print(\"Check",
"imgname = ntpath.basename(img) values = imgname, IMAGE_FOLDER, \"local\" print(values) db_ops.image_store_migrations()",
"# get image name print(\"current list\" + str(img)) self.images_list[\"image_hash\"] =",
"self.image_store.clear() self.images_list.clear() for img in images: # get image name",
"values = imgname, IMAGE_FOLDER, \"local\" print(values) db_ops.image_store_migrations() # TODO Abstract",
"# image table values to insert in database self.images_list =",
"insert in database self.images_list = dict() self.image_store = list() def",
"print(\"We have\" + str(len(self.image_store)) + \"images in the store\") print(self.image_store)",
"images is the # sum of the squared difference between",
"request image name from image store database img_name = db_ops.conditional_request_matches(",
"skimage.metrics import structural_similarity as ssim from glob import glob from",
"# request image name from image store database img_name =",
"error, the more \"similar\" # the two images are return",
"store\") print(self.image_store) return self.image_store def calculate_hamming_dist(self, uploaded_hash, db_store_hash): i =",
"list() def request_image_hashes(self): images = db_ops.request_matches(\"image_store_hash\") print(\"list from database\" +",
"get image name print(\"current list\" + str(img)) self.images_list[\"image_hash\"] = img[1]",
"for img in images_in_db: image = Image.open(IMAGE_FOLDER + \"\\\\\" +",
"\"images in the store\") print(self.image_store) return self.image_store def calculate_hamming_dist(self, uploaded_hash,",
"in images: # get image name print(\"current list\" + str(img))",
"dhash import cv2 from database_structure import database_migrations IMAGE_FOLDER = \"./image_store\"",
"= Image.open(IMAGE_FOLDER + \"\\\\\" + img[\"image_name\"]) row, col = dhash.dhash_row_col(image)",
"database self.images_list = dict() self.image_store = list() def load_images_into_to_db(self): for",
"of the squared difference between the two images; # NOTE:",
"if (uploaded_hash[i] != db_store_hash[i]): count += 1 i += 1",
"<reponame>olubiyiontheweb/digid_websearch_flask from skimage.metrics import structural_similarity as ssim from glob import",
"\"images in the store\") print(self.image_store) return self.image_store def generate_hash(self): images_in_db",
"img[2], \"image_name\", \"image_id\") self.images_list[\"image_name\"] = img_name[0][0] print(\"Check the values\" +",
"class preprocess: def __init__(self): # image table values to insert",
"the two images; # NOTE: the two images must have",
"the store\") print(self.image_store) return self.image_store def generate_hash(self): images_in_db = self.request_list_of_images_in_db()",
"print(\"current list\" + str(self.image_store)) self.images_list[\"image_id\"] = img[0] self.images_list[\"image_name\"] = img[1]",
"values to insert in database self.images_list = dict() self.image_store =",
"more \"similar\" # the two images are return err def",
"as ssim from glob import glob from PIL import Image",
"must have the same dimension err = np.sum((uploaded_image.astype(\"float\") - db_store_image.astype(\"float\"))**2)",
"cv2.COLOR_BGR2GRAY) db_store_image = cv2.cvtColor(db_store_image, cv2.COLOR_BGR2GRAY) mean_sq_error = self.mean_squared_error(uploaded_image, db_store_image) ssim_index",
"import cv2 from database_structure import database_migrations IMAGE_FOLDER = \"./image_store\" ALLOWED_EXTENSIONS",
"self.images_list[\"image_name\"] = img_name[0][0] print(\"Check the values\" + str(self.images_list)) self.image_store.append(self.images_list.copy()) print(\"Check",
"image table values to insert in database self.images_list = dict()",
"return count def mean_squared_error(self, uploaded_image, db_store_image): # the 'Mean Squared",
"= dict() self.image_store = list() def load_images_into_to_db(self): for img_type in",
"self.image_store = list() def load_images_into_to_db(self): for img_type in ALLOWED_EXTENSIONS: images",
"the same dimension err = np.sum((uploaded_image.astype(\"float\") - db_store_image.astype(\"float\"))**2) err /=",
"while (i < len(uploaded_hash)): if (uploaded_hash[i] != db_store_hash[i]): count +=",
"+ img_type) images = db_ops.request_matches(\"image_store\") print(\"list from database\" + str(images))",
"image store database img_name = db_ops.conditional_request_matches( \"image_store\", img[2], \"image_name\", \"image_id\")",
"lower the error, the more \"similar\" # the two images",
"def request_image_hashes(self): images = db_ops.request_matches(\"image_store_hash\") print(\"list from database\" + str(images))",
"error functionals uploaded_image = cv2.imread(uploaded_image) db_store_image = cv2.imread(db_store_image) uploaded_image =",
"# NOTE: the two images must have the same dimension",
"the MSE, the lower the error, the more \"similar\" #",
"img in images: # get image name print(\"current list\" +",
"< len(uploaded_hash)): if (uploaded_hash[i] != db_store_hash[i]): count += 1 i",
"structural_similarity_index(self, uploaded_image, db_store_image): ssim_index = ssim(uploaded_image, db_store_image) return ssim_index def",
"return self.image_store def calculate_hamming_dist(self, uploaded_hash, db_store_hash): i = 0 count",
"and insert from database db_ops.insert_operations(\"image_store\", values) def request_list_of_images_in_db(self): # images",
"mean_sq_error = self.mean_squared_error(uploaded_image, db_store_image) ssim_index = self.structural_similarity_index(uploaded_image, db_store_image) return ssim_index,",
"np.sum((uploaded_image.astype(\"float\") - db_store_image.astype(\"float\"))**2) err /= float(uploaded_image.shape[0] * uploaded_image.shape[1]) # return",
"in ALLOWED_EXTENSIONS: images = glob(IMAGE_FOLDER + \"/*\" + img_type) for",
"the squared difference between the two images; # NOTE: the",
"mean squared error functionals uploaded_image = cv2.imread(uploaded_image) db_store_image = cv2.imread(db_store_image)",
"image name print(\"current list\" + str(img)) self.images_list[\"image_hash\"] = img[1] #",
"dhash.format_hex(row, col) values = img_hash, img[\"image_id\"] db_ops.image_store_migrations() print(values) db_ops.insert_operations(\"image_store_hash\", values)",
"values\" + str(self.images_list)) self.image_store.append(self.images_list.copy()) print(\"Check the images\" + str(self.image_store)) print(\"We",
"= dhash.dhash_row_col(image) img_hash = dhash.format_hex(row, col) values = img_hash, img[\"image_id\"]",
"def generate_hash(self): images_in_db = self.request_list_of_images_in_db() print(images_in_db) for img in images_in_db:",
"MSE, the lower the error, the more \"similar\" # the",
"two images is the # sum of the squared difference",
"= list() def request_image_hashes(self): images = db_ops.request_matches(\"image_store_hash\") print(\"list from database\"",
"between the two images; # NOTE: the two images must",
"cv2.imread(db_store_image) uploaded_image = cv2.resize() db_store_image = cv2.resize() uploaded_image = cv2.cvtColor(uploaded_image,",
"return the MSE, the lower the error, the more \"similar\"",
"import database_migrations IMAGE_FOLDER = \"./image_store\" ALLOWED_EXTENSIONS = ['png', 'jpg', 'jpeg']",
"def convert_and_resize_compare(self, uploaded_image, db_store_image): # TODO: make structural similarity and",
"database_structure import database_migrations IMAGE_FOLDER = \"./image_store\" ALLOWED_EXTENSIONS = ['png', 'jpg',",
"= self.mean_squared_error(uploaded_image, db_store_image) ssim_index = self.structural_similarity_index(uploaded_image, db_store_image) return ssim_index, mean_sq_error",
"db_store_image) return ssim_index def convert_and_resize_compare(self, uploaded_image, db_store_image): # TODO: make",
"= imgname, IMAGE_FOLDER, \"local\" print(values) db_ops.image_store_migrations() # TODO Abstract requests",
"+ \"/*\" + img_type) for img in images: imgname =",
"in images: imgname = ntpath.basename(img) values = imgname, IMAGE_FOLDER, \"local\"",
"+ \"\\\\\" + img[\"image_name\"]) row, col = dhash.dhash_row_col(image) img_hash =",
"from skimage.metrics import structural_similarity as ssim from glob import glob",
"\"\\\\\" + img[\"image_name\"]) row, col = dhash.dhash_row_col(image) img_hash = dhash.format_hex(row,",
"np import ntpath import dhash import cv2 from database_structure import",
"ssim_index def convert_and_resize_compare(self, uploaded_image, db_store_image): # TODO: make structural similarity",
"= cv2.cvtColor(db_store_image, cv2.COLOR_BGR2GRAY) mean_sq_error = self.mean_squared_error(uploaded_image, db_store_image) ssim_index = self.structural_similarity_index(uploaded_image,",
"squared error functionals uploaded_image = cv2.imread(uploaded_image) db_store_image = cv2.imread(db_store_image) uploaded_image",
"= img_name[0][0] print(\"Check the values\" + str(self.images_list)) self.image_store.append(self.images_list.copy()) print(\"Check the",
"def calculate_hamming_dist(self, uploaded_hash, db_store_hash): i = 0 count = 0",
"img[1] # request image name from image store database img_name",
"uploaded_image = cv2.imread(uploaded_image) db_store_image = cv2.imread(db_store_image) uploaded_image = cv2.resize() db_store_image",
"the # sum of the squared difference between the two",
"the two images is the # sum of the squared",
"name from image store database img_name = db_ops.conditional_request_matches( \"image_store\", img[2],",
"return err def structural_similarity_index(self, uploaded_image, db_store_image): ssim_index = ssim(uploaded_image, db_store_image)",
"import numpy as np import ntpath import dhash import cv2",
"= cv2.resize() db_store_image = cv2.resize() uploaded_image = cv2.cvtColor(uploaded_image, cv2.COLOR_BGR2GRAY) db_store_image",
"Squared Error' between the two images is the # sum",
"self.images_list[\"image_id\"] = img[0] self.images_list[\"image_name\"] = img[1] print(\"Check the values\" +",
"ssim from glob import glob from PIL import Image import",
"= ntpath.basename(img) values = imgname, IMAGE_FOLDER, \"local\" print(values) db_ops.image_store_migrations() #",
"db_ops.insert_operations(\"image_store_hash\", values) class compare_files: def __init__(self): # image table values",
"= 0 while (i < len(uploaded_hash)): if (uploaded_hash[i] != db_store_hash[i]):",
"print(\"current list\" + str(img)) self.images_list[\"image_hash\"] = img[1] # request image",
"cv2.resize() uploaded_image = cv2.cvtColor(uploaded_image, cv2.COLOR_BGR2GRAY) db_store_image = cv2.cvtColor(db_store_image, cv2.COLOR_BGR2GRAY) mean_sq_error",
"functionals uploaded_image = cv2.imread(uploaded_image) db_store_image = cv2.imread(db_store_image) uploaded_image = cv2.resize()",
"+= 1 return count def mean_squared_error(self, uploaded_image, db_store_image): # the",
"ssim_index = ssim(uploaded_image, db_store_image) return ssim_index def convert_and_resize_compare(self, uploaded_image, db_store_image):",
"squared difference between the two images; # NOTE: the two",
"import glob from PIL import Image import numpy as np",
"str(self.image_store)) print(\"We have\" + str(len(self.image_store)) + \"images in the store\")",
"db_store_image.astype(\"float\"))**2) err /= float(uploaded_image.shape[0] * uploaded_image.shape[1]) # return the MSE,",
"\"image_name\", \"image_id\") self.images_list[\"image_name\"] = img_name[0][0] print(\"Check the values\" + str(self.images_list))",
"str(images)) self.image_store.clear() self.images_list.clear() for img in images: # get image",
"images: # get image name print(\"current list\" + str(img)) self.images_list[\"image_hash\"]",
"and mean squared error functionals uploaded_image = cv2.imread(uploaded_image) db_store_image =",
"\"./image_store\" ALLOWED_EXTENSIONS = ['png', 'jpg', 'jpeg'] image_store_hash = dict() db_ops",
"= \"./image_store\" ALLOWED_EXTENSIONS = ['png', 'jpg', 'jpeg'] image_store_hash = dict()",
"dimension err = np.sum((uploaded_image.astype(\"float\") - db_store_image.astype(\"float\"))**2) err /= float(uploaded_image.shape[0] *",
"uploaded_image.shape[1]) # return the MSE, the lower the error, the",
"\"image_store\", img[2], \"image_name\", \"image_id\") self.images_list[\"image_name\"] = img_name[0][0] print(\"Check the values\"",
"IMAGE_FOLDER = \"./image_store\" ALLOWED_EXTENSIONS = ['png', 'jpg', 'jpeg'] image_store_hash =",
"+ str(self.images_list)) self.image_store.append(self.images_list.copy()) print(\"Check the images\" + str(self.image_store)) print(\"We have\"",
"from glob import glob from PIL import Image import numpy",
"difference between the two images; # NOTE: the two images",
"from database db_ops.insert_operations(\"image_store\", values) def request_list_of_images_in_db(self): # images = glob(IMAGE_FOLDER",
"count += 1 i += 1 return count def mean_squared_error(self,",
"from database_structure import database_migrations IMAGE_FOLDER = \"./image_store\" ALLOWED_EXTENSIONS = ['png',",
"!= db_store_hash[i]): count += 1 i += 1 return count",
"uploaded_image, db_store_image): # TODO: make structural similarity and mean squared",
"database\" + str(images)) self.image_store.clear() self.images_list.clear() for img in images: #",
"the images\" + str(self.image_store)) print(\"We have\" + str(len(self.image_store)) + \"images",
"float(uploaded_image.shape[0] * uploaded_image.shape[1]) # return the MSE, the lower the",
"img[1] print(\"Check the values\" + str(self.images_list)) self.image_store.append(self.images_list.copy()) print(\"Check the images\"",
"structural similarity and mean squared error functionals uploaded_image = cv2.imread(uploaded_image)",
"= cv2.cvtColor(uploaded_image, cv2.COLOR_BGR2GRAY) db_store_image = cv2.cvtColor(db_store_image, cv2.COLOR_BGR2GRAY) mean_sq_error = self.mean_squared_error(uploaded_image,",
"count = 0 while (i < len(uploaded_hash)): if (uploaded_hash[i] !=",
"= np.sum((uploaded_image.astype(\"float\") - db_store_image.astype(\"float\"))**2) err /= float(uploaded_image.shape[0] * uploaded_image.shape[1]) #",
"from PIL import Image import numpy as np import ntpath",
"load_images_into_to_db(self): for img_type in ALLOWED_EXTENSIONS: images = glob(IMAGE_FOLDER + \"/*\"",
"+ img[\"image_name\"]) row, col = dhash.dhash_row_col(image) img_hash = dhash.format_hex(row, col)",
"import Image import numpy as np import ntpath import dhash",
"= glob(IMAGE_FOLDER + \"/*\" + img_type) for img in images:",
"class compare_files: def __init__(self): # image table values to insert",
"\"/*\" + img_type) images = db_ops.request_matches(\"image_store\") print(\"list from database\" +",
"TODO Abstract requests and insert from database db_ops.insert_operations(\"image_store\", values) def",
"preprocess: def __init__(self): # image table values to insert in",
"db_store_hash[i]): count += 1 i += 1 return count def",
"# get image name print(\"current list\" + str(self.image_store)) self.images_list[\"image_id\"] =",
"compare_files: def __init__(self): # image table values to insert in",
"table values to insert in database self.images_list = dict() self.image_store",
"= img[1] # request image name from image store database",
"str(self.image_store)) self.images_list[\"image_id\"] = img[0] self.images_list[\"image_name\"] = img[1] print(\"Check the values\"",
"mean_squared_error(self, uploaded_image, db_store_image): # the 'Mean Squared Error' between the",
"between the two images is the # sum of the",
"+ str(images)) self.image_store.clear() self.images_list.clear() for img in images: # get",
"1 i += 1 return count def mean_squared_error(self, uploaded_image, db_store_image):",
"ntpath.basename(img) values = imgname, IMAGE_FOLDER, \"local\" print(values) db_ops.image_store_migrations() # TODO",
"= cv2.imread(uploaded_image) db_store_image = cv2.imread(db_store_image) uploaded_image = cv2.resize() db_store_image =",
"in images_in_db: image = Image.open(IMAGE_FOLDER + \"\\\\\" + img[\"image_name\"]) row,",
"db_store_image = cv2.imread(db_store_image) uploaded_image = cv2.resize() db_store_image = cv2.resize() uploaded_image",
"'jpg', 'jpeg'] image_store_hash = dict() db_ops = database_migrations() class preprocess:",
"# sum of the squared difference between the two images;",
"(i < len(uploaded_hash)): if (uploaded_hash[i] != db_store_hash[i]): count += 1",
"self.request_list_of_images_in_db() print(images_in_db) for img in images_in_db: image = Image.open(IMAGE_FOLDER +",
"img_type) for img in images: imgname = ntpath.basename(img) values =",
"are return err def structural_similarity_index(self, uploaded_image, db_store_image): ssim_index = ssim(uploaded_image,",
"in images: # get image name print(\"current list\" + str(self.image_store))",
"values) class compare_files: def __init__(self): # image table values to",
"= db_ops.request_matches(\"image_store\") print(\"list from database\" + str(images)) self.image_store.clear() self.images_list.clear() for",
"def structural_similarity_index(self, uploaded_image, db_store_image): ssim_index = ssim(uploaded_image, db_store_image) return ssim_index",
"for img_type in ALLOWED_EXTENSIONS: images = glob(IMAGE_FOLDER + \"/*\" +",
"err /= float(uploaded_image.shape[0] * uploaded_image.shape[1]) # return the MSE, the",
"image name print(\"current list\" + str(self.image_store)) self.images_list[\"image_id\"] = img[0] self.images_list[\"image_name\"]",
"self.images_list[\"image_name\"] = img[1] print(\"Check the values\" + str(self.images_list)) self.image_store.append(self.images_list.copy()) print(\"Check",
"self.image_store = list() def request_image_hashes(self): images = db_ops.request_matches(\"image_store_hash\") print(\"list from",
"image_store_hash = dict() db_ops = database_migrations() class preprocess: def __init__(self):",
"len(uploaded_hash)): if (uploaded_hash[i] != db_store_hash[i]): count += 1 i +=",
"requests and insert from database db_ops.insert_operations(\"image_store\", values) def request_list_of_images_in_db(self): #",
"print(\"Check the images\" + str(self.image_store)) print(\"We have\" + str(len(self.image_store)) +",
"list() def load_images_into_to_db(self): for img_type in ALLOWED_EXTENSIONS: images = glob(IMAGE_FOLDER",
"dict() db_ops = database_migrations() class preprocess: def __init__(self): # image",
"cv2 from database_structure import database_migrations IMAGE_FOLDER = \"./image_store\" ALLOWED_EXTENSIONS =",
"the 'Mean Squared Error' between the two images is the",
"database self.images_list = dict() self.image_store = list() def request_image_hashes(self): images",
"two images are return err def structural_similarity_index(self, uploaded_image, db_store_image): ssim_index",
"cv2.imread(uploaded_image) db_store_image = cv2.imread(db_store_image) uploaded_image = cv2.resize() db_store_image = cv2.resize()",
"dict() self.image_store = list() def request_image_hashes(self): images = db_ops.request_matches(\"image_store_hash\") print(\"list",
"* uploaded_image.shape[1]) # return the MSE, the lower the error,",
"def __init__(self): # image table values to insert in database",
"db_ops.conditional_request_matches( \"image_store\", img[2], \"image_name\", \"image_id\") self.images_list[\"image_name\"] = img_name[0][0] print(\"Check the",
"self.image_store.append(self.images_list.copy()) print(\"Check the images\" + str(self.image_store)) print(\"We have\" + str(len(self.image_store))",
"the store\") print(self.image_store) return self.image_store def calculate_hamming_dist(self, uploaded_hash, db_store_hash): i",
"sum of the squared difference between the two images; #",
"two images; # NOTE: the two images must have the",
"\"local\" print(values) db_ops.image_store_migrations() # TODO Abstract requests and insert from",
"the two images are return err def structural_similarity_index(self, uploaded_image, db_store_image):",
"db_store_image): # TODO: make structural similarity and mean squared error",
"is the # sum of the squared difference between the",
"from image store database img_name = db_ops.conditional_request_matches( \"image_store\", img[2], \"image_name\",",
"= 0 count = 0 while (i < len(uploaded_hash)): if",
"= cv2.resize() uploaded_image = cv2.cvtColor(uploaded_image, cv2.COLOR_BGR2GRAY) db_store_image = cv2.cvtColor(db_store_image, cv2.COLOR_BGR2GRAY)",
"+= 1 i += 1 return count def mean_squared_error(self, uploaded_image,",
"list\" + str(img)) self.images_list[\"image_hash\"] = img[1] # request image name",
"img in images_in_db: image = Image.open(IMAGE_FOLDER + \"\\\\\" + img[\"image_name\"])",
"= dict() db_ops = database_migrations() class preprocess: def __init__(self): #",
"name print(\"current list\" + str(self.image_store)) self.images_list[\"image_id\"] = img[0] self.images_list[\"image_name\"] =",
"img[\"image_name\"]) row, col = dhash.dhash_row_col(image) img_hash = dhash.format_hex(row, col) values",
"+ str(img)) self.images_list[\"image_hash\"] = img[1] # request image name from",
"col) values = img_hash, img[\"image_id\"] db_ops.image_store_migrations() print(values) db_ops.insert_operations(\"image_store_hash\", values) class",
"print(self.image_store) return self.image_store def calculate_hamming_dist(self, uploaded_hash, db_store_hash): i = 0",
"img_name = db_ops.conditional_request_matches( \"image_store\", img[2], \"image_name\", \"image_id\") self.images_list[\"image_name\"] = img_name[0][0]",
"= self.request_list_of_images_in_db() print(images_in_db) for img in images_in_db: image = Image.open(IMAGE_FOLDER",
"insert from database db_ops.insert_operations(\"image_store\", values) def request_list_of_images_in_db(self): # images =",
"db_ops = database_migrations() class preprocess: def __init__(self): # image table",
"NOTE: the two images must have the same dimension err",
"images = db_ops.request_matches(\"image_store_hash\") print(\"list from database\" + str(images)) self.image_store.clear() self.images_list.clear()",
"structural_similarity as ssim from glob import glob from PIL import",
"PIL import Image import numpy as np import ntpath import",
"calculate_hamming_dist(self, uploaded_hash, db_store_hash): i = 0 count = 0 while",
"print(images_in_db) for img in images_in_db: image = Image.open(IMAGE_FOLDER + \"\\\\\"",
"images_in_db: image = Image.open(IMAGE_FOLDER + \"\\\\\" + img[\"image_name\"]) row, col",
"= dhash.format_hex(row, col) values = img_hash, img[\"image_id\"] db_ops.image_store_migrations() print(values) db_ops.insert_operations(\"image_store_hash\",",
"images: imgname = ntpath.basename(img) values = imgname, IMAGE_FOLDER, \"local\" print(values)",
"img_hash = dhash.format_hex(row, col) values = img_hash, img[\"image_id\"] db_ops.image_store_migrations() print(values)",
"db_ops.request_matches(\"image_store\") print(\"list from database\" + str(images)) self.image_store.clear() self.images_list.clear() for img",
"the lower the error, the more \"similar\" # the two",
"db_store_hash): i = 0 count = 0 while (i <",
"# TODO: make structural similarity and mean squared error functionals",
"+ str(self.image_store)) print(\"We have\" + str(len(self.image_store)) + \"images in the",
"images\" + str(self.image_store)) print(\"We have\" + str(len(self.image_store)) + \"images in",
"the values\" + str(self.images_list)) self.image_store.append(self.images_list.copy()) print(\"Check the images\" + str(self.image_store))",
"= img[1] print(\"Check the values\" + str(self.images_list)) self.image_store.append(self.images_list.copy()) print(\"Check the",
"image name from image store database img_name = db_ops.conditional_request_matches( \"image_store\",",
"to insert in database self.images_list = dict() self.image_store = list()",
"= dict() self.image_store = list() def request_image_hashes(self): images = db_ops.request_matches(\"image_store_hash\")",
"db_store_image): # the 'Mean Squared Error' between the two images",
"Image.open(IMAGE_FOLDER + \"\\\\\" + img[\"image_name\"]) row, col = dhash.dhash_row_col(image) img_hash",
"= glob(IMAGE_FOLDER + \"/*\" + img_type) images = db_ops.request_matches(\"image_store\") print(\"list",
"self.images_list.clear() for img in images: # get image name print(\"current",
"print(values) db_ops.insert_operations(\"image_store_hash\", values) class compare_files: def __init__(self): # image table",
"img_type in ALLOWED_EXTENSIONS: images = glob(IMAGE_FOLDER + \"/*\" + img_type)",
"img_hash, img[\"image_id\"] db_ops.image_store_migrations() print(values) db_ops.insert_operations(\"image_store_hash\", values) class compare_files: def __init__(self):",
"db_ops.image_store_migrations() # TODO Abstract requests and insert from database db_ops.insert_operations(\"image_store\",",
"def mean_squared_error(self, uploaded_image, db_store_image): # the 'Mean Squared Error' between",
"err def structural_similarity_index(self, uploaded_image, db_store_image): ssim_index = ssim(uploaded_image, db_store_image) return",
"= img[0] self.images_list[\"image_name\"] = img[1] print(\"Check the values\" + str(self.images_list))",
"dict() self.image_store = list() def load_images_into_to_db(self): for img_type in ALLOWED_EXTENSIONS:",
"glob from PIL import Image import numpy as np import",
"Abstract requests and insert from database db_ops.insert_operations(\"image_store\", values) def request_list_of_images_in_db(self):",
"glob(IMAGE_FOLDER + \"/*\" + img_type) images = db_ops.request_matches(\"image_store\") print(\"list from",
"str(img)) self.images_list[\"image_hash\"] = img[1] # request image name from image",
"images: # get image name print(\"current list\" + str(self.image_store)) self.images_list[\"image_id\"]",
"store database img_name = db_ops.conditional_request_matches( \"image_store\", img[2], \"image_name\", \"image_id\") self.images_list[\"image_name\"]",
"two images must have the same dimension err = np.sum((uploaded_image.astype(\"float\")",
"ssim(uploaded_image, db_store_image) return ssim_index def convert_and_resize_compare(self, uploaded_image, db_store_image): # TODO:",
"+ \"/*\" + img_type) images = db_ops.request_matches(\"image_store\") print(\"list from database\"",
"return self.image_store def generate_hash(self): images_in_db = self.request_list_of_images_in_db() print(images_in_db) for img",
"img[0] self.images_list[\"image_name\"] = img[1] print(\"Check the values\" + str(self.images_list)) self.image_store.append(self.images_list.copy())",
"+ str(len(self.image_store)) + \"images in the store\") print(self.image_store) return self.image_store",
"i += 1 return count def mean_squared_error(self, uploaded_image, db_store_image): #",
"in the store\") print(self.image_store) return self.image_store def calculate_hamming_dist(self, uploaded_hash, db_store_hash):",
"get image name print(\"current list\" + str(self.image_store)) self.images_list[\"image_id\"] = img[0]",
"= database_migrations() class preprocess: def __init__(self): # image table values",
"database img_name = db_ops.conditional_request_matches( \"image_store\", img[2], \"image_name\", \"image_id\") self.images_list[\"image_name\"] =",
"the more \"similar\" # the two images are return err",
"def request_list_of_images_in_db(self): # images = glob(IMAGE_FOLDER + \"/*\" + img_type)",
"str(len(self.image_store)) + \"images in the store\") print(self.image_store) return self.image_store def",
"db_ops.request_matches(\"image_store_hash\") print(\"list from database\" + str(images)) self.image_store.clear() self.images_list.clear() for img",
"1 return count def mean_squared_error(self, uploaded_image, db_store_image): # the 'Mean",
"images are return err def structural_similarity_index(self, uploaded_image, db_store_image): ssim_index =",
"+ \"images in the store\") print(self.image_store) return self.image_store def calculate_hamming_dist(self,",
"col = dhash.dhash_row_col(image) img_hash = dhash.format_hex(row, col) values = img_hash,",
"count def mean_squared_error(self, uploaded_image, db_store_image): # the 'Mean Squared Error'",
"i = 0 count = 0 while (i < len(uploaded_hash)):",
"# the two images are return err def structural_similarity_index(self, uploaded_image,",
"in the store\") print(self.image_store) return self.image_store def generate_hash(self): images_in_db =",
"cv2.COLOR_BGR2GRAY) mean_sq_error = self.mean_squared_error(uploaded_image, db_store_image) ssim_index = self.structural_similarity_index(uploaded_image, db_store_image) return",
"return ssim_index def convert_and_resize_compare(self, uploaded_image, db_store_image): # TODO: make structural",
"cv2.resize() db_store_image = cv2.resize() uploaded_image = cv2.cvtColor(uploaded_image, cv2.COLOR_BGR2GRAY) db_store_image =",
"import dhash import cv2 from database_structure import database_migrations IMAGE_FOLDER =",
"store\") print(self.image_store) return self.image_store def generate_hash(self): images_in_db = self.request_list_of_images_in_db() print(images_in_db)",
"+ \"images in the store\") print(self.image_store) return self.image_store def generate_hash(self):",
"self.images_list[\"image_hash\"] = img[1] # request image name from image store",
"in database self.images_list = dict() self.image_store = list() def request_image_hashes(self):",
"import ntpath import dhash import cv2 from database_structure import database_migrations",
"request_image_hashes(self): images = db_ops.request_matches(\"image_store_hash\") print(\"list from database\" + str(images)) self.image_store.clear()",
"- db_store_image.astype(\"float\"))**2) err /= float(uploaded_image.shape[0] * uploaded_image.shape[1]) # return the",
"# TODO Abstract requests and insert from database db_ops.insert_operations(\"image_store\", values)",
"similarity and mean squared error functionals uploaded_image = cv2.imread(uploaded_image) db_store_image",
"request_list_of_images_in_db(self): # images = glob(IMAGE_FOLDER + \"/*\" + img_type) images",
"glob import glob from PIL import Image import numpy as",
"the error, the more \"similar\" # the two images are",
"in database self.images_list = dict() self.image_store = list() def load_images_into_to_db(self):",
"uploaded_hash, db_store_hash): i = 0 count = 0 while (i",
"self.image_store def generate_hash(self): images_in_db = self.request_list_of_images_in_db() print(images_in_db) for img in",
"database_migrations() class preprocess: def __init__(self): # image table values to",
"str(self.images_list)) self.image_store.append(self.images_list.copy()) print(\"Check the images\" + str(self.image_store)) print(\"We have\" +",
"same dimension err = np.sum((uploaded_image.astype(\"float\") - db_store_image.astype(\"float\"))**2) err /= float(uploaded_image.shape[0]",
"db_ops.image_store_migrations() print(values) db_ops.insert_operations(\"image_store_hash\", values) class compare_files: def __init__(self): # image",
"have the same dimension err = np.sum((uploaded_image.astype(\"float\") - db_store_image.astype(\"float\"))**2) err",
"make structural similarity and mean squared error functionals uploaded_image =",
"uploaded_image = cv2.resize() db_store_image = cv2.resize() uploaded_image = cv2.cvtColor(uploaded_image, cv2.COLOR_BGR2GRAY)",
"image = Image.open(IMAGE_FOLDER + \"\\\\\" + img[\"image_name\"]) row, col =",
"TODO: make structural similarity and mean squared error functionals uploaded_image",
"0 count = 0 while (i < len(uploaded_hash)): if (uploaded_hash[i]",
"as np import ntpath import dhash import cv2 from database_structure",
"images = glob(IMAGE_FOLDER + \"/*\" + img_type) for img in",
"cv2.cvtColor(uploaded_image, cv2.COLOR_BGR2GRAY) db_store_image = cv2.cvtColor(db_store_image, cv2.COLOR_BGR2GRAY) mean_sq_error = self.mean_squared_error(uploaded_image, db_store_image)",
"values = img_hash, img[\"image_id\"] db_ops.image_store_migrations() print(values) db_ops.insert_operations(\"image_store_hash\", values) class compare_files:",
"self.images_list = dict() self.image_store = list() def load_images_into_to_db(self): for img_type",
"images = db_ops.request_matches(\"image_store\") print(\"list from database\" + str(images)) self.image_store.clear() self.images_list.clear()",
"for img in images: # get image name print(\"current list\"",
"name print(\"current list\" + str(img)) self.images_list[\"image_hash\"] = img[1] # request",
"row, col = dhash.dhash_row_col(image) img_hash = dhash.format_hex(row, col) values =",
"def load_images_into_to_db(self): for img_type in ALLOWED_EXTENSIONS: images = glob(IMAGE_FOLDER +",
"values) def request_list_of_images_in_db(self): # images = glob(IMAGE_FOLDER + \"/*\" +",
"images_in_db = self.request_list_of_images_in_db() print(images_in_db) for img in images_in_db: image =",
"\"image_id\") self.images_list[\"image_name\"] = img_name[0][0] print(\"Check the values\" + str(self.images_list)) self.image_store.append(self.images_list.copy())",
"generate_hash(self): images_in_db = self.request_list_of_images_in_db() print(images_in_db) for img in images_in_db: image",
"ntpath import dhash import cv2 from database_structure import database_migrations IMAGE_FOLDER",
"have\" + str(len(self.image_store)) + \"images in the store\") print(self.image_store) return",
"err = np.sum((uploaded_image.astype(\"float\") - db_store_image.astype(\"float\"))**2) err /= float(uploaded_image.shape[0] * uploaded_image.shape[1])",
"imgname, IMAGE_FOLDER, \"local\" print(values) db_ops.image_store_migrations() # TODO Abstract requests and",
"\"/*\" + img_type) for img in images: imgname = ntpath.basename(img)",
"uploaded_image, db_store_image): ssim_index = ssim(uploaded_image, db_store_image) return ssim_index def convert_and_resize_compare(self,",
"Image import numpy as np import ntpath import dhash import",
"database_migrations IMAGE_FOLDER = \"./image_store\" ALLOWED_EXTENSIONS = ['png', 'jpg', 'jpeg'] image_store_hash",
"uploaded_image, db_store_image): # the 'Mean Squared Error' between the two",
"__init__(self): # image table values to insert in database self.images_list",
"from database\" + str(images)) self.image_store.clear() self.images_list.clear() for img in images:",
"'Mean Squared Error' between the two images is the #",
"= db_ops.request_matches(\"image_store_hash\") print(\"list from database\" + str(images)) self.image_store.clear() self.images_list.clear() for",
"print(\"Check the values\" + str(self.images_list)) self.image_store.append(self.images_list.copy()) print(\"Check the images\" +",
"for img in images: imgname = ntpath.basename(img) values = imgname,",
"# images = glob(IMAGE_FOLDER + \"/*\" + img_type) images =",
"db_store_image = cv2.resize() uploaded_image = cv2.cvtColor(uploaded_image, cv2.COLOR_BGR2GRAY) db_store_image = cv2.cvtColor(db_store_image,",
"= list() def load_images_into_to_db(self): for img_type in ALLOWED_EXTENSIONS: images =",
"IMAGE_FOLDER, \"local\" print(values) db_ops.image_store_migrations() # TODO Abstract requests and insert",
"numpy as np import ntpath import dhash import cv2 from",
"+ img_type) for img in images: imgname = ntpath.basename(img) values",
"images; # NOTE: the two images must have the same",
"= img_hash, img[\"image_id\"] db_ops.image_store_migrations() print(values) db_ops.insert_operations(\"image_store_hash\", values) class compare_files: def",
"glob(IMAGE_FOLDER + \"/*\" + img_type) for img in images: imgname",
"cv2.cvtColor(db_store_image, cv2.COLOR_BGR2GRAY) mean_sq_error = self.mean_squared_error(uploaded_image, db_store_image) ssim_index = self.structural_similarity_index(uploaded_image, db_store_image)",
"db_store_image = cv2.cvtColor(db_store_image, cv2.COLOR_BGR2GRAY) mean_sq_error = self.mean_squared_error(uploaded_image, db_store_image) ssim_index =",
"db_store_image): ssim_index = ssim(uploaded_image, db_store_image) return ssim_index def convert_and_resize_compare(self, uploaded_image,",
"'jpeg'] image_store_hash = dict() db_ops = database_migrations() class preprocess: def",
"print(self.image_store) return self.image_store def generate_hash(self): images_in_db = self.request_list_of_images_in_db() print(images_in_db) for",
"\"similar\" # the two images are return err def structural_similarity_index(self,",
"img_type) images = db_ops.request_matches(\"image_store\") print(\"list from database\" + str(images)) self.image_store.clear()",
"Error' between the two images is the # sum of",
"/= float(uploaded_image.shape[0] * uploaded_image.shape[1]) # return the MSE, the lower",
"= cv2.imread(db_store_image) uploaded_image = cv2.resize() db_store_image = cv2.resize() uploaded_image =",
"# return the MSE, the lower the error, the more",
"images must have the same dimension err = np.sum((uploaded_image.astype(\"float\") -",
"dhash.dhash_row_col(image) img_hash = dhash.format_hex(row, col) values = img_hash, img[\"image_id\"] db_ops.image_store_migrations()",
"convert_and_resize_compare(self, uploaded_image, db_store_image): # TODO: make structural similarity and mean",
"import structural_similarity as ssim from glob import glob from PIL",
"the two images must have the same dimension err =",
"img[\"image_id\"] db_ops.image_store_migrations() print(values) db_ops.insert_operations(\"image_store_hash\", values) class compare_files: def __init__(self): #",
"print(\"list from database\" + str(images)) self.image_store.clear() self.images_list.clear() for img in",
"ALLOWED_EXTENSIONS: images = glob(IMAGE_FOLDER + \"/*\" + img_type) for img",
"= db_ops.conditional_request_matches( \"image_store\", img[2], \"image_name\", \"image_id\") self.images_list[\"image_name\"] = img_name[0][0] print(\"Check",
"(uploaded_hash[i] != db_store_hash[i]): count += 1 i += 1 return",
"images = glob(IMAGE_FOLDER + \"/*\" + img_type) images = db_ops.request_matches(\"image_store\")"
] |
[
"language you are learning\" f\" (for example, if you are",
"@hf.is_admin() async def swap(self, ctx): \"\"\"Swaps JHO/JHO2's names and positions",
"chosen to enable ultra hardcore mode. It works the same",
"if self.bot.db['ultraHardcore']['users'][str(ctx.author.id)][0]: await ctx.send(f\"{ctx.author.mention} is currently using ultra hardcore mode.",
"and can't explain it\"\"\" if ctx.guild.id != 189571157446492161: return if",
"= ctx.guild.get_role(486851965121331200) config = self.bot.db['ultraHardcore']['users'] if str(ctx.author.id) in config: #",
"# if not enabled user = config[str(ctx.author.id)] if user[0]: await",
"a leaderboard of who has had UHC on for the",
"they seem to have left the server') await ctx.send(string +",
"i[1][2]] for i in list(time_dict.items())] # to_sort: [['243703909166612480', True, 162],",
"self.bot = bot async def cog_check(self, ctx): if not ctx.guild:",
"are ' guild = self.bot.get_guild(189571157446492161) members = [] config =",
"# if you specified someone else's ID, then remove UHC",
"not be undone unless you ask a mod to remove",
"sorted_dict = sorted(to_sort, key=lambda x: x[2], reverse=True) leaderboard = f\"The",
"189571157446492161: return time_dict = deepcopy(self.bot.db['ultraHardcore']['users']) for i in time_dict: if",
"list(self, ctx): \"\"\"Lists the people currently in ultra hardcore mode\"\"\"",
"bot): self.bot = bot async def cog_check(self, ctx): if not",
"return await ctx.send(f\"This is ultra hardcore mode. It means you",
"is not None: # in case a member leaves members.append(member.name)",
"to undo this.\") @ultrahardcore.command() async def list(self, ctx): \"\"\"Lists the",
"are using it and can't explain it\"\"\" if ctx.guild.id !=",
"want welcome messages to go to JHO2\"\"\" jpJHO = self.bot.get_channel(189571157446492161)",
"or (not user): continue if user.nick: name_str = f\"{user.mention} ({user.name})\"",
"member_id in config.copy(): if config[member_id][0]: member = guild.get_member(int(member_id)) if member",
"@ultrahardcore.command() async def explanation(self, ctx): \"\"\"Explains ultra hardcore mode for",
"for i in list(time_dict.items())] # to_sort: [['243703909166612480', True, 162], ['219617844973797376',",
"ctx.send(f\"Added {ctx.channel.name} to list of ignored channels for UHC\") else:",
"for if we temporarily want welcome messages to go to",
"in the lists, for if we temporarily want welcome messages",
"UHC on for the longest\"\"\" if ctx.guild.id != 189571157446492161: return",
"UHC mode.\") return await hf.dump_json() try: await member.remove_roles(role) except discord.errors.Forbidden:",
"i[1]) or (not user): continue if user.nick: name_str = f\"{user.mention}",
"must speak in the language you are learning\" f\" (for",
"ctx.send(f\"Removed {ctx.channel.name} from list of ignored channels for UHC\") except",
"!= 189571157446492161: # return role = ctx.guild.get_role(486851965121331200) config = self.bot.db['ultraHardcore']['users']",
"x[2], reverse=True) leaderboard = f\"The number of days each user",
"themselves.\") return await ctx.send(f\"{ctx.author.mention} is currently NOT using hardcore mode,",
"for {member.name}') else: await ctx.send(\"You can not remove UHC. Ask",
"[False, '2018/11/30', 122]), ...} to_sort = [[i[0], i[1][0], i[1][2]] for",
"the same as \" \"normal hardcore mode except that you",
"enabled user = config[str(ctx.author.id)] if user[0]: await ctx.send(\"You're already in",
"...] sorted_dict = sorted(to_sort, key=lambda x: x[2], reverse=True) leaderboard =",
"hardcore role\") await ctx.send(f'Undid ultra hardcore mode for {member.name}') else:",
"if i[1]: leaderboard += f\"**{i[2]}: {name_str}**\\n\" else: leaderboard += f\"{i[2]}:",
"continue if user.nick: name_str = f\"{user.mention} ({user.name})\" else: name_str =",
"list of ignored channels for UHC\") except KeyError: config['ignore'] =",
"x: x[2], reverse=True) leaderboard = f\"The number of days each",
"UHC enabled \" \\ f\"(Bold = This user currently has",
"(not user): continue if user.nick: name_str = f\"{user.mention} ({user.name})\" else:",
"currently NOT using hardcore mode, so I don't know why",
"for UHC\") else: config['ignore'].remove(ctx.channel.id) await ctx.send(f\"Removed {ctx.channel.name} from list of",
"ctx.invoke(self.explanation) return await ctx.send(f\"This is ultra hardcore mode. It means",
"await ctx.send(\"I couldn't add the ultra hardcore role\") await ctx.send(f\"{ctx.author.name}",
"to have left the server') await ctx.send(string + ', '.join(members))",
"reverse=True) leaderboard = f\"The number of days each user has",
"[[i[0], i[1][0], i[1][2]] for i in list(time_dict.items())] # to_sort: [['243703909166612480',",
"= os.path.dirname(os.path.dirname(os.path.realpath(__file__))).replace('\\\\', '/') class Jpserv(commands.Cog): \"\"\"Modules unique for the Japanese",
"left the server') await ctx.send(string + ', '.join(members)) @ultrahardcore.command() async",
"@ultrahardcore.command(aliases=['enable']) async def on(self, ctx): \"\"\"Enables UHC\"\"\" if ctx.guild.id !=",
"leaderboard = f\"The number of days each user has had",
"hardcore mode right now are ' guild = self.bot.get_guild(189571157446492161) members",
"name_str = f\"{user.name}\" if i[1]: leaderboard += f\"**{i[2]}: {name_str}**\\n\" else:",
"i[1][0], i[1][2]] for i in list(time_dict.items())] # to_sort: [['243703909166612480', True,",
"= ctx.guild.get_role(486851965121331200) config = self.bot.db['ultraHardcore']['users'] if member: # if you",
"ctx.author.id != member.id: if str(member.id) in config: if config[str(member.id)][0]: config[str(member.id)][0]",
"what.\") @ultrahardcore.command(aliases=['lb']) async def leaderboard(self, ctx): \"\"\"Shows a leaderboard of",
"else: config['ignore'].remove(ctx.channel.id) await ctx.send(f\"Removed {ctx.channel.name} from list of ignored channels",
"ctx.send(embed=emb) @ultrahardcore.command() @hf.is_admin() async def ignore(self, ctx): \"\"\"Ignores a channel",
"to list of ignored channels for UHC\") await hf.dump_json() def",
"In this mode, they can't\" f\" speak their native language,",
"@ultrahardcore.command(aliases=['lb']) async def leaderboard(self, ctx): \"\"\"Shows a leaderboard of who",
"async def cog_check(self, ctx): if not ctx.guild: return return ctx.guild.id",
"= self.bot.get_guild(189571157446492161) members = [] config = self.bot.db['ultraHardcore']['users'] for member_id",
"+= (datetime.today() - datetime.strptime(time_dict[i][1], \"%Y/%m/%d\")).days # {('243703909166612480', [True, '2019/02/14', 124]),",
"if (i[2] < 10 and not i[1]) or (not user):",
"else's ID, then remove UHC from them member = await",
"using hardcore mode, so I don't know why \" f\"they're",
"{ctx.channel.name} to list of ignored channels for UHC\") else: config['ignore'].remove(ctx.channel.id)",
"\"\"\"Irreversible hardcore mode. Must talk to an admin to have",
"async def list(self, ctx): \"\"\"Lists the people currently in ultra",
"ctx): \"\"\"Shows a leaderboard of who has had UHC on",
"are only useable on Japanese server or my testing server",
"not i[1]) or (not user): continue if user.nick: name_str =",
"not member: return if hf.admin_check(ctx) and ctx.author.id != member.id: if",
"role = ctx.guild.get_role(486851965121331200) config = self.bot.db['ultraHardcore']['users'] if str(ctx.author.id) in config:",
"undone unless you ask a mod to remove it for",
"+= f\"{i[2]}: {name_str}\\n\" emb = discord.Embed(title=\"UHC Leaderboard\", description=leaderboard, color=discord.Color(int('ff5500', 16)))",
"ultra hardcore mode means a user can't speak \" f\"any",
"hardcore mode for {member.name}') else: await ctx.send(\"You can not remove",
"UHC enabled)\\n\\n\" for i in sorted_dict: user = ctx.guild.get_member(int(i[0])) if",
"'2018/11/30', 122]), ...} to_sort = [[i[0], i[1][0], i[1][2]] for i",
"to remove it for you. \\n\\n\" f\"To enable ultra hardcore",
"', '.join(members)) @ultrahardcore.command() async def explanation(self, ctx): \"\"\"Explains ultra hardcore",
"config[str(member.id)][0] = False else: await ctx.send(\"That user is not in",
"of who has had UHC on for the longest\"\"\" if",
"datetime, timedelta from .utils import helper_functions as hf from copy",
"are learning\" f\" (for example, if you are learning Japanese,",
"don't know why \" f\"they're trying to use this command.",
"f\" This can not be undone unless you ask a",
"on(self, ctx): \"\"\"Enables UHC\"\"\" if ctx.guild.id != 189571157446492161: return role",
"in config['ignore']: config['ignore'].append(ctx.channel.id) await ctx.send(f\"Added {ctx.channel.name} to list of ignored",
"the lists, for if we temporarily want welcome messages to",
"welcome messages to go to JHO2\"\"\" jpJHO = self.bot.get_channel(189571157446492161) jpJHO2",
"mode. It works the same as \" \"normal hardcore mode",
"these commands are only useable on Japanese server or my",
"= 'The members in ultra hardcore mode right now are",
"189571157446492161: return if str(ctx.author.id) in self.bot.db['ultraHardcore']['users']: if self.bot.db['ultraHardcore']['users'][str(ctx.author.id)][0]: await ctx.send(f\"{ctx.author.mention}",
"async def explanation(self, ctx): \"\"\"Explains ultra hardcore mode for those",
"if config[str(member.id)][0]: config[str(member.id)][0] = False else: await ctx.send(\"That user is",
"f\"The number of days each user has had UHC enabled",
"member=None): \"\"\"Irreversible hardcore mode. Must talk to an admin to",
"server') await ctx.send(string + ', '.join(members)) @ultrahardcore.command() async def explanation(self,",
"couldn't remove the ultra hardcore role\") await ctx.send(f'Undid ultra hardcore",
"# to_sort: [['243703909166612480', True, 162], ['219617844973797376', False, 122], ...] sorted_dict",
"ctx.send(f\"{ctx.author.name} has chosen to enable ultra hardcore mode. It works",
"who has had UHC on for the longest\"\"\" if ctx.guild.id",
"enable ultra hardcore mode. It works the same as \"",
"@commands.group(invoke_without_command=True, aliases=['uhc']) async def ultrahardcore(self, ctx, *, member=None): \"\"\"Irreversible hardcore",
"hf.admin_check(ctx) and ctx.author.id != member.id: if str(member.id) in config: if",
"return else: await ctx.send(\"That user is not in UHC mode.\")",
"you. \\n\\n\" f\"To enable ultra hardcore mode, type `;uhc on`",
"122], ...] sorted_dict = sorted(to_sort, key=lambda x: x[2], reverse=True) leaderboard",
"ignore(self, ctx): \"\"\"Ignores a channel for UHC\"\"\" if ctx.guild.id !=",
"or `;uhc enable`. \") @ultrahardcore.command(aliases=['enable']) async def on(self, ctx): \"\"\"Enables",
"currently in ultra hardcore mode\"\"\" if ctx.guild.id != 189571157446492161: return",
"not enabled user = config[str(ctx.author.id)] if user[0]: await ctx.send(\"You're already",
"hf.member_converter(ctx, member) if not member: return if hf.admin_check(ctx) and ctx.author.id",
"to list of ignored channels for UHC\") else: config['ignore'].remove(ctx.channel.id) await",
"be deleted).\" f\" This can not be undone unless you",
"list of ignored channels for UHC\") await hf.dump_json() def setup(bot):",
"leaves members.append(member.name) else: del config[member_id] await ctx.send(f'Removed <@{member_id}> from the",
"self.bot.get_channel(189571157446492161) jpJHO2 = self.bot.get_channel(326263874770829313) if jpJHO.position == 4: await jpJHO.edit(position=5,",
"type `;uhc on` or `;uhc enable`. \") @ultrahardcore.command(aliases=['enable']) async def",
"emb = discord.Embed(title=\"UHC Leaderboard\", description=leaderboard, color=discord.Color(int('ff5500', 16))) await ctx.send(embed=emb) @ultrahardcore.command()",
"the server') await ctx.send(string + ', '.join(members)) @ultrahardcore.command() async def",
"Leaderboard\", description=leaderboard, color=discord.Color(int('ff5500', 16))) await ctx.send(embed=emb) @ultrahardcore.command() @hf.is_admin() async def",
"await ctx.send(f\"Added {ctx.channel.name} to list of ignored channels for UHC\")",
"def on(self, ctx): \"\"\"Enables UHC\"\"\" if ctx.guild.id != 189571157446492161: return",
"not in UHC\") return else: await ctx.send(\"That user is not",
"await ctx.send(f\"This is ultra hardcore mode. It means you must",
"means a user can't speak \" f\"any English, and can't",
"return if hf.admin_check(ctx) and ctx.author.id != member.id: if str(member.id) in",
"= f\"{user.mention} ({user.name})\" else: name_str = f\"{user.name}\" if i[1]: leaderboard",
"hardcore mode. In this mode, they can't\" f\" speak their",
"change \" \"anything. Talk to a mod to undo this.\")",
"f\"{user.mention} ({user.name})\" else: name_str = f\"{user.name}\" if i[1]: leaderboard +=",
"ctx): \"\"\"Ignores a channel for UHC\"\"\" if ctx.guild.id != 189571157446492161:",
"discord.Embed(title=\"UHC Leaderboard\", description=leaderboard, color=discord.Color(int('ff5500', 16))) await ctx.send(embed=emb) @ultrahardcore.command() @hf.is_admin() async",
"import discord from discord.ext import commands import os import json",
"you are learning Japanese, any messages in English will be",
"try: await ctx.author.add_roles(role) except discord.errors.Forbidden: await ctx.send(\"I couldn't add the",
"date, datetime, timedelta from .utils import helper_functions as hf from",
"import helper_functions as hf from copy import deepcopy dir_path =",
"ultrahardcore(self, ctx, *, member=None): \"\"\"Irreversible hardcore mode. Must talk to",
"if str(member.id) in config: if config[str(member.id)][0]: config[str(member.id)][0] = False else:",
"except that you can't undo it and asterisks don't change",
"has had UHC enabled \" \\ f\"(Bold = This user",
"config = self.bot.db['ultraHardcore']['users'] if member: # if you specified someone",
"ctx.guild.get_role(486851965121331200) config = self.bot.db['ultraHardcore']['users'] if member: # if you specified",
"already in ultra hardcore mode.\") return else: user[0] = True",
"the Japanese server\"\"\" def __init__(self, bot): self.bot = bot async",
"config: if config[str(member.id)][0]: config[str(member.id)][0] = False else: await ctx.send(\"That user",
"leaderboard += f\"**{i[2]}: {name_str}**\\n\" else: leaderboard += f\"{i[2]}: {name_str}\\n\" emb",
"this.\") @ultrahardcore.command() async def list(self, ctx): \"\"\"Lists the people currently",
"deepcopy dir_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))).replace('\\\\', '/') class Jpserv(commands.Cog): \"\"\"Modules unique for",
"await hf.dump_json() try: await ctx.author.add_roles(role) except discord.errors.Forbidden: await ctx.send(\"I couldn't",
"'The members in ultra hardcore mode right now are '",
"this undone.\"\"\" # if ctx.guild.id != 189571157446492161: # return role",
"__init__(self, bot): self.bot = bot async def cog_check(self, ctx): if",
"only useable on Japanese server or my testing server @commands.command()",
"ctx.send(f'Removed <@{member_id}> from the list, as they seem to have",
"user.nick: name_str = f\"{user.mention} ({user.name})\" else: name_str = f\"{user.name}\" if",
"if ctx.guild.id != 189571157446492161: # return role = ctx.guild.get_role(486851965121331200) config",
"True, 162], ['219617844973797376', False, 122], ...] sorted_dict = sorted(to_sort, key=lambda",
"explain it\"\"\" if ctx.guild.id != 189571157446492161: return if str(ctx.author.id) in",
"else: config[str(ctx.author.id)] = [True, date.today().strftime(\"%Y/%m/%d\"), 0] await hf.dump_json() try: await",
"channel for UHC\"\"\" if ctx.guild.id != 189571157446492161: return config =",
"try: if ctx.channel.id not in config['ignore']: config['ignore'].append(ctx.channel.id) await ctx.send(f\"Added {ctx.channel.name}",
"who are using it and can't explain it\"\"\" if ctx.guild.id",
"= guild.get_member(int(member_id)) if member is not None: # in case",
"sorted(to_sort, key=lambda x: x[2], reverse=True) leaderboard = f\"The number of",
"self.bot.db['ultraHardcore']['users'] if member: # if you specified someone else's ID,",
"now are ' guild = self.bot.get_guild(189571157446492161) members = [] config",
"command. But, ultra hardcore mode means a user can't speak",
"JHO/JHO2's names and positions in the lists, for if we",
"else: await ctx.send(\"That user is not in UHC mode.\") return",
"if ctx.guild.id != 189571157446492161: return role = ctx.guild.get_role(486851965121331200) config =",
"same as \" \"normal hardcore mode except that you can't",
"@ultrahardcore.command() async def list(self, ctx): \"\"\"Lists the people currently in",
"members in ultra hardcore mode right now are ' guild",
"<@{member_id}> from the list, as they seem to have left",
"4: await jpJHO.edit(position=5, name='just_hanging_out_2') await jpJHO2.edit(position=4, name='just_hanging_out') else: await jpJHO.edit(position=4,",
"jpJHO2.edit(position=5, name='just_hanging_out_2') @commands.group(invoke_without_command=True, aliases=['uhc']) async def ultrahardcore(self, ctx, *, member=None):",
"name='just_hanging_out_2') @commands.group(invoke_without_command=True, aliases=['uhc']) async def ultrahardcore(self, ctx, *, member=None): \"\"\"Irreversible",
"\"normal hardcore mode except that you can't undo it and",
"mode themselves.\") return await ctx.send(f\"{ctx.author.mention} is currently NOT using hardcore",
"cannot undo this mode themselves.\") return await ctx.send(f\"{ctx.author.mention} is currently",
"return await ctx.send(f\"{ctx.author.mention} is currently NOT using hardcore mode, so",
"hardcore mode\"\"\" if ctx.guild.id != 189571157446492161: return string = 'The",
"await ctx.send(f\"{ctx.author.mention} is currently using ultra hardcore mode. In this",
"so I don't know why \" f\"they're trying to use",
"member: return if hf.admin_check(ctx) and ctx.author.id != member.id: if str(member.id)",
"= False else: await ctx.send(\"That user is not in UHC\")",
"and they also cannot undo this mode themselves.\") return await",
"also cannot undo this mode themselves.\") return await ctx.send(f\"{ctx.author.mention} is",
"config[member_id] await ctx.send(f'Removed <@{member_id}> from the list, as they seem",
"async def leaderboard(self, ctx): \"\"\"Shows a leaderboard of who has",
"\"\"\"Ignores a channel for UHC\"\"\" if ctx.guild.id != 189571157446492161: return",
"config[str(member.id)][0]: config[str(member.id)][0] = False else: await ctx.send(\"That user is not",
"await ctx.invoke(self.explanation) return await ctx.send(f\"This is ultra hardcore mode. It",
"['219617844973797376', False, 122], ...] sorted_dict = sorted(to_sort, key=lambda x: x[2],",
"Japanese server or my testing server @commands.command() @hf.is_admin() async def",
"else: if str(ctx.author.id) in config: if config[str(ctx.author.id)][0]: await ctx.invoke(self.explanation) return",
"in sorted_dict: user = ctx.guild.get_member(int(i[0])) if (i[2] < 10 and",
"def explanation(self, ctx): \"\"\"Explains ultra hardcore mode for those who",
"to_sort = [[i[0], i[1][0], i[1][2]] for i in list(time_dict.items())] #",
"hardcore mode for those who are using it and can't",
"mod to remove it for you. \\n\\n\" f\"To enable ultra",
"mode themselves no matter what.\") @ultrahardcore.command(aliases=['lb']) async def leaderboard(self, ctx):",
"is not in UHC mode.\") return await hf.dump_json() try: await",
"as they seem to have left the server') await ctx.send(string",
"# {('243703909166612480', [True, '2019/02/14', 124]), # ('219617844973797376', [False, '2018/11/30', 122]),",
"if config[member_id][0]: member = guild.get_member(int(member_id)) if member is not None:",
"hardcore mode except that you can't undo it and asterisks",
"in UHC mode.\") return await hf.dump_json() try: await member.remove_roles(role) except",
"user = config[str(ctx.author.id)] if user[0]: await ctx.send(\"You're already in ultra",
"user[0] = True else: config[str(ctx.author.id)] = [True, date.today().strftime(\"%Y/%m/%d\"), 0] await",
"add the ultra hardcore role\") await ctx.send(f\"{ctx.author.name} has chosen to",
"config.copy(): if config[member_id][0]: member = guild.get_member(int(member_id)) if member is not",
"speak \" f\"any English, and can't undo this mode themselves",
"admin to have this undone.\"\"\" # if ctx.guild.id != 189571157446492161:",
"ultra hardcore mode right now are ' guild = self.bot.get_guild(189571157446492161)",
"members.append(member.name) else: del config[member_id] await ctx.send(f'Removed <@{member_id}> from the list,",
"ctx.send(string + ', '.join(members)) @ultrahardcore.command() async def explanation(self, ctx): \"\"\"Explains",
"124]), # ('219617844973797376', [False, '2018/11/30', 122]), ...} to_sort = [[i[0],",
"you ask a mod to remove it for you. \\n\\n\"",
"False, 122], ...] sorted_dict = sorted(to_sort, key=lambda x: x[2], reverse=True)",
"you can't undo it and asterisks don't change \" \"anything.",
"UHC\") else: config['ignore'].remove(ctx.channel.id) await ctx.send(f\"Removed {ctx.channel.name} from list of ignored",
"if hf.admin_check(ctx) and ctx.author.id != member.id: if str(member.id) in config:",
"return time_dict = deepcopy(self.bot.db['ultraHardcore']['users']) for i in time_dict: if time_dict[i][0]:",
"member.id: if str(member.id) in config: if config[str(member.id)][0]: config[str(member.id)][0] = False",
"from the list, as they seem to have left the",
"their native language, and they also cannot undo this mode",
"or my testing server @commands.command() @hf.is_admin() async def swap(self, ctx):",
"`;uhc on` or `;uhc enable`. \") @ultrahardcore.command(aliases=['enable']) async def on(self,",
"jpJHO = self.bot.get_channel(189571157446492161) jpJHO2 = self.bot.get_channel(326263874770829313) if jpJHO.position == 4:",
"f\"{i[2]}: {name_str}\\n\" emb = discord.Embed(title=\"UHC Leaderboard\", description=leaderboard, color=discord.Color(int('ff5500', 16))) await",
"you.\") else: if str(ctx.author.id) in config: if config[str(ctx.author.id)][0]: await ctx.invoke(self.explanation)",
"ctx.guild.id != 189571157446492161: return role = ctx.guild.get_role(486851965121331200) config = self.bot.db['ultraHardcore']['users']",
"and asterisks don't change \" \"anything. Talk to a mod",
"role\") await ctx.send(f\"{ctx.author.name} has chosen to enable ultra hardcore mode.",
"jpJHO.position == 4: await jpJHO.edit(position=5, name='just_hanging_out_2') await jpJHO2.edit(position=4, name='just_hanging_out') else:",
"else: await jpJHO.edit(position=4, name='just_hanging_out') await jpJHO2.edit(position=5, name='just_hanging_out_2') @commands.group(invoke_without_command=True, aliases=['uhc']) async",
"if not enabled user = config[str(ctx.author.id)] if user[0]: await ctx.send(\"You're",
"you are learning\" f\" (for example, if you are learning",
"discord.ext import commands import os import json from datetime import",
"days each user has had UHC enabled \" \\ f\"(Bold",
"if ctx.guild.id != 189571157446492161: return if str(ctx.author.id) in self.bot.db['ultraHardcore']['users']: if",
"await ctx.send(\"You can not remove UHC. Ask a mod/admin to",
"!= member.id: if str(member.id) in config: if config[str(member.id)][0]: config[str(member.id)][0] =",
"!= 189571157446492161: return config = self.bot.db['ultraHardcore'] try: if ctx.channel.id not",
"or ctx.guild.id == 275146036178059265 # these commands are only useable",
"trying to use this command. But, ultra hardcore mode means",
"ignored channels for UHC\") else: config['ignore'].remove(ctx.channel.id) await ctx.send(f\"Removed {ctx.channel.name} from",
"Jpserv(commands.Cog): \"\"\"Modules unique for the Japanese server\"\"\" def __init__(self, bot):",
"162], ['219617844973797376', False, 122], ...] sorted_dict = sorted(to_sort, key=lambda x:",
"ultra hardcore mode.\") return else: user[0] = True else: config[str(ctx.author.id)]",
"them member = await hf.member_converter(ctx, member) if not member: return",
"f\" speak their native language, and they also cannot undo",
"f\"{user.name}\" if i[1]: leaderboard += f\"**{i[2]}: {name_str}**\\n\" else: leaderboard +=",
"enabled)\\n\\n\" for i in sorted_dict: user = ctx.guild.get_member(int(i[0])) if (i[2]",
"if not member: return if hf.admin_check(ctx) and ctx.author.id != member.id:",
"await ctx.send(\"I couldn't remove the ultra hardcore role\") await ctx.send(f'Undid",
"await ctx.send(f\"{ctx.author.name} has chosen to enable ultra hardcore mode. It",
"ctx.guild.id != 189571157446492161: # return role = ctx.guild.get_role(486851965121331200) config =",
"@commands.command() @hf.is_admin() async def swap(self, ctx): \"\"\"Swaps JHO/JHO2's names and",
"else: await ctx.send(\"You can not remove UHC. Ask a mod/admin",
"KeyError: config['ignore'] = [ctx.channel.id] await ctx.send(f\"Added {ctx.channel.name} to list of",
"right now are ' guild = self.bot.get_guild(189571157446492161) members = []",
"hardcore mode. Must talk to an admin to have this",
"async def on(self, ctx): \"\"\"Enables UHC\"\"\" if ctx.guild.id != 189571157446492161:",
"on Japanese server or my testing server @commands.command() @hf.is_admin() async",
"the ultra hardcore role\") await ctx.send(f'Undid ultra hardcore mode for",
"\"\"\"Lists the people currently in ultra hardcore mode\"\"\" if ctx.guild.id",
"189571157446492161: return role = ctx.guild.get_role(486851965121331200) config = self.bot.db['ultraHardcore']['users'] if str(ctx.author.id)",
"mode for {member.name}') else: await ctx.send(\"You can not remove UHC.",
"the language you are learning\" f\" (for example, if you",
"to help you.\") else: if str(ctx.author.id) in config: if config[str(ctx.author.id)][0]:",
"\"\"\"Shows a leaderboard of who has had UHC on for",
"ctx.guild.id != 189571157446492161: return config = self.bot.db['ultraHardcore'] try: if ctx.channel.id",
"hardcore mode. It means you must speak in the language",
"config['ignore'].append(ctx.channel.id) await ctx.send(f\"Added {ctx.channel.name} to list of ignored channels for",
"don't change \" \"anything. Talk to a mod to undo",
"ctx.send(\"You can not remove UHC. Ask a mod/admin to help",
"ctx.guild.id != 189571157446492161: return string = 'The members in ultra",
"\" \"anything. Talk to a mod to undo this.\") @ultrahardcore.command()",
"in config.copy(): if config[member_id][0]: member = guild.get_member(int(member_id)) if member is",
"English will be deleted).\" f\" This can not be undone",
"else: name_str = f\"{user.name}\" if i[1]: leaderboard += f\"**{i[2]}: {name_str}**\\n\"",
"== 4: await jpJHO.edit(position=5, name='just_hanging_out_2') await jpJHO2.edit(position=4, name='just_hanging_out') else: await",
"self.bot.db['ultraHardcore'] try: if ctx.channel.id not in config['ignore']: config['ignore'].append(ctx.channel.id) await ctx.send(f\"Added",
"= self.bot.db['ultraHardcore']['users'] if member: # if you specified someone else's",
"return config = self.bot.db['ultraHardcore'] try: if ctx.channel.id not in config['ignore']:",
"+= f\"**{i[2]}: {name_str}**\\n\" else: leaderboard += f\"{i[2]}: {name_str}\\n\" emb =",
"mode, type `;uhc on` or `;uhc enable`. \") @ultrahardcore.command(aliases=['enable']) async",
"\" f\"any English, and can't undo this mode themselves no",
"ctx): \"\"\"Enables UHC\"\"\" if ctx.guild.id != 189571157446492161: return role =",
"ultra hardcore mode. In this mode, they can't\" f\" speak",
"- datetime.strptime(time_dict[i][1], \"%Y/%m/%d\")).days # {('243703909166612480', [True, '2019/02/14', 124]), # ('219617844973797376',",
"ctx.send(f\"{ctx.author.mention} is currently NOT using hardcore mode, so I don't",
"leaderboard(self, ctx): \"\"\"Shows a leaderboard of who has had UHC",
".utils import helper_functions as hf from copy import deepcopy dir_path",
"ctx.guild.get_member(int(i[0])) if (i[2] < 10 and not i[1]) or (not",
"is ultra hardcore mode. It means you must speak in",
"names and positions in the lists, for if we temporarily",
"bot async def cog_check(self, ctx): if not ctx.guild: return return",
"remove it for you. \\n\\n\" f\"To enable ultra hardcore mode,",
"hardcore mode.\") return else: user[0] = True else: config[str(ctx.author.id)] =",
"= config[str(ctx.author.id)] if user[0]: await ctx.send(\"You're already in ultra hardcore",
"ctx, *, member=None): \"\"\"Irreversible hardcore mode. Must talk to an",
"list of ignored channels for UHC\") else: config['ignore'].remove(ctx.channel.id) await ctx.send(f\"Removed",
"discord.errors.Forbidden: await ctx.send(\"I couldn't remove the ultra hardcore role\") await",
"< 10 and not i[1]) or (not user): continue if",
"async def ignore(self, ctx): \"\"\"Ignores a channel for UHC\"\"\" if",
"ultra hardcore mode for {member.name}') else: await ctx.send(\"You can not",
"JHO2\"\"\" jpJHO = self.bot.get_channel(189571157446492161) jpJHO2 = self.bot.get_channel(326263874770829313) if jpJHO.position ==",
"mode. In this mode, they can't\" f\" speak their native",
"hardcore mode, so I don't know why \" f\"they're trying",
"await jpJHO2.edit(position=4, name='just_hanging_out') else: await jpJHO.edit(position=4, name='just_hanging_out') await jpJHO2.edit(position=5, name='just_hanging_out_2')",
"else: leaderboard += f\"{i[2]}: {name_str}\\n\" emb = discord.Embed(title=\"UHC Leaderboard\", description=leaderboard,",
"server\"\"\" def __init__(self, bot): self.bot = bot async def cog_check(self,",
"# return role = ctx.guild.get_role(486851965121331200) config = self.bot.db['ultraHardcore']['users'] if member:",
"try: await member.remove_roles(role) except discord.errors.Forbidden: await ctx.send(\"I couldn't remove the",
"await member.remove_roles(role) except discord.errors.Forbidden: await ctx.send(\"I couldn't remove the ultra",
"currently using ultra hardcore mode. In this mode, they can't\"",
"language, and they also cannot undo this mode themselves.\") return",
"cog_check(self, ctx): if not ctx.guild: return return ctx.guild.id == 189571157446492161",
"str(ctx.author.id) in self.bot.db['ultraHardcore']['users']: if self.bot.db['ultraHardcore']['users'][str(ctx.author.id)][0]: await ctx.send(f\"{ctx.author.mention} is currently using",
"ultra hardcore mode. It means you must speak in the",
"not in config['ignore']: config['ignore'].append(ctx.channel.id) await ctx.send(f\"Added {ctx.channel.name} to list of",
"I don't know why \" f\"they're trying to use this",
"number of days each user has had UHC enabled \"",
"if we temporarily want welcome messages to go to JHO2\"\"\"",
"my testing server @commands.command() @hf.is_admin() async def swap(self, ctx): \"\"\"Swaps",
"to an admin to have this undone.\"\"\" # if ctx.guild.id",
"leaderboard += f\"{i[2]}: {name_str}\\n\" emb = discord.Embed(title=\"UHC Leaderboard\", description=leaderboard, color=discord.Color(int('ff5500',",
"if you are learning Japanese, any messages in English will",
"is not in UHC\") return else: await ctx.send(\"That user is",
"of ignored channels for UHC\") except KeyError: config['ignore'] = [ctx.channel.id]",
"if jpJHO.position == 4: await jpJHO.edit(position=5, name='just_hanging_out_2') await jpJHO2.edit(position=4, name='just_hanging_out')",
"i[1]: leaderboard += f\"**{i[2]}: {name_str}**\\n\" else: leaderboard += f\"{i[2]}: {name_str}\\n\"",
"= await hf.member_converter(ctx, member) if not member: return if hf.admin_check(ctx)",
"timedelta from .utils import helper_functions as hf from copy import",
"time_dict = deepcopy(self.bot.db['ultraHardcore']['users']) for i in time_dict: if time_dict[i][0]: time_dict[i][2]",
"config[str(ctx.author.id)] = [True, date.today().strftime(\"%Y/%m/%d\"), 0] await hf.dump_json() try: await ctx.author.add_roles(role)",
"guild.get_member(int(member_id)) if member is not None: # in case a",
"i in time_dict: if time_dict[i][0]: time_dict[i][2] += (datetime.today() - datetime.strptime(time_dict[i][1],",
"275146036178059265 # these commands are only useable on Japanese server",
"this command. But, ultra hardcore mode means a user can't",
"= This user currently has UHC enabled)\\n\\n\" for i in",
"aliases=['uhc']) async def ultrahardcore(self, ctx, *, member=None): \"\"\"Irreversible hardcore mode.",
"the people currently in ultra hardcore mode\"\"\" if ctx.guild.id !=",
"on` or `;uhc enable`. \") @ultrahardcore.command(aliases=['enable']) async def on(self, ctx):",
"await hf.member_converter(ctx, member) if not member: return if hf.admin_check(ctx) and",
"+ ', '.join(members)) @ultrahardcore.command() async def explanation(self, ctx): \"\"\"Explains ultra",
"\"\"\"Modules unique for the Japanese server\"\"\" def __init__(self, bot): self.bot",
"ultra hardcore role\") await ctx.send(f\"{ctx.author.name} has chosen to enable ultra",
"*, member=None): \"\"\"Irreversible hardcore mode. Must talk to an admin",
"using it and can't explain it\"\"\" if ctx.guild.id != 189571157446492161:",
"discord.errors.Forbidden: await ctx.send(\"I couldn't add the ultra hardcore role\") await",
"mode, they can't\" f\" speak their native language, and they",
"UHC\"\"\" if ctx.guild.id != 189571157446492161: return config = self.bot.db['ultraHardcore'] try:",
"lists, for if we temporarily want welcome messages to go",
"learning Japanese, any messages in English will be deleted).\" f\"",
"that you can't undo it and asterisks don't change \"",
"= f\"The number of days each user has had UHC",
"This can not be undone unless you ask a mod",
"UHC. Ask a mod/admin to help you.\") else: if str(ctx.author.id)",
"enabled \" \\ f\"(Bold = This user currently has UHC",
"[True, date.today().strftime(\"%Y/%m/%d\"), 0] await hf.dump_json() try: await ctx.author.add_roles(role) except discord.errors.Forbidden:",
"in ultra hardcore mode\"\"\" if ctx.guild.id != 189571157446492161: return string",
"is currently using ultra hardcore mode. In this mode, they",
"ctx.send(\"I couldn't remove the ultra hardcore role\") await ctx.send(f'Undid ultra",
"UHC\") return else: await ctx.send(\"That user is not in UHC",
"from copy import deepcopy dir_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))).replace('\\\\', '/') class Jpserv(commands.Cog):",
"\"\"\"Explains ultra hardcore mode for those who are using it",
"the list, as they seem to have left the server')",
"ctx): if not ctx.guild: return return ctx.guild.id == 189571157446492161 or",
"import os import json from datetime import date, datetime, timedelta",
"i in list(time_dict.items())] # to_sort: [['243703909166612480', True, 162], ['219617844973797376', False,",
"ctx.channel.id not in config['ignore']: config['ignore'].append(ctx.channel.id) await ctx.send(f\"Added {ctx.channel.name} to list",
"will be deleted).\" f\" This can not be undone unless",
"mode. It means you must speak in the language you",
"any messages in English will be deleted).\" f\" This can",
"deleted).\" f\" This can not be undone unless you ask",
"commands are only useable on Japanese server or my testing",
"mode.\") return else: user[0] = True else: config[str(ctx.author.id)] = [True,",
"await hf.dump_json() try: await member.remove_roles(role) except discord.errors.Forbidden: await ctx.send(\"I couldn't",
"UHC\") except KeyError: config['ignore'] = [ctx.channel.id] await ctx.send(f\"Added {ctx.channel.name} to",
"Must talk to an admin to have this undone.\"\"\" #",
"people currently in ultra hardcore mode\"\"\" if ctx.guild.id != 189571157446492161:",
"ctx.send(\"I couldn't add the ultra hardcore role\") await ctx.send(f\"{ctx.author.name} has",
"mode except that you can't undo it and asterisks don't",
"talk to an admin to have this undone.\"\"\" # if",
"know why \" f\"they're trying to use this command. But,",
"await ctx.send(embed=emb) @ultrahardcore.command() @hf.is_admin() async def ignore(self, ctx): \"\"\"Ignores a",
"undo this.\") @ultrahardcore.command() async def list(self, ctx): \"\"\"Lists the people",
"a mod/admin to help you.\") else: if str(ctx.author.id) in config:",
"an admin to have this undone.\"\"\" # if ctx.guild.id !=",
"def ultrahardcore(self, ctx, *, member=None): \"\"\"Irreversible hardcore mode. Must talk",
"user can't speak \" f\"any English, and can't undo this",
"def list(self, ctx): \"\"\"Lists the people currently in ultra hardcore",
"English, and can't undo this mode themselves no matter what.\")",
"matter what.\") @ultrahardcore.command(aliases=['lb']) async def leaderboard(self, ctx): \"\"\"Shows a leaderboard",
"have this undone.\"\"\" # if ctx.guild.id != 189571157446492161: # return",
"hardcore role\") await ctx.send(f\"{ctx.author.name} has chosen to enable ultra hardcore",
"ctx.guild.id != 189571157446492161: return time_dict = deepcopy(self.bot.db['ultraHardcore']['users']) for i in",
"0] await hf.dump_json() try: await ctx.author.add_roles(role) except discord.errors.Forbidden: await ctx.send(\"I",
"has had UHC on for the longest\"\"\" if ctx.guild.id !=",
"ctx.guild.id == 275146036178059265 # these commands are only useable on",
"if time_dict[i][0]: time_dict[i][2] += (datetime.today() - datetime.strptime(time_dict[i][1], \"%Y/%m/%d\")).days # {('243703909166612480',",
"else: del config[member_id] await ctx.send(f'Removed <@{member_id}> from the list, as",
"# these commands are only useable on Japanese server or",
"native language, and they also cannot undo this mode themselves.\")",
"\" \\ f\"(Bold = This user currently has UHC enabled)\\n\\n\"",
"if user.nick: name_str = f\"{user.mention} ({user.name})\" else: name_str = f\"{user.name}\"",
"for i in sorted_dict: user = ctx.guild.get_member(int(i[0])) if (i[2] <",
"Ask a mod/admin to help you.\") else: if str(ctx.author.id) in",
"= True else: config[str(ctx.author.id)] = [True, date.today().strftime(\"%Y/%m/%d\"), 0] await hf.dump_json()",
"ctx.send(\"That user is not in UHC mode.\") return await hf.dump_json()",
"key=lambda x: x[2], reverse=True) leaderboard = f\"The number of days",
"False else: await ctx.send(\"That user is not in UHC\") return",
"str(member.id) in config: if config[str(member.id)][0]: config[str(member.id)][0] = False else: await",
"if ctx.guild.id != 189571157446492161: return string = 'The members in",
"to have this undone.\"\"\" # if ctx.guild.id != 189571157446492161: #",
"@ultrahardcore.command() @hf.is_admin() async def ignore(self, ctx): \"\"\"Ignores a channel for",
"positions in the lists, for if we temporarily want welcome",
"self.bot.db['ultraHardcore']['users'] if str(ctx.author.id) in config: # if not enabled user",
"to a mod to undo this.\") @ultrahardcore.command() async def list(self,",
"ID, then remove UHC from them member = await hf.member_converter(ctx,",
"# in case a member leaves members.append(member.name) else: del config[member_id]",
"ctx.send(\"You're already in ultra hardcore mode.\") return else: user[0] =",
"undo this mode themselves no matter what.\") @ultrahardcore.command(aliases=['lb']) async def",
"mode, so I don't know why \" f\"they're trying to",
"and can't undo this mode themselves no matter what.\") @ultrahardcore.command(aliases=['lb'])",
"name='just_hanging_out') await jpJHO2.edit(position=5, name='just_hanging_out_2') @commands.group(invoke_without_command=True, aliases=['uhc']) async def ultrahardcore(self, ctx,",
"undo it and asterisks don't change \" \"anything. Talk to",
"for the Japanese server\"\"\" def __init__(self, bot): self.bot = bot",
"Japanese server\"\"\" def __init__(self, bot): self.bot = bot async def",
"in case a member leaves members.append(member.name) else: del config[member_id] await",
"had UHC enabled \" \\ f\"(Bold = This user currently",
"had UHC on for the longest\"\"\" if ctx.guild.id != 189571157446492161:",
"ctx): \"\"\"Explains ultra hardcore mode for those who are using",
"config['ignore']: config['ignore'].append(ctx.channel.id) await ctx.send(f\"Added {ctx.channel.name} to list of ignored channels",
"i in sorted_dict: user = ctx.guild.get_member(int(i[0])) if (i[2] < 10",
"member.remove_roles(role) except discord.errors.Forbidden: await ctx.send(\"I couldn't remove the ultra hardcore",
"[['243703909166612480', True, 162], ['219617844973797376', False, 122], ...] sorted_dict = sorted(to_sort,",
"if str(ctx.author.id) in config: if config[str(ctx.author.id)][0]: await ctx.invoke(self.explanation) return await",
"[] config = self.bot.db['ultraHardcore']['users'] for member_id in config.copy(): if config[member_id][0]:",
"await ctx.send(f\"{ctx.author.mention} is currently NOT using hardcore mode, so I",
"189571157446492161 or ctx.guild.id == 275146036178059265 # these commands are only",
"ctx.guild.id != 189571157446492161: return if str(ctx.author.id) in self.bot.db['ultraHardcore']['users']: if self.bot.db['ultraHardcore']['users'][str(ctx.author.id)][0]:",
"can't undo this mode themselves no matter what.\") @ultrahardcore.command(aliases=['lb']) async",
"member = guild.get_member(int(member_id)) if member is not None: # in",
"discord from discord.ext import commands import os import json from",
"explanation(self, ctx): \"\"\"Explains ultra hardcore mode for those who are",
"It means you must speak in the language you are",
"...} to_sort = [[i[0], i[1][0], i[1][2]] for i in list(time_dict.items())]",
"can not remove UHC. Ask a mod/admin to help you.\")",
"return ctx.guild.id == 189571157446492161 or ctx.guild.id == 275146036178059265 # these",
"in time_dict: if time_dict[i][0]: time_dict[i][2] += (datetime.today() - datetime.strptime(time_dict[i][1], \"%Y/%m/%d\")).days",
"has UHC enabled)\\n\\n\" for i in sorted_dict: user = ctx.guild.get_member(int(i[0]))",
"copy import deepcopy dir_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))).replace('\\\\', '/') class Jpserv(commands.Cog): \"\"\"Modules",
"config['ignore'].remove(ctx.channel.id) await ctx.send(f\"Removed {ctx.channel.name} from list of ignored channels for",
"os import json from datetime import date, datetime, timedelta from",
"await ctx.send(f'Undid ultra hardcore mode for {member.name}') else: await ctx.send(\"You",
"user is not in UHC\") return else: await ctx.send(\"That user",
"mod to undo this.\") @ultrahardcore.command() async def list(self, ctx): \"\"\"Lists",
"\"%Y/%m/%d\")).days # {('243703909166612480', [True, '2019/02/14', 124]), # ('219617844973797376', [False, '2018/11/30',",
"\" \"normal hardcore mode except that you can't undo it",
"can't\" f\" speak their native language, and they also cannot",
"f\"To enable ultra hardcore mode, type `;uhc on` or `;uhc",
"someone else's ID, then remove UHC from them member =",
"speak their native language, and they also cannot undo this",
"for member_id in config.copy(): if config[member_id][0]: member = guild.get_member(int(member_id)) if",
"= f\"{user.name}\" if i[1]: leaderboard += f\"**{i[2]}: {name_str}**\\n\" else: leaderboard",
"!= 189571157446492161: return string = 'The members in ultra hardcore",
"def leaderboard(self, ctx): \"\"\"Shows a leaderboard of who has had",
"except discord.errors.Forbidden: await ctx.send(\"I couldn't remove the ultra hardcore role\")",
"ctx.send(f\"{ctx.author.mention} is currently using ultra hardcore mode. In this mode,",
"'2019/02/14', 124]), # ('219617844973797376', [False, '2018/11/30', 122]), ...} to_sort =",
"time_dict[i][0]: time_dict[i][2] += (datetime.today() - datetime.strptime(time_dict[i][1], \"%Y/%m/%d\")).days # {('243703909166612480', [True,",
"config: # if not enabled user = config[str(ctx.author.id)] if user[0]:",
"@hf.is_admin() async def ignore(self, ctx): \"\"\"Ignores a channel for UHC\"\"\"",
"== 189571157446492161 or ctx.guild.id == 275146036178059265 # these commands are",
"a mod to remove it for you. \\n\\n\" f\"To enable",
"return if str(ctx.author.id) in self.bot.db['ultraHardcore']['users']: if self.bot.db['ultraHardcore']['users'][str(ctx.author.id)][0]: await ctx.send(f\"{ctx.author.mention} is",
"using ultra hardcore mode. In this mode, they can't\" f\"",
"return else: user[0] = True else: config[str(ctx.author.id)] = [True, date.today().strftime(\"%Y/%m/%d\"),",
"mode means a user can't speak \" f\"any English, and",
"jpJHO2.edit(position=4, name='just_hanging_out') else: await jpJHO.edit(position=4, name='just_hanging_out') await jpJHO2.edit(position=5, name='just_hanging_out_2') @commands.group(invoke_without_command=True,",
"(i[2] < 10 and not i[1]) or (not user): continue",
"= self.bot.get_channel(326263874770829313) if jpJHO.position == 4: await jpJHO.edit(position=5, name='just_hanging_out_2') await",
"if config[str(ctx.author.id)][0]: await ctx.invoke(self.explanation) return await ctx.send(f\"This is ultra hardcore",
"os.path.dirname(os.path.dirname(os.path.realpath(__file__))).replace('\\\\', '/') class Jpserv(commands.Cog): \"\"\"Modules unique for the Japanese server\"\"\"",
"name='just_hanging_out_2') await jpJHO2.edit(position=4, name='just_hanging_out') else: await jpJHO.edit(position=4, name='just_hanging_out') await jpJHO2.edit(position=5,",
"for i in time_dict: if time_dict[i][0]: time_dict[i][2] += (datetime.today() -",
"= [[i[0], i[1][0], i[1][2]] for i in list(time_dict.items())] # to_sort:",
"you must speak in the language you are learning\" f\"",
"await ctx.send(\"That user is not in UHC mode.\") return await",
"except KeyError: config['ignore'] = [ctx.channel.id] await ctx.send(f\"Added {ctx.channel.name} to list",
"enable`. \") @ultrahardcore.command(aliases=['enable']) async def on(self, ctx): \"\"\"Enables UHC\"\"\" if",
"from .utils import helper_functions as hf from copy import deepcopy",
"!= 189571157446492161: return role = ctx.guild.get_role(486851965121331200) config = self.bot.db['ultraHardcore']['users'] if",
"datetime import date, datetime, timedelta from .utils import helper_functions as",
"currently has UHC enabled)\\n\\n\" for i in sorted_dict: user =",
"unique for the Japanese server\"\"\" def __init__(self, bot): self.bot =",
"in config: if config[str(ctx.author.id)][0]: await ctx.invoke(self.explanation) return await ctx.send(f\"This is",
"if ctx.guild.id != 189571157446492161: return config = self.bot.db['ultraHardcore'] try: if",
"no matter what.\") @ultrahardcore.command(aliases=['lb']) async def leaderboard(self, ctx): \"\"\"Shows a",
"member: # if you specified someone else's ID, then remove",
"use this command. But, ultra hardcore mode means a user",
"if ctx.channel.id not in config['ignore']: config['ignore'].append(ctx.channel.id) await ctx.send(f\"Added {ctx.channel.name} to",
"helper_functions as hf from copy import deepcopy dir_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))).replace('\\\\',",
"str(ctx.author.id) in config: # if not enabled user = config[str(ctx.author.id)]",
"string = 'The members in ultra hardcore mode right now",
"go to JHO2\"\"\" jpJHO = self.bot.get_channel(189571157446492161) jpJHO2 = self.bot.get_channel(326263874770829313) if",
"can't speak \" f\"any English, and can't undo this mode",
"10 and not i[1]) or (not user): continue if user.nick:",
"messages to go to JHO2\"\"\" jpJHO = self.bot.get_channel(189571157446492161) jpJHO2 =",
"works the same as \" \"normal hardcore mode except that",
"role\") await ctx.send(f'Undid ultra hardcore mode for {member.name}') else: await",
"mod/admin to help you.\") else: if str(ctx.author.id) in config: if",
"the longest\"\"\" if ctx.guild.id != 189571157446492161: return time_dict = deepcopy(self.bot.db['ultraHardcore']['users'])",
"Japanese, any messages in English will be deleted).\" f\" This",
"NOT using hardcore mode, so I don't know why \"",
"channels for UHC\") else: config['ignore'].remove(ctx.channel.id) await ctx.send(f\"Removed {ctx.channel.name} from list",
"ultra hardcore mode, type `;uhc on` or `;uhc enable`. \")",
"== 275146036178059265 # these commands are only useable on Japanese",
"testing server @commands.command() @hf.is_admin() async def swap(self, ctx): \"\"\"Swaps JHO/JHO2's",
"mode.\") return await hf.dump_json() try: await member.remove_roles(role) except discord.errors.Forbidden: await",
"to JHO2\"\"\" jpJHO = self.bot.get_channel(189571157446492161) jpJHO2 = self.bot.get_channel(326263874770829313) if jpJHO.position",
"those who are using it and can't explain it\"\"\" if",
"This user currently has UHC enabled)\\n\\n\" for i in sorted_dict:",
"ctx): \"\"\"Swaps JHO/JHO2's names and positions in the lists, for",
"self.bot.db['ultraHardcore']['users'] for member_id in config.copy(): if config[member_id][0]: member = guild.get_member(int(member_id))",
"speak in the language you are learning\" f\" (for example,",
"import deepcopy dir_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))).replace('\\\\', '/') class Jpserv(commands.Cog): \"\"\"Modules unique",
"ctx.send(f'Undid ultra hardcore mode for {member.name}') else: await ctx.send(\"You can",
"this mode themselves.\") return await ctx.send(f\"{ctx.author.mention} is currently NOT using",
"to use this command. But, ultra hardcore mode means a",
"from datetime import date, datetime, timedelta from .utils import helper_functions",
"remove UHC. Ask a mod/admin to help you.\") else: if",
"{name_str}\\n\" emb = discord.Embed(title=\"UHC Leaderboard\", description=leaderboard, color=discord.Color(int('ff5500', 16))) await ctx.send(embed=emb)",
"useable on Japanese server or my testing server @commands.command() @hf.is_admin()",
"deepcopy(self.bot.db['ultraHardcore']['users']) for i in time_dict: if time_dict[i][0]: time_dict[i][2] += (datetime.today()",
"\\ f\"(Bold = This user currently has UHC enabled)\\n\\n\" for",
"= deepcopy(self.bot.db['ultraHardcore']['users']) for i in time_dict: if time_dict[i][0]: time_dict[i][2] +=",
"to enable ultra hardcore mode. It works the same as",
"f\" (for example, if you are learning Japanese, any messages",
"remove UHC from them member = await hf.member_converter(ctx, member) if",
"commands import os import json from datetime import date, datetime,",
"we temporarily want welcome messages to go to JHO2\"\"\" jpJHO",
"return await hf.dump_json() try: await member.remove_roles(role) except discord.errors.Forbidden: await ctx.send(\"I",
"await jpJHO2.edit(position=5, name='just_hanging_out_2') @commands.group(invoke_without_command=True, aliases=['uhc']) async def ultrahardcore(self, ctx, *,",
"ctx.send(f\"This is ultra hardcore mode. It means you must speak",
"(for example, if you are learning Japanese, any messages in",
"specified someone else's ID, then remove UHC from them member",
"{ctx.channel.name} from list of ignored channels for UHC\") except KeyError:",
"messages in English will be deleted).\" f\" This can not",
"import json from datetime import date, datetime, timedelta from .utils",
"return role = ctx.guild.get_role(486851965121331200) config = self.bot.db['ultraHardcore']['users'] if str(ctx.author.id) in",
"are learning Japanese, any messages in English will be deleted).\"",
"ultra hardcore mode. It works the same as \" \"normal",
"{ctx.channel.name} to list of ignored channels for UHC\") await hf.dump_json()",
"and ctx.author.id != member.id: if str(member.id) in config: if config[str(member.id)][0]:",
"config = self.bot.db['ultraHardcore']['users'] for member_id in config.copy(): if config[member_id][0]: member",
"self.bot.db['ultraHardcore']['users'][str(ctx.author.id)][0]: await ctx.send(f\"{ctx.author.mention} is currently using ultra hardcore mode. In",
"mode right now are ' guild = self.bot.get_guild(189571157446492161) members =",
"= self.bot.db['ultraHardcore']['users'] for member_id in config.copy(): if config[member_id][0]: member =",
"else: await ctx.send(\"That user is not in UHC\") return else:",
"a mod to undo this.\") @ultrahardcore.command() async def list(self, ctx):",
"a user can't speak \" f\"any English, and can't undo",
"member leaves members.append(member.name) else: del config[member_id] await ctx.send(f'Removed <@{member_id}> from",
"189571157446492161: return config = self.bot.db['ultraHardcore'] try: if ctx.channel.id not in",
"temporarily want welcome messages to go to JHO2\"\"\" jpJHO =",
"it and can't explain it\"\"\" if ctx.guild.id != 189571157446492161: return",
"if not ctx.guild: return return ctx.guild.id == 189571157446492161 or ctx.guild.id",
"a channel for UHC\"\"\" if ctx.guild.id != 189571157446492161: return config",
"\"\"\"Enables UHC\"\"\" if ctx.guild.id != 189571157446492161: return role = ctx.guild.get_role(486851965121331200)",
"return return ctx.guild.id == 189571157446492161 or ctx.guild.id == 275146036178059265 #",
"in ultra hardcore mode.\") return else: user[0] = True else:",
"class Jpserv(commands.Cog): \"\"\"Modules unique for the Japanese server\"\"\" def __init__(self,",
"if str(ctx.author.id) in config: # if not enabled user =",
"It works the same as \" \"normal hardcore mode except",
"for the longest\"\"\" if ctx.guild.id != 189571157446492161: return time_dict =",
"server @commands.command() @hf.is_admin() async def swap(self, ctx): \"\"\"Swaps JHO/JHO2's names",
"if member is not None: # in case a member",
"mode. Must talk to an admin to have this undone.\"\"\"",
"swap(self, ctx): \"\"\"Swaps JHO/JHO2's names and positions in the lists,",
"UHC\"\"\" if ctx.guild.id != 189571157446492161: return role = ctx.guild.get_role(486851965121331200) config",
"= [True, date.today().strftime(\"%Y/%m/%d\"), 0] await hf.dump_json() try: await ctx.author.add_roles(role) except",
"ultra hardcore mode for those who are using it and",
"of ignored channels for UHC\") else: config['ignore'].remove(ctx.channel.id) await ctx.send(f\"Removed {ctx.channel.name}",
"can not be undone unless you ask a mod to",
"config: if config[str(ctx.author.id)][0]: await ctx.invoke(self.explanation) return await ctx.send(f\"This is ultra",
"user): continue if user.nick: name_str = f\"{user.mention} ({user.name})\" else: name_str",
"they also cannot undo this mode themselves.\") return await ctx.send(f\"{ctx.author.mention}",
"f\"they're trying to use this command. But, ultra hardcore mode",
"user = ctx.guild.get_member(int(i[0])) if (i[2] < 10 and not i[1])",
"mode\"\"\" if ctx.guild.id != 189571157446492161: return string = 'The members",
"ultra hardcore role\") await ctx.send(f'Undid ultra hardcore mode for {member.name}')",
"jpJHO2 = self.bot.get_channel(326263874770829313) if jpJHO.position == 4: await jpJHO.edit(position=5, name='just_hanging_out_2')",
"mode for those who are using it and can't explain",
"member = await hf.member_converter(ctx, member) if not member: return if",
"for you. \\n\\n\" f\"To enable ultra hardcore mode, type `;uhc",
"from list of ignored channels for UHC\") except KeyError: config['ignore']",
"self.bot.get_channel(326263874770829313) if jpJHO.position == 4: await jpJHO.edit(position=5, name='just_hanging_out_2') await jpJHO2.edit(position=4,",
"await ctx.send(f'Removed <@{member_id}> from the list, as they seem to",
"await ctx.author.add_roles(role) except discord.errors.Forbidden: await ctx.send(\"I couldn't add the ultra",
"= sorted(to_sort, key=lambda x: x[2], reverse=True) leaderboard = f\"The number",
"asterisks don't change \" \"anything. Talk to a mod to",
"date.today().strftime(\"%Y/%m/%d\"), 0] await hf.dump_json() try: await ctx.author.add_roles(role) except discord.errors.Forbidden: await",
"each user has had UHC enabled \" \\ f\"(Bold =",
"they can't\" f\" speak their native language, and they also",
"and positions in the lists, for if we temporarily want",
"if member: # if you specified someone else's ID, then",
"except discord.errors.Forbidden: await ctx.send(\"I couldn't add the ultra hardcore role\")",
"str(ctx.author.id) in config: if config[str(ctx.author.id)][0]: await ctx.invoke(self.explanation) return await ctx.send(f\"This",
"ctx.guild.get_role(486851965121331200) config = self.bot.db['ultraHardcore']['users'] if str(ctx.author.id) in config: # if",
"time_dict: if time_dict[i][0]: time_dict[i][2] += (datetime.today() - datetime.strptime(time_dict[i][1], \"%Y/%m/%d\")).days #",
"server or my testing server @commands.command() @hf.is_admin() async def swap(self,",
"for UHC\") except KeyError: config['ignore'] = [ctx.channel.id] await ctx.send(f\"Added {ctx.channel.name}",
"config[str(ctx.author.id)] if user[0]: await ctx.send(\"You're already in ultra hardcore mode.\")",
"list, as they seem to have left the server') await",
"channels for UHC\") except KeyError: config['ignore'] = [ctx.channel.id] await ctx.send(f\"Added",
"in UHC\") return else: await ctx.send(\"That user is not in",
"= self.bot.get_channel(189571157446492161) jpJHO2 = self.bot.get_channel(326263874770829313) if jpJHO.position == 4: await",
"why \" f\"they're trying to use this command. But, ultra",
"= ctx.guild.get_member(int(i[0])) if (i[2] < 10 and not i[1]) or",
"seem to have left the server') await ctx.send(string + ',",
"ctx.guild: return return ctx.guild.id == 189571157446492161 or ctx.guild.id == 275146036178059265",
"name='just_hanging_out') else: await jpJHO.edit(position=4, name='just_hanging_out') await jpJHO2.edit(position=5, name='just_hanging_out_2') @commands.group(invoke_without_command=True, aliases=['uhc'])",
"user currently has UHC enabled)\\n\\n\" for i in sorted_dict: user",
"= [] config = self.bot.db['ultraHardcore']['users'] for member_id in config.copy(): if",
"user[0]: await ctx.send(\"You're already in ultra hardcore mode.\") return else:",
"not in UHC mode.\") return await hf.dump_json() try: await member.remove_roles(role)",
"can't undo it and asterisks don't change \" \"anything. Talk",
"dir_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))).replace('\\\\', '/') class Jpserv(commands.Cog): \"\"\"Modules unique for the",
"for UHC\"\"\" if ctx.guild.id != 189571157446492161: return config = self.bot.db['ultraHardcore']",
"return role = ctx.guild.get_role(486851965121331200) config = self.bot.db['ultraHardcore']['users'] if member: #",
"hardcore mode. It works the same as \" \"normal hardcore",
"await ctx.send(string + ', '.join(members)) @ultrahardcore.command() async def explanation(self, ctx):",
"is currently NOT using hardcore mode, so I don't know",
"enable ultra hardcore mode, type `;uhc on` or `;uhc enable`.",
"f\"any English, and can't undo this mode themselves no matter",
"case a member leaves members.append(member.name) else: del config[member_id] await ctx.send(f'Removed",
"`;uhc enable`. \") @ultrahardcore.command(aliases=['enable']) async def on(self, ctx): \"\"\"Enables UHC\"\"\"",
"def cog_check(self, ctx): if not ctx.guild: return return ctx.guild.id ==",
"undone.\"\"\" # if ctx.guild.id != 189571157446492161: # return role =",
"example, if you are learning Japanese, any messages in English",
"Talk to a mod to undo this.\") @ultrahardcore.command() async def",
"on for the longest\"\"\" if ctx.guild.id != 189571157446492161: return time_dict",
"await ctx.send(f\"Removed {ctx.channel.name} from list of ignored channels for UHC\")",
"\") @ultrahardcore.command(aliases=['enable']) async def on(self, ctx): \"\"\"Enables UHC\"\"\" if ctx.guild.id",
"to go to JHO2\"\"\" jpJHO = self.bot.get_channel(189571157446492161) jpJHO2 = self.bot.get_channel(326263874770829313)",
"[True, '2019/02/14', 124]), # ('219617844973797376', [False, '2018/11/30', 122]), ...} to_sort",
"leaderboard of who has had UHC on for the longest\"\"\"",
"await ctx.send(\"You're already in ultra hardcore mode.\") return else: user[0]",
"\"anything. Talk to a mod to undo this.\") @ultrahardcore.command() async",
"in the language you are learning\" f\" (for example, if",
"in English will be deleted).\" f\" This can not be",
"= self.bot.db['ultraHardcore'] try: if ctx.channel.id not in config['ignore']: config['ignore'].append(ctx.channel.id) await",
"can't explain it\"\"\" if ctx.guild.id != 189571157446492161: return if str(ctx.author.id)",
"await jpJHO.edit(position=5, name='just_hanging_out_2') await jpJHO2.edit(position=4, name='just_hanging_out') else: await jpJHO.edit(position=4, name='just_hanging_out')",
"await jpJHO.edit(position=4, name='just_hanging_out') await jpJHO2.edit(position=5, name='just_hanging_out_2') @commands.group(invoke_without_command=True, aliases=['uhc']) async def",
"ask a mod to remove it for you. \\n\\n\" f\"To",
"for those who are using it and can't explain it\"\"\"",
"f\"(Bold = This user currently has UHC enabled)\\n\\n\" for i",
"undo this mode themselves.\") return await ctx.send(f\"{ctx.author.mention} is currently NOT",
"member is not None: # in case a member leaves",
"remove the ultra hardcore role\") await ctx.send(f'Undid ultra hardcore mode",
"longest\"\"\" if ctx.guild.id != 189571157446492161: return time_dict = deepcopy(self.bot.db['ultraHardcore']['users']) for",
"config['ignore'] = [ctx.channel.id] await ctx.send(f\"Added {ctx.channel.name} to list of ignored",
"from discord.ext import commands import os import json from datetime",
"def ignore(self, ctx): \"\"\"Ignores a channel for UHC\"\"\" if ctx.guild.id",
"!= 189571157446492161: return time_dict = deepcopy(self.bot.db['ultraHardcore']['users']) for i in time_dict:",
"'/') class Jpserv(commands.Cog): \"\"\"Modules unique for the Japanese server\"\"\" def",
"189571157446492161: # return role = ctx.guild.get_role(486851965121331200) config = self.bot.db['ultraHardcore']['users'] if",
"But, ultra hardcore mode means a user can't speak \"",
"and not i[1]) or (not user): continue if user.nick: name_str",
"couldn't add the ultra hardcore role\") await ctx.send(f\"{ctx.author.name} has chosen",
"= bot async def cog_check(self, ctx): if not ctx.guild: return",
"UHC from them member = await hf.member_converter(ctx, member) if not",
"self.bot.db['ultraHardcore']['users']: if self.bot.db['ultraHardcore']['users'][str(ctx.author.id)][0]: await ctx.send(f\"{ctx.author.mention} is currently using ultra hardcore",
"to_sort: [['243703909166612480', True, 162], ['219617844973797376', False, 122], ...] sorted_dict =",
"user has had UHC enabled \" \\ f\"(Bold = This",
"in ultra hardcore mode right now are ' guild =",
"config = self.bot.db['ultraHardcore']['users'] if str(ctx.author.id) in config: # if not",
"have left the server') await ctx.send(string + ', '.join(members)) @ultrahardcore.command()",
"name_str = f\"{user.mention} ({user.name})\" else: name_str = f\"{user.name}\" if i[1]:",
"del config[member_id] await ctx.send(f'Removed <@{member_id}> from the list, as they",
"import date, datetime, timedelta from .utils import helper_functions as hf",
"[ctx.channel.id] await ctx.send(f\"Added {ctx.channel.name} to list of ignored channels for",
"of ignored channels for UHC\") await hf.dump_json() def setup(bot): bot.add_cog(Jpserv(bot))",
"it and asterisks don't change \" \"anything. Talk to a",
"it\"\"\" if ctx.guild.id != 189571157446492161: return if str(ctx.author.id) in self.bot.db['ultraHardcore']['users']:",
"({user.name})\" else: name_str = f\"{user.name}\" if i[1]: leaderboard += f\"**{i[2]}:",
"ctx.author.add_roles(role) except discord.errors.Forbidden: await ctx.send(\"I couldn't add the ultra hardcore",
"True else: config[str(ctx.author.id)] = [True, date.today().strftime(\"%Y/%m/%d\"), 0] await hf.dump_json() try:",
"ignored channels for UHC\") except KeyError: config['ignore'] = [ctx.channel.id] await",
"if ctx.guild.id != 189571157446492161: return time_dict = deepcopy(self.bot.db['ultraHardcore']['users']) for i",
"def swap(self, ctx): \"\"\"Swaps JHO/JHO2's names and positions in the",
"learning\" f\" (for example, if you are learning Japanese, any",
"None: # in case a member leaves members.append(member.name) else: del",
"# ('219617844973797376', [False, '2018/11/30', 122]), ...} to_sort = [[i[0], i[1][0],",
"time_dict[i][2] += (datetime.today() - datetime.strptime(time_dict[i][1], \"%Y/%m/%d\")).days # {('243703909166612480', [True, '2019/02/14',",
"if you specified someone else's ID, then remove UHC from",
"of days each user has had UHC enabled \" \\",
"unless you ask a mod to remove it for you.",
"as hf from copy import deepcopy dir_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))).replace('\\\\', '/')",
"this mode themselves no matter what.\") @ultrahardcore.command(aliases=['lb']) async def leaderboard(self,",
"\\n\\n\" f\"To enable ultra hardcore mode, type `;uhc on` or",
"in list(time_dict.items())] # to_sort: [['243703909166612480', True, 162], ['219617844973797376', False, 122],",
"'.join(members)) @ultrahardcore.command() async def explanation(self, ctx): \"\"\"Explains ultra hardcore mode",
"not None: # in case a member leaves members.append(member.name) else:",
"this mode, they can't\" f\" speak their native language, and",
"async def ultrahardcore(self, ctx, *, member=None): \"\"\"Irreversible hardcore mode. Must",
"means you must speak in the language you are learning\"",
"{member.name}') else: await ctx.send(\"You can not remove UHC. Ask a",
"def __init__(self, bot): self.bot = bot async def cog_check(self, ctx):",
"not ctx.guild: return return ctx.guild.id == 189571157446492161 or ctx.guild.id ==",
"a member leaves members.append(member.name) else: del config[member_id] await ctx.send(f'Removed <@{member_id}>",
"ctx.send(f\"Added {ctx.channel.name} to list of ignored channels for UHC\") await",
"= self.bot.db['ultraHardcore']['users'] if str(ctx.author.id) in config: # if not enabled",
"jpJHO.edit(position=5, name='just_hanging_out_2') await jpJHO2.edit(position=4, name='just_hanging_out') else: await jpJHO.edit(position=4, name='just_hanging_out') await",
"config[str(ctx.author.id)][0]: await ctx.invoke(self.explanation) return await ctx.send(f\"This is ultra hardcore mode.",
"hardcore mode, type `;uhc on` or `;uhc enable`. \") @ultrahardcore.command(aliases=['enable'])",
"user is not in UHC mode.\") return await hf.dump_json() try:",
"async def swap(self, ctx): \"\"\"Swaps JHO/JHO2's names and positions in",
"not remove UHC. Ask a mod/admin to help you.\") else:",
"be undone unless you ask a mod to remove it",
"import commands import os import json from datetime import date,",
"await ctx.send(\"That user is not in UHC\") return else: await",
"hf.dump_json() try: await ctx.author.add_roles(role) except discord.errors.Forbidden: await ctx.send(\"I couldn't add",
"as \" \"normal hardcore mode except that you can't undo",
"config = self.bot.db['ultraHardcore'] try: if ctx.channel.id not in config['ignore']: config['ignore'].append(ctx.channel.id)",
"then remove UHC from them member = await hf.member_converter(ctx, member)",
"\"\"\"Swaps JHO/JHO2's names and positions in the lists, for if",
"return string = 'The members in ultra hardcore mode right",
"f\"**{i[2]}: {name_str}**\\n\" else: leaderboard += f\"{i[2]}: {name_str}\\n\" emb = discord.Embed(title=\"UHC",
"# if ctx.guild.id != 189571157446492161: # return role = ctx.guild.get_role(486851965121331200)",
"json from datetime import date, datetime, timedelta from .utils import",
"{name_str}**\\n\" else: leaderboard += f\"{i[2]}: {name_str}\\n\" emb = discord.Embed(title=\"UHC Leaderboard\",",
"16))) await ctx.send(embed=emb) @ultrahardcore.command() @hf.is_admin() async def ignore(self, ctx): \"\"\"Ignores",
"themselves no matter what.\") @ultrahardcore.command(aliases=['lb']) async def leaderboard(self, ctx): \"\"\"Shows",
"description=leaderboard, color=discord.Color(int('ff5500', 16))) await ctx.send(embed=emb) @ultrahardcore.command() @hf.is_admin() async def ignore(self,",
"\" f\"they're trying to use this command. But, ultra hardcore",
"self.bot.get_guild(189571157446492161) members = [] config = self.bot.db['ultraHardcore']['users'] for member_id in",
"' guild = self.bot.get_guild(189571157446492161) members = [] config = self.bot.db['ultraHardcore']['users']",
"sorted_dict: user = ctx.guild.get_member(int(i[0])) if (i[2] < 10 and not",
"the ultra hardcore role\") await ctx.send(f\"{ctx.author.name} has chosen to enable",
"122]), ...} to_sort = [[i[0], i[1][0], i[1][2]] for i in",
"hf from copy import deepcopy dir_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))).replace('\\\\', '/') class",
"config[member_id][0]: member = guild.get_member(int(member_id)) if member is not None: #",
"else: user[0] = True else: config[str(ctx.author.id)] = [True, date.today().strftime(\"%Y/%m/%d\"), 0]",
"hardcore mode means a user can't speak \" f\"any English,",
"= [ctx.channel.id] await ctx.send(f\"Added {ctx.channel.name} to list of ignored channels",
"189571157446492161: return string = 'The members in ultra hardcore mode",
"jpJHO.edit(position=4, name='just_hanging_out') await jpJHO2.edit(position=5, name='just_hanging_out_2') @commands.group(invoke_without_command=True, aliases=['uhc']) async def ultrahardcore(self,",
"in config: if config[str(member.id)][0]: config[str(member.id)][0] = False else: await ctx.send(\"That",
"member) if not member: return if hf.admin_check(ctx) and ctx.author.id !=",
"in config: # if not enabled user = config[str(ctx.author.id)] if",
"has chosen to enable ultra hardcore mode. It works the",
"guild = self.bot.get_guild(189571157446492161) members = [] config = self.bot.db['ultraHardcore']['users'] for",
"{('243703909166612480', [True, '2019/02/14', 124]), # ('219617844973797376', [False, '2018/11/30', 122]), ...}",
"role = ctx.guild.get_role(486851965121331200) config = self.bot.db['ultraHardcore']['users'] if member: # if",
"it for you. \\n\\n\" f\"To enable ultra hardcore mode, type",
"!= 189571157446492161: return if str(ctx.author.id) in self.bot.db['ultraHardcore']['users']: if self.bot.db['ultraHardcore']['users'][str(ctx.author.id)][0]: await",
"in self.bot.db['ultraHardcore']['users']: if self.bot.db['ultraHardcore']['users'][str(ctx.author.id)][0]: await ctx.send(f\"{ctx.author.mention} is currently using ultra",
"if user[0]: await ctx.send(\"You're already in ultra hardcore mode.\") return",
"ctx): \"\"\"Lists the people currently in ultra hardcore mode\"\"\" if",
"= discord.Embed(title=\"UHC Leaderboard\", description=leaderboard, color=discord.Color(int('ff5500', 16))) await ctx.send(embed=emb) @ultrahardcore.command() @hf.is_admin()",
"hf.dump_json() try: await member.remove_roles(role) except discord.errors.Forbidden: await ctx.send(\"I couldn't remove",
"help you.\") else: if str(ctx.author.id) in config: if config[str(ctx.author.id)][0]: await",
"ultra hardcore mode\"\"\" if ctx.guild.id != 189571157446492161: return string =",
"if str(ctx.author.id) in self.bot.db['ultraHardcore']['users']: if self.bot.db['ultraHardcore']['users'][str(ctx.author.id)][0]: await ctx.send(f\"{ctx.author.mention} is currently",
"list(time_dict.items())] # to_sort: [['243703909166612480', True, 162], ['219617844973797376', False, 122], ...]",
"from them member = await hf.member_converter(ctx, member) if not member:",
"ctx.send(\"That user is not in UHC\") return else: await ctx.send(\"That",
"members = [] config = self.bot.db['ultraHardcore']['users'] for member_id in config.copy():",
"color=discord.Color(int('ff5500', 16))) await ctx.send(embed=emb) @ultrahardcore.command() @hf.is_admin() async def ignore(self, ctx):",
"datetime.strptime(time_dict[i][1], \"%Y/%m/%d\")).days # {('243703909166612480', [True, '2019/02/14', 124]), # ('219617844973797376', [False,",
"ctx.guild.id == 189571157446492161 or ctx.guild.id == 275146036178059265 # these commands",
"(datetime.today() - datetime.strptime(time_dict[i][1], \"%Y/%m/%d\")).days # {('243703909166612480', [True, '2019/02/14', 124]), #",
"you specified someone else's ID, then remove UHC from them",
"('219617844973797376', [False, '2018/11/30', 122]), ...} to_sort = [[i[0], i[1][0], i[1][2]]"
] |
[
"File: \" prog = int((prog.count/(prog.total+1))*34.0) stdscr.addstr(2, 4, loadingText) stdscr.addstr(2, 4",
"else: raise IOError(\"File does not exist.\") else: program = ProgramState(stdscr)",
"= int((prog.count/(prog.total+1))*34.0) stdscr.addstr(2, 4, loadingText) stdscr.addstr(2, 4 + len(loadingText), state)",
"IOError(\"File does not exist.\") else: program = ProgramState(stdscr) key =",
"== binja.AnalysisState.DisassembleState: state = \"Disassembling\" else: state = \"Analyzing\" loadingText",
"prog.state == binja.AnalysisState.DisassembleState: state = \"Disassembling\" else: state = \"Analyzing\"",
"raise IOError(\"File does not exist.\") else: program = ProgramState(stdscr) key",
"stdscr.addstr(4, 4, '[' + '#'*prog + ' '*(34-prog) + ']')",
"= argparse.ArgumentParser(description='Nearly Headless BinaryNinja.') parser.add_argument('filename', nargs='?', default=\"\") args = parser.parse_args()",
"== \"no input\": raise curses.error(str(err)) else: key = \"\" #",
"\"\" # Clear Key Buffer # Rendering and input program.parseInput(key)",
"' '*(34-prog) + ']') stdscr.refresh() program = ProgramState(stdscr, bv) else:",
"'' if not args.filename == \"\": if os.path.isfile(args.filename): bv =",
"import curses # TODO...impliment live-refreashing the settings.json during run (add",
"as binja import argparse import os.path import curses # TODO...impliment",
"= bv.analysis_progress stdscr.erase() stdscr.border() state = '' if prog.state ==",
"the global input loop) # TODO...support multi-key presses? Not sure",
"key = \"\" while program.is_running: # Input Filtering try: key",
"loadingText) stdscr.addstr(2, 4 + len(loadingText), state) stdscr.addstr(4, 4, '[' +",
"binja import argparse import os.path import curses # TODO...impliment live-refreashing",
"\" prog = int((prog.count/(prog.total+1))*34.0) stdscr.addstr(2, 4, loadingText) stdscr.addstr(2, 4 +",
"+ ']') stdscr.refresh() program = ProgramState(stdscr, bv) else: raise IOError(\"File",
"program.render() curses.doupdate() if __name__ == \"__main__\": background = \"2a2a2a\" text",
"python3 from components import ProgramState import binaryninja as binja import",
"stdscr.erase() stdscr.border() state = '' if prog.state == binja.AnalysisState.DisassembleState: state",
"while program.is_running: # Input Filtering try: key = stdscr.getkey() except",
"program = '' if not args.filename == \"\": if os.path.isfile(args.filename):",
"multi-key presses? Not sure if this already works or not",
"stdscr.addstr(2, 4, loadingText) stdscr.addstr(2, 4 + len(loadingText), state) stdscr.addstr(4, 4,",
"curses.error as err: if not str(err) == \"no input\": raise",
"loop) # TODO...support multi-key presses? Not sure if this already",
"bv.update_analysis() while not str(bv.analysis_progress) == \"Idle\": prog = bv.analysis_progress stdscr.erase()",
"except curses.error as err: if not str(err) == \"no input\":",
"# Clear Key Buffer # Rendering and input program.parseInput(key) program.render()",
"== \"Idle\": prog = bv.analysis_progress stdscr.erase() stdscr.border() state = ''",
"if prog.state == binja.AnalysisState.DisassembleState: state = \"Disassembling\" else: state =",
"# Rendering and input program.parseInput(key) program.render() curses.doupdate() if __name__ ==",
"the settings.json during run (add the keybinding and check for",
"ProgramState import binaryninja as binja import argparse import os.path import",
"add some more checks so nothing goes out of bounds)",
"stdscr.border() state = '' if prog.state == binja.AnalysisState.DisassembleState: state =",
"binaryninja as binja import argparse import os.path import curses #",
"main(stdscr): # Setup parser = argparse.ArgumentParser(description='Nearly Headless BinaryNinja.') parser.add_argument('filename', nargs='?',",
"+ '#'*prog + ' '*(34-prog) + ']') stdscr.refresh() program =",
"terminals (I think it does right now, but I should",
"stdscr.addstr(2, 4 + len(loadingText), state) stdscr.addstr(4, 4, '[' + '#'*prog",
"run (add the keybinding and check for it here in",
"= '' if not args.filename == \"\": if os.path.isfile(args.filename): bv",
"if __name__ == \"__main__\": background = \"2a2a2a\" text = \"e0e0e0\"",
"right now, but I should add some more checks so",
"Buffer # Rendering and input program.parseInput(key) program.render() curses.doupdate() if __name__",
"if not str(err) == \"no input\": raise curses.error(str(err)) else: key",
"it here in the global input loop) # TODO...support multi-key",
"Headless BinaryNinja.') parser.add_argument('filename', nargs='?', default=\"\") args = parser.parse_args() program =",
"str(bv.analysis_progress) == \"Idle\": prog = bv.analysis_progress stdscr.erase() stdscr.border() state =",
"or not # TODO...make sure to support small terminals (I",
"bv.analysis_progress stdscr.erase() stdscr.border() state = '' if prog.state == binja.AnalysisState.DisassembleState:",
"try: key = stdscr.getkey() except curses.error as err: if not",
"\"Disassembling\" else: state = \"Analyzing\" loadingText = \"Loading File: \"",
"and check for it here in the global input loop)",
"program = ProgramState(stdscr) key = \"\" while program.is_running: # Input",
"key = stdscr.getkey() except curses.error as err: if not str(err)",
"to support small terminals (I think it does right now,",
"as err: if not str(err) == \"no input\": raise curses.error(str(err))",
"os.path.isfile(args.filename): bv = binja.BinaryViewType.get_view_of_file(''.join(args.filename), False) bv.update_analysis() while not str(bv.analysis_progress) ==",
"else: program = ProgramState(stdscr) key = \"\" while program.is_running: #",
"global input loop) # TODO...support multi-key presses? Not sure if",
"if this already works or not # TODO...make sure to",
"Key Buffer # Rendering and input program.parseInput(key) program.render() curses.doupdate() if",
"len(loadingText), state) stdscr.addstr(4, 4, '[' + '#'*prog + ' '*(34-prog)",
"Setup parser = argparse.ArgumentParser(description='Nearly Headless BinaryNinja.') parser.add_argument('filename', nargs='?', default=\"\") args",
"= \"Analyzing\" loadingText = \"Loading File: \" prog = int((prog.count/(prog.total+1))*34.0)",
"binja.BinaryViewType.get_view_of_file(''.join(args.filename), False) bv.update_analysis() while not str(bv.analysis_progress) == \"Idle\": prog =",
"exist.\") else: program = ProgramState(stdscr) key = \"\" while program.is_running:",
"input\": raise curses.error(str(err)) else: key = \"\" # Clear Key",
"if os.path.isfile(args.filename): bv = binja.BinaryViewType.get_view_of_file(''.join(args.filename), False) bv.update_analysis() while not str(bv.analysis_progress)",
"parser.parse_args() program = '' if not args.filename == \"\": if",
"prog = bv.analysis_progress stdscr.erase() stdscr.border() state = '' if prog.state",
"err: if not str(err) == \"no input\": raise curses.error(str(err)) else:",
"else: key = \"\" # Clear Key Buffer # Rendering",
"argparse.ArgumentParser(description='Nearly Headless BinaryNinja.') parser.add_argument('filename', nargs='?', default=\"\") args = parser.parse_args() program",
"# TODO...impliment live-refreashing the settings.json during run (add the keybinding",
"settings.json during run (add the keybinding and check for it",
"of bounds) def main(stdscr): # Setup parser = argparse.ArgumentParser(description='Nearly Headless",
"out of bounds) def main(stdscr): # Setup parser = argparse.ArgumentParser(description='Nearly",
"not str(err) == \"no input\": raise curses.error(str(err)) else: key =",
"ProgramState(stdscr) key = \"\" while program.is_running: # Input Filtering try:",
"the keybinding and check for it here in the global",
"program.parseInput(key) program.render() curses.doupdate() if __name__ == \"__main__\": background = \"2a2a2a\"",
"# TODO...make sure to support small terminals (I think it",
"parser.add_argument('filename', nargs='?', default=\"\") args = parser.parse_args() program = '' if",
"<gh_stars>0 #!/usr/bin/env python3 from components import ProgramState import binaryninja as",
"'' if prog.state == binja.AnalysisState.DisassembleState: state = \"Disassembling\" else: state",
"'#'*prog + ' '*(34-prog) + ']') stdscr.refresh() program = ProgramState(stdscr,",
"Filtering try: key = stdscr.getkey() except curses.error as err: if",
"some more checks so nothing goes out of bounds) def",
"presses? Not sure if this already works or not #",
"check for it here in the global input loop) #",
"program = ProgramState(stdscr, bv) else: raise IOError(\"File does not exist.\")",
"\"\": if os.path.isfile(args.filename): bv = binja.BinaryViewType.get_view_of_file(''.join(args.filename), False) bv.update_analysis() while not",
"now, but I should add some more checks so nothing",
"curses.doupdate() if __name__ == \"__main__\": background = \"2a2a2a\" text =",
"key = \"\" # Clear Key Buffer # Rendering and",
"= ProgramState(stdscr) key = \"\" while program.is_running: # Input Filtering",
"Input Filtering try: key = stdscr.getkey() except curses.error as err:",
"bv = binja.BinaryViewType.get_view_of_file(''.join(args.filename), False) bv.update_analysis() while not str(bv.analysis_progress) == \"Idle\":",
"state = \"Disassembling\" else: state = \"Analyzing\" loadingText = \"Loading",
"'[' + '#'*prog + ' '*(34-prog) + ']') stdscr.refresh() program",
"Not sure if this already works or not # TODO...make",
"nargs='?', default=\"\") args = parser.parse_args() program = '' if not",
"goes out of bounds) def main(stdscr): # Setup parser =",
"= \"Disassembling\" else: state = \"Analyzing\" loadingText = \"Loading File:",
"4, loadingText) stdscr.addstr(2, 4 + len(loadingText), state) stdscr.addstr(4, 4, '['",
"+ ' '*(34-prog) + ']') stdscr.refresh() program = ProgramState(stdscr, bv)",
"= \"\" while program.is_running: # Input Filtering try: key =",
"not # TODO...make sure to support small terminals (I think",
"+ len(loadingText), state) stdscr.addstr(4, 4, '[' + '#'*prog + '",
"in the global input loop) # TODO...support multi-key presses? Not",
"args.filename == \"\": if os.path.isfile(args.filename): bv = binja.BinaryViewType.get_view_of_file(''.join(args.filename), False) bv.update_analysis()",
"during run (add the keybinding and check for it here",
"here in the global input loop) # TODO...support multi-key presses?",
"curses # TODO...impliment live-refreashing the settings.json during run (add the",
"#!/usr/bin/env python3 from components import ProgramState import binaryninja as binja",
"(add the keybinding and check for it here in the",
"components import ProgramState import binaryninja as binja import argparse import",
"= \"\" # Clear Key Buffer # Rendering and input",
"keybinding and check for it here in the global input",
"state) stdscr.addstr(4, 4, '[' + '#'*prog + ' '*(34-prog) +",
"TODO...impliment live-refreashing the settings.json during run (add the keybinding and",
"bounds) def main(stdscr): # Setup parser = argparse.ArgumentParser(description='Nearly Headless BinaryNinja.')",
"stdscr.refresh() program = ProgramState(stdscr, bv) else: raise IOError(\"File does not",
"input program.parseInput(key) program.render() curses.doupdate() if __name__ == \"__main__\": background =",
"curses.error(str(err)) else: key = \"\" # Clear Key Buffer #",
"args = parser.parse_args() program = '' if not args.filename ==",
"and input program.parseInput(key) program.render() curses.doupdate() if __name__ == \"__main__\": background",
"\"Idle\": prog = bv.analysis_progress stdscr.erase() stdscr.border() state = '' if",
"= parser.parse_args() program = '' if not args.filename == \"\":",
"but I should add some more checks so nothing goes",
"default=\"\") args = parser.parse_args() program = '' if not args.filename",
"(I think it does right now, but I should add",
"import argparse import os.path import curses # TODO...impliment live-refreashing the",
"not args.filename == \"\": if os.path.isfile(args.filename): bv = binja.BinaryViewType.get_view_of_file(''.join(args.filename), False)",
"loadingText = \"Loading File: \" prog = int((prog.count/(prog.total+1))*34.0) stdscr.addstr(2, 4,",
"\"\" while program.is_running: # Input Filtering try: key = stdscr.getkey()",
"program.is_running: # Input Filtering try: key = stdscr.getkey() except curses.error",
"= stdscr.getkey() except curses.error as err: if not str(err) ==",
"= \"Loading File: \" prog = int((prog.count/(prog.total+1))*34.0) stdscr.addstr(2, 4, loadingText)",
"\"Analyzing\" loadingText = \"Loading File: \" prog = int((prog.count/(prog.total+1))*34.0) stdscr.addstr(2,",
"def main(stdscr): # Setup parser = argparse.ArgumentParser(description='Nearly Headless BinaryNinja.') parser.add_argument('filename',",
"TODO...make sure to support small terminals (I think it does",
"Clear Key Buffer # Rendering and input program.parseInput(key) program.render() curses.doupdate()",
"input loop) # TODO...support multi-key presses? Not sure if this",
"raise curses.error(str(err)) else: key = \"\" # Clear Key Buffer",
"live-refreashing the settings.json during run (add the keybinding and check",
"parser = argparse.ArgumentParser(description='Nearly Headless BinaryNinja.') parser.add_argument('filename', nargs='?', default=\"\") args =",
"stdscr.getkey() except curses.error as err: if not str(err) == \"no",
"import os.path import curses # TODO...impliment live-refreashing the settings.json during",
"ProgramState(stdscr, bv) else: raise IOError(\"File does not exist.\") else: program",
"argparse import os.path import curses # TODO...impliment live-refreashing the settings.json",
"works or not # TODO...make sure to support small terminals",
"support small terminals (I think it does right now, but",
"this already works or not # TODO...make sure to support",
"= binja.BinaryViewType.get_view_of_file(''.join(args.filename), False) bv.update_analysis() while not str(bv.analysis_progress) == \"Idle\": prog",
"str(err) == \"no input\": raise curses.error(str(err)) else: key = \"\"",
"']') stdscr.refresh() program = ProgramState(stdscr, bv) else: raise IOError(\"File does",
"import ProgramState import binaryninja as binja import argparse import os.path",
"'*(34-prog) + ']') stdscr.refresh() program = ProgramState(stdscr, bv) else: raise",
"small terminals (I think it does right now, but I",
"for it here in the global input loop) # TODO...support",
"bv) else: raise IOError(\"File does not exist.\") else: program =",
"already works or not # TODO...make sure to support small",
"state = '' if prog.state == binja.AnalysisState.DisassembleState: state = \"Disassembling\"",
"not exist.\") else: program = ProgramState(stdscr) key = \"\" while",
"sure if this already works or not # TODO...make sure",
"checks so nothing goes out of bounds) def main(stdscr): #",
"\"Loading File: \" prog = int((prog.count/(prog.total+1))*34.0) stdscr.addstr(2, 4, loadingText) stdscr.addstr(2,",
"from components import ProgramState import binaryninja as binja import argparse",
"so nothing goes out of bounds) def main(stdscr): # Setup",
"False) bv.update_analysis() while not str(bv.analysis_progress) == \"Idle\": prog = bv.analysis_progress",
"int((prog.count/(prog.total+1))*34.0) stdscr.addstr(2, 4, loadingText) stdscr.addstr(2, 4 + len(loadingText), state) stdscr.addstr(4,",
"4, '[' + '#'*prog + ' '*(34-prog) + ']') stdscr.refresh()",
"binja.AnalysisState.DisassembleState: state = \"Disassembling\" else: state = \"Analyzing\" loadingText =",
"4 + len(loadingText), state) stdscr.addstr(4, 4, '[' + '#'*prog +",
"BinaryNinja.') parser.add_argument('filename', nargs='?', default=\"\") args = parser.parse_args() program = ''",
"else: state = \"Analyzing\" loadingText = \"Loading File: \" prog",
"I should add some more checks so nothing goes out",
"should add some more checks so nothing goes out of",
"while not str(bv.analysis_progress) == \"Idle\": prog = bv.analysis_progress stdscr.erase() stdscr.border()",
"does right now, but I should add some more checks",
"nothing goes out of bounds) def main(stdscr): # Setup parser",
"= '' if prog.state == binja.AnalysisState.DisassembleState: state = \"Disassembling\" else:",
"TODO...support multi-key presses? Not sure if this already works or",
"import binaryninja as binja import argparse import os.path import curses",
"think it does right now, but I should add some",
"# TODO...support multi-key presses? Not sure if this already works",
"# Input Filtering try: key = stdscr.getkey() except curses.error as",
"state = \"Analyzing\" loadingText = \"Loading File: \" prog =",
"\"no input\": raise curses.error(str(err)) else: key = \"\" # Clear",
"__name__ == \"__main__\": background = \"2a2a2a\" text = \"e0e0e0\" curses.wrapper(main)",
"if not args.filename == \"\": if os.path.isfile(args.filename): bv = binja.BinaryViewType.get_view_of_file(''.join(args.filename),",
"os.path import curses # TODO...impliment live-refreashing the settings.json during run",
"more checks so nothing goes out of bounds) def main(stdscr):",
"= ProgramState(stdscr, bv) else: raise IOError(\"File does not exist.\") else:",
"Rendering and input program.parseInput(key) program.render() curses.doupdate() if __name__ == \"__main__\":",
"it does right now, but I should add some more",
"not str(bv.analysis_progress) == \"Idle\": prog = bv.analysis_progress stdscr.erase() stdscr.border() state",
"prog = int((prog.count/(prog.total+1))*34.0) stdscr.addstr(2, 4, loadingText) stdscr.addstr(2, 4 + len(loadingText),",
"sure to support small terminals (I think it does right",
"does not exist.\") else: program = ProgramState(stdscr) key = \"\"",
"# Setup parser = argparse.ArgumentParser(description='Nearly Headless BinaryNinja.') parser.add_argument('filename', nargs='?', default=\"\")",
"== \"\": if os.path.isfile(args.filename): bv = binja.BinaryViewType.get_view_of_file(''.join(args.filename), False) bv.update_analysis() while"
] |
[
"same value for all spatial dimensions. strides: An integer or",
"the strides of the pooling operation. Can be a single",
"the same value for all spatial dimensions. strides: An integer",
"2.0 (the \"License\"); # you may not use this file",
"len_dim1, self.pool_size[0], self.padding, self.strides[0] ) len_dim2 = conv_utils.conv_output_length( len_dim2, self.pool_size[1],",
"manually. # TODO(fchollet): remove this when TF pooling is feature-complete.",
"strides is None: strides = pool_size self.pool_function = pool_function self.pool_size",
"pooling functions, for 3D inputs. This class only exists for",
"len_dim1 = input_shape[2] len_dim2 = input_shape[3] len_dim3 = input_shape[4] else:",
"padding=\"valid\", data_format=\"channels_last\", name=None, **kwargs ): super().__init__(name=name, **kwargs) if data_format is",
"the License. # ============================================================================== \"\"\"Private base class for pooling 3D",
"== \"channels_first\": # TF does not support `channels_first` with 3D",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"len_dim2 = conv_utils.conv_output_length( len_dim2, self.pool_size[1], self.padding, self.strides[1] ) len_dim3 =",
"in the inputs. `channels_last` corresponds to inputs with shape `(batch,",
"self.data_format == \"channels_first\": outputs = tf.transpose(outputs, (0, 4, 1, 2,",
"be a single integer to specify the same value for",
"permissions and # limitations under the License. # ============================================================================== \"\"\"Private",
"= tf.transpose(outputs, (0, 4, 1, 2, 3)) return outputs def",
"name of the layer. \"\"\" def __init__( self, pool_function, pool_size,",
"self.pool_function = pool_function self.pool_size = conv_utils.normalize_tuple(pool_size, 3, \"pool_size\") self.strides =",
"use this file except in compliance with the License. #",
"self.pool_size[2], self.padding, self.strides[2] ) if self.data_format == \"channels_first\": return tf.TensorShape(",
"with shape `(batch, channels, depth, height, width)`. name: A string,",
"strides=strides, padding=self.padding.upper(), ) if self.data_format == \"channels_first\": outputs = tf.transpose(outputs,",
"[input_shape[0], len_dim1, len_dim2, len_dim3, input_shape[4]] ) def get_config(self): config =",
"`tf.nn.max_pool2d`. pool_size: An integer or tuple/list of 3 integers: (pool_depth,",
"(0, 2, 3, 4, 1)) outputs = self.pool_function( inputs, ksize=pool_shape,",
"3 integers, specifying the strides of the pooling operation. Can",
"else: return tf.TensorShape( [input_shape[0], len_dim1, len_dim2, len_dim3, input_shape[4]] ) def",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"License. # You may obtain a copy of the License",
"The TensorFlow Authors. All Rights Reserved. # # Licensed under",
"backend from keras.engine.base_layer import Layer from keras.engine.input_spec import InputSpec from",
"The pooling function to apply, e.g. `tf.nn.max_pool2d`. pool_size: An integer",
"from keras.engine.input_spec import InputSpec from keras.utils import conv_utils class Pooling3D(Layer):",
"the layer. \"\"\" def __init__( self, pool_function, pool_size, strides, padding=\"valid\",",
"the dimensions in the inputs. `channels_last` corresponds to inputs with",
"under the License is distributed on an \"AS IS\" BASIS,",
"License for the specific language governing permissions and # limitations",
"self.strides, \"data_format\": self.data_format, } base_config = super().get_config() return dict(list(base_config.items()) +",
"not support `channels_first` with 3D pooling operations, # so we",
") if self.data_format == \"channels_first\": outputs = tf.transpose(outputs, (0, 4,",
"len_dim3, self.pool_size[2], self.padding, self.strides[2] ) if self.data_format == \"channels_first\": return",
"class for pooling 3D layers.\"\"\" import tensorflow.compat.v2 as tf from",
"inputs): pool_shape = (1,) + self.pool_size + (1,) strides =",
"if self.data_format == \"channels_first\": # TF does not support `channels_first`",
"Reserved. # # Licensed under the Apache License, Version 2.0",
"\"channels_first\": return tf.TensorShape( [input_shape[0], input_shape[1], len_dim1, len_dim2, len_dim3] ) else:",
"\"strides\": self.strides, \"data_format\": self.data_format, } base_config = super().get_config() return dict(list(base_config.items())",
"same value for all spatial dimensions. padding: A string. The",
"the pooling operation. Can be a single integer to specify",
"ordering of the dimensions in the inputs. `channels_last` corresponds to",
"'same'. Case-insensitive. data_format: A string, one of `channels_last` (default) or",
"governing permissions and # limitations under the License. # ==============================================================================",
"\"strides\", allow_zero=True ) self.padding = conv_utils.normalize_padding(padding) self.data_format = conv_utils.normalize_data_format(data_format) self.input_spec",
"operations, # so we must handle this case manually. #",
"string, one of `channels_last` (default) or `channels_first`. The ordering of",
"pooling operations, # so we must handle this case manually.",
"TensorFlow Authors. All Rights Reserved. # # Licensed under the",
"and # limitations under the License. # ============================================================================== \"\"\"Private base",
"return outputs def compute_output_shape(self, input_shape): input_shape = tf.TensorShape(input_shape).as_list() if self.data_format",
"self.pool_function( inputs, ksize=pool_shape, strides=strides, padding=self.padding.upper(), ) if self.data_format == \"channels_first\":",
"strides, padding=\"valid\", data_format=\"channels_last\", name=None, **kwargs ): super().__init__(name=name, **kwargs) if data_format",
"in compliance with the License. # You may obtain a",
"3, \"pool_size\") self.strides = conv_utils.normalize_tuple( strides, 3, \"strides\", allow_zero=True )",
"software # distributed under the License is distributed on an",
"outputs = tf.transpose(outputs, (0, 4, 1, 2, 3)) return outputs",
"specify the same value for all spatial dimensions. padding: A",
"= conv_utils.normalize_data_format(data_format) self.input_spec = InputSpec(ndim=5) def call(self, inputs): pool_shape =",
"**kwargs) if data_format is None: data_format = backend.image_data_format() if strides",
"operation. Can be a single integer to specify the same",
"channels)` while `channels_first` corresponds to inputs with shape `(batch, channels,",
"function to apply, e.g. `tf.nn.max_pool2d`. pool_size: An integer or tuple/list",
"Pooling3D(Layer): \"\"\"Pooling layer for arbitrary pooling functions, for 3D inputs.",
"self.padding, \"strides\": self.strides, \"data_format\": self.data_format, } base_config = super().get_config() return",
"pooling operation. Can be a single integer to specify the",
"height, width)`. name: A string, the name of the layer.",
"is None: data_format = backend.image_data_format() if strides is None: strides",
"of the dimensions in the inputs. `channels_last` corresponds to inputs",
"dimensions in the inputs. `channels_last` corresponds to inputs with shape",
"limitations under the License. # ============================================================================== \"\"\"Private base class for",
"padding: A string. The padding method, either 'valid' or 'same'.",
"data_format=\"channels_last\", name=None, **kwargs ): super().__init__(name=name, **kwargs) if data_format is None:",
"is feature-complete. inputs = tf.transpose(inputs, (0, 2, 3, 4, 1))",
"padding=self.padding.upper(), ) if self.data_format == \"channels_first\": outputs = tf.transpose(outputs, (0,",
"\"pool_size\") self.strides = conv_utils.normalize_tuple( strides, 3, \"strides\", allow_zero=True ) self.padding",
"height, width, channels)` while `channels_first` corresponds to inputs with shape",
") self.padding = conv_utils.normalize_padding(padding) self.data_format = conv_utils.normalize_data_format(data_format) self.input_spec = InputSpec(ndim=5)",
"Args: pool_function: The pooling function to apply, e.g. `tf.nn.max_pool2d`. pool_size:",
"self.data_format == \"channels_first\": return tf.TensorShape( [input_shape[0], input_shape[1], len_dim1, len_dim2, len_dim3]",
"strides of the pooling operation. Can be a single integer",
"self.pool_size[0], self.padding, self.strides[0] ) len_dim2 = conv_utils.conv_output_length( len_dim2, self.pool_size[1], self.padding,",
"len_dim3 = input_shape[3] len_dim1 = conv_utils.conv_output_length( len_dim1, self.pool_size[0], self.padding, self.strides[0]",
"super().__init__(name=name, **kwargs) if data_format is None: data_format = backend.image_data_format() if",
"OF ANY KIND, either express or implied. # See the",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"when TF pooling is feature-complete. inputs = tf.transpose(inputs, (0, 2,",
"conv_utils.conv_output_length( len_dim3, self.pool_size[2], self.padding, self.strides[2] ) if self.data_format == \"channels_first\":",
"get_config(self): config = { \"pool_size\": self.pool_size, \"padding\": self.padding, \"strides\": self.strides,",
"ANY KIND, either express or implied. # See the License",
"See the License for the specific language governing permissions and",
"self.strides[0] ) len_dim2 = conv_utils.conv_output_length( len_dim2, self.pool_size[1], self.padding, self.strides[1] )",
"layers.\"\"\" import tensorflow.compat.v2 as tf from keras import backend from",
"3D inputs. This class only exists for code reuse. It",
"either 'valid' or 'same'. Case-insensitive. data_format: A string, one of",
"the License. # You may obtain a copy of the",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"for the specific language governing permissions and # limitations under",
"spatial dimensions. strides: An integer or tuple/list of 3 integers,",
"to in writing, software # distributed under the License is",
"1)) outputs = self.pool_function( inputs, ksize=pool_shape, strides=strides, padding=self.padding.upper(), ) if",
"= conv_utils.conv_output_length( len_dim3, self.pool_size[2], self.padding, self.strides[2] ) if self.data_format ==",
"= input_shape[2] len_dim3 = input_shape[3] len_dim1 = conv_utils.conv_output_length( len_dim1, self.pool_size[0],",
"# See the License for the specific language governing permissions",
"for code reuse. It will never be an exposed API.",
"of the pooling operation. Can be a single integer to",
"3, 4, 1)) outputs = self.pool_function( inputs, ksize=pool_shape, strides=strides, padding=self.padding.upper(),",
"language governing permissions and # limitations under the License. #",
"or agreed to in writing, software # distributed under the",
"self.padding, self.strides[2] ) if self.data_format == \"channels_first\": return tf.TensorShape( [input_shape[0],",
"required by applicable law or agreed to in writing, software",
"to specify the same value for all spatial dimensions. padding:",
"pooling window. Can be a single integer to specify the",
"= conv_utils.conv_output_length( len_dim1, self.pool_size[0], self.padding, self.strides[0] ) len_dim2 = conv_utils.conv_output_length(",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"pool_function: The pooling function to apply, e.g. `tf.nn.max_pool2d`. pool_size: An",
"value for all spatial dimensions. padding: A string. The padding",
"with the License. # You may obtain a copy of",
"allow_zero=True ) self.padding = conv_utils.normalize_padding(padding) self.data_format = conv_utils.normalize_data_format(data_format) self.input_spec =",
"return tf.TensorShape( [input_shape[0], len_dim1, len_dim2, len_dim3, input_shape[4]] ) def get_config(self):",
"pool_function self.pool_size = conv_utils.normalize_tuple(pool_size, 3, \"pool_size\") self.strides = conv_utils.normalize_tuple( strides,",
"__init__( self, pool_function, pool_size, strides, padding=\"valid\", data_format=\"channels_last\", name=None, **kwargs ):",
"compliance with the License. # You may obtain a copy",
"All Rights Reserved. # # Licensed under the Apache License,",
"agreed to in writing, software # distributed under the License",
"exists for code reuse. It will never be an exposed",
"e.g. `tf.nn.max_pool2d`. pool_size: An integer or tuple/list of 3 integers:",
"inputs with shape `(batch, depth, height, width, channels)` while `channels_first`",
"shape `(batch, depth, height, width, channels)` while `channels_first` corresponds to",
"data_format is None: data_format = backend.image_data_format() if strides is None:",
"strides = pool_size self.pool_function = pool_function self.pool_size = conv_utils.normalize_tuple(pool_size, 3,",
"= conv_utils.normalize_tuple( strides, 3, \"strides\", allow_zero=True ) self.padding = conv_utils.normalize_padding(padding)",
"if self.data_format == \"channels_first\": return tf.TensorShape( [input_shape[0], input_shape[1], len_dim1, len_dim2,",
"distributed under the License is distributed on an \"AS IS\"",
"if strides is None: strides = pool_size self.pool_function = pool_function",
"pool_height, pool_width) specifying the size of the pooling window. Can",
"or tuple/list of 3 integers, specifying the strides of the",
"+ self.pool_size + (1,) strides = (1,) + self.strides +",
"name: A string, the name of the layer. \"\"\" def",
"integer or tuple/list of 3 integers: (pool_depth, pool_height, pool_width) specifying",
"self.data_format == \"channels_first\": len_dim1 = input_shape[2] len_dim2 = input_shape[3] len_dim3",
"express or implied. # See the License for the specific",
"as tf from keras import backend from keras.engine.base_layer import Layer",
"except in compliance with the License. # You may obtain",
"input_shape[3] len_dim1 = conv_utils.conv_output_length( len_dim1, self.pool_size[0], self.padding, self.strides[0] ) len_dim2",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"(default) or `channels_first`. The ordering of the dimensions in the",
"from keras.utils import conv_utils class Pooling3D(Layer): \"\"\"Pooling layer for arbitrary",
"not use this file except in compliance with the License.",
"len_dim2, self.pool_size[1], self.padding, self.strides[1] ) len_dim3 = conv_utils.conv_output_length( len_dim3, self.pool_size[2],",
"channels, depth, height, width)`. name: A string, the name of",
"writing, software # distributed under the License is distributed on",
"to apply, e.g. `tf.nn.max_pool2d`. pool_size: An integer or tuple/list of",
"you may not use this file except in compliance with",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"of the layer. \"\"\" def __init__( self, pool_function, pool_size, strides,",
"method, either 'valid' or 'same'. Case-insensitive. data_format: A string, one",
"= InputSpec(ndim=5) def call(self, inputs): pool_shape = (1,) + self.pool_size",
"to specify the same value for all spatial dimensions. strides:",
"InputSpec(ndim=5) def call(self, inputs): pool_shape = (1,) + self.pool_size +",
"so we must handle this case manually. # TODO(fchollet): remove",
"= tf.transpose(inputs, (0, 2, 3, 4, 1)) outputs = self.pool_function(",
"string, the name of the layer. \"\"\" def __init__( self,",
"conv_utils.conv_output_length( len_dim1, self.pool_size[0], self.padding, self.strides[0] ) len_dim2 = conv_utils.conv_output_length( len_dim2,",
"tuple/list of 3 integers, specifying the strides of the pooling",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"for all spatial dimensions. strides: An integer or tuple/list of",
"TODO(fchollet): remove this when TF pooling is feature-complete. inputs =",
"len_dim2 = input_shape[3] len_dim3 = input_shape[4] else: len_dim1 = input_shape[1]",
"integers, specifying the strides of the pooling operation. Can be",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"dimensions. strides: An integer or tuple/list of 3 integers, specifying",
"inputs. This class only exists for code reuse. It will",
"input_shape = tf.TensorShape(input_shape).as_list() if self.data_format == \"channels_first\": len_dim1 = input_shape[2]",
"while `channels_first` corresponds to inputs with shape `(batch, channels, depth,",
"corresponds to inputs with shape `(batch, channels, depth, height, width)`.",
"tf.TensorShape( [input_shape[0], len_dim1, len_dim2, len_dim3, input_shape[4]] ) def get_config(self): config",
"pool_function, pool_size, strides, padding=\"valid\", data_format=\"channels_last\", name=None, **kwargs ): super().__init__(name=name, **kwargs)",
"= pool_size self.pool_function = pool_function self.pool_size = conv_utils.normalize_tuple(pool_size, 3, \"pool_size\")",
"`channels_last` (default) or `channels_first`. The ordering of the dimensions in",
"\"\"\"Pooling layer for arbitrary pooling functions, for 3D inputs. This",
"len_dim1 = conv_utils.conv_output_length( len_dim1, self.pool_size[0], self.padding, self.strides[0] ) len_dim2 =",
"must handle this case manually. # TODO(fchollet): remove this when",
"pooling function to apply, e.g. `tf.nn.max_pool2d`. pool_size: An integer or",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"self.pool_size + (1,) strides = (1,) + self.strides + (1,)",
"the License is distributed on an \"AS IS\" BASIS, #",
"2015 The TensorFlow Authors. All Rights Reserved. # # Licensed",
"keras.utils import conv_utils class Pooling3D(Layer): \"\"\"Pooling layer for arbitrary pooling",
"A string. The padding method, either 'valid' or 'same'. Case-insensitive.",
"an exposed API. Args: pool_function: The pooling function to apply,",
"outputs def compute_output_shape(self, input_shape): input_shape = tf.TensorShape(input_shape).as_list() if self.data_format ==",
"specify the same value for all spatial dimensions. strides: An",
"A string, one of `channels_last` (default) or `channels_first`. The ordering",
"(1,) + self.strides + (1,) if self.data_format == \"channels_first\": #",
"pooling is feature-complete. inputs = tf.transpose(inputs, (0, 2, 3, 4,",
"config = { \"pool_size\": self.pool_size, \"padding\": self.padding, \"strides\": self.strides, \"data_format\":",
"len_dim3] ) else: return tf.TensorShape( [input_shape[0], len_dim1, len_dim2, len_dim3, input_shape[4]]",
"+ (1,) if self.data_format == \"channels_first\": # TF does not",
"size of the pooling window. Can be a single integer",
"None: strides = pool_size self.pool_function = pool_function self.pool_size = conv_utils.normalize_tuple(pool_size,",
"conv_utils.normalize_tuple(pool_size, 3, \"pool_size\") self.strides = conv_utils.normalize_tuple( strides, 3, \"strides\", allow_zero=True",
"arbitrary pooling functions, for 3D inputs. This class only exists",
"tf.transpose(inputs, (0, 2, 3, 4, 1)) outputs = self.pool_function( inputs,",
"law or agreed to in writing, software # distributed under",
"of 3 integers, specifying the strides of the pooling operation.",
"of `channels_last` (default) or `channels_first`. The ordering of the dimensions",
"keras import backend from keras.engine.base_layer import Layer from keras.engine.input_spec import",
"data_format = backend.image_data_format() if strides is None: strides = pool_size",
"An integer or tuple/list of 3 integers: (pool_depth, pool_height, pool_width)",
"code reuse. It will never be an exposed API. Args:",
"self.strides = conv_utils.normalize_tuple( strides, 3, \"strides\", allow_zero=True ) self.padding =",
"outputs = self.pool_function( inputs, ksize=pool_shape, strides=strides, padding=self.padding.upper(), ) if self.data_format",
"len_dim3 = conv_utils.conv_output_length( len_dim3, self.pool_size[2], self.padding, self.strides[2] ) if self.data_format",
"may obtain a copy of the License at # #",
"= self.pool_function( inputs, ksize=pool_shape, strides=strides, padding=self.padding.upper(), ) if self.data_format ==",
"2, 3, 4, 1)) outputs = self.pool_function( inputs, ksize=pool_shape, strides=strides,",
"strides = (1,) + self.strides + (1,) if self.data_format ==",
"len_dim1, len_dim2, len_dim3, input_shape[4]] ) def get_config(self): config = {",
"\"pool_size\": self.pool_size, \"padding\": self.padding, \"strides\": self.strides, \"data_format\": self.data_format, } base_config",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"pool_width) specifying the size of the pooling window. Can be",
"width, channels)` while `channels_first` corresponds to inputs with shape `(batch,",
"of the pooling window. Can be a single integer to",
"width)`. name: A string, the name of the layer. \"\"\"",
"to inputs with shape `(batch, channels, depth, height, width)`. name:",
"\"\"\"Private base class for pooling 3D layers.\"\"\" import tensorflow.compat.v2 as",
"may not use this file except in compliance with the",
"def compute_output_shape(self, input_shape): input_shape = tf.TensorShape(input_shape).as_list() if self.data_format == \"channels_first\":",
"# so we must handle this case manually. # TODO(fchollet):",
"\"data_format\": self.data_format, } base_config = super().get_config() return dict(list(base_config.items()) + list(config.items()))",
"len_dim1, len_dim2, len_dim3] ) else: return tf.TensorShape( [input_shape[0], len_dim1, len_dim2,",
"for 3D inputs. This class only exists for code reuse.",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"License. # ============================================================================== \"\"\"Private base class for pooling 3D layers.\"\"\"",
"this file except in compliance with the License. # You",
"\"\"\" def __init__( self, pool_function, pool_size, strides, padding=\"valid\", data_format=\"channels_last\", name=None,",
"Layer from keras.engine.input_spec import InputSpec from keras.utils import conv_utils class",
"tensorflow.compat.v2 as tf from keras import backend from keras.engine.base_layer import",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"pooling 3D layers.\"\"\" import tensorflow.compat.v2 as tf from keras import",
"# # Licensed under the Apache License, Version 2.0 (the",
"file except in compliance with the License. # You may",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"compute_output_shape(self, input_shape): input_shape = tf.TensorShape(input_shape).as_list() if self.data_format == \"channels_first\": len_dim1",
"= input_shape[3] len_dim1 = conv_utils.conv_output_length( len_dim1, self.pool_size[0], self.padding, self.strides[0] )",
") len_dim3 = conv_utils.conv_output_length( len_dim3, self.pool_size[2], self.padding, self.strides[2] ) if",
"only exists for code reuse. It will never be an",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"self.pool_size[1], self.padding, self.strides[1] ) len_dim3 = conv_utils.conv_output_length( len_dim3, self.pool_size[2], self.padding,",
"call(self, inputs): pool_shape = (1,) + self.pool_size + (1,) strides",
"============================================================================== \"\"\"Private base class for pooling 3D layers.\"\"\" import tensorflow.compat.v2",
"reuse. It will never be an exposed API. Args: pool_function:",
"[input_shape[0], input_shape[1], len_dim1, len_dim2, len_dim3] ) else: return tf.TensorShape( [input_shape[0],",
"inputs = tf.transpose(inputs, (0, 2, 3, 4, 1)) outputs =",
"for arbitrary pooling functions, for 3D inputs. This class only",
"= conv_utils.normalize_padding(padding) self.data_format = conv_utils.normalize_data_format(data_format) self.input_spec = InputSpec(ndim=5) def call(self,",
"the size of the pooling window. Can be a single",
"# TF does not support `channels_first` with 3D pooling operations,",
"# TODO(fchollet): remove this when TF pooling is feature-complete. inputs",
"(0, 4, 1, 2, 3)) return outputs def compute_output_shape(self, input_shape):",
"input_shape[1], len_dim1, len_dim2, len_dim3] ) else: return tf.TensorShape( [input_shape[0], len_dim1,",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"tuple/list of 3 integers: (pool_depth, pool_height, pool_width) specifying the size",
"def get_config(self): config = { \"pool_size\": self.pool_size, \"padding\": self.padding, \"strides\":",
"else: len_dim1 = input_shape[1] len_dim2 = input_shape[2] len_dim3 = input_shape[3]",
"conv_utils class Pooling3D(Layer): \"\"\"Pooling layer for arbitrary pooling functions, for",
"len_dim2, len_dim3] ) else: return tf.TensorShape( [input_shape[0], len_dim1, len_dim2, len_dim3,",
"= { \"pool_size\": self.pool_size, \"padding\": self.padding, \"strides\": self.strides, \"data_format\": self.data_format,",
"or implied. # See the License for the specific language",
"Rights Reserved. # # Licensed under the Apache License, Version",
"specifying the size of the pooling window. Can be a",
"depth, height, width)`. name: A string, the name of the",
"KIND, either express or implied. # See the License for",
"specific language governing permissions and # limitations under the License.",
"layer for arbitrary pooling functions, for 3D inputs. This class",
"if self.data_format == \"channels_first\": len_dim1 = input_shape[2] len_dim2 = input_shape[3]",
"= (1,) + self.strides + (1,) if self.data_format == \"channels_first\":",
"(1,) + self.pool_size + (1,) strides = (1,) + self.strides",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"pool_shape = (1,) + self.pool_size + (1,) strides = (1,)",
"input_shape[4] else: len_dim1 = input_shape[1] len_dim2 = input_shape[2] len_dim3 =",
"integer to specify the same value for all spatial dimensions.",
"self.input_spec = InputSpec(ndim=5) def call(self, inputs): pool_shape = (1,) +",
"strides: An integer or tuple/list of 3 integers, specifying the",
"(the \"License\"); # you may not use this file except",
"An integer or tuple/list of 3 integers, specifying the strides",
"+ (1,) strides = (1,) + self.strides + (1,) if",
"# you may not use this file except in compliance",
"one of `channels_last` (default) or `channels_first`. The ordering of the",
"(1,) strides = (1,) + self.strides + (1,) if self.data_format",
"input_shape[4]] ) def get_config(self): config = { \"pool_size\": self.pool_size, \"padding\":",
"`channels_first` corresponds to inputs with shape `(batch, channels, depth, height,",
"under the License. # ============================================================================== \"\"\"Private base class for pooling",
"len_dim1 = input_shape[1] len_dim2 = input_shape[2] len_dim3 = input_shape[3] len_dim1",
"the inputs. `channels_last` corresponds to inputs with shape `(batch, depth,",
"layer. \"\"\" def __init__( self, pool_function, pool_size, strides, padding=\"valid\", data_format=\"channels_last\",",
"3 integers: (pool_depth, pool_height, pool_width) specifying the size of the",
"single integer to specify the same value for all spatial",
"Copyright 2015 The TensorFlow Authors. All Rights Reserved. # #",
"if self.data_format == \"channels_first\": outputs = tf.transpose(outputs, (0, 4, 1,",
"# ============================================================================== \"\"\"Private base class for pooling 3D layers.\"\"\" import",
"**kwargs ): super().__init__(name=name, **kwargs) if data_format is None: data_format =",
"is None: strides = pool_size self.pool_function = pool_function self.pool_size =",
"'valid' or 'same'. Case-insensitive. data_format: A string, one of `channels_last`",
"# # Unless required by applicable law or agreed to",
"len_dim2 = input_shape[2] len_dim3 = input_shape[3] len_dim1 = conv_utils.conv_output_length( len_dim1,",
"tf.TensorShape(input_shape).as_list() if self.data_format == \"channels_first\": len_dim1 = input_shape[2] len_dim2 =",
"tf from keras import backend from keras.engine.base_layer import Layer from",
"depth, height, width, channels)` while `channels_first` corresponds to inputs with",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
") else: return tf.TensorShape( [input_shape[0], len_dim1, len_dim2, len_dim3, input_shape[4]] )",
"integer or tuple/list of 3 integers, specifying the strides of",
"Version 2.0 (the \"License\"); # you may not use this",
"input_shape[2] len_dim3 = input_shape[3] len_dim1 = conv_utils.conv_output_length( len_dim1, self.pool_size[0], self.padding,",
"backend.image_data_format() if strides is None: strides = pool_size self.pool_function =",
"len_dim2, len_dim3, input_shape[4]] ) def get_config(self): config = { \"pool_size\":",
"from keras.engine.base_layer import Layer from keras.engine.input_spec import InputSpec from keras.utils",
"\"channels_first\": len_dim1 = input_shape[2] len_dim2 = input_shape[3] len_dim3 = input_shape[4]",
"self.data_format == \"channels_first\": # TF does not support `channels_first` with",
"A string, the name of the layer. \"\"\" def __init__(",
"4, 1)) outputs = self.pool_function( inputs, ksize=pool_shape, strides=strides, padding=self.padding.upper(), )",
"remove this when TF pooling is feature-complete. inputs = tf.transpose(inputs,",
"implied. # See the License for the specific language governing",
"): super().__init__(name=name, **kwargs) if data_format is None: data_format = backend.image_data_format()",
"functions, for 3D inputs. This class only exists for code",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"TF pooling is feature-complete. inputs = tf.transpose(inputs, (0, 2, 3,",
"{ \"pool_size\": self.pool_size, \"padding\": self.padding, \"strides\": self.strides, \"data_format\": self.data_format, }",
"3, \"strides\", allow_zero=True ) self.padding = conv_utils.normalize_padding(padding) self.data_format = conv_utils.normalize_data_format(data_format)",
"`channels_first` with 3D pooling operations, # so we must handle",
"apply, e.g. `tf.nn.max_pool2d`. pool_size: An integer or tuple/list of 3",
"specifying the strides of the pooling operation. Can be a",
"handle this case manually. # TODO(fchollet): remove this when TF",
"3)) return outputs def compute_output_shape(self, input_shape): input_shape = tf.TensorShape(input_shape).as_list() if",
"1, 2, 3)) return outputs def compute_output_shape(self, input_shape): input_shape =",
"len_dim3, input_shape[4]] ) def get_config(self): config = { \"pool_size\": self.pool_size,",
"by applicable law or agreed to in writing, software #",
"if data_format is None: data_format = backend.image_data_format() if strides is",
"string. The padding method, either 'valid' or 'same'. Case-insensitive. data_format:",
"corresponds to inputs with shape `(batch, depth, height, width, channels)`",
"with 3D pooling operations, # so we must handle this",
") def get_config(self): config = { \"pool_size\": self.pool_size, \"padding\": self.padding,",
"keras.engine.base_layer import Layer from keras.engine.input_spec import InputSpec from keras.utils import",
"`channels_first`. The ordering of the dimensions in the inputs. `channels_last`",
"import tensorflow.compat.v2 as tf from keras import backend from keras.engine.base_layer",
"Case-insensitive. data_format: A string, one of `channels_last` (default) or `channels_first`.",
"def __init__( self, pool_function, pool_size, strides, padding=\"valid\", data_format=\"channels_last\", name=None, **kwargs",
"== \"channels_first\": len_dim1 = input_shape[2] len_dim2 = input_shape[3] len_dim3 =",
"`channels_last` corresponds to inputs with shape `(batch, depth, height, width,",
"the same value for all spatial dimensions. padding: A string.",
"input_shape): input_shape = tf.TensorShape(input_shape).as_list() if self.data_format == \"channels_first\": len_dim1 =",
"self.strides + (1,) if self.data_format == \"channels_first\": # TF does",
"conv_utils.conv_output_length( len_dim2, self.pool_size[1], self.padding, self.strides[1] ) len_dim3 = conv_utils.conv_output_length( len_dim3,",
"all spatial dimensions. strides: An integer or tuple/list of 3",
"The padding method, either 'valid' or 'same'. Case-insensitive. data_format: A",
"\"channels_first\": outputs = tf.transpose(outputs, (0, 4, 1, 2, 3)) return",
"be an exposed API. Args: pool_function: The pooling function to",
"self, pool_function, pool_size, strides, padding=\"valid\", data_format=\"channels_last\", name=None, **kwargs ): super().__init__(name=name,",
"pool_size self.pool_function = pool_function self.pool_size = conv_utils.normalize_tuple(pool_size, 3, \"pool_size\") self.strides",
"a single integer to specify the same value for all",
"inputs, ksize=pool_shape, strides=strides, padding=self.padding.upper(), ) if self.data_format == \"channels_first\": outputs",
"of 3 integers: (pool_depth, pool_height, pool_width) specifying the size of",
"the name of the layer. \"\"\" def __init__( self, pool_function,",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"Unless required by applicable law or agreed to in writing,",
"all spatial dimensions. padding: A string. The padding method, either",
"window. Can be a single integer to specify the same",
"Can be a single integer to specify the same value",
"or `channels_first`. The ordering of the dimensions in the inputs.",
"input_shape[3] len_dim3 = input_shape[4] else: len_dim1 = input_shape[1] len_dim2 =",
"the specific language governing permissions and # limitations under the",
"applicable law or agreed to in writing, software # distributed",
"input_shape[1] len_dim2 = input_shape[2] len_dim3 = input_shape[3] len_dim1 = conv_utils.conv_output_length(",
"inputs with shape `(batch, channels, depth, height, width)`. name: A",
"or 'same'. Case-insensitive. data_format: A string, one of `channels_last` (default)",
"3D pooling operations, # so we must handle this case",
"keras.engine.input_spec import InputSpec from keras.utils import conv_utils class Pooling3D(Layer): \"\"\"Pooling",
"def call(self, inputs): pool_shape = (1,) + self.pool_size + (1,)",
"the pooling window. Can be a single integer to specify",
"in writing, software # distributed under the License is distributed",
"(1,) if self.data_format == \"channels_first\": # TF does not support",
"tf.transpose(outputs, (0, 4, 1, 2, 3)) return outputs def compute_output_shape(self,",
"== \"channels_first\": outputs = tf.transpose(outputs, (0, 4, 1, 2, 3))",
"self.padding, self.strides[1] ) len_dim3 = conv_utils.conv_output_length( len_dim3, self.pool_size[2], self.padding, self.strides[2]",
"padding method, either 'valid' or 'same'. Case-insensitive. data_format: A string,",
"3D layers.\"\"\" import tensorflow.compat.v2 as tf from keras import backend",
"dimensions. padding: A string. The padding method, either 'valid' or",
"It will never be an exposed API. Args: pool_function: The",
"base class for pooling 3D layers.\"\"\" import tensorflow.compat.v2 as tf",
"self.strides[1] ) len_dim3 = conv_utils.conv_output_length( len_dim3, self.pool_size[2], self.padding, self.strides[2] )",
"class only exists for code reuse. It will never be",
"we must handle this case manually. # TODO(fchollet): remove this",
"shape `(batch, channels, depth, height, width)`. name: A string, the",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"This class only exists for code reuse. It will never",
"= input_shape[2] len_dim2 = input_shape[3] len_dim3 = input_shape[4] else: len_dim1",
"License, Version 2.0 (the \"License\"); # you may not use",
"# You may obtain a copy of the License at",
"API. Args: pool_function: The pooling function to apply, e.g. `tf.nn.max_pool2d`.",
"# limitations under the License. # ============================================================================== \"\"\"Private base class",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"Authors. All Rights Reserved. # # Licensed under the Apache",
"= backend.image_data_format() if strides is None: strides = pool_size self.pool_function",
"TF does not support `channels_first` with 3D pooling operations, #",
"\"channels_first\": # TF does not support `channels_first` with 3D pooling",
"= tf.TensorShape(input_shape).as_list() if self.data_format == \"channels_first\": len_dim1 = input_shape[2] len_dim2",
"integers: (pool_depth, pool_height, pool_width) specifying the size of the pooling",
"class Pooling3D(Layer): \"\"\"Pooling layer for arbitrary pooling functions, for 3D",
"support `channels_first` with 3D pooling operations, # so we must",
"the License for the specific language governing permissions and #",
"strides, 3, \"strides\", allow_zero=True ) self.padding = conv_utils.normalize_padding(padding) self.data_format =",
"2, 3)) return outputs def compute_output_shape(self, input_shape): input_shape = tf.TensorShape(input_shape).as_list()",
"self.padding, self.strides[0] ) len_dim2 = conv_utils.conv_output_length( len_dim2, self.pool_size[1], self.padding, self.strides[1]",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"case manually. # TODO(fchollet): remove this when TF pooling is",
"either express or implied. # See the License for the",
"self.pool_size = conv_utils.normalize_tuple(pool_size, 3, \"pool_size\") self.strides = conv_utils.normalize_tuple( strides, 3,",
"to inputs with shape `(batch, depth, height, width, channels)` while",
"this case manually. # TODO(fchollet): remove this when TF pooling",
"import conv_utils class Pooling3D(Layer): \"\"\"Pooling layer for arbitrary pooling functions,",
"4, 1, 2, 3)) return outputs def compute_output_shape(self, input_shape): input_shape",
"self.padding = conv_utils.normalize_padding(padding) self.data_format = conv_utils.normalize_data_format(data_format) self.input_spec = InputSpec(ndim=5) def",
"or tuple/list of 3 integers: (pool_depth, pool_height, pool_width) specifying the",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"inputs. `channels_last` corresponds to inputs with shape `(batch, depth, height,",
"+ self.strides + (1,) if self.data_format == \"channels_first\": # TF",
"for all spatial dimensions. padding: A string. The padding method,",
"len_dim3 = input_shape[4] else: len_dim1 = input_shape[1] len_dim2 = input_shape[2]",
"ksize=pool_shape, strides=strides, padding=self.padding.upper(), ) if self.data_format == \"channels_first\": outputs =",
"conv_utils.normalize_padding(padding) self.data_format = conv_utils.normalize_data_format(data_format) self.input_spec = InputSpec(ndim=5) def call(self, inputs):",
"data_format: A string, one of `channels_last` (default) or `channels_first`. The",
"= conv_utils.conv_output_length( len_dim2, self.pool_size[1], self.padding, self.strides[1] ) len_dim3 = conv_utils.conv_output_length(",
"conv_utils.normalize_tuple( strides, 3, \"strides\", allow_zero=True ) self.padding = conv_utils.normalize_padding(padding) self.data_format",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"exposed API. Args: pool_function: The pooling function to apply, e.g.",
") len_dim2 = conv_utils.conv_output_length( len_dim2, self.pool_size[1], self.padding, self.strides[1] ) len_dim3",
"`(batch, channels, depth, height, width)`. name: A string, the name",
"return tf.TensorShape( [input_shape[0], input_shape[1], len_dim1, len_dim2, len_dim3] ) else: return",
"self.pool_size, \"padding\": self.padding, \"strides\": self.strides, \"data_format\": self.data_format, } base_config =",
"= (1,) + self.pool_size + (1,) strides = (1,) +",
"will never be an exposed API. Args: pool_function: The pooling",
"from keras import backend from keras.engine.base_layer import Layer from keras.engine.input_spec",
"import Layer from keras.engine.input_spec import InputSpec from keras.utils import conv_utils",
") if self.data_format == \"channels_first\": return tf.TensorShape( [input_shape[0], input_shape[1], len_dim1,",
"= input_shape[1] len_dim2 = input_shape[2] len_dim3 = input_shape[3] len_dim1 =",
"conv_utils.normalize_data_format(data_format) self.input_spec = InputSpec(ndim=5) def call(self, inputs): pool_shape = (1,)",
"(pool_depth, pool_height, pool_width) specifying the size of the pooling window.",
"this when TF pooling is feature-complete. inputs = tf.transpose(inputs, (0,",
"InputSpec from keras.utils import conv_utils class Pooling3D(Layer): \"\"\"Pooling layer for",
"\"License\"); # you may not use this file except in",
"= conv_utils.normalize_tuple(pool_size, 3, \"pool_size\") self.strides = conv_utils.normalize_tuple( strides, 3, \"strides\",",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"\"padding\": self.padding, \"strides\": self.strides, \"data_format\": self.data_format, } base_config = super().get_config()",
"self.strides[2] ) if self.data_format == \"channels_first\": return tf.TensorShape( [input_shape[0], input_shape[1],",
"None: data_format = backend.image_data_format() if strides is None: strides =",
"# distributed under the License is distributed on an \"AS",
"# Unless required by applicable law or agreed to in",
"= input_shape[3] len_dim3 = input_shape[4] else: len_dim1 = input_shape[1] len_dim2",
"= pool_function self.pool_size = conv_utils.normalize_tuple(pool_size, 3, \"pool_size\") self.strides = conv_utils.normalize_tuple(",
"spatial dimensions. padding: A string. The padding method, either 'valid'",
"name=None, **kwargs ): super().__init__(name=name, **kwargs) if data_format is None: data_format",
"self.data_format = conv_utils.normalize_data_format(data_format) self.input_spec = InputSpec(ndim=5) def call(self, inputs): pool_shape",
"with shape `(batch, depth, height, width, channels)` while `channels_first` corresponds",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"never be an exposed API. Args: pool_function: The pooling function",
"The ordering of the dimensions in the inputs. `channels_last` corresponds",
"`(batch, depth, height, width, channels)` while `channels_first` corresponds to inputs",
"= input_shape[4] else: len_dim1 = input_shape[1] len_dim2 = input_shape[2] len_dim3",
"input_shape[2] len_dim2 = input_shape[3] len_dim3 = input_shape[4] else: len_dim1 =",
"You may obtain a copy of the License at #",
"== \"channels_first\": return tf.TensorShape( [input_shape[0], input_shape[1], len_dim1, len_dim2, len_dim3] )",
"for pooling 3D layers.\"\"\" import tensorflow.compat.v2 as tf from keras",
"value for all spatial dimensions. strides: An integer or tuple/list",
"# Copyright 2015 The TensorFlow Authors. All Rights Reserved. #",
"pool_size: An integer or tuple/list of 3 integers: (pool_depth, pool_height,",
"pool_size, strides, padding=\"valid\", data_format=\"channels_last\", name=None, **kwargs ): super().__init__(name=name, **kwargs) if",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"import backend from keras.engine.base_layer import Layer from keras.engine.input_spec import InputSpec",
"does not support `channels_first` with 3D pooling operations, # so",
"tf.TensorShape( [input_shape[0], input_shape[1], len_dim1, len_dim2, len_dim3] ) else: return tf.TensorShape(",
"import InputSpec from keras.utils import conv_utils class Pooling3D(Layer): \"\"\"Pooling layer",
"feature-complete. inputs = tf.transpose(inputs, (0, 2, 3, 4, 1)) outputs"
] |
[
"range(202): col = Image.open(\"frames_temp/\" + str(i + 1) + \".bmp\")",
"and resize video clip = mpy.VideoFileClip(\"smoke.mp4\") (w, h) = clip.size",
"# Convert video to frames # Make sure to install",
"cropped_clip.write_videofile('smoke-cropped.mp4') # Convert video to frames # Make sure to",
"\".bmp\") gray = col.convert('L') bw = gray.point(lambda x: 0 if",
"str(i + 1) + \".bmp\") gray = col.convert('L') bw =",
"= mpy.VideoFileClip(\"smoke.mp4\") (w, h) = clip.size cropped_clip = vfx.crop(clip, width=(h/128)*64,",
"video to frames # Make sure to install ffmpeg on",
"subprocess as sp # Crop and resize video clip =",
"in range(202): col = Image.open(\"frames_temp/\" + str(i + 1) +",
"and white bitmap for i in range(202): col = Image.open(\"frames_temp/\"",
"sp.call(cmd,shell=True) # Convert image to black and white bitmap for",
"# Convert image to black and white bitmap for i",
"ffmpeg on machine cmd='ffmpeg -i /path/to/smoke-cropped.mp4 /path/to/frames_temp/%d.bmp' sp.call(cmd,shell=True) # Convert",
"= gray.point(lambda x: 0 if x<128 else 255, '1') bw.save(\"frames/\"",
"# Make sure to install ffmpeg on machine cmd='ffmpeg -i",
"/path/to/frames_temp/%d.bmp' sp.call(cmd,shell=True) # Convert image to black and white bitmap",
"Convert video to frames # Make sure to install ffmpeg",
"if x<128 else 255, '1') bw.save(\"frames/\" + str(i) + \".bmp\")",
"sure to install ffmpeg on machine cmd='ffmpeg -i /path/to/smoke-cropped.mp4 /path/to/frames_temp/%d.bmp'",
"to install ffmpeg on machine cmd='ffmpeg -i /path/to/smoke-cropped.mp4 /path/to/frames_temp/%d.bmp' sp.call(cmd,shell=True)",
"# Crop and resize video clip = mpy.VideoFileClip(\"smoke.mp4\") (w, h)",
"+ \".bmp\") gray = col.convert('L') bw = gray.point(lambda x: 0",
"as sp # Crop and resize video clip = mpy.VideoFileClip(\"smoke.mp4\")",
"cmd='ffmpeg -i /path/to/smoke-cropped.mp4 /path/to/frames_temp/%d.bmp' sp.call(cmd,shell=True) # Convert image to black",
"x1=w/4*3-100, y1=0).resize((64, 128)) cropped_clip.write_videofile('smoke-cropped.mp4') # Convert video to frames #",
"height=h, x1=w/4*3-100, y1=0).resize((64, 128)) cropped_clip.write_videofile('smoke-cropped.mp4') # Convert video to frames",
"import subprocess as sp # Crop and resize video clip",
"gray = col.convert('L') bw = gray.point(lambda x: 0 if x<128",
"import moviepy.video.fx.all as vfx import subprocess as sp # Crop",
"= clip.size cropped_clip = vfx.crop(clip, width=(h/128)*64, height=h, x1=w/4*3-100, y1=0).resize((64, 128))",
"on machine cmd='ffmpeg -i /path/to/smoke-cropped.mp4 /path/to/frames_temp/%d.bmp' sp.call(cmd,shell=True) # Convert image",
"Make sure to install ffmpeg on machine cmd='ffmpeg -i /path/to/smoke-cropped.mp4",
"bw = gray.point(lambda x: 0 if x<128 else 255, '1')",
"col = Image.open(\"frames_temp/\" + str(i + 1) + \".bmp\") gray",
"(w, h) = clip.size cropped_clip = vfx.crop(clip, width=(h/128)*64, height=h, x1=w/4*3-100,",
"frames # Make sure to install ffmpeg on machine cmd='ffmpeg",
"+ 1) + \".bmp\") gray = col.convert('L') bw = gray.point(lambda",
"image to black and white bitmap for i in range(202):",
"128)) cropped_clip.write_videofile('smoke-cropped.mp4') # Convert video to frames # Make sure",
"clip = mpy.VideoFileClip(\"smoke.mp4\") (w, h) = clip.size cropped_clip = vfx.crop(clip,",
"to black and white bitmap for i in range(202): col",
"= col.convert('L') bw = gray.point(lambda x: 0 if x<128 else",
"i in range(202): col = Image.open(\"frames_temp/\" + str(i + 1)",
"x: 0 if x<128 else 255, '1') bw.save(\"frames/\" + str(i)",
"to frames # Make sure to install ffmpeg on machine",
"0 if x<128 else 255, '1') bw.save(\"frames/\" + str(i) +",
"moviepy.video.fx.all as vfx import subprocess as sp # Crop and",
"white bitmap for i in range(202): col = Image.open(\"frames_temp/\" +",
"width=(h/128)*64, height=h, x1=w/4*3-100, y1=0).resize((64, 128)) cropped_clip.write_videofile('smoke-cropped.mp4') # Convert video to",
"mpy.VideoFileClip(\"smoke.mp4\") (w, h) = clip.size cropped_clip = vfx.crop(clip, width=(h/128)*64, height=h,",
"y1=0).resize((64, 128)) cropped_clip.write_videofile('smoke-cropped.mp4') # Convert video to frames # Make",
"bitmap for i in range(202): col = Image.open(\"frames_temp/\" + str(i",
"resize video clip = mpy.VideoFileClip(\"smoke.mp4\") (w, h) = clip.size cropped_clip",
"+ str(i + 1) + \".bmp\") gray = col.convert('L') bw",
"Convert image to black and white bitmap for i in",
"/path/to/smoke-cropped.mp4 /path/to/frames_temp/%d.bmp' sp.call(cmd,shell=True) # Convert image to black and white",
"= Image.open(\"frames_temp/\" + str(i + 1) + \".bmp\") gray =",
"install ffmpeg on machine cmd='ffmpeg -i /path/to/smoke-cropped.mp4 /path/to/frames_temp/%d.bmp' sp.call(cmd,shell=True) #",
"-i /path/to/smoke-cropped.mp4 /path/to/frames_temp/%d.bmp' sp.call(cmd,shell=True) # Convert image to black and",
"Crop and resize video clip = mpy.VideoFileClip(\"smoke.mp4\") (w, h) =",
"for i in range(202): col = Image.open(\"frames_temp/\" + str(i +",
"= vfx.crop(clip, width=(h/128)*64, height=h, x1=w/4*3-100, y1=0).resize((64, 128)) cropped_clip.write_videofile('smoke-cropped.mp4') # Convert",
"black and white bitmap for i in range(202): col =",
"gray.point(lambda x: 0 if x<128 else 255, '1') bw.save(\"frames/\" +",
"moviepy.editor as mpy import moviepy.video.fx.all as vfx import subprocess as",
"import moviepy.editor as mpy import moviepy.video.fx.all as vfx import subprocess",
"mpy import moviepy.video.fx.all as vfx import subprocess as sp #",
"as vfx import subprocess as sp # Crop and resize",
"Image.open(\"frames_temp/\" + str(i + 1) + \".bmp\") gray = col.convert('L')",
"machine cmd='ffmpeg -i /path/to/smoke-cropped.mp4 /path/to/frames_temp/%d.bmp' sp.call(cmd,shell=True) # Convert image to",
"clip.size cropped_clip = vfx.crop(clip, width=(h/128)*64, height=h, x1=w/4*3-100, y1=0).resize((64, 128)) cropped_clip.write_videofile('smoke-cropped.mp4')",
"sp # Crop and resize video clip = mpy.VideoFileClip(\"smoke.mp4\") (w,",
"vfx import subprocess as sp # Crop and resize video",
"1) + \".bmp\") gray = col.convert('L') bw = gray.point(lambda x:",
"as mpy import moviepy.video.fx.all as vfx import subprocess as sp",
"cropped_clip = vfx.crop(clip, width=(h/128)*64, height=h, x1=w/4*3-100, y1=0).resize((64, 128)) cropped_clip.write_videofile('smoke-cropped.mp4') #",
"col.convert('L') bw = gray.point(lambda x: 0 if x<128 else 255,",
"h) = clip.size cropped_clip = vfx.crop(clip, width=(h/128)*64, height=h, x1=w/4*3-100, y1=0).resize((64,",
"<reponame>lucastan96/video2bitmap<gh_stars>1-10 import moviepy.editor as mpy import moviepy.video.fx.all as vfx import",
"video clip = mpy.VideoFileClip(\"smoke.mp4\") (w, h) = clip.size cropped_clip =",
"vfx.crop(clip, width=(h/128)*64, height=h, x1=w/4*3-100, y1=0).resize((64, 128)) cropped_clip.write_videofile('smoke-cropped.mp4') # Convert video"
] |
[
"RolodexConfig(AppConfig): name = \"ghostwriter.rolodex\" def ready(self): try: import ghostwriter.rolodex.signals #",
"\"ghostwriter.rolodex\" def ready(self): try: import ghostwriter.rolodex.signals # noqa F401 isort:skip",
"django.apps import AppConfig class RolodexConfig(AppConfig): name = \"ghostwriter.rolodex\" def ready(self):",
"Django Imports from django.apps import AppConfig class RolodexConfig(AppConfig): name =",
"ready(self): try: import ghostwriter.rolodex.signals # noqa F401 isort:skip except ImportError:",
"Imports from django.apps import AppConfig class RolodexConfig(AppConfig): name = \"ghostwriter.rolodex\"",
"# Django Imports from django.apps import AppConfig class RolodexConfig(AppConfig): name",
"AppConfig class RolodexConfig(AppConfig): name = \"ghostwriter.rolodex\" def ready(self): try: import",
"import AppConfig class RolodexConfig(AppConfig): name = \"ghostwriter.rolodex\" def ready(self): try:",
"def ready(self): try: import ghostwriter.rolodex.signals # noqa F401 isort:skip except",
"Rolodex application.\"\"\" # Django Imports from django.apps import AppConfig class",
"= \"ghostwriter.rolodex\" def ready(self): try: import ghostwriter.rolodex.signals # noqa F401",
"from django.apps import AppConfig class RolodexConfig(AppConfig): name = \"ghostwriter.rolodex\" def",
"contains the configuration of the Rolodex application.\"\"\" # Django Imports",
"class RolodexConfig(AppConfig): name = \"ghostwriter.rolodex\" def ready(self): try: import ghostwriter.rolodex.signals",
"name = \"ghostwriter.rolodex\" def ready(self): try: import ghostwriter.rolodex.signals # noqa",
"the Rolodex application.\"\"\" # Django Imports from django.apps import AppConfig",
"application.\"\"\" # Django Imports from django.apps import AppConfig class RolodexConfig(AppConfig):",
"the configuration of the Rolodex application.\"\"\" # Django Imports from",
"of the Rolodex application.\"\"\" # Django Imports from django.apps import",
"try: import ghostwriter.rolodex.signals # noqa F401 isort:skip except ImportError: pass",
"\"\"\"This contains the configuration of the Rolodex application.\"\"\" # Django",
"configuration of the Rolodex application.\"\"\" # Django Imports from django.apps"
] |
[
"import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies",
"migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('boards', '0023_alter_image_type'), ] operations = [ migrations.AddField( model_name='boardpreferences', name='moderators',",
"# Generated by Django 4.0.3 on 2022-03-01 14:42 from django.conf",
"by Django 4.0.3 on 2022-03-01 14:42 from django.conf import settings",
"settings from django.db import migrations, models class Migration(migrations.Migration): dependencies =",
"on 2022-03-01 14:42 from django.conf import settings from django.db import",
"('boards', '0023_alter_image_type'), ] operations = [ migrations.AddField( model_name='boardpreferences', name='moderators', field=models.ManyToManyField(blank=True,",
"import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('boards',",
"4.0.3 on 2022-03-01 14:42 from django.conf import settings from django.db",
"from django.db import migrations, models class Migration(migrations.Migration): dependencies = [",
"class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('boards', '0023_alter_image_type'), ] operations",
"operations = [ migrations.AddField( model_name='boardpreferences', name='moderators', field=models.ManyToManyField(blank=True, related_name='moderated_boards', to=settings.AUTH_USER_MODEL), ),",
"dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('boards', '0023_alter_image_type'), ] operations = [",
"= [ migrations.AddField( model_name='boardpreferences', name='moderators', field=models.ManyToManyField(blank=True, related_name='moderated_boards', to=settings.AUTH_USER_MODEL), ), ]",
"django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL),",
"Django 4.0.3 on 2022-03-01 14:42 from django.conf import settings from",
"'0023_alter_image_type'), ] operations = [ migrations.AddField( model_name='boardpreferences', name='moderators', field=models.ManyToManyField(blank=True, related_name='moderated_boards',",
"] operations = [ migrations.AddField( model_name='boardpreferences', name='moderators', field=models.ManyToManyField(blank=True, related_name='moderated_boards', to=settings.AUTH_USER_MODEL),",
"2022-03-01 14:42 from django.conf import settings from django.db import migrations,",
"14:42 from django.conf import settings from django.db import migrations, models",
"= [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('boards', '0023_alter_image_type'), ] operations = [ migrations.AddField(",
"[ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('boards', '0023_alter_image_type'), ] operations = [ migrations.AddField( model_name='boardpreferences',",
"<filename>boards/migrations/0024_boardpreferences_moderators.py # Generated by Django 4.0.3 on 2022-03-01 14:42 from",
"from django.conf import settings from django.db import migrations, models class",
"Generated by Django 4.0.3 on 2022-03-01 14:42 from django.conf import",
"models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('boards', '0023_alter_image_type'), ]",
"Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('boards', '0023_alter_image_type'), ] operations =",
"django.conf import settings from django.db import migrations, models class Migration(migrations.Migration):",
"migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('boards', '0023_alter_image_type'),"
] |
[
"@author: Michal.Busta at gmail.com ''' #get rid of the optimizer",
"torch MODEL_PATH = '/models/model-b2-2.pth' state = torch.load(MODEL_PATH, map_location=lambda storage, loc:",
"MODEL_PATH = '/models/model-b2-2.pth' state = torch.load(MODEL_PATH, map_location=lambda storage, loc: storage)",
"state ... import torch MODEL_PATH = '/models/model-b2-2.pth' state = torch.load(MODEL_PATH,",
"map_location=lambda storage, loc: storage) state_out = { \"state_dict\": state[\"state_dict\"], }",
"''' #get rid of the optimizer state ... import torch",
"optimizer state ... import torch MODEL_PATH = '/models/model-b2-2.pth' state =",
"import torch MODEL_PATH = '/models/model-b2-2.pth' state = torch.load(MODEL_PATH, map_location=lambda storage,",
"<filename>models/minimize_model.py ''' Created on Mar 22, 2020 @author: Michal.Busta at",
"Mar 22, 2020 @author: Michal.Busta at gmail.com ''' #get rid",
"2020 @author: Michal.Busta at gmail.com ''' #get rid of the",
"gmail.com ''' #get rid of the optimizer state ... import",
"#get rid of the optimizer state ... import torch MODEL_PATH",
"rid of the optimizer state ... import torch MODEL_PATH =",
"... import torch MODEL_PATH = '/models/model-b2-2.pth' state = torch.load(MODEL_PATH, map_location=lambda",
"storage, loc: storage) state_out = { \"state_dict\": state[\"state_dict\"], } torch.save(state_out,",
"Created on Mar 22, 2020 @author: Michal.Busta at gmail.com '''",
"torch.load(MODEL_PATH, map_location=lambda storage, loc: storage) state_out = { \"state_dict\": state[\"state_dict\"],",
"''' Created on Mar 22, 2020 @author: Michal.Busta at gmail.com",
"the optimizer state ... import torch MODEL_PATH = '/models/model-b2-2.pth' state",
"Michal.Busta at gmail.com ''' #get rid of the optimizer state",
"22, 2020 @author: Michal.Busta at gmail.com ''' #get rid of",
"at gmail.com ''' #get rid of the optimizer state ...",
"of the optimizer state ... import torch MODEL_PATH = '/models/model-b2-2.pth'",
"'/models/model-b2-2.pth' state = torch.load(MODEL_PATH, map_location=lambda storage, loc: storage) state_out =",
"loc: storage) state_out = { \"state_dict\": state[\"state_dict\"], } torch.save(state_out, 'model-b2-2.pth')",
"= torch.load(MODEL_PATH, map_location=lambda storage, loc: storage) state_out = { \"state_dict\":",
"on Mar 22, 2020 @author: Michal.Busta at gmail.com ''' #get",
"= '/models/model-b2-2.pth' state = torch.load(MODEL_PATH, map_location=lambda storage, loc: storage) state_out",
"state = torch.load(MODEL_PATH, map_location=lambda storage, loc: storage) state_out = {"
] |
[
":: Utilities\", \"Topic :: Software Development :: Version Control ::",
"\"Intended Audience :: Developers\", \"Topic :: Utilities\", \"Topic :: Software",
"4 - Beta\", \"Environment :: Console\", \"Intended Audience :: Developers\",",
"\"Environment :: Console\", \"Intended Audience :: Developers\", \"Topic :: Utilities\",",
"read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=\"braumeister\", packages=[\"braumeister\", \"braumeister.actions\"], version=version, author=\"<NAME>\",",
"JIRA and git\", long_description=read('README.md'), license=\"MIT\", keywords=\"git jira release\", url=\"https://www.talentsconnect.com\", include_package_data=True,",
"entry_points={ 'console_scripts': [\"braumeister = braumeister.braumeister:main\"] }, python_requires='!=2.7, !=3.4, >=3.5', zip_safe=False,",
":: Developers\", \"Topic :: Utilities\", \"Topic :: Software Development ::",
"= braumeister.braumeister:main\"] }, python_requires='!=2.7, !=3.4, >=3.5', zip_safe=False, classifiers=[ \"Development Status",
"Console\", \"Intended Audience :: Developers\", \"Topic :: Utilities\", \"Topic ::",
"open('braumeister/braumeister.py').read(), re.M ).group(1) def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=\"braumeister\",",
">=3.5', zip_safe=False, classifiers=[ \"Development Status :: 4 - Beta\", \"Environment",
"setuptools import setup version = re.search( '^__version__\\s*=\\s*\"(.*)\"', open('braumeister/braumeister.py').read(), re.M ).group(1)",
"open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=\"braumeister\", packages=[\"braumeister\", \"braumeister.actions\"], version=version, author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Easy",
"bulding, combining JIRA and git\", long_description=read('README.md'), license=\"MIT\", keywords=\"git jira release\",",
"Audience :: Developers\", \"Topic :: Utilities\", \"Topic :: Software Development",
"\"Topic :: Utilities\", \"Topic :: Software Development :: Version Control",
":: Console\", \"Intended Audience :: Developers\", \"Topic :: Utilities\", \"Topic",
"release bulding, combining JIRA and git\", long_description=read('README.md'), license=\"MIT\", keywords=\"git jira",
"combining JIRA and git\", long_description=read('README.md'), license=\"MIT\", keywords=\"git jira release\", url=\"https://www.talentsconnect.com\",",
"author_email=\"<EMAIL>\", description=\"Easy release bulding, combining JIRA and git\", long_description=read('README.md'), license=\"MIT\",",
"name=\"braumeister\", packages=[\"braumeister\", \"braumeister.actions\"], version=version, author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Easy release bulding, combining",
"url=\"https://www.talentsconnect.com\", include_package_data=True, install_requires=['requests', 'colorama'], entry_points={ 'console_scripts': [\"braumeister = braumeister.braumeister:main\"] },",
"include_package_data=True, install_requires=['requests', 'colorama'], entry_points={ 'console_scripts': [\"braumeister = braumeister.braumeister:main\"] }, python_requires='!=2.7,",
"license=\"MIT\", keywords=\"git jira release\", url=\"https://www.talentsconnect.com\", include_package_data=True, install_requires=['requests', 'colorama'], entry_points={ 'console_scripts':",
"\"Topic :: Software Development :: Version Control :: Git\" ],",
"\"braumeister.actions\"], version=version, author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Easy release bulding, combining JIRA and",
"import os import re from setuptools import setup version =",
"version = re.search( '^__version__\\s*=\\s*\"(.*)\"', open('braumeister/braumeister.py').read(), re.M ).group(1) def read(fname): return",
"description=\"Easy release bulding, combining JIRA and git\", long_description=read('README.md'), license=\"MIT\", keywords=\"git",
"= re.search( '^__version__\\s*=\\s*\"(.*)\"', open('braumeister/braumeister.py').read(), re.M ).group(1) def read(fname): return open(os.path.join(os.path.dirname(__file__),",
"\"Development Status :: 4 - Beta\", \"Environment :: Console\", \"Intended",
"fname)).read() setup( name=\"braumeister\", packages=[\"braumeister\", \"braumeister.actions\"], version=version, author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Easy release",
"zip_safe=False, classifiers=[ \"Development Status :: 4 - Beta\", \"Environment ::",
"'colorama'], entry_points={ 'console_scripts': [\"braumeister = braumeister.braumeister:main\"] }, python_requires='!=2.7, !=3.4, >=3.5',",
"git\", long_description=read('README.md'), license=\"MIT\", keywords=\"git jira release\", url=\"https://www.talentsconnect.com\", include_package_data=True, install_requires=['requests', 'colorama'],",
"Developers\", \"Topic :: Utilities\", \"Topic :: Software Development :: Version",
"Utilities\", \"Topic :: Software Development :: Version Control :: Git\"",
"install_requires=['requests', 'colorama'], entry_points={ 'console_scripts': [\"braumeister = braumeister.braumeister:main\"] }, python_requires='!=2.7, !=3.4,",
"import re from setuptools import setup version = re.search( '^__version__\\s*=\\s*\"(.*)\"',",
"setup version = re.search( '^__version__\\s*=\\s*\"(.*)\"', open('braumeister/braumeister.py').read(), re.M ).group(1) def read(fname):",
"classifiers=[ \"Development Status :: 4 - Beta\", \"Environment :: Console\",",
"'console_scripts': [\"braumeister = braumeister.braumeister:main\"] }, python_requires='!=2.7, !=3.4, >=3.5', zip_safe=False, classifiers=[",
"Beta\", \"Environment :: Console\", \"Intended Audience :: Developers\", \"Topic ::",
"!=3.4, >=3.5', zip_safe=False, classifiers=[ \"Development Status :: 4 - Beta\",",
"jira release\", url=\"https://www.talentsconnect.com\", include_package_data=True, install_requires=['requests', 'colorama'], entry_points={ 'console_scripts': [\"braumeister =",
"braumeister.braumeister:main\"] }, python_requires='!=2.7, !=3.4, >=3.5', zip_safe=False, classifiers=[ \"Development Status ::",
"packages=[\"braumeister\", \"braumeister.actions\"], version=version, author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Easy release bulding, combining JIRA",
"release\", url=\"https://www.talentsconnect.com\", include_package_data=True, install_requires=['requests', 'colorama'], entry_points={ 'console_scripts': [\"braumeister = braumeister.braumeister:main\"]",
"[\"braumeister = braumeister.braumeister:main\"] }, python_requires='!=2.7, !=3.4, >=3.5', zip_safe=False, classifiers=[ \"Development",
").group(1) def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=\"braumeister\", packages=[\"braumeister\", \"braumeister.actions\"],",
"import setup version = re.search( '^__version__\\s*=\\s*\"(.*)\"', open('braumeister/braumeister.py').read(), re.M ).group(1) def",
"- Beta\", \"Environment :: Console\", \"Intended Audience :: Developers\", \"Topic",
":: 4 - Beta\", \"Environment :: Console\", \"Intended Audience ::",
"long_description=read('README.md'), license=\"MIT\", keywords=\"git jira release\", url=\"https://www.talentsconnect.com\", include_package_data=True, install_requires=['requests', 'colorama'], entry_points={",
"and git\", long_description=read('README.md'), license=\"MIT\", keywords=\"git jira release\", url=\"https://www.talentsconnect.com\", include_package_data=True, install_requires=['requests',",
"re.M ).group(1) def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=\"braumeister\", packages=[\"braumeister\",",
"os import re from setuptools import setup version = re.search(",
"setup( name=\"braumeister\", packages=[\"braumeister\", \"braumeister.actions\"], version=version, author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Easy release bulding,",
"def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=\"braumeister\", packages=[\"braumeister\", \"braumeister.actions\"], version=version,",
"'^__version__\\s*=\\s*\"(.*)\"', open('braumeister/braumeister.py').read(), re.M ).group(1) def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(",
"author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Easy release bulding, combining JIRA and git\", long_description=read('README.md'),",
"}, python_requires='!=2.7, !=3.4, >=3.5', zip_safe=False, classifiers=[ \"Development Status :: 4",
"keywords=\"git jira release\", url=\"https://www.talentsconnect.com\", include_package_data=True, install_requires=['requests', 'colorama'], entry_points={ 'console_scripts': [\"braumeister",
"python_requires='!=2.7, !=3.4, >=3.5', zip_safe=False, classifiers=[ \"Development Status :: 4 -",
":: Software Development :: Version Control :: Git\" ], )",
"re.search( '^__version__\\s*=\\s*\"(.*)\"', open('braumeister/braumeister.py').read(), re.M ).group(1) def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read()",
"version=version, author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Easy release bulding, combining JIRA and git\",",
"re from setuptools import setup version = re.search( '^__version__\\s*=\\s*\"(.*)\"', open('braumeister/braumeister.py').read(),",
"Status :: 4 - Beta\", \"Environment :: Console\", \"Intended Audience",
"return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=\"braumeister\", packages=[\"braumeister\", \"braumeister.actions\"], version=version, author=\"<NAME>\", author_email=\"<EMAIL>\",",
"from setuptools import setup version = re.search( '^__version__\\s*=\\s*\"(.*)\"', open('braumeister/braumeister.py').read(), re.M"
] |
[
"epoch): # inverse normalization of the images along with channel",
"output_on_random_product.cpu().numpy() for i in range(batch_size): self._save_image_sheet( batch_index*config.PARAMS[\"batch_size\"] + i, model_apparel[i],",
"output_on_random_product[i], epoch) def _save_image_sheet(self, idx, model_apparel, warped_image, model_image, warped_model_image, random_product_image,",
"local imports import config from . import utils from .",
"np from PIL import Image import torch.nn as nn from",
"= warped_image.shape[0] model_apparel = model_apparel.cpu().numpy() warped_image = warped_image.cpu().numpy() model_image =",
"utils from . import geometric_transformer class GeoTransformationInfer(nn.Module): def __init__(self, output_dir=\"./output/results\"):",
"[0.485, 0.456, 0.406] model_apparel = Image.fromarray(np.uint8(model_apparel * 255)) warped_image =",
"imports import config from . import utils from . import",
"= Image.fromarray(np.uint8(model_apparel * 255)) warped_image = np.moveaxis(warped_image, 0, 2) *",
"0.224, 0.225] + [0.485, 0.456, 0.406] model_image = Image.fromarray(np.uint8(model_image *",
"* [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] random_product_image =",
"'white') sheet.paste(model_apparel, (0, 0)) sheet.paste(warped_image, (224, 0)) sheet.paste(model_image, (448, 0))",
"for saving model_apparel = np.moveaxis(model_apparel, 0, 2) * [0.229, 0.224,",
"PIL import Image import torch.nn as nn from torchvision import",
"last steps and finally converting np array to pillow format",
"sheet.paste(random_product_image_warped, (1120, 0)) sheet.paste(output_on_random_product, (1344, 0)) sheet.save(os.path.join(self.output_dir, \"image_sheet_{}-epoch{}\".format(idx, str(epoch).zfill(3)) +",
"def _save_image_sheet(self, idx, model_apparel, warped_image, model_image, warped_model_image, random_product_image, random_product_image_warped, output_on_random_product,",
"os # third party imports import numpy as np from",
"torchvision import transforms # local imports import config from .",
"# standard library imports import os # third party imports",
"model_apparel.cpu().numpy() warped_image = warped_image.cpu().numpy() model_image = model_image.cpu().numpy() warped_model_image = warped_model_image.cpu().numpy()",
"warped_image.cpu().numpy() model_image = model_image.cpu().numpy() warped_model_image = warped_model_image.cpu().numpy() random_product_image = random_product_image.cpu().numpy()",
"[0.485, 0.456, 0.406] random_product_image = Image.fromarray(np.uint8(random_product_image * 255)) random_product_image_warped =",
"output_dir=\"./output/results\"): super(GeoTransformationInfer, self).__init__() self.output_dir = output_dir utils.ensure_folder(self.output_dir) def forward(self, model_apparel,",
"2) * [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] warped_image",
"0, 2) * [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406]",
"to channel last steps and finally converting np array to",
"* [0.229, 0.224, 0.225] + (0.485, 0.456, 0.406) random_product_image_warped =",
"model_apparel, warped_image, model_image, warped_model_image, random_product_image, random_product_image_warped, output_on_random_product, epoch): # inverse",
"converting np array to pillow format for saving model_apparel =",
"warped_model_image = warped_model_image.cpu().numpy() random_product_image = random_product_image.cpu().numpy() random_product_image_warped = random_product_image_warped.cpu().numpy() output_on_random_product",
"np.moveaxis(warped_model_image, 0, 2) * [0.229, 0.224, 0.225] + [0.485, 0.456,",
"nn from torchvision import transforms # local imports import config",
"from torchvision import transforms # local imports import config from",
"import config from . import utils from . import geometric_transformer",
"0.225] + [0.485, 0.456, 0.406] output_on_random_product = Image.fromarray(np.uint8(output_on_random_product * 255))",
"[0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] output_on_random_product = Image.fromarray(np.uint8(output_on_random_product",
"255)) sheet = Image.new('RGB', (1568, 224), 'white') sheet.paste(model_apparel, (0, 0))",
"sheet = Image.new('RGB', (1568, 224), 'white') sheet.paste(model_apparel, (0, 0)) sheet.paste(warped_image,",
"utils.ensure_folder(self.output_dir) def forward(self, model_apparel, warped_image, model_image, warped_model_image, random_product_image, random_product_image_warped, output_on_random_product,",
". import geometric_transformer class GeoTransformationInfer(nn.Module): def __init__(self, output_dir=\"./output/results\"): super(GeoTransformationInfer, self).__init__()",
"with channel first to channel last steps and finally converting",
"0.456, 0.406] output_on_random_product = Image.fromarray(np.uint8(output_on_random_product * 255)) sheet = Image.new('RGB',",
"0.224, 0.225] + (0.485, 0.456, 0.406) random_product_image_warped = Image.fromarray(np.uint8(random_product_image_warped *",
"(1568, 224), 'white') sheet.paste(model_apparel, (0, 0)) sheet.paste(warped_image, (224, 0)) sheet.paste(model_image,",
"[0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] model_image = Image.fromarray(np.uint8(model_image",
"array to pillow format for saving model_apparel = np.moveaxis(model_apparel, 0,",
"* 255)) random_product_image = np.moveaxis(random_product_image, 0, 2) * [0.229, 0.224,",
"0, 2) * [0.229, 0.224, 0.225] + (0.485, 0.456, 0.406)",
"model_image = Image.fromarray(np.uint8(model_image * 255)) warped_model_image = np.moveaxis(warped_model_image, 0, 2)",
"output_on_random_product = np.moveaxis(output_on_random_product, 0, 2) * [0.229, 0.224, 0.225] +",
"import os # third party imports import numpy as np",
"Image import torch.nn as nn from torchvision import transforms #",
"range(batch_size): self._save_image_sheet( batch_index*config.PARAMS[\"batch_size\"] + i, model_apparel[i], warped_image[i], model_image[i], warped_model_image[i], random_product_image[i],",
"+ [0.485, 0.456, 0.406] warped_model_image = Image.fromarray(np.uint8(warped_model_image * 255)) random_product_image",
"np.moveaxis(random_product_image, 0, 2) * [0.229, 0.224, 0.225] + [0.485, 0.456,",
"of the images along with channel first to channel last",
"[0.485, 0.456, 0.406] model_image = Image.fromarray(np.uint8(model_image * 255)) warped_model_image =",
"idx, model_apparel, warped_image, model_image, warped_model_image, random_product_image, random_product_image_warped, output_on_random_product, epoch): #",
"= output_on_random_product.cpu().numpy() for i in range(batch_size): self._save_image_sheet( batch_index*config.PARAMS[\"batch_size\"] + i,",
"* [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] model_image =",
"* 255)) warped_model_image = np.moveaxis(warped_model_image, 0, 2) * [0.229, 0.224,",
"0.224, 0.225] + [0.485, 0.456, 0.406] random_product_image = Image.fromarray(np.uint8(random_product_image *",
"0)) sheet.paste(warped_model_image, (672, 0)) sheet.paste(random_product_image, (896, 0)) sheet.paste(random_product_image_warped, (1120, 0))",
"np.moveaxis(random_product_image_warped, 0, 2) * [0.229, 0.224, 0.225] + (0.485, 0.456,",
"model_apparel = Image.fromarray(np.uint8(model_apparel * 255)) warped_image = np.moveaxis(warped_image, 0, 2)",
"sheet.paste(warped_model_image, (672, 0)) sheet.paste(random_product_image, (896, 0)) sheet.paste(random_product_image_warped, (1120, 0)) sheet.paste(output_on_random_product,",
"output_on_random_product, epoch): # inverse normalization of the images along with",
"warped_model_image.cpu().numpy() random_product_image = random_product_image.cpu().numpy() random_product_image_warped = random_product_image_warped.cpu().numpy() output_on_random_product = output_on_random_product.cpu().numpy()",
"np.moveaxis(model_apparel, 0, 2) * [0.229, 0.224, 0.225] + [0.485, 0.456,",
"random_product_image = Image.fromarray(np.uint8(random_product_image * 255)) random_product_image_warped = np.moveaxis(random_product_image_warped, 0, 2)",
"0.225] + [0.485, 0.456, 0.406] model_image = Image.fromarray(np.uint8(model_image * 255))",
"model_apparel = model_apparel.cpu().numpy() warped_image = warped_image.cpu().numpy() model_image = model_image.cpu().numpy() warped_model_image",
"random_product_image, random_product_image_warped, output_on_random_product, epoch): # inverse normalization of the images",
"import transforms # local imports import config from . import",
"0.456, 0.406] model_apparel = Image.fromarray(np.uint8(model_apparel * 255)) warped_image = np.moveaxis(warped_image,",
"random_product_image = np.moveaxis(random_product_image, 0, 2) * [0.229, 0.224, 0.225] +",
"as np from PIL import Image import torch.nn as nn",
"forward(self, model_apparel, warped_image, model_image, warped_model_image, random_product_image, random_product_image_warped, output_on_random_product, batch_index, epoch):",
"model_image, warped_model_image, random_product_image, random_product_image_warped, output_on_random_product, batch_index, epoch): batch_size = warped_image.shape[0]",
"= np.moveaxis(output_on_random_product, 0, 2) * [0.229, 0.224, 0.225] + [0.485,",
"images along with channel first to channel last steps and",
"numpy as np from PIL import Image import torch.nn as",
"def forward(self, model_apparel, warped_image, model_image, warped_model_image, random_product_image, random_product_image_warped, output_on_random_product, batch_index,",
"255)) random_product_image_warped = np.moveaxis(random_product_image_warped, 0, 2) * [0.229, 0.224, 0.225]",
"sheet.paste(model_image, (448, 0)) sheet.paste(warped_model_image, (672, 0)) sheet.paste(random_product_image, (896, 0)) sheet.paste(random_product_image_warped,",
"+ [0.485, 0.456, 0.406] model_apparel = Image.fromarray(np.uint8(model_apparel * 255)) warped_image",
"* [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] output_on_random_product =",
"0.224, 0.225] + [0.485, 0.456, 0.406] model_apparel = Image.fromarray(np.uint8(model_apparel *",
"0.224, 0.225] + [0.485, 0.456, 0.406] output_on_random_product = Image.fromarray(np.uint8(output_on_random_product *",
"random_product_image_warped = random_product_image_warped.cpu().numpy() output_on_random_product = output_on_random_product.cpu().numpy() for i in range(batch_size):",
"from . import utils from . import geometric_transformer class GeoTransformationInfer(nn.Module):",
"sheet.paste(random_product_image, (896, 0)) sheet.paste(random_product_image_warped, (1120, 0)) sheet.paste(output_on_random_product, (1344, 0)) sheet.save(os.path.join(self.output_dir,",
"= Image.fromarray(np.uint8(random_product_image * 255)) random_product_image_warped = np.moveaxis(random_product_image_warped, 0, 2) *",
"0)) sheet.paste(warped_image, (224, 0)) sheet.paste(model_image, (448, 0)) sheet.paste(warped_model_image, (672, 0))",
"(1120, 0)) sheet.paste(output_on_random_product, (1344, 0)) sheet.save(os.path.join(self.output_dir, \"image_sheet_{}-epoch{}\".format(idx, str(epoch).zfill(3)) + \".jpg\"))",
"self).__init__() self.output_dir = output_dir utils.ensure_folder(self.output_dir) def forward(self, model_apparel, warped_image, model_image,",
"warped_model_image = np.moveaxis(warped_model_image, 0, 2) * [0.229, 0.224, 0.225] +",
"= Image.fromarray(np.uint8(warped_image * 255)) model_image = np.moveaxis(model_image, 0, 2) *",
"random_product_image_warped.cpu().numpy() output_on_random_product = output_on_random_product.cpu().numpy() for i in range(batch_size): self._save_image_sheet( batch_index*config.PARAMS[\"batch_size\"]",
"in range(batch_size): self._save_image_sheet( batch_index*config.PARAMS[\"batch_size\"] + i, model_apparel[i], warped_image[i], model_image[i], warped_model_image[i],",
"0.456, 0.406] warped_image = Image.fromarray(np.uint8(warped_image * 255)) model_image = np.moveaxis(model_image,",
"= Image.fromarray(np.uint8(model_image * 255)) warped_model_image = np.moveaxis(warped_model_image, 0, 2) *",
"= np.moveaxis(model_apparel, 0, 2) * [0.229, 0.224, 0.225] + [0.485,",
"+ [0.485, 0.456, 0.406] warped_image = Image.fromarray(np.uint8(warped_image * 255)) model_image",
"[0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] warped_model_image = Image.fromarray(np.uint8(warped_model_image",
"0.456, 0.406] random_product_image = Image.fromarray(np.uint8(random_product_image * 255)) random_product_image_warped = np.moveaxis(random_product_image_warped,",
"* 255)) sheet = Image.new('RGB', (1568, 224), 'white') sheet.paste(model_apparel, (0,",
"[0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] random_product_image = Image.fromarray(np.uint8(random_product_image",
"model_apparel = np.moveaxis(model_apparel, 0, 2) * [0.229, 0.224, 0.225] +",
"(448, 0)) sheet.paste(warped_model_image, (672, 0)) sheet.paste(random_product_image, (896, 0)) sheet.paste(random_product_image_warped, (1120,",
"import Image import torch.nn as nn from torchvision import transforms",
"warped_image = np.moveaxis(warped_image, 0, 2) * [0.229, 0.224, 0.225] +",
"2) * [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] model_image",
"config from . import utils from . import geometric_transformer class",
"batch_size = warped_image.shape[0] model_apparel = model_apparel.cpu().numpy() warped_image = warped_image.cpu().numpy() model_image",
"Image.fromarray(np.uint8(model_apparel * 255)) warped_image = np.moveaxis(warped_image, 0, 2) * [0.229,",
"party imports import numpy as np from PIL import Image",
"_save_image_sheet(self, idx, model_apparel, warped_image, model_image, warped_model_image, random_product_image, random_product_image_warped, output_on_random_product, epoch):",
"[0.485, 0.456, 0.406] warped_image = Image.fromarray(np.uint8(warped_image * 255)) model_image =",
"random_product_image.cpu().numpy() random_product_image_warped = random_product_image_warped.cpu().numpy() output_on_random_product = output_on_random_product.cpu().numpy() for i in",
"format for saving model_apparel = np.moveaxis(model_apparel, 0, 2) * [0.229,",
"* 255)) model_image = np.moveaxis(model_image, 0, 2) * [0.229, 0.224,",
"(224, 0)) sheet.paste(model_image, (448, 0)) sheet.paste(warped_model_image, (672, 0)) sheet.paste(random_product_image, (896,",
"# inverse normalization of the images along with channel first",
"pillow format for saving model_apparel = np.moveaxis(model_apparel, 0, 2) *",
"i in range(batch_size): self._save_image_sheet( batch_index*config.PARAMS[\"batch_size\"] + i, model_apparel[i], warped_image[i], model_image[i],",
"* [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] warped_model_image =",
"warped_model_image = Image.fromarray(np.uint8(warped_model_image * 255)) random_product_image = np.moveaxis(random_product_image, 0, 2)",
"[0.229, 0.224, 0.225] + (0.485, 0.456, 0.406) random_product_image_warped = Image.fromarray(np.uint8(random_product_image_warped",
"Image.fromarray(np.uint8(random_product_image_warped * 255)) output_on_random_product = np.moveaxis(output_on_random_product, 0, 2) * [0.229,",
"self.output_dir = output_dir utils.ensure_folder(self.output_dir) def forward(self, model_apparel, warped_image, model_image, warped_model_image,",
"= model_image.cpu().numpy() warped_model_image = warped_model_image.cpu().numpy() random_product_image = random_product_image.cpu().numpy() random_product_image_warped =",
"finally converting np array to pillow format for saving model_apparel",
"import torch.nn as nn from torchvision import transforms # local",
"# third party imports import numpy as np from PIL",
"= np.moveaxis(warped_image, 0, 2) * [0.229, 0.224, 0.225] + [0.485,",
"# local imports import config from . import utils from",
"0.406) random_product_image_warped = Image.fromarray(np.uint8(random_product_image_warped * 255)) output_on_random_product = np.moveaxis(output_on_random_product, 0,",
"0.456, 0.406] warped_model_image = Image.fromarray(np.uint8(warped_model_image * 255)) random_product_image = np.moveaxis(random_product_image,",
"255)) output_on_random_product = np.moveaxis(output_on_random_product, 0, 2) * [0.229, 0.224, 0.225]",
"0.224, 0.225] + [0.485, 0.456, 0.406] warped_image = Image.fromarray(np.uint8(warped_image *",
"255)) warped_image = np.moveaxis(warped_image, 0, 2) * [0.229, 0.224, 0.225]",
"model_apparel[i], warped_image[i], model_image[i], warped_model_image[i], random_product_image[i], random_product_image_warped[i], output_on_random_product[i], epoch) def _save_image_sheet(self,",
"[0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] warped_image = Image.fromarray(np.uint8(warped_image",
"0)) sheet.paste(model_image, (448, 0)) sheet.paste(warped_model_image, (672, 0)) sheet.paste(random_product_image, (896, 0))",
"[0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] model_apparel = Image.fromarray(np.uint8(model_apparel",
"= model_apparel.cpu().numpy() warped_image = warped_image.cpu().numpy() model_image = model_image.cpu().numpy() warped_model_image =",
"= np.moveaxis(warped_model_image, 0, 2) * [0.229, 0.224, 0.225] + [0.485,",
"standard library imports import os # third party imports import",
"class GeoTransformationInfer(nn.Module): def __init__(self, output_dir=\"./output/results\"): super(GeoTransformationInfer, self).__init__() self.output_dir = output_dir",
"model_apparel, warped_image, model_image, warped_model_image, random_product_image, random_product_image_warped, output_on_random_product, batch_index, epoch): batch_size",
"* 255)) warped_image = np.moveaxis(warped_image, 0, 2) * [0.229, 0.224,",
"(0.485, 0.456, 0.406) random_product_image_warped = Image.fromarray(np.uint8(random_product_image_warped * 255)) output_on_random_product =",
"np.moveaxis(output_on_random_product, 0, 2) * [0.229, 0.224, 0.225] + [0.485, 0.456,",
"as nn from torchvision import transforms # local imports import",
"model_image = model_image.cpu().numpy() warped_model_image = warped_model_image.cpu().numpy() random_product_image = random_product_image.cpu().numpy() random_product_image_warped",
"255)) random_product_image = np.moveaxis(random_product_image, 0, 2) * [0.229, 0.224, 0.225]",
"warped_image = Image.fromarray(np.uint8(warped_image * 255)) model_image = np.moveaxis(model_image, 0, 2)",
"warped_image.shape[0] model_apparel = model_apparel.cpu().numpy() warped_image = warped_image.cpu().numpy() model_image = model_image.cpu().numpy()",
"2) * [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] random_product_image",
"+ (0.485, 0.456, 0.406) random_product_image_warped = Image.fromarray(np.uint8(random_product_image_warped * 255)) output_on_random_product",
"0.406] output_on_random_product = Image.fromarray(np.uint8(output_on_random_product * 255)) sheet = Image.new('RGB', (1568,",
"2) * [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] output_on_random_product",
"= warped_model_image.cpu().numpy() random_product_image = random_product_image.cpu().numpy() random_product_image_warped = random_product_image_warped.cpu().numpy() output_on_random_product =",
"from PIL import Image import torch.nn as nn from torchvision",
"0.225] + [0.485, 0.456, 0.406] random_product_image = Image.fromarray(np.uint8(random_product_image * 255))",
"warped_model_image[i], random_product_image[i], random_product_image_warped[i], output_on_random_product[i], epoch) def _save_image_sheet(self, idx, model_apparel, warped_image,",
"[0.485, 0.456, 0.406] output_on_random_product = Image.fromarray(np.uint8(output_on_random_product * 255)) sheet =",
"warped_image, model_image, warped_model_image, random_product_image, random_product_image_warped, output_on_random_product, epoch): # inverse normalization",
". import utils from . import geometric_transformer class GeoTransformationInfer(nn.Module): def",
"output_on_random_product = output_on_random_product.cpu().numpy() for i in range(batch_size): self._save_image_sheet( batch_index*config.PARAMS[\"batch_size\"] +",
"steps and finally converting np array to pillow format for",
"0.225] + [0.485, 0.456, 0.406] model_apparel = Image.fromarray(np.uint8(model_apparel * 255))",
"= Image.new('RGB', (1568, 224), 'white') sheet.paste(model_apparel, (0, 0)) sheet.paste(warped_image, (224,",
"0.456, 0.406) random_product_image_warped = Image.fromarray(np.uint8(random_product_image_warped * 255)) output_on_random_product = np.moveaxis(output_on_random_product,",
"inverse normalization of the images along with channel first to",
"0.224, 0.225] + [0.485, 0.456, 0.406] warped_model_image = Image.fromarray(np.uint8(warped_model_image *",
"from . import geometric_transformer class GeoTransformationInfer(nn.Module): def __init__(self, output_dir=\"./output/results\"): super(GeoTransformationInfer,",
"= np.moveaxis(model_image, 0, 2) * [0.229, 0.224, 0.225] + [0.485,",
"0.406] random_product_image = Image.fromarray(np.uint8(random_product_image * 255)) random_product_image_warped = np.moveaxis(random_product_image_warped, 0,",
"model_image, warped_model_image, random_product_image, random_product_image_warped, output_on_random_product, epoch): # inverse normalization of",
"0.225] + [0.485, 0.456, 0.406] warped_model_image = Image.fromarray(np.uint8(warped_model_image * 255))",
"(896, 0)) sheet.paste(random_product_image_warped, (1120, 0)) sheet.paste(output_on_random_product, (1344, 0)) sheet.save(os.path.join(self.output_dir, \"image_sheet_{}-epoch{}\".format(idx,",
"* [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] warped_image =",
"warped_model_image, random_product_image, random_product_image_warped, output_on_random_product, epoch): # inverse normalization of the",
"random_product_image = random_product_image.cpu().numpy() random_product_image_warped = random_product_image_warped.cpu().numpy() output_on_random_product = output_on_random_product.cpu().numpy() for",
"output_dir utils.ensure_folder(self.output_dir) def forward(self, model_apparel, warped_image, model_image, warped_model_image, random_product_image, random_product_image_warped,",
"for i in range(batch_size): self._save_image_sheet( batch_index*config.PARAMS[\"batch_size\"] + i, model_apparel[i], warped_image[i],",
"transforms # local imports import config from . import utils",
"[0.485, 0.456, 0.406] warped_model_image = Image.fromarray(np.uint8(warped_model_image * 255)) random_product_image =",
"np array to pillow format for saving model_apparel = np.moveaxis(model_apparel,",
"model_image[i], warped_model_image[i], random_product_image[i], random_product_image_warped[i], output_on_random_product[i], epoch) def _save_image_sheet(self, idx, model_apparel,",
"torch.nn as nn from torchvision import transforms # local imports",
"0.225] + (0.485, 0.456, 0.406) random_product_image_warped = Image.fromarray(np.uint8(random_product_image_warped * 255))",
"+ i, model_apparel[i], warped_image[i], model_image[i], warped_model_image[i], random_product_image[i], random_product_image_warped[i], output_on_random_product[i], epoch)",
"random_product_image_warped = np.moveaxis(random_product_image_warped, 0, 2) * [0.229, 0.224, 0.225] +",
"255)) warped_model_image = np.moveaxis(warped_model_image, 0, 2) * [0.229, 0.224, 0.225]",
"np.moveaxis(warped_image, 0, 2) * [0.229, 0.224, 0.225] + [0.485, 0.456,",
"super(GeoTransformationInfer, self).__init__() self.output_dir = output_dir utils.ensure_folder(self.output_dir) def forward(self, model_apparel, warped_image,",
"= Image.fromarray(np.uint8(warped_model_image * 255)) random_product_image = np.moveaxis(random_product_image, 0, 2) *",
"channel first to channel last steps and finally converting np",
"batch_index, epoch): batch_size = warped_image.shape[0] model_apparel = model_apparel.cpu().numpy() warped_image =",
"2) * [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] model_apparel",
"+ [0.485, 0.456, 0.406] random_product_image = Image.fromarray(np.uint8(random_product_image * 255)) random_product_image_warped",
"random_product_image_warped, output_on_random_product, epoch): # inverse normalization of the images along",
"and finally converting np array to pillow format for saving",
"0.406] model_image = Image.fromarray(np.uint8(model_image * 255)) warped_model_image = np.moveaxis(warped_model_image, 0,",
"(0, 0)) sheet.paste(warped_image, (224, 0)) sheet.paste(model_image, (448, 0)) sheet.paste(warped_model_image, (672,",
"= Image.fromarray(np.uint8(output_on_random_product * 255)) sheet = Image.new('RGB', (1568, 224), 'white')",
"* 255)) output_on_random_product = np.moveaxis(output_on_random_product, 0, 2) * [0.229, 0.224,",
"0)) sheet.paste(random_product_image, (896, 0)) sheet.paste(random_product_image_warped, (1120, 0)) sheet.paste(output_on_random_product, (1344, 0))",
"0.406] warped_model_image = Image.fromarray(np.uint8(warped_model_image * 255)) random_product_image = np.moveaxis(random_product_image, 0,",
"224), 'white') sheet.paste(model_apparel, (0, 0)) sheet.paste(warped_image, (224, 0)) sheet.paste(model_image, (448,",
"model_image.cpu().numpy() warped_model_image = warped_model_image.cpu().numpy() random_product_image = random_product_image.cpu().numpy() random_product_image_warped = random_product_image_warped.cpu().numpy()",
"saving model_apparel = np.moveaxis(model_apparel, 0, 2) * [0.229, 0.224, 0.225]",
"= output_dir utils.ensure_folder(self.output_dir) def forward(self, model_apparel, warped_image, model_image, warped_model_image, random_product_image,",
"first to channel last steps and finally converting np array",
"2) * [0.229, 0.224, 0.225] + (0.485, 0.456, 0.406) random_product_image_warped",
"import geometric_transformer class GeoTransformationInfer(nn.Module): def __init__(self, output_dir=\"./output/results\"): super(GeoTransformationInfer, self).__init__() self.output_dir",
"GeoTransformationInfer(nn.Module): def __init__(self, output_dir=\"./output/results\"): super(GeoTransformationInfer, self).__init__() self.output_dir = output_dir utils.ensure_folder(self.output_dir)",
"import numpy as np from PIL import Image import torch.nn",
"warped_image[i], model_image[i], warped_model_image[i], random_product_image[i], random_product_image_warped[i], output_on_random_product[i], epoch) def _save_image_sheet(self, idx,",
"= random_product_image.cpu().numpy() random_product_image_warped = random_product_image_warped.cpu().numpy() output_on_random_product = output_on_random_product.cpu().numpy() for i",
"Image.fromarray(np.uint8(warped_image * 255)) model_image = np.moveaxis(model_image, 0, 2) * [0.229,",
"random_product_image_warped = Image.fromarray(np.uint8(random_product_image_warped * 255)) output_on_random_product = np.moveaxis(output_on_random_product, 0, 2)",
"def __init__(self, output_dir=\"./output/results\"): super(GeoTransformationInfer, self).__init__() self.output_dir = output_dir utils.ensure_folder(self.output_dir) def",
"warped_image = warped_image.cpu().numpy() model_image = model_image.cpu().numpy() warped_model_image = warped_model_image.cpu().numpy() random_product_image",
"self._save_image_sheet( batch_index*config.PARAMS[\"batch_size\"] + i, model_apparel[i], warped_image[i], model_image[i], warped_model_image[i], random_product_image[i], random_product_image_warped[i],",
"= Image.fromarray(np.uint8(random_product_image_warped * 255)) output_on_random_product = np.moveaxis(output_on_random_product, 0, 2) *",
"Image.fromarray(np.uint8(model_image * 255)) warped_model_image = np.moveaxis(warped_model_image, 0, 2) * [0.229,",
"normalization of the images along with channel first to channel",
"channel last steps and finally converting np array to pillow",
"0.406] warped_image = Image.fromarray(np.uint8(warped_image * 255)) model_image = np.moveaxis(model_image, 0,",
"Image.new('RGB', (1568, 224), 'white') sheet.paste(model_apparel, (0, 0)) sheet.paste(warped_image, (224, 0))",
"= warped_image.cpu().numpy() model_image = model_image.cpu().numpy() warped_model_image = warped_model_image.cpu().numpy() random_product_image =",
"output_on_random_product = Image.fromarray(np.uint8(output_on_random_product * 255)) sheet = Image.new('RGB', (1568, 224),",
"third party imports import numpy as np from PIL import",
"(672, 0)) sheet.paste(random_product_image, (896, 0)) sheet.paste(random_product_image_warped, (1120, 0)) sheet.paste(output_on_random_product, (1344,",
"sheet.paste(model_apparel, (0, 0)) sheet.paste(warped_image, (224, 0)) sheet.paste(model_image, (448, 0)) sheet.paste(warped_model_image,",
"Image.fromarray(np.uint8(warped_model_image * 255)) random_product_image = np.moveaxis(random_product_image, 0, 2) * [0.229,",
"batch_index*config.PARAMS[\"batch_size\"] + i, model_apparel[i], warped_image[i], model_image[i], warped_model_image[i], random_product_image[i], random_product_image_warped[i], output_on_random_product[i],",
"imports import numpy as np from PIL import Image import",
"np.moveaxis(model_image, 0, 2) * [0.229, 0.224, 0.225] + [0.485, 0.456,",
"import utils from . import geometric_transformer class GeoTransformationInfer(nn.Module): def __init__(self,",
"random_product_image, random_product_image_warped, output_on_random_product, batch_index, epoch): batch_size = warped_image.shape[0] model_apparel =",
"geometric_transformer class GeoTransformationInfer(nn.Module): def __init__(self, output_dir=\"./output/results\"): super(GeoTransformationInfer, self).__init__() self.output_dir =",
"epoch) def _save_image_sheet(self, idx, model_apparel, warped_image, model_image, warped_model_image, random_product_image, random_product_image_warped,",
"0.225] + [0.485, 0.456, 0.406] warped_image = Image.fromarray(np.uint8(warped_image * 255))",
"* 255)) random_product_image_warped = np.moveaxis(random_product_image_warped, 0, 2) * [0.229, 0.224,",
"+ [0.485, 0.456, 0.406] output_on_random_product = Image.fromarray(np.uint8(output_on_random_product * 255)) sheet",
"__init__(self, output_dir=\"./output/results\"): super(GeoTransformationInfer, self).__init__() self.output_dir = output_dir utils.ensure_folder(self.output_dir) def forward(self,",
"imports import os # third party imports import numpy as",
"Image.fromarray(np.uint8(random_product_image * 255)) random_product_image_warped = np.moveaxis(random_product_image_warped, 0, 2) * [0.229,",
"random_product_image_warped[i], output_on_random_product[i], epoch) def _save_image_sheet(self, idx, model_apparel, warped_image, model_image, warped_model_image,",
"0)) sheet.paste(random_product_image_warped, (1120, 0)) sheet.paste(output_on_random_product, (1344, 0)) sheet.save(os.path.join(self.output_dir, \"image_sheet_{}-epoch{}\".format(idx, str(epoch).zfill(3))",
"random_product_image_warped, output_on_random_product, batch_index, epoch): batch_size = warped_image.shape[0] model_apparel = model_apparel.cpu().numpy()",
"2) * [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] warped_model_image",
"0.406] model_apparel = Image.fromarray(np.uint8(model_apparel * 255)) warped_image = np.moveaxis(warped_image, 0,",
"= np.moveaxis(random_product_image_warped, 0, 2) * [0.229, 0.224, 0.225] + (0.485,",
"= np.moveaxis(random_product_image, 0, 2) * [0.229, 0.224, 0.225] + [0.485,",
"sheet.paste(warped_image, (224, 0)) sheet.paste(model_image, (448, 0)) sheet.paste(warped_model_image, (672, 0)) sheet.paste(random_product_image,",
"along with channel first to channel last steps and finally",
"i, model_apparel[i], warped_image[i], model_image[i], warped_model_image[i], random_product_image[i], random_product_image_warped[i], output_on_random_product[i], epoch) def",
"the images along with channel first to channel last steps",
"model_image = np.moveaxis(model_image, 0, 2) * [0.229, 0.224, 0.225] +",
"epoch): batch_size = warped_image.shape[0] model_apparel = model_apparel.cpu().numpy() warped_image = warped_image.cpu().numpy()",
"random_product_image[i], random_product_image_warped[i], output_on_random_product[i], epoch) def _save_image_sheet(self, idx, model_apparel, warped_image, model_image,",
"+ [0.485, 0.456, 0.406] model_image = Image.fromarray(np.uint8(model_image * 255)) warped_model_image",
"* [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] model_apparel =",
"to pillow format for saving model_apparel = np.moveaxis(model_apparel, 0, 2)",
"Image.fromarray(np.uint8(output_on_random_product * 255)) sheet = Image.new('RGB', (1568, 224), 'white') sheet.paste(model_apparel,",
"0.456, 0.406] model_image = Image.fromarray(np.uint8(model_image * 255)) warped_model_image = np.moveaxis(warped_model_image,",
"library imports import os # third party imports import numpy",
"warped_model_image, random_product_image, random_product_image_warped, output_on_random_product, batch_index, epoch): batch_size = warped_image.shape[0] model_apparel",
"output_on_random_product, batch_index, epoch): batch_size = warped_image.shape[0] model_apparel = model_apparel.cpu().numpy() warped_image",
"= random_product_image_warped.cpu().numpy() output_on_random_product = output_on_random_product.cpu().numpy() for i in range(batch_size): self._save_image_sheet(",
"255)) model_image = np.moveaxis(model_image, 0, 2) * [0.229, 0.224, 0.225]",
"warped_image, model_image, warped_model_image, random_product_image, random_product_image_warped, output_on_random_product, batch_index, epoch): batch_size ="
] |
[
"self.denoise: img = self.data[index] img = Image.fromarray(img) if self.transform is",
"mean characters as test set split (str): 'train', 'val', 'test'",
"idx = np.argmin(np.sum(np.square(all_imgs - x), axis=(1,2))) return self[idx] def download(self):",
"img, target = self.all_data[index], self.all_targets[index] domain_label = self.all_domain_labels[index] # doing",
"idxs[num_examples: train_val_max] else: idxs = idxs[train_val_max:] self.targets = self.all_targets[idxs] self.domain_labels",
"to return a PIL Image img = Image.fromarray(img) if self.transform",
"new chunks f.write(chunk) class Fonts(VisionDataset): url_id = '0B0GtwTQ6IF9AU3NOdzFzUWZ0aDQ' base_folder =",
"idxs = idxs[:num_examples] elif split == 'val': idxs = idxs[num_examples:",
"Path import h5py import numpy as np from torchvision.datasets.vision import",
"'r') as f: data_by_domain = f['fonts'][()] np.random.seed(484347) # limit the",
"to heuristically test what happens if we have more training",
"all_data[idxs] if num_fonts_pi is not None: data_by_domain = data_by_domain[font_idxs[num_fonts:num_fonts+num_fonts_pi]] else:",
"idxs[:num_examples] elif split == 'val': idxs = idxs[num_examples: train_val_max] else:",
"100 font_idxs = np.arange(len(data_by_domain)) np.random.shuffle(font_idxs) if not denoise: data_by_domain =",
"self.all_targets[index] domain_label = self.all_domain_labels[index] # doing this so that it",
"train_dbd = data_by_domain[font_idxs[:num_fonts]] all_data = train_dbd.reshape(train_dbd.shape[0]*train_dbd.shape[1], train_dbd.shape[2], train_dbd.shape[3]) idxs =",
"train_dbd.reshape(train_dbd.shape[0]*train_dbd.shape[1], train_dbd.shape[2], train_dbd.shape[3]) idxs = np.arange(len(all_data)) np.random.shuffle(idxs) idxs = idxs[:num_examples]",
"split self.transform = transform self.target_transform = target_transform self.denoise = denoise",
"self.all_targets = np.concatenate( [np.arange(num_classes)]*num_fonts, axis=0) self.all_domain_labels = np.repeat(np.arange(num_fonts), num_classes) self.all_data",
"from pathlib import Path import h5py import numpy as np",
"Fonts(VisionDataset): url_id = '0B0GtwTQ6IF9AU3NOdzFzUWZ0aDQ' base_folder = 'fonts' def __init__(self, root,",
"Image.fromarray(img) if self.transform is not None: img = self.transform(img) if",
"if we have more training data train_val_max = 5000 if",
"self.all_domain_labels[idxs] self.data = self.all_data[idxs] else: # get the train data",
"that it is consistent with all other datasets # to",
"None def save_response_content(response, destination): CHUNK_SIZE = 32768 with open(destination, \"wb\")",
"out keep-alive new chunks f.write(chunk) class Fonts(VisionDataset): url_id = '0B0GtwTQ6IF9AU3NOdzFzUWZ0aDQ'",
"= 2600 if num_examples > train_val_max: # to be able",
"denoise_transform=None, num_fonts_pi=None, num_examples=2500): ''' Args: root (str): path num_train_domains (int):",
"num_examples=2500): ''' Args: root (str): path num_train_domains (int): number of",
"== 'train': idxs = idxs[:num_examples] elif split == 'val': idxs",
"datasets # to return a PIL Image img = Image.fromarray(img)",
"key.startswith('download_warning'): return value return None def save_response_content(response, destination): CHUNK_SIZE =",
"other datasets # to return a PIL Image img =",
"self.targets = self.all_targets[idxs] self.domain_labels = self.all_domain_labels[idxs] self.data = self.all_data[idxs] else:",
"not None: data_by_domain = data_by_domain[font_idxs[num_fonts:num_fonts+num_fonts_pi]] else: data_by_domain = data_by_domain[font_idxs[num_fonts:]] self.data",
"filter out keep-alive new chunks f.write(chunk) class Fonts(VisionDataset): url_id =",
"'train', 'val', 'test' transform: input transformation target_transform: target transformation download",
"of train domains up to 41443 test_mean_chars (bool): Use the",
"data_by_domain[font_idxs[num_fonts:num_fonts+num_fonts_pi]] else: data_by_domain = data_by_domain[font_idxs[num_fonts:]] self.data = data_by_domain.reshape(data_by_domain.shape[0]*data_by_domain.shape[1], data_by_domain.shape[2], data_by_domain.shape[3])",
"= self.all_targets[idxs] self.domain_labels = self.all_domain_labels[idxs] self.data = self.all_data[idxs] else: #",
"of the target class. \"\"\" if self.denoise: img = self.data[index]",
"target_transform: target transformation download (bool): download or not ''' super().__init__(root,",
"self.path = Path(self.root) / self.base_folder self.path.mkdir(parents=True, exist_ok=True) self.download_path = self.path",
"idxs = np.arange(len(self.all_data)) np.random.shuffle(idxs) train_val_max = 2600 if num_examples >",
"''' Args: root (str): path num_train_domains (int): number of train",
"all_imgs, x): idx = np.argmin(np.sum(np.square(all_imgs - x), axis=(1,2))) return self[idx]",
"np.arange(len(self.all_data)) np.random.shuffle(idxs) train_val_max = 2600 if num_examples > train_val_max: #",
"elif split == 'val': idxs = idxs[num_examples: train_val_max] else: idxs",
"params = { 'id' : id }, stream = True)",
"url_id = '0B0GtwTQ6IF9AU3NOdzFzUWZ0aDQ' base_folder = 'fonts' def __init__(self, root, split='train',",
"import VisionDataset from PIL import Image import requests import zipfile",
"= requests.Session() response = session.get(URL, params = { 'id' :",
"__init__(self, root, split='train', transform=None, target_transform=None, download=True, denoise=False, denoise_transform=None, num_fonts_pi=None, num_examples=2500):",
"= self.data[index], self.targets[index] domain_label = self.domain_labels[index] # doing this so",
"not None: target = self.target_transform(target) return img, target, domain_label def",
"data_by_domain = f['fonts'][()] np.random.seed(484347) # limit the number of fonts",
"= self.transform(img) if self.denoise_transform is not None: src_img = self.denoise_transform(img)",
"target = self.data[index], self.targets[index] domain_label = self.domain_labels[index] # doing this",
"pathlib import Path import h5py import numpy as np from",
"\"\"\" if self.denoise: img = self.data[index] img = Image.fromarray(img) if",
"(image, target) where target is index of the target class.",
"= self.all_data[idxs] else: # get the train data train_dbd =",
"target = self.target_transform(target) return img, target, domain_label def __len__(self): return",
"[np.arange(num_classes)]*num_fonts, axis=0) self.all_domain_labels = np.repeat(np.arange(num_fonts), num_classes) self.all_data = data_by_domain.reshape(data_by_domain.shape[0]*data_by_domain.shape[1], data_by_domain.shape[2],",
"return a PIL Image img = Image.fromarray(img) if self.transform is",
"= { 'id' : id }, stream = True) token",
"idxs = idxs[:num_examples] train_data = all_data[idxs] if num_fonts_pi is not",
"self.transform is not None: tgt_img = self.transform(img) if self.denoise_transform is",
"def download_file_from_google_drive(id, destination): URL = \"https://docs.google.com/uc?export=download\" session = requests.Session() response",
"(str): path num_train_domains (int): number of train domains up to",
"return None def save_response_content(response, destination): CHUNK_SIZE = 32768 with open(destination,",
"consistent with all other datasets # to return a PIL",
"{ 'id' : id, 'confirm' : token } response =",
"= params, stream = True) save_response_content(response, destination) def get_confirm_token(response): for",
"response = session.get(URL, params = params, stream = True) save_response_content(response,",
"np.random.shuffle(font_idxs) if not denoise: data_by_domain = data_by_domain[font_idxs[:num_fonts]] print(f\"NUM FONTS: {num_fonts}\")",
"not None: img = self.transform(img) if self.target_transform is not None:",
"index): \"\"\" Args: index (int): Index Returns: tuple: (image, target)",
"be able to heuristically test what happens if we have",
"split == 'train': idxs = idxs[:num_examples] elif split == 'val':",
"if self.target_transform is not None: target = self.target_transform(target) return img,",
"= idxs[train_val_max:] self.targets = self.all_targets[idxs] self.domain_labels = self.all_domain_labels[idxs] self.data =",
"as np from torchvision.datasets.vision import VisionDataset from PIL import Image",
"src_img = self.denoise_transform(img) return src_img, tgt_img else: img, target =",
"return value return None def save_response_content(response, destination): CHUNK_SIZE = 32768",
"as test set split (str): 'train', 'val', 'test' transform: input",
"fonts num_fonts = 100 font_idxs = np.arange(len(data_by_domain)) np.random.shuffle(font_idxs) if not",
"session.get(URL, params = params, stream = True) save_response_content(response, destination) def",
"def __getitem__(self, index): \"\"\" Args: index (int): Index Returns: tuple:",
"torchvision.datasets.vision import VisionDataset from PIL import Image import requests import",
"if self.transform is not None: img = self.transform(img) if self.target_transform",
"if num_examples > train_val_max: # to be able to heuristically",
"self.all_domain_labels[index] # doing this so that it is consistent with",
"None: data_by_domain = data_by_domain[font_idxs[num_fonts:num_fonts+num_fonts_pi]] else: data_by_domain = data_by_domain[font_idxs[num_fonts:]] self.data =",
"target = self.target_transform(target) return img, target, domain_label def get_item_from_all(self, index):",
"self.all_domain_labels = np.repeat(np.arange(num_fonts), num_classes) self.all_data = data_by_domain.reshape(data_by_domain.shape[0]*data_by_domain.shape[1], data_by_domain.shape[2], data_by_domain.shape[3]) idxs",
"requests import zipfile from tqdm import tqdm def download_file_from_google_drive(id, destination):",
"download (bool): download or not ''' super().__init__(root, transform=transform, target_transform=target_transform) self.split",
"target_transform=target_transform) self.split = split self.transform = transform self.target_transform = target_transform",
"as f: data_by_domain = f['fonts'][()] np.random.seed(484347) # limit the number",
"def download(self): if not self.download_path.exists(): download_file_from_google_drive(self.url_id, str(self.download_path)) def __getitem__(self, index):",
"self.split = split self.transform = transform self.target_transform = target_transform self.denoise",
"token } response = session.get(URL, params = params, stream =",
"img = self.transform(img) if self.target_transform is not None: target =",
"limit the number of fonts num_fonts = 100 font_idxs =",
"more training data train_val_max = 5000 if split == 'train':",
"if not self.download_path.exists(): download_file_from_google_drive(self.url_id, str(self.download_path)) def __getitem__(self, index): \"\"\" Args:",
"data_by_domain.reshape(data_by_domain.shape[0]*data_by_domain.shape[1], data_by_domain.shape[2], data_by_domain.shape[3]) self.data = np.concatenate([train_data, self.data], axis=0) def get_nearest_neighbor(self,",
"num_fonts_pi=None, num_examples=2500): ''' Args: root (str): path num_train_domains (int): number",
"np.random.shuffle(idxs) idxs = idxs[:num_examples] train_data = all_data[idxs] if num_fonts_pi is",
"return self[idx] def download(self): if not self.download_path.exists(): download_file_from_google_drive(self.url_id, str(self.download_path)) def",
"self.target_transform is not None: target = self.target_transform(target) return img, target,",
"Index Returns: tuple: (image, target) where target is index of",
"tgt_img = self.transform(img) if self.denoise_transform is not None: src_img =",
"= transform self.target_transform = target_transform self.denoise = denoise self.denoise_transform =",
"train_val_max = 2600 if num_examples > train_val_max: # to be",
"def get_item_from_all(self, index): img, target = self.all_data[index], self.all_targets[index] domain_label =",
"if not denoise: data_by_domain = data_by_domain[font_idxs[:num_fonts]] print(f\"NUM FONTS: {num_fonts}\") print(f\"NUM",
"(bool): Use the mean characters as test set split (str):",
"split == 'val': idxs = idxs[num_examples: train_val_max] else: idxs =",
"img = Image.fromarray(img) if self.transform is not None: tgt_img =",
"self.target_transform(target) return img, target, domain_label def get_item_from_all(self, index): img, target",
"None: target = self.target_transform(target) return img, target, domain_label def __len__(self):",
"(str): 'train', 'val', 'test' transform: input transformation target_transform: target transformation",
"denoise: data_by_domain = data_by_domain[font_idxs[:num_fonts]] print(f\"NUM FONTS: {num_fonts}\") print(f\"NUM CHARS: {data_by_domain.shape[1]}\")",
"is not None: target = self.target_transform(target) return img, target, domain_label",
"# filter out keep-alive new chunks f.write(chunk) class Fonts(VisionDataset): url_id",
"/ self.base_folder self.path.mkdir(parents=True, exist_ok=True) self.download_path = self.path / 'fonts.hdf5' if",
"= self.domain_labels[index] # doing this so that it is consistent",
"= self.denoise_transform(img) return src_img, tgt_img else: img, target = self.data[index],",
"\"https://docs.google.com/uc?export=download\" session = requests.Session() response = session.get(URL, params = {",
"= Path(self.root) / self.base_folder self.path.mkdir(parents=True, exist_ok=True) self.download_path = self.path /",
"to 41443 test_mean_chars (bool): Use the mean characters as test",
"with h5py.File(str(self.download_path), 'r') as f: data_by_domain = f['fonts'][()] np.random.seed(484347) #",
"domain_label def get_item_from_all(self, index): img, target = self.all_data[index], self.all_targets[index] domain_label",
"self.download() with h5py.File(str(self.download_path), 'r') as f: data_by_domain = f['fonts'][()] np.random.seed(484347)",
"= Image.fromarray(img) if self.transform is not None: tgt_img = self.transform(img)",
"destination): CHUNK_SIZE = 32768 with open(destination, \"wb\") as f: for",
"transformation target_transform: target transformation download (bool): download or not '''",
"FONTS: {num_fonts}\") print(f\"NUM CHARS: {data_by_domain.shape[1]}\") num_classes = data_by_domain.shape[1] self.all_targets =",
"f: for chunk in tqdm(response.iter_content(CHUNK_SIZE)): if chunk: # filter out",
"self.targets[index] domain_label = self.domain_labels[index] # doing this so that it",
"num_classes) self.all_data = data_by_domain.reshape(data_by_domain.shape[0]*data_by_domain.shape[1], data_by_domain.shape[2], data_by_domain.shape[3]) idxs = np.arange(len(self.all_data)) np.random.shuffle(idxs)",
"= Image.fromarray(img) if self.transform is not None: img = self.transform(img)",
"self.denoise_transform is not None: src_img = self.denoise_transform(img) return src_img, tgt_img",
"test set split (str): 'train', 'val', 'test' transform: input transformation",
"self.denoise = denoise self.denoise_transform = denoise_transform self.path = Path(self.root) /",
"None: tgt_img = self.transform(img) if self.denoise_transform is not None: src_img",
"zipfile from tqdm import tqdm def download_file_from_google_drive(id, destination): URL =",
"data_by_domain.shape[1] self.all_targets = np.concatenate( [np.arange(num_classes)]*num_fonts, axis=0) self.all_domain_labels = np.repeat(np.arange(num_fonts), num_classes)",
"= idxs[:num_examples] train_data = all_data[idxs] if num_fonts_pi is not None:",
"= idxs[:num_examples] elif split == 'val': idxs = idxs[num_examples: train_val_max]",
"data_by_domain.shape[2], data_by_domain.shape[3]) idxs = np.arange(len(self.all_data)) np.random.shuffle(idxs) train_val_max = 2600 if",
"= self.path / 'fonts.hdf5' if download: self.download() with h5py.File(str(self.download_path), 'r')",
"'fonts' def __init__(self, root, split='train', transform=None, target_transform=None, download=True, denoise=False, denoise_transform=None,",
"= 100 font_idxs = np.arange(len(data_by_domain)) np.random.shuffle(font_idxs) if not denoise: data_by_domain",
"transform=None, target_transform=None, download=True, denoise=False, denoise_transform=None, num_fonts_pi=None, num_examples=2500): ''' Args: root",
"= get_confirm_token(response) if token: params = { 'id' : id,",
"self.data], axis=0) def get_nearest_neighbor(self, all_imgs, x): idx = np.argmin(np.sum(np.square(all_imgs -",
"up to 41443 test_mean_chars (bool): Use the mean characters as",
"target_transform self.denoise = denoise self.denoise_transform = denoise_transform self.path = Path(self.root)",
"download_file_from_google_drive(id, destination): URL = \"https://docs.google.com/uc?export=download\" session = requests.Session() response =",
"'val', 'test' transform: input transformation target_transform: target transformation download (bool):",
"str(self.download_path)) def __getitem__(self, index): \"\"\" Args: index (int): Index Returns:",
"= self.data[index] img = Image.fromarray(img) if self.transform is not None:",
"'id' : id }, stream = True) token = get_confirm_token(response)",
"self.data = np.concatenate([train_data, self.data], axis=0) def get_nearest_neighbor(self, all_imgs, x): idx",
"import zipfile from tqdm import tqdm def download_file_from_google_drive(id, destination): URL",
"> train_val_max: # to be able to heuristically test what",
"where target is index of the target class. \"\"\" if",
"data_by_domain.shape[3]) idxs = np.arange(len(self.all_data)) np.random.shuffle(idxs) train_val_max = 2600 if num_examples",
"transform: input transformation target_transform: target transformation download (bool): download or",
"what happens if we have more training data train_val_max =",
"= data_by_domain.reshape(data_by_domain.shape[0]*data_by_domain.shape[1], data_by_domain.shape[2], data_by_domain.shape[3]) self.data = np.concatenate([train_data, self.data], axis=0) def",
"def get_confirm_token(response): for key, value in response.cookies.items(): if key.startswith('download_warning'): return",
"f.write(chunk) class Fonts(VisionDataset): url_id = '0B0GtwTQ6IF9AU3NOdzFzUWZ0aDQ' base_folder = 'fonts' def",
"value return None def save_response_content(response, destination): CHUNK_SIZE = 32768 with",
"not ''' super().__init__(root, transform=transform, target_transform=target_transform) self.split = split self.transform =",
"np.random.seed(484347) # limit the number of fonts num_fonts = 100",
"training data train_val_max = 5000 if split == 'train': idxs",
"num_train_domains (int): number of train domains up to 41443 test_mean_chars",
"so that it is consistent with all other datasets #",
"all other datasets # to return a PIL Image img",
"= self.transform(img) if self.target_transform is not None: target = self.target_transform(target)",
"self.domain_labels[index] # doing this so that it is consistent with",
"img, target = self.data[index], self.targets[index] domain_label = self.domain_labels[index] # doing",
"= True) token = get_confirm_token(response) if token: params = {",
"self.data[index] img = Image.fromarray(img) if self.transform is not None: tgt_img",
"train_val_max] else: idxs = idxs[train_val_max:] self.targets = self.all_targets[idxs] self.domain_labels =",
"None: src_img = self.denoise_transform(img) return src_img, tgt_img else: img, target",
"denoise=False, denoise_transform=None, num_fonts_pi=None, num_examples=2500): ''' Args: root (str): path num_train_domains",
"PIL import Image import requests import zipfile from tqdm import",
"get_confirm_token(response): for key, value in response.cookies.items(): if key.startswith('download_warning'): return value",
"= np.arange(len(self.all_data)) np.random.shuffle(idxs) train_val_max = 2600 if num_examples > train_val_max:",
"this so that it is consistent with all other datasets",
"img = Image.fromarray(img) if self.transform is not None: img =",
"h5py import numpy as np from torchvision.datasets.vision import VisionDataset from",
"return img, target, domain_label def get_item_from_all(self, index): img, target =",
"download or not ''' super().__init__(root, transform=transform, target_transform=target_transform) self.split = split",
"transform self.target_transform = target_transform self.denoise = denoise self.denoise_transform = denoise_transform",
"data train_dbd = data_by_domain[font_idxs[:num_fonts]] all_data = train_dbd.reshape(train_dbd.shape[0]*train_dbd.shape[1], train_dbd.shape[2], train_dbd.shape[3]) idxs",
"data_by_domain.shape[3]) self.data = np.concatenate([train_data, self.data], axis=0) def get_nearest_neighbor(self, all_imgs, x):",
"is not None: img = self.transform(img) if self.target_transform is not",
"get_nearest_neighbor(self, all_imgs, x): idx = np.argmin(np.sum(np.square(all_imgs - x), axis=(1,2))) return",
"not None: src_img = self.denoise_transform(img) return src_img, tgt_img else: img,",
"domains up to 41443 test_mean_chars (bool): Use the mean characters",
"target is index of the target class. \"\"\" if self.denoise:",
"root (str): path num_train_domains (int): number of train domains up",
"class Fonts(VisionDataset): url_id = '0B0GtwTQ6IF9AU3NOdzFzUWZ0aDQ' base_folder = 'fonts' def __init__(self,",
"= data_by_domain[font_idxs[:num_fonts]] print(f\"NUM FONTS: {num_fonts}\") print(f\"NUM CHARS: {data_by_domain.shape[1]}\") num_classes =",
"transformation download (bool): download or not ''' super().__init__(root, transform=transform, target_transform=target_transform)",
"data_by_domain = data_by_domain[font_idxs[num_fonts:]] self.data = data_by_domain.reshape(data_by_domain.shape[0]*data_by_domain.shape[1], data_by_domain.shape[2], data_by_domain.shape[3]) self.data =",
"PIL Image img = Image.fromarray(img) if self.transform is not None:",
"np from torchvision.datasets.vision import VisionDataset from PIL import Image import",
"np.concatenate( [np.arange(num_classes)]*num_fonts, axis=0) self.all_domain_labels = np.repeat(np.arange(num_fonts), num_classes) self.all_data = data_by_domain.reshape(data_by_domain.shape[0]*data_by_domain.shape[1],",
"chunks f.write(chunk) class Fonts(VisionDataset): url_id = '0B0GtwTQ6IF9AU3NOdzFzUWZ0aDQ' base_folder = 'fonts'",
"if chunk: # filter out keep-alive new chunks f.write(chunk) class",
"axis=0) def get_nearest_neighbor(self, all_imgs, x): idx = np.argmin(np.sum(np.square(all_imgs - x),",
"the mean characters as test set split (str): 'train', 'val',",
"= target_transform self.denoise = denoise self.denoise_transform = denoise_transform self.path =",
"key, value in response.cookies.items(): if key.startswith('download_warning'): return value return None",
"axis=(1,2))) return self[idx] def download(self): if not self.download_path.exists(): download_file_from_google_drive(self.url_id, str(self.download_path))",
"save_response_content(response, destination): CHUNK_SIZE = 32768 with open(destination, \"wb\") as f:",
"from PIL import Image import requests import zipfile from tqdm",
"Use the mean characters as test set split (str): 'train',",
"None: img = self.transform(img) if self.target_transform is not None: target",
"download: self.download() with h5py.File(str(self.download_path), 'r') as f: data_by_domain = f['fonts'][()]",
"of fonts num_fonts = 100 font_idxs = np.arange(len(data_by_domain)) np.random.shuffle(font_idxs) if",
"data train_val_max = 5000 if split == 'train': idxs =",
"# doing this so that it is consistent with all",
"= session.get(URL, params = { 'id' : id }, stream",
"self.denoise_transform = denoise_transform self.path = Path(self.root) / self.base_folder self.path.mkdir(parents=True, exist_ok=True)",
"= split self.transform = transform self.target_transform = target_transform self.denoise =",
"index of the target class. \"\"\" if self.denoise: img =",
"else: data_by_domain = data_by_domain[font_idxs[num_fonts:]] self.data = data_by_domain.reshape(data_by_domain.shape[0]*data_by_domain.shape[1], data_by_domain.shape[2], data_by_domain.shape[3]) self.data",
"= 5000 if split == 'train': idxs = idxs[:num_examples] elif",
"target = self.all_data[index], self.all_targets[index] domain_label = self.all_domain_labels[index] # doing this",
"if token: params = { 'id' : id, 'confirm' :",
"2600 if num_examples > train_val_max: # to be able to",
"target class. \"\"\" if self.denoise: img = self.data[index] img =",
": token } response = session.get(URL, params = params, stream",
"== 'val': idxs = idxs[num_examples: train_val_max] else: idxs = idxs[train_val_max:]",
"data_by_domain[font_idxs[num_fonts:]] self.data = data_by_domain.reshape(data_by_domain.shape[0]*data_by_domain.shape[1], data_by_domain.shape[2], data_by_domain.shape[3]) self.data = np.concatenate([train_data, self.data],",
"np.random.shuffle(idxs) train_val_max = 2600 if num_examples > train_val_max: # to",
"URL = \"https://docs.google.com/uc?export=download\" session = requests.Session() response = session.get(URL, params",
"= self.target_transform(target) return img, target, domain_label def __len__(self): return len(self.data)",
"/ 'fonts.hdf5' if download: self.download() with h5py.File(str(self.download_path), 'r') as f:",
"session = requests.Session() response = session.get(URL, params = { 'id'",
"data_by_domain.shape[2], data_by_domain.shape[3]) self.data = np.concatenate([train_data, self.data], axis=0) def get_nearest_neighbor(self, all_imgs,",
"data_by_domain.reshape(data_by_domain.shape[0]*data_by_domain.shape[1], data_by_domain.shape[2], data_by_domain.shape[3]) idxs = np.arange(len(self.all_data)) np.random.shuffle(idxs) train_val_max = 2600",
"VisionDataset from PIL import Image import requests import zipfile from",
"a PIL Image img = Image.fromarray(img) if self.transform is not",
"np.argmin(np.sum(np.square(all_imgs - x), axis=(1,2))) return self[idx] def download(self): if not",
"domain_label = self.all_domain_labels[index] # doing this so that it is",
"have more training data train_val_max = 5000 if split ==",
"num_fonts_pi is not None: data_by_domain = data_by_domain[font_idxs[num_fonts:num_fonts+num_fonts_pi]] else: data_by_domain =",
"params = { 'id' : id, 'confirm' : token }",
"def get_nearest_neighbor(self, all_imgs, x): idx = np.argmin(np.sum(np.square(all_imgs - x), axis=(1,2)))",
"= np.repeat(np.arange(num_fonts), num_classes) self.all_data = data_by_domain.reshape(data_by_domain.shape[0]*data_by_domain.shape[1], data_by_domain.shape[2], data_by_domain.shape[3]) idxs =",
"for key, value in response.cookies.items(): if key.startswith('download_warning'): return value return",
"tuple: (image, target) where target is index of the target",
"number of fonts num_fonts = 100 font_idxs = np.arange(len(data_by_domain)) np.random.shuffle(font_idxs)",
"the train data train_dbd = data_by_domain[font_idxs[:num_fonts]] all_data = train_dbd.reshape(train_dbd.shape[0]*train_dbd.shape[1], train_dbd.shape[2],",
"keep-alive new chunks f.write(chunk) class Fonts(VisionDataset): url_id = '0B0GtwTQ6IF9AU3NOdzFzUWZ0aDQ' base_folder",
"Args: index (int): Index Returns: tuple: (image, target) where target",
"{ 'id' : id }, stream = True) token =",
"Image.fromarray(img) if self.transform is not None: tgt_img = self.transform(img) if",
"32768 with open(destination, \"wb\") as f: for chunk in tqdm(response.iter_content(CHUNK_SIZE)):",
"} response = session.get(URL, params = params, stream = True)",
"download_file_from_google_drive(self.url_id, str(self.download_path)) def __getitem__(self, index): \"\"\" Args: index (int): Index",
"is not None: tgt_img = self.transform(img) if self.denoise_transform is not",
"= np.concatenate([train_data, self.data], axis=0) def get_nearest_neighbor(self, all_imgs, x): idx =",
"test_mean_chars (bool): Use the mean characters as test set split",
"{num_fonts}\") print(f\"NUM CHARS: {data_by_domain.shape[1]}\") num_classes = data_by_domain.shape[1] self.all_targets = np.concatenate(",
"idxs = np.arange(len(all_data)) np.random.shuffle(idxs) idxs = idxs[:num_examples] train_data = all_data[idxs]",
"Path(self.root) / self.base_folder self.path.mkdir(parents=True, exist_ok=True) self.download_path = self.path / 'fonts.hdf5'",
"self.transform(img) if self.denoise_transform is not None: src_img = self.denoise_transform(img) return",
"= True) save_response_content(response, destination) def get_confirm_token(response): for key, value in",
"self.path / 'fonts.hdf5' if download: self.download() with h5py.File(str(self.download_path), 'r') as",
"get the train data train_dbd = data_by_domain[font_idxs[:num_fonts]] all_data = train_dbd.reshape(train_dbd.shape[0]*train_dbd.shape[1],",
"import numpy as np from torchvision.datasets.vision import VisionDataset from PIL",
"set split (str): 'train', 'val', 'test' transform: input transformation target_transform:",
"img, target, domain_label def get_item_from_all(self, index): img, target = self.all_data[index],",
"= np.arange(len(all_data)) np.random.shuffle(idxs) idxs = idxs[:num_examples] train_data = all_data[idxs] if",
"train domains up to 41443 test_mean_chars (bool): Use the mean",
"# to be able to heuristically test what happens if",
"x): idx = np.argmin(np.sum(np.square(all_imgs - x), axis=(1,2))) return self[idx] def",
"is not None: data_by_domain = data_by_domain[font_idxs[num_fonts:num_fonts+num_fonts_pi]] else: data_by_domain = data_by_domain[font_idxs[num_fonts:]]",
"if num_fonts_pi is not None: data_by_domain = data_by_domain[font_idxs[num_fonts:num_fonts+num_fonts_pi]] else: data_by_domain",
"if key.startswith('download_warning'): return value return None def save_response_content(response, destination): CHUNK_SIZE",
"None: target = self.target_transform(target) return img, target, domain_label def get_item_from_all(self,",
"Image import requests import zipfile from tqdm import tqdm def",
"index): img, target = self.all_data[index], self.all_targets[index] domain_label = self.all_domain_labels[index] #",
"idxs = idxs[num_examples: train_val_max] else: idxs = idxs[train_val_max:] self.targets =",
"numpy as np from torchvision.datasets.vision import VisionDataset from PIL import",
"not self.download_path.exists(): download_file_from_google_drive(self.url_id, str(self.download_path)) def __getitem__(self, index): \"\"\" Args: index",
"from torchvision.datasets.vision import VisionDataset from PIL import Image import requests",
"= self.target_transform(target) return img, target, domain_label def get_item_from_all(self, index): img,",
"\"\"\" Args: index (int): Index Returns: tuple: (image, target) where",
"import requests import zipfile from tqdm import tqdm def download_file_from_google_drive(id,",
"exist_ok=True) self.download_path = self.path / 'fonts.hdf5' if download: self.download() with",
"happens if we have more training data train_val_max = 5000",
"= { 'id' : id, 'confirm' : token } response",
"split='train', transform=None, target_transform=None, download=True, denoise=False, denoise_transform=None, num_fonts_pi=None, num_examples=2500): ''' Args:",
"(bool): download or not ''' super().__init__(root, transform=transform, target_transform=target_transform) self.split =",
"import Image import requests import zipfile from tqdm import tqdm",
"params, stream = True) save_response_content(response, destination) def get_confirm_token(response): for key,",
"'val': idxs = idxs[num_examples: train_val_max] else: idxs = idxs[train_val_max:] self.targets",
"we have more training data train_val_max = 5000 if split",
"= np.arange(len(data_by_domain)) np.random.shuffle(font_idxs) if not denoise: data_by_domain = data_by_domain[font_idxs[:num_fonts]] print(f\"NUM",
"np.repeat(np.arange(num_fonts), num_classes) self.all_data = data_by_domain.reshape(data_by_domain.shape[0]*data_by_domain.shape[1], data_by_domain.shape[2], data_by_domain.shape[3]) idxs = np.arange(len(self.all_data))",
"train_dbd.shape[3]) idxs = np.arange(len(all_data)) np.random.shuffle(idxs) idxs = idxs[:num_examples] train_data =",
"doing this so that it is consistent with all other",
"print(f\"NUM CHARS: {data_by_domain.shape[1]}\") num_classes = data_by_domain.shape[1] self.all_targets = np.concatenate( [np.arange(num_classes)]*num_fonts,",
"index (int): Index Returns: tuple: (image, target) where target is",
"= 'fonts' def __init__(self, root, split='train', transform=None, target_transform=None, download=True, denoise=False,",
"# get the train data train_dbd = data_by_domain[font_idxs[:num_fonts]] all_data =",
"data_by_domain = data_by_domain[font_idxs[num_fonts:num_fonts+num_fonts_pi]] else: data_by_domain = data_by_domain[font_idxs[num_fonts:]] self.data = data_by_domain.reshape(data_by_domain.shape[0]*data_by_domain.shape[1],",
"requests.Session() response = session.get(URL, params = { 'id' : id",
"else: # get the train data train_dbd = data_by_domain[font_idxs[:num_fonts]] all_data",
"return src_img, tgt_img else: img, target = self.data[index], self.targets[index] domain_label",
"num_classes = data_by_domain.shape[1] self.all_targets = np.concatenate( [np.arange(num_classes)]*num_fonts, axis=0) self.all_domain_labels =",
"= '0B0GtwTQ6IF9AU3NOdzFzUWZ0aDQ' base_folder = 'fonts' def __init__(self, root, split='train', transform=None,",
"able to heuristically test what happens if we have more",
"not None: tgt_img = self.transform(img) if self.denoise_transform is not None:",
"\"wb\") as f: for chunk in tqdm(response.iter_content(CHUNK_SIZE)): if chunk: #",
"self.all_data[idxs] else: # get the train data train_dbd = data_by_domain[font_idxs[:num_fonts]]",
"f['fonts'][()] np.random.seed(484347) # limit the number of fonts num_fonts =",
"train data train_dbd = data_by_domain[font_idxs[:num_fonts]] all_data = train_dbd.reshape(train_dbd.shape[0]*train_dbd.shape[1], train_dbd.shape[2], train_dbd.shape[3])",
"or not ''' super().__init__(root, transform=transform, target_transform=target_transform) self.split = split self.transform",
"{data_by_domain.shape[1]}\") num_classes = data_by_domain.shape[1] self.all_targets = np.concatenate( [np.arange(num_classes)]*num_fonts, axis=0) self.all_domain_labels",
"41443 test_mean_chars (bool): Use the mean characters as test set",
"destination) def get_confirm_token(response): for key, value in response.cookies.items(): if key.startswith('download_warning'):",
"in response.cookies.items(): if key.startswith('download_warning'): return value return None def save_response_content(response,",
"num_examples > train_val_max: # to be able to heuristically test",
"if split == 'train': idxs = idxs[:num_examples] elif split ==",
"img = self.data[index] img = Image.fromarray(img) if self.transform is not",
"tqdm(response.iter_content(CHUNK_SIZE)): if chunk: # filter out keep-alive new chunks f.write(chunk)",
": id }, stream = True) token = get_confirm_token(response) if",
"h5py.File(str(self.download_path), 'r') as f: data_by_domain = f['fonts'][()] np.random.seed(484347) # limit",
"f: data_by_domain = f['fonts'][()] np.random.seed(484347) # limit the number of",
"(int): Index Returns: tuple: (image, target) where target is index",
"get_confirm_token(response) if token: params = { 'id' : id, 'confirm'",
"= idxs[num_examples: train_val_max] else: idxs = idxs[train_val_max:] self.targets = self.all_targets[idxs]",
"id }, stream = True) token = get_confirm_token(response) if token:",
"5000 if split == 'train': idxs = idxs[:num_examples] elif split",
"value in response.cookies.items(): if key.startswith('download_warning'): return value return None def",
"if self.denoise_transform is not None: src_img = self.denoise_transform(img) return src_img,",
"is index of the target class. \"\"\" if self.denoise: img",
"'0B0GtwTQ6IF9AU3NOdzFzUWZ0aDQ' base_folder = 'fonts' def __init__(self, root, split='train', transform=None, target_transform=None,",
"test what happens if we have more training data train_val_max",
"chunk: # filter out keep-alive new chunks f.write(chunk) class Fonts(VisionDataset):",
"is not None: src_img = self.denoise_transform(img) return src_img, tgt_img else:",
"self.path.mkdir(parents=True, exist_ok=True) self.download_path = self.path / 'fonts.hdf5' if download: self.download()",
"self.data = data_by_domain.reshape(data_by_domain.shape[0]*data_by_domain.shape[1], data_by_domain.shape[2], data_by_domain.shape[3]) self.data = np.concatenate([train_data, self.data], axis=0)",
"CHARS: {data_by_domain.shape[1]}\") num_classes = data_by_domain.shape[1] self.all_targets = np.concatenate( [np.arange(num_classes)]*num_fonts, axis=0)",
"split (str): 'train', 'val', 'test' transform: input transformation target_transform: target",
"train_val_max = 5000 if split == 'train': idxs = idxs[:num_examples]",
"self.denoise_transform(img) return src_img, tgt_img else: img, target = self.data[index], self.targets[index]",
"'fonts.hdf5' if download: self.download() with h5py.File(str(self.download_path), 'r') as f: data_by_domain",
"self.all_data[index], self.all_targets[index] domain_label = self.all_domain_labels[index] # doing this so that",
"self.transform is not None: img = self.transform(img) if self.target_transform is",
"= \"https://docs.google.com/uc?export=download\" session = requests.Session() response = session.get(URL, params =",
"is consistent with all other datasets # to return a",
"axis=0) self.all_domain_labels = np.repeat(np.arange(num_fonts), num_classes) self.all_data = data_by_domain.reshape(data_by_domain.shape[0]*data_by_domain.shape[1], data_by_domain.shape[2], data_by_domain.shape[3])",
"'test' transform: input transformation target_transform: target transformation download (bool): download",
"self.download_path = self.path / 'fonts.hdf5' if download: self.download() with h5py.File(str(self.download_path),",
"save_response_content(response, destination) def get_confirm_token(response): for key, value in response.cookies.items(): if",
"self.base_folder self.path.mkdir(parents=True, exist_ok=True) self.download_path = self.path / 'fonts.hdf5' if download:",
"src_img, tgt_img else: img, target = self.data[index], self.targets[index] domain_label =",
"= all_data[idxs] if num_fonts_pi is not None: data_by_domain = data_by_domain[font_idxs[num_fonts:num_fonts+num_fonts_pi]]",
"Args: root (str): path num_train_domains (int): number of train domains",
"transform=transform, target_transform=target_transform) self.split = split self.transform = transform self.target_transform =",
"path num_train_domains (int): number of train domains up to 41443",
"number of train domains up to 41443 test_mean_chars (bool): Use",
"download(self): if not self.download_path.exists(): download_file_from_google_drive(self.url_id, str(self.download_path)) def __getitem__(self, index): \"\"\"",
"x), axis=(1,2))) return self[idx] def download(self): if not self.download_path.exists(): download_file_from_google_drive(self.url_id,",
"= denoise_transform self.path = Path(self.root) / self.base_folder self.path.mkdir(parents=True, exist_ok=True) self.download_path",
": id, 'confirm' : token } response = session.get(URL, params",
"denoise_transform self.path = Path(self.root) / self.base_folder self.path.mkdir(parents=True, exist_ok=True) self.download_path =",
"import h5py import numpy as np from torchvision.datasets.vision import VisionDataset",
"import tqdm def download_file_from_google_drive(id, destination): URL = \"https://docs.google.com/uc?export=download\" session =",
"if self.transform is not None: tgt_img = self.transform(img) if self.denoise_transform",
"# to return a PIL Image img = Image.fromarray(img) if",
"# limit the number of fonts num_fonts = 100 font_idxs",
"self.data[index], self.targets[index] domain_label = self.domain_labels[index] # doing this so that",
"if self.denoise: img = self.data[index] img = Image.fromarray(img) if self.transform",
"'train': idxs = idxs[:num_examples] elif split == 'val': idxs =",
"self.data = self.all_data[idxs] else: # get the train data train_dbd",
"= self.all_data[index], self.all_targets[index] domain_label = self.all_domain_labels[index] # doing this so",
"self.all_targets[idxs] self.domain_labels = self.all_domain_labels[idxs] self.data = self.all_data[idxs] else: # get",
"tqdm import tqdm def download_file_from_google_drive(id, destination): URL = \"https://docs.google.com/uc?export=download\" session",
"np.arange(len(all_data)) np.random.shuffle(idxs) idxs = idxs[:num_examples] train_data = all_data[idxs] if num_fonts_pi",
"def save_response_content(response, destination): CHUNK_SIZE = 32768 with open(destination, \"wb\") as",
"data_by_domain[font_idxs[:num_fonts]] print(f\"NUM FONTS: {num_fonts}\") print(f\"NUM CHARS: {data_by_domain.shape[1]}\") num_classes = data_by_domain.shape[1]",
"CHUNK_SIZE = 32768 with open(destination, \"wb\") as f: for chunk",
"__getitem__(self, index): \"\"\" Args: index (int): Index Returns: tuple: (image,",
"token = get_confirm_token(response) if token: params = { 'id' :",
"target, domain_label def get_item_from_all(self, index): img, target = self.all_data[index], self.all_targets[index]",
"= data_by_domain.reshape(data_by_domain.shape[0]*data_by_domain.shape[1], data_by_domain.shape[2], data_by_domain.shape[3]) idxs = np.arange(len(self.all_data)) np.random.shuffle(idxs) train_val_max =",
"token: params = { 'id' : id, 'confirm' : token",
"idxs[:num_examples] train_data = all_data[idxs] if num_fonts_pi is not None: data_by_domain",
"= 32768 with open(destination, \"wb\") as f: for chunk in",
"self.domain_labels = self.all_domain_labels[idxs] self.data = self.all_data[idxs] else: # get the",
"= np.concatenate( [np.arange(num_classes)]*num_fonts, axis=0) self.all_domain_labels = np.repeat(np.arange(num_fonts), num_classes) self.all_data =",
"heuristically test what happens if we have more training data",
"get_item_from_all(self, index): img, target = self.all_data[index], self.all_targets[index] domain_label = self.all_domain_labels[index]",
"True) token = get_confirm_token(response) if token: params = { 'id'",
"= self.all_domain_labels[index] # doing this so that it is consistent",
"data_by_domain[font_idxs[:num_fonts]] all_data = train_dbd.reshape(train_dbd.shape[0]*train_dbd.shape[1], train_dbd.shape[2], train_dbd.shape[3]) idxs = np.arange(len(all_data)) np.random.shuffle(idxs)",
"= f['fonts'][()] np.random.seed(484347) # limit the number of fonts num_fonts",
"self.transform(img) if self.target_transform is not None: target = self.target_transform(target) return",
"train_dbd.shape[2], train_dbd.shape[3]) idxs = np.arange(len(all_data)) np.random.shuffle(idxs) idxs = idxs[:num_examples] train_data",
"- x), axis=(1,2))) return self[idx] def download(self): if not self.download_path.exists():",
"= np.argmin(np.sum(np.square(all_imgs - x), axis=(1,2))) return self[idx] def download(self): if",
"self.download_path.exists(): download_file_from_google_drive(self.url_id, str(self.download_path)) def __getitem__(self, index): \"\"\" Args: index (int):",
"= session.get(URL, params = params, stream = True) save_response_content(response, destination)",
"= train_dbd.reshape(train_dbd.shape[0]*train_dbd.shape[1], train_dbd.shape[2], train_dbd.shape[3]) idxs = np.arange(len(all_data)) np.random.shuffle(idxs) idxs =",
"session.get(URL, params = { 'id' : id }, stream =",
"tqdm def download_file_from_google_drive(id, destination): URL = \"https://docs.google.com/uc?export=download\" session = requests.Session()",
"chunk in tqdm(response.iter_content(CHUNK_SIZE)): if chunk: # filter out keep-alive new",
"= data_by_domain[font_idxs[:num_fonts]] all_data = train_dbd.reshape(train_dbd.shape[0]*train_dbd.shape[1], train_dbd.shape[2], train_dbd.shape[3]) idxs = np.arange(len(all_data))",
"= data_by_domain[font_idxs[num_fonts:num_fonts+num_fonts_pi]] else: data_by_domain = data_by_domain[font_idxs[num_fonts:]] self.data = data_by_domain.reshape(data_by_domain.shape[0]*data_by_domain.shape[1], data_by_domain.shape[2],",
"np.concatenate([train_data, self.data], axis=0) def get_nearest_neighbor(self, all_imgs, x): idx = np.argmin(np.sum(np.square(all_imgs",
"for chunk in tqdm(response.iter_content(CHUNK_SIZE)): if chunk: # filter out keep-alive",
"train_val_max: # to be able to heuristically test what happens",
"domain_label = self.domain_labels[index] # doing this so that it is",
"as f: for chunk in tqdm(response.iter_content(CHUNK_SIZE)): if chunk: # filter",
"stream = True) save_response_content(response, destination) def get_confirm_token(response): for key, value",
"else: img, target = self.data[index], self.targets[index] domain_label = self.domain_labels[index] #",
"with open(destination, \"wb\") as f: for chunk in tqdm(response.iter_content(CHUNK_SIZE)): if",
"True) save_response_content(response, destination) def get_confirm_token(response): for key, value in response.cookies.items():",
"= data_by_domain[font_idxs[num_fonts:]] self.data = data_by_domain.reshape(data_by_domain.shape[0]*data_by_domain.shape[1], data_by_domain.shape[2], data_by_domain.shape[3]) self.data = np.concatenate([train_data,",
"download=True, denoise=False, denoise_transform=None, num_fonts_pi=None, num_examples=2500): ''' Args: root (str): path",
"num_fonts = 100 font_idxs = np.arange(len(data_by_domain)) np.random.shuffle(font_idxs) if not denoise:",
"target) where target is index of the target class. \"\"\"",
"all_data = train_dbd.reshape(train_dbd.shape[0]*train_dbd.shape[1], train_dbd.shape[2], train_dbd.shape[3]) idxs = np.arange(len(all_data)) np.random.shuffle(idxs) idxs",
"data_by_domain = data_by_domain[font_idxs[:num_fonts]] print(f\"NUM FONTS: {num_fonts}\") print(f\"NUM CHARS: {data_by_domain.shape[1]}\") num_classes",
"it is consistent with all other datasets # to return",
"from tqdm import tqdm def download_file_from_google_drive(id, destination): URL = \"https://docs.google.com/uc?export=download\"",
"idxs[train_val_max:] self.targets = self.all_targets[idxs] self.domain_labels = self.all_domain_labels[idxs] self.data = self.all_data[idxs]",
"'id' : id, 'confirm' : token } response = session.get(URL,",
"root, split='train', transform=None, target_transform=None, download=True, denoise=False, denoise_transform=None, num_fonts_pi=None, num_examples=2500): '''",
"class. \"\"\" if self.denoise: img = self.data[index] img = Image.fromarray(img)",
"base_folder = 'fonts' def __init__(self, root, split='train', transform=None, target_transform=None, download=True,",
"font_idxs = np.arange(len(data_by_domain)) np.random.shuffle(font_idxs) if not denoise: data_by_domain = data_by_domain[font_idxs[:num_fonts]]",
"= self.all_domain_labels[idxs] self.data = self.all_data[idxs] else: # get the train",
"self.transform = transform self.target_transform = target_transform self.denoise = denoise self.denoise_transform",
"= denoise self.denoise_transform = denoise_transform self.path = Path(self.root) / self.base_folder",
"denoise self.denoise_transform = denoise_transform self.path = Path(self.root) / self.base_folder self.path.mkdir(parents=True,",
"'confirm' : token } response = session.get(URL, params = params,",
"super().__init__(root, transform=transform, target_transform=target_transform) self.split = split self.transform = transform self.target_transform",
"if download: self.download() with h5py.File(str(self.download_path), 'r') as f: data_by_domain =",
"to be able to heuristically test what happens if we",
"response = session.get(URL, params = { 'id' : id },",
"input transformation target_transform: target transformation download (bool): download or not",
"}, stream = True) token = get_confirm_token(response) if token: params",
"def __init__(self, root, split='train', transform=None, target_transform=None, download=True, denoise=False, denoise_transform=None, num_fonts_pi=None,",
"np.arange(len(data_by_domain)) np.random.shuffle(font_idxs) if not denoise: data_by_domain = data_by_domain[font_idxs[:num_fonts]] print(f\"NUM FONTS:",
"Image img = Image.fromarray(img) if self.transform is not None: img",
"open(destination, \"wb\") as f: for chunk in tqdm(response.iter_content(CHUNK_SIZE)): if chunk:",
"self.target_transform = target_transform self.denoise = denoise self.denoise_transform = denoise_transform self.path",
"not denoise: data_by_domain = data_by_domain[font_idxs[:num_fonts]] print(f\"NUM FONTS: {num_fonts}\") print(f\"NUM CHARS:",
"in tqdm(response.iter_content(CHUNK_SIZE)): if chunk: # filter out keep-alive new chunks",
"idxs = idxs[train_val_max:] self.targets = self.all_targets[idxs] self.domain_labels = self.all_domain_labels[idxs] self.data",
"import Path import h5py import numpy as np from torchvision.datasets.vision",
"Returns: tuple: (image, target) where target is index of the",
"destination): URL = \"https://docs.google.com/uc?export=download\" session = requests.Session() response = session.get(URL,",
"params = params, stream = True) save_response_content(response, destination) def get_confirm_token(response):",
"the number of fonts num_fonts = 100 font_idxs = np.arange(len(data_by_domain))",
"= data_by_domain.shape[1] self.all_targets = np.concatenate( [np.arange(num_classes)]*num_fonts, axis=0) self.all_domain_labels = np.repeat(np.arange(num_fonts),",
"''' super().__init__(root, transform=transform, target_transform=target_transform) self.split = split self.transform = transform",
"train_data = all_data[idxs] if num_fonts_pi is not None: data_by_domain =",
"self[idx] def download(self): if not self.download_path.exists(): download_file_from_google_drive(self.url_id, str(self.download_path)) def __getitem__(self,",
"with all other datasets # to return a PIL Image",
"target_transform=None, download=True, denoise=False, denoise_transform=None, num_fonts_pi=None, num_examples=2500): ''' Args: root (str):",
"tgt_img else: img, target = self.data[index], self.targets[index] domain_label = self.domain_labels[index]",
"(int): number of train domains up to 41443 test_mean_chars (bool):",
"else: idxs = idxs[train_val_max:] self.targets = self.all_targets[idxs] self.domain_labels = self.all_domain_labels[idxs]",
"response.cookies.items(): if key.startswith('download_warning'): return value return None def save_response_content(response, destination):",
"characters as test set split (str): 'train', 'val', 'test' transform:",
"target transformation download (bool): download or not ''' super().__init__(root, transform=transform,",
"stream = True) token = get_confirm_token(response) if token: params =",
"the target class. \"\"\" if self.denoise: img = self.data[index] img",
"self.all_data = data_by_domain.reshape(data_by_domain.shape[0]*data_by_domain.shape[1], data_by_domain.shape[2], data_by_domain.shape[3]) idxs = np.arange(len(self.all_data)) np.random.shuffle(idxs) train_val_max",
"id, 'confirm' : token } response = session.get(URL, params =",
"print(f\"NUM FONTS: {num_fonts}\") print(f\"NUM CHARS: {data_by_domain.shape[1]}\") num_classes = data_by_domain.shape[1] self.all_targets"
] |
[
"nums: List[int]) -> List[List[int]]: if len(nums) == 1: return [nums]",
"i in range(0, len(new_nums)): if i + 1 < len(new_nums)",
"[] for i in range(0, len(new_nums)): if i + 1",
"in range(0, len(new_nums)): if i + 1 < len(new_nums) and",
"-> List[List[int]]: if len(nums) == 1: return [nums] new_nums =",
"res = [] for i in range(0, len(new_nums)): if i",
"continue new_nums[i], new_nums[0] = new_nums[0], new_nums[i] sub_result = self.permuteUnique(new_nums[1:]) for",
"new_nums[0] = new_nums[0], new_nums[i] sub_result = self.permuteUnique(new_nums[1:]) for r in",
"and new_nums[i] == new_nums[i + 1]: continue new_nums[i], new_nums[0] =",
"同46,加上排序即可 \"\"\" class Solution: def permuteUnique(self, nums: List[int]) -> List[List[int]]:",
"1]: continue new_nums[i], new_nums[0] = new_nums[0], new_nums[i] sub_result = self.permuteUnique(new_nums[1:])",
"+ 1 < len(new_nums) and new_nums[i] == new_nums[i + 1]:",
"new_nums[i] == new_nums[i + 1]: continue new_nums[i], new_nums[0] = new_nums[0],",
"new_nums[0], new_nums[i] sub_result = self.permuteUnique(new_nums[1:]) for r in sub_result: res.append([new_nums[0]]",
"in sub_result: res.append([new_nums[0]] + r.copy()) new_nums[i], new_nums[0] = new_nums[0], new_nums[i]",
"self.permuteUnique(new_nums[1:]) for r in sub_result: res.append([new_nums[0]] + r.copy()) new_nums[i], new_nums[0]",
"solution: 同46,加上排序即可 \"\"\" class Solution: def permuteUnique(self, nums: List[int]) ->",
"new_nums[i + 1]: continue new_nums[i], new_nums[0] = new_nums[0], new_nums[i] sub_result",
"= self.permuteUnique(new_nums[1:]) for r in sub_result: res.append([new_nums[0]] + r.copy()) new_nums[i],",
"new_nums.sort() res = [] for i in range(0, len(new_nums)): if",
"\"\"\" link: https://leetcode.com/problems/permutations-ii problem: 求全排列,nums中存在重复数 solution: 同46,加上排序即可 \"\"\" class Solution:",
"+ 1]: continue new_nums[i], new_nums[0] = new_nums[0], new_nums[i] sub_result =",
"problem: 求全排列,nums中存在重复数 solution: 同46,加上排序即可 \"\"\" class Solution: def permuteUnique(self, nums:",
"len(new_nums)): if i + 1 < len(new_nums) and new_nums[i] ==",
"link: https://leetcode.com/problems/permutations-ii problem: 求全排列,nums中存在重复数 solution: 同46,加上排序即可 \"\"\" class Solution: def",
"new_nums[i], new_nums[0] = new_nums[0], new_nums[i] sub_result = self.permuteUnique(new_nums[1:]) for r",
"return [nums] new_nums = nums.copy() new_nums.sort() res = [] for",
"= [] for i in range(0, len(new_nums)): if i +",
"i + 1 < len(new_nums) and new_nums[i] == new_nums[i +",
"sub_result = self.permuteUnique(new_nums[1:]) for r in sub_result: res.append([new_nums[0]] + r.copy())",
"\"\"\" class Solution: def permuteUnique(self, nums: List[int]) -> List[List[int]]: if",
"if i + 1 < len(new_nums) and new_nums[i] == new_nums[i",
"len(new_nums) and new_nums[i] == new_nums[i + 1]: continue new_nums[i], new_nums[0]",
"res.append([new_nums[0]] + r.copy()) new_nums[i], new_nums[0] = new_nums[0], new_nums[i] return res",
"class Solution: def permuteUnique(self, nums: List[int]) -> List[List[int]]: if len(nums)",
"1 < len(new_nums) and new_nums[i] == new_nums[i + 1]: continue",
"= new_nums[0], new_nums[i] sub_result = self.permuteUnique(new_nums[1:]) for r in sub_result:",
"if len(nums) == 1: return [nums] new_nums = nums.copy() new_nums.sort()",
"List[List[int]]: if len(nums) == 1: return [nums] new_nums = nums.copy()",
"for r in sub_result: res.append([new_nums[0]] + r.copy()) new_nums[i], new_nums[0] =",
"r in sub_result: res.append([new_nums[0]] + r.copy()) new_nums[i], new_nums[0] = new_nums[0],",
"< len(new_nums) and new_nums[i] == new_nums[i + 1]: continue new_nums[i],",
"def permuteUnique(self, nums: List[int]) -> List[List[int]]: if len(nums) == 1:",
"Solution: def permuteUnique(self, nums: List[int]) -> List[List[int]]: if len(nums) ==",
"== 1: return [nums] new_nums = nums.copy() new_nums.sort() res =",
"求全排列,nums中存在重复数 solution: 同46,加上排序即可 \"\"\" class Solution: def permuteUnique(self, nums: List[int])",
"== new_nums[i + 1]: continue new_nums[i], new_nums[0] = new_nums[0], new_nums[i]",
"new_nums = nums.copy() new_nums.sort() res = [] for i in",
"1: return [nums] new_nums = nums.copy() new_nums.sort() res = []",
"sub_result: res.append([new_nums[0]] + r.copy()) new_nums[i], new_nums[0] = new_nums[0], new_nums[i] return",
"permuteUnique(self, nums: List[int]) -> List[List[int]]: if len(nums) == 1: return",
"[nums] new_nums = nums.copy() new_nums.sort() res = [] for i",
"range(0, len(new_nums)): if i + 1 < len(new_nums) and new_nums[i]",
"new_nums[i] sub_result = self.permuteUnique(new_nums[1:]) for r in sub_result: res.append([new_nums[0]] +",
"List[int]) -> List[List[int]]: if len(nums) == 1: return [nums] new_nums",
"for i in range(0, len(new_nums)): if i + 1 <",
"https://leetcode.com/problems/permutations-ii problem: 求全排列,nums中存在重复数 solution: 同46,加上排序即可 \"\"\" class Solution: def permuteUnique(self,",
"= nums.copy() new_nums.sort() res = [] for i in range(0,",
"nums.copy() new_nums.sort() res = [] for i in range(0, len(new_nums)):",
"len(nums) == 1: return [nums] new_nums = nums.copy() new_nums.sort() res"
] |
[
"conf.setAppName(\"BigData\") sc=SparkContext(conf=conf) ssc=StreamingContext(sc,int(sys.argv[1])) ssc.checkpoint(\"/checkpoint_BIGDATA\") ''' #Selecting a window : #outpu3:",
"= count +1 conf=SparkConf() conf.setAppName(\"BigData\") sc=SparkContext(conf=conf) ssc=StreamingContext(sc,int(sys.argv[1])) ssc.checkpoint(\"/checkpoint_BIGDATA\") ''' #Selecting",
"window : #outpu3: inputStream=ssc.socketTextStream(\"localhost\",9009) dataStream = inputStream.window(int(sys.argv[1]),int(sys.argv[2])) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) count=septweet.reduceByKey(lambda",
"outpu1 inputStream=ssc.socketTextStream(\"localhost\",9009) dataStream = inputStream.window(int(sys.argv[2]),int(sys.argv[1])) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) count=septweet.reduceByKey(lambda x,y:x+y) sortcount",
"inputStream=ssc.socketTextStream(\"localhost\",9009) dataStream = inputStream.window(int(sys.argv[2]),int(sys.argv[1])) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) count=septweet.reduceByKey(lambda x,y:x+y) sortcount =",
"#outpu2 dataStream=ssc.socketTextStream(\"localhost\",9009) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) #septweet.pprint() count=septweet.reduceByKeyAndWindow(lambda x,y:x+y,int(sys.argv[1]),int(sys.argv[2])) sortcount = count.transform(lambda",
"pyspark.sql import Row,SQLContext import sys import requests def tmp(x): y",
"by window: #outpu2 dataStream=ssc.socketTextStream(\"localhost\",9009) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) #septweet.pprint() count=septweet.reduceByKeyAndWindow(lambda x,y:x+y,int(sys.argv[1]),int(sys.argv[2])) sortcount",
"tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) count=septweet.reduceByKey(lambda x,y:x+y) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[0],ascending=True))",
"#septweet.pprint() count=septweet.reduceByKeyAndWindow(lambda x,y:x+y,int(sys.argv[1]),int(sys.argv[2])) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[0],ascending=True)) sortcount",
"= tweet1.map(lambda a : a[0]) res.foreachRDD(topprint) #TO maintain state #",
"res.foreachRDD(topprint) #res.pprint(3) ''' ''' #Selecting a datastream and then reducing",
"sortcount = sortcount.transform(lambda rdd :rdd.sortBy(lambda a:a[1],ascending=False)) tweet1=sortcount.filter(lambda w:w[0] is not",
"findspark findspark.init() from pyspark import SparkConf,SparkContext from pyspark.streaming import StreamingContext",
"count.transform(lambda rdd :rdd.sortBy(lambda a:a[1],ascending=False)) tweet1=sortcount.filter(lambda w:w[0] is not '') tweet1.pprint()",
"a:a[1],ascending=False)) tweet1=sortcount.filter(lambda w:w[0] is not '') #tweet1.pprint() res = tweet1.map(lambda",
"% i,end=',') count = count +1 conf=SparkConf() conf.setAppName(\"BigData\") sc=SparkContext(conf=conf) ssc=StreamingContext(sc,int(sys.argv[1]))",
"# totalcount.pprint() #To Perform operation on each RDD # totalcount.foreachRDD(process_rdd)",
"= (x.split(';')[7]).split(',') return (y) def forf(x): for i in x:",
"count = count +1 conf=SparkConf() conf.setAppName(\"BigData\") sc=SparkContext(conf=conf) ssc=StreamingContext(sc,int(sys.argv[1])) ssc.checkpoint(\"/checkpoint_BIGDATA\") '''",
"a : a[0]) res.foreachRDD(topprint) ''' #Try in outpu1 inputStream=ssc.socketTextStream(\"localhost\",9009) dataStream",
"i,end=',') count = count +1 conf=SparkConf() conf.setAppName(\"BigData\") sc=SparkContext(conf=conf) ssc=StreamingContext(sc,int(sys.argv[1])) ssc.checkpoint(\"/checkpoint_BIGDATA\")",
"sc=SparkContext(conf=conf) ssc=StreamingContext(sc,int(sys.argv[1])) ssc.checkpoint(\"/checkpoint_BIGDATA\") ''' #Selecting a window : #outpu3: inputStream=ssc.socketTextStream(\"localhost\",9009)",
"# totalcount=tweet.updateStateByKey(aggregate_tweets_count) # totalcount.pprint() #To Perform operation on each RDD",
"tweet1.map(lambda a : a[0]) res.foreachRDD(topprint) #res.pprint(3) ''' ''' #Selecting a",
"Row,SQLContext import sys import requests def tmp(x): y = (x.split(';')[7]).split(',')",
"inputStream=ssc.socketTextStream(\"localhost\",9009) dataStream = inputStream.window(int(sys.argv[1]),int(sys.argv[2])) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) count=septweet.reduceByKey(lambda x,y:x+y) sortcount =",
"state # totalcount=tweet.updateStateByKey(aggregate_tweets_count) # totalcount.pprint() #To Perform operation on each",
"w:w[0] is not '') tweet1.pprint() res = tweet1.map(lambda a :",
"from pyspark.streaming import StreamingContext from pyspark.sql import Row,SQLContext import sys",
"topprint(time,rdd): res1=rdd.take(5) count=0 for i in res1: if(count==4): print(\"%s\" %",
"tweet1.map(lambda a : a[0]) res.foreachRDD(topprint) ''' #Try in outpu1 inputStream=ssc.socketTextStream(\"localhost\",9009)",
"inputStream.window(int(sys.argv[2]),int(sys.argv[1])) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) count=septweet.reduceByKey(lambda x,y:x+y) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda",
"#TO maintain state # totalcount=tweet.updateStateByKey(aggregate_tweets_count) # totalcount.pprint() #To Perform operation",
"= tweet1.map(lambda a : a[0]) res.foreachRDD(topprint) ''' #Try in outpu1",
"#To Perform operation on each RDD # totalcount.foreachRDD(process_rdd) ssc.start() ssc.awaitTermination(25)",
"res = tweet1.map(lambda a : a[0]) res.foreachRDD(topprint) #res.pprint(3) ''' '''",
"SparkConf,SparkContext from pyspark.streaming import StreamingContext from pyspark.sql import Row,SQLContext import",
"sys import requests def tmp(x): y = (x.split(';')[7]).split(',') return (y)",
"res = tweet1.map(lambda a : a[0]) res.foreachRDD(topprint) ''' #Try in",
"tweet1=sortcount.filter(lambda w:w[0] is not '') tweet1.pprint() res = tweet1.map(lambda a",
"forf(x): for i in x: yield (i,1) def topprint(time,rdd): res1=rdd.take(5)",
"septweet=tweet.flatMap(forf) #septweet.pprint() count=septweet.reduceByKeyAndWindow(lambda x,y:x+y,int(sys.argv[1]),int(sys.argv[2])) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[0],ascending=True))",
"''' #Try in outpu1 inputStream=ssc.socketTextStream(\"localhost\",9009) dataStream = inputStream.window(int(sys.argv[2]),int(sys.argv[1])) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf)",
"datastream and then reducing by window: #outpu2 dataStream=ssc.socketTextStream(\"localhost\",9009) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf)",
"#Selecting a window : #outpu3: inputStream=ssc.socketTextStream(\"localhost\",9009) dataStream = inputStream.window(int(sys.argv[1]),int(sys.argv[2])) tweet=dataStream.map(tmp)",
"x,y:x+y) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[0],ascending=True)) sortcount = sortcount.transform(lambda",
"(x.split(';')[7]).split(',') return (y) def forf(x): for i in x: yield",
"Perform operation on each RDD # totalcount.foreachRDD(process_rdd) ssc.start() ssc.awaitTermination(25) ssc.stop()",
"a : a[0]) res.foreachRDD(topprint) #TO maintain state # totalcount=tweet.updateStateByKey(aggregate_tweets_count) #",
"reducing by window: #outpu2 dataStream=ssc.socketTextStream(\"localhost\",9009) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) #septweet.pprint() count=septweet.reduceByKeyAndWindow(lambda x,y:x+y,int(sys.argv[1]),int(sys.argv[2]))",
"''' #Selecting a window : #outpu3: inputStream=ssc.socketTextStream(\"localhost\",9009) dataStream = inputStream.window(int(sys.argv[1]),int(sys.argv[2]))",
"''' #Selecting a datastream and then reducing by window: #outpu2",
"tmp(x): y = (x.split(';')[7]).split(',') return (y) def forf(x): for i",
"#res.pprint(3) ''' ''' #Selecting a datastream and then reducing by",
"rdd :rdd.sortBy(lambda a:a[0],ascending=True)) sortcount = sortcount.transform(lambda rdd :rdd.sortBy(lambda a:a[1],ascending=False)) tweet1=sortcount.filter(lambda",
"tweet1.pprint() res = tweet1.map(lambda a : a[0]) res.foreachRDD(topprint) #res.pprint(3) '''",
"= count.transform(lambda rdd :rdd.sortBy(lambda a:a[0],ascending=True)) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda",
"+1 conf=SparkConf() conf.setAppName(\"BigData\") sc=SparkContext(conf=conf) ssc=StreamingContext(sc,int(sys.argv[1])) ssc.checkpoint(\"/checkpoint_BIGDATA\") ''' #Selecting a window",
"tweet1.map(lambda a : a[0]) res.foreachRDD(topprint) #TO maintain state # totalcount=tweet.updateStateByKey(aggregate_tweets_count)",
"(y) def forf(x): for i in x: yield (i,1) def",
"dataStream = inputStream.window(int(sys.argv[1]),int(sys.argv[2])) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) count=septweet.reduceByKey(lambda x,y:x+y) sortcount = count.transform(lambda",
"a[0]) res.foreachRDD(topprint) #res.pprint(3) ''' ''' #Selecting a datastream and then",
": a[0]) res.foreachRDD(topprint) #TO maintain state # totalcount=tweet.updateStateByKey(aggregate_tweets_count) # totalcount.pprint()",
"pyspark import SparkConf,SparkContext from pyspark.streaming import StreamingContext from pyspark.sql import",
":rdd.sortBy(lambda a:a[1],ascending=False)) tweet1=sortcount.filter(lambda w:w[0] is not '') #tweet1.pprint() res =",
"a window : #outpu3: inputStream=ssc.socketTextStream(\"localhost\",9009) dataStream = inputStream.window(int(sys.argv[1]),int(sys.argv[2])) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf)",
"count.transform(lambda rdd :rdd.sortBy(lambda a:a[0],ascending=True)) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[1],ascending=False))",
"= count.transform(lambda rdd :rdd.sortBy(lambda a:a[1],ascending=False)) tweet1=sortcount.filter(lambda w:w[0] is not '')",
"if(count==4): print(\"%s\" % i) else: print(\"%s\" % i,end=',') count =",
"tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) count=septweet.reduceByKey(lambda x,y:x+y) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[1],ascending=False))",
"a:a[1],ascending=False)) tweet1=sortcount.filter(lambda w:w[0] is not '') tweet1.pprint() res = tweet1.map(lambda",
"in res1: if(count==4): print(\"%s\" % i) else: print(\"%s\" % i,end=',')",
":rdd.sortBy(lambda a:a[0],ascending=True)) sortcount = sortcount.transform(lambda rdd :rdd.sortBy(lambda a:a[1],ascending=False)) tweet1=sortcount.filter(lambda w:w[0]",
"'') tweet1.pprint() res = tweet1.map(lambda a : a[0]) res.foreachRDD(topprint) #res.pprint(3)",
"#tweet1.pprint() res = tweet1.map(lambda a : a[0]) res.foreachRDD(topprint) #TO maintain",
"import sys import requests def tmp(x): y = (x.split(';')[7]).split(',') return",
"sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[0],ascending=True)) sortcount = sortcount.transform(lambda rdd",
"'') #tweet1.pprint() res = tweet1.map(lambda a : a[0]) res.foreachRDD(topprint) #TO",
"= inputStream.window(int(sys.argv[1]),int(sys.argv[2])) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) count=septweet.reduceByKey(lambda x,y:x+y) sortcount = count.transform(lambda rdd",
"#Selecting a datastream and then reducing by window: #outpu2 dataStream=ssc.socketTextStream(\"localhost\",9009)",
"import Row,SQLContext import sys import requests def tmp(x): y =",
"a[0]) res.foreachRDD(topprint) ''' #Try in outpu1 inputStream=ssc.socketTextStream(\"localhost\",9009) dataStream = inputStream.window(int(sys.argv[2]),int(sys.argv[1]))",
"res = tweet1.map(lambda a : a[0]) res.foreachRDD(topprint) #TO maintain state",
"from pyspark.sql import Row,SQLContext import sys import requests def tmp(x):",
"= inputStream.window(int(sys.argv[2]),int(sys.argv[1])) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) count=septweet.reduceByKey(lambda x,y:x+y) sortcount = count.transform(lambda rdd",
"not '') #tweet1.pprint() res = tweet1.map(lambda a : a[0]) res.foreachRDD(topprint)",
"i in x: yield (i,1) def topprint(time,rdd): res1=rdd.take(5) count=0 for",
"count=septweet.reduceByKey(lambda x,y:x+y) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[1],ascending=False)) tweet1=sortcount.filter(lambda w:w[0]",
"res1: if(count==4): print(\"%s\" % i) else: print(\"%s\" % i,end=',') count",
"def forf(x): for i in x: yield (i,1) def topprint(time,rdd):",
"else: print(\"%s\" % i,end=',') count = count +1 conf=SparkConf() conf.setAppName(\"BigData\")",
"count=0 for i in res1: if(count==4): print(\"%s\" % i) else:",
"a datastream and then reducing by window: #outpu2 dataStream=ssc.socketTextStream(\"localhost\",9009) tweet=dataStream.map(tmp)",
"x,y:x+y) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[1],ascending=False)) tweet1=sortcount.filter(lambda w:w[0] is",
"= tweet1.map(lambda a : a[0]) res.foreachRDD(topprint) #res.pprint(3) ''' ''' #Selecting",
"a : a[0]) res.foreachRDD(topprint) #res.pprint(3) ''' ''' #Selecting a datastream",
"res1=rdd.take(5) count=0 for i in res1: if(count==4): print(\"%s\" % i)",
"septweet=tweet.flatMap(forf) count=septweet.reduceByKey(lambda x,y:x+y) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[0],ascending=True)) sortcount",
":rdd.sortBy(lambda a:a[0],ascending=True)) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[1],ascending=False)) tweet1=sortcount.filter(lambda w:w[0]",
"rdd :rdd.sortBy(lambda a:a[1],ascending=False)) tweet1=sortcount.filter(lambda w:w[0] is not '') #tweet1.pprint() res",
"w:w[0] is not '') #tweet1.pprint() res = tweet1.map(lambda a :",
"% i) else: print(\"%s\" % i,end=',') count = count +1",
"is not '') tweet1.pprint() res = tweet1.map(lambda a : a[0])",
"not '') tweet1.pprint() res = tweet1.map(lambda a : a[0]) res.foreachRDD(topprint)",
"tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) #septweet.pprint() count=septweet.reduceByKeyAndWindow(lambda x,y:x+y,int(sys.argv[1]),int(sys.argv[2])) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda",
"count +1 conf=SparkConf() conf.setAppName(\"BigData\") sc=SparkContext(conf=conf) ssc=StreamingContext(sc,int(sys.argv[1])) ssc.checkpoint(\"/checkpoint_BIGDATA\") ''' #Selecting a",
": a[0]) res.foreachRDD(topprint) #res.pprint(3) ''' ''' #Selecting a datastream and",
"sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[1],ascending=False)) tweet1=sortcount.filter(lambda w:w[0] is not",
"print(\"%s\" % i,end=',') count = count +1 conf=SparkConf() conf.setAppName(\"BigData\") sc=SparkContext(conf=conf)",
"in x: yield (i,1) def topprint(time,rdd): res1=rdd.take(5) count=0 for i",
"yield (i,1) def topprint(time,rdd): res1=rdd.take(5) count=0 for i in res1:",
"ssc=StreamingContext(sc,int(sys.argv[1])) ssc.checkpoint(\"/checkpoint_BIGDATA\") ''' #Selecting a window : #outpu3: inputStream=ssc.socketTextStream(\"localhost\",9009) dataStream",
"i in res1: if(count==4): print(\"%s\" % i) else: print(\"%s\" %",
"requests def tmp(x): y = (x.split(';')[7]).split(',') return (y) def forf(x):",
": a[0]) res.foreachRDD(topprint) ''' #Try in outpu1 inputStream=ssc.socketTextStream(\"localhost\",9009) dataStream =",
"dataStream=ssc.socketTextStream(\"localhost\",9009) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) #septweet.pprint() count=septweet.reduceByKeyAndWindow(lambda x,y:x+y,int(sys.argv[1]),int(sys.argv[2])) sortcount = count.transform(lambda rdd",
":rdd.sortBy(lambda a:a[1],ascending=False)) tweet1=sortcount.filter(lambda w:w[0] is not '') tweet1.pprint() res =",
"import findspark findspark.init() from pyspark import SparkConf,SparkContext from pyspark.streaming import",
"maintain state # totalcount=tweet.updateStateByKey(aggregate_tweets_count) # totalcount.pprint() #To Perform operation on",
"for i in x: yield (i,1) def topprint(time,rdd): res1=rdd.take(5) count=0",
"def tmp(x): y = (x.split(';')[7]).split(',') return (y) def forf(x): for",
"for i in res1: if(count==4): print(\"%s\" % i) else: print(\"%s\"",
"sortcount.transform(lambda rdd :rdd.sortBy(lambda a:a[1],ascending=False)) tweet1=sortcount.filter(lambda w:w[0] is not '') #tweet1.pprint()",
"ssc.checkpoint(\"/checkpoint_BIGDATA\") ''' #Selecting a window : #outpu3: inputStream=ssc.socketTextStream(\"localhost\",9009) dataStream =",
"y = (x.split(';')[7]).split(',') return (y) def forf(x): for i in",
"findspark.init() from pyspark import SparkConf,SparkContext from pyspark.streaming import StreamingContext from",
"'') #tweet1.pprint() res = tweet1.map(lambda a : a[0]) res.foreachRDD(topprint) '''",
"= sortcount.transform(lambda rdd :rdd.sortBy(lambda a:a[1],ascending=False)) tweet1=sortcount.filter(lambda w:w[0] is not '')",
"septweet=tweet.flatMap(forf) count=septweet.reduceByKey(lambda x,y:x+y) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[1],ascending=False)) tweet1=sortcount.filter(lambda",
"in outpu1 inputStream=ssc.socketTextStream(\"localhost\",9009) dataStream = inputStream.window(int(sys.argv[2]),int(sys.argv[1])) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) count=septweet.reduceByKey(lambda x,y:x+y)",
"StreamingContext from pyspark.sql import Row,SQLContext import sys import requests def",
"x: yield (i,1) def topprint(time,rdd): res1=rdd.take(5) count=0 for i in",
"''' ''' #Selecting a datastream and then reducing by window:",
"and then reducing by window: #outpu2 dataStream=ssc.socketTextStream(\"localhost\",9009) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) #septweet.pprint()",
"a:a[0],ascending=True)) sortcount = sortcount.transform(lambda rdd :rdd.sortBy(lambda a:a[1],ascending=False)) tweet1=sortcount.filter(lambda w:w[0] is",
"res.foreachRDD(topprint) ''' #Try in outpu1 inputStream=ssc.socketTextStream(\"localhost\",9009) dataStream = inputStream.window(int(sys.argv[2]),int(sys.argv[1])) tweet=dataStream.map(tmp)",
"x,y:x+y,int(sys.argv[1]),int(sys.argv[2])) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[0],ascending=True)) sortcount = count.transform(lambda",
"def topprint(time,rdd): res1=rdd.take(5) count=0 for i in res1: if(count==4): print(\"%s\"",
"totalcount.pprint() #To Perform operation on each RDD # totalcount.foreachRDD(process_rdd) ssc.start()",
"is not '') #tweet1.pprint() res = tweet1.map(lambda a : a[0])",
"(i,1) def topprint(time,rdd): res1=rdd.take(5) count=0 for i in res1: if(count==4):",
"from pyspark import SparkConf,SparkContext from pyspark.streaming import StreamingContext from pyspark.sql",
"a[0]) res.foreachRDD(topprint) #TO maintain state # totalcount=tweet.updateStateByKey(aggregate_tweets_count) # totalcount.pprint() #To",
"res.foreachRDD(topprint) #TO maintain state # totalcount=tweet.updateStateByKey(aggregate_tweets_count) # totalcount.pprint() #To Perform",
"count.transform(lambda rdd :rdd.sortBy(lambda a:a[0],ascending=True)) sortcount = sortcount.transform(lambda rdd :rdd.sortBy(lambda a:a[1],ascending=False))",
"count=septweet.reduceByKeyAndWindow(lambda x,y:x+y,int(sys.argv[1]),int(sys.argv[2])) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[0],ascending=True)) sortcount =",
"print(\"%s\" % i) else: print(\"%s\" % i,end=',') count = count",
"i) else: print(\"%s\" % i,end=',') count = count +1 conf=SparkConf()",
"totalcount=tweet.updateStateByKey(aggregate_tweets_count) # totalcount.pprint() #To Perform operation on each RDD #",
"#Try in outpu1 inputStream=ssc.socketTextStream(\"localhost\",9009) dataStream = inputStream.window(int(sys.argv[2]),int(sys.argv[1])) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) count=septweet.reduceByKey(lambda",
"#outpu3: inputStream=ssc.socketTextStream(\"localhost\",9009) dataStream = inputStream.window(int(sys.argv[1]),int(sys.argv[2])) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) count=septweet.reduceByKey(lambda x,y:x+y) sortcount",
"import StreamingContext from pyspark.sql import Row,SQLContext import sys import requests",
"rdd :rdd.sortBy(lambda a:a[1],ascending=False)) tweet1=sortcount.filter(lambda w:w[0] is not '') tweet1.pprint() res",
"import SparkConf,SparkContext from pyspark.streaming import StreamingContext from pyspark.sql import Row,SQLContext",
"pyspark.streaming import StreamingContext from pyspark.sql import Row,SQLContext import sys import",
"count.transform(lambda rdd :rdd.sortBy(lambda a:a[1],ascending=False)) tweet1=sortcount.filter(lambda w:w[0] is not '') #tweet1.pprint()",
"sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[0],ascending=True)) sortcount = count.transform(lambda rdd",
"import requests def tmp(x): y = (x.split(';')[7]).split(',') return (y) def",
"conf=SparkConf() conf.setAppName(\"BigData\") sc=SparkContext(conf=conf) ssc=StreamingContext(sc,int(sys.argv[1])) ssc.checkpoint(\"/checkpoint_BIGDATA\") ''' #Selecting a window :",
"then reducing by window: #outpu2 dataStream=ssc.socketTextStream(\"localhost\",9009) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) #septweet.pprint() count=septweet.reduceByKeyAndWindow(lambda",
"return (y) def forf(x): for i in x: yield (i,1)",
"rdd :rdd.sortBy(lambda a:a[0],ascending=True)) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[1],ascending=False)) tweet1=sortcount.filter(lambda",
"count=septweet.reduceByKey(lambda x,y:x+y) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[0],ascending=True)) sortcount =",
"a:a[0],ascending=True)) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[1],ascending=False)) tweet1=sortcount.filter(lambda w:w[0] is",
"= count.transform(lambda rdd :rdd.sortBy(lambda a:a[0],ascending=True)) sortcount = sortcount.transform(lambda rdd :rdd.sortBy(lambda",
"#tweet1.pprint() res = tweet1.map(lambda a : a[0]) res.foreachRDD(topprint) ''' #Try",
"inputStream.window(int(sys.argv[1]),int(sys.argv[2])) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) count=septweet.reduceByKey(lambda x,y:x+y) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda",
": #outpu3: inputStream=ssc.socketTextStream(\"localhost\",9009) dataStream = inputStream.window(int(sys.argv[1]),int(sys.argv[2])) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) count=septweet.reduceByKey(lambda x,y:x+y)",
"window: #outpu2 dataStream=ssc.socketTextStream(\"localhost\",9009) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) #septweet.pprint() count=septweet.reduceByKeyAndWindow(lambda x,y:x+y,int(sys.argv[1]),int(sys.argv[2])) sortcount =",
"dataStream = inputStream.window(int(sys.argv[2]),int(sys.argv[1])) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) count=septweet.reduceByKey(lambda x,y:x+y) sortcount = count.transform(lambda",
"tweet1=sortcount.filter(lambda w:w[0] is not '') #tweet1.pprint() res = tweet1.map(lambda a"
] |
[
"# Generated by Django 4.0.1 on 2022-01-20 13:10 import courses.fields",
"class Migration(migrations.Migration): dependencies = [ ('courses', '0002_video_text_image_file_content'), ] operations =",
"name='content', options={'ordering': ['order']}, ), migrations.AlterModelOptions( name='module', options={'ordering': ['order']}, ), migrations.AddField(",
"migrations class Migration(migrations.Migration): dependencies = [ ('courses', '0002_video_text_image_file_content'), ] operations",
"= [ ('courses', '0002_video_text_image_file_content'), ] operations = [ migrations.AlterModelOptions( name='content',",
"[ migrations.AlterModelOptions( name='content', options={'ordering': ['order']}, ), migrations.AlterModelOptions( name='module', options={'ordering': ['order']},",
"on 2022-01-20 13:10 import courses.fields from django.db import migrations class",
"13:10 import courses.fields from django.db import migrations class Migration(migrations.Migration): dependencies",
"model_name='content', name='order', field=courses.fields.OrderField(blank=True, default=0), preserve_default=False, ), migrations.AddField( model_name='module', name='order', field=courses.fields.OrderField(blank=True,",
"preserve_default=False, ), migrations.AddField( model_name='module', name='order', field=courses.fields.OrderField(blank=True, default=0), preserve_default=False, ), ]",
"operations = [ migrations.AlterModelOptions( name='content', options={'ordering': ['order']}, ), migrations.AlterModelOptions( name='module',",
"dependencies = [ ('courses', '0002_video_text_image_file_content'), ] operations = [ migrations.AlterModelOptions(",
"] operations = [ migrations.AlterModelOptions( name='content', options={'ordering': ['order']}, ), migrations.AlterModelOptions(",
"2022-01-20 13:10 import courses.fields from django.db import migrations class Migration(migrations.Migration):",
"'0002_video_text_image_file_content'), ] operations = [ migrations.AlterModelOptions( name='content', options={'ordering': ['order']}, ),",
"options={'ordering': ['order']}, ), migrations.AddField( model_name='content', name='order', field=courses.fields.OrderField(blank=True, default=0), preserve_default=False, ),",
"Migration(migrations.Migration): dependencies = [ ('courses', '0002_video_text_image_file_content'), ] operations = [",
"migrations.AddField( model_name='content', name='order', field=courses.fields.OrderField(blank=True, default=0), preserve_default=False, ), migrations.AddField( model_name='module', name='order',",
"['order']}, ), migrations.AddField( model_name='content', name='order', field=courses.fields.OrderField(blank=True, default=0), preserve_default=False, ), migrations.AddField(",
"['order']}, ), migrations.AlterModelOptions( name='module', options={'ordering': ['order']}, ), migrations.AddField( model_name='content', name='order',",
"courses.fields from django.db import migrations class Migration(migrations.Migration): dependencies = [",
"import courses.fields from django.db import migrations class Migration(migrations.Migration): dependencies =",
"4.0.1 on 2022-01-20 13:10 import courses.fields from django.db import migrations",
"), migrations.AlterModelOptions( name='module', options={'ordering': ['order']}, ), migrations.AddField( model_name='content', name='order', field=courses.fields.OrderField(blank=True,",
"Django 4.0.1 on 2022-01-20 13:10 import courses.fields from django.db import",
"name='module', options={'ordering': ['order']}, ), migrations.AddField( model_name='content', name='order', field=courses.fields.OrderField(blank=True, default=0), preserve_default=False,",
"field=courses.fields.OrderField(blank=True, default=0), preserve_default=False, ), migrations.AddField( model_name='module', name='order', field=courses.fields.OrderField(blank=True, default=0), preserve_default=False,",
"default=0), preserve_default=False, ), migrations.AddField( model_name='module', name='order', field=courses.fields.OrderField(blank=True, default=0), preserve_default=False, ),",
"= [ migrations.AlterModelOptions( name='content', options={'ordering': ['order']}, ), migrations.AlterModelOptions( name='module', options={'ordering':",
"migrations.AlterModelOptions( name='content', options={'ordering': ['order']}, ), migrations.AlterModelOptions( name='module', options={'ordering': ['order']}, ),",
"Generated by Django 4.0.1 on 2022-01-20 13:10 import courses.fields from",
"name='order', field=courses.fields.OrderField(blank=True, default=0), preserve_default=False, ), migrations.AddField( model_name='module', name='order', field=courses.fields.OrderField(blank=True, default=0),",
"django.db import migrations class Migration(migrations.Migration): dependencies = [ ('courses', '0002_video_text_image_file_content'),",
"('courses', '0002_video_text_image_file_content'), ] operations = [ migrations.AlterModelOptions( name='content', options={'ordering': ['order']},",
"[ ('courses', '0002_video_text_image_file_content'), ] operations = [ migrations.AlterModelOptions( name='content', options={'ordering':",
"options={'ordering': ['order']}, ), migrations.AlterModelOptions( name='module', options={'ordering': ['order']}, ), migrations.AddField( model_name='content',",
"), migrations.AddField( model_name='content', name='order', field=courses.fields.OrderField(blank=True, default=0), preserve_default=False, ), migrations.AddField( model_name='module',",
"import migrations class Migration(migrations.Migration): dependencies = [ ('courses', '0002_video_text_image_file_content'), ]",
"by Django 4.0.1 on 2022-01-20 13:10 import courses.fields from django.db",
"migrations.AlterModelOptions( name='module', options={'ordering': ['order']}, ), migrations.AddField( model_name='content', name='order', field=courses.fields.OrderField(blank=True, default=0),",
"from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('courses',"
] |
[
"input and update result for i in range(len(string)): res =",
"of three for calculating an integer given another integer representing",
"# Iterate through all characters of # input and update",
"to Integer Conversion def atoi(string): res = 0 # Iterate",
"- ord('0')) return res #Adjustment contains rule of three for",
"percentage def Adjustment(a, b): return (a * b) / 100",
"10 + (ord(string[i]) - ord('0')) return res #Adjustment contains rule",
"through all characters of # input and update result for",
"# input and update result for i in range(len(string)): res",
"for i in range(len(string)): res = res * 10 +",
"+ (ord(string[i]) - ord('0')) return res #Adjustment contains rule of",
"all characters of # input and update result for i",
"calculating an integer given another integer representing a percentage def",
"of # input and update result for i in range(len(string)):",
"an integer given another integer representing a percentage def Adjustment(a,",
"res = 0 # Iterate through all characters of #",
"ASCII to Integer Conversion def atoi(string): res = 0 #",
"= res * 10 + (ord(string[i]) - ord('0')) return res",
"#Atoi stands for ASCII to Integer Conversion def atoi(string): res",
"ord('0')) return res #Adjustment contains rule of three for calculating",
"def atoi(string): res = 0 # Iterate through all characters",
"stands for ASCII to Integer Conversion def atoi(string): res =",
"(ord(string[i]) - ord('0')) return res #Adjustment contains rule of three",
"in range(len(string)): res = res * 10 + (ord(string[i]) -",
"* 10 + (ord(string[i]) - ord('0')) return res #Adjustment contains",
"range(len(string)): res = res * 10 + (ord(string[i]) - ord('0'))",
"integer given another integer representing a percentage def Adjustment(a, b):",
"res * 10 + (ord(string[i]) - ord('0')) return res #Adjustment",
"Conversion def atoi(string): res = 0 # Iterate through all",
"contains rule of three for calculating an integer given another",
"for ASCII to Integer Conversion def atoi(string): res = 0",
"three for calculating an integer given another integer representing a",
"a percentage def Adjustment(a, b): return (a * b) /",
"return res #Adjustment contains rule of three for calculating an",
"rule of three for calculating an integer given another integer",
"res = res * 10 + (ord(string[i]) - ord('0')) return",
"#Adjustment contains rule of three for calculating an integer given",
"update result for i in range(len(string)): res = res *",
"Integer Conversion def atoi(string): res = 0 # Iterate through",
"atoi(string): res = 0 # Iterate through all characters of",
"= 0 # Iterate through all characters of # input",
"0 # Iterate through all characters of # input and",
"res #Adjustment contains rule of three for calculating an integer",
"Iterate through all characters of # input and update result",
"another integer representing a percentage def Adjustment(a, b): return (a",
"integer representing a percentage def Adjustment(a, b): return (a *",
"representing a percentage def Adjustment(a, b): return (a * b)",
"result for i in range(len(string)): res = res * 10",
"given another integer representing a percentage def Adjustment(a, b): return",
"and update result for i in range(len(string)): res = res",
"for calculating an integer given another integer representing a percentage",
"i in range(len(string)): res = res * 10 + (ord(string[i])",
"characters of # input and update result for i in"
] |
[
"value of. value: string, the value to set the option.",
"the config values to a given file. Args: config_file: string,",
"2.0 (the \"License\"); # you may not use this file",
"option is enabled or not set. \"\"\" return (not self.config.has_option(section,",
"file. Args: section: string, the section of the config file",
"2016 Google Inc. All Rights Reserved. # # Licensed under",
"Returns: bool, True if the option is enabled or not",
"def GetOptionString(self, section, option): \"\"\"Get the value of an option",
"to check. option: string, the option to set the value",
"\"\"\" text = textwrap.wrap( textwrap.dedent(self.config_header), break_on_hyphens=False) fp.write('\\n'.join(['# ' + line",
"the message to write at the top of the config.",
"option or None if the option doesn't exist. \"\"\" if",
"option): \"\"\"Get the value of an option in the config",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"the file location of the config file to write. \"\"\"",
"option doesn't exist. \"\"\" if self.config.has_option(section, option): return self.config.get(section, option)",
"header. \"\"\" text = textwrap.wrap( textwrap.dedent(self.config_header), break_on_hyphens=False) fp.write('\\n'.join(['# ' +",
"option to set the value of. value: string, the value",
"option): return self.config.get(section, option) else: return None def GetOptionBool(self, section,",
"line in text])) fp.write('\\n\\n') def GetOptionString(self, section, option): \"\"\"Get the",
"section of the config file to check. option: string, the",
"string, the file location of the config file to write.",
"string, the section of the config file to check. option:",
"self.config.has_section(section): self.config.add_section(section) self.config.set(section, option, str(value)) def WriteConfig(self, config_file=None): \"\"\"Write the",
"use this file except in compliance with the License. #",
"language governing permissions and # limitations under the License. \"\"\"A",
"defaults.\"\"\" def __init__(self, config_file=None, config_header=None): \"\"\"Constructor. Args: config_file: string, the",
"option: string, the option to retrieve the value of. Returns:",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"def GetOptionBool(self, section, option): \"\"\"Get the value of an option",
"with file_utils.LockFile(config_lock): with open(config_file, 'w') as config_fp: if self.config_header: self._AddHeader(config_fp)",
"= '/var/lock/google_%s.lock' % config_name with file_utils.LockFile(config_lock): with open(config_file, 'w') as",
"License. # You may obtain a copy of the License",
"option): return if not self.config.has_section(section): self.config.add_section(section) self.config.set(section, option, str(value)) def",
"header in the config. Args: fp: int, a file pointer",
"the option to retrieve the value of. Returns: string, the",
"string, the option to set the value of. value: string,",
"textwrap from google_compute_engine import file_utils from google_compute_engine.compat import parser CONFIG",
"under the License is distributed on an \"AS IS\" BASIS,",
"'/var/lock/google_%s.lock' % config_name with file_utils.LockFile(config_lock): with open(config_file, 'w') as config_fp:",
"License for the specific language governing permissions and # limitations",
"value to set the option. overwrite: bool, True to overwrite",
"% config_name with file_utils.LockFile(config_lock): with open(config_file, 'w') as config_fp: if",
"Reserved. # # Licensed under the Apache License, Version 2.0",
"doesn't exist. \"\"\" if self.config.has_option(section, option): return self.config.get(section, option) else:",
"def WriteConfig(self, config_file=None): \"\"\"Write the config values to a given",
"textwrap.dedent(self.config_header), break_on_hyphens=False) fp.write('\\n'.join(['# ' + line for line in text]))",
"config. Args: fp: int, a file pointer for writing the",
"google_compute_engine.compat import parser CONFIG = '/etc/default/instance_configs.cfg' class ConfigManager(object): \"\"\"Process the",
"value of an option in the config file. Args: section:",
"option to retrieve the value of. Returns: bool, True if",
"textwrap.wrap( textwrap.dedent(self.config_header), break_on_hyphens=False) fp.write('\\n'.join(['# ' + line for line in",
"else: return None def GetOptionBool(self, section, option): \"\"\"Get the value",
"file_utils from google_compute_engine.compat import parser CONFIG = '/etc/default/instance_configs.cfg' class ConfigManager(object):",
"Copyright 2016 Google Inc. All Rights Reserved. # # Licensed",
"in compliance with the License. # You may obtain a",
"software # distributed under the License is distributed on an",
"= config_header self.config = parser.SafeConfigParser() self.config.read(self.config_file) def _AddHeader(self, fp): \"\"\"Create",
"config_name = os.path.splitext(os.path.basename(config_file))[0] config_lock = '/var/lock/google_%s.lock' % config_name with file_utils.LockFile(config_lock):",
"overwrite an existing value in the config file. \"\"\" if",
"config_lock = '/var/lock/google_%s.lock' % config_name with file_utils.LockFile(config_lock): with open(config_file, 'w')",
"section, option): \"\"\"Get the value of an option in the",
"section: string, the section of the config file to check.",
"GetOptionString(self, section, option): \"\"\"Get the value of an option in",
"if not self.config.has_section(section): self.config.add_section(section) self.config.set(section, option, str(value)) def WriteConfig(self, config_file=None):",
"Args: section: string, the section of the config file to",
"option) or self.config.getboolean(section, option)) def SetOption(self, section, option, value, overwrite=True):",
"check. option: string, the option to retrieve the value of.",
"None def GetOptionBool(self, section, option): \"\"\"Get the value of an",
"configuration settings.\"\"\" import os import textwrap from google_compute_engine import file_utils",
"file_utils.LockFile(config_lock): with open(config_file, 'w') as config_fp: if self.config_header: self._AddHeader(config_fp) self.config.write(config_fp)",
"bool, True if the option is enabled or not set.",
"the option to set the value of. value: string, the",
"config values to a given file. Args: config_file: string, the",
"to a given file. Args: config_file: string, the file location",
"OF ANY KIND, either express or implied. # See the",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"ANY KIND, either express or implied. # See the License",
"See the License for the specific language governing permissions and",
"config file. config_header: string, the message to write at the",
"the License. # You may obtain a copy of the",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"for the specific language governing permissions and # limitations under",
"of an option in the config file. Args: section: string,",
"of the option or None if the option doesn't exist.",
"GetOptionBool(self, section, option): \"\"\"Get the value of an option in",
"if the option doesn't exist. \"\"\" if self.config.has_option(section, option): return",
"to in writing, software # distributed under the License is",
"# See the License for the specific language governing permissions",
"value, overwrite=True): \"\"\"Set the value of an option in the",
"\"\"\" if self.config.has_option(section, option): return self.config.get(section, option) else: return None",
"the section of the config file to check. option: string,",
"value in the config file. \"\"\" if not overwrite and",
"or agreed to in writing, software # distributed under the",
"required by applicable law or agreed to in writing, software",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"config file to check. option: string, the option to set",
"the config file. Args: section: string, the section of the",
"with the License. # You may obtain a copy of",
"the option. overwrite: bool, True to overwrite an existing value",
"config_name with file_utils.LockFile(config_lock): with open(config_file, 'w') as config_fp: if self.config_header:",
"the value of. Returns: string, the value of the option",
"fp.write('\\n\\n') def GetOptionString(self, section, option): \"\"\"Get the value of an",
"compliance with the License. # You may obtain a copy",
"All Rights Reserved. # # Licensed under the Apache License,",
"agreed to in writing, software # distributed under the License",
"str(value)) def WriteConfig(self, config_file=None): \"\"\"Write the config values to a",
"self.config = parser.SafeConfigParser() self.config.read(self.config_file) def _AddHeader(self, fp): \"\"\"Create a file",
"is enabled or not set. \"\"\" return (not self.config.has_option(section, option)",
"distributed under the License is distributed on an \"AS IS\"",
"break_on_hyphens=False) fp.write('\\n'.join(['# ' + line for line in text])) fp.write('\\n\\n')",
"Inc. All Rights Reserved. # # Licensed under the Apache",
"parser.SafeConfigParser() self.config.read(self.config_file) def _AddHeader(self, fp): \"\"\"Create a file header in",
"class ConfigManager(object): \"\"\"Process the configuration defaults.\"\"\" def __init__(self, config_file=None, config_header=None):",
"or self.config.getboolean(section, option)) def SetOption(self, section, option, value, overwrite=True): \"\"\"Set",
"express or implied. # See the License for the specific",
"except in compliance with the License. # You may obtain",
"file. Args: config_file: string, the file location of the config",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"not use this file except in compliance with the License.",
"string, the value of the option or None if the",
"writing, software # distributed under the License is distributed on",
"file to write. \"\"\" config_file = config_file or self.config_file config_name",
"you may not use this file except in compliance with",
"given file. Args: config_file: string, the file location of the",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"the option doesn't exist. \"\"\" if self.config.has_option(section, option): return self.config.get(section,",
"the config. \"\"\" self.config_file = config_file or CONFIG self.config_header =",
"location of the config file to write. \"\"\" config_file =",
"configuration defaults.\"\"\" def __init__(self, config_file=None, config_header=None): \"\"\"Constructor. Args: config_file: string,",
"at the top of the config. \"\"\" self.config_file = config_file",
"value of. Returns: bool, True if the option is enabled",
"config_file: string, the file location of the config file to",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"the config file. \"\"\" if not overwrite and self.config.has_option(section, option):",
"the value of. value: string, the value to set the",
"config_file = config_file or self.config_file config_name = os.path.splitext(os.path.basename(config_file))[0] config_lock =",
"overwrite and self.config.has_option(section, option): return if not self.config.has_section(section): self.config.add_section(section) self.config.set(section,",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"retrieve the value of. Returns: string, the value of the",
"the config file to check. option: string, the option to",
"overwrite: bool, True to overwrite an existing value in the",
"file. \"\"\" if not overwrite and self.config.has_option(section, option): return if",
"option to retrieve the value of. Returns: string, the value",
"int, a file pointer for writing the header. \"\"\" text",
"config_file=None): \"\"\"Write the config values to a given file. Args:",
"text])) fp.write('\\n\\n') def GetOptionString(self, section, option): \"\"\"Get the value of",
"True to overwrite an existing value in the config file.",
"settings.\"\"\" import os import textwrap from google_compute_engine import file_utils from",
"of the config. \"\"\" self.config_file = config_file or CONFIG self.config_header",
"# Copyright 2016 Google Inc. All Rights Reserved. # #",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"modifying configuration settings.\"\"\" import os import textwrap from google_compute_engine import",
"and self.config.has_option(section, option): return if not self.config.has_section(section): self.config.add_section(section) self.config.set(section, option,",
"the License is distributed on an \"AS IS\" BASIS, #",
"\"\"\" self.config_file = config_file or CONFIG self.config_header = config_header self.config",
"return if not self.config.has_section(section): self.config.add_section(section) self.config.set(section, option, str(value)) def WriteConfig(self,",
"WriteConfig(self, config_file=None): \"\"\"Write the config values to a given file.",
"# limitations under the License. \"\"\"A library for retrieving and",
"Returns: string, the value of the option or None if",
"section, option, value, overwrite=True): \"\"\"Set the value of an option",
"set the value of. value: string, the value to set",
"config_file or self.config_file config_name = os.path.splitext(os.path.basename(config_file))[0] config_lock = '/var/lock/google_%s.lock' %",
"self.config.add_section(section) self.config.set(section, option, str(value)) def WriteConfig(self, config_file=None): \"\"\"Write the config",
"line for line in text])) fp.write('\\n\\n') def GetOptionString(self, section, option):",
"self.config.set(section, option, str(value)) def WriteConfig(self, config_file=None): \"\"\"Write the config values",
"law or agreed to in writing, software # distributed under",
"not set. \"\"\" return (not self.config.has_option(section, option) or self.config.getboolean(section, option))",
"or None if the option doesn't exist. \"\"\" if self.config.has_option(section,",
"message to write at the top of the config. \"\"\"",
"ConfigManager(object): \"\"\"Process the configuration defaults.\"\"\" def __init__(self, config_file=None, config_header=None): \"\"\"Constructor.",
"set. \"\"\" return (not self.config.has_option(section, option) or self.config.getboolean(section, option)) def",
"file location of the config file to write. \"\"\" config_file",
"to retrieve the value of. Returns: string, the value of",
"to check. option: string, the option to retrieve the value",
"may obtain a copy of the License at # #",
"of. Returns: string, the value of the option or None",
"import textwrap from google_compute_engine import file_utils from google_compute_engine.compat import parser",
"for writing the header. \"\"\" text = textwrap.wrap( textwrap.dedent(self.config_header), break_on_hyphens=False)",
"enabled or not set. \"\"\" return (not self.config.has_option(section, option) or",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"Args: fp: int, a file pointer for writing the header.",
"to set the value of. value: string, the value to",
"may not use this file except in compliance with the",
"\"\"\"Write the config values to a given file. Args: config_file:",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"Args: config_file: string, the file location of the config file",
"this file except in compliance with the License. # You",
"existing value in the config file. \"\"\" if not overwrite",
"os import textwrap from google_compute_engine import file_utils from google_compute_engine.compat import",
"self.config.has_option(section, option): return if not self.config.has_section(section): self.config.add_section(section) self.config.set(section, option, str(value))",
"_AddHeader(self, fp): \"\"\"Create a file header in the config. Args:",
"value: string, the value to set the option. overwrite: bool,",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"# # Licensed under the Apache License, Version 2.0 (the",
"file except in compliance with the License. # You may",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"' + line for line in text])) fp.write('\\n\\n') def GetOptionString(self,",
"a file pointer for writing the header. \"\"\" text =",
"the config. Args: fp: int, a file pointer for writing",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"string, the option to retrieve the value of. Returns: string,",
"governing permissions and # limitations under the License. \"\"\"A library",
"in the config. Args: fp: int, a file pointer for",
"from google_compute_engine import file_utils from google_compute_engine.compat import parser CONFIG =",
"in the config file. Args: section: string, the section of",
"= textwrap.wrap( textwrap.dedent(self.config_header), break_on_hyphens=False) fp.write('\\n'.join(['# ' + line for line",
"to set the option. overwrite: bool, True to overwrite an",
"a given file. Args: config_file: string, the file location of",
"Google Inc. All Rights Reserved. # # Licensed under the",
"write. \"\"\" config_file = config_file or self.config_file config_name = os.path.splitext(os.path.basename(config_file))[0]",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"License. \"\"\"A library for retrieving and modifying configuration settings.\"\"\" import",
"top of the config. \"\"\" self.config_file = config_file or CONFIG",
"\"\"\"Process the configuration defaults.\"\"\" def __init__(self, config_file=None, config_header=None): \"\"\"Constructor. Args:",
"or implied. # See the License for the specific language",
"Rights Reserved. # # Licensed under the Apache License, Version",
"the option to retrieve the value of. Returns: bool, True",
"the configuration defaults.\"\"\" def __init__(self, config_file=None, config_header=None): \"\"\"Constructor. Args: config_file:",
"KIND, either express or implied. # See the License for",
"specific language governing permissions and # limitations under the License.",
"config_file: string, the location of the config file. config_header: string,",
"self.config_header = config_header self.config = parser.SafeConfigParser() self.config.read(self.config_file) def _AddHeader(self, fp):",
"the header. \"\"\" text = textwrap.wrap( textwrap.dedent(self.config_header), break_on_hyphens=False) fp.write('\\n'.join(['# '",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"config_header: string, the message to write at the top of",
"of. value: string, the value to set the option. overwrite:",
"of. Returns: bool, True if the option is enabled or",
"from google_compute_engine.compat import parser CONFIG = '/etc/default/instance_configs.cfg' class ConfigManager(object): \"\"\"Process",
"option)) def SetOption(self, section, option, value, overwrite=True): \"\"\"Set the value",
"(the \"License\"); # you may not use this file except",
"# you may not use this file except in compliance",
"the config file. config_header: string, the message to write at",
"def _AddHeader(self, fp): \"\"\"Create a file header in the config.",
"\"\"\" return (not self.config.has_option(section, option) or self.config.getboolean(section, option)) def SetOption(self,",
"\"\"\" config_file = config_file or self.config_file config_name = os.path.splitext(os.path.basename(config_file))[0] config_lock",
"if not overwrite and self.config.has_option(section, option): return if not self.config.has_section(section):",
"return None def GetOptionBool(self, section, option): \"\"\"Get the value of",
"(not self.config.has_option(section, option) or self.config.getboolean(section, option)) def SetOption(self, section, option,",
"limitations under the License. \"\"\"A library for retrieving and modifying",
"import parser CONFIG = '/etc/default/instance_configs.cfg' class ConfigManager(object): \"\"\"Process the configuration",
"file to check. option: string, the option to retrieve the",
"self.config.has_option(section, option): return self.config.get(section, option) else: return None def GetOptionBool(self,",
"# # Unless required by applicable law or agreed to",
"the config file to write. \"\"\" config_file = config_file or",
"the option or None if the option doesn't exist. \"\"\"",
"self.config.has_option(section, option) or self.config.getboolean(section, option)) def SetOption(self, section, option, value,",
"string, the option to retrieve the value of. Returns: bool,",
"and # limitations under the License. \"\"\"A library for retrieving",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"self.config_file config_name = os.path.splitext(os.path.basename(config_file))[0] config_lock = '/var/lock/google_%s.lock' % config_name with",
"Args: config_file: string, the location of the config file. config_header:",
"Version 2.0 (the \"License\"); # you may not use this",
"and modifying configuration settings.\"\"\" import os import textwrap from google_compute_engine",
"location of the config file. config_header: string, the message to",
"SetOption(self, section, option, value, overwrite=True): \"\"\"Set the value of an",
"implied. # See the License for the specific language governing",
"writing the header. \"\"\" text = textwrap.wrap( textwrap.dedent(self.config_header), break_on_hyphens=False) fp.write('\\n'.join(['#",
"the option is enabled or not set. \"\"\" return (not",
"to overwrite an existing value in the config file. \"\"\"",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"exist. \"\"\" if self.config.has_option(section, option): return self.config.get(section, option) else: return",
"or self.config_file config_name = os.path.splitext(os.path.basename(config_file))[0] config_lock = '/var/lock/google_%s.lock' % config_name",
"config_header=None): \"\"\"Constructor. Args: config_file: string, the location of the config",
"library for retrieving and modifying configuration settings.\"\"\" import os import",
"retrieve the value of. Returns: bool, True if the option",
"\"\"\" if not overwrite and self.config.has_option(section, option): return if not",
"for retrieving and modifying configuration settings.\"\"\" import os import textwrap",
"config. \"\"\" self.config_file = config_file or CONFIG self.config_header = config_header",
"by applicable law or agreed to in writing, software #",
"fp): \"\"\"Create a file header in the config. Args: fp:",
"CONFIG self.config_header = config_header self.config = parser.SafeConfigParser() self.config.read(self.config_file) def _AddHeader(self,",
"#!/usr/bin/python # Copyright 2016 Google Inc. All Rights Reserved. #",
"the value to set the option. overwrite: bool, True to",
"parser CONFIG = '/etc/default/instance_configs.cfg' class ConfigManager(object): \"\"\"Process the configuration defaults.\"\"\"",
"'/etc/default/instance_configs.cfg' class ConfigManager(object): \"\"\"Process the configuration defaults.\"\"\" def __init__(self, config_file=None,",
"not self.config.has_section(section): self.config.add_section(section) self.config.set(section, option, str(value)) def WriteConfig(self, config_file=None): \"\"\"Write",
"not overwrite and self.config.has_option(section, option): return if not self.config.has_section(section): self.config.add_section(section)",
"the License. \"\"\"A library for retrieving and modifying configuration settings.\"\"\"",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"Unless required by applicable law or agreed to in writing,",
"= config_file or CONFIG self.config_header = config_header self.config = parser.SafeConfigParser()",
"\"\"\"Constructor. Args: config_file: string, the location of the config file.",
"the value of. Returns: bool, True if the option is",
"set the option. overwrite: bool, True to overwrite an existing",
"config file to check. option: string, the option to retrieve",
"of the config file to check. option: string, the option",
"the specific language governing permissions and # limitations under the",
"applicable law or agreed to in writing, software # distributed",
"option: string, the option to set the value of. value:",
"return self.config.get(section, option) else: return None def GetOptionBool(self, section, option):",
"retrieving and modifying configuration settings.\"\"\" import os import textwrap from",
"the value of an option in the config file. Args:",
"import file_utils from google_compute_engine.compat import parser CONFIG = '/etc/default/instance_configs.cfg' class",
"in writing, software # distributed under the License is distributed",
"string, the location of the config file. config_header: string, the",
"fp.write('\\n'.join(['# ' + line for line in text])) fp.write('\\n\\n') def",
"config_file=None, config_header=None): \"\"\"Constructor. Args: config_file: string, the location of the",
"option, str(value)) def WriteConfig(self, config_file=None): \"\"\"Write the config values to",
"an option in the config file. Args: section: string, the",
"to write. \"\"\" config_file = config_file or self.config_file config_name =",
"a file header in the config. Args: fp: int, a",
"text = textwrap.wrap( textwrap.dedent(self.config_header), break_on_hyphens=False) fp.write('\\n'.join(['# ' + line for",
"or not set. \"\"\" return (not self.config.has_option(section, option) or self.config.getboolean(section,",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"License, Version 2.0 (the \"License\"); # you may not use",
"value of. Returns: string, the value of the option or",
"config_file or CONFIG self.config_header = config_header self.config = parser.SafeConfigParser() self.config.read(self.config_file)",
"# You may obtain a copy of the License at",
"to retrieve the value of. Returns: bool, True if the",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"self.config.read(self.config_file) def _AddHeader(self, fp): \"\"\"Create a file header in the",
"an existing value in the config file. \"\"\" if not",
"\"\"\"Get the value of an option in the config file.",
"import os import textwrap from google_compute_engine import file_utils from google_compute_engine.compat",
"file pointer for writing the header. \"\"\" text = textwrap.wrap(",
"self.config.getboolean(section, option)) def SetOption(self, section, option, value, overwrite=True): \"\"\"Set the",
"None if the option doesn't exist. \"\"\" if self.config.has_option(section, option):",
"the License for the specific language governing permissions and #",
"under the License. \"\"\"A library for retrieving and modifying configuration",
"file. config_header: string, the message to write at the top",
"pointer for writing the header. \"\"\" text = textwrap.wrap( textwrap.dedent(self.config_header),",
"the location of the config file. config_header: string, the message",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"option) else: return None def GetOptionBool(self, section, option): \"\"\"Get the",
"the value of the option or None if the option",
"if the option is enabled or not set. \"\"\" return",
"either express or implied. # See the License for the",
"os.path.splitext(os.path.basename(config_file))[0] config_lock = '/var/lock/google_%s.lock' % config_name with file_utils.LockFile(config_lock): with open(config_file,",
"in text])) fp.write('\\n\\n') def GetOptionString(self, section, option): \"\"\"Get the value",
"return (not self.config.has_option(section, option) or self.config.getboolean(section, option)) def SetOption(self, section,",
"config file. \"\"\" if not overwrite and self.config.has_option(section, option): return",
"file to check. option: string, the option to set the",
"string, the message to write at the top of the",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"= '/etc/default/instance_configs.cfg' class ConfigManager(object): \"\"\"Process the configuration defaults.\"\"\" def __init__(self,",
"overwrite=True): \"\"\"Set the value of an option in the config",
"\"\"\"Set the value of an option in the config file.",
"bool, True to overwrite an existing value in the config",
"option. overwrite: bool, True to overwrite an existing value in",
"to write at the top of the config. \"\"\" self.config_file",
"in the config file. \"\"\" if not overwrite and self.config.has_option(section,",
"def SetOption(self, section, option, value, overwrite=True): \"\"\"Set the value of",
"value of the option or None if the option doesn't",
"of the config file to write. \"\"\" config_file = config_file",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"self.config.get(section, option) else: return None def GetOptionBool(self, section, option): \"\"\"Get",
"config file to write. \"\"\" config_file = config_file or self.config_file",
"True if the option is enabled or not set. \"\"\"",
"check. option: string, the option to set the value of.",
"of the config file. config_header: string, the message to write",
"file header in the config. Args: fp: int, a file",
"string, the value to set the option. overwrite: bool, True",
"def __init__(self, config_file=None, config_header=None): \"\"\"Constructor. Args: config_file: string, the location",
"\"License\"); # you may not use this file except in",
"write at the top of the config. \"\"\" self.config_file =",
"__init__(self, config_file=None, config_header=None): \"\"\"Constructor. Args: config_file: string, the location of",
"if self.config.has_option(section, option): return self.config.get(section, option) else: return None def",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"google_compute_engine import file_utils from google_compute_engine.compat import parser CONFIG = '/etc/default/instance_configs.cfg'",
"CONFIG = '/etc/default/instance_configs.cfg' class ConfigManager(object): \"\"\"Process the configuration defaults.\"\"\" def",
"option in the config file. Args: section: string, the section",
"config_header self.config = parser.SafeConfigParser() self.config.read(self.config_file) def _AddHeader(self, fp): \"\"\"Create a",
"option, value, overwrite=True): \"\"\"Set the value of an option in",
"# distributed under the License is distributed on an \"AS",
"+ line for line in text])) fp.write('\\n\\n') def GetOptionString(self, section,",
"self.config_file = config_file or CONFIG self.config_header = config_header self.config =",
"for line in text])) fp.write('\\n\\n') def GetOptionString(self, section, option): \"\"\"Get",
"# Unless required by applicable law or agreed to in",
"the top of the config. \"\"\" self.config_file = config_file or",
"\"\"\"Create a file header in the config. Args: fp: int,",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"permissions and # limitations under the License. \"\"\"A library for",
"\"\"\"A library for retrieving and modifying configuration settings.\"\"\" import os",
"You may obtain a copy of the License at #",
"= os.path.splitext(os.path.basename(config_file))[0] config_lock = '/var/lock/google_%s.lock' % config_name with file_utils.LockFile(config_lock): with",
"config file. Args: section: string, the section of the config",
"fp: int, a file pointer for writing the header. \"\"\"",
"or CONFIG self.config_header = config_header self.config = parser.SafeConfigParser() self.config.read(self.config_file) def",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"= parser.SafeConfigParser() self.config.read(self.config_file) def _AddHeader(self, fp): \"\"\"Create a file header",
"values to a given file. Args: config_file: string, the file",
"= config_file or self.config_file config_name = os.path.splitext(os.path.basename(config_file))[0] config_lock = '/var/lock/google_%s.lock'"
] |
[
"not isinstance(request, launchJobRequest) and\\ not issubclass(launchJobRequest, request.__class__): raise TypeError(\"%s incorrect",
"**kw ): launchJobRequest.__init__( self, name=None, ns=None ) class launchJobResponse(ns1.launchJobOutput_Dec): if",
"): typecode = ns1.launchJobOutput_Dec() def __init__(self, name=None, ns=None): ns1.launchJobOutput_Dec.__init__(self, name=None,",
"\"\"\" if not isinstance(request, getAppConfigRequest) and\\ not issubclass(getAppConfigRequest, request.__class__): raise",
"def __init__(self, name=None, ns=None): ns1.launchJobBlockingInput_Dec.__init__(self, name=None, ns=None) class launchJobBlockingRequestWrapper(launchJobBlockingRequest): \"\"\"wrapper",
"import ZSI class AppServiceInterface: def getAppServicePortType(self, portAddress=None, **kw): raise NonImplementationError(\"method",
"self.binding = client.Binding(**kw) def destroy(self, request): \"\"\" @param: request is",
"getAppConfigRequest.typecode = Struct(getAppConfigRequest,[], pname=name, aname=\"%s\" % name, oname=\"%s xmlns=\\\"\\\"\" %",
"self, name=None, ns=None, **kw ): getAppMetadataResponse.__init__( self, name=None, ns=None )",
"typecode = launchJobRequest( name=None, ns=None ).typecode def __init__( self, name=None,",
"ns1.getOutputsInput_Dec() def __init__(self, name=None, ns=None): ns1.getOutputsInput_Dec.__init__(self, name=None, ns=None) class getOutputsRequestWrapper(getOutputsRequest):",
").typecode def __init__( self, name=None, ns=None, **kw ): launchJobRequest.__init__( self,",
"self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getAppConfig\", **kw) response = self.binding.Receive(getAppConfigResponseWrapper()) if not",
"self, name=None, ns=None ) class getAppConfigRequest: def __init__(self, name=None, ns=None):",
"is str @return: response from destroyResponse:: _destroyOutput: ns1.StatusOutputType_Def _baseURL: str",
"int(netloc[1]) if \"url\" not in kw: kw[\"url\"] = urllib.parse.urlparse(addr)[2] self.binding",
"isinstance(request, getOutputAsBase64ByNameRequest) and\\ not issubclass(getOutputAsBase64ByNameRequest, request.__class__): raise TypeError(\"%s incorrect request",
"{} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getAppConfig\", **kw) response =",
"and\\ not issubclass(getAppMetadataResponse, response.__class__): raise TypeError(\"%s incorrect response type\" %(response.__class__))",
"__init__(self, name=None, ns=None): ns1.getOutputsOutput_Dec.__init__(self, name=None, ns=None) class getOutputsResponseWrapper(getOutputsResponse): \"\"\"wrapper for",
"type\" %(request.__class__)) kw = {'requestclass': queryStatusRequestWrapper} response = self.binding.Send(None, None,",
"__init__(self, name=None, ns=None): ns1.getOutputAsBase64ByNameInput_Dec.__init__(self, name=None, ns=None) class getOutputAsBase64ByNameRequestWrapper(getOutputAsBase64ByNameRequest): \"\"\"wrapper for",
"and\\ not issubclass(getAppConfigRequest, request.__class__): raise TypeError(\"%s incorrect request type\" %(request.__class__))",
"ns1.destroyInput_Dec() def __init__(self, name=None, ns=None): ns1.destroyInput_Dec.__init__(self, name=None, ns=None) class destroyRequestWrapper(destroyRequest):",
"getAppConfigResponseWrapper(getAppConfigResponse): \"\"\"wrapper for document:literal message\"\"\" typecode = getAppConfigResponse( name=None, ns=None",
"%(request.__class__)) kw = {'requestclass': queryStatusRequestWrapper} response = self.binding.Send(None, None, request,",
"@return: response from queryStatusResponse:: _queryStatusOutput: ns1.StatusOutputType_Def _baseURL: str _code: int",
"getAppConfig(self, request): \"\"\" @param: request to getAppConfigRequest @return: response from",
"and\\ not issubclass(getAppMetadataRequest, request.__class__): raise TypeError(\"%s incorrect request type\" %(request.__class__))",
"class AppServiceLocator(AppServiceInterface): AppServicePortType_address = \"https://rocks-106.sdsc.edu:8443/axis/services/AutogridServicePort\" def getAppServicePortTypeAddress(self): return AppServiceLocator.AppServicePortType_address def",
"destroyRequestWrapper} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/destroy\", **kw) response =",
") class destroyResponse(ns1.destroyOutput_Dec): if not hasattr( ns1.destroyOutput_Dec(), \"typecode\" ): typecode",
"for document:literal message\"\"\" typecode = launchJobRequest( name=None, ns=None ).typecode def",
"ns=None, **kw ): getAppConfigResponse.__init__( self, name=None, ns=None ) class getAppMetadataRequest:",
"_inputFile: ns1.InputFileType_Def, optional _contents: str _name: str _numProcs: int, optional",
"launchJobRequest:: _launchJobInput: ns1.JobInputType_Def _argList: str, optional _inputFile: ns1.InputFileType_Def, optional _contents:",
"response def launchJob(self, request): \"\"\" @param: request to launchJobRequest:: _launchJobInput:",
"str, optional _untaggedParams: ns1.ParamsArrayType_Def, optional _usage: str \"\"\" if not",
"_status: ns1.StatusOutputType_Def _baseURL: str _code: int _message: str \"\"\" if",
"################################################## # ./AppService_services.py # generated by ZSI.wsdl2python # # ##################################################",
"isinstance(response, getAppMetadataResponse) and\\ not issubclass(getAppMetadataResponse, response.__class__): raise TypeError(\"%s incorrect response",
"return response def getAppConfig(self, request): \"\"\" @param: request to getAppConfigRequest",
"name=None, ns=None) class getAppConfigResponseWrapper(getAppConfigResponse): \"\"\"wrapper for document:literal message\"\"\" typecode =",
"_value: str, optional _separator: str, optional _untaggedParams: ns1.ParamsArrayType_Def, optional _usage:",
"def __init__( self, name=None, ns=None, **kw ): getAppConfigResponse.__init__( self, name=None,",
"ns=None ) class getAppMetadataResponse(ns1.getAppMetadataOutput_Dec): if not hasattr( ns1.getAppMetadataOutput_Dec(), \"typecode\" ):",
"_launchJobBlockingOutput: ns1.BlockingOutputType_Def _jobOut: ns1.JobOutputType_Def _outputFile: ns1.OutputFileType_Def, optional _name: str _url:",
"if not isinstance(request, launchJobBlockingRequest) and\\ not issubclass(launchJobBlockingRequest, request.__class__): raise TypeError(\"%s",
"class getAppMetadataResponseWrapper(getAppMetadataResponse): \"\"\"wrapper for document:literal message\"\"\" typecode = getAppMetadataResponse( name=None,",
"ns=None, **kw ): getAppConfigRequest.__init__( self, name=None, ns=None ) class getAppConfigResponse(ns1.getAppConfigOutput_Dec):",
"launchJobResponse:: _launchJobOutput: ns1.JobSubOutputType_Def _jobID: str _status: ns1.StatusOutputType_Def _baseURL: str _code:",
"self, name=None, ns=None, **kw ): launchJobBlockingRequest.__init__( self, name=None, ns=None )",
"queryStatusRequestWrapper(queryStatusRequest): \"\"\"wrapper for document:literal message\"\"\" typecode = queryStatusRequest( name=None, ns=None",
"message\"\"\" typecode = queryStatusResponse( name=None, ns=None ).typecode def __init__( self,",
"ns=None) class getOutputsRequestWrapper(getOutputsRequest): \"\"\"wrapper for document:literal message\"\"\" typecode = getOutputsRequest(",
"@return: response from destroyResponse:: _destroyOutput: ns1.StatusOutputType_Def _baseURL: str _code: int",
"not issubclass(launchJobBlockingResponse, response.__class__): raise TypeError(\"%s incorrect response type\" %(response.__class__)) return",
"################################################## from .AppService_services_types import * from .AppService_services_types import \\ nbcr_sdsc_edu_opal_types",
"document:literal message\"\"\" typecode = getOutputAsBase64ByNameRequest( name=None, ns=None ).typecode def __init__(",
"name=None, ns=None ) class launchJobBlockingResponse(ns1.launchJobBlockingOutput_Dec): if not hasattr( ns1.launchJobBlockingOutput_Dec(), \"typecode\"",
"__init__(self, name=None, ns=None): ns1.queryStatusOutput_Dec.__init__(self, name=None, ns=None) class queryStatusResponseWrapper(queryStatusResponse): \"\"\"wrapper for",
"= (urllib.parse.urlparse(addr)[1]).split(\":\") + [80,] if \"host\" not in kw: kw[\"host\"]",
").typecode def __init__( self, name=None, ns=None, **kw ): getAppMetadataResponse.__init__( self,",
"def __init__( self, name=None, ns=None, **kw ): launchJobRequest.__init__( self, name=None,",
"response = self.binding.Receive(getOutputAsBase64ByNameResponseWrapper()) if not isinstance(response, getOutputAsBase64ByNameResponse) and\\ not issubclass(getOutputAsBase64ByNameResponse,",
"is str @return: response from getOutputsResponse:: _getOutputsOutput: ns1.JobOutputType_Def _outputFile: ns1.OutputFileType_Def,",
"if not isinstance(response, launchJobBlockingResponse) and\\ not issubclass(launchJobBlockingResponse, response.__class__): raise TypeError(\"%s",
"incorrect response type\" %(response.__class__)) return response def queryStatus(self, request): \"\"\"",
"def getOutputAsBase64ByName(self, request): \"\"\" @param: request to getOutputAsBase64ByNameRequest:: _getOutputAsBase64ByNameInput: ns1.OutputsByNameInputType_Def",
"name=None, ns=None ) class launchJobResponse(ns1.launchJobOutput_Dec): if not hasattr( ns1.launchJobOutput_Dec(), \"typecode\"",
"__init__(self, name=None, ns=None): ns1.destroyOutput_Dec.__init__(self, name=None, ns=None) class destroyResponseWrapper(destroyResponse): \"\"\"wrapper for",
") class getOutputsRequest(ns1.getOutputsInput_Dec): if not hasattr( ns1.getOutputsInput_Dec(), \"typecode\" ): typecode",
"_numProcs: int, optional @return: response from launchJobBlockingResponse:: _launchJobBlockingOutput: ns1.BlockingOutputType_Def _jobOut:",
"getAppServicePortType(self, portAddress=None, **kw): return AppServicePortSoapBindingSOAP(portAddress or AppServiceLocator.AppServicePortType_address, **kw) class AppServicePortSoapBindingSOAP:",
"document:literal message\"\"\" typecode = queryStatusResponse( name=None, ns=None ).typecode def __init__(",
"_parallel: boolean \"\"\" if not isinstance(request, getAppConfigRequest) and\\ not issubclass(getAppConfigRequest,",
"import * from .AppService_services_types import \\ nbcr_sdsc_edu_opal_types as ns1 import",
"./AppService_services.py # generated by ZSI.wsdl2python # # ################################################## from .AppService_services_types",
"isinstance(response, queryStatusResponse) and\\ not issubclass(queryStatusResponse, response.__class__): raise TypeError(\"%s incorrect response",
"to getAppMetadataRequest @return: response from getAppMetadataResponse:: _getAppMetadataOutput: ns1.AppMetadataType_Def _info: str,",
"type\" %(response.__class__)) return response def launchJob(self, request): \"\"\" @param: request",
"self, name=None, ns=None, **kw ): launchJobResponse.__init__( self, name=None, ns=None )",
"document:literal message\"\"\" typecode = getAppConfigResponse( name=None, ns=None ).typecode def __init__(",
"\"typecode\" ): typecode = ns1.destroyOutput_Dec() def __init__(self, name=None, ns=None): ns1.destroyOutput_Dec.__init__(self,",
"destroyRequest(ns1.destroyInput_Dec): if not hasattr( ns1.destroyInput_Dec(), \"typecode\" ): typecode = ns1.destroyInput_Dec()",
").typecode def __init__( self, name=None, ns=None, **kw ): getAppConfigResponse.__init__( self,",
"class getAppConfigResponse(ns1.getAppConfigOutput_Dec): if not hasattr( ns1.getAppConfigOutput_Dec(), \"typecode\" ): typecode =",
"): typecode = ns1.launchJobInput_Dec() def __init__(self, name=None, ns=None): ns1.launchJobInput_Dec.__init__(self, name=None,",
"request.__class__): raise TypeError(\"%s incorrect request type\" %(request.__class__)) kw = {}",
"ns=None, **kw ): launchJobBlockingRequest.__init__( self, name=None, ns=None ) class launchJobBlockingResponse(ns1.launchJobBlockingOutput_Dec):",
"= ns1.queryStatusOutput_Dec() def __init__(self, name=None, ns=None): ns1.queryStatusOutput_Dec.__init__(self, name=None, ns=None) class",
"\"typecode\" ): typecode = ns1.launchJobBlockingInput_Dec() def __init__(self, name=None, ns=None): ns1.launchJobBlockingInput_Dec.__init__(self,",
"destroyResponse) and\\ not issubclass(destroyResponse, response.__class__): raise TypeError(\"%s incorrect response type\"",
"in kw: kw[\"url\"] = urllib.parse.urlparse(addr)[2] self.binding = client.Binding(**kw) def destroy(self,",
"ns1.getOutputsOutput_Dec() def __init__(self, name=None, ns=None): ns1.getOutputsOutput_Dec.__init__(self, name=None, ns=None) class getOutputsResponseWrapper(getOutputsResponse):",
"AppServiceLocator(AppServiceInterface): AppServicePortType_address = \"https://rocks-106.sdsc.edu:8443/axis/services/AutogridServicePort\" def getAppServicePortTypeAddress(self): return AppServiceLocator.AppServicePortType_address def getAppServicePortType(self,",
"issubclass(getOutputAsBase64ByNameRequest, request.__class__): raise TypeError(\"%s incorrect request type\" %(request.__class__)) kw =",
"_semanticType: str, optional _textDesc: str, optional _taggedParams: ns1.ParamsArrayType_Def, optional _param:",
"not isinstance(request, launchJobBlockingRequest) and\\ not issubclass(launchJobBlockingRequest, request.__class__): raise TypeError(\"%s incorrect",
"str, optional _textDesc: str, optional _taggedParams: ns1.ParamsArrayType_Def, optional _param: ns1.ParamsType_Def,",
"not hasattr( ns1.queryStatusInput_Dec(), \"typecode\" ): typecode = ns1.queryStatusInput_Dec() def __init__(self,",
") class queryStatusResponse(ns1.queryStatusOutput_Dec): if not hasattr( ns1.queryStatusOutput_Dec(), \"typecode\" ): typecode",
"launchJobBlockingResponse) and\\ not issubclass(launchJobBlockingResponse, response.__class__): raise TypeError(\"%s incorrect response type\"",
"None, request, soapaction=\"http://nbcr.sdsc.edu/opal/launchJob\", **kw) response = self.binding.Receive(launchJobResponseWrapper()) if not isinstance(response,",
"class launchJobRequestWrapper(launchJobRequest): \"\"\"wrapper for document:literal message\"\"\" typecode = launchJobRequest( name=None,",
"_info: str, optional _types: ns1.ArgumentsType_Def, optional _flags: ns1.FlagsArrayType_Def, optional _flag:",
"hasattr( ns1.getOutputsOutput_Dec(), \"typecode\" ): typecode = ns1.getOutputsOutput_Dec() def __init__(self, name=None,",
"ns=None) class queryStatusResponseWrapper(queryStatusResponse): \"\"\"wrapper for document:literal message\"\"\" typecode = queryStatusResponse(",
"for document:literal message\"\"\" typecode = launchJobBlockingRequest( name=None, ns=None ).typecode def",
"\"typecode\" ): typecode = ns1.getAppMetadataOutput_Dec() def __init__(self, name=None, ns=None): ns1.getAppMetadataOutput_Dec.__init__(self,",
") class launchJobResponse(ns1.launchJobOutput_Dec): if not hasattr( ns1.launchJobOutput_Dec(), \"typecode\" ): typecode",
"class getOutputsRequest(ns1.getOutputsInput_Dec): if not hasattr( ns1.getOutputsInput_Dec(), \"typecode\" ): typecode =",
"ns=None, **kw ): launchJobBlockingResponse.__init__( self, name=None, ns=None ) class launchJobRequest(ns1.launchJobInput_Dec):",
"optional _id: str _tag: str _textDesc: str, optional _implicitParams: ns1.ImplicitParamsArrayType_Def,",
"def __init__(self, name=None, ns=None): ns1.queryStatusOutput_Dec.__init__(self, name=None, ns=None) class queryStatusResponseWrapper(queryStatusResponse): \"\"\"wrapper",
"getAppMetadataRequest.__init__( self, name=None, ns=None ) class getAppMetadataResponse(ns1.getAppMetadataOutput_Dec): if not hasattr(",
"self, name=None, ns=None, **kw ): getOutputsRequest.__init__( self, name=None, ns=None )",
"__init__( self, name=None, ns=None, **kw ): destroyResponse.__init__( self, name=None, ns=None",
"**kw) response = self.binding.Receive(launchJobBlockingResponseWrapper()) if not isinstance(response, launchJobBlockingResponse) and\\ not",
"getOutputsRequestWrapper} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getOutputs\", **kw) response =",
"): typecode = ns1.getOutputsInput_Dec() def __init__(self, name=None, ns=None): ns1.getOutputsInput_Dec.__init__(self, name=None,",
"\"typecode\" ): typecode = ns1.queryStatusInput_Dec() def __init__(self, name=None, ns=None): ns1.queryStatusInput_Dec.__init__(self,",
"_required: boolean, optional _semanticType: str, optional _tag: str, optional _textDesc:",
"implemented\") class AppServiceLocator(AppServiceInterface): AppServicePortType_address = \"https://rocks-106.sdsc.edu:8443/axis/services/AutogridServicePort\" def getAppServicePortTypeAddress(self): return AppServiceLocator.AppServicePortType_address",
"_taggedParams: ns1.ParamsArrayType_Def, optional _param: ns1.ParamsType_Def, optional _id: str _ioType: ns1.IOType_Def,",
"optional _min: int, optional _name: str, optional _required: boolean, optional",
"self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/destroy\", **kw) response = self.binding.Receive(destroyResponseWrapper()) if not",
"str _parallel: boolean \"\"\" if not isinstance(request, getAppConfigRequest) and\\ not",
"self.binding.Receive(getOutputAsBase64ByNameResponseWrapper()) if not isinstance(response, getOutputAsBase64ByNameResponse) and\\ not issubclass(getOutputAsBase64ByNameResponse, response.__class__): raise",
"name=None, ns=None) class getOutputAsBase64ByNameResponseWrapper(getOutputAsBase64ByNameResponse): \"\"\"wrapper for document:literal message\"\"\" typecode =",
"issubclass(queryStatusResponse, response.__class__): raise TypeError(\"%s incorrect response type\" %(response.__class__)) return response",
"destroyResponse.__init__( self, name=None, ns=None ) class getAppConfigRequest: def __init__(self, name=None,",
"= launchJobBlockingResponse( name=None, ns=None ).typecode def __init__( self, name=None, ns=None,",
"): getOutputAsBase64ByNameRequest.__init__( self, name=None, ns=None ) class getOutputAsBase64ByNameResponse(ns1.getOutputAsBase64ByNameOutput_Dec): if not",
"not hasattr( ns1.getOutputAsBase64ByNameOutput_Dec(), \"typecode\" ): typecode = ns1.getOutputAsBase64ByNameOutput_Dec() def __init__(self,",
"name=None, ns=None ) class getAppConfigResponse(ns1.getAppConfigOutput_Dec): if not hasattr( ns1.getAppConfigOutput_Dec(), \"typecode\"",
"name=None, ns=None, **kw ): getAppMetadataRequest.__init__( self, name=None, ns=None ) class",
"self, name=None, ns=None, **kw ): getAppConfigResponse.__init__( self, name=None, ns=None )",
"TypeError(\"%s incorrect response type\" %(response.__class__)) return response def getAppConfig(self, request):",
"document:literal message\"\"\" typecode = destroyResponse( name=None, ns=None ).typecode def __init__(",
"): queryStatusRequest.__init__( self, name=None, ns=None ) class queryStatusResponse(ns1.queryStatusOutput_Dec): if not",
"# generated by ZSI.wsdl2python # # ################################################## from .AppService_services_types import",
"getOutputAsBase64ByNameResponse:: _item: str, optional \"\"\" if not isinstance(request, getOutputAsBase64ByNameRequest) and\\",
"for document:literal message\"\"\" typecode = getAppConfigRequest( name=None, ns=None ).typecode def",
"name=None, ns=None) class launchJobBlockingRequestWrapper(launchJobBlockingRequest): \"\"\"wrapper for document:literal message\"\"\" typecode =",
"ns1.InputFileType_Def, optional _contents: str _name: str _numProcs: int, optional @return:",
"incorrect response type\" %(response.__class__)) return response def getAppMetadata(self, request): \"\"\"",
"\"\"\"wrapper for document:literal message\"\"\" typecode = launchJobRequest( name=None, ns=None ).typecode",
"hasattr( ns1.queryStatusOutput_Dec(), \"typecode\" ): typecode = ns1.queryStatusOutput_Dec() def __init__(self, name=None,",
"type\" %(response.__class__)) return response def getAppConfig(self, request): \"\"\" @param: request",
"_id: str _tag: str _textDesc: str, optional _implicitParams: ns1.ImplicitParamsArrayType_Def, optional",
"def __init__( self, name=None, ns=None, **kw ): destroyRequest.__init__( self, name=None,",
"ns1.launchJobInput_Dec() def __init__(self, name=None, ns=None): ns1.launchJobInput_Dec.__init__(self, name=None, ns=None) class launchJobRequestWrapper(launchJobRequest):",
"not isinstance(request, getOutputAsBase64ByNameRequest) and\\ not issubclass(getOutputAsBase64ByNameRequest, request.__class__): raise TypeError(\"%s incorrect",
"_code: int _message: str \"\"\" if not isinstance(request, str): raise",
"request, soapaction=\"http://nbcr.sdsc.edu/opal/launchJobBlocking\", **kw) response = self.binding.Receive(launchJobBlockingResponseWrapper()) if not isinstance(response, launchJobBlockingResponse)",
"str, optional _max: int, optional _min: int, optional _name: str,",
"getAppConfigResponse( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw",
") class launchJobRequest(ns1.launchJobInput_Dec): if not hasattr( ns1.launchJobInput_Dec(), \"typecode\" ): typecode",
"__init__(self, name=None, ns=None): ns1.launchJobBlockingInput_Dec.__init__(self, name=None, ns=None) class launchJobBlockingRequestWrapper(launchJobBlockingRequest): \"\"\"wrapper for",
"self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/launchJob\", **kw) response = self.binding.Receive(launchJobResponseWrapper()) if not",
"name=None, ns=None) class destroyResponseWrapper(destroyResponse): \"\"\"wrapper for document:literal message\"\"\" typecode =",
"boolean \"\"\" if not isinstance(request, getAppConfigRequest) and\\ not issubclass(getAppConfigRequest, request.__class__):",
"name=None, ns=None, **kw ): getAppConfigResponse.__init__( self, name=None, ns=None ) class",
"name ) class getAppMetadataRequestWrapper(getAppMetadataRequest): \"\"\"wrapper for document:literal message\"\"\" typecode =",
"incorrect response type\" %(response.__class__)) return response def getOutputs(self, request): \"\"\"",
"): getAppMetadataRequest.__init__( self, name=None, ns=None ) class getAppMetadataResponse(ns1.getAppMetadataOutput_Dec): if not",
"_getAppConfigOutput: ns1.AppConfigType_Def _binaryLocation: str _defaultArgs: str, optional _metadata: ns1.AppMetadataType_Def _info:",
"typecode = getAppMetadataResponse( name=None, ns=None ).typecode def __init__( self, name=None,",
"= self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/destroy\", **kw) response = self.binding.Receive(destroyResponseWrapper()) if",
"ns=None): ns1.getOutputsInput_Dec.__init__(self, name=None, ns=None) class getOutputsRequestWrapper(getOutputsRequest): \"\"\"wrapper for document:literal message\"\"\"",
"hasattr( ns1.launchJobBlockingInput_Dec(), \"typecode\" ): typecode = ns1.launchJobBlockingInput_Dec() def __init__(self, name=None,",
"__init__( self, name=None, ns=None, **kw ): launchJobBlockingRequest.__init__( self, name=None, ns=None",
"_contents: str _name: str _numProcs: int, optional @return: response from",
"not issubclass(getOutputsResponse, response.__class__): raise TypeError(\"%s incorrect response type\" %(response.__class__)) return",
"typecode = ns1.getAppMetadataOutput_Dec() def __init__(self, name=None, ns=None): ns1.getAppMetadataOutput_Dec.__init__(self, name=None, ns=None)",
"ns=None, **kw ): getAppMetadataResponse.__init__( self, name=None, ns=None ) class getOutputAsBase64ByNameRequest(ns1.getOutputAsBase64ByNameInput_Dec):",
"return response def getOutputs(self, request): \"\"\" @param: request is str",
"optional _param: ns1.ImplicitParamsType_Def, optional _extension: str, optional _id: str _ioType:",
"request): \"\"\" @param: request is str @return: response from getOutputsResponse::",
"_param: ns1.ImplicitParamsType_Def, optional _extension: str, optional _id: str _ioType: ns1.IOType_Def",
"= client.Binding(**kw) def destroy(self, request): \"\"\" @param: request is str",
"incorrect response type\" %(response.__class__)) return response def launchJobBlocking(self, request): \"\"\"",
"**kw ): launchJobBlockingRequest.__init__( self, name=None, ns=None ) class launchJobBlockingResponse(ns1.launchJobBlockingOutput_Dec): if",
"): getAppMetadataResponse.__init__( self, name=None, ns=None ) class getOutputAsBase64ByNameRequest(ns1.getOutputAsBase64ByNameInput_Dec): if not",
"TypeError(\"%s incorrect response type\" %(response.__class__)) return response def getAppMetadata(self, request):",
"__init__(self, name=None, ns=None): ns1.destroyInput_Dec.__init__(self, name=None, ns=None) class destroyRequestWrapper(destroyRequest): \"\"\"wrapper for",
"optional _untaggedParams: ns1.ParamsArrayType_Def, optional _usage: str \"\"\" if not isinstance(request,",
"kw[\"url\"] = urllib.parse.urlparse(addr)[2] self.binding = client.Binding(**kw) def destroy(self, request): \"\"\"",
"response type\" %(response.__class__)) return response def getAppConfig(self, request): \"\"\" @param:",
"class getOutputAsBase64ByNameResponse(ns1.getOutputAsBase64ByNameOutput_Dec): if not hasattr( ns1.getOutputAsBase64ByNameOutput_Dec(), \"typecode\" ): typecode =",
"getAppConfigResponse) and\\ not issubclass(getAppConfigResponse, response.__class__): raise TypeError(\"%s incorrect response type\"",
"ns1.launchJobInput_Dec.__init__(self, name=None, ns=None) class launchJobRequestWrapper(launchJobRequest): \"\"\"wrapper for document:literal message\"\"\" typecode",
"= {} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getOutputAsBase64ByName\", **kw) response",
"name=None, ns=None ) class destroyResponse(ns1.destroyOutput_Dec): if not hasattr( ns1.destroyOutput_Dec(), \"typecode\"",
"str _name: str _numProcs: int, optional @return: response from launchJobBlockingResponse::",
"import urllib.parse, types from ZSI.TCcompound import Struct from ZSI import",
"str \"\"\" if not isinstance(request, str): raise TypeError(\"%s incorrect request",
"launchJobBlockingRequestWrapper(launchJobBlockingRequest): \"\"\"wrapper for document:literal message\"\"\" typecode = launchJobBlockingRequest( name=None, ns=None",
"_metadata: ns1.AppMetadataType_Def _info: str, optional _types: ns1.ArgumentsType_Def, optional _flags: ns1.FlagsArrayType_Def,",
"queryStatusResponse(ns1.queryStatusOutput_Dec): if not hasattr( ns1.queryStatusOutput_Dec(), \"typecode\" ): typecode = ns1.queryStatusOutput_Dec()",
"optional _status: ns1.StatusOutputType_Def _baseURL: str _code: int _message: str \"\"\"",
"ns1.queryStatusInput_Dec.__init__(self, name=None, ns=None) class queryStatusRequestWrapper(queryStatusRequest): \"\"\"wrapper for document:literal message\"\"\" typecode",
"AppServiceLocator.AppServicePortType_address, **kw) class AppServicePortSoapBindingSOAP: def __init__(self, addr, **kw): netloc =",
"import \\ nbcr_sdsc_edu_opal_types as ns1 import urllib.parse, types from ZSI.TCcompound",
"getOutputs(self, request): \"\"\" @param: request is str @return: response from",
"for document:literal message\"\"\" typecode = getAppMetadataRequest( name=None, ns=None ).typecode def",
"_flag: ns1.FlagsType_Def, optional _id: str _tag: str _textDesc: str, optional",
"= ns1.getAppConfigOutput_Dec() def __init__(self, name=None, ns=None): ns1.getAppConfigOutput_Dec.__init__(self, name=None, ns=None) class",
"typecode = launchJobBlockingResponse( name=None, ns=None ).typecode def __init__( self, name=None,",
"_jobOut: ns1.JobOutputType_Def _outputFile: ns1.OutputFileType_Def, optional _name: str _url: str _stdErr:",
"**kw) response = self.binding.Receive(launchJobResponseWrapper()) if not isinstance(response, launchJobResponse) and\\ not",
"ns1.ImplicitParamsArrayType_Def, optional _param: ns1.ImplicitParamsType_Def, optional _extension: str, optional _id: str",
"name=None, ns=None, **kw ): destroyResponse.__init__( self, name=None, ns=None ) class",
"not isinstance(request, getAppConfigRequest) and\\ not issubclass(getAppConfigRequest, request.__class__): raise TypeError(\"%s incorrect",
"message\"\"\" typecode = getAppConfigResponse( name=None, ns=None ).typecode def __init__( self,",
"raise TypeError(\"%s incorrect response type\" %(response.__class__)) return response class destroyRequest(ns1.destroyInput_Dec):",
"class getAppConfigResponseWrapper(getAppConfigResponse): \"\"\"wrapper for document:literal message\"\"\" typecode = getAppConfigResponse( name=None,",
"message\"\"\" typecode = getAppConfigRequest( name=None, ns=None ).typecode def __init__( self,",
"kw: kw[\"host\"] = netloc[0] if \"port\" not in kw: kw[\"port\"]",
"\"port\" not in kw: kw[\"port\"] = int(netloc[1]) if \"url\" not",
"ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): getOutputAsBase64ByNameResponse.__init__(",
"__init__( self, name=None, ns=None, **kw ): launchJobBlockingResponse.__init__( self, name=None, ns=None",
"str, optional _required: boolean, optional _semanticType: str, optional _textDesc: str,",
"{'requestclass': destroyRequestWrapper} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/destroy\", **kw) response",
"_fileName: str _jobID: str @return: response from getOutputAsBase64ByNameResponse:: _item: str,",
"%(response.__class__)) return response def getAppMetadata(self, request): \"\"\" @param: request to",
"class launchJobResponseWrapper(launchJobResponse): \"\"\"wrapper for document:literal message\"\"\" typecode = launchJobResponse( name=None,",
"def __init__(self, name=None, ns=None): ns1.launchJobBlockingOutput_Dec.__init__(self, name=None, ns=None) class launchJobBlockingResponseWrapper(launchJobBlockingResponse): \"\"\"wrapper",
"{'requestclass': getOutputsRequestWrapper} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getOutputs\", **kw) response",
"name=None, ns=None): ns1.queryStatusOutput_Dec.__init__(self, name=None, ns=None) class queryStatusResponseWrapper(queryStatusResponse): \"\"\"wrapper for document:literal",
"= queryStatusResponse( name=None, ns=None ).typecode def __init__( self, name=None, ns=None,",
"class AppServiceInterface: def getAppServicePortType(self, portAddress=None, **kw): raise NonImplementationError(\"method not implemented\")",
"def __init__(self, name=None, ns=None): ns1.launchJobOutput_Dec.__init__(self, name=None, ns=None) class launchJobResponseWrapper(launchJobResponse): \"\"\"wrapper",
"not hasattr( ns1.getAppMetadataOutput_Dec(), \"typecode\" ): typecode = ns1.getAppMetadataOutput_Dec() def __init__(self,",
"@return: response from getOutputsResponse:: _getOutputsOutput: ns1.JobOutputType_Def _outputFile: ns1.OutputFileType_Def, optional _name:",
"launchJobResponse( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw",
"self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/queryStatus\", **kw) response = self.binding.Receive(queryStatusResponseWrapper()) if not",
") class getAppConfigRequest: def __init__(self, name=None, ns=None): getAppConfigRequest.typecode = Struct(getAppConfigRequest,[],",
"ns1.getAppMetadataOutput_Dec(), \"typecode\" ): typecode = ns1.getAppMetadataOutput_Dec() def __init__(self, name=None, ns=None):",
"raise TypeError(\"%s incorrect response type\" %(response.__class__)) return response def getAppMetadata(self,",
"document:literal message\"\"\" typecode = getOutputAsBase64ByNameResponse( name=None, ns=None ).typecode def __init__(",
"__init__(self, name=None, ns=None): getAppConfigRequest.typecode = Struct(getAppConfigRequest,[], pname=name, aname=\"%s\" % name,",
"= ns1.launchJobInput_Dec() def __init__(self, name=None, ns=None): ns1.launchJobInput_Dec.__init__(self, name=None, ns=None) class",
"getAppConfigRequest) and\\ not issubclass(getAppConfigRequest, request.__class__): raise TypeError(\"%s incorrect request type\"",
"optional _usage: str _parallel: boolean \"\"\" if not isinstance(request, getAppConfigRequest)",
"from queryStatusResponse:: _queryStatusOutput: ns1.StatusOutputType_Def _baseURL: str _code: int _message: str",
"name=None, ns=None) class launchJobRequestWrapper(launchJobRequest): \"\"\"wrapper for document:literal message\"\"\" typecode =",
"getAppServicePortTypeAddress(self): return AppServiceLocator.AppServicePortType_address def getAppServicePortType(self, portAddress=None, **kw): return AppServicePortSoapBindingSOAP(portAddress or",
"str \"\"\" if not isinstance(request, getAppMetadataRequest) and\\ not issubclass(getAppMetadataRequest, request.__class__):",
"\"\"\" @param: request to getOutputAsBase64ByNameRequest:: _getOutputAsBase64ByNameInput: ns1.OutputsByNameInputType_Def _fileName: str _jobID:",
"class AppServicePortSoapBindingSOAP: def __init__(self, addr, **kw): netloc = (urllib.parse.urlparse(addr)[1]).split(\":\") +",
"ns1.getOutputAsBase64ByNameOutput_Dec.__init__(self, name=None, ns=None) class getOutputAsBase64ByNameResponseWrapper(getOutputAsBase64ByNameResponse): \"\"\"wrapper for document:literal message\"\"\" typecode",
"optional _untaggedParams: ns1.ParamsArrayType_Def, optional _usage: str _parallel: boolean \"\"\" if",
"class launchJobRequest(ns1.launchJobInput_Dec): if not hasattr( ns1.launchJobInput_Dec(), \"typecode\" ): typecode =",
"None, request, soapaction=\"http://nbcr.sdsc.edu/opal/queryStatus\", **kw) response = self.binding.Receive(queryStatusResponseWrapper()) if not isinstance(response,",
"int, optional _min: int, optional _name: str, optional _required: boolean,",
"__init__(self, name=None, ns=None): ns1.launchJobInput_Dec.__init__(self, name=None, ns=None) class launchJobRequestWrapper(launchJobRequest): \"\"\"wrapper for",
"optional \"\"\" if not isinstance(request, getOutputAsBase64ByNameRequest) and\\ not issubclass(getOutputAsBase64ByNameRequest, request.__class__):",
"hasattr( ns1.getOutputsInput_Dec(), \"typecode\" ): typecode = ns1.getOutputsInput_Dec() def __init__(self, name=None,",
"ns=None): ns1.getOutputsOutput_Dec.__init__(self, name=None, ns=None) class getOutputsResponseWrapper(getOutputsResponse): \"\"\"wrapper for document:literal message\"\"\"",
"to launchJobRequest:: _launchJobInput: ns1.JobInputType_Def _argList: str, optional _inputFile: ns1.InputFileType_Def, optional",
"% name ) class getAppConfigRequestWrapper(getAppConfigRequest): \"\"\"wrapper for document:literal message\"\"\" typecode",
"response def getAppConfig(self, request): \"\"\" @param: request to getAppConfigRequest @return:",
"name=None, ns=None): ns1.getAppMetadataOutput_Dec.__init__(self, name=None, ns=None) class getAppMetadataResponseWrapper(getAppMetadataResponse): \"\"\"wrapper for document:literal",
"ns1.getOutputAsBase64ByNameInput_Dec() def __init__(self, name=None, ns=None): ns1.getOutputAsBase64ByNameInput_Dec.__init__(self, name=None, ns=None) class getOutputAsBase64ByNameRequestWrapper(getOutputAsBase64ByNameRequest):",
"optional _textDesc: str, optional _taggedParams: ns1.ParamsArrayType_Def, optional _param: ns1.ParamsType_Def, optional",
"): getOutputAsBase64ByNameResponse.__init__( self, name=None, ns=None ) class getOutputsRequest(ns1.getOutputsInput_Dec): if not",
"ns1.getOutputsInput_Dec(), \"typecode\" ): typecode = ns1.getOutputsInput_Dec() def __init__(self, name=None, ns=None):",
"getAppConfigRequest.__init__( self, name=None, ns=None ) class getAppConfigResponse(ns1.getAppConfigOutput_Dec): if not hasattr(",
"launchJobRequest( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw",
"def __init__(self, name=None, ns=None): ns1.destroyOutput_Dec.__init__(self, name=None, ns=None) class destroyResponseWrapper(destroyResponse): \"\"\"wrapper",
"__init__( self, name=None, ns=None, **kw ): getAppMetadataResponse.__init__( self, name=None, ns=None",
"= launchJobBlockingRequest( name=None, ns=None ).typecode def __init__( self, name=None, ns=None,",
"not hasattr( ns1.launchJobBlockingInput_Dec(), \"typecode\" ): typecode = ns1.launchJobBlockingInput_Dec() def __init__(self,",
"typecode = ns1.destroyOutput_Dec() def __init__(self, name=None, ns=None): ns1.destroyOutput_Dec.__init__(self, name=None, ns=None)",
"response = self.binding.Receive(queryStatusResponseWrapper()) if not isinstance(response, queryStatusResponse) and\\ not issubclass(queryStatusResponse,",
"typecode = ns1.queryStatusOutput_Dec() def __init__(self, name=None, ns=None): ns1.queryStatusOutput_Dec.__init__(self, name=None, ns=None)",
"hasattr( ns1.launchJobOutput_Dec(), \"typecode\" ): typecode = ns1.launchJobOutput_Dec() def __init__(self, name=None,",
"not hasattr( ns1.getOutputAsBase64ByNameInput_Dec(), \"typecode\" ): typecode = ns1.getOutputAsBase64ByNameInput_Dec() def __init__(self,",
") class getAppMetadataRequest: def __init__(self, name=None, ns=None): getAppMetadataRequest.typecode = Struct(getAppMetadataRequest,[],",
"= self.binding.Receive(destroyResponseWrapper()) if not isinstance(response, destroyResponse) and\\ not issubclass(destroyResponse, response.__class__):",
"request): \"\"\" @param: request is str @return: response from destroyResponse::",
"name=None, ns=None) class getOutputsRequestWrapper(getOutputsRequest): \"\"\"wrapper for document:literal message\"\"\" typecode =",
"typecode = queryStatusResponse( name=None, ns=None ).typecode def __init__( self, name=None,",
"_textDesc: str, optional _taggedParams: ns1.ParamsArrayType_Def, optional _param: ns1.ParamsType_Def, optional _id:",
"class getOutputAsBase64ByNameRequestWrapper(getOutputAsBase64ByNameRequest): \"\"\"wrapper for document:literal message\"\"\" typecode = getOutputAsBase64ByNameRequest( name=None,",
"optional _name: str _url: str _stdErr: str, optional _stdOut: str,",
"str _code: int _message: str \"\"\" if not isinstance(request, launchJobRequest)",
"request, soapaction=\"http://nbcr.sdsc.edu/opal/getOutputs\", **kw) response = self.binding.Receive(getOutputsResponseWrapper()) if not isinstance(response, getOutputsResponse)",
"ns=None) class launchJobRequestWrapper(launchJobRequest): \"\"\"wrapper for document:literal message\"\"\" typecode = launchJobRequest(",
"%(request.__class__)) kw = {'requestclass': getOutputsRequestWrapper} response = self.binding.Send(None, None, request,",
"not hasattr( ns1.launchJobBlockingOutput_Dec(), \"typecode\" ): typecode = ns1.launchJobBlockingOutput_Dec() def __init__(self,",
"None, request, soapaction=\"http://nbcr.sdsc.edu/opal/launchJobBlocking\", **kw) response = self.binding.Receive(launchJobBlockingResponseWrapper()) if not isinstance(response,",
"message\"\"\" typecode = launchJobRequest( name=None, ns=None ).typecode def __init__( self,",
"%(response.__class__)) return response def getAppConfig(self, request): \"\"\" @param: request to",
"%(response.__class__)) return response def launchJob(self, request): \"\"\" @param: request to",
"ns=None): getAppConfigRequest.typecode = Struct(getAppConfigRequest,[], pname=name, aname=\"%s\" % name, oname=\"%s xmlns=\\\"\\\"\"",
"= self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/launchJob\", **kw) response = self.binding.Receive(launchJobResponseWrapper()) if",
"return response def getAppMetadata(self, request): \"\"\" @param: request to getAppMetadataRequest",
"**kw ): launchJobResponse.__init__( self, name=None, ns=None ) class queryStatusRequest(ns1.queryStatusInput_Dec): if",
"# # ################################################## from .AppService_services_types import * from .AppService_services_types import",
"ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): queryStatusResponse.__init__(",
"typecode = destroyRequest( name=None, ns=None ).typecode def __init__( self, name=None,",
"ns1.queryStatusOutput_Dec() def __init__(self, name=None, ns=None): ns1.queryStatusOutput_Dec.__init__(self, name=None, ns=None) class queryStatusResponseWrapper(queryStatusResponse):",
"destroyResponseWrapper(destroyResponse): \"\"\"wrapper for document:literal message\"\"\" typecode = destroyResponse( name=None, ns=None",
"name=None, ns=None): ns1.launchJobInput_Dec.__init__(self, name=None, ns=None) class launchJobRequestWrapper(launchJobRequest): \"\"\"wrapper for document:literal",
"\"\"\"wrapper for document:literal message\"\"\" typecode = getAppMetadataResponse( name=None, ns=None ).typecode",
"**kw ): getOutputsRequest.__init__( self, name=None, ns=None ) class getOutputsResponse(ns1.getOutputsOutput_Dec): if",
"name=None, ns=None, **kw ): getOutputsRequest.__init__( self, name=None, ns=None ) class",
"self, name=None, ns=None, **kw ): launchJobRequest.__init__( self, name=None, ns=None )",
"str _code: int _message: str \"\"\" if not isinstance(request, launchJobBlockingRequest)",
"type\" %(request.__class__)) kw = {'requestclass': destroyRequestWrapper} response = self.binding.Send(None, None,",
"return AppServicePortSoapBindingSOAP(portAddress or AppServiceLocator.AppServicePortType_address, **kw) class AppServicePortSoapBindingSOAP: def __init__(self, addr,",
").typecode def __init__( self, name=None, ns=None, **kw ): getOutputAsBase64ByNameRequest.__init__( self,",
"\"\"\"wrapper for document:literal message\"\"\" typecode = getOutputAsBase64ByNameRequest( name=None, ns=None ).typecode",
"AppServiceLocator.AppServicePortType_address def getAppServicePortType(self, portAddress=None, **kw): return AppServicePortSoapBindingSOAP(portAddress or AppServiceLocator.AppServicePortType_address, **kw)",
"request): \"\"\" @param: request to launchJobRequest:: _launchJobInput: ns1.JobInputType_Def _argList: str,",
"kw = {} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getAppConfig\", **kw)",
"_semanticType: str, optional _tag: str, optional _textDesc: str, optional _value:",
"request, soapaction=\"http://nbcr.sdsc.edu/opal/launchJob\", **kw) response = self.binding.Receive(launchJobResponseWrapper()) if not isinstance(response, launchJobResponse)",
"def __init__( self, name=None, ns=None, **kw ): getOutputAsBase64ByNameRequest.__init__( self, name=None,",
"): getOutputsRequest.__init__( self, name=None, ns=None ) class getOutputsResponse(ns1.getOutputsOutput_Dec): if not",
").typecode def __init__( self, name=None, ns=None, **kw ): getOutputAsBase64ByNameResponse.__init__( self,",
"__init__(self, name=None, ns=None): ns1.getAppMetadataOutput_Dec.__init__(self, name=None, ns=None) class getAppMetadataResponseWrapper(getAppMetadataResponse): \"\"\"wrapper for",
"optional _flag: ns1.FlagsType_Def, optional _id: str _tag: str _textDesc: str,",
"if not isinstance(response, getAppConfigResponse) and\\ not issubclass(getAppConfigResponse, response.__class__): raise TypeError(\"%s",
"type\" %(response.__class__)) return response def launchJobBlocking(self, request): \"\"\" @param: request",
"\"\"\" @param: request to getAppMetadataRequest @return: response from getAppMetadataResponse:: _getAppMetadataOutput:",
"for document:literal message\"\"\" typecode = getOutputsResponse( name=None, ns=None ).typecode def",
"TypeError(\"%s incorrect request type\" %(request.__class__)) kw = {} response =",
"issubclass(getAppMetadataRequest, request.__class__): raise TypeError(\"%s incorrect request type\" %(request.__class__)) kw =",
"str, optional \"\"\" if not isinstance(request, str): raise TypeError(\"%s incorrect",
"%(request.__class__)) kw = {} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getOutputAsBase64ByName\",",
"self, name=None, ns=None ) class getOutputsRequest(ns1.getOutputsInput_Dec): if not hasattr( ns1.getOutputsInput_Dec(),",
"= getAppMetadataRequest( name=None, ns=None ).typecode def __init__( self, name=None, ns=None,",
"_id: str _ioType: ns1.IOType_Def, optional _paramType: ns1.ParamType_Def _ParamType: str, optional",
"and\\ not issubclass(getOutputAsBase64ByNameResponse, response.__class__): raise TypeError(\"%s incorrect response type\" %(response.__class__))",
"__init__( self, name=None, ns=None, **kw ): getOutputsResponse.__init__( self, name=None, ns=None",
") class getAppConfigRequestWrapper(getAppConfigRequest): \"\"\"wrapper for document:literal message\"\"\" typecode = getAppConfigRequest(",
"def getAppServicePortTypeAddress(self): return AppServiceLocator.AppServicePortType_address def getAppServicePortType(self, portAddress=None, **kw): return AppServicePortSoapBindingSOAP(portAddress",
"optional @return: response from launchJobResponse:: _launchJobOutput: ns1.JobSubOutputType_Def _jobID: str _status:",
"destroyResponse(ns1.destroyOutput_Dec): if not hasattr( ns1.destroyOutput_Dec(), \"typecode\" ): typecode = ns1.destroyOutput_Dec()",
"hasattr( ns1.getAppMetadataOutput_Dec(), \"typecode\" ): typecode = ns1.getAppMetadataOutput_Dec() def __init__(self, name=None,",
"\"\"\"wrapper for document:literal message\"\"\" typecode = queryStatusRequest( name=None, ns=None ).typecode",
"def __init__( self, name=None, ns=None, **kw ): getAppMetadataResponse.__init__( self, name=None,",
"\"\"\"wrapper for document:literal message\"\"\" typecode = launchJobResponse( name=None, ns=None ).typecode",
"_stdOut: str, optional \"\"\" if not isinstance(request, str): raise TypeError(\"%s",
"ns=None ) class launchJobResponse(ns1.launchJobOutput_Dec): if not hasattr( ns1.launchJobOutput_Dec(), \"typecode\" ):",
"if not isinstance(response, launchJobResponse) and\\ not issubclass(launchJobResponse, response.__class__): raise TypeError(\"%s",
"and\\ not issubclass(getOutputsResponse, response.__class__): raise TypeError(\"%s incorrect response type\" %(response.__class__))",
"**kw ): destroyRequest.__init__( self, name=None, ns=None ) class destroyResponse(ns1.destroyOutput_Dec): if",
"response type\" %(response.__class__)) return response def queryStatus(self, request): \"\"\" @param:",
"ns=None) class getAppMetadataResponseWrapper(getAppMetadataResponse): \"\"\"wrapper for document:literal message\"\"\" typecode = getAppMetadataResponse(",
"str @return: response from getOutputAsBase64ByNameResponse:: _item: str, optional \"\"\" if",
"ns1.FlagsArrayType_Def, optional _flag: ns1.FlagsType_Def, optional _id: str _tag: str _textDesc:",
"self, name=None, ns=None, **kw ): launchJobBlockingResponse.__init__( self, name=None, ns=None )",
"ns1.ParamsArrayType_Def, optional _usage: str \"\"\" if not isinstance(request, getAppMetadataRequest) and\\",
"if not isinstance(request, getAppMetadataRequest) and\\ not issubclass(getAppMetadataRequest, request.__class__): raise TypeError(\"%s",
"not isinstance(response, getOutputAsBase64ByNameResponse) and\\ not issubclass(getOutputAsBase64ByNameResponse, response.__class__): raise TypeError(\"%s incorrect",
"isinstance(response, launchJobResponse) and\\ not issubclass(launchJobResponse, response.__class__): raise TypeError(\"%s incorrect response",
"= {'requestclass': destroyRequestWrapper} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/destroy\", **kw)",
"def __init__( self, name=None, ns=None, **kw ): launchJobBlockingRequest.__init__( self, name=None,",
"from .AppService_services_types import * from .AppService_services_types import \\ nbcr_sdsc_edu_opal_types as",
"TypeError(\"%s incorrect response type\" %(response.__class__)) return response def getOutputs(self, request):",
"ns=None ) class getAppConfigResponse(ns1.getAppConfigOutput_Dec): if not hasattr( ns1.getAppConfigOutput_Dec(), \"typecode\" ):",
"_name: str _url: str _stdErr: str, optional _stdOut: str, optional",
"def __init__( self, name=None, ns=None, **kw ): launchJobResponse.__init__( self, name=None,",
"typecode = ns1.launchJobBlockingOutput_Dec() def __init__(self, name=None, ns=None): ns1.launchJobBlockingOutput_Dec.__init__(self, name=None, ns=None)",
"optional _required: boolean, optional _semanticType: str, optional _textDesc: str, optional",
"response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getAppConfig\", **kw) response = self.binding.Receive(getAppConfigResponseWrapper())",
"_launchJobOutput: ns1.JobSubOutputType_Def _jobID: str _status: ns1.StatusOutputType_Def _baseURL: str _code: int",
"ns=None): ns1.launchJobBlockingOutput_Dec.__init__(self, name=None, ns=None) class launchJobBlockingResponseWrapper(launchJobBlockingResponse): \"\"\"wrapper for document:literal message\"\"\"",
"_IOType: str, optional _max: int, optional _min: int, optional _name:",
"def __init__(self, name=None, ns=None): getAppMetadataRequest.typecode = Struct(getAppMetadataRequest,[], pname=name, aname=\"%s\" %",
"def __init__(self, name=None, ns=None): getAppConfigRequest.typecode = Struct(getAppConfigRequest,[], pname=name, aname=\"%s\" %",
"pname=name, aname=\"%s\" % name, oname=\"%s xmlns=\\\"\\\"\" % name ) class",
"ns1.getOutputAsBase64ByNameInput_Dec.__init__(self, name=None, ns=None) class getOutputAsBase64ByNameRequestWrapper(getOutputAsBase64ByNameRequest): \"\"\"wrapper for document:literal message\"\"\" typecode",
"ns=None): ns1.getAppConfigOutput_Dec.__init__(self, name=None, ns=None) class getAppConfigResponseWrapper(getAppConfigResponse): \"\"\"wrapper for document:literal message\"\"\"",
"as ns1 import urllib.parse, types from ZSI.TCcompound import Struct from",
"for document:literal message\"\"\" typecode = destroyResponse( name=None, ns=None ).typecode def",
"launchJobResponseWrapper(launchJobResponse): \"\"\"wrapper for document:literal message\"\"\" typecode = launchJobResponse( name=None, ns=None",
"boolean, optional _semanticType: str, optional _textDesc: str, optional _taggedParams: ns1.ParamsArrayType_Def,",
"_max: int, optional _min: int, optional _name: str, optional _required:",
"issubclass(launchJobRequest, request.__class__): raise TypeError(\"%s incorrect request type\" %(request.__class__)) kw =",
"incorrect response type\" %(response.__class__)) return response def getOutputAsBase64ByName(self, request): \"\"\"",
"ns=None) class getOutputAsBase64ByNameResponseWrapper(getOutputAsBase64ByNameResponse): \"\"\"wrapper for document:literal message\"\"\" typecode = getOutputAsBase64ByNameResponse(",
"TypeError(\"%s incorrect request type\" %(request.__class__)) kw = {'requestclass': getOutputsRequestWrapper} response",
"str _url: str _stdErr: str, optional _stdOut: str, optional \"\"\"",
"ns1.ImplicitParamsType_Def, optional _extension: str, optional _id: str _ioType: ns1.IOType_Def _IOType:",
"netloc[0] if \"port\" not in kw: kw[\"port\"] = int(netloc[1]) if",
"self.binding.Receive(destroyResponseWrapper()) if not isinstance(response, destroyResponse) and\\ not issubclass(destroyResponse, response.__class__): raise",
"name=None, ns=None) class getAppMetadataResponseWrapper(getAppMetadataResponse): \"\"\"wrapper for document:literal message\"\"\" typecode =",
"ns=None ) class getOutputsRequest(ns1.getOutputsInput_Dec): if not hasattr( ns1.getOutputsInput_Dec(), \"typecode\" ):",
"ns=None) class destroyRequestWrapper(destroyRequest): \"\"\"wrapper for document:literal message\"\"\" typecode = destroyRequest(",
"urllib.parse.urlparse(addr)[2] self.binding = client.Binding(**kw) def destroy(self, request): \"\"\" @param: request",
"netloc = (urllib.parse.urlparse(addr)[1]).split(\":\") + [80,] if \"host\" not in kw:",
"\"\"\"wrapper for document:literal message\"\"\" typecode = getOutputAsBase64ByNameResponse( name=None, ns=None ).typecode",
"ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): getAppMetadataRequest.__init__(",
"self, name=None, ns=None ) class launchJobBlockingResponse(ns1.launchJobBlockingOutput_Dec): if not hasattr( ns1.launchJobBlockingOutput_Dec(),",
"not isinstance(request, str): raise TypeError(\"%s incorrect request type\" %(request.__class__)) kw",
"ns=None, **kw ): launchJobRequest.__init__( self, name=None, ns=None ) class launchJobResponse(ns1.launchJobOutput_Dec):",
"name=None, ns=None): ns1.getOutputAsBase64ByNameOutput_Dec.__init__(self, name=None, ns=None) class getOutputAsBase64ByNameResponseWrapper(getOutputAsBase64ByNameResponse): \"\"\"wrapper for document:literal",
"if not hasattr( ns1.launchJobOutput_Dec(), \"typecode\" ): typecode = ns1.launchJobOutput_Dec() def",
"@return: response from launchJobResponse:: _launchJobOutput: ns1.JobSubOutputType_Def _jobID: str _status: ns1.StatusOutputType_Def",
"message\"\"\" typecode = getOutputAsBase64ByNameRequest( name=None, ns=None ).typecode def __init__( self,",
"\"\"\" if not isinstance(request, launchJobRequest) and\\ not issubclass(launchJobRequest, request.__class__): raise",
"+ [80,] if \"host\" not in kw: kw[\"host\"] = netloc[0]",
"typecode = ns1.getAppConfigOutput_Dec() def __init__(self, name=None, ns=None): ns1.getAppConfigOutput_Dec.__init__(self, name=None, ns=None)",
"optional _value: str, optional _separator: str, optional _untaggedParams: ns1.ParamsArrayType_Def, optional",
"not isinstance(response, getAppMetadataResponse) and\\ not issubclass(getAppMetadataResponse, response.__class__): raise TypeError(\"%s incorrect",
"str _numProcs: int, optional @return: response from launchJobBlockingResponse:: _launchJobBlockingOutput: ns1.BlockingOutputType_Def",
"request): \"\"\" @param: request to launchJobBlockingRequest:: _launchJobBlockingInput: ns1.JobInputType_Def _argList: str,",
"not isinstance(response, queryStatusResponse) and\\ not issubclass(queryStatusResponse, response.__class__): raise TypeError(\"%s incorrect",
"def __init__( self, name=None, ns=None, **kw ): getAppMetadataRequest.__init__( self, name=None,",
"document:literal message\"\"\" typecode = launchJobBlockingResponse( name=None, ns=None ).typecode def __init__(",
"= netloc[0] if \"port\" not in kw: kw[\"port\"] = int(netloc[1])",
"str @return: response from getOutputsResponse:: _getOutputsOutput: ns1.JobOutputType_Def _outputFile: ns1.OutputFileType_Def, optional",
"__init__( self, name=None, ns=None, **kw ): destroyRequest.__init__( self, name=None, ns=None",
"def queryStatus(self, request): \"\"\" @param: request is str @return: response",
"for document:literal message\"\"\" typecode = queryStatusRequest( name=None, ns=None ).typecode def",
"request, soapaction=\"http://nbcr.sdsc.edu/opal/getOutputAsBase64ByName\", **kw) response = self.binding.Receive(getOutputAsBase64ByNameResponseWrapper()) if not isinstance(response, getOutputAsBase64ByNameResponse)",
"= destroyResponse( name=None, ns=None ).typecode def __init__( self, name=None, ns=None,",
"__init__(self, name=None, ns=None): ns1.getOutputAsBase64ByNameOutput_Dec.__init__(self, name=None, ns=None) class getOutputAsBase64ByNameResponseWrapper(getOutputAsBase64ByNameResponse): \"\"\"wrapper for",
").typecode def __init__( self, name=None, ns=None, **kw ): destroyResponse.__init__( self,",
"isinstance(request, str): raise TypeError(\"%s incorrect request type\" %(request.__class__)) kw =",
"ZSI.wsdl2python # # ################################################## from .AppService_services_types import * from .AppService_services_types",
"ns=None ) class getOutputAsBase64ByNameResponse(ns1.getOutputAsBase64ByNameOutput_Dec): if not hasattr( ns1.getOutputAsBase64ByNameOutput_Dec(), \"typecode\" ):",
"= self.binding.Receive(queryStatusResponseWrapper()) if not isinstance(response, queryStatusResponse) and\\ not issubclass(queryStatusResponse, response.__class__):",
"hasattr( ns1.getAppConfigOutput_Dec(), \"typecode\" ): typecode = ns1.getAppConfigOutput_Dec() def __init__(self, name=None,",
"if not hasattr( ns1.launchJobBlockingOutput_Dec(), \"typecode\" ): typecode = ns1.launchJobBlockingOutput_Dec() def",
"getAppConfigResponse(ns1.getAppConfigOutput_Dec): if not hasattr( ns1.getAppConfigOutput_Dec(), \"typecode\" ): typecode = ns1.getAppConfigOutput_Dec()",
"= ns1.getOutputAsBase64ByNameInput_Dec() def __init__(self, name=None, ns=None): ns1.getOutputAsBase64ByNameInput_Dec.__init__(self, name=None, ns=None) class",
"response from getOutputsResponse:: _getOutputsOutput: ns1.JobOutputType_Def _outputFile: ns1.OutputFileType_Def, optional _name: str",
"typecode = ns1.getOutputsOutput_Dec() def __init__(self, name=None, ns=None): ns1.getOutputsOutput_Dec.__init__(self, name=None, ns=None)",
"= ns1.destroyOutput_Dec() def __init__(self, name=None, ns=None): ns1.destroyOutput_Dec.__init__(self, name=None, ns=None) class",
"_ParamType: str, optional _required: boolean, optional _semanticType: str, optional _tag:",
"response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/launchJob\", **kw) response = self.binding.Receive(launchJobResponseWrapper())",
"getOutputsResponse( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw",
"__init__( self, name=None, ns=None, **kw ): launchJobResponse.__init__( self, name=None, ns=None",
"def __init__( self, name=None, ns=None, **kw ): getAppConfigRequest.__init__( self, name=None,",
"ns=None) class getAppConfigResponseWrapper(getAppConfigResponse): \"\"\"wrapper for document:literal message\"\"\" typecode = getAppConfigResponse(",
"def __init__( self, name=None, ns=None, **kw ): getOutputsResponse.__init__( self, name=None,",
"ns1.ParamsType_Def, optional _id: str _ioType: ns1.IOType_Def, optional _paramType: ns1.ParamType_Def _ParamType:",
"is str @return: response from queryStatusResponse:: _queryStatusOutput: ns1.StatusOutputType_Def _baseURL: str",
"[80,] if \"host\" not in kw: kw[\"host\"] = netloc[0] if",
"name=None, ns=None ) class launchJobRequest(ns1.launchJobInput_Dec): if not hasattr( ns1.launchJobInput_Dec(), \"typecode\"",
"getOutputAsBase64ByNameRequest.__init__( self, name=None, ns=None ) class getOutputAsBase64ByNameResponse(ns1.getOutputAsBase64ByNameOutput_Dec): if not hasattr(",
"ns1.FlagsType_Def, optional _id: str _tag: str _textDesc: str, optional _implicitParams:",
"portAddress=None, **kw): return AppServicePortSoapBindingSOAP(portAddress or AppServiceLocator.AppServicePortType_address, **kw) class AppServicePortSoapBindingSOAP: def",
"ns1.BlockingOutputType_Def _jobOut: ns1.JobOutputType_Def _outputFile: ns1.OutputFileType_Def, optional _name: str _url: str",
"getOutputsResponse:: _getOutputsOutput: ns1.JobOutputType_Def _outputFile: ns1.OutputFileType_Def, optional _name: str _url: str",
"optional _param: ns1.ParamsType_Def, optional _id: str _ioType: ns1.IOType_Def, optional _paramType:",
"): typecode = ns1.launchJobBlockingOutput_Dec() def __init__(self, name=None, ns=None): ns1.launchJobBlockingOutput_Dec.__init__(self, name=None,",
"response = self.binding.Receive(launchJobBlockingResponseWrapper()) if not isinstance(response, launchJobBlockingResponse) and\\ not issubclass(launchJobBlockingResponse,",
"ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): launchJobBlockingResponse.__init__(",
"_name: str _numProcs: int, optional @return: response from launchJobResponse:: _launchJobOutput:",
"message\"\"\" typecode = getOutputsResponse( name=None, ns=None ).typecode def __init__( self,",
"def getAppMetadata(self, request): \"\"\" @param: request to getAppMetadataRequest @return: response",
"not issubclass(launchJobResponse, response.__class__): raise TypeError(\"%s incorrect response type\" %(response.__class__)) return",
"str _ioType: ns1.IOType_Def _IOType: str, optional _max: int, optional _min:",
"type\" %(request.__class__)) kw = {} response = self.binding.Send(None, None, request,",
"name=None, ns=None): ns1.getAppConfigOutput_Dec.__init__(self, name=None, ns=None) class getAppConfigResponseWrapper(getAppConfigResponse): \"\"\"wrapper for document:literal",
"_usage: str \"\"\" if not isinstance(request, getAppMetadataRequest) and\\ not issubclass(getAppMetadataRequest,",
"__init__( self, name=None, ns=None, **kw ): getAppMetadataRequest.__init__( self, name=None, ns=None",
"request is str @return: response from destroyResponse:: _destroyOutput: ns1.StatusOutputType_Def _baseURL:",
"name=None, ns=None ) class getAppMetadataResponse(ns1.getAppMetadataOutput_Dec): if not hasattr( ns1.getAppMetadataOutput_Dec(), \"typecode\"",
"ns1.launchJobBlockingOutput_Dec.__init__(self, name=None, ns=None) class launchJobBlockingResponseWrapper(launchJobBlockingResponse): \"\"\"wrapper for document:literal message\"\"\" typecode",
"ns1.AppMetadataType_Def _info: str, optional _types: ns1.ArgumentsType_Def, optional _flags: ns1.FlagsArrayType_Def, optional",
"name=None, ns=None, **kw ): getAppConfigRequest.__init__( self, name=None, ns=None ) class",
"): typecode = ns1.getAppConfigOutput_Dec() def __init__(self, name=None, ns=None): ns1.getAppConfigOutput_Dec.__init__(self, name=None,",
"str, optional _metadata: ns1.AppMetadataType_Def _info: str, optional _types: ns1.ArgumentsType_Def, optional",
"ns1.launchJobBlockingInput_Dec(), \"typecode\" ): typecode = ns1.launchJobBlockingInput_Dec() def __init__(self, name=None, ns=None):",
"optional _implicitParams: ns1.ImplicitParamsArrayType_Def, optional _param: ns1.ImplicitParamsType_Def, optional _extension: str, optional",
"ns1.launchJobInput_Dec(), \"typecode\" ): typecode = ns1.launchJobInput_Dec() def __init__(self, name=None, ns=None):",
"name=None, ns=None, **kw ): getOutputsResponse.__init__( self, name=None, ns=None ) class",
"ns1.launchJobOutput_Dec() def __init__(self, name=None, ns=None): ns1.launchJobOutput_Dec.__init__(self, name=None, ns=None) class launchJobResponseWrapper(launchJobResponse):",
"optional _tag: str, optional _textDesc: str, optional _value: str, optional",
"= ns1.launchJobBlockingInput_Dec() def __init__(self, name=None, ns=None): ns1.launchJobBlockingInput_Dec.__init__(self, name=None, ns=None) class",
"def __init__( self, name=None, ns=None, **kw ): queryStatusRequest.__init__( self, name=None,",
"): destroyResponse.__init__( self, name=None, ns=None ) class getAppConfigRequest: def __init__(self,",
"incorrect response type\" %(response.__class__)) return response def launchJob(self, request): \"\"\"",
"name=None, ns=None): ns1.getOutputsOutput_Dec.__init__(self, name=None, ns=None) class getOutputsResponseWrapper(getOutputsResponse): \"\"\"wrapper for document:literal",
"typecode = getAppConfigResponse( name=None, ns=None ).typecode def __init__( self, name=None,",
"_stdOut: str, optional _status: ns1.StatusOutputType_Def _baseURL: str _code: int _message:",
"_code: int _message: str \"\"\" if not isinstance(request, launchJobBlockingRequest) and\\",
"= ns1.getOutputAsBase64ByNameOutput_Dec() def __init__(self, name=None, ns=None): ns1.getOutputAsBase64ByNameOutput_Dec.__init__(self, name=None, ns=None) class",
"class getOutputsResponse(ns1.getOutputsOutput_Dec): if not hasattr( ns1.getOutputsOutput_Dec(), \"typecode\" ): typecode =",
"for document:literal message\"\"\" typecode = getOutputAsBase64ByNameResponse( name=None, ns=None ).typecode def",
"ns1.launchJobOutput_Dec(), \"typecode\" ): typecode = ns1.launchJobOutput_Dec() def __init__(self, name=None, ns=None):",
"launchJobBlockingResponse( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw",
"request to getOutputAsBase64ByNameRequest:: _getOutputAsBase64ByNameInput: ns1.OutputsByNameInputType_Def _fileName: str _jobID: str @return:",
"AppServiceInterface: def getAppServicePortType(self, portAddress=None, **kw): raise NonImplementationError(\"method not implemented\") class",
"name=None, ns=None) class getOutputsResponseWrapper(getOutputsResponse): \"\"\"wrapper for document:literal message\"\"\" typecode =",
"if not isinstance(response, getOutputAsBase64ByNameResponse) and\\ not issubclass(getOutputAsBase64ByNameResponse, response.__class__): raise TypeError(\"%s",
"self.binding.Receive(getOutputsResponseWrapper()) if not isinstance(response, getOutputsResponse) and\\ not issubclass(getOutputsResponse, response.__class__): raise",
"launchJobBlockingResponse.__init__( self, name=None, ns=None ) class launchJobRequest(ns1.launchJobInput_Dec): if not hasattr(",
"ns=None, **kw ): getOutputAsBase64ByNameRequest.__init__( self, name=None, ns=None ) class getOutputAsBase64ByNameResponse(ns1.getOutputAsBase64ByNameOutput_Dec):",
"TypeError(\"%s incorrect request type\" %(request.__class__)) kw = {'requestclass': queryStatusRequestWrapper} response",
").typecode def __init__( self, name=None, ns=None, **kw ): queryStatusResponse.__init__( self,",
"= \"https://rocks-106.sdsc.edu:8443/axis/services/AutogridServicePort\" def getAppServicePortTypeAddress(self): return AppServiceLocator.AppServicePortType_address def getAppServicePortType(self, portAddress=None, **kw):",
"ns=None ) class launchJobRequest(ns1.launchJobInput_Dec): if not hasattr( ns1.launchJobInput_Dec(), \"typecode\" ):",
"= getOutputAsBase64ByNameResponse( name=None, ns=None ).typecode def __init__( self, name=None, ns=None,",
"optional _max: int, optional _min: int, optional _name: str, optional",
"self, name=None, ns=None, **kw ): queryStatusResponse.__init__( self, name=None, ns=None )",
").typecode def __init__( self, name=None, ns=None, **kw ): getAppConfigRequest.__init__( self,",
"_name: str _numProcs: int, optional @return: response from launchJobBlockingResponse:: _launchJobBlockingOutput:",
"getOutputsResponse(ns1.getOutputsOutput_Dec): if not hasattr( ns1.getOutputsOutput_Dec(), \"typecode\" ): typecode = ns1.getOutputsOutput_Dec()",
"str \"\"\" if not isinstance(request, launchJobRequest) and\\ not issubclass(launchJobRequest, request.__class__):",
"class destroyRequestWrapper(destroyRequest): \"\"\"wrapper for document:literal message\"\"\" typecode = destroyRequest( name=None,",
"message\"\"\" typecode = getAppMetadataResponse( name=None, ns=None ).typecode def __init__( self,",
"ns=None, **kw ): queryStatusRequest.__init__( self, name=None, ns=None ) class queryStatusResponse(ns1.queryStatusOutput_Dec):",
"ns=None): ns1.queryStatusInput_Dec.__init__(self, name=None, ns=None) class queryStatusRequestWrapper(queryStatusRequest): \"\"\"wrapper for document:literal message\"\"\"",
"hasattr( ns1.destroyOutput_Dec(), \"typecode\" ): typecode = ns1.destroyOutput_Dec() def __init__(self, name=None,",
"\"\"\"wrapper for document:literal message\"\"\" typecode = destroyResponse( name=None, ns=None ).typecode",
"getAppMetadata(self, request): \"\"\" @param: request to getAppMetadataRequest @return: response from",
"request, soapaction=\"http://nbcr.sdsc.edu/opal/destroy\", **kw) response = self.binding.Receive(destroyResponseWrapper()) if not isinstance(response, destroyResponse)",
"isinstance(request, launchJobRequest) and\\ not issubclass(launchJobRequest, request.__class__): raise TypeError(\"%s incorrect request",
"response = self.binding.Receive(destroyResponseWrapper()) if not isinstance(response, destroyResponse) and\\ not issubclass(destroyResponse,",
"ZSI.TCcompound import Struct from ZSI import client import ZSI class",
"not hasattr( ns1.destroyOutput_Dec(), \"typecode\" ): typecode = ns1.destroyOutput_Dec() def __init__(self,",
"oname=\"%s xmlns=\\\"\\\"\" % name ) class getAppMetadataRequestWrapper(getAppMetadataRequest): \"\"\"wrapper for document:literal",
"**kw ): getOutputAsBase64ByNameRequest.__init__( self, name=None, ns=None ) class getOutputAsBase64ByNameResponse(ns1.getOutputAsBase64ByNameOutput_Dec): if",
"issubclass(launchJobBlockingRequest, request.__class__): raise TypeError(\"%s incorrect request type\" %(request.__class__)) kw =",
"raise TypeError(\"%s incorrect request type\" %(request.__class__)) kw = {} response",
"\"\"\" @param: request to getAppConfigRequest @return: response from getAppConfigResponse:: _getAppConfigOutput:",
"for document:literal message\"\"\" typecode = getOutputsRequest( name=None, ns=None ).typecode def",
"name=None, ns=None, **kw ): getOutputAsBase64ByNameResponse.__init__( self, name=None, ns=None ) class",
"_url: str _stdErr: str, optional _stdOut: str, optional _status: ns1.StatusOutputType_Def",
"name=None, ns=None): getAppConfigRequest.typecode = Struct(getAppConfigRequest,[], pname=name, aname=\"%s\" % name, oname=\"%s",
"ZSI import client import ZSI class AppServiceInterface: def getAppServicePortType(self, portAddress=None,",
"generated by ZSI.wsdl2python # # ################################################## from .AppService_services_types import *",
"getAppConfigRequest @return: response from getAppConfigResponse:: _getAppConfigOutput: ns1.AppConfigType_Def _binaryLocation: str _defaultArgs:",
"and\\ not issubclass(launchJobResponse, response.__class__): raise TypeError(\"%s incorrect response type\" %(response.__class__))",
"name=None, ns=None) class destroyRequestWrapper(destroyRequest): \"\"\"wrapper for document:literal message\"\"\" typecode =",
"destroyRequestWrapper(destroyRequest): \"\"\"wrapper for document:literal message\"\"\" typecode = destroyRequest( name=None, ns=None",
"def __init__(self, name=None, ns=None): ns1.launchJobInput_Dec.__init__(self, name=None, ns=None) class launchJobRequestWrapper(launchJobRequest): \"\"\"wrapper",
"optional _semanticType: str, optional _tag: str, optional _textDesc: str, optional",
"document:literal message\"\"\" typecode = launchJobResponse( name=None, ns=None ).typecode def __init__(",
"%(response.__class__)) return response def getOutputs(self, request): \"\"\" @param: request is",
"kw: kw[\"url\"] = urllib.parse.urlparse(addr)[2] self.binding = client.Binding(**kw) def destroy(self, request):",
"aname=\"%s\" % name, oname=\"%s xmlns=\\\"\\\"\" % name ) class getAppMetadataRequestWrapper(getAppMetadataRequest):",
"request to launchJobBlockingRequest:: _launchJobBlockingInput: ns1.JobInputType_Def _argList: str, optional _inputFile: ns1.InputFileType_Def,",
"ns=None ) class getOutputsResponse(ns1.getOutputsOutput_Dec): if not hasattr( ns1.getOutputsOutput_Dec(), \"typecode\" ):",
"not isinstance(response, destroyResponse) and\\ not issubclass(destroyResponse, response.__class__): raise TypeError(\"%s incorrect",
"= getAppConfigResponse( name=None, ns=None ).typecode def __init__( self, name=None, ns=None,",
"str, optional _untaggedParams: ns1.ParamsArrayType_Def, optional _usage: str _parallel: boolean \"\"\"",
"queryStatusResponse:: _queryStatusOutput: ns1.StatusOutputType_Def _baseURL: str _code: int _message: str \"\"\"",
"to getOutputAsBase64ByNameRequest:: _getOutputAsBase64ByNameInput: ns1.OutputsByNameInputType_Def _fileName: str _jobID: str @return: response",
"optional _name: str, optional _required: boolean, optional _semanticType: str, optional",
"{'requestclass': queryStatusRequestWrapper} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/queryStatus\", **kw) response",
"def destroy(self, request): \"\"\" @param: request is str @return: response",
"from destroyResponse:: _destroyOutput: ns1.StatusOutputType_Def _baseURL: str _code: int _message: str",
"self, name=None, ns=None, **kw ): getOutputAsBase64ByNameResponse.__init__( self, name=None, ns=None )",
"optional \"\"\" if not isinstance(request, str): raise TypeError(\"%s incorrect request",
"= self.binding.Receive(getAppConfigResponseWrapper()) if not isinstance(response, getAppConfigResponse) and\\ not issubclass(getAppConfigResponse, response.__class__):",
"ns1.launchJobBlockingInput_Dec.__init__(self, name=None, ns=None) class launchJobBlockingRequestWrapper(launchJobBlockingRequest): \"\"\"wrapper for document:literal message\"\"\" typecode",
"__init__(self, name=None, ns=None): ns1.launchJobOutput_Dec.__init__(self, name=None, ns=None) class launchJobResponseWrapper(launchJobResponse): \"\"\"wrapper for",
"): launchJobRequest.__init__( self, name=None, ns=None ) class launchJobResponse(ns1.launchJobOutput_Dec): if not",
"_stdErr: str, optional _stdOut: str, optional \"\"\" if not isinstance(request,",
"self, name=None, ns=None ) class destroyResponse(ns1.destroyOutput_Dec): if not hasattr( ns1.destroyOutput_Dec(),",
"type\" %(response.__class__)) return response def queryStatus(self, request): \"\"\" @param: request",
"_item: str, optional \"\"\" if not isinstance(request, getOutputAsBase64ByNameRequest) and\\ not",
"raise TypeError(\"%s incorrect request type\" %(request.__class__)) kw = {'requestclass': getOutputsRequestWrapper}",
"not in kw: kw[\"port\"] = int(netloc[1]) if \"url\" not in",
"ns1.OutputFileType_Def, optional _name: str _url: str _stdErr: str, optional _stdOut:",
"__init__(self, addr, **kw): netloc = (urllib.parse.urlparse(addr)[1]).split(\":\") + [80,] if \"host\"",
"ns=None) class launchJobBlockingResponseWrapper(launchJobBlockingResponse): \"\"\"wrapper for document:literal message\"\"\" typecode = launchJobBlockingResponse(",
"\"\"\"wrapper for document:literal message\"\"\" typecode = getOutputsResponse( name=None, ns=None ).typecode",
"class launchJobBlockingResponse(ns1.launchJobBlockingOutput_Dec): if not hasattr( ns1.launchJobBlockingOutput_Dec(), \"typecode\" ): typecode =",
"def __init__( self, name=None, ns=None, **kw ): launchJobBlockingResponse.__init__( self, name=None,",
"@return: response from getAppConfigResponse:: _getAppConfigOutput: ns1.AppConfigType_Def _binaryLocation: str _defaultArgs: str,",
"optional _separator: str, optional _untaggedParams: ns1.ParamsArrayType_Def, optional _usage: str \"\"\"",
"issubclass(getOutputAsBase64ByNameResponse, response.__class__): raise TypeError(\"%s incorrect response type\" %(response.__class__)) return response",
"): getAppConfigResponse.__init__( self, name=None, ns=None ) class getAppMetadataRequest: def __init__(self,",
"name=None, ns=None ) class getOutputsRequest(ns1.getOutputsInput_Dec): if not hasattr( ns1.getOutputsInput_Dec(), \"typecode\"",
"optional _types: ns1.ArgumentsType_Def, optional _flags: ns1.FlagsArrayType_Def, optional _flag: ns1.FlagsType_Def, optional",
"queryStatusRequest( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw",
"and\\ not issubclass(launchJobRequest, request.__class__): raise TypeError(\"%s incorrect request type\" %(request.__class__))",
"if not isinstance(response, getAppMetadataResponse) and\\ not issubclass(getAppMetadataResponse, response.__class__): raise TypeError(\"%s",
"_tag: str, optional _textDesc: str, optional _value: str, optional _separator:",
"request): \"\"\" @param: request is str @return: response from queryStatusResponse::",
"and\\ not issubclass(queryStatusResponse, response.__class__): raise TypeError(\"%s incorrect response type\" %(response.__class__))",
"not hasattr( ns1.getAppConfigOutput_Dec(), \"typecode\" ): typecode = ns1.getAppConfigOutput_Dec() def __init__(self,",
"_tag: str _textDesc: str, optional _implicitParams: ns1.ImplicitParamsArrayType_Def, optional _param: ns1.ImplicitParamsType_Def,",
"__init__( self, name=None, ns=None, **kw ): getOutputsRequest.__init__( self, name=None, ns=None",
"name=None, ns=None, **kw ): getAppMetadataResponse.__init__( self, name=None, ns=None ) class",
"class queryStatusResponse(ns1.queryStatusOutput_Dec): if not hasattr( ns1.queryStatusOutput_Dec(), \"typecode\" ): typecode =",
"None, request, soapaction=\"http://nbcr.sdsc.edu/opal/destroy\", **kw) response = self.binding.Receive(destroyResponseWrapper()) if not isinstance(response,",
"ns1.JobOutputType_Def _outputFile: ns1.OutputFileType_Def, optional _name: str _url: str _stdErr: str,",
"{} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/launchJob\", **kw) response =",
"aname=\"%s\" % name, oname=\"%s xmlns=\\\"\\\"\" % name ) class getAppConfigRequestWrapper(getAppConfigRequest):",
"response type\" %(response.__class__)) return response def launchJob(self, request): \"\"\" @param:",
"def __init__( self, name=None, ns=None, **kw ): destroyResponse.__init__( self, name=None,",
"ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): launchJobRequest.__init__(",
"class getOutputAsBase64ByNameRequest(ns1.getOutputAsBase64ByNameInput_Dec): if not hasattr( ns1.getOutputAsBase64ByNameInput_Dec(), \"typecode\" ): typecode =",
"self, name=None, ns=None ) class getOutputAsBase64ByNameRequest(ns1.getOutputAsBase64ByNameInput_Dec): if not hasattr( ns1.getOutputAsBase64ByNameInput_Dec(),",
"if not isinstance(request, getOutputAsBase64ByNameRequest) and\\ not issubclass(getOutputAsBase64ByNameRequest, request.__class__): raise TypeError(\"%s",
"= getOutputsRequest( name=None, ns=None ).typecode def __init__( self, name=None, ns=None,",
"getAppConfigRequestWrapper(getAppConfigRequest): \"\"\"wrapper for document:literal message\"\"\" typecode = getAppConfigRequest( name=None, ns=None",
"int _message: str \"\"\" if not isinstance(request, launchJobRequest) and\\ not",
"types from ZSI.TCcompound import Struct from ZSI import client import",
"% name, oname=\"%s xmlns=\\\"\\\"\" % name ) class getAppConfigRequestWrapper(getAppConfigRequest): \"\"\"wrapper",
"ns1.launchJobBlockingOutput_Dec() def __init__(self, name=None, ns=None): ns1.launchJobBlockingOutput_Dec.__init__(self, name=None, ns=None) class launchJobBlockingResponseWrapper(launchJobBlockingResponse):",
"): launchJobBlockingResponse.__init__( self, name=None, ns=None ) class launchJobRequest(ns1.launchJobInput_Dec): if not",
"__init__( self, name=None, ns=None, **kw ): launchJobRequest.__init__( self, name=None, ns=None",
"class getOutputsResponseWrapper(getOutputsResponse): \"\"\"wrapper for document:literal message\"\"\" typecode = getOutputsResponse( name=None,",
"_launchJobBlockingInput: ns1.JobInputType_Def _argList: str, optional _inputFile: ns1.InputFileType_Def, optional _contents: str",
"ns=None): ns1.getOutputAsBase64ByNameOutput_Dec.__init__(self, name=None, ns=None) class getOutputAsBase64ByNameResponseWrapper(getOutputAsBase64ByNameResponse): \"\"\"wrapper for document:literal message\"\"\"",
"response def getOutputs(self, request): \"\"\" @param: request is str @return:",
"str _jobID: str @return: response from getOutputAsBase64ByNameResponse:: _item: str, optional",
"= self.binding.Receive(launchJobBlockingResponseWrapper()) if not isinstance(response, launchJobBlockingResponse) and\\ not issubclass(launchJobBlockingResponse, response.__class__):",
"self, name=None, ns=None, **kw ): getAppConfigRequest.__init__( self, name=None, ns=None )",
"optional _taggedParams: ns1.ParamsArrayType_Def, optional _param: ns1.ParamsType_Def, optional _id: str _ioType:",
"getOutputAsBase64ByNameRequest(ns1.getOutputAsBase64ByNameInput_Dec): if not hasattr( ns1.getOutputAsBase64ByNameInput_Dec(), \"typecode\" ): typecode = ns1.getOutputAsBase64ByNameInput_Dec()",
"**kw ): destroyResponse.__init__( self, name=None, ns=None ) class getAppConfigRequest: def",
"typecode = getOutputsResponse( name=None, ns=None ).typecode def __init__( self, name=None,",
"_stdErr: str, optional _stdOut: str, optional _status: ns1.StatusOutputType_Def _baseURL: str",
"): launchJobBlockingRequest.__init__( self, name=None, ns=None ) class launchJobBlockingResponse(ns1.launchJobBlockingOutput_Dec): if not",
"message\"\"\" typecode = launchJobResponse( name=None, ns=None ).typecode def __init__( self,",
"or AppServiceLocator.AppServicePortType_address, **kw) class AppServicePortSoapBindingSOAP: def __init__(self, addr, **kw): netloc",
"%(request.__class__)) kw = {} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/launchJobBlocking\",",
"int _message: str \"\"\" if not isinstance(request, launchJobBlockingRequest) and\\ not",
"optional _contents: str _name: str _numProcs: int, optional @return: response",
"getOutputAsBase64ByNameResponse.__init__( self, name=None, ns=None ) class getOutputsRequest(ns1.getOutputsInput_Dec): if not hasattr(",
"class getOutputAsBase64ByNameResponseWrapper(getOutputAsBase64ByNameResponse): \"\"\"wrapper for document:literal message\"\"\" typecode = getOutputAsBase64ByNameResponse( name=None,",
"self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getOutputs\", **kw) response = self.binding.Receive(getOutputsResponseWrapper()) if not",
"_textDesc: str, optional _implicitParams: ns1.ImplicitParamsArrayType_Def, optional _param: ns1.ImplicitParamsType_Def, optional _extension:",
"_usage: str _parallel: boolean \"\"\" if not isinstance(request, getAppConfigRequest) and\\",
"= getAppConfigRequest( name=None, ns=None ).typecode def __init__( self, name=None, ns=None,",
"TypeError(\"%s incorrect request type\" %(request.__class__)) kw = {'requestclass': destroyRequestWrapper} response",
"response type\" %(response.__class__)) return response def getOutputs(self, request): \"\"\" @param:",
"message\"\"\" typecode = launchJobBlockingRequest( name=None, ns=None ).typecode def __init__( self,",
"%(request.__class__)) kw = {} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getAppConfig\",",
"document:literal message\"\"\" typecode = destroyRequest( name=None, ns=None ).typecode def __init__(",
"ns=None ) class queryStatusResponse(ns1.queryStatusOutput_Dec): if not hasattr( ns1.queryStatusOutput_Dec(), \"typecode\" ):",
"response from getAppConfigResponse:: _getAppConfigOutput: ns1.AppConfigType_Def _binaryLocation: str _defaultArgs: str, optional",
"name, oname=\"%s xmlns=\\\"\\\"\" % name ) class getAppConfigRequestWrapper(getAppConfigRequest): \"\"\"wrapper for",
"message\"\"\" typecode = destroyResponse( name=None, ns=None ).typecode def __init__( self,",
"class getAppMetadataRequest: def __init__(self, name=None, ns=None): getAppMetadataRequest.typecode = Struct(getAppMetadataRequest,[], pname=name,",
"if not hasattr( ns1.launchJobBlockingInput_Dec(), \"typecode\" ): typecode = ns1.launchJobBlockingInput_Dec() def",
"typecode = ns1.getOutputsInput_Dec() def __init__(self, name=None, ns=None): ns1.getOutputsInput_Dec.__init__(self, name=None, ns=None)",
"getOutputAsBase64ByNameResponse(ns1.getOutputAsBase64ByNameOutput_Dec): if not hasattr( ns1.getOutputAsBase64ByNameOutput_Dec(), \"typecode\" ): typecode = ns1.getOutputAsBase64ByNameOutput_Dec()",
"kw = {'requestclass': destroyRequestWrapper} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/destroy\",",
"def __init__(self, name=None, ns=None): ns1.getOutputAsBase64ByNameInput_Dec.__init__(self, name=None, ns=None) class getOutputAsBase64ByNameRequestWrapper(getOutputAsBase64ByNameRequest): \"\"\"wrapper",
"typecode = ns1.queryStatusInput_Dec() def __init__(self, name=None, ns=None): ns1.queryStatusInput_Dec.__init__(self, name=None, ns=None)",
"ns=None, **kw ): getAppMetadataRequest.__init__( self, name=None, ns=None ) class getAppMetadataResponse(ns1.getAppMetadataOutput_Dec):",
"ns1.launchJobOutput_Dec.__init__(self, name=None, ns=None) class launchJobResponseWrapper(launchJobResponse): \"\"\"wrapper for document:literal message\"\"\" typecode",
"ns1.queryStatusInput_Dec(), \"typecode\" ): typecode = ns1.queryStatusInput_Dec() def __init__(self, name=None, ns=None):",
"self, name=None, ns=None, **kw ): destroyResponse.__init__( self, name=None, ns=None )",
"ns1.getAppConfigOutput_Dec.__init__(self, name=None, ns=None) class getAppConfigResponseWrapper(getAppConfigResponse): \"\"\"wrapper for document:literal message\"\"\" typecode",
"\"typecode\" ): typecode = ns1.launchJobInput_Dec() def __init__(self, name=None, ns=None): ns1.launchJobInput_Dec.__init__(self,",
"\"\"\" @param: request is str @return: response from destroyResponse:: _destroyOutput:",
"request): \"\"\" @param: request to getAppConfigRequest @return: response from getAppConfigResponse::",
"for document:literal message\"\"\" typecode = launchJobBlockingResponse( name=None, ns=None ).typecode def",
"getAppMetadataRequest( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw",
"launchJobBlockingRequest:: _launchJobBlockingInput: ns1.JobInputType_Def _argList: str, optional _inputFile: ns1.InputFileType_Def, optional _contents:",
"kw: kw[\"port\"] = int(netloc[1]) if \"url\" not in kw: kw[\"url\"]",
"raise NonImplementationError(\"method not implemented\") class AppServiceLocator(AppServiceInterface): AppServicePortType_address = \"https://rocks-106.sdsc.edu:8443/axis/services/AutogridServicePort\" def",
"return response def getOutputAsBase64ByName(self, request): \"\"\" @param: request to getOutputAsBase64ByNameRequest::",
"queryStatusResponse( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw",
"if not hasattr( ns1.destroyInput_Dec(), \"typecode\" ): typecode = ns1.destroyInput_Dec() def",
"= self.binding.Receive(getOutputsResponseWrapper()) if not isinstance(response, getOutputsResponse) and\\ not issubclass(getOutputsResponse, response.__class__):",
"message\"\"\" typecode = getAppMetadataRequest( name=None, ns=None ).typecode def __init__( self,",
"request): \"\"\" @param: request to getAppMetadataRequest @return: response from getAppMetadataResponse::",
"response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getOutputAsBase64ByName\", **kw) response = self.binding.Receive(getOutputAsBase64ByNameResponseWrapper())",
"= {'requestclass': getOutputsRequestWrapper} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getOutputs\", **kw)",
"getOutputAsBase64ByNameResponseWrapper(getOutputAsBase64ByNameResponse): \"\"\"wrapper for document:literal message\"\"\" typecode = getOutputAsBase64ByNameResponse( name=None, ns=None",
"ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): queryStatusRequest.__init__(",
"ns=None) class launchJobResponseWrapper(launchJobResponse): \"\"\"wrapper for document:literal message\"\"\" typecode = launchJobResponse(",
"def getAppServicePortType(self, portAddress=None, **kw): return AppServicePortSoapBindingSOAP(portAddress or AppServiceLocator.AppServicePortType_address, **kw) class",
"typecode = getOutputAsBase64ByNameResponse( name=None, ns=None ).typecode def __init__( self, name=None,",
"self, name=None, ns=None, **kw ): getAppMetadataRequest.__init__( self, name=None, ns=None )",
"self.binding.Receive(getAppConfigResponseWrapper()) if not isinstance(response, getAppConfigResponse) and\\ not issubclass(getAppConfigResponse, response.__class__): raise",
"name=None, ns=None, **kw ): launchJobResponse.__init__( self, name=None, ns=None ) class",
"return response def launchJob(self, request): \"\"\" @param: request to launchJobRequest::",
").typecode def __init__( self, name=None, ns=None, **kw ): destroyRequest.__init__( self,",
"\"\"\" @param: request to launchJobBlockingRequest:: _launchJobBlockingInput: ns1.JobInputType_Def _argList: str, optional",
"request is str @return: response from getOutputsResponse:: _getOutputsOutput: ns1.JobOutputType_Def _outputFile:",
"getOutputsResponse) and\\ not issubclass(getOutputsResponse, response.__class__): raise TypeError(\"%s incorrect response type\"",
"ns1.getOutputsInput_Dec.__init__(self, name=None, ns=None) class getOutputsRequestWrapper(getOutputsRequest): \"\"\"wrapper for document:literal message\"\"\" typecode",
"ns1.IOType_Def _IOType: str, optional _max: int, optional _min: int, optional",
"document:literal message\"\"\" typecode = getAppConfigRequest( name=None, ns=None ).typecode def __init__(",
"launchJobRequest(ns1.launchJobInput_Dec): if not hasattr( ns1.launchJobInput_Dec(), \"typecode\" ): typecode = ns1.launchJobInput_Dec()",
"name=None, ns=None) class launchJobBlockingResponseWrapper(launchJobBlockingResponse): \"\"\"wrapper for document:literal message\"\"\" typecode =",
"ns=None): ns1.getAppMetadataOutput_Dec.__init__(self, name=None, ns=None) class getAppMetadataResponseWrapper(getAppMetadataResponse): \"\"\"wrapper for document:literal message\"\"\"",
"ns1.destroyOutput_Dec() def __init__(self, name=None, ns=None): ns1.destroyOutput_Dec.__init__(self, name=None, ns=None) class destroyResponseWrapper(destroyResponse):",
"getAppMetadataResponse( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw",
"= int(netloc[1]) if \"url\" not in kw: kw[\"url\"] = urllib.parse.urlparse(addr)[2]",
"% name, oname=\"%s xmlns=\\\"\\\"\" % name ) class getAppMetadataRequestWrapper(getAppMetadataRequest): \"\"\"wrapper",
"= self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getAppConfig\", **kw) response = self.binding.Receive(getAppConfigResponseWrapper()) if",
"not isinstance(response, getAppConfigResponse) and\\ not issubclass(getAppConfigResponse, response.__class__): raise TypeError(\"%s incorrect",
"destroyRequest( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw",
"= {'requestclass': queryStatusRequestWrapper} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/queryStatus\", **kw)",
"str, optional _taggedParams: ns1.ParamsArrayType_Def, optional _param: ns1.ParamsType_Def, optional _id: str",
"launchJobBlockingResponse(ns1.launchJobBlockingOutput_Dec): if not hasattr( ns1.launchJobBlockingOutput_Dec(), \"typecode\" ): typecode = ns1.launchJobBlockingOutput_Dec()",
"typecode = getOutputAsBase64ByNameRequest( name=None, ns=None ).typecode def __init__( self, name=None,",
"name=None, ns=None): ns1.launchJobBlockingOutput_Dec.__init__(self, name=None, ns=None) class launchJobBlockingResponseWrapper(launchJobBlockingResponse): \"\"\"wrapper for document:literal",
"self, name=None, ns=None ) class queryStatusRequest(ns1.queryStatusInput_Dec): if not hasattr( ns1.queryStatusInput_Dec(),",
"response from getAppMetadataResponse:: _getAppMetadataOutput: ns1.AppMetadataType_Def _info: str, optional _types: ns1.ArgumentsType_Def,",
"\"typecode\" ): typecode = ns1.queryStatusOutput_Dec() def __init__(self, name=None, ns=None): ns1.queryStatusOutput_Dec.__init__(self,",
"@param: request to getOutputAsBase64ByNameRequest:: _getOutputAsBase64ByNameInput: ns1.OutputsByNameInputType_Def _fileName: str _jobID: str",
"class getOutputsRequestWrapper(getOutputsRequest): \"\"\"wrapper for document:literal message\"\"\" typecode = getOutputsRequest( name=None,",
"{} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getOutputAsBase64ByName\", **kw) response =",
"int, optional @return: response from launchJobBlockingResponse:: _launchJobBlockingOutput: ns1.BlockingOutputType_Def _jobOut: ns1.JobOutputType_Def",
"ns1.ParamsArrayType_Def, optional _param: ns1.ParamsType_Def, optional _id: str _ioType: ns1.IOType_Def, optional",
"not issubclass(getOutputAsBase64ByNameRequest, request.__class__): raise TypeError(\"%s incorrect request type\" %(request.__class__)) kw",
"getAppMetadataResponse.__init__( self, name=None, ns=None ) class getOutputAsBase64ByNameRequest(ns1.getOutputAsBase64ByNameInput_Dec): if not hasattr(",
"\"\"\"wrapper for document:literal message\"\"\" typecode = getAppConfigRequest( name=None, ns=None ).typecode",
"request to getAppConfigRequest @return: response from getAppConfigResponse:: _getAppConfigOutput: ns1.AppConfigType_Def _binaryLocation:",
"ns=None) class queryStatusRequestWrapper(queryStatusRequest): \"\"\"wrapper for document:literal message\"\"\" typecode = queryStatusRequest(",
"= self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getOutputs\", **kw) response = self.binding.Receive(getOutputsResponseWrapper()) if",
"Struct(getAppMetadataRequest,[], pname=name, aname=\"%s\" % name, oname=\"%s xmlns=\\\"\\\"\" % name )",
"_ioType: ns1.IOType_Def _IOType: str, optional _max: int, optional _min: int,",
"ns=None): ns1.launchJobBlockingInput_Dec.__init__(self, name=None, ns=None) class launchJobBlockingRequestWrapper(launchJobBlockingRequest): \"\"\"wrapper for document:literal message\"\"\"",
"issubclass(getOutputsResponse, response.__class__): raise TypeError(\"%s incorrect response type\" %(response.__class__)) return response",
"not hasattr( ns1.launchJobInput_Dec(), \"typecode\" ): typecode = ns1.launchJobInput_Dec() def __init__(self,",
"self.binding.Receive(getAppMetadataResponseWrapper()) if not isinstance(response, getAppMetadataResponse) and\\ not issubclass(getAppMetadataResponse, response.__class__): raise",
"\"typecode\" ): typecode = ns1.destroyInput_Dec() def __init__(self, name=None, ns=None): ns1.destroyInput_Dec.__init__(self,",
"not hasattr( ns1.getOutputsInput_Dec(), \"typecode\" ): typecode = ns1.getOutputsInput_Dec() def __init__(self,",
"str, optional _tag: str, optional _textDesc: str, optional _value: str,",
"(urllib.parse.urlparse(addr)[1]).split(\":\") + [80,] if \"host\" not in kw: kw[\"host\"] =",
"* from .AppService_services_types import \\ nbcr_sdsc_edu_opal_types as ns1 import urllib.parse,",
"name=None, ns=None): ns1.destroyOutput_Dec.__init__(self, name=None, ns=None) class destroyResponseWrapper(destroyResponse): \"\"\"wrapper for document:literal",
"ns1.getOutputAsBase64ByNameOutput_Dec(), \"typecode\" ): typecode = ns1.getOutputAsBase64ByNameOutput_Dec() def __init__(self, name=None, ns=None):",
"ns=None): ns1.getOutputAsBase64ByNameInput_Dec.__init__(self, name=None, ns=None) class getOutputAsBase64ByNameRequestWrapper(getOutputAsBase64ByNameRequest): \"\"\"wrapper for document:literal message\"\"\"",
"optional _semanticType: str, optional _textDesc: str, optional _taggedParams: ns1.ParamsArrayType_Def, optional",
"): typecode = ns1.queryStatusOutput_Dec() def __init__(self, name=None, ns=None): ns1.queryStatusOutput_Dec.__init__(self, name=None,",
"for document:literal message\"\"\" typecode = getAppConfigResponse( name=None, ns=None ).typecode def",
"request): \"\"\" @param: request to getOutputAsBase64ByNameRequest:: _getOutputAsBase64ByNameInput: ns1.OutputsByNameInputType_Def _fileName: str",
"str, optional _separator: str, optional _untaggedParams: ns1.ParamsArrayType_Def, optional _usage: str",
"__init__(self, name=None, ns=None): ns1.queryStatusInput_Dec.__init__(self, name=None, ns=None) class queryStatusRequestWrapper(queryStatusRequest): \"\"\"wrapper for",
"if not isinstance(request, str): raise TypeError(\"%s incorrect request type\" %(request.__class__))",
"response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getAppMetadata\", **kw) response = self.binding.Receive(getAppMetadataResponseWrapper())",
"= {} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getAppConfig\", **kw) response",
"None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getOutputs\", **kw) response = self.binding.Receive(getOutputsResponseWrapper()) if not isinstance(response,",
"if not isinstance(response, queryStatusResponse) and\\ not issubclass(queryStatusResponse, response.__class__): raise TypeError(\"%s",
"self, name=None, ns=None ) class getAppConfigResponse(ns1.getAppConfigOutput_Dec): if not hasattr( ns1.getAppConfigOutput_Dec(),",
"_ioType: ns1.IOType_Def, optional _paramType: ns1.ParamType_Def _ParamType: str, optional _required: boolean,",
"kw[\"port\"] = int(netloc[1]) if \"url\" not in kw: kw[\"url\"] =",
"message\"\"\" typecode = getOutputsRequest( name=None, ns=None ).typecode def __init__( self,",
".AppService_services_types import * from .AppService_services_types import \\ nbcr_sdsc_edu_opal_types as ns1",
"typecode = ns1.launchJobOutput_Dec() def __init__(self, name=None, ns=None): ns1.launchJobOutput_Dec.__init__(self, name=None, ns=None)",
"xmlns=\\\"\\\"\" % name ) class getAppMetadataRequestWrapper(getAppMetadataRequest): \"\"\"wrapper for document:literal message\"\"\"",
"name=None, ns=None) class queryStatusRequestWrapper(queryStatusRequest): \"\"\"wrapper for document:literal message\"\"\" typecode =",
"getOutputsResponse.__init__( self, name=None, ns=None ) class launchJobBlockingRequest(ns1.launchJobBlockingInput_Dec): if not hasattr(",
"= {} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/launchJobBlocking\", **kw) response",
"ns=None, **kw ): destroyRequest.__init__( self, name=None, ns=None ) class destroyResponse(ns1.destroyOutput_Dec):",
"incorrect request type\" %(request.__class__)) kw = {} response = self.binding.Send(None,",
"name=None, ns=None, **kw ): launchJobBlockingRequest.__init__( self, name=None, ns=None ) class",
"def launchJobBlocking(self, request): \"\"\" @param: request to launchJobBlockingRequest:: _launchJobBlockingInput: ns1.JobInputType_Def",
"optional _paramType: ns1.ParamType_Def _ParamType: str, optional _required: boolean, optional _semanticType:",
") class getAppMetadataRequestWrapper(getAppMetadataRequest): \"\"\"wrapper for document:literal message\"\"\" typecode = getAppMetadataRequest(",
"issubclass(launchJobResponse, response.__class__): raise TypeError(\"%s incorrect response type\" %(response.__class__)) return response",
"**kw ): launchJobBlockingResponse.__init__( self, name=None, ns=None ) class launchJobRequest(ns1.launchJobInput_Dec): if",
"_queryStatusOutput: ns1.StatusOutputType_Def _baseURL: str _code: int _message: str \"\"\" if",
"\"https://rocks-106.sdsc.edu:8443/axis/services/AutogridServicePort\" def getAppServicePortTypeAddress(self): return AppServiceLocator.AppServicePortType_address def getAppServicePortType(self, portAddress=None, **kw): return",
"name=None, ns=None) class launchJobResponseWrapper(launchJobResponse): \"\"\"wrapper for document:literal message\"\"\" typecode =",
"name=None, ns=None) class queryStatusResponseWrapper(queryStatusResponse): \"\"\"wrapper for document:literal message\"\"\" typecode =",
"incorrect response type\" %(response.__class__)) return response def getAppConfig(self, request): \"\"\"",
"name=None, ns=None ) class getOutputsResponse(ns1.getOutputsOutput_Dec): if not hasattr( ns1.getOutputsOutput_Dec(), \"typecode\"",
"= getOutputAsBase64ByNameRequest( name=None, ns=None ).typecode def __init__( self, name=None, ns=None,",
"= self.binding.Receive(getOutputAsBase64ByNameResponseWrapper()) if not isinstance(response, getOutputAsBase64ByNameResponse) and\\ not issubclass(getOutputAsBase64ByNameResponse, response.__class__):",
"launchJobBlockingRequest) and\\ not issubclass(launchJobBlockingRequest, request.__class__): raise TypeError(\"%s incorrect request type\"",
"# ./AppService_services.py # generated by ZSI.wsdl2python # # ################################################## from",
"__init__( self, name=None, ns=None, **kw ): getOutputAsBase64ByNameResponse.__init__( self, name=None, ns=None",
"\"typecode\" ): typecode = ns1.launchJobBlockingOutput_Dec() def __init__(self, name=None, ns=None): ns1.launchJobBlockingOutput_Dec.__init__(self,",
"hasattr( ns1.destroyInput_Dec(), \"typecode\" ): typecode = ns1.destroyInput_Dec() def __init__(self, name=None,",
"**kw) response = self.binding.Receive(getOutputsResponseWrapper()) if not isinstance(response, getOutputsResponse) and\\ not",
") class queryStatusRequest(ns1.queryStatusInput_Dec): if not hasattr( ns1.queryStatusInput_Dec(), \"typecode\" ): typecode",
"getOutputAsBase64ByNameResponse) and\\ not issubclass(getOutputAsBase64ByNameResponse, response.__class__): raise TypeError(\"%s incorrect response type\"",
"self, name=None, ns=None ) class launchJobBlockingRequest(ns1.launchJobBlockingInput_Dec): if not hasattr( ns1.launchJobBlockingInput_Dec(),",
"response from queryStatusResponse:: _queryStatusOutput: ns1.StatusOutputType_Def _baseURL: str _code: int _message:",
"name=None, ns=None, **kw ): queryStatusRequest.__init__( self, name=None, ns=None ) class",
"message\"\"\" typecode = getOutputAsBase64ByNameResponse( name=None, ns=None ).typecode def __init__( self,",
"and\\ not issubclass(launchJobBlockingResponse, response.__class__): raise TypeError(\"%s incorrect response type\" %(response.__class__))",
"getAppServicePortType(self, portAddress=None, **kw): raise NonImplementationError(\"method not implemented\") class AppServiceLocator(AppServiceInterface): AppServicePortType_address",
"in kw: kw[\"port\"] = int(netloc[1]) if \"url\" not in kw:",
"self.binding.Receive(launchJobBlockingResponseWrapper()) if not isinstance(response, launchJobBlockingResponse) and\\ not issubclass(launchJobBlockingResponse, response.__class__): raise",
"**kw ): getOutputsResponse.__init__( self, name=None, ns=None ) class launchJobBlockingRequest(ns1.launchJobBlockingInput_Dec): if",
"\"\"\"wrapper for document:literal message\"\"\" typecode = getOutputsRequest( name=None, ns=None ).typecode",
"launchJobBlockingResponseWrapper(launchJobBlockingResponse): \"\"\"wrapper for document:literal message\"\"\" typecode = launchJobBlockingResponse( name=None, ns=None",
"ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): launchJobResponse.__init__(",
") class getOutputAsBase64ByNameRequest(ns1.getOutputAsBase64ByNameInput_Dec): if not hasattr( ns1.getOutputAsBase64ByNameInput_Dec(), \"typecode\" ): typecode",
"str, optional _stdOut: str, optional \"\"\" if not isinstance(request, str):",
"_message: str \"\"\" if not isinstance(request, launchJobBlockingRequest) and\\ not issubclass(launchJobBlockingRequest,",
"str _code: int _message: str \"\"\" if not isinstance(request, str):",
"str _name: str _numProcs: int, optional @return: response from launchJobResponse::",
").typecode def __init__( self, name=None, ns=None, **kw ): getAppMetadataRequest.__init__( self,",
"incorrect request type\" %(request.__class__)) kw = {'requestclass': destroyRequestWrapper} response =",
"name=None, ns=None ) class queryStatusRequest(ns1.queryStatusInput_Dec): if not hasattr( ns1.queryStatusInput_Dec(), \"typecode\"",
"soapaction=\"http://nbcr.sdsc.edu/opal/queryStatus\", **kw) response = self.binding.Receive(queryStatusResponseWrapper()) if not isinstance(response, queryStatusResponse) and\\",
"getOutputAsBase64ByName(self, request): \"\"\" @param: request to getOutputAsBase64ByNameRequest:: _getOutputAsBase64ByNameInput: ns1.OutputsByNameInputType_Def _fileName:",
"if not isinstance(response, getOutputsResponse) and\\ not issubclass(getOutputsResponse, response.__class__): raise TypeError(\"%s",
"for document:literal message\"\"\" typecode = destroyRequest( name=None, ns=None ).typecode def",
"class queryStatusRequest(ns1.queryStatusInput_Dec): if not hasattr( ns1.queryStatusInput_Dec(), \"typecode\" ): typecode =",
"ns1.OutputsByNameInputType_Def _fileName: str _jobID: str @return: response from getOutputAsBase64ByNameResponse:: _item:",
"ns=None) class getOutputsResponseWrapper(getOutputsResponse): \"\"\"wrapper for document:literal message\"\"\" typecode = getOutputsResponse(",
"launchJobResponse.__init__( self, name=None, ns=None ) class queryStatusRequest(ns1.queryStatusInput_Dec): if not hasattr(",
"not issubclass(launchJobBlockingRequest, request.__class__): raise TypeError(\"%s incorrect request type\" %(request.__class__)) kw",
"\"\"\"wrapper for document:literal message\"\"\" typecode = getAppConfigResponse( name=None, ns=None ).typecode",
"_textDesc: str, optional _value: str, optional _separator: str, optional _untaggedParams:",
"getAppConfigResponse:: _getAppConfigOutput: ns1.AppConfigType_Def _binaryLocation: str _defaultArgs: str, optional _metadata: ns1.AppMetadataType_Def",
"soapaction=\"http://nbcr.sdsc.edu/opal/getAppMetadata\", **kw) response = self.binding.Receive(getAppMetadataResponseWrapper()) if not isinstance(response, getAppMetadataResponse) and\\",
"_separator: str, optional _untaggedParams: ns1.ParamsArrayType_Def, optional _usage: str _parallel: boolean",
"ns1.queryStatusInput_Dec() def __init__(self, name=None, ns=None): ns1.queryStatusInput_Dec.__init__(self, name=None, ns=None) class queryStatusRequestWrapper(queryStatusRequest):",
"kw = {} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/launchJob\", **kw)",
"client import ZSI class AppServiceInterface: def getAppServicePortType(self, portAddress=None, **kw): raise",
"self, name=None, ns=None ) class queryStatusResponse(ns1.queryStatusOutput_Dec): if not hasattr( ns1.queryStatusOutput_Dec(),",
"NonImplementationError(\"method not implemented\") class AppServiceLocator(AppServiceInterface): AppServicePortType_address = \"https://rocks-106.sdsc.edu:8443/axis/services/AutogridServicePort\" def getAppServicePortTypeAddress(self):",
"name=None, ns=None) class getOutputAsBase64ByNameRequestWrapper(getOutputAsBase64ByNameRequest): \"\"\"wrapper for document:literal message\"\"\" typecode =",
"not hasattr( ns1.queryStatusOutput_Dec(), \"typecode\" ): typecode = ns1.queryStatusOutput_Dec() def __init__(self,",
"name=None, ns=None): ns1.launchJobBlockingInput_Dec.__init__(self, name=None, ns=None) class launchJobBlockingRequestWrapper(launchJobBlockingRequest): \"\"\"wrapper for document:literal",
"response from launchJobResponse:: _launchJobOutput: ns1.JobSubOutputType_Def _jobID: str _status: ns1.StatusOutputType_Def _baseURL:",
"isinstance(request, getAppConfigRequest) and\\ not issubclass(getAppConfigRequest, request.__class__): raise TypeError(\"%s incorrect request",
"request type\" %(request.__class__)) kw = {'requestclass': queryStatusRequestWrapper} response = self.binding.Send(None,",
"isinstance(response, getAppConfigResponse) and\\ not issubclass(getAppConfigResponse, response.__class__): raise TypeError(\"%s incorrect response",
"@param: request is str @return: response from queryStatusResponse:: _queryStatusOutput: ns1.StatusOutputType_Def",
"ns1.IOType_Def, optional _paramType: ns1.ParamType_Def _ParamType: str, optional _required: boolean, optional",
"_name: str, optional _required: boolean, optional _semanticType: str, optional _textDesc:",
"_launchJobInput: ns1.JobInputType_Def _argList: str, optional _inputFile: ns1.InputFileType_Def, optional _contents: str",
"soapaction=\"http://nbcr.sdsc.edu/opal/getOutputAsBase64ByName\", **kw) response = self.binding.Receive(getOutputAsBase64ByNameResponseWrapper()) if not isinstance(response, getOutputAsBase64ByNameResponse) and\\",
"ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): getOutputsRequest.__init__(",
"@param: request is str @return: response from destroyResponse:: _destroyOutput: ns1.StatusOutputType_Def",
"if not hasattr( ns1.getOutputAsBase64ByNameOutput_Dec(), \"typecode\" ): typecode = ns1.getOutputAsBase64ByNameOutput_Dec() def",
"optional _id: str _ioType: ns1.IOType_Def _IOType: str, optional _max: int,",
"response = self.binding.Receive(getAppMetadataResponseWrapper()) if not isinstance(response, getAppMetadataResponse) and\\ not issubclass(getAppMetadataResponse,",
"queryStatusRequestWrapper} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/queryStatus\", **kw) response =",
"issubclass(destroyResponse, response.__class__): raise TypeError(\"%s incorrect response type\" %(response.__class__)) return response",
"getAppMetadataRequest) and\\ not issubclass(getAppMetadataRequest, request.__class__): raise TypeError(\"%s incorrect request type\"",
"%(request.__class__)) kw = {} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/launchJob\",",
".AppService_services_types import \\ nbcr_sdsc_edu_opal_types as ns1 import urllib.parse, types from",
"for document:literal message\"\"\" typecode = getOutputAsBase64ByNameRequest( name=None, ns=None ).typecode def",
"if \"port\" not in kw: kw[\"port\"] = int(netloc[1]) if \"url\"",
"destroy(self, request): \"\"\" @param: request is str @return: response from",
"from ZSI.TCcompound import Struct from ZSI import client import ZSI",
"_jobID: str _status: ns1.StatusOutputType_Def _baseURL: str _code: int _message: str",
"request type\" %(request.__class__)) kw = {} response = self.binding.Send(None, None,",
"ns1.queryStatusOutput_Dec(), \"typecode\" ): typecode = ns1.queryStatusOutput_Dec() def __init__(self, name=None, ns=None):",
"getAppMetadataResponseWrapper(getAppMetadataResponse): \"\"\"wrapper for document:literal message\"\"\" typecode = getAppMetadataResponse( name=None, ns=None",
"type\" %(response.__class__)) return response def getAppMetadata(self, request): \"\"\" @param: request",
") class launchJobBlockingRequest(ns1.launchJobBlockingInput_Dec): if not hasattr( ns1.launchJobBlockingInput_Dec(), \"typecode\" ): typecode",
"): typecode = ns1.launchJobBlockingInput_Dec() def __init__(self, name=None, ns=None): ns1.launchJobBlockingInput_Dec.__init__(self, name=None,",
"\"typecode\" ): typecode = ns1.getOutputsOutput_Dec() def __init__(self, name=None, ns=None): ns1.getOutputsOutput_Dec.__init__(self,",
"response def getAppMetadata(self, request): \"\"\" @param: request to getAppMetadataRequest @return:",
"class getAppMetadataRequestWrapper(getAppMetadataRequest): \"\"\"wrapper for document:literal message\"\"\" typecode = getAppMetadataRequest( name=None,",
"raise TypeError(\"%s incorrect response type\" %(response.__class__)) return response def launchJob(self,",
"**kw): raise NonImplementationError(\"method not implemented\") class AppServiceLocator(AppServiceInterface): AppServicePortType_address = \"https://rocks-106.sdsc.edu:8443/axis/services/AutogridServicePort\"",
"not isinstance(response, getOutputsResponse) and\\ not issubclass(getOutputsResponse, response.__class__): raise TypeError(\"%s incorrect",
"getOutputsRequestWrapper(getOutputsRequest): \"\"\"wrapper for document:literal message\"\"\" typecode = getOutputsRequest( name=None, ns=None",
"getAppMetadataRequestWrapper(getAppMetadataRequest): \"\"\"wrapper for document:literal message\"\"\" typecode = getAppMetadataRequest( name=None, ns=None",
"issubclass(getAppConfigRequest, request.__class__): raise TypeError(\"%s incorrect request type\" %(request.__class__)) kw =",
"# ################################################## from .AppService_services_types import * from .AppService_services_types import \\",
"document:literal message\"\"\" typecode = getOutputsRequest( name=None, ns=None ).typecode def __init__(",
"ns=None ) class getAppMetadataRequest: def __init__(self, name=None, ns=None): getAppMetadataRequest.typecode =",
"<reponame>e-mayo/mscreen ################################################## # ./AppService_services.py # generated by ZSI.wsdl2python # #",
"ZSI class AppServiceInterface: def getAppServicePortType(self, portAddress=None, **kw): raise NonImplementationError(\"method not",
"self, name=None, ns=None ) class getAppMetadataResponse(ns1.getAppMetadataOutput_Dec): if not hasattr( ns1.getAppMetadataOutput_Dec(),",
"name ) class getAppConfigRequestWrapper(getAppConfigRequest): \"\"\"wrapper for document:literal message\"\"\" typecode =",
"**kw): return AppServicePortSoapBindingSOAP(portAddress or AppServiceLocator.AppServicePortType_address, **kw) class AppServicePortSoapBindingSOAP: def __init__(self,",
"_code: int _message: str \"\"\" if not isinstance(request, launchJobRequest) and\\",
"not isinstance(response, launchJobBlockingResponse) and\\ not issubclass(launchJobBlockingResponse, response.__class__): raise TypeError(\"%s incorrect",
"optional _flags: ns1.FlagsArrayType_Def, optional _flag: ns1.FlagsType_Def, optional _id: str _tag:",
"ns=None ) class launchJobBlockingRequest(ns1.launchJobBlockingInput_Dec): if not hasattr( ns1.launchJobBlockingInput_Dec(), \"typecode\" ):",
"_untaggedParams: ns1.ParamsArrayType_Def, optional _usage: str _parallel: boolean \"\"\" if not",
"__init__(self, name=None, ns=None): getAppMetadataRequest.typecode = Struct(getAppMetadataRequest,[], pname=name, aname=\"%s\" % name,",
"= {} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getAppMetadata\", **kw) response",
"@param: request to launchJobBlockingRequest:: _launchJobBlockingInput: ns1.JobInputType_Def _argList: str, optional _inputFile:",
"isinstance(response, launchJobBlockingResponse) and\\ not issubclass(launchJobBlockingResponse, response.__class__): raise TypeError(\"%s incorrect response",
"not isinstance(request, getAppMetadataRequest) and\\ not issubclass(getAppMetadataRequest, request.__class__): raise TypeError(\"%s incorrect",
"\"host\" not in kw: kw[\"host\"] = netloc[0] if \"port\" not",
"TypeError(\"%s incorrect response type\" %(response.__class__)) return response def launchJobBlocking(self, request):",
"str _url: str _stdErr: str, optional _stdOut: str, optional _status:",
"str): raise TypeError(\"%s incorrect request type\" %(request.__class__)) kw = {'requestclass':",
"_min: int, optional _name: str, optional _required: boolean, optional _semanticType:",
"launchJobRequest.__init__( self, name=None, ns=None ) class launchJobResponse(ns1.launchJobOutput_Dec): if not hasattr(",
"import client import ZSI class AppServiceInterface: def getAppServicePortType(self, portAddress=None, **kw):",
"\"typecode\" ): typecode = ns1.getAppConfigOutput_Dec() def __init__(self, name=None, ns=None): ns1.getAppConfigOutput_Dec.__init__(self,",
"@param: request to getAppMetadataRequest @return: response from getAppMetadataResponse:: _getAppMetadataOutput: ns1.AppMetadataType_Def",
"= launchJobResponse( name=None, ns=None ).typecode def __init__( self, name=None, ns=None,",
"typecode = ns1.launchJobBlockingInput_Dec() def __init__(self, name=None, ns=None): ns1.launchJobBlockingInput_Dec.__init__(self, name=None, ns=None)",
"queryStatus(self, request): \"\"\" @param: request is str @return: response from",
"and\\ not issubclass(getOutputAsBase64ByNameRequest, request.__class__): raise TypeError(\"%s incorrect request type\" %(request.__class__))",
"\"\"\"wrapper for document:literal message\"\"\" typecode = destroyRequest( name=None, ns=None ).typecode",
"self, name=None, ns=None ) class launchJobRequest(ns1.launchJobInput_Dec): if not hasattr( ns1.launchJobInput_Dec(),",
"_required: boolean, optional _semanticType: str, optional _textDesc: str, optional _taggedParams:",
"_outputFile: ns1.OutputFileType_Def, optional _name: str _url: str _stdErr: str, optional",
"isinstance(request, launchJobBlockingRequest) and\\ not issubclass(launchJobBlockingRequest, request.__class__): raise TypeError(\"%s incorrect request",
"class launchJobBlockingRequestWrapper(launchJobBlockingRequest): \"\"\"wrapper for document:literal message\"\"\" typecode = launchJobBlockingRequest( name=None,",
"not issubclass(destroyResponse, response.__class__): raise TypeError(\"%s incorrect response type\" %(response.__class__)) return",
"boolean, optional _semanticType: str, optional _tag: str, optional _textDesc: str,",
"self.binding.Receive(launchJobResponseWrapper()) if not isinstance(response, launchJobResponse) and\\ not issubclass(launchJobResponse, response.__class__): raise",
"launchJobBlockingRequest.__init__( self, name=None, ns=None ) class launchJobBlockingResponse(ns1.launchJobBlockingOutput_Dec): if not hasattr(",
"raise TypeError(\"%s incorrect response type\" %(response.__class__)) return response def getOutputAsBase64ByName(self,",
") class getOutputsResponse(ns1.getOutputsOutput_Dec): if not hasattr( ns1.getOutputsOutput_Dec(), \"typecode\" ): typecode",
"_untaggedParams: ns1.ParamsArrayType_Def, optional _usage: str \"\"\" if not isinstance(request, getAppMetadataRequest)",
"__init__(self, name=None, ns=None): ns1.getOutputsInput_Dec.__init__(self, name=None, ns=None) class getOutputsRequestWrapper(getOutputsRequest): \"\"\"wrapper for",
"response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/destroy\", **kw) response = self.binding.Receive(destroyResponseWrapper())",
"_numProcs: int, optional @return: response from launchJobResponse:: _launchJobOutput: ns1.JobSubOutputType_Def _jobID:",
"class destroyResponse(ns1.destroyOutput_Dec): if not hasattr( ns1.destroyOutput_Dec(), \"typecode\" ): typecode =",
"ns=None, **kw ): getOutputsResponse.__init__( self, name=None, ns=None ) class launchJobBlockingRequest(ns1.launchJobBlockingInput_Dec):",
"getAppMetadataRequest.typecode = Struct(getAppMetadataRequest,[], pname=name, aname=\"%s\" % name, oname=\"%s xmlns=\\\"\\\"\" %",
"optional _separator: str, optional _untaggedParams: ns1.ParamsArrayType_Def, optional _usage: str _parallel:",
"_destroyOutput: ns1.StatusOutputType_Def _baseURL: str _code: int _message: str \"\"\" if",
"def __init__(self, name=None, ns=None): ns1.getOutputAsBase64ByNameOutput_Dec.__init__(self, name=None, ns=None) class getOutputAsBase64ByNameResponseWrapper(getOutputAsBase64ByNameResponse): \"\"\"wrapper",
"getAppMetadataResponse:: _getAppMetadataOutput: ns1.AppMetadataType_Def _info: str, optional _types: ns1.ArgumentsType_Def, optional _flags:",
"\"url\" not in kw: kw[\"url\"] = urllib.parse.urlparse(addr)[2] self.binding = client.Binding(**kw)",
"**kw) response = self.binding.Receive(queryStatusResponseWrapper()) if not isinstance(response, queryStatusResponse) and\\ not",
"if not hasattr( ns1.queryStatusInput_Dec(), \"typecode\" ): typecode = ns1.queryStatusInput_Dec() def",
"ns1.AppConfigType_Def _binaryLocation: str _defaultArgs: str, optional _metadata: ns1.AppMetadataType_Def _info: str,",
"getOutputsResponseWrapper(getOutputsResponse): \"\"\"wrapper for document:literal message\"\"\" typecode = getOutputsResponse( name=None, ns=None",
"**kw) response = self.binding.Receive(getAppConfigResponseWrapper()) if not isinstance(response, getAppConfigResponse) and\\ not",
"not issubclass(getOutputAsBase64ByNameResponse, response.__class__): raise TypeError(\"%s incorrect response type\" %(response.__class__)) return",
"class getAppConfigRequestWrapper(getAppConfigRequest): \"\"\"wrapper for document:literal message\"\"\" typecode = getAppConfigRequest( name=None,",
"ns1.getOutputAsBase64ByNameInput_Dec(), \"typecode\" ): typecode = ns1.getOutputAsBase64ByNameInput_Dec() def __init__(self, name=None, ns=None):",
"ns1.destroyOutput_Dec.__init__(self, name=None, ns=None) class destroyResponseWrapper(destroyResponse): \"\"\"wrapper for document:literal message\"\"\" typecode",
"urllib.parse, types from ZSI.TCcompound import Struct from ZSI import client",
"typecode = ns1.getOutputAsBase64ByNameInput_Dec() def __init__(self, name=None, ns=None): ns1.getOutputAsBase64ByNameInput_Dec.__init__(self, name=None, ns=None)",
"optional _id: str _ioType: ns1.IOType_Def, optional _paramType: ns1.ParamType_Def _ParamType: str,",
"= destroyRequest( name=None, ns=None ).typecode def __init__( self, name=None, ns=None,",
"isinstance(response, getOutputsResponse) and\\ not issubclass(getOutputsResponse, response.__class__): raise TypeError(\"%s incorrect response",
"str _ioType: ns1.IOType_Def, optional _paramType: ns1.ParamType_Def _ParamType: str, optional _required:",
"str, optional _types: ns1.ArgumentsType_Def, optional _flags: ns1.FlagsArrayType_Def, optional _flag: ns1.FlagsType_Def,",
"str, optional _inputFile: ns1.InputFileType_Def, optional _contents: str _name: str _numProcs:",
"response = self.binding.Receive(getOutputsResponseWrapper()) if not isinstance(response, getOutputsResponse) and\\ not issubclass(getOutputsResponse,",
"= self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getAppMetadata\", **kw) response = self.binding.Receive(getAppMetadataResponseWrapper()) if",
"): launchJobResponse.__init__( self, name=None, ns=None ) class queryStatusRequest(ns1.queryStatusInput_Dec): if not",
"if not hasattr( ns1.launchJobInput_Dec(), \"typecode\" ): typecode = ns1.launchJobInput_Dec() def",
").typecode def __init__( self, name=None, ns=None, **kw ): launchJobBlockingRequest.__init__( self,",
"issubclass(launchJobBlockingResponse, response.__class__): raise TypeError(\"%s incorrect response type\" %(response.__class__)) return response",
"launchJobRequest) and\\ not issubclass(launchJobRequest, request.__class__): raise TypeError(\"%s incorrect request type\"",
"ns=None) class destroyResponseWrapper(destroyResponse): \"\"\"wrapper for document:literal message\"\"\" typecode = destroyResponse(",
"str _defaultArgs: str, optional _metadata: ns1.AppMetadataType_Def _info: str, optional _types:",
"): getAppConfigRequest.__init__( self, name=None, ns=None ) class getAppConfigResponse(ns1.getAppConfigOutput_Dec): if not",
"typecode = getAppMetadataRequest( name=None, ns=None ).typecode def __init__( self, name=None,",
"def __init__(self, name=None, ns=None): ns1.getAppConfigOutput_Dec.__init__(self, name=None, ns=None) class getAppConfigResponseWrapper(getAppConfigResponse): \"\"\"wrapper",
"isinstance(response, getOutputAsBase64ByNameResponse) and\\ not issubclass(getOutputAsBase64ByNameResponse, response.__class__): raise TypeError(\"%s incorrect response",
"**kw) response = self.binding.Receive(getAppMetadataResponseWrapper()) if not isinstance(response, getAppMetadataResponse) and\\ not",
"if not hasattr( ns1.getAppMetadataOutput_Dec(), \"typecode\" ): typecode = ns1.getAppMetadataOutput_Dec() def",
"= Struct(getAppMetadataRequest,[], pname=name, aname=\"%s\" % name, oname=\"%s xmlns=\\\"\\\"\" % name",
"issubclass(getAppConfigResponse, response.__class__): raise TypeError(\"%s incorrect response type\" %(response.__class__)) return response",
"raise TypeError(\"%s incorrect response type\" %(response.__class__)) return response def queryStatus(self,",
"not hasattr( ns1.destroyInput_Dec(), \"typecode\" ): typecode = ns1.destroyInput_Dec() def __init__(self,",
"optional _extension: str, optional _id: str _ioType: ns1.IOType_Def _IOType: str,",
"str, optional _implicitParams: ns1.ImplicitParamsArrayType_Def, optional _param: ns1.ImplicitParamsType_Def, optional _extension: str,",
"**kw) class AppServicePortSoapBindingSOAP: def __init__(self, addr, **kw): netloc = (urllib.parse.urlparse(addr)[1]).split(\":\")",
"kw = {'requestclass': getOutputsRequestWrapper} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getOutputs\",",
"soapaction=\"http://nbcr.sdsc.edu/opal/getAppConfig\", **kw) response = self.binding.Receive(getAppConfigResponseWrapper()) if not isinstance(response, getAppConfigResponse) and\\",
"_jobID: str @return: response from getOutputAsBase64ByNameResponse:: _item: str, optional \"\"\"",
"def __init__(self, name=None, ns=None): ns1.destroyInput_Dec.__init__(self, name=None, ns=None) class destroyRequestWrapper(destroyRequest): \"\"\"wrapper",
"TypeError(\"%s incorrect response type\" %(response.__class__)) return response class destroyRequest(ns1.destroyInput_Dec): if",
"not issubclass(getAppConfigRequest, request.__class__): raise TypeError(\"%s incorrect request type\" %(request.__class__)) kw",
"ns=None ) class getOutputAsBase64ByNameRequest(ns1.getOutputAsBase64ByNameInput_Dec): if not hasattr( ns1.getOutputAsBase64ByNameInput_Dec(), \"typecode\" ):",
"): typecode = ns1.queryStatusInput_Dec() def __init__(self, name=None, ns=None): ns1.queryStatusInput_Dec.__init__(self, name=None,",
"def getAppConfig(self, request): \"\"\" @param: request to getAppConfigRequest @return: response",
"__init__( self, name=None, ns=None, **kw ): getAppConfigRequest.__init__( self, name=None, ns=None",
"ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): launchJobBlockingRequest.__init__(",
"ns=None, **kw ): launchJobResponse.__init__( self, name=None, ns=None ) class queryStatusRequest(ns1.queryStatusInput_Dec):",
"**kw) response = self.binding.Receive(getOutputAsBase64ByNameResponseWrapper()) if not isinstance(response, getOutputAsBase64ByNameResponse) and\\ not",
"def __init__(self, name=None, ns=None): ns1.queryStatusInput_Dec.__init__(self, name=None, ns=None) class queryStatusRequestWrapper(queryStatusRequest): \"\"\"wrapper",
"def getAppServicePortType(self, portAddress=None, **kw): raise NonImplementationError(\"method not implemented\") class AppServiceLocator(AppServiceInterface):",
"{} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/launchJobBlocking\", **kw) response =",
"response.__class__): raise TypeError(\"%s incorrect response type\" %(response.__class__)) return response class",
"): destroyRequest.__init__( self, name=None, ns=None ) class destroyResponse(ns1.destroyOutput_Dec): if not",
"request type\" %(request.__class__)) kw = {'requestclass': destroyRequestWrapper} response = self.binding.Send(None,",
"name=None, ns=None): ns1.destroyInput_Dec.__init__(self, name=None, ns=None) class destroyRequestWrapper(destroyRequest): \"\"\"wrapper for document:literal",
"__init__( self, name=None, ns=None, **kw ): getAppConfigResponse.__init__( self, name=None, ns=None",
"None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getAppMetadata\", **kw) response = self.binding.Receive(getAppMetadataResponseWrapper()) if not isinstance(response,",
"getAppConfigResponse.__init__( self, name=None, ns=None ) class getAppMetadataRequest: def __init__(self, name=None,",
"raise TypeError(\"%s incorrect response type\" %(response.__class__)) return response def getOutputs(self,",
"ns1.StatusOutputType_Def _baseURL: str _code: int _message: str \"\"\" if not",
"self, name=None, ns=None, **kw ): getOutputsResponse.__init__( self, name=None, ns=None )",
"soapaction=\"http://nbcr.sdsc.edu/opal/destroy\", **kw) response = self.binding.Receive(destroyResponseWrapper()) if not isinstance(response, destroyResponse) and\\",
"ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): getOutputAsBase64ByNameRequest.__init__(",
"kw = {} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/launchJobBlocking\", **kw)",
"name=None, ns=None, **kw ): destroyRequest.__init__( self, name=None, ns=None ) class",
"from launchJobResponse:: _launchJobOutput: ns1.JobSubOutputType_Def _jobID: str _status: ns1.StatusOutputType_Def _baseURL: str",
"response class destroyRequest(ns1.destroyInput_Dec): if not hasattr( ns1.destroyInput_Dec(), \"typecode\" ): typecode",
"from ZSI import client import ZSI class AppServiceInterface: def getAppServicePortType(self,",
"**kw ): getOutputAsBase64ByNameResponse.__init__( self, name=None, ns=None ) class getOutputsRequest(ns1.getOutputsInput_Dec): if",
"str _tag: str _textDesc: str, optional _implicitParams: ns1.ImplicitParamsArrayType_Def, optional _param:",
"from getAppMetadataResponse:: _getAppMetadataOutput: ns1.AppMetadataType_Def _info: str, optional _types: ns1.ArgumentsType_Def, optional",
"str _stdErr: str, optional _stdOut: str, optional \"\"\" if not",
"hasattr( ns1.getOutputAsBase64ByNameOutput_Dec(), \"typecode\" ): typecode = ns1.getOutputAsBase64ByNameOutput_Dec() def __init__(self, name=None,",
"request type\" %(request.__class__)) kw = {'requestclass': getOutputsRequestWrapper} response = self.binding.Send(None,",
"response = self.binding.Receive(getAppConfigResponseWrapper()) if not isinstance(response, getAppConfigResponse) and\\ not issubclass(getAppConfigResponse,",
"ns1.destroyOutput_Dec(), \"typecode\" ): typecode = ns1.destroyOutput_Dec() def __init__(self, name=None, ns=None):",
"document:literal message\"\"\" typecode = getAppMetadataRequest( name=None, ns=None ).typecode def __init__(",
"kw[\"host\"] = netloc[0] if \"port\" not in kw: kw[\"port\"] =",
"str, optional _required: boolean, optional _semanticType: str, optional _tag: str,",
"= self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/queryStatus\", **kw) response = self.binding.Receive(queryStatusResponseWrapper()) if",
"ns1.JobSubOutputType_Def _jobID: str _status: ns1.StatusOutputType_Def _baseURL: str _code: int _message:",
"= self.binding.Receive(getAppMetadataResponseWrapper()) if not isinstance(response, getAppMetadataResponse) and\\ not issubclass(getAppMetadataResponse, response.__class__):",
"response type\" %(response.__class__)) return response def launchJobBlocking(self, request): \"\"\" @param:",
"self, name=None, ns=None, **kw ): getOutputAsBase64ByNameRequest.__init__( self, name=None, ns=None )",
"request to getAppMetadataRequest @return: response from getAppMetadataResponse:: _getAppMetadataOutput: ns1.AppMetadataType_Def _info:",
"getAppMetadataResponse) and\\ not issubclass(getAppMetadataResponse, response.__class__): raise TypeError(\"%s incorrect response type\"",
"launchJobBlockingRequest(ns1.launchJobBlockingInput_Dec): if not hasattr( ns1.launchJobBlockingInput_Dec(), \"typecode\" ): typecode = ns1.launchJobBlockingInput_Dec()",
"typecode = ns1.destroyInput_Dec() def __init__(self, name=None, ns=None): ns1.destroyInput_Dec.__init__(self, name=None, ns=None)",
"queryStatusRequest(ns1.queryStatusInput_Dec): if not hasattr( ns1.queryStatusInput_Dec(), \"typecode\" ): typecode = ns1.queryStatusInput_Dec()",
"ns=None) class getOutputAsBase64ByNameRequestWrapper(getOutputAsBase64ByNameRequest): \"\"\"wrapper for document:literal message\"\"\" typecode = getOutputAsBase64ByNameRequest(",
"%(request.__class__)) kw = {} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getAppMetadata\",",
"from getAppConfigResponse:: _getAppConfigOutput: ns1.AppConfigType_Def _binaryLocation: str _defaultArgs: str, optional _metadata:",
"%(response.__class__)) return response def getOutputAsBase64ByName(self, request): \"\"\" @param: request to",
"self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getOutputAsBase64ByName\", **kw) response = self.binding.Receive(getOutputAsBase64ByNameResponseWrapper()) if not",
"**kw ): getAppConfigRequest.__init__( self, name=None, ns=None ) class getAppConfigResponse(ns1.getAppConfigOutput_Dec): if",
"**kw) response = self.binding.Receive(destroyResponseWrapper()) if not isinstance(response, destroyResponse) and\\ not",
"response from getOutputAsBase64ByNameResponse:: _item: str, optional \"\"\" if not isinstance(request,",
"incorrect response type\" %(response.__class__)) return response class destroyRequest(ns1.destroyInput_Dec): if not",
"ns=None): ns1.launchJobOutput_Dec.__init__(self, name=None, ns=None) class launchJobResponseWrapper(launchJobResponse): \"\"\"wrapper for document:literal message\"\"\"",
"nbcr_sdsc_edu_opal_types as ns1 import urllib.parse, types from ZSI.TCcompound import Struct",
"ns1.destroyInput_Dec.__init__(self, name=None, ns=None) class destroyRequestWrapper(destroyRequest): \"\"\"wrapper for document:literal message\"\"\" typecode",
"def __init__( self, name=None, ns=None, **kw ): queryStatusResponse.__init__( self, name=None,",
"from launchJobBlockingResponse:: _launchJobBlockingOutput: ns1.BlockingOutputType_Def _jobOut: ns1.JobOutputType_Def _outputFile: ns1.OutputFileType_Def, optional _name:",
"AppServicePortSoapBindingSOAP(portAddress or AppServiceLocator.AppServicePortType_address, **kw) class AppServicePortSoapBindingSOAP: def __init__(self, addr, **kw):",
"_baseURL: str _code: int _message: str \"\"\" if not isinstance(request,",
"@param: request to launchJobRequest:: _launchJobInput: ns1.JobInputType_Def _argList: str, optional _inputFile:",
"_separator: str, optional _untaggedParams: ns1.ParamsArrayType_Def, optional _usage: str \"\"\" if",
"ns1.getAppConfigOutput_Dec() def __init__(self, name=None, ns=None): ns1.getAppConfigOutput_Dec.__init__(self, name=None, ns=None) class getAppConfigResponseWrapper(getAppConfigResponse):",
"_param: ns1.ParamsType_Def, optional _id: str _ioType: ns1.IOType_Def, optional _paramType: ns1.ParamType_Def",
"name=None, ns=None): ns1.getOutputsInput_Dec.__init__(self, name=None, ns=None) class getOutputsRequestWrapper(getOutputsRequest): \"\"\"wrapper for document:literal",
"not hasattr( ns1.launchJobOutput_Dec(), \"typecode\" ): typecode = ns1.launchJobOutput_Dec() def __init__(self,",
"TypeError(\"%s incorrect response type\" %(response.__class__)) return response def getOutputAsBase64ByName(self, request):",
"class getAppMetadataResponse(ns1.getAppMetadataOutput_Dec): if not hasattr( ns1.getAppMetadataOutput_Dec(), \"typecode\" ): typecode =",
"class destroyResponseWrapper(destroyResponse): \"\"\"wrapper for document:literal message\"\"\" typecode = destroyResponse( name=None,",
"str, optional \"\"\" if not isinstance(request, getOutputAsBase64ByNameRequest) and\\ not issubclass(getOutputAsBase64ByNameRequest,",
"launchJobBlockingResponse:: _launchJobBlockingOutput: ns1.BlockingOutputType_Def _jobOut: ns1.JobOutputType_Def _outputFile: ns1.OutputFileType_Def, optional _name: str",
"incorrect request type\" %(request.__class__)) kw = {'requestclass': queryStatusRequestWrapper} response =",
"isinstance(response, destroyResponse) and\\ not issubclass(destroyResponse, response.__class__): raise TypeError(\"%s incorrect response",
"import Struct from ZSI import client import ZSI class AppServiceInterface:",
"name=None, ns=None ) class queryStatusResponse(ns1.queryStatusOutput_Dec): if not hasattr( ns1.queryStatusOutput_Dec(), \"typecode\"",
"str \"\"\" if not isinstance(request, launchJobBlockingRequest) and\\ not issubclass(launchJobBlockingRequest, request.__class__):",
"ns=None): ns1.destroyOutput_Dec.__init__(self, name=None, ns=None) class destroyResponseWrapper(destroyResponse): \"\"\"wrapper for document:literal message\"\"\"",
"_implicitParams: ns1.ImplicitParamsArrayType_Def, optional _param: ns1.ImplicitParamsType_Def, optional _extension: str, optional _id:",
"response = self.binding.Receive(launchJobResponseWrapper()) if not isinstance(response, launchJobResponse) and\\ not issubclass(launchJobResponse,",
"= self.binding.Receive(launchJobResponseWrapper()) if not isinstance(response, launchJobResponse) and\\ not issubclass(launchJobResponse, response.__class__):",
"name=None, ns=None, **kw ): getOutputAsBase64ByNameRequest.__init__( self, name=None, ns=None ) class",
"launchJobRequestWrapper(launchJobRequest): \"\"\"wrapper for document:literal message\"\"\" typecode = launchJobRequest( name=None, ns=None",
"ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): getAppConfigRequest.__init__(",
"\"\"\" @param: request to launchJobRequest:: _launchJobInput: ns1.JobInputType_Def _argList: str, optional",
"= self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getOutputAsBase64ByName\", **kw) response = self.binding.Receive(getOutputAsBase64ByNameResponseWrapper()) if",
"_id: str _ioType: ns1.IOType_Def _IOType: str, optional _max: int, optional",
"ns1 import urllib.parse, types from ZSI.TCcompound import Struct from ZSI",
"destroyResponse:: _destroyOutput: ns1.StatusOutputType_Def _baseURL: str _code: int _message: str \"\"\"",
"self, name=None, ns=None, **kw ): destroyRequest.__init__( self, name=None, ns=None )",
"response def queryStatus(self, request): \"\"\" @param: request is str @return:",
"response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/launchJobBlocking\", **kw) response = self.binding.Receive(launchJobBlockingResponseWrapper())",
"\"typecode\" ): typecode = ns1.getOutputsInput_Dec() def __init__(self, name=None, ns=None): ns1.getOutputsInput_Dec.__init__(self,",
"str, optional _status: ns1.StatusOutputType_Def _baseURL: str _code: int _message: str",
"= urllib.parse.urlparse(addr)[2] self.binding = client.Binding(**kw) def destroy(self, request): \"\"\" @param:",
"request, soapaction=\"http://nbcr.sdsc.edu/opal/getAppMetadata\", **kw) response = self.binding.Receive(getAppMetadataResponseWrapper()) if not isinstance(response, getAppMetadataResponse)",
"from getOutputsResponse:: _getOutputsOutput: ns1.JobOutputType_Def _outputFile: ns1.OutputFileType_Def, optional _name: str _url:",
"name, oname=\"%s xmlns=\\\"\\\"\" % name ) class getAppMetadataRequestWrapper(getAppMetadataRequest): \"\"\"wrapper for",
"getOutputAsBase64ByNameRequest) and\\ not issubclass(getOutputAsBase64ByNameRequest, request.__class__): raise TypeError(\"%s incorrect request type\"",
"response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/queryStatus\", **kw) response = self.binding.Receive(queryStatusResponseWrapper())",
"def __init__( self, name=None, ns=None, **kw ): getOutputsRequest.__init__( self, name=None,",
"soapaction=\"http://nbcr.sdsc.edu/opal/launchJobBlocking\", **kw) response = self.binding.Receive(launchJobBlockingResponseWrapper()) if not isinstance(response, launchJobBlockingResponse) and\\",
"type\" %(request.__class__)) kw = {'requestclass': getOutputsRequestWrapper} response = self.binding.Send(None, None,",
"name=None, ns=None): ns1.launchJobOutput_Dec.__init__(self, name=None, ns=None) class launchJobResponseWrapper(launchJobResponse): \"\"\"wrapper for document:literal",
"optional _stdOut: str, optional _status: ns1.StatusOutputType_Def _baseURL: str _code: int",
"= launchJobRequest( name=None, ns=None ).typecode def __init__( self, name=None, ns=None,",
"getOutputAsBase64ByNameRequest:: _getOutputAsBase64ByNameInput: ns1.OutputsByNameInputType_Def _fileName: str _jobID: str @return: response from",
"): typecode = ns1.destroyInput_Dec() def __init__(self, name=None, ns=None): ns1.destroyInput_Dec.__init__(self, name=None,",
"ns1.getAppMetadataOutput_Dec() def __init__(self, name=None, ns=None): ns1.getAppMetadataOutput_Dec.__init__(self, name=None, ns=None) class getAppMetadataResponseWrapper(getAppMetadataResponse):",
"response from destroyResponse:: _destroyOutput: ns1.StatusOutputType_Def _baseURL: str _code: int _message:",
").typecode def __init__( self, name=None, ns=None, **kw ): queryStatusRequest.__init__( self,",
"return response class destroyRequest(ns1.destroyInput_Dec): if not hasattr( ns1.destroyInput_Dec(), \"typecode\" ):",
"TypeError(\"%s incorrect response type\" %(response.__class__)) return response def queryStatus(self, request):",
"None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getAppConfig\", **kw) response = self.binding.Receive(getAppConfigResponseWrapper()) if not isinstance(response,",
"soapaction=\"http://nbcr.sdsc.edu/opal/launchJob\", **kw) response = self.binding.Receive(launchJobResponseWrapper()) if not isinstance(response, launchJobResponse) and\\",
"launchJob(self, request): \"\"\" @param: request to launchJobRequest:: _launchJobInput: ns1.JobInputType_Def _argList:",
"**kw ): getAppConfigResponse.__init__( self, name=None, ns=None ) class getAppMetadataRequest: def",
"def __init__(self, name=None, ns=None): ns1.getOutputsInput_Dec.__init__(self, name=None, ns=None) class getOutputsRequestWrapper(getOutputsRequest): \"\"\"wrapper",
"type\" %(response.__class__)) return response def getOutputAsBase64ByName(self, request): \"\"\" @param: request",
"name=None, ns=None ) class getAppMetadataRequest: def __init__(self, name=None, ns=None): getAppMetadataRequest.typecode",
"= ns1.getAppMetadataOutput_Dec() def __init__(self, name=None, ns=None): ns1.getAppMetadataOutput_Dec.__init__(self, name=None, ns=None) class",
"raise TypeError(\"%s incorrect request type\" %(request.__class__)) kw = {'requestclass': destroyRequestWrapper}",
"optional _required: boolean, optional _semanticType: str, optional _tag: str, optional",
"ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): destroyResponse.__init__(",
"self, name=None, ns=None ) class getOutputAsBase64ByNameResponse(ns1.getOutputAsBase64ByNameOutput_Dec): if not hasattr( ns1.getOutputAsBase64ByNameOutput_Dec(),",
"if \"host\" not in kw: kw[\"host\"] = netloc[0] if \"port\"",
"hasattr( ns1.getOutputAsBase64ByNameInput_Dec(), \"typecode\" ): typecode = ns1.getOutputAsBase64ByNameInput_Dec() def __init__(self, name=None,",
"\"\"\" if not isinstance(request, launchJobBlockingRequest) and\\ not issubclass(launchJobBlockingRequest, request.__class__): raise",
"@param: request is str @return: response from getOutputsResponse:: _getOutputsOutput: ns1.JobOutputType_Def",
"\"\"\" if not isinstance(request, getOutputAsBase64ByNameRequest) and\\ not issubclass(getOutputAsBase64ByNameRequest, request.__class__): raise",
"@return: response from getAppMetadataResponse:: _getAppMetadataOutput: ns1.AppMetadataType_Def _info: str, optional _types:",
"response type\" %(response.__class__)) return response def getOutputAsBase64ByName(self, request): \"\"\" @param:",
"%(response.__class__)) return response def launchJobBlocking(self, request): \"\"\" @param: request to",
"str @return: response from destroyResponse:: _destroyOutput: ns1.StatusOutputType_Def _baseURL: str _code:",
"= self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/launchJobBlocking\", **kw) response = self.binding.Receive(launchJobBlockingResponseWrapper()) if",
"ns1.JobInputType_Def _argList: str, optional _inputFile: ns1.InputFileType_Def, optional _contents: str _name:",
"ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): getOutputsResponse.__init__(",
"): typecode = ns1.getAppMetadataOutput_Dec() def __init__(self, name=None, ns=None): ns1.getAppMetadataOutput_Dec.__init__(self, name=None,",
"ns1.getOutputsOutput_Dec(), \"typecode\" ): typecode = ns1.getOutputsOutput_Dec() def __init__(self, name=None, ns=None):",
"not issubclass(getAppConfigResponse, response.__class__): raise TypeError(\"%s incorrect response type\" %(response.__class__)) return",
"launchJobResponse(ns1.launchJobOutput_Dec): if not hasattr( ns1.launchJobOutput_Dec(), \"typecode\" ): typecode = ns1.launchJobOutput_Dec()",
"optional _metadata: ns1.AppMetadataType_Def _info: str, optional _types: ns1.ArgumentsType_Def, optional _flags:",
"client.Binding(**kw) def destroy(self, request): \"\"\" @param: request is str @return:",
"if \"url\" not in kw: kw[\"url\"] = urllib.parse.urlparse(addr)[2] self.binding =",
"if not hasattr( ns1.queryStatusOutput_Dec(), \"typecode\" ): typecode = ns1.queryStatusOutput_Dec() def",
"soapaction=\"http://nbcr.sdsc.edu/opal/getOutputs\", **kw) response = self.binding.Receive(getOutputsResponseWrapper()) if not isinstance(response, getOutputsResponse) and\\",
"str, optional _textDesc: str, optional _value: str, optional _separator: str,",
"AppServicePortSoapBindingSOAP: def __init__(self, addr, **kw): netloc = (urllib.parse.urlparse(addr)[1]).split(\":\") + [80,]",
"str @return: response from queryStatusResponse:: _queryStatusOutput: ns1.StatusOutputType_Def _baseURL: str _code:",
"): typecode = ns1.destroyOutput_Dec() def __init__(self, name=None, ns=None): ns1.destroyOutput_Dec.__init__(self, name=None,",
"from .AppService_services_types import \\ nbcr_sdsc_edu_opal_types as ns1 import urllib.parse, types",
"ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): getAppMetadataResponse.__init__(",
"ns1.getOutputsOutput_Dec.__init__(self, name=None, ns=None) class getOutputsResponseWrapper(getOutputsResponse): \"\"\"wrapper for document:literal message\"\"\" typecode",
"): typecode = ns1.getOutputAsBase64ByNameInput_Dec() def __init__(self, name=None, ns=None): ns1.getOutputAsBase64ByNameInput_Dec.__init__(self, name=None,",
") class launchJobBlockingResponse(ns1.launchJobBlockingOutput_Dec): if not hasattr( ns1.launchJobBlockingOutput_Dec(), \"typecode\" ): typecode",
"__init__( self, name=None, ns=None, **kw ): queryStatusResponse.__init__( self, name=None, ns=None",
"\"\"\"wrapper for document:literal message\"\"\" typecode = launchJobBlockingRequest( name=None, ns=None ).typecode",
"class queryStatusRequestWrapper(queryStatusRequest): \"\"\"wrapper for document:literal message\"\"\" typecode = queryStatusRequest( name=None,",
"if not isinstance(request, getAppConfigRequest) and\\ not issubclass(getAppConfigRequest, request.__class__): raise TypeError(\"%s",
"message\"\"\" typecode = destroyRequest( name=None, ns=None ).typecode def __init__( self,",
"def __init__( self, name=None, ns=None, **kw ): getOutputAsBase64ByNameResponse.__init__( self, name=None,",
"ns1.getOutputAsBase64ByNameOutput_Dec() def __init__(self, name=None, ns=None): ns1.getOutputAsBase64ByNameOutput_Dec.__init__(self, name=None, ns=None) class getOutputAsBase64ByNameResponseWrapper(getOutputAsBase64ByNameResponse):",
"ns=None): ns1.launchJobInput_Dec.__init__(self, name=None, ns=None) class launchJobRequestWrapper(launchJobRequest): \"\"\"wrapper for document:literal message\"\"\"",
"str, optional _stdOut: str, optional _status: ns1.StatusOutputType_Def _baseURL: str _code:",
"name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw ):",
"%(request.__class__)) kw = {'requestclass': destroyRequestWrapper} response = self.binding.Send(None, None, request,",
"and\\ not issubclass(launchJobBlockingRequest, request.__class__): raise TypeError(\"%s incorrect request type\" %(request.__class__))",
"\\ nbcr_sdsc_edu_opal_types as ns1 import urllib.parse, types from ZSI.TCcompound import",
"ns=None ) class launchJobBlockingResponse(ns1.launchJobBlockingOutput_Dec): if not hasattr( ns1.launchJobBlockingOutput_Dec(), \"typecode\" ):",
"and\\ not issubclass(destroyResponse, response.__class__): raise TypeError(\"%s incorrect response type\" %(response.__class__))",
"ns1.launchJobBlockingOutput_Dec(), \"typecode\" ): typecode = ns1.launchJobBlockingOutput_Dec() def __init__(self, name=None, ns=None):",
"ns=None ) class destroyResponse(ns1.destroyOutput_Dec): if not hasattr( ns1.destroyOutput_Dec(), \"typecode\" ):",
"str _textDesc: str, optional _implicitParams: ns1.ImplicitParamsArrayType_Def, optional _param: ns1.ImplicitParamsType_Def, optional",
"name=None, ns=None ) class getOutputAsBase64ByNameResponse(ns1.getOutputAsBase64ByNameOutput_Dec): if not hasattr( ns1.getOutputAsBase64ByNameOutput_Dec(), \"typecode\"",
"\"typecode\" ): typecode = ns1.launchJobOutput_Dec() def __init__(self, name=None, ns=None): ns1.launchJobOutput_Dec.__init__(self,",
"str _numProcs: int, optional @return: response from launchJobResponse:: _launchJobOutput: ns1.JobSubOutputType_Def",
"incorrect request type\" %(request.__class__)) kw = {'requestclass': getOutputsRequestWrapper} response =",
"typecode = getOutputsRequest( name=None, ns=None ).typecode def __init__( self, name=None,",
"ns=None, **kw ): getOutputAsBase64ByNameResponse.__init__( self, name=None, ns=None ) class getOutputsRequest(ns1.getOutputsInput_Dec):",
"launchJobBlockingRequest( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw",
"response from launchJobBlockingResponse:: _launchJobBlockingOutput: ns1.BlockingOutputType_Def _jobOut: ns1.JobOutputType_Def _outputFile: ns1.OutputFileType_Def, optional",
"str _stdErr: str, optional _stdOut: str, optional _status: ns1.StatusOutputType_Def _baseURL:",
"not in kw: kw[\"host\"] = netloc[0] if \"port\" not in",
"document:literal message\"\"\" typecode = queryStatusRequest( name=None, ns=None ).typecode def __init__(",
"typecode = getAppConfigRequest( name=None, ns=None ).typecode def __init__( self, name=None,",
"document:literal message\"\"\" typecode = getAppMetadataResponse( name=None, ns=None ).typecode def __init__(",
"if not hasattr( ns1.getAppConfigOutput_Dec(), \"typecode\" ): typecode = ns1.getAppConfigOutput_Dec() def",
"self, name=None, ns=None, **kw ): queryStatusRequest.__init__( self, name=None, ns=None )",
"not issubclass(getAppMetadataResponse, response.__class__): raise TypeError(\"%s incorrect response type\" %(response.__class__)) return",
"_argList: str, optional _inputFile: ns1.InputFileType_Def, optional _contents: str _name: str",
"self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getAppMetadata\", **kw) response = self.binding.Receive(getAppMetadataResponseWrapper()) if not",
"self, name=None, ns=None ) class getOutputsResponse(ns1.getOutputsOutput_Dec): if not hasattr( ns1.getOutputsOutput_Dec(),",
"oname=\"%s xmlns=\\\"\\\"\" % name ) class getAppConfigRequestWrapper(getAppConfigRequest): \"\"\"wrapper for document:literal",
"hasattr( ns1.launchJobBlockingOutput_Dec(), \"typecode\" ): typecode = ns1.launchJobBlockingOutput_Dec() def __init__(self, name=None,",
"not issubclass(queryStatusResponse, response.__class__): raise TypeError(\"%s incorrect response type\" %(response.__class__)) return",
"): typecode = ns1.getOutputAsBase64ByNameOutput_Dec() def __init__(self, name=None, ns=None): ns1.getOutputAsBase64ByNameOutput_Dec.__init__(self, name=None,",
"name=None, ns=None, **kw ): launchJobRequest.__init__( self, name=None, ns=None ) class",
"getOutputAsBase64ByNameRequestWrapper(getOutputAsBase64ByNameRequest): \"\"\"wrapper for document:literal message\"\"\" typecode = getOutputAsBase64ByNameRequest( name=None, ns=None",
"queryStatusResponseWrapper(queryStatusResponse): \"\"\"wrapper for document:literal message\"\"\" typecode = queryStatusResponse( name=None, ns=None",
"launchJobResponse) and\\ not issubclass(launchJobResponse, response.__class__): raise TypeError(\"%s incorrect response type\"",
"queryStatusResponse) and\\ not issubclass(queryStatusResponse, response.__class__): raise TypeError(\"%s incorrect response type\"",
"class getAppConfigRequest: def __init__(self, name=None, ns=None): getAppConfigRequest.typecode = Struct(getAppConfigRequest,[], pname=name,",
"_defaultArgs: str, optional _metadata: ns1.AppMetadataType_Def _info: str, optional _types: ns1.ArgumentsType_Def,",
"not issubclass(launchJobRequest, request.__class__): raise TypeError(\"%s incorrect request type\" %(request.__class__)) kw",
"ns1.queryStatusOutput_Dec.__init__(self, name=None, ns=None) class queryStatusResponseWrapper(queryStatusResponse): \"\"\"wrapper for document:literal message\"\"\" typecode",
"getAppConfigRequest( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw",
"**kw ): getAppMetadataRequest.__init__( self, name=None, ns=None ) class getAppMetadataResponse(ns1.getAppMetadataOutput_Dec): if",
"not hasattr( ns1.getOutputsOutput_Dec(), \"typecode\" ): typecode = ns1.getOutputsOutput_Dec() def __init__(self,",
"getOutputsRequest(ns1.getOutputsInput_Dec): if not hasattr( ns1.getOutputsInput_Dec(), \"typecode\" ): typecode = ns1.getOutputsInput_Dec()",
"ns1.getAppMetadataOutput_Dec.__init__(self, name=None, ns=None) class getAppMetadataResponseWrapper(getAppMetadataResponse): \"\"\"wrapper for document:literal message\"\"\" typecode",
"@param: request to getAppConfigRequest @return: response from getAppConfigResponse:: _getAppConfigOutput: ns1.AppConfigType_Def",
"type\" %(response.__class__)) return response class destroyRequest(ns1.destroyInput_Dec): if not hasattr( ns1.destroyInput_Dec(),",
"in kw: kw[\"host\"] = netloc[0] if \"port\" not in kw:",
").typecode def __init__( self, name=None, ns=None, **kw ): getOutputsRequest.__init__( self,",
"_url: str _stdErr: str, optional _stdOut: str, optional \"\"\" if",
"= ns1.getOutputsInput_Dec() def __init__(self, name=None, ns=None): ns1.getOutputsInput_Dec.__init__(self, name=None, ns=None) class",
"name=None, ns=None, **kw ): launchJobBlockingResponse.__init__( self, name=None, ns=None ) class",
"typecode = launchJobResponse( name=None, ns=None ).typecode def __init__( self, name=None,",
"self, name=None, ns=None ) class launchJobResponse(ns1.launchJobOutput_Dec): if not hasattr( ns1.launchJobOutput_Dec(),",
"ns=None): ns1.destroyInput_Dec.__init__(self, name=None, ns=None) class destroyRequestWrapper(destroyRequest): \"\"\"wrapper for document:literal message\"\"\"",
"Struct(getAppConfigRequest,[], pname=name, aname=\"%s\" % name, oname=\"%s xmlns=\\\"\\\"\" % name )",
"def __init__(self, addr, **kw): netloc = (urllib.parse.urlparse(addr)[1]).split(\":\") + [80,] if",
"None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getOutputAsBase64ByName\", **kw) response = self.binding.Receive(getOutputAsBase64ByNameResponseWrapper()) if not isinstance(response,",
"response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getOutputs\", **kw) response = self.binding.Receive(getOutputsResponseWrapper())",
"_flags: ns1.FlagsArrayType_Def, optional _flag: ns1.FlagsType_Def, optional _id: str _tag: str",
"def getOutputs(self, request): \"\"\" @param: request is str @return: response",
"document:literal message\"\"\" typecode = getOutputsResponse( name=None, ns=None ).typecode def __init__(",
"optional _textDesc: str, optional _value: str, optional _separator: str, optional",
"kw = {} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getOutputAsBase64ByName\", **kw)",
"): getOutputsResponse.__init__( self, name=None, ns=None ) class launchJobBlockingRequest(ns1.launchJobBlockingInput_Dec): if not",
"TypeError(\"%s incorrect response type\" %(response.__class__)) return response def launchJob(self, request):",
"ns=None ) class getAppConfigRequest: def __init__(self, name=None, ns=None): getAppConfigRequest.typecode =",
"portAddress=None, **kw): raise NonImplementationError(\"method not implemented\") class AppServiceLocator(AppServiceInterface): AppServicePortType_address =",
"ns1.launchJobBlockingInput_Dec() def __init__(self, name=None, ns=None): ns1.launchJobBlockingInput_Dec.__init__(self, name=None, ns=None) class launchJobBlockingRequestWrapper(launchJobBlockingRequest):",
"self.binding.Receive(queryStatusResponseWrapper()) if not isinstance(response, queryStatusResponse) and\\ not issubclass(queryStatusResponse, response.__class__): raise",
"name=None, ns=None): getAppMetadataRequest.typecode = Struct(getAppMetadataRequest,[], pname=name, aname=\"%s\" % name, oname=\"%s",
"request to launchJobRequest:: _launchJobInput: ns1.JobInputType_Def _argList: str, optional _inputFile: ns1.InputFileType_Def,",
"return response def launchJobBlocking(self, request): \"\"\" @param: request to launchJobBlockingRequest::",
").typecode def __init__( self, name=None, ns=None, **kw ): launchJobResponse.__init__( self,",
"isinstance(request, getAppMetadataRequest) and\\ not issubclass(getAppMetadataRequest, request.__class__): raise TypeError(\"%s incorrect request",
"response def getOutputAsBase64ByName(self, request): \"\"\" @param: request to getOutputAsBase64ByNameRequest:: _getOutputAsBase64ByNameInput:",
"): typecode = ns1.getOutputsOutput_Dec() def __init__(self, name=None, ns=None): ns1.getOutputsOutput_Dec.__init__(self, name=None,",
"Struct from ZSI import client import ZSI class AppServiceInterface: def",
"class destroyRequest(ns1.destroyInput_Dec): if not hasattr( ns1.destroyInput_Dec(), \"typecode\" ): typecode =",
"_paramType: ns1.ParamType_Def _ParamType: str, optional _required: boolean, optional _semanticType: str,",
"str _status: ns1.StatusOutputType_Def _baseURL: str _code: int _message: str \"\"\"",
") class getAppConfigResponse(ns1.getAppConfigOutput_Dec): if not hasattr( ns1.getAppConfigOutput_Dec(), \"typecode\" ): typecode",
"= getAppMetadataResponse( name=None, ns=None ).typecode def __init__( self, name=None, ns=None,",
"str, optional _value: str, optional _separator: str, optional _untaggedParams: ns1.ParamsArrayType_Def,",
"**kw ): getAppMetadataResponse.__init__( self, name=None, ns=None ) class getOutputAsBase64ByNameRequest(ns1.getOutputAsBase64ByNameInput_Dec): if",
"\"\"\" @param: request is str @return: response from getOutputsResponse:: _getOutputsOutput:",
"not in kw: kw[\"url\"] = urllib.parse.urlparse(addr)[2] self.binding = client.Binding(**kw) def",
"queryStatusRequest.__init__( self, name=None, ns=None ) class queryStatusResponse(ns1.queryStatusOutput_Dec): if not hasattr(",
"int _message: str \"\"\" if not isinstance(request, str): raise TypeError(\"%s",
"typecode = ns1.getOutputAsBase64ByNameOutput_Dec() def __init__(self, name=None, ns=None): ns1.getOutputAsBase64ByNameOutput_Dec.__init__(self, name=None, ns=None)",
"_binaryLocation: str _defaultArgs: str, optional _metadata: ns1.AppMetadataType_Def _info: str, optional",
"request, soapaction=\"http://nbcr.sdsc.edu/opal/getAppConfig\", **kw) response = self.binding.Receive(getAppConfigResponseWrapper()) if not isinstance(response, getAppConfigResponse)",
"class launchJobResponse(ns1.launchJobOutput_Dec): if not hasattr( ns1.launchJobOutput_Dec(), \"typecode\" ): typecode =",
"_message: str \"\"\" if not isinstance(request, launchJobRequest) and\\ not issubclass(launchJobRequest,",
"raise TypeError(\"%s incorrect response type\" %(response.__class__)) return response def launchJobBlocking(self,",
"typecode = launchJobBlockingRequest( name=None, ns=None ).typecode def __init__( self, name=None,",
"if not isinstance(request, launchJobRequest) and\\ not issubclass(launchJobRequest, request.__class__): raise TypeError(\"%s",
"%(response.__class__)) return response def queryStatus(self, request): \"\"\" @param: request is",
") class getAppMetadataResponse(ns1.getAppMetadataOutput_Dec): if not hasattr( ns1.getAppMetadataOutput_Dec(), \"typecode\" ): typecode",
"typecode = ns1.launchJobInput_Dec() def __init__(self, name=None, ns=None): ns1.launchJobInput_Dec.__init__(self, name=None, ns=None)",
"if not hasattr( ns1.getOutputAsBase64ByNameInput_Dec(), \"typecode\" ): typecode = ns1.getOutputAsBase64ByNameInput_Dec() def",
"ns1.ParamsArrayType_Def, optional _usage: str _parallel: boolean \"\"\" if not isinstance(request,",
"getOutputAsBase64ByNameResponse( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw",
"name=None, ns=None ) class getOutputAsBase64ByNameRequest(ns1.getOutputAsBase64ByNameInput_Dec): if not hasattr( ns1.getOutputAsBase64ByNameInput_Dec(), \"typecode\"",
"__init__(self, name=None, ns=None): ns1.getAppConfigOutput_Dec.__init__(self, name=None, ns=None) class getAppConfigResponseWrapper(getAppConfigResponse): \"\"\"wrapper for",
"class launchJobBlockingResponseWrapper(launchJobBlockingResponse): \"\"\"wrapper for document:literal message\"\"\" typecode = launchJobBlockingResponse( name=None,",
"not isinstance(response, launchJobResponse) and\\ not issubclass(launchJobResponse, response.__class__): raise TypeError(\"%s incorrect",
"_getOutputsOutput: ns1.JobOutputType_Def _outputFile: ns1.OutputFileType_Def, optional _name: str _url: str _stdErr:",
"ns=None): getAppMetadataRequest.typecode = Struct(getAppMetadataRequest,[], pname=name, aname=\"%s\" % name, oname=\"%s xmlns=\\\"\\\"\"",
"document:literal message\"\"\" typecode = launchJobBlockingRequest( name=None, ns=None ).typecode def __init__(",
"and\\ not issubclass(getAppConfigResponse, response.__class__): raise TypeError(\"%s incorrect response type\" %(response.__class__))",
"optional _usage: str \"\"\" if not isinstance(request, getAppMetadataRequest) and\\ not",
"ns=None, **kw ): destroyResponse.__init__( self, name=None, ns=None ) class getAppConfigRequest:",
"@return: response from getOutputAsBase64ByNameResponse:: _item: str, optional \"\"\" if not",
"= queryStatusRequest( name=None, ns=None ).typecode def __init__( self, name=None, ns=None,",
"\"\"\"wrapper for document:literal message\"\"\" typecode = getAppMetadataRequest( name=None, ns=None ).typecode",
"= ns1.launchJobBlockingOutput_Dec() def __init__(self, name=None, ns=None): ns1.launchJobBlockingOutput_Dec.__init__(self, name=None, ns=None) class",
"ns=None, **kw ): getOutputsRequest.__init__( self, name=None, ns=None ) class getOutputsResponse(ns1.getOutputsOutput_Dec):",
"to getAppConfigRequest @return: response from getAppConfigResponse:: _getAppConfigOutput: ns1.AppConfigType_Def _binaryLocation: str",
"return response def queryStatus(self, request): \"\"\" @param: request is str",
"kw = {'requestclass': queryStatusRequestWrapper} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/queryStatus\",",
"def __init__(self, name=None, ns=None): ns1.getAppMetadataOutput_Dec.__init__(self, name=None, ns=None) class getAppMetadataResponseWrapper(getAppMetadataResponse): \"\"\"wrapper",
"ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): destroyRequest.__init__(",
"\"\"\" if not isinstance(request, str): raise TypeError(\"%s incorrect request type\"",
"optional _stdOut: str, optional \"\"\" if not isinstance(request, str): raise",
"@return: response from launchJobBlockingResponse:: _launchJobBlockingOutput: ns1.BlockingOutputType_Def _jobOut: ns1.JobOutputType_Def _outputFile: ns1.OutputFileType_Def,",
"ns1.ArgumentsType_Def, optional _flags: ns1.FlagsArrayType_Def, optional _flag: ns1.FlagsType_Def, optional _id: str",
"= Struct(getAppConfigRequest,[], pname=name, aname=\"%s\" % name, oname=\"%s xmlns=\\\"\\\"\" % name",
"by ZSI.wsdl2python # # ################################################## from .AppService_services_types import * from",
"ns=None): ns1.queryStatusOutput_Dec.__init__(self, name=None, ns=None) class queryStatusResponseWrapper(queryStatusResponse): \"\"\"wrapper for document:literal message\"\"\"",
"issubclass(getAppMetadataResponse, response.__class__): raise TypeError(\"%s incorrect response type\" %(response.__class__)) return response",
"\"\"\"wrapper for document:literal message\"\"\" typecode = launchJobBlockingResponse( name=None, ns=None ).typecode",
"type\" %(response.__class__)) return response def getOutputs(self, request): \"\"\" @param: request",
"ns=None ).typecode def __init__( self, name=None, ns=None, **kw ): getAppConfigResponse.__init__(",
"int, optional _name: str, optional _required: boolean, optional _semanticType: str,",
"raise TypeError(\"%s incorrect response type\" %(response.__class__)) return response def getAppConfig(self,",
"hasattr( ns1.launchJobInput_Dec(), \"typecode\" ): typecode = ns1.launchJobInput_Dec() def __init__(self, name=None,",
"raise TypeError(\"%s incorrect request type\" %(request.__class__)) kw = {'requestclass': queryStatusRequestWrapper}",
"_types: ns1.ArgumentsType_Def, optional _flags: ns1.FlagsArrayType_Def, optional _flag: ns1.FlagsType_Def, optional _id:",
"**kw): netloc = (urllib.parse.urlparse(addr)[1]).split(\":\") + [80,] if \"host\" not in",
"response type\" %(response.__class__)) return response def getAppMetadata(self, request): \"\"\" @param:",
"ns1.getAppConfigOutput_Dec(), \"typecode\" ): typecode = ns1.getAppConfigOutput_Dec() def __init__(self, name=None, ns=None):",
"optional @return: response from launchJobBlockingResponse:: _launchJobBlockingOutput: ns1.BlockingOutputType_Def _jobOut: ns1.JobOutputType_Def _outputFile:",
"response.__class__): raise TypeError(\"%s incorrect response type\" %(response.__class__)) return response def",
"__init__(self, name=None, ns=None): ns1.launchJobBlockingOutput_Dec.__init__(self, name=None, ns=None) class launchJobBlockingResponseWrapper(launchJobBlockingResponse): \"\"\"wrapper for",
"name=None, ns=None): ns1.getOutputAsBase64ByNameInput_Dec.__init__(self, name=None, ns=None) class getOutputAsBase64ByNameRequestWrapper(getOutputAsBase64ByNameRequest): \"\"\"wrapper for document:literal",
"str, optional _id: str _ioType: ns1.IOType_Def _IOType: str, optional _max:",
"getAppMetadataRequest @return: response from getAppMetadataResponse:: _getAppMetadataOutput: ns1.AppMetadataType_Def _info: str, optional",
").typecode def __init__( self, name=None, ns=None, **kw ): launchJobBlockingResponse.__init__( self,",
"def __init__(self, name=None, ns=None): ns1.getOutputsOutput_Dec.__init__(self, name=None, ns=None) class getOutputsResponseWrapper(getOutputsResponse): \"\"\"wrapper",
"addr, **kw): netloc = (urllib.parse.urlparse(addr)[1]).split(\":\") + [80,] if \"host\" not",
"if not hasattr( ns1.getOutputsInput_Dec(), \"typecode\" ): typecode = ns1.getOutputsInput_Dec() def",
"ns=None) class launchJobBlockingRequestWrapper(launchJobBlockingRequest): \"\"\"wrapper for document:literal message\"\"\" typecode = launchJobBlockingRequest(",
"destroyRequest.__init__( self, name=None, ns=None ) class destroyResponse(ns1.destroyOutput_Dec): if not hasattr(",
"name=None, ns=None ) class getAppConfigRequest: def __init__(self, name=None, ns=None): getAppConfigRequest.typecode",
"= ns1.queryStatusInput_Dec() def __init__(self, name=None, ns=None): ns1.queryStatusInput_Dec.__init__(self, name=None, ns=None) class",
"getOutputsRequest.__init__( self, name=None, ns=None ) class getOutputsResponse(ns1.getOutputsOutput_Dec): if not hasattr(",
"typecode = destroyResponse( name=None, ns=None ).typecode def __init__( self, name=None,",
"launchJobBlocking(self, request): \"\"\" @param: request to launchJobBlockingRequest:: _launchJobBlockingInput: ns1.JobInputType_Def _argList:",
"self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/launchJobBlocking\", **kw) response = self.binding.Receive(launchJobBlockingResponseWrapper()) if not",
"_message: str \"\"\" if not isinstance(request, str): raise TypeError(\"%s incorrect",
"document:literal message\"\"\" typecode = launchJobRequest( name=None, ns=None ).typecode def __init__(",
"% name ) class getAppMetadataRequestWrapper(getAppMetadataRequest): \"\"\"wrapper for document:literal message\"\"\" typecode",
"from getOutputAsBase64ByNameResponse:: _item: str, optional \"\"\" if not isinstance(request, getOutputAsBase64ByNameRequest)",
") class getOutputAsBase64ByNameResponse(ns1.getOutputAsBase64ByNameOutput_Dec): if not hasattr( ns1.getOutputAsBase64ByNameOutput_Dec(), \"typecode\" ): typecode",
"message\"\"\" typecode = launchJobBlockingResponse( name=None, ns=None ).typecode def __init__( self,",
"request, soapaction=\"http://nbcr.sdsc.edu/opal/queryStatus\", **kw) response = self.binding.Receive(queryStatusResponseWrapper()) if not isinstance(response, queryStatusResponse)",
"class queryStatusResponseWrapper(queryStatusResponse): \"\"\"wrapper for document:literal message\"\"\" typecode = queryStatusResponse( name=None,",
"optional _inputFile: ns1.InputFileType_Def, optional _contents: str _name: str _numProcs: int,",
").typecode def __init__( self, name=None, ns=None, **kw ): getOutputsResponse.__init__( self,",
"name=None, ns=None ) class launchJobBlockingRequest(ns1.launchJobBlockingInput_Dec): if not hasattr( ns1.launchJobBlockingInput_Dec(), \"typecode\"",
"= ns1.getOutputsOutput_Dec() def __init__(self, name=None, ns=None): ns1.getOutputsOutput_Dec.__init__(self, name=None, ns=None) class",
"for document:literal message\"\"\" typecode = launchJobResponse( name=None, ns=None ).typecode def",
"= ns1.launchJobOutput_Dec() def __init__(self, name=None, ns=None): ns1.launchJobOutput_Dec.__init__(self, name=None, ns=None) class",
"to launchJobBlockingRequest:: _launchJobBlockingInput: ns1.JobInputType_Def _argList: str, optional _inputFile: ns1.InputFileType_Def, optional",
"= {} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/launchJob\", **kw) response",
"response type\" %(response.__class__)) return response class destroyRequest(ns1.destroyInput_Dec): if not hasattr(",
"= ns1.destroyInput_Dec() def __init__(self, name=None, ns=None): ns1.destroyInput_Dec.__init__(self, name=None, ns=None) class",
"__init__( self, name=None, ns=None, **kw ): queryStatusRequest.__init__( self, name=None, ns=None",
"__init__( self, name=None, ns=None, **kw ): getOutputAsBase64ByNameRequest.__init__( self, name=None, ns=None",
"ns1.ParamType_Def _ParamType: str, optional _required: boolean, optional _semanticType: str, optional",
"\"\"\"wrapper for document:literal message\"\"\" typecode = queryStatusResponse( name=None, ns=None ).typecode",
"for document:literal message\"\"\" typecode = getAppMetadataResponse( name=None, ns=None ).typecode def",
"getAppMetadataRequest: def __init__(self, name=None, ns=None): getAppMetadataRequest.typecode = Struct(getAppMetadataRequest,[], pname=name, aname=\"%s\"",
"**kw ): queryStatusRequest.__init__( self, name=None, ns=None ) class queryStatusResponse(ns1.queryStatusOutput_Dec): if",
"\"\"\" @param: request is str @return: response from queryStatusResponse:: _queryStatusOutput:",
"self, name=None, ns=None ) class getAppMetadataRequest: def __init__(self, name=None, ns=None):",
"\"typecode\" ): typecode = ns1.getOutputAsBase64ByNameOutput_Dec() def __init__(self, name=None, ns=None): ns1.getOutputAsBase64ByNameOutput_Dec.__init__(self,",
"typecode = queryStatusRequest( name=None, ns=None ).typecode def __init__( self, name=None,",
"\"\"\" if not isinstance(request, getAppMetadataRequest) and\\ not issubclass(getAppMetadataRequest, request.__class__): raise",
"for document:literal message\"\"\" typecode = queryStatusResponse( name=None, ns=None ).typecode def",
"request is str @return: response from queryStatusResponse:: _queryStatusOutput: ns1.StatusOutputType_Def _baseURL:",
"%(response.__class__)) return response class destroyRequest(ns1.destroyInput_Dec): if not hasattr( ns1.destroyInput_Dec(), \"typecode\"",
"getAppMetadataResponse(ns1.getAppMetadataOutput_Dec): if not hasattr( ns1.getAppMetadataOutput_Dec(), \"typecode\" ): typecode = ns1.getAppMetadataOutput_Dec()",
"_extension: str, optional _id: str _ioType: ns1.IOType_Def _IOType: str, optional",
"ns1.destroyInput_Dec(), \"typecode\" ): typecode = ns1.destroyInput_Dec() def __init__(self, name=None, ns=None):",
"message\"\"\" typecode = queryStatusRequest( name=None, ns=None ).typecode def __init__( self,",
"getOutputAsBase64ByNameRequest( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw",
"not issubclass(getAppMetadataRequest, request.__class__): raise TypeError(\"%s incorrect request type\" %(request.__class__)) kw",
"if not hasattr( ns1.getOutputsOutput_Dec(), \"typecode\" ): typecode = ns1.getOutputsOutput_Dec() def",
"{} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getAppMetadata\", **kw) response =",
"hasattr( ns1.queryStatusInput_Dec(), \"typecode\" ): typecode = ns1.queryStatusInput_Dec() def __init__(self, name=None,",
"\"typecode\" ): typecode = ns1.getOutputAsBase64ByNameInput_Dec() def __init__(self, name=None, ns=None): ns1.getOutputAsBase64ByNameInput_Dec.__init__(self,",
"response def launchJobBlocking(self, request): \"\"\" @param: request to launchJobBlockingRequest:: _launchJobBlockingInput:",
"int, optional @return: response from launchJobResponse:: _launchJobOutput: ns1.JobSubOutputType_Def _jobID: str",
"destroyResponse( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw",
"def launchJob(self, request): \"\"\" @param: request to launchJobRequest:: _launchJobInput: ns1.JobInputType_Def",
"ns=None ) class queryStatusRequest(ns1.queryStatusInput_Dec): if not hasattr( ns1.queryStatusInput_Dec(), \"typecode\" ):",
"AppServicePortType_address = \"https://rocks-106.sdsc.edu:8443/axis/services/AutogridServicePort\" def getAppServicePortTypeAddress(self): return AppServiceLocator.AppServicePortType_address def getAppServicePortType(self, portAddress=None,",
"if not isinstance(response, destroyResponse) and\\ not issubclass(destroyResponse, response.__class__): raise TypeError(\"%s",
"name=None, ns=None): ns1.queryStatusInput_Dec.__init__(self, name=None, ns=None) class queryStatusRequestWrapper(queryStatusRequest): \"\"\"wrapper for document:literal",
"_getOutputAsBase64ByNameInput: ns1.OutputsByNameInputType_Def _fileName: str _jobID: str @return: response from getOutputAsBase64ByNameResponse::",
"kw = {} response = self.binding.Send(None, None, request, soapaction=\"http://nbcr.sdsc.edu/opal/getAppMetadata\", **kw)",
"not implemented\") class AppServiceLocator(AppServiceInterface): AppServicePortType_address = \"https://rocks-106.sdsc.edu:8443/axis/services/AutogridServicePort\" def getAppServicePortTypeAddress(self): return",
"= getOutputsResponse( name=None, ns=None ).typecode def __init__( self, name=None, ns=None,",
"return AppServiceLocator.AppServicePortType_address def getAppServicePortType(self, portAddress=None, **kw): return AppServicePortSoapBindingSOAP(portAddress or AppServiceLocator.AppServicePortType_address,",
"getAppConfigRequest: def __init__(self, name=None, ns=None): getAppConfigRequest.typecode = Struct(getAppConfigRequest,[], pname=name, aname=\"%s\"",
"if not hasattr( ns1.destroyOutput_Dec(), \"typecode\" ): typecode = ns1.destroyOutput_Dec() def",
"_getAppMetadataOutput: ns1.AppMetadataType_Def _info: str, optional _types: ns1.ArgumentsType_Def, optional _flags: ns1.FlagsArrayType_Def,",
"xmlns=\\\"\\\"\" % name ) class getAppConfigRequestWrapper(getAppConfigRequest): \"\"\"wrapper for document:literal message\"\"\"",
"class launchJobBlockingRequest(ns1.launchJobBlockingInput_Dec): if not hasattr( ns1.launchJobBlockingInput_Dec(), \"typecode\" ): typecode =",
"getOutputsRequest( name=None, ns=None ).typecode def __init__( self, name=None, ns=None, **kw"
] |
[
"NVIDIA CORPORATION. All rights reserved. # # Licensed under the",
"amax_name)].item() amax = abs(quant_max)#round(abs(quant_max)*factor)/factor if amax_name in int8O_gemm_input_list: int8O_gemm_input_amax_list[int8O_gemm_input_list.index(amax_name)] =",
"int8O_gemm_output_amax_list[int8O_gemm_output_list.index(amax_name)] = amax if amax_name in int8O_gemm_weight_list: int8O_gemm_weight_amax_list[int8O_gemm_weight_list.index(amax_name)] = amax",
"# #### bmm2 amax # amaxList[amax_id] = amaxList[8] # amax_id",
"2.0 (the \"License\"); # you may not use this file",
"depth, amax_name)].item() amax = abs(quant_max)#round(abs(quant_max)*factor)/factor if amax_name in int8O_gemm_input_list: int8O_gemm_input_amax_list[int8O_gemm_input_list.index(amax_name)]",
"# #### softmax amax # amaxList[amax_id] = amaxList[28] # amax_id",
"= [\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\"] amax_name_list = [\"attn.qkv._input_quantizer\", \"attn.qkv._aftergemm_quantizer\", \"attn.proj._input_quantizer\",",
"-2).contiguous() quant_max2 = init_dict[\"layers.{}.blocks.{}.{}._weight_quantizer._amax\".format(i, depth, kernel_name)] amax2 = abs(quant_max2) #",
"int8O gemm deQuant for j in range(INT8O_GEMM_NUM - 1): amaxList[amax_id]",
"# amax_id += 1 # #### softmax amax # amaxList[amax_id]",
"starts from ACTIVATION_AMAX_NUM assert amax_id == 68 amax_id = ACTIVATION_AMAX_NUM",
"torch.ops.fastertransformer.swin_weight_quantize layer_num = len(depths) amaxTotalNum = ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM +",
"amax2.cuda()) init_dict[\"layers.{}.blocks.{}.{}.weight\".format(i, depth, kernel_name)] = kernel_processed if kernel_name in int8O_gemm_weight_list:",
"amaxList[amax_id] = init_dict[\"layers.{}.downsample.reduction._weight_quantizer._amax\".format(i)].item() amax_id += 1 assert amax_id == ACTIVATION_AMAX_NUM",
"init_dict[\"layers.{}.downsample.reduction._weight_quantizer._amax\".format(i)].item() amax_id += 1 assert amax_id == ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM",
"kernel.transpose(-1, -2).contiguous() kernel_processed = weight_quantize(kernel, amax2.cuda()) init_dict[\"layers.{}.downsample.reduction.weight\".format(i)] = kernel_processed #",
"weight_quantize(kernel, amax2.cuda()) init_dict[\"layers.{}.downsample.reduction.weight\".format(i)] = kernel_processed # print(\"Quantizing checkpoint done.\") return",
"amax = init_dict[\"layers.{}.{}._amax\".format(i, downsample_out)].item() amaxList[amax_id] = amax amax_id += 1",
"layer_{} block_{} kernel weight\".format(i, depth)) if i != layer_num -",
"[\"attn.qkv._input_quantizer\", \"attn.qkv._aftergemm_quantizer\", \"attn.proj._input_quantizer\", \"attn.proj._aftergemm_quantizer\", \"attn.matmul_q_input_quantizer\", \"attn.matmul_k_input_quantizer\", \"attn.matmul_v_input_quantizer\", \"attn.matmul_a_input_quantizer\", \"attn.softmax_input_quantizer\", \"mlp.fc1._input_quantizer\",",
"\"mlp.fc1\", \"mlp.fc2\"] amax_name_list = [\"attn.qkv._input_quantizer\", \"attn.qkv._aftergemm_quantizer\", \"attn.proj._input_quantizer\", \"attn.proj._aftergemm_quantizer\", \"attn.matmul_q_input_quantizer\", \"attn.matmul_k_input_quantizer\",",
"int8O_gemm_output_amax_list = [0 for i in range(INT8O_GEMM_NUM)] int8O_gemm_output_list = [\"attn.qkv._aftergemm_quantizer\",",
"init_dict[\"layers.{}.{}._amax\".format(i, downsample_out)].item() amaxList[amax_id] = amax amax_id += 1 amaxList[amax_id] =",
"amax\".format(i, depth)) #kernel amax starts from ACTIVATION_AMAX_NUM assert amax_id ==",
"int8O_gemm_input_list = [\"attn.qkv._input_quantizer\", \"attn.proj._input_quantizer\", \"mlp.fc1._input_quantizer\", \"mlp.fc2._input_quantizer\", \"attn.matmul_q_input_quantizer\", \"attn.matmul_a_input_quantizer\"] int8O_gemm_output_amax_list =",
"i in range(layer_num): for depth in range(depths[i]): amaxList = np.zeros([amaxTotalNum]).astype(np.float32)",
"patchMerge_w) / (127 * patchMerge_o) amax_id += 1 assert amax_id",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"j, ' gemm_int8IO_scale:',amaxList[amax_id]) # print(int8O_gemm_input_amax_list[j], int8O_gemm_weight_amax_list[j], int8O_gemm_output_amax_list[j]) amax_id += 1",
"i in range(INT8O_GEMM_NUM)] int8O_gemm_weight_list = [\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\", \"attn.matmul_k_input_quantizer\",",
"(127 * patchMerge_o) amax_id += 1 assert amax_id == ACTIVATION_AMAX_NUM",
"1): amaxList[amax_id] = (int8O_gemm_input_amax_list[j]*int8O_gemm_weight_amax_list[j])/(127.0*int8O_gemm_output_amax_list[j]) # print('layernum:', i, 'j:', j, '",
"i != layer_num - 1: amaxList[amax_id] = init_dict[\"layers.{}.downsample.reduction._weight_quantizer._amax\".format(i)].item() amax_id +=",
"+= 1 # #### softmax amax # amaxList[amax_id] = amaxList[28]",
"init_dict[\"layers.{}.{}._amax\".format(i, downsample_out)].item() amaxList[amax_id] = (patchMerge_i * patchMerge_w) / (127 *",
"numpy as np import torch ACTIVATION_AMAX_NUM = 72 INT8O_KERNEL_NUM =",
"quant_max2 = init_dict[\"layers.{}.downsample.reduction._weight_quantizer._amax\".format(i)] amax2 = abs(quant_max2) kernel = kernel.transpose(-1, -2).contiguous()",
"= torch.tensor(amaxList, dtype=torch.float32) if verbose: print(\"done process layer_{} block_{} kernel",
"= kernel.transpose(-1, -2).contiguous() kernel_processed = weight_quantize(kernel, amax2.cuda()) init_dict[\"layers.{}.downsample.reduction.weight\".format(i)] = kernel_processed",
"if __name__ == '__main__': weights = torch.load('pytorch_model.bin') extract_amaxlist(weights, [2, 2,",
"init_dict[\"layers.{}.downsample.reduction.weight\".format(i)] = kernel_processed # print(\"Quantizing checkpoint done.\") return init_dict if",
"= init_dict[\"layers.{}.{}._amax\".format(i, downsample_input)].item() patchMerge_w = init_dict[\"layers.{}.{}._amax\".format(i, downsample_weight)].item() patchMerge_o = init_dict[\"layers.{}.{}._amax\".format(i,",
"int8O_gemm_output_amax_list[j]) amax_id += 1 if i != layer_num - 1:",
"print(\"done process layer_{} block_{} kernel weight\".format(i, depth)) if i !=",
"' gemm_int8IO_scale:',amaxList[amax_id]) # print(int8O_gemm_input_amax_list[j], int8O_gemm_weight_amax_list[j], int8O_gemm_output_amax_list[j]) amax_id += 1 if",
"amaxList[20] / (127.0 * 127.0) amax_id += 1 amaxList[amax_id] =",
"process layer_{} block_{} kernel weight\".format(i, depth)) if i != layer_num",
"limitations under the License. import sys import argparse import re",
"/ (127.0 * amaxList[8]) amax_id += 1 init_dict[\"layers.{}.blocks.{}.amaxList\".format(i, depth)] =",
"[\"attn.qkv._input_quantizer\", \"attn.proj._input_quantizer\", \"mlp.fc1._input_quantizer\", \"mlp.fc2._input_quantizer\", \"attn.matmul_q_input_quantizer\", \"attn.matmul_a_input_quantizer\"] int8O_gemm_output_amax_list = [0 for",
"# print(int8O_gemm_input_amax_list[j], int8O_gemm_weight_amax_list[j], int8O_gemm_output_amax_list[j]) amax_id += 1 if i !=",
"use this file except in compliance with the License. #",
"2020-2022, NVIDIA CORPORATION. All rights reserved. # # Licensed under",
"#### QKV_addBias_amax # amaxList[amax_id] = np.maximum(np.maximum(amaxList[16],amaxList[20]), amaxList[24]) # amax_id +=",
"if verbose: print(\"done process layer_{} block_{} kernel weight\".format(i, depth)) if",
"# Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved. #",
"kernel_processed = weight_quantize(kernel, amax2.cuda()) init_dict[\"layers.{}.blocks.{}.{}.weight\".format(i, depth, kernel_name)] = kernel_processed if",
"amaxList[amax_id] = 127.0/amax amax_id += 1 else: amax_id += 8",
"!= layer_num - 1: kernel = init_dict[\"layers.{}.downsample.reduction.weight\".format(i)] quant_max2 = init_dict[\"layers.{}.downsample.reduction._weight_quantizer._amax\".format(i)]",
"1: patchMerge_i = init_dict[\"layers.{}.{}._amax\".format(i, downsample_input)].item() patchMerge_w = init_dict[\"layers.{}.{}._amax\".format(i, downsample_weight)].item() patchMerge_o",
"reserved. # # Licensed under the Apache License, Version 2.0",
"+= 1 amaxList[amax_id] = 127.0 / amaxList[28] amax_id += 1",
"patchMerge_i = init_dict[\"layers.{}.{}._amax\".format(i, downsample_input)].item() patchMerge_w = init_dict[\"layers.{}.{}._amax\".format(i, downsample_weight)].item() patchMerge_o =",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"+ INT8O_GEMM_NUM + 1 + TRT_FUSED_MHA_AMAX_NUM + SCALE_RESERVE_NUM kernel_name_list =",
"\"downsample.reduction._aftergemm_quantizer\" factor = 1000000.0 for i in range(layer_num): for depth",
"License. # You may obtain a copy of the License",
"for i in range(INT8O_GEMM_NUM)] int8O_gemm_input_list = [\"attn.qkv._input_quantizer\", \"attn.proj._input_quantizer\", \"mlp.fc1._input_quantizer\", \"mlp.fc2._input_quantizer\",",
"= init_dict[\"layers.{}.blocks.{}.{}._amax\".format(i, depth, amax_name)].item() amax = abs(quant_max)#round(abs(quant_max)*factor)/factor if amax_name in",
"#for int8O gemm deQuant for j in range(INT8O_GEMM_NUM - 1):",
"1 # #### bmm2 amax # amaxList[amax_id] = amaxList[8] #",
"weight\".format(i, depth)) if i != layer_num - 1: kernel =",
"done.\") return init_dict if __name__ == '__main__': weights = torch.load('pytorch_model.bin')",
"quant_max_processed = amax2.view(-1) kernel_processed = weight_quantize(kernel, amax2.cuda()) init_dict[\"layers.{}.blocks.{}.{}.weight\".format(i, depth, kernel_name)]",
"\"attn.matmul_v_input_quantizer\"] int8O_gemm_input_amax_list = [0 for i in range(INT8O_GEMM_NUM)] int8O_gemm_input_list =",
"under the License is distributed on an \"AS IS\" BASIS,",
"License for the specific language governing permissions and # limitations",
"int8O_gemm_weight_list = [\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\", \"attn.matmul_k_input_quantizer\", \"attn.matmul_v_input_quantizer\"] int8O_gemm_input_amax_list =",
"+ TRT_FUSED_MHA_AMAX_NUM + SCALE_RESERVE_NUM kernel_name_list = [\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\"]",
"- 1: kernel = init_dict[\"layers.{}.downsample.reduction.weight\".format(i)] quant_max2 = init_dict[\"layers.{}.downsample.reduction._weight_quantizer._amax\".format(i)] amax2 =",
"= 8 def extract_amaxlist(init_dict, depths, ths_path='../lib/libpyt_swintransformer.so', verbose=True): # print(\"Quantizing checkpoint",
"amax_name_list = [\"attn.qkv._input_quantizer\", \"attn.qkv._aftergemm_quantizer\", \"attn.proj._input_quantizer\", \"attn.proj._aftergemm_quantizer\", \"attn.matmul_q_input_quantizer\", \"attn.matmul_k_input_quantizer\", \"attn.matmul_v_input_quantizer\", \"attn.matmul_a_input_quantizer\",",
"amaxList[24]) amaxList[amax_id] = amaxList[16] * amaxList[20] / (127.0 * 127.0)",
"= amax/127.0/127.0 amax_id += 1 amaxList[amax_id] = 127.0/amax amax_id +=",
"#### bmm2 amax # amaxList[amax_id] = amaxList[8] # amax_id +=",
"- 1): amaxList[amax_id] = (int8O_gemm_input_amax_list[j]*int8O_gemm_weight_amax_list[j])/(127.0*int8O_gemm_output_amax_list[j]) # print('layernum:', i, 'j:', j,",
"[\"attn.qkv._aftergemm_quantizer\", \"attn.proj._aftergemm_quantizer\", \"mlp.fc1._aftergemm_quantizer\", \"mlp.fc2._aftergemm_quantizer\", \"attn.softmax_input_quantizer\", \"attn.proj._input_quantizer\"] downsample_input = \"downsample.reduction._input_quantizer\" downsample_weight",
"amax_id += 1 if i != layer_num - 1: patchMerge_i",
"# amaxList[amax_id] = amaxList[28] # amax_id += 1 # ####",
"int8O_gemm_input_amax_list = [0 for i in range(INT8O_GEMM_NUM)] int8O_gemm_input_list = [\"attn.qkv._input_quantizer\",",
"= [\"attn.qkv._input_quantizer\", \"attn.proj._input_quantizer\", \"mlp.fc1._input_quantizer\", \"mlp.fc2._input_quantizer\", \"attn.matmul_q_input_quantizer\", \"attn.matmul_a_input_quantizer\"] int8O_gemm_output_amax_list = [0",
"print(int8O_gemm_input_amax_list[j], int8O_gemm_weight_amax_list[j], int8O_gemm_output_amax_list[j]) amax_id += 1 if i != layer_num",
"Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved. # #",
"+= 1 assert amax_id == ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM #for int8O",
"\"attn.proj._aftergemm_quantizer\", \"mlp.fc1._aftergemm_quantizer\", \"mlp.fc2._aftergemm_quantizer\", \"attn.softmax_input_quantizer\", \"attn.proj._input_quantizer\"] downsample_input = \"downsample.reduction._input_quantizer\" downsample_weight =",
"== '__main__': weights = torch.load('pytorch_model.bin') extract_amaxlist(weights, [2, 2, 6, 2])",
"(127.0 * 127.0) amax_id += 1 amaxList[amax_id] = 127.0 /",
"== ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM + INT8O_GEMM_NUM amax_id += 1 #for",
"in compliance with the License. # You may obtain a",
"1 init_dict[\"layers.{}.blocks.{}.amaxList\".format(i, depth)] = torch.tensor(amaxList, dtype=torch.float32) if verbose: print(\"done process",
"depth in range(depths[i]): amaxList = np.zeros([amaxTotalNum]).astype(np.float32) amax_id = 0 for",
"software # distributed under the License is distributed on an",
"\"downsample.reduction._input_quantizer\" downsample_weight = \"downsample.reduction._weight_quantizer\" downsample_out = \"downsample.reduction._aftergemm_quantizer\" factor = 1000000.0",
"= [\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\", \"attn.matmul_k_input_quantizer\", \"attn.matmul_v_input_quantizer\"] int8O_gemm_input_amax_list = [0",
"INT8O_GEMM_NUM amax_id += 1 #for trt fused MHA amax ####",
"bmm2 amax # amaxList[amax_id] = amaxList[8] # amax_id += 1",
"\"mlp.fc2\"] amax_name_list = [\"attn.qkv._input_quantizer\", \"attn.qkv._aftergemm_quantizer\", \"attn.proj._input_quantizer\", \"attn.proj._aftergemm_quantizer\", \"attn.matmul_q_input_quantizer\", \"attn.matmul_k_input_quantizer\", \"attn.matmul_v_input_quantizer\",",
"quant_max = init_dict[\"layers.{}.blocks.{}.{}._amax\".format(i, depth, amax_name)].item() amax = abs(quant_max)#round(abs(quant_max)*factor)/factor if amax_name",
"= len(depths) amaxTotalNum = ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM + INT8O_GEMM_NUM +",
"8 if verbose: print(\"done process layer_{} block_{} activation amax\".format(i, depth))",
"# print('quant_max_processed_:', quant_max_processed) if i != layer_num - 1: amaxList[amax_id]",
"for kernel_id, kernel_name in enumerate(kernel_name_list): kernel = init_dict[\"layers.{}.blocks.{}.{}.weight\".format(i, depth, kernel_name)].transpose(-1,",
"* amaxList[28] / (127.0 * amaxList[8]) amax_id += 1 init_dict[\"layers.{}.blocks.{}.amaxList\".format(i,",
"0): # quant_max_processed = torch.full((kernel.size(1),), amax2.item(), dtype=amax2.dtype, device=amax2.device) # else:",
"1 amaxList[amax_id] = 127.0/amax amax_id += 1 amax = init_dict[\"layers.{}.{}._amax\".format(i,",
"= init_dict[\"layers.{}.blocks.{}.{}._weight_quantizer._amax\".format(i, depth, kernel_name)] amax2 = abs(quant_max2) # if (amax2.dim()",
"weight_quantize(kernel, amax2.cuda()) init_dict[\"layers.{}.blocks.{}.{}.weight\".format(i, depth, kernel_name)] = kernel_processed if kernel_name in",
"amax_id += 1 amaxList[amax_id] = amaxList[24] * amaxList[28] / (127.0",
"1: amaxList[amax_id] = init_dict[\"layers.{}.downsample.reduction._weight_quantizer._amax\".format(i)].item() amax_id += 1 assert amax_id ==",
"amax2 = abs(quant_max2) kernel = kernel.transpose(-1, -2).contiguous() kernel_processed = weight_quantize(kernel,",
"= 72 INT8O_KERNEL_NUM = 5 INT8O_GEMM_NUM = 7 TRT_FUSED_MHA_AMAX_NUM =",
"ACTIVATION_AMAX_NUM for kernel_id, kernel_name in enumerate(kernel_name_list): kernel = init_dict[\"layers.{}.blocks.{}.{}.weight\".format(i, depth,",
"amax/127.0 amax_id += 1 amaxList[amax_id] = amax/127.0/127.0 amax_id += 1",
"range(depths[i]): amaxList = np.zeros([amaxTotalNum]).astype(np.float32) amax_id = 0 for amax_name in",
"INT8O_KERNEL_NUM + INT8O_GEMM_NUM amax_id += 1 #for trt fused MHA",
"kernel = init_dict[\"layers.{}.downsample.reduction.weight\".format(i)] quant_max2 = init_dict[\"layers.{}.downsample.reduction._weight_quantizer._amax\".format(i)] amax2 = abs(quant_max2) kernel",
"# print(\"Quantizing checkpoint done.\") return init_dict if __name__ == '__main__':",
"kernel = kernel.transpose(-1, -2).contiguous() kernel_processed = weight_quantize(kernel, amax2.cuda()) init_dict[\"layers.{}.downsample.reduction.weight\".format(i)] =",
"# if (amax2.dim() == 0): # quant_max_processed = torch.full((kernel.size(1),), amax2.item(),",
"amax_id += 1 amaxList[amax_id] = 127.0/amax amax_id += 1 amax",
"# print('layernum:', i, 'j:', j, ' gemm_int8IO_scale:',amaxList[amax_id]) # print(int8O_gemm_input_amax_list[j], int8O_gemm_weight_amax_list[j],",
"+= 1 # if verbose: # print(i, amax_name) # print('quant_max:',",
"= (patchMerge_i * patchMerge_w) / (127 * patchMerge_o) amax_id +=",
"SCALE_RESERVE_NUM = 8 def extract_amaxlist(init_dict, depths, ths_path='../lib/libpyt_swintransformer.so', verbose=True): # print(\"Quantizing",
"in range(INT8O_GEMM_NUM)] int8O_gemm_output_list = [\"attn.qkv._aftergemm_quantizer\", \"attn.proj._aftergemm_quantizer\", \"mlp.fc1._aftergemm_quantizer\", \"mlp.fc2._aftergemm_quantizer\", \"attn.softmax_input_quantizer\", \"attn.proj._input_quantizer\"]",
"import numpy as np import torch ACTIVATION_AMAX_NUM = 72 INT8O_KERNEL_NUM",
"+= 1 # if verbose: # print(i, kernel_name) # print('kernel:',",
"in range(INT8O_GEMM_NUM)] int8O_gemm_input_list = [\"attn.qkv._input_quantizer\", \"attn.proj._input_quantizer\", \"mlp.fc1._input_quantizer\", \"mlp.fc2._input_quantizer\", \"attn.matmul_q_input_quantizer\", \"attn.matmul_a_input_quantizer\"]",
"OF ANY KIND, either express or implied. # See the",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"depth, kernel_name)].transpose(-1, -2).contiguous() quant_max2 = init_dict[\"layers.{}.blocks.{}.{}._weight_quantizer._amax\".format(i, depth, kernel_name)] amax2 =",
"__name__ == '__main__': weights = torch.load('pytorch_model.bin') extract_amaxlist(weights, [2, 2, 6,",
"ANY KIND, either express or implied. # See the License",
"See the License for the specific language governing permissions and",
"downsample_input)].item() patchMerge_w = init_dict[\"layers.{}.{}._amax\".format(i, downsample_weight)].item() patchMerge_o = init_dict[\"layers.{}.{}._amax\".format(i, downsample_out)].item() amaxList[amax_id]",
"1 assert amax_id == ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM + INT8O_GEMM_NUM amax_id",
"for amax_name in amax_name_list: quant_max = init_dict[\"layers.{}.blocks.{}.{}._amax\".format(i, depth, amax_name)].item() amax",
"the License. # You may obtain a copy of the",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"for the specific language governing permissions and # limitations under",
"depth)] = torch.tensor(amaxList, dtype=torch.float32) if verbose: print(\"done process layer_{} block_{}",
"to in writing, software # distributed under the License is",
"1 amaxList[amax_id] = amax/127.0 amax_id += 1 amaxList[amax_id] = amax/127.0/127.0",
"+ INT8O_GEMM_NUM amax_id += 1 #for trt fused MHA amax",
"# See the License for the specific language governing permissions",
"= abs(quant_max2) # if (amax2.dim() == 0): # quant_max_processed =",
"= 3 SCALE_RESERVE_NUM = 8 def extract_amaxlist(init_dict, depths, ths_path='../lib/libpyt_swintransformer.so', verbose=True):",
"i != layer_num - 1: amax = init_dict[\"layers.{}.{}._amax\".format(i, downsample_input)].item() amaxList[amax_id]",
"INT8O_GEMM_NUM = 7 TRT_FUSED_MHA_AMAX_NUM = 3 SCALE_RESERVE_NUM = 8 def",
"* amaxList[20] / (127.0 * 127.0) amax_id += 1 amaxList[amax_id]",
"or agreed to in writing, software # distributed under the",
"required by applicable law or agreed to in writing, software",
"amax_name) # print('quant_max:', quant_max) # print('amax:', amax) if i !=",
"\"attn.matmul_v_input_quantizer\", \"attn.matmul_a_input_quantizer\", \"attn.softmax_input_quantizer\", \"mlp.fc1._input_quantizer\", \"mlp.fc1._aftergemm_quantizer\", \"mlp.fc2._input_quantizer\", \"mlp.fc2._aftergemm_quantizer\", \"add1_residual_input_quantizer\", \"add2_residual_input_quantizer\" ]",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"with the License. # You may obtain a copy of",
"amaxList[16] * amaxList[20] / (127.0 * 127.0) amax_id += 1",
"amax2.cuda()) init_dict[\"layers.{}.downsample.reduction.weight\".format(i)] = kernel_processed # print(\"Quantizing checkpoint done.\") return init_dict",
"ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM + INT8O_GEMM_NUM amax_id += 1 #for trt",
"!= layer_num - 1: amax = init_dict[\"layers.{}.{}._amax\".format(i, downsample_input)].item() amaxList[amax_id] =",
"# limitations under the License. import sys import argparse import",
"+ SCALE_RESERVE_NUM kernel_name_list = [\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\"] amax_name_list =",
"[0 for i in range(INT8O_GEMM_NUM)] int8O_gemm_output_list = [\"attn.qkv._aftergemm_quantizer\", \"attn.proj._aftergemm_quantizer\", \"mlp.fc1._aftergemm_quantizer\",",
"compliance with the License. # You may obtain a copy",
"ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM #for int8O gemm deQuant for j in",
"agreed to in writing, software # distributed under the License",
"\"attn.matmul_q_input_quantizer\", \"attn.matmul_a_input_quantizer\"] int8O_gemm_output_amax_list = [0 for i in range(INT8O_GEMM_NUM)] int8O_gemm_output_list",
"= \"downsample.reduction._aftergemm_quantizer\" factor = 1000000.0 for i in range(layer_num): for",
"quant_max2 = init_dict[\"layers.{}.blocks.{}.{}._weight_quantizer._amax\".format(i, depth, kernel_name)] amax2 = abs(quant_max2) # if",
"1 qkvMax = np.maximum(np.maximum(amaxList[16],amaxList[20]), amaxList[24]) amaxList[amax_id] = amaxList[16] * amaxList[20]",
"downsample_input)].item() amaxList[amax_id] = amax amax_id += 1 amaxList[amax_id] = amax/127.0",
"distributed under the License is distributed on an \"AS IS\"",
"amax_id += 1 amaxList[amax_id] = 127.0/amax amax_id += 1 #",
"# amax_id += 1 qkvMax = np.maximum(np.maximum(amaxList[16],amaxList[20]), amaxList[24]) amaxList[amax_id] =",
"amax_id = ACTIVATION_AMAX_NUM for kernel_id, kernel_name in enumerate(kernel_name_list): kernel =",
"depth, kernel_name)] = kernel_processed if kernel_name in int8O_gemm_weight_list: int8O_gemm_weight_amax_list[int8O_gemm_weight_list.index(kernel_name)] =",
"= (int8O_gemm_input_amax_list[j]*int8O_gemm_weight_amax_list[j])/(127.0*int8O_gemm_output_amax_list[j]) # print('layernum:', i, 'j:', j, ' gemm_int8IO_scale:',amaxList[amax_id]) #",
"init_dict[\"layers.{}.blocks.{}.{}._weight_quantizer._amax\".format(i, depth, kernel_name)] amax2 = abs(quant_max2) # if (amax2.dim() ==",
"for i in range(INT8O_GEMM_NUM)] int8O_gemm_weight_list = [\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\",",
"amax2.view(-1) kernel_processed = weight_quantize(kernel, amax2.cuda()) init_dict[\"layers.{}.blocks.{}.{}.weight\".format(i, depth, kernel_name)] = kernel_processed",
"/ (127 * patchMerge_o) amax_id += 1 assert amax_id ==",
"express or implied. # See the License for the specific",
"kernel_name)].transpose(-1, -2).contiguous() quant_max2 = init_dict[\"layers.{}.blocks.{}.{}._weight_quantizer._amax\".format(i, depth, kernel_name)] amax2 = abs(quant_max2)",
"except in compliance with the License. # You may obtain",
"'j:', j, ' gemm_int8IO_scale:',amaxList[amax_id]) # print(int8O_gemm_input_amax_list[j], int8O_gemm_weight_amax_list[j], int8O_gemm_output_amax_list[j]) amax_id +=",
"amax #### QKV_addBias_amax # amaxList[amax_id] = np.maximum(np.maximum(amaxList[16],amaxList[20]), amaxList[24]) # amax_id",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"\"mlp.fc2._aftergemm_quantizer\", \"add1_residual_input_quantizer\", \"add2_residual_input_quantizer\" ] int8O_gemm_weight_amax_list = [0 for i in",
"not use this file except in compliance with the License.",
"= abs(quant_max)#round(abs(quant_max)*factor)/factor if amax_name in int8O_gemm_input_list: int8O_gemm_input_amax_list[int8O_gemm_input_list.index(amax_name)] = amax if",
"as np import torch ACTIVATION_AMAX_NUM = 72 INT8O_KERNEL_NUM = 5",
"downsample_weight)].item() patchMerge_o = init_dict[\"layers.{}.{}._amax\".format(i, downsample_out)].item() amaxList[amax_id] = (patchMerge_i * patchMerge_w)",
"patchMerge_o) amax_id += 1 assert amax_id == ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM",
"block_{} kernel weight\".format(i, depth)) if i != layer_num - 1:",
"= weight_quantize(kernel, amax2.cuda()) init_dict[\"layers.{}.blocks.{}.{}.weight\".format(i, depth, kernel_name)] = kernel_processed if kernel_name",
"abs(quant_max)#round(abs(quant_max)*factor)/factor if amax_name in int8O_gemm_input_list: int8O_gemm_input_amax_list[int8O_gemm_input_list.index(amax_name)] = amax if amax_name",
"writing, software # distributed under the License is distributed on",
"print(\"Quantizing checkpoint ...\") torch.classes.load_library(ths_path) weight_quantize = torch.ops.fastertransformer.swin_weight_quantize layer_num = len(depths)",
"verbose: print(\"done process layer_{} block_{} kernel weight\".format(i, depth)) if i",
"you may not use this file except in compliance with",
"depth, kernel_name)] amax2 = abs(quant_max2) # if (amax2.dim() == 0):",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"print('quant_max:', quant_max) # print('amax:', amax) if i != layer_num -",
"127.0/amax amax_id += 1 amax = init_dict[\"layers.{}.{}._amax\".format(i, downsample_out)].item() amaxList[amax_id] =",
"\"attn.proj._input_quantizer\", \"attn.proj._aftergemm_quantizer\", \"attn.matmul_q_input_quantizer\", \"attn.matmul_k_input_quantizer\", \"attn.matmul_v_input_quantizer\", \"attn.matmul_a_input_quantizer\", \"attn.softmax_input_quantizer\", \"mlp.fc1._input_quantizer\", \"mlp.fc1._aftergemm_quantizer\", \"mlp.fc2._input_quantizer\",",
"init_dict[\"layers.{}.blocks.{}.{}.weight\".format(i, depth, kernel_name)] = kernel_processed if kernel_name in int8O_gemm_weight_list: int8O_gemm_weight_amax_list[int8O_gemm_weight_list.index(kernel_name)]",
"amax_id = 0 for amax_name in amax_name_list: quant_max = init_dict[\"layers.{}.blocks.{}.{}._amax\".format(i,",
"amax_name in amax_name_list: quant_max = init_dict[\"layers.{}.blocks.{}.{}._amax\".format(i, depth, amax_name)].item() amax =",
"amax_id += 8 if verbose: print(\"done process layer_{} block_{} activation",
"int8O_gemm_output_list: int8O_gemm_output_amax_list[int8O_gemm_output_list.index(amax_name)] = amax if amax_name in int8O_gemm_weight_list: int8O_gemm_weight_amax_list[int8O_gemm_weight_list.index(amax_name)] =",
"depth)) if i != layer_num - 1: kernel = init_dict[\"layers.{}.downsample.reduction.weight\".format(i)]",
"if i != layer_num - 1: patchMerge_i = init_dict[\"layers.{}.{}._amax\".format(i, downsample_input)].item()",
"quant_max2) # print('quant_max_processed_:', quant_max_processed) if i != layer_num - 1:",
"for i in range(layer_num): for depth in range(depths[i]): amaxList =",
"torch ACTIVATION_AMAX_NUM = 72 INT8O_KERNEL_NUM = 5 INT8O_GEMM_NUM = 7",
"= torch.full((kernel.size(1),), amax2.item(), dtype=amax2.dtype, device=amax2.device) # else: # quant_max_processed =",
"1 amaxList[amax_id] = amaxList[24] * amaxList[28] / (127.0 * amaxList[8])",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"the License. import sys import argparse import re import numpy",
"amax_id += 1 # #### softmax amax # amaxList[amax_id] =",
"for depth in range(depths[i]): amaxList = np.zeros([amaxTotalNum]).astype(np.float32) amax_id = 0",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"amax2 = abs(quant_max2) # if (amax2.dim() == 0): # quant_max_processed",
"if i != layer_num - 1: amaxList[amax_id] = init_dict[\"layers.{}.downsample.reduction._weight_quantizer._amax\".format(i)].item() amax_id",
"= amax if amax_name in int8O_gemm_weight_list: int8O_gemm_weight_amax_list[int8O_gemm_weight_list.index(amax_name)] = amax amaxList[amax_id]",
"layer_num - 1: amaxList[amax_id] = init_dict[\"layers.{}.downsample.reduction._weight_quantizer._amax\".format(i)].item() amax_id += 1 assert",
"#### softmax amax # amaxList[amax_id] = amaxList[28] # amax_id +=",
"1 amaxList[amax_id] = amax/127.0/127.0 amax_id += 1 amaxList[amax_id] = 127.0/amax",
"amaxList[amax_id] = amax/127.0/127.0 amax_id += 1 amaxList[amax_id] = 127.0/amax amax_id",
"amaxList[24] * amaxList[28] / (127.0 * amaxList[8]) amax_id += 1",
"3 SCALE_RESERVE_NUM = 8 def extract_amaxlist(init_dict, depths, ths_path='../lib/libpyt_swintransformer.so', verbose=True): #",
"in amax_name_list: quant_max = init_dict[\"layers.{}.blocks.{}.{}._amax\".format(i, depth, amax_name)].item() amax = abs(quant_max)#round(abs(quant_max)*factor)/factor",
"amax_id += 1 else: amax_id += 8 if verbose: print(\"done",
"int8O_gemm_input_amax_list[int8O_gemm_input_list.index(amax_name)] = amax if amax_name in int8O_gemm_output_list: int8O_gemm_output_amax_list[int8O_gemm_output_list.index(amax_name)] = amax",
"= kernel_processed if kernel_name in int8O_gemm_weight_list: int8O_gemm_weight_amax_list[int8O_gemm_weight_list.index(kernel_name)] = amax2.item() amaxList[amax_id]",
"= ACTIVATION_AMAX_NUM for kernel_id, kernel_name in enumerate(kernel_name_list): kernel = init_dict[\"layers.{}.blocks.{}.{}.weight\".format(i,",
"\"mlp.fc2._input_quantizer\", \"mlp.fc2._aftergemm_quantizer\", \"add1_residual_input_quantizer\", \"add2_residual_input_quantizer\" ] int8O_gemm_weight_amax_list = [0 for i",
"\"mlp.fc1._aftergemm_quantizer\", \"mlp.fc2._input_quantizer\", \"mlp.fc2._aftergemm_quantizer\", \"add1_residual_input_quantizer\", \"add2_residual_input_quantizer\" ] int8O_gemm_weight_amax_list = [0 for",
"i != layer_num - 1: kernel = init_dict[\"layers.{}.downsample.reduction.weight\".format(i)] quant_max2 =",
"in int8O_gemm_weight_list: int8O_gemm_weight_amax_list[int8O_gemm_weight_list.index(kernel_name)] = amax2.item() amaxList[amax_id] = amax2 amax_id +=",
"downsample_weight = \"downsample.reduction._weight_quantizer\" downsample_out = \"downsample.reduction._aftergemm_quantizer\" factor = 1000000.0 for",
"layer_num - 1: kernel = init_dict[\"layers.{}.downsample.reduction.weight\".format(i)] quant_max2 = init_dict[\"layers.{}.downsample.reduction._weight_quantizer._amax\".format(i)] amax2",
"kernel_name in enumerate(kernel_name_list): kernel = init_dict[\"layers.{}.blocks.{}.{}.weight\".format(i, depth, kernel_name)].transpose(-1, -2).contiguous() quant_max2",
"INT8O_KERNEL_NUM = 5 INT8O_GEMM_NUM = 7 TRT_FUSED_MHA_AMAX_NUM = 3 SCALE_RESERVE_NUM",
"[0 for i in range(INT8O_GEMM_NUM)] int8O_gemm_input_list = [\"attn.qkv._input_quantizer\", \"attn.proj._input_quantizer\", \"mlp.fc1._input_quantizer\",",
"amaxList[28] amax_id += 1 amaxList[amax_id] = amaxList[24] * amaxList[28] /",
"1 amaxList[amax_id] = 127.0/amax amax_id += 1 else: amax_id +=",
"process layer_{} block_{} activation amax\".format(i, depth)) #kernel amax starts from",
"governing permissions and # limitations under the License. import sys",
"amax2.item() amaxList[amax_id] = amax2 amax_id += 1 # if verbose:",
"amaxList[amax_id] = 127.0/amax amax_id += 1 # if verbose: #",
"5 INT8O_GEMM_NUM = 7 TRT_FUSED_MHA_AMAX_NUM = 3 SCALE_RESERVE_NUM = 8",
"amax = init_dict[\"layers.{}.{}._amax\".format(i, downsample_input)].item() amaxList[amax_id] = amax amax_id += 1",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"\"attn.softmax_input_quantizer\", \"attn.proj._input_quantizer\"] downsample_input = \"downsample.reduction._input_quantizer\" downsample_weight = \"downsample.reduction._weight_quantizer\" downsample_out =",
"amax_id += 1 amax = init_dict[\"layers.{}.{}._amax\".format(i, downsample_out)].item() amaxList[amax_id] = amax",
"[0 for i in range(INT8O_GEMM_NUM)] int8O_gemm_weight_list = [\"attn.qkv\", \"attn.proj\", \"mlp.fc1\",",
"the License is distributed on an \"AS IS\" BASIS, #",
"# amaxList[amax_id] = np.maximum(np.maximum(amaxList[16],amaxList[20]), amaxList[24]) # amax_id += 1 #",
"dtype=amax2.dtype, device=amax2.device) # else: # quant_max_processed = amax2.view(-1) kernel_processed =",
"in range(layer_num): for depth in range(depths[i]): amaxList = np.zeros([amaxTotalNum]).astype(np.float32) amax_id",
"int8O_gemm_weight_amax_list[int8O_gemm_weight_list.index(kernel_name)] = amax2.item() amaxList[amax_id] = amax2 amax_id += 1 #",
"print(\"done process layer_{} block_{} activation amax\".format(i, depth)) #kernel amax starts",
"print('quant_max2:', quant_max2) # print('quant_max_processed_:', quant_max_processed) if i != layer_num -",
"+ INT8O_KERNEL_NUM + INT8O_GEMM_NUM + 1 + TRT_FUSED_MHA_AMAX_NUM + SCALE_RESERVE_NUM",
"argparse import re import numpy as np import torch ACTIVATION_AMAX_NUM",
"in int8O_gemm_input_list: int8O_gemm_input_amax_list[int8O_gemm_input_list.index(amax_name)] = amax if amax_name in int8O_gemm_output_list: int8O_gemm_output_amax_list[int8O_gemm_output_list.index(amax_name)]",
"sys import argparse import re import numpy as np import",
"1 # if verbose: # print(i, amax_name) # print('quant_max:', quant_max)",
"amax_name_list: quant_max = init_dict[\"layers.{}.blocks.{}.{}._amax\".format(i, depth, amax_name)].item() amax = abs(quant_max)#round(abs(quant_max)*factor)/factor if",
"127.0/amax amax_id += 1 else: amax_id += 8 if verbose:",
"depth)) #kernel amax starts from ACTIVATION_AMAX_NUM assert amax_id == 68",
"1 + TRT_FUSED_MHA_AMAX_NUM + SCALE_RESERVE_NUM kernel_name_list = [\"attn.qkv\", \"attn.proj\", \"mlp.fc1\",",
"amaxList[amax_id] = np.maximum(np.maximum(amaxList[16],amaxList[20]), amaxList[24]) # amax_id += 1 # ####",
"amax_id += 1 # #### bmm2 amax # amaxList[amax_id] =",
"i in range(INT8O_GEMM_NUM)] int8O_gemm_output_list = [\"attn.qkv._aftergemm_quantizer\", \"attn.proj._aftergemm_quantizer\", \"mlp.fc1._aftergemm_quantizer\", \"mlp.fc2._aftergemm_quantizer\", \"attn.softmax_input_quantizer\",",
"\"mlp.fc1._aftergemm_quantizer\", \"mlp.fc2._aftergemm_quantizer\", \"attn.softmax_input_quantizer\", \"attn.proj._input_quantizer\"] downsample_input = \"downsample.reduction._input_quantizer\" downsample_weight = \"downsample.reduction._weight_quantizer\"",
"= amax2.view(-1) kernel_processed = weight_quantize(kernel, amax2.cuda()) init_dict[\"layers.{}.blocks.{}.{}.weight\".format(i, depth, kernel_name)] =",
"1 # if verbose: # print(i, kernel_name) # print('kernel:', kernel)",
"\"mlp.fc1._input_quantizer\", \"mlp.fc1._aftergemm_quantizer\", \"mlp.fc2._input_quantizer\", \"mlp.fc2._aftergemm_quantizer\", \"add1_residual_input_quantizer\", \"add2_residual_input_quantizer\" ] int8O_gemm_weight_amax_list = [0",
"law or agreed to in writing, software # distributed under",
"= np.maximum(np.maximum(amaxList[16],amaxList[20]), amaxList[24]) # amax_id += 1 # #### softmax",
"factor = 1000000.0 for i in range(layer_num): for depth in",
"amaxList[amax_id] = 127.0/amax amax_id += 1 amax = init_dict[\"layers.{}.{}._amax\".format(i, downsample_out)].item()",
"# amax_id += 1 # #### bmm2 amax # amaxList[amax_id]",
"1 amaxList[amax_id] = 127.0/amax amax_id += 1 # if verbose:",
"dtype=torch.float32) if verbose: print(\"done process layer_{} block_{} kernel weight\".format(i, depth))",
"if i != layer_num - 1: amax = init_dict[\"layers.{}.{}._amax\".format(i, downsample_input)].item()",
"\"attn.proj\", \"mlp.fc1\", \"mlp.fc2\", \"attn.matmul_k_input_quantizer\", \"attn.matmul_v_input_quantizer\"] int8O_gemm_input_amax_list = [0 for i",
"= [0 for i in range(INT8O_GEMM_NUM)] int8O_gemm_output_list = [\"attn.qkv._aftergemm_quantizer\", \"attn.proj._aftergemm_quantizer\",",
"quant_max_processed = torch.full((kernel.size(1),), amax2.item(), dtype=amax2.dtype, device=amax2.device) # else: # quant_max_processed",
"...\") torch.classes.load_library(ths_path) weight_quantize = torch.ops.fastertransformer.swin_weight_quantize layer_num = len(depths) amaxTotalNum =",
"+= 1 amax = init_dict[\"layers.{}.{}._amax\".format(i, downsample_out)].item() amaxList[amax_id] = amax amax_id",
"for i in range(INT8O_GEMM_NUM)] int8O_gemm_output_list = [\"attn.qkv._aftergemm_quantizer\", \"attn.proj._aftergemm_quantizer\", \"mlp.fc1._aftergemm_quantizer\", \"mlp.fc2._aftergemm_quantizer\",",
"torch.classes.load_library(ths_path) weight_quantize = torch.ops.fastertransformer.swin_weight_quantize layer_num = len(depths) amaxTotalNum = ACTIVATION_AMAX_NUM",
"amax_id += 1 assert amax_id == ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM #for",
"= init_dict[\"layers.{}.downsample.reduction._weight_quantizer._amax\".format(i)].item() amax_id += 1 assert amax_id == ACTIVATION_AMAX_NUM +",
"= abs(quant_max2) kernel = kernel.transpose(-1, -2).contiguous() kernel_processed = weight_quantize(kernel, amax2.cuda())",
"deQuant for j in range(INT8O_GEMM_NUM - 1): amaxList[amax_id] = (int8O_gemm_input_amax_list[j]*int8O_gemm_weight_amax_list[j])/(127.0*int8O_gemm_output_amax_list[j])",
"may obtain a copy of the License at # #",
"\"attn.softmax_input_quantizer\", \"mlp.fc1._input_quantizer\", \"mlp.fc1._aftergemm_quantizer\", \"mlp.fc2._input_quantizer\", \"mlp.fc2._aftergemm_quantizer\", \"add1_residual_input_quantizer\", \"add2_residual_input_quantizer\" ] int8O_gemm_weight_amax_list =",
"init_dict[\"layers.{}.blocks.{}.{}.weight\".format(i, depth, kernel_name)].transpose(-1, -2).contiguous() quant_max2 = init_dict[\"layers.{}.blocks.{}.{}._weight_quantizer._amax\".format(i, depth, kernel_name)] amax2",
"downsample_out)].item() amaxList[amax_id] = (patchMerge_i * patchMerge_w) / (127 * patchMerge_o)",
"-2).contiguous() kernel_processed = weight_quantize(kernel, amax2.cuda()) init_dict[\"layers.{}.downsample.reduction.weight\".format(i)] = kernel_processed # print(\"Quantizing",
"+= 1 amaxList[amax_id] = 127.0/amax amax_id += 1 amax =",
"layer_num - 1: patchMerge_i = init_dict[\"layers.{}.{}._amax\".format(i, downsample_input)].item() patchMerge_w = init_dict[\"layers.{}.{}._amax\".format(i,",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"+= 1 # #### bmm2 amax # amaxList[amax_id] = amaxList[8]",
"= 0 for amax_name in amax_name_list: quant_max = init_dict[\"layers.{}.blocks.{}.{}._amax\".format(i, depth,",
"print('layernum:', i, 'j:', j, ' gemm_int8IO_scale:',amaxList[amax_id]) # print(int8O_gemm_input_amax_list[j], int8O_gemm_weight_amax_list[j], int8O_gemm_output_amax_list[j])",
"\"attn.matmul_a_input_quantizer\"] int8O_gemm_output_amax_list = [0 for i in range(INT8O_GEMM_NUM)] int8O_gemm_output_list =",
"may not use this file except in compliance with the",
"# print(i, amax_name) # print('quant_max:', quant_max) # print('amax:', amax) if",
"= 127.0/amax amax_id += 1 # if verbose: # print(i,",
"verbose: print(\"done process layer_{} block_{} activation amax\".format(i, depth)) #kernel amax",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"amaxList[amax_id] = amax/127.0 amax_id += 1 amaxList[amax_id] = amax/127.0/127.0 amax_id",
"\"mlp.fc2._aftergemm_quantizer\", \"attn.softmax_input_quantizer\", \"attn.proj._input_quantizer\"] downsample_input = \"downsample.reduction._input_quantizer\" downsample_weight = \"downsample.reduction._weight_quantizer\" downsample_out",
"amax2 amax_id += 1 # if verbose: # print(i, kernel_name)",
"this file except in compliance with the License. # You",
"ths_path='../lib/libpyt_swintransformer.so', verbose=True): # print(\"Quantizing checkpoint ...\") torch.classes.load_library(ths_path) weight_quantize = torch.ops.fastertransformer.swin_weight_quantize",
"!= layer_num - 1: patchMerge_i = init_dict[\"layers.{}.{}._amax\".format(i, downsample_input)].item() patchMerge_w =",
"+ INT8O_KERNEL_NUM #for int8O gemm deQuant for j in range(INT8O_GEMM_NUM",
"1 # #### softmax amax # amaxList[amax_id] = amaxList[28] #",
"License. import sys import argparse import re import numpy as",
"MHA amax #### QKV_addBias_amax # amaxList[amax_id] = np.maximum(np.maximum(amaxList[16],amaxList[20]), amaxList[24]) #",
"+= 1 qkvMax = np.maximum(np.maximum(amaxList[16],amaxList[20]), amaxList[24]) amaxList[amax_id] = amaxList[16] *",
"/ (127.0 * 127.0) amax_id += 1 amaxList[amax_id] = 127.0",
"amax/127.0/127.0 amax_id += 1 amaxList[amax_id] = 127.0/amax amax_id += 1",
"+= 8 if verbose: print(\"done process layer_{} block_{} activation amax\".format(i,",
"= [\"attn.qkv._input_quantizer\", \"attn.qkv._aftergemm_quantizer\", \"attn.proj._input_quantizer\", \"attn.proj._aftergemm_quantizer\", \"attn.matmul_q_input_quantizer\", \"attn.matmul_k_input_quantizer\", \"attn.matmul_v_input_quantizer\", \"attn.matmul_a_input_quantizer\", \"attn.softmax_input_quantizer\",",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"amaxList[amax_id] = (patchMerge_i * patchMerge_w) / (127 * patchMerge_o) amax_id",
"range(INT8O_GEMM_NUM)] int8O_gemm_output_list = [\"attn.qkv._aftergemm_quantizer\", \"attn.proj._aftergemm_quantizer\", \"mlp.fc1._aftergemm_quantizer\", \"mlp.fc2._aftergemm_quantizer\", \"attn.softmax_input_quantizer\", \"attn.proj._input_quantizer\"] downsample_input",
"amaxList[8] # amax_id += 1 qkvMax = np.maximum(np.maximum(amaxList[16],amaxList[20]), amaxList[24]) amaxList[amax_id]",
"(patchMerge_i * patchMerge_w) / (127 * patchMerge_o) amax_id += 1",
"# # Licensed under the Apache License, Version 2.0 (the",
"SCALE_RESERVE_NUM kernel_name_list = [\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\"] amax_name_list = [\"attn.qkv._input_quantizer\",",
"file except in compliance with the License. # You may",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"int8O_gemm_weight_amax_list[j], int8O_gemm_output_amax_list[j]) amax_id += 1 if i != layer_num -",
"= np.zeros([amaxTotalNum]).astype(np.float32) amax_id = 0 for amax_name in amax_name_list: quant_max",
"np.maximum(np.maximum(amaxList[16],amaxList[20]), amaxList[24]) amaxList[amax_id] = amaxList[16] * amaxList[20] / (127.0 *",
"# if verbose: # print(i, amax_name) # print('quant_max:', quant_max) #",
"int8O_gemm_weight_list: int8O_gemm_weight_amax_list[int8O_gemm_weight_list.index(amax_name)] = amax amaxList[amax_id] = amax amax_id += 1",
"== 0): # quant_max_processed = torch.full((kernel.size(1),), amax2.item(), dtype=amax2.dtype, device=amax2.device) #",
"== ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM #for int8O gemm deQuant for j",
"] int8O_gemm_weight_amax_list = [0 for i in range(INT8O_GEMM_NUM)] int8O_gemm_weight_list =",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"\"attn.proj._input_quantizer\"] downsample_input = \"downsample.reduction._input_quantizer\" downsample_weight = \"downsample.reduction._weight_quantizer\" downsample_out = \"downsample.reduction._aftergemm_quantizer\"",
"= init_dict[\"layers.{}.{}._amax\".format(i, downsample_out)].item() amaxList[amax_id] = (patchMerge_i * patchMerge_w) / (127",
"def extract_amaxlist(init_dict, depths, ths_path='../lib/libpyt_swintransformer.so', verbose=True): # print(\"Quantizing checkpoint ...\") torch.classes.load_library(ths_path)",
"import re import numpy as np import torch ACTIVATION_AMAX_NUM =",
"= [0 for i in range(INT8O_GEMM_NUM)] int8O_gemm_input_list = [\"attn.qkv._input_quantizer\", \"attn.proj._input_quantizer\",",
"rights reserved. # # Licensed under the Apache License, Version",
"* patchMerge_o) amax_id += 1 assert amax_id == ACTIVATION_AMAX_NUM +",
"in range(INT8O_GEMM_NUM)] int8O_gemm_weight_list = [\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\", \"attn.matmul_k_input_quantizer\", \"attn.matmul_v_input_quantizer\"]",
"int8O_gemm_input_list: int8O_gemm_input_amax_list[int8O_gemm_input_list.index(amax_name)] = amax if amax_name in int8O_gemm_output_list: int8O_gemm_output_amax_list[int8O_gemm_output_list.index(amax_name)] =",
"layer_{} block_{} activation amax\".format(i, depth)) #kernel amax starts from ACTIVATION_AMAX_NUM",
"#kernel amax starts from ACTIVATION_AMAX_NUM assert amax_id == 68 amax_id",
"init_dict[\"layers.{}.{}._amax\".format(i, downsample_input)].item() patchMerge_w = init_dict[\"layers.{}.{}._amax\".format(i, downsample_weight)].item() patchMerge_o = init_dict[\"layers.{}.{}._amax\".format(i, downsample_out)].item()",
"in range(INT8O_GEMM_NUM - 1): amaxList[amax_id] = (int8O_gemm_input_amax_list[j]*int8O_gemm_weight_amax_list[j])/(127.0*int8O_gemm_output_amax_list[j]) # print('layernum:', i,",
"int8O_gemm_weight_amax_list = [0 for i in range(INT8O_GEMM_NUM)] int8O_gemm_weight_list = [\"attn.qkv\",",
"amax_id += 1 init_dict[\"layers.{}.blocks.{}.amaxList\".format(i, depth)] = torch.tensor(amaxList, dtype=torch.float32) if verbose:",
"import argparse import re import numpy as np import torch",
"amaxList[amax_id] = amaxList[8] # amax_id += 1 qkvMax = np.maximum(np.maximum(amaxList[16],amaxList[20]),",
"language governing permissions and # limitations under the License. import",
"init_dict[\"layers.{}.downsample.reduction.weight\".format(i)] quant_max2 = init_dict[\"layers.{}.downsample.reduction._weight_quantizer._amax\".format(i)] amax2 = abs(quant_max2) kernel = kernel.transpose(-1,",
"amaxList[amax_id] = amaxList[24] * amaxList[28] / (127.0 * amaxList[8]) amax_id",
"1000000.0 for i in range(layer_num): for depth in range(depths[i]): amaxList",
"= amax if amax_name in int8O_gemm_output_list: int8O_gemm_output_amax_list[int8O_gemm_output_list.index(amax_name)] = amax if",
"layer_num - 1: amax = init_dict[\"layers.{}.{}._amax\".format(i, downsample_input)].item() amaxList[amax_id] = amax",
"= init_dict[\"layers.{}.{}._amax\".format(i, downsample_input)].item() amaxList[amax_id] = amax amax_id += 1 amaxList[amax_id]",
"1 amaxList[amax_id] = 127.0 / amaxList[28] amax_id += 1 amaxList[amax_id]",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"if verbose: print(\"done process layer_{} block_{} activation amax\".format(i, depth)) #kernel",
"= [0 for i in range(INT8O_GEMM_NUM)] int8O_gemm_weight_list = [\"attn.qkv\", \"attn.proj\",",
"\"add2_residual_input_quantizer\" ] int8O_gemm_weight_amax_list = [0 for i in range(INT8O_GEMM_NUM)] int8O_gemm_weight_list",
"1 #for trt fused MHA amax #### QKV_addBias_amax # amaxList[amax_id]",
"amaxList[amax_id] = amax amax_id += 1 amaxList[amax_id] = amax/127.0 amax_id",
"kernel_name)] = kernel_processed if kernel_name in int8O_gemm_weight_list: int8O_gemm_weight_amax_list[int8O_gemm_weight_list.index(kernel_name)] = amax2.item()",
"amaxList[8]) amax_id += 1 init_dict[\"layers.{}.blocks.{}.amaxList\".format(i, depth)] = torch.tensor(amaxList, dtype=torch.float32) if",
"i in range(INT8O_GEMM_NUM)] int8O_gemm_input_list = [\"attn.qkv._input_quantizer\", \"attn.proj._input_quantizer\", \"mlp.fc1._input_quantizer\", \"mlp.fc2._input_quantizer\", \"attn.matmul_q_input_quantizer\",",
"or implied. # See the License for the specific language",
"return init_dict if __name__ == '__main__': weights = torch.load('pytorch_model.bin') extract_amaxlist(weights,",
"= init_dict[\"layers.{}.{}._amax\".format(i, downsample_out)].item() amaxList[amax_id] = amax amax_id += 1 amaxList[amax_id]",
"= 7 TRT_FUSED_MHA_AMAX_NUM = 3 SCALE_RESERVE_NUM = 8 def extract_amaxlist(init_dict,",
"KIND, either express or implied. # See the License for",
"specific language governing permissions and # limitations under the License.",
"if amax_name in int8O_gemm_input_list: int8O_gemm_input_amax_list[int8O_gemm_input_list.index(amax_name)] = amax if amax_name in",
"QKV_addBias_amax # amaxList[amax_id] = np.maximum(np.maximum(amaxList[16],amaxList[20]), amaxList[24]) # amax_id += 1",
"#for trt fused MHA amax #### QKV_addBias_amax # amaxList[amax_id] =",
"print('amax:', amax) if i != layer_num - 1: amax =",
"INT8O_KERNEL_NUM #for int8O gemm deQuant for j in range(INT8O_GEMM_NUM -",
"# quant_max_processed = amax2.view(-1) kernel_processed = weight_quantize(kernel, amax2.cuda()) init_dict[\"layers.{}.blocks.{}.{}.weight\".format(i, depth,",
"\"downsample.reduction._weight_quantizer\" downsample_out = \"downsample.reduction._aftergemm_quantizer\" factor = 1000000.0 for i in",
"= amaxList[8] # amax_id += 1 qkvMax = np.maximum(np.maximum(amaxList[16],amaxList[20]), amaxList[24])",
"if i != layer_num - 1: kernel = init_dict[\"layers.{}.downsample.reduction.weight\".format(i)] quant_max2",
"= torch.ops.fastertransformer.swin_weight_quantize layer_num = len(depths) amaxTotalNum = ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM",
"if (amax2.dim() == 0): # quant_max_processed = torch.full((kernel.size(1),), amax2.item(), dtype=amax2.dtype,",
"init_dict[\"layers.{}.blocks.{}.{}._amax\".format(i, depth, amax_name)].item() amax = abs(quant_max)#round(abs(quant_max)*factor)/factor if amax_name in int8O_gemm_input_list:",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"\"attn.matmul_q_input_quantizer\", \"attn.matmul_k_input_quantizer\", \"attn.matmul_v_input_quantizer\", \"attn.matmul_a_input_quantizer\", \"attn.softmax_input_quantizer\", \"mlp.fc1._input_quantizer\", \"mlp.fc1._aftergemm_quantizer\", \"mlp.fc2._input_quantizer\", \"mlp.fc2._aftergemm_quantizer\", \"add1_residual_input_quantizer\",",
"+= 1 if i != layer_num - 1: patchMerge_i =",
"amax_id += 1 qkvMax = np.maximum(np.maximum(amaxList[16],amaxList[20]), amaxList[24]) amaxList[amax_id] = amaxList[16]",
"= amax2 amax_id += 1 # if verbose: # print(i,",
"+ INT8O_KERNEL_NUM + INT8O_GEMM_NUM amax_id += 1 #for trt fused",
"softmax amax # amaxList[amax_id] = amaxList[28] # amax_id += 1",
"quant_max_processed) if i != layer_num - 1: amaxList[amax_id] = init_dict[\"layers.{}.downsample.reduction._weight_quantizer._amax\".format(i)].item()",
"amax_id += 1 #for trt fused MHA amax #### QKV_addBias_amax",
"+ 1 + TRT_FUSED_MHA_AMAX_NUM + SCALE_RESERVE_NUM kernel_name_list = [\"attn.qkv\", \"attn.proj\",",
"(the \"License\"); # you may not use this file except",
"= amax amax_id += 1 amaxList[amax_id] = amax/127.0 amax_id +=",
"assert amax_id == ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM + INT8O_GEMM_NUM amax_id +=",
"np.maximum(np.maximum(amaxList[16],amaxList[20]), amaxList[24]) # amax_id += 1 # #### softmax amax",
"# you may not use this file except in compliance",
"fused MHA amax #### QKV_addBias_amax # amaxList[amax_id] = np.maximum(np.maximum(amaxList[16],amaxList[20]), amaxList[24])",
"range(layer_num): for depth in range(depths[i]): amaxList = np.zeros([amaxTotalNum]).astype(np.float32) amax_id =",
"amaxList[28] / (127.0 * amaxList[8]) amax_id += 1 init_dict[\"layers.{}.blocks.{}.amaxList\".format(i, depth)]",
"weight_quantize = torch.ops.fastertransformer.swin_weight_quantize layer_num = len(depths) amaxTotalNum = ACTIVATION_AMAX_NUM +",
"if verbose: # print(i, amax_name) # print('quant_max:', quant_max) # print('amax:',",
"abs(quant_max2) # if (amax2.dim() == 0): # quant_max_processed = torch.full((kernel.size(1),),",
"activation amax\".format(i, depth)) #kernel amax starts from ACTIVATION_AMAX_NUM assert amax_id",
"device=amax2.device) # else: # quant_max_processed = amax2.view(-1) kernel_processed = weight_quantize(kernel,",
"= \"downsample.reduction._weight_quantizer\" downsample_out = \"downsample.reduction._aftergemm_quantizer\" factor = 1000000.0 for i",
"kernel) # print('quant_max2:', quant_max2) # print('quant_max_processed_:', quant_max_processed) if i !=",
"# print('quant_max2:', quant_max2) # print('quant_max_processed_:', quant_max_processed) if i != layer_num",
"= \"downsample.reduction._input_quantizer\" downsample_weight = \"downsample.reduction._weight_quantizer\" downsample_out = \"downsample.reduction._aftergemm_quantizer\" factor =",
"= amaxList[16] * amaxList[20] / (127.0 * 127.0) amax_id +=",
"# # Unless required by applicable law or agreed to",
"1: kernel = init_dict[\"layers.{}.downsample.reduction.weight\".format(i)] quant_max2 = init_dict[\"layers.{}.downsample.reduction._weight_quantizer._amax\".format(i)] amax2 = abs(quant_max2)",
"\"add1_residual_input_quantizer\", \"add2_residual_input_quantizer\" ] int8O_gemm_weight_amax_list = [0 for i in range(INT8O_GEMM_NUM)]",
"amaxList = np.zeros([amaxTotalNum]).astype(np.float32) amax_id = 0 for amax_name in amax_name_list:",
"gemm_int8IO_scale:',amaxList[amax_id]) # print(int8O_gemm_input_amax_list[j], int8O_gemm_weight_amax_list[j], int8O_gemm_output_amax_list[j]) amax_id += 1 if i",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"amaxList[amax_id] = amaxList[28] # amax_id += 1 # #### bmm2",
"Version 2.0 (the \"License\"); # you may not use this",
"(amax2.dim() == 0): # quant_max_processed = torch.full((kernel.size(1),), amax2.item(), dtype=amax2.dtype, device=amax2.device)",
"# print('amax:', amax) if i != layer_num - 1: amax",
"amax if amax_name in int8O_gemm_output_list: int8O_gemm_output_amax_list[int8O_gemm_output_list.index(amax_name)] = amax if amax_name",
"torch.tensor(amaxList, dtype=torch.float32) if verbose: print(\"done process layer_{} block_{} kernel weight\".format(i,",
"init_dict[\"layers.{}.blocks.{}.amaxList\".format(i, depth)] = torch.tensor(amaxList, dtype=torch.float32) if verbose: print(\"done process layer_{}",
"amax = abs(quant_max)#round(abs(quant_max)*factor)/factor if amax_name in int8O_gemm_input_list: int8O_gemm_input_amax_list[int8O_gemm_input_list.index(amax_name)] = amax",
"+= 1 amaxList[amax_id] = 127.0/amax amax_id += 1 # if",
"else: # quant_max_processed = amax2.view(-1) kernel_processed = weight_quantize(kernel, amax2.cuda()) init_dict[\"layers.{}.blocks.{}.{}.weight\".format(i,",
"amax_id += 1 # if verbose: # print(i, amax_name) #",
"+= 1 assert amax_id == ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM + INT8O_GEMM_NUM",
"kernel_id, kernel_name in enumerate(kernel_name_list): kernel = init_dict[\"layers.{}.blocks.{}.{}.weight\".format(i, depth, kernel_name)].transpose(-1, -2).contiguous()",
"implied. # See the License for the specific language governing",
"\"attn.proj._input_quantizer\", \"mlp.fc1._input_quantizer\", \"mlp.fc2._input_quantizer\", \"attn.matmul_q_input_quantizer\", \"attn.matmul_a_input_quantizer\"] int8O_gemm_output_amax_list = [0 for i",
"ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM + INT8O_GEMM_NUM + 1 + TRT_FUSED_MHA_AMAX_NUM +",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"= 127.0 / amaxList[28] amax_id += 1 amaxList[amax_id] = amaxList[24]",
"+= 1 amaxList[amax_id] = amax/127.0/127.0 amax_id += 1 amaxList[amax_id] =",
"from ACTIVATION_AMAX_NUM assert amax_id == 68 amax_id = ACTIVATION_AMAX_NUM for",
"quant_max) # print('amax:', amax) if i != layer_num - 1:",
"\"mlp.fc2\", \"attn.matmul_k_input_quantizer\", \"attn.matmul_v_input_quantizer\"] int8O_gemm_input_amax_list = [0 for i in range(INT8O_GEMM_NUM)]",
"range(INT8O_GEMM_NUM)] int8O_gemm_weight_list = [\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\", \"attn.matmul_k_input_quantizer\", \"attn.matmul_v_input_quantizer\"] int8O_gemm_input_amax_list",
"init_dict[\"layers.{}.{}._amax\".format(i, downsample_weight)].item() patchMerge_o = init_dict[\"layers.{}.{}._amax\".format(i, downsample_out)].item() amaxList[amax_id] = (patchMerge_i *",
"\"attn.matmul_a_input_quantizer\", \"attn.softmax_input_quantizer\", \"mlp.fc1._input_quantizer\", \"mlp.fc1._aftergemm_quantizer\", \"mlp.fc2._input_quantizer\", \"mlp.fc2._aftergemm_quantizer\", \"add1_residual_input_quantizer\", \"add2_residual_input_quantizer\" ] int8O_gemm_weight_amax_list",
"= ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM + INT8O_GEMM_NUM + 1 + TRT_FUSED_MHA_AMAX_NUM",
"in int8O_gemm_weight_list: int8O_gemm_weight_amax_list[int8O_gemm_weight_list.index(amax_name)] = amax amaxList[amax_id] = amax amax_id +=",
"+= 1 amaxList[amax_id] = amax/127.0 amax_id += 1 amaxList[amax_id] =",
"np import torch ACTIVATION_AMAX_NUM = 72 INT8O_KERNEL_NUM = 5 INT8O_GEMM_NUM",
"= 1000000.0 for i in range(layer_num): for depth in range(depths[i]):",
"[\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\", \"attn.matmul_k_input_quantizer\", \"attn.matmul_v_input_quantizer\"] int8O_gemm_input_amax_list = [0 for",
"All rights reserved. # # Licensed under the Apache License,",
"by applicable law or agreed to in writing, software #",
"for j in range(INT8O_GEMM_NUM - 1): amaxList[amax_id] = (int8O_gemm_input_amax_list[j]*int8O_gemm_weight_amax_list[j])/(127.0*int8O_gemm_output_amax_list[j]) #",
"amax amaxList[amax_id] = amax amax_id += 1 amaxList[amax_id] = amax/127.0",
"1 if i != layer_num - 1: patchMerge_i = init_dict[\"layers.{}.{}._amax\".format(i,",
"= weight_quantize(kernel, amax2.cuda()) init_dict[\"layers.{}.downsample.reduction.weight\".format(i)] = kernel_processed # print(\"Quantizing checkpoint done.\")",
"and # limitations under the License. import sys import argparse",
"1 else: amax_id += 8 if verbose: print(\"done process layer_{}",
"in int8O_gemm_output_list: int8O_gemm_output_amax_list[int8O_gemm_output_list.index(amax_name)] = amax if amax_name in int8O_gemm_weight_list: int8O_gemm_weight_amax_list[int8O_gemm_weight_list.index(amax_name)]",
"- 1: amax = init_dict[\"layers.{}.{}._amax\".format(i, downsample_input)].item() amaxList[amax_id] = amax amax_id",
"amaxList[24]) # amax_id += 1 # #### softmax amax #",
"print('quant_max_processed_:', quant_max_processed) if i != layer_num - 1: amaxList[amax_id] =",
"INT8O_GEMM_NUM + 1 + TRT_FUSED_MHA_AMAX_NUM + SCALE_RESERVE_NUM kernel_name_list = [\"attn.qkv\",",
"/ amaxList[28] amax_id += 1 amaxList[amax_id] = amaxList[24] * amaxList[28]",
"68 amax_id = ACTIVATION_AMAX_NUM for kernel_id, kernel_name in enumerate(kernel_name_list): kernel",
"amax_id += 1 amaxList[amax_id] = amax/127.0 amax_id += 1 amaxList[amax_id]",
"import sys import argparse import re import numpy as np",
"\"attn.matmul_k_input_quantizer\", \"attn.matmul_v_input_quantizer\"] int8O_gemm_input_amax_list = [0 for i in range(INT8O_GEMM_NUM)] int8O_gemm_input_list",
"amax if amax_name in int8O_gemm_weight_list: int8O_gemm_weight_amax_list[int8O_gemm_weight_list.index(amax_name)] = amax amaxList[amax_id] =",
"= amax2.item() amaxList[amax_id] = amax2 amax_id += 1 # if",
"= 5 INT8O_GEMM_NUM = 7 TRT_FUSED_MHA_AMAX_NUM = 3 SCALE_RESERVE_NUM =",
"amax_id += 1 # if verbose: # print(i, kernel_name) #",
"print(\"Quantizing checkpoint done.\") return init_dict if __name__ == '__main__': weights",
"1 amax = init_dict[\"layers.{}.{}._amax\".format(i, downsample_out)].item() amaxList[amax_id] = amax amax_id +=",
"if verbose: # print(i, kernel_name) # print('kernel:', kernel) # print('quant_max2:',",
"amaxList[amax_id] = 127.0 / amaxList[28] amax_id += 1 amaxList[amax_id] =",
"amaxList[28] # amax_id += 1 # #### bmm2 amax #",
"downsample_out = \"downsample.reduction._aftergemm_quantizer\" factor = 1000000.0 for i in range(layer_num):",
"= 127.0/amax amax_id += 1 else: amax_id += 8 if",
"!= layer_num - 1: amaxList[amax_id] = init_dict[\"layers.{}.downsample.reduction._weight_quantizer._amax\".format(i)].item() amax_id += 1",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"Unless required by applicable law or agreed to in writing,",
"[\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\"] amax_name_list = [\"attn.qkv._input_quantizer\", \"attn.qkv._aftergemm_quantizer\", \"attn.proj._input_quantizer\", \"attn.proj._aftergemm_quantizer\",",
"= init_dict[\"layers.{}.downsample.reduction.weight\".format(i)] quant_max2 = init_dict[\"layers.{}.downsample.reduction._weight_quantizer._amax\".format(i)] amax2 = abs(quant_max2) kernel =",
"amax_id == ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM + INT8O_GEMM_NUM amax_id += 1",
"range(INT8O_GEMM_NUM - 1): amaxList[amax_id] = (int8O_gemm_input_amax_list[j]*int8O_gemm_weight_amax_list[j])/(127.0*int8O_gemm_output_amax_list[j]) # print('layernum:', i, 'j:',",
"amaxTotalNum = ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM + INT8O_GEMM_NUM + 1 +",
"the specific language governing permissions and # limitations under the",
"np.zeros([amaxTotalNum]).astype(np.float32) amax_id = 0 for amax_name in amax_name_list: quant_max =",
"# amaxList[amax_id] = amaxList[8] # amax_id += 1 qkvMax =",
"under the License. import sys import argparse import re import",
"amax) if i != layer_num - 1: amax = init_dict[\"layers.{}.{}._amax\".format(i,",
"applicable law or agreed to in writing, software # distributed",
"# print(\"Quantizing checkpoint ...\") torch.classes.load_library(ths_path) weight_quantize = torch.ops.fastertransformer.swin_weight_quantize layer_num =",
"permissions and # limitations under the License. import sys import",
"* amaxList[8]) amax_id += 1 init_dict[\"layers.{}.blocks.{}.amaxList\".format(i, depth)] = torch.tensor(amaxList, dtype=torch.float32)",
"import torch ACTIVATION_AMAX_NUM = 72 INT8O_KERNEL_NUM = 5 INT8O_GEMM_NUM =",
"127.0/amax amax_id += 1 # if verbose: # print(i, amax_name)",
"+= 1 amaxList[amax_id] = amaxList[24] * amaxList[28] / (127.0 *",
"patchMerge_o = init_dict[\"layers.{}.{}._amax\".format(i, downsample_out)].item() amaxList[amax_id] = (patchMerge_i * patchMerge_w) /",
"127.0) amax_id += 1 amaxList[amax_id] = 127.0 / amaxList[28] amax_id",
"in range(depths[i]): amaxList = np.zeros([amaxTotalNum]).astype(np.float32) amax_id = 0 for amax_name",
"= [\"attn.qkv._aftergemm_quantizer\", \"attn.proj._aftergemm_quantizer\", \"mlp.fc1._aftergemm_quantizer\", \"mlp.fc2._aftergemm_quantizer\", \"attn.softmax_input_quantizer\", \"attn.proj._input_quantizer\"] downsample_input = \"downsample.reduction._input_quantizer\"",
"trt fused MHA amax #### QKV_addBias_amax # amaxList[amax_id] = np.maximum(np.maximum(amaxList[16],amaxList[20]),",
"in writing, software # distributed under the License is distributed",
"amax_id += 1 amaxList[amax_id] = 127.0/amax amax_id += 1 else:",
"block_{} activation amax\".format(i, depth)) #kernel amax starts from ACTIVATION_AMAX_NUM assert",
"kernel_name) # print('kernel:', kernel) # print('quant_max2:', quant_max2) # print('quant_max_processed_:', quant_max_processed)",
"\"attn.proj._aftergemm_quantizer\", \"attn.matmul_q_input_quantizer\", \"attn.matmul_k_input_quantizer\", \"attn.matmul_v_input_quantizer\", \"attn.matmul_a_input_quantizer\", \"attn.softmax_input_quantizer\", \"mlp.fc1._input_quantizer\", \"mlp.fc1._aftergemm_quantizer\", \"mlp.fc2._input_quantizer\", \"mlp.fc2._aftergemm_quantizer\",",
"+= 1 else: amax_id += 8 if verbose: print(\"done process",
"(c) 2020-2022, NVIDIA CORPORATION. All rights reserved. # # Licensed",
"int8O_gemm_output_list = [\"attn.qkv._aftergemm_quantizer\", \"attn.proj._aftergemm_quantizer\", \"mlp.fc1._aftergemm_quantizer\", \"mlp.fc2._aftergemm_quantizer\", \"attn.softmax_input_quantizer\", \"attn.proj._input_quantizer\"] downsample_input =",
"kernel_name)] amax2 = abs(quant_max2) # if (amax2.dim() == 0): #",
"verbose=True): # print(\"Quantizing checkpoint ...\") torch.classes.load_library(ths_path) weight_quantize = torch.ops.fastertransformer.swin_weight_quantize layer_num",
"amax amax_id += 1 amaxList[amax_id] = amax/127.0 amax_id += 1",
"downsample_input = \"downsample.reduction._input_quantizer\" downsample_weight = \"downsample.reduction._weight_quantizer\" downsample_out = \"downsample.reduction._aftergemm_quantizer\" factor",
"if amax_name in int8O_gemm_weight_list: int8O_gemm_weight_amax_list[int8O_gemm_weight_list.index(amax_name)] = amax amaxList[amax_id] = amax",
"init_dict[\"layers.{}.{}._amax\".format(i, downsample_input)].item() amaxList[amax_id] = amax amax_id += 1 amaxList[amax_id] =",
"amax_id == 68 amax_id = ACTIVATION_AMAX_NUM for kernel_id, kernel_name in",
"i, 'j:', j, ' gemm_int8IO_scale:',amaxList[amax_id]) # print(int8O_gemm_input_amax_list[j], int8O_gemm_weight_amax_list[j], int8O_gemm_output_amax_list[j]) amax_id",
"= np.maximum(np.maximum(amaxList[16],amaxList[20]), amaxList[24]) amaxList[amax_id] = amaxList[16] * amaxList[20] / (127.0",
"else: amax_id += 8 if verbose: print(\"done process layer_{} block_{}",
"- 1: amaxList[amax_id] = init_dict[\"layers.{}.downsample.reduction._weight_quantizer._amax\".format(i)].item() amax_id += 1 assert amax_id",
"* 127.0) amax_id += 1 amaxList[amax_id] = 127.0 / amaxList[28]",
"amaxList[amax_id] = amax2 amax_id += 1 # if verbose: #",
"\"mlp.fc2._input_quantizer\", \"attn.matmul_q_input_quantizer\", \"attn.matmul_a_input_quantizer\"] int8O_gemm_output_amax_list = [0 for i in range(INT8O_GEMM_NUM)]",
"depths, ths_path='../lib/libpyt_swintransformer.so', verbose=True): # print(\"Quantizing checkpoint ...\") torch.classes.load_library(ths_path) weight_quantize =",
"= amax amaxList[amax_id] = amax amax_id += 1 amaxList[amax_id] =",
"+= 1 #for trt fused MHA amax #### QKV_addBias_amax #",
"= init_dict[\"layers.{}.downsample.reduction._weight_quantizer._amax\".format(i)] amax2 = abs(quant_max2) kernel = kernel.transpose(-1, -2).contiguous() kernel_processed",
"# print('quant_max:', quant_max) # print('amax:', amax) if i != layer_num",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"abs(quant_max2) kernel = kernel.transpose(-1, -2).contiguous() kernel_processed = weight_quantize(kernel, amax2.cuda()) init_dict[\"layers.{}.downsample.reduction.weight\".format(i)]",
"License, Version 2.0 (the \"License\"); # you may not use",
"* patchMerge_w) / (127 * patchMerge_o) amax_id += 1 assert",
"# You may obtain a copy of the License at",
"amax_name in int8O_gemm_output_list: int8O_gemm_output_amax_list[int8O_gemm_output_list.index(amax_name)] = amax if amax_name in int8O_gemm_weight_list:",
"amaxList[amax_id] = (int8O_gemm_input_amax_list[j]*int8O_gemm_weight_amax_list[j])/(127.0*int8O_gemm_output_amax_list[j]) # print('layernum:', i, 'j:', j, ' gemm_int8IO_scale:',amaxList[amax_id])",
"kernel = init_dict[\"layers.{}.blocks.{}.{}.weight\".format(i, depth, kernel_name)].transpose(-1, -2).contiguous() quant_max2 = init_dict[\"layers.{}.blocks.{}.{}._weight_quantizer._amax\".format(i, depth,",
"ACTIVATION_AMAX_NUM assert amax_id == 68 amax_id = ACTIVATION_AMAX_NUM for kernel_id,",
"if amax_name in int8O_gemm_output_list: int8O_gemm_output_amax_list[int8O_gemm_output_list.index(amax_name)] = amax if amax_name in",
"\"mlp.fc1\", \"mlp.fc2\", \"attn.matmul_k_input_quantizer\", \"attn.matmul_v_input_quantizer\"] int8O_gemm_input_amax_list = [0 for i in",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"== 68 amax_id = ACTIVATION_AMAX_NUM for kernel_id, kernel_name in enumerate(kernel_name_list):",
"ACTIVATION_AMAX_NUM = 72 INT8O_KERNEL_NUM = 5 INT8O_GEMM_NUM = 7 TRT_FUSED_MHA_AMAX_NUM",
"amax_name in int8O_gemm_weight_list: int8O_gemm_weight_amax_list[int8O_gemm_weight_list.index(amax_name)] = amax amaxList[amax_id] = amax amax_id",
"range(INT8O_GEMM_NUM)] int8O_gemm_input_list = [\"attn.qkv._input_quantizer\", \"attn.proj._input_quantizer\", \"mlp.fc1._input_quantizer\", \"mlp.fc2._input_quantizer\", \"attn.matmul_q_input_quantizer\", \"attn.matmul_a_input_quantizer\"] int8O_gemm_output_amax_list",
"amax_id += 1 amaxList[amax_id] = amax/127.0/127.0 amax_id += 1 amaxList[amax_id]",
"127.0 / amaxList[28] amax_id += 1 amaxList[amax_id] = amaxList[24] *",
"CORPORATION. All rights reserved. # # Licensed under the Apache",
"in enumerate(kernel_name_list): kernel = init_dict[\"layers.{}.blocks.{}.{}.weight\".format(i, depth, kernel_name)].transpose(-1, -2).contiguous() quant_max2 =",
"kernel_name in int8O_gemm_weight_list: int8O_gemm_weight_amax_list[int8O_gemm_weight_list.index(kernel_name)] = amax2.item() amaxList[amax_id] = amax2 amax_id",
"patchMerge_w = init_dict[\"layers.{}.{}._amax\".format(i, downsample_weight)].item() patchMerge_o = init_dict[\"layers.{}.{}._amax\".format(i, downsample_out)].item() amaxList[amax_id] =",
"# quant_max_processed = torch.full((kernel.size(1),), amax2.item(), dtype=amax2.dtype, device=amax2.device) # else: #",
"if kernel_name in int8O_gemm_weight_list: int8O_gemm_weight_amax_list[int8O_gemm_weight_list.index(kernel_name)] = amax2.item() amaxList[amax_id] = amax2",
"qkvMax = np.maximum(np.maximum(amaxList[16],amaxList[20]), amaxList[24]) amaxList[amax_id] = amaxList[16] * amaxList[20] /",
"amax_name in int8O_gemm_input_list: int8O_gemm_input_amax_list[int8O_gemm_input_list.index(amax_name)] = amax if amax_name in int8O_gemm_output_list:",
"kernel_name_list = [\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\"] amax_name_list = [\"attn.qkv._input_quantizer\", \"attn.qkv._aftergemm_quantizer\",",
"amax2.item(), dtype=amax2.dtype, device=amax2.device) # else: # quant_max_processed = amax2.view(-1) kernel_processed",
"the License for the specific language governing permissions and #",
"print(i, kernel_name) # print('kernel:', kernel) # print('quant_max2:', quant_max2) # print('quant_max_processed_:',",
"kernel_processed # print(\"Quantizing checkpoint done.\") return init_dict if __name__ ==",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"j in range(INT8O_GEMM_NUM - 1): amaxList[amax_id] = (int8O_gemm_input_amax_list[j]*int8O_gemm_weight_amax_list[j])/(127.0*int8O_gemm_output_amax_list[j]) # print('layernum:',",
"either express or implied. # See the License for the",
"0 for amax_name in amax_name_list: quant_max = init_dict[\"layers.{}.blocks.{}.{}._amax\".format(i, depth, amax_name)].item()",
"int8O_gemm_weight_list: int8O_gemm_weight_amax_list[int8O_gemm_weight_list.index(kernel_name)] = amax2.item() amaxList[amax_id] = amax2 amax_id += 1",
"(int8O_gemm_input_amax_list[j]*int8O_gemm_weight_amax_list[j])/(127.0*int8O_gemm_output_amax_list[j]) # print('layernum:', i, 'j:', j, ' gemm_int8IO_scale:',amaxList[amax_id]) # print(int8O_gemm_input_amax_list[j],",
"= amax/127.0 amax_id += 1 amaxList[amax_id] = amax/127.0/127.0 amax_id +=",
"i != layer_num - 1: patchMerge_i = init_dict[\"layers.{}.{}._amax\".format(i, downsample_input)].item() patchMerge_w",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"8 def extract_amaxlist(init_dict, depths, ths_path='../lib/libpyt_swintransformer.so', verbose=True): # print(\"Quantizing checkpoint ...\")",
"7 TRT_FUSED_MHA_AMAX_NUM = 3 SCALE_RESERVE_NUM = 8 def extract_amaxlist(init_dict, depths,",
"= 127.0/amax amax_id += 1 amax = init_dict[\"layers.{}.{}._amax\".format(i, downsample_out)].item() amaxList[amax_id]",
"kernel_processed = weight_quantize(kernel, amax2.cuda()) init_dict[\"layers.{}.downsample.reduction.weight\".format(i)] = kernel_processed # print(\"Quantizing checkpoint",
"gemm deQuant for j in range(INT8O_GEMM_NUM - 1): amaxList[amax_id] =",
"= init_dict[\"layers.{}.blocks.{}.{}.weight\".format(i, depth, kernel_name)].transpose(-1, -2).contiguous() quant_max2 = init_dict[\"layers.{}.blocks.{}.{}._weight_quantizer._amax\".format(i, depth, kernel_name)]",
"1 assert amax_id == ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM #for int8O gemm",
"torch.full((kernel.size(1),), amax2.item(), dtype=amax2.dtype, device=amax2.device) # else: # quant_max_processed = amax2.view(-1)",
"INT8O_KERNEL_NUM + INT8O_GEMM_NUM + 1 + TRT_FUSED_MHA_AMAX_NUM + SCALE_RESERVE_NUM kernel_name_list",
"re import numpy as np import torch ACTIVATION_AMAX_NUM = 72",
"(127.0 * amaxList[8]) amax_id += 1 init_dict[\"layers.{}.blocks.{}.amaxList\".format(i, depth)] = torch.tensor(amaxList,",
"# print(i, kernel_name) # print('kernel:', kernel) # print('quant_max2:', quant_max2) #",
"print('kernel:', kernel) # print('quant_max2:', quant_max2) # print('quant_max_processed_:', quant_max_processed) if i",
"amax_id += 1 assert amax_id == ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM +",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"checkpoint ...\") torch.classes.load_library(ths_path) weight_quantize = torch.ops.fastertransformer.swin_weight_quantize layer_num = len(depths) amaxTotalNum",
"+= 1 amaxList[amax_id] = 127.0/amax amax_id += 1 else: amax_id",
"amax_id == ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM #for int8O gemm deQuant for",
"downsample_out)].item() amaxList[amax_id] = amax amax_id += 1 amaxList[amax_id] = amax/127.0",
"len(depths) amaxTotalNum = ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM + INT8O_GEMM_NUM + 1",
"assert amax_id == 68 amax_id = ACTIVATION_AMAX_NUM for kernel_id, kernel_name",
"\"attn.matmul_k_input_quantizer\", \"attn.matmul_v_input_quantizer\", \"attn.matmul_a_input_quantizer\", \"attn.softmax_input_quantizer\", \"mlp.fc1._input_quantizer\", \"mlp.fc1._aftergemm_quantizer\", \"mlp.fc2._input_quantizer\", \"mlp.fc2._aftergemm_quantizer\", \"add1_residual_input_quantizer\", \"add2_residual_input_quantizer\"",
"TRT_FUSED_MHA_AMAX_NUM = 3 SCALE_RESERVE_NUM = 8 def extract_amaxlist(init_dict, depths, ths_path='../lib/libpyt_swintransformer.so',",
"init_dict if __name__ == '__main__': weights = torch.load('pytorch_model.bin') extract_amaxlist(weights, [2,",
"amax # amaxList[amax_id] = amaxList[8] # amax_id += 1 qkvMax",
"+= 1 init_dict[\"layers.{}.blocks.{}.amaxList\".format(i, depth)] = torch.tensor(amaxList, dtype=torch.float32) if verbose: print(\"done",
"init_dict[\"layers.{}.downsample.reduction._weight_quantizer._amax\".format(i)] amax2 = abs(quant_max2) kernel = kernel.transpose(-1, -2).contiguous() kernel_processed =",
"# if verbose: # print(i, kernel_name) # print('kernel:', kernel) #",
"amax_id += 1 amaxList[amax_id] = 127.0 / amaxList[28] amax_id +=",
"\"License\"); # you may not use this file except in",
"- 1: patchMerge_i = init_dict[\"layers.{}.{}._amax\".format(i, downsample_input)].item() patchMerge_w = init_dict[\"layers.{}.{}._amax\".format(i, downsample_weight)].item()",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"amax starts from ACTIVATION_AMAX_NUM assert amax_id == 68 amax_id =",
"= amaxList[24] * amaxList[28] / (127.0 * amaxList[8]) amax_id +=",
"assert amax_id == ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM #for int8O gemm deQuant",
"TRT_FUSED_MHA_AMAX_NUM + SCALE_RESERVE_NUM kernel_name_list = [\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\"] amax_name_list",
"# distributed under the License is distributed on an \"AS",
"= init_dict[\"layers.{}.{}._amax\".format(i, downsample_weight)].item() patchMerge_o = init_dict[\"layers.{}.{}._amax\".format(i, downsample_out)].item() amaxList[amax_id] = (patchMerge_i",
"checkpoint done.\") return init_dict if __name__ == '__main__': weights =",
"# Unless required by applicable law or agreed to in",
"72 INT8O_KERNEL_NUM = 5 INT8O_GEMM_NUM = 7 TRT_FUSED_MHA_AMAX_NUM = 3",
"# print('kernel:', kernel) # print('quant_max2:', quant_max2) # print('quant_max_processed_:', quant_max_processed) if",
"kernel weight\".format(i, depth)) if i != layer_num - 1: kernel",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"1: amax = init_dict[\"layers.{}.{}._amax\".format(i, downsample_input)].item() amaxList[amax_id] = amax amax_id +=",
"amax # amaxList[amax_id] = amaxList[28] # amax_id += 1 #",
"\"attn.proj\", \"mlp.fc1\", \"mlp.fc2\"] amax_name_list = [\"attn.qkv._input_quantizer\", \"attn.qkv._aftergemm_quantizer\", \"attn.proj._input_quantizer\", \"attn.proj._aftergemm_quantizer\", \"attn.matmul_q_input_quantizer\",",
"extract_amaxlist(init_dict, depths, ths_path='../lib/libpyt_swintransformer.so', verbose=True): # print(\"Quantizing checkpoint ...\") torch.classes.load_library(ths_path) weight_quantize",
"You may obtain a copy of the License at #",
"layer_num = len(depths) amaxTotalNum = ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM + INT8O_GEMM_NUM",
"print(i, amax_name) # print('quant_max:', quant_max) # print('amax:', amax) if i",
"verbose: # print(i, amax_name) # print('quant_max:', quant_max) # print('amax:', amax)",
"\"attn.qkv._aftergemm_quantizer\", \"attn.proj._input_quantizer\", \"attn.proj._aftergemm_quantizer\", \"attn.matmul_q_input_quantizer\", \"attn.matmul_k_input_quantizer\", \"attn.matmul_v_input_quantizer\", \"attn.matmul_a_input_quantizer\", \"attn.softmax_input_quantizer\", \"mlp.fc1._input_quantizer\", \"mlp.fc1._aftergemm_quantizer\",",
"enumerate(kernel_name_list): kernel = init_dict[\"layers.{}.blocks.{}.{}.weight\".format(i, depth, kernel_name)].transpose(-1, -2).contiguous() quant_max2 = init_dict[\"layers.{}.blocks.{}.{}._weight_quantizer._amax\".format(i,",
"= amaxList[28] # amax_id += 1 # #### bmm2 amax",
"= kernel_processed # print(\"Quantizing checkpoint done.\") return init_dict if __name__",
"verbose: # print(i, kernel_name) # print('kernel:', kernel) # print('quant_max2:', quant_max2)",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"\"mlp.fc1._input_quantizer\", \"mlp.fc2._input_quantizer\", \"attn.matmul_q_input_quantizer\", \"attn.matmul_a_input_quantizer\"] int8O_gemm_output_amax_list = [0 for i in",
"amaxList[amax_id] = amaxList[16] * amaxList[20] / (127.0 * 127.0) amax_id",
"# else: # quant_max_processed = amax2.view(-1) kernel_processed = weight_quantize(kernel, amax2.cuda())",
"kernel_processed if kernel_name in int8O_gemm_weight_list: int8O_gemm_weight_amax_list[int8O_gemm_weight_list.index(kernel_name)] = amax2.item() amaxList[amax_id] =",
"int8O_gemm_weight_amax_list[int8O_gemm_weight_list.index(amax_name)] = amax amaxList[amax_id] = amax amax_id += 1 amaxList[amax_id]"
] |
[
"name, pod_ep = self._extract_pod_name_ep(el) if pod_ep is not None and",
"\"\"\" Dummy actor indicating service start \"\"\" @classmethod def default_uid(cls):",
"2.0 (the \"License\"); # you may not use this file",
"not self.scheduler_discoverer.is_all_ready(): sleep_fun(1) kube_schedulers = self.scheduler_discoverer.get() logger.debug('Schedulers all ready in",
"is_all_ready(self): self.get(True) return all(a is not None for a in",
"def get(self, update=False): if self._pod_to_ep is None or update: self._pod_to_ep",
"in self._pod_to_ep.values()) def watch(self): from urllib3.exceptions import ReadTimeoutError from kubernetes",
"!= cur_pods: cur_pods = new_pods yield self.get(False) break except: #",
"= new_client() while True: cluster_info = actor_client.actor_ref( SchedulerClusterInfoActor.default_uid(), address=random.choice(kube_schedulers)) cluster_info_schedulers",
"return all(a is not None for a in self._pod_to_ep.values()) def",
"logger = logging.getLogger(__name__) class K8SPodsIPWatcher(object): \"\"\" Pods watcher class, compatible",
"self._k8s_namespace, self._label_selector) def _extract_pod_name_ep(self, pod_data): svc_port = pod_data['spec']['containers'][0]['ports'][0]['container_port'] return pod_data['metadata']['name'],",
"kubernetes, waiting ClusterInfoActor to be ready') # check if all",
"if conditions not supported, always return True if 'status' not",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"check if all schedulers are registered in ClusterInfoActor actor_client =",
"if set(cluster_info_schedulers) == set(kube_schedulers): from ...cluster_info import INITIAL_SCHEDULER_FILE with open(INITIAL_SCHEDULER_FILE,",
"logging import os import random import time from ...actors import",
"ThreadPool(1) self._pod_to_ep = None def __reduce__(self): return type(self), (self._k8s_config, self._k8s_namespace,",
"is not None) def is_all_ready(self): self.get(True) return all(a is not",
"import logging import os import random import time from ...actors",
"query = self._pool.spawn(self._client.list_namespaced_pod, namespace=self._k8s_namespace, label_selector=self._label_selector).result().to_dict() result = dict() for el",
"from ...actors import new_client, FunctionActor logger = logging.getLogger(__name__) class K8SPodsIPWatcher(object):",
"or 'default' self._label_selector = label_selector self._client = client.CoreV1Api(client.ApiClient(self._k8s_config)) self._pool =",
"containers are ready, both in kubernetes and in ClusterInfoActor \"\"\"",
"new_pods = set(self.get(True)) if new_pods != cur_pods: cur_pods = new_pods",
"ReadinessActor(FunctionActor): \"\"\" Dummy actor indicating service start \"\"\" @classmethod def",
"# if conditions not supported, always return True if 'status'",
"use this file except in compliance with the License. #",
"timeout_seconds=linger) while True: try: event = self._pool.spawn(next, streamer, StopIteration).result() if",
"True: try: event = self._pool.spawn(next, streamer, StopIteration).result() if event is",
"= k8s_config elif os.environ.get('KUBE_API_ADDRESS'): self._k8s_config = client.Configuration() self._k8s_config.host = os.environ['KUBE_API_ADDRESS']",
"is not None for a in self._pod_to_ep.values()) def watch(self): from",
"endpoint \\ if endpoint and self._extract_pod_ready(obj_dict) else None yield self.get(False)",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"StopIteration).result() if event is StopIteration: raise StopIteration except (ReadTimeoutError, StopIteration):",
"ClusterInfoActor \"\"\" from ...scheduler.utils import SchedulerClusterInfoActor # check if all",
"License. # You may obtain a copy of the License",
"= None result[name] = pod_ep return result def get(self, update=False):",
"'status' not in obj_data or 'conditions' not in obj_data['status']: return",
"cur_pods = new_pods yield self.get(False) break except: # noqa: E722",
"StopIteration: raise StopIteration except (ReadTimeoutError, StopIteration): new_pods = set(self.get(True)) if",
"if new_pods != cur_pods: cur_pods = new_pods yield self.get(False) break",
"= new_pods yield self.get(False) break except: # noqa: E722 logger.exception('Unexpected",
"under the License is distributed on an \"AS IS\" BASIS,",
"(getattr(self, 'pool', None) or time).sleep while not self.scheduler_discoverer.is_all_ready(): sleep_fun(1) kube_schedulers",
"License for the specific language governing permissions and # limitations",
"or update: self._pod_to_ep = self._get_pod_to_ep() return sorted(a for a in",
"return result def get(self, update=False): if self._pod_to_ep is None or",
"not None for a in self._pod_to_ep.values()) def watch(self): from urllib3.exceptions",
"yield self.get(False) class ReadinessActor(FunctionActor): \"\"\" Dummy actor indicating service start",
"from ...cluster_info import INITIAL_SCHEDULER_FILE with open(INITIAL_SCHEDULER_FILE, 'w') as scheduler_file: scheduler_file.write(','.join(cluster_info_schedulers))",
"while True: # when some schedulers are not ready, we",
"def _extract_pod_ready(obj_data): # if conditions not supported, always return True",
"for a in self._pod_to_ep.values()) def watch(self): from urllib3.exceptions import ReadTimeoutError",
"self._k8s_config = client.Configuration() self._k8s_config.host = os.environ['KUBE_API_ADDRESS'] else: self._k8s_config = config.load_incluster_config()",
"sleep_fun = (getattr(self, 'pool', None) or time).sleep while not self.scheduler_discoverer.is_all_ready():",
"= (getattr(self, 'pool', None) or time).sleep while not self.scheduler_discoverer.is_all_ready(): sleep_fun(1)",
"supported, always return True if 'status' not in obj_data or",
"get(self, update=False): if self._pod_to_ep is None or update: self._pod_to_ep =",
"endpoint and self._extract_pod_ready(obj_dict) else None yield self.get(False) class ReadinessActor(FunctionActor): \"\"\"",
"None result[name] = pod_ep return result def get(self, update=False): if",
"\\ if endpoint and self._extract_pod_ready(obj_dict) else None yield self.get(False) class",
"in self._pod_to_ep.values() if a is not None) def is_all_ready(self): self.get(True)",
"obj_data['status']['conditions']) def _get_pod_to_ep(self): query = self._pool.spawn(self._client.list_namespaced_pod, namespace=self._k8s_namespace, label_selector=self._label_selector).result().to_dict() result =",
"as scheduler_file: scheduler_file.write(','.join(cluster_info_schedulers)) logger.debug('Scheduler detection finished. Result: %r', kube_schedulers) break",
"in compliance with the License. # You may obtain a",
"INITIAL_SCHEDULER_FILE with open(INITIAL_SCHEDULER_FILE, 'w') as scheduler_file: scheduler_file.write(','.join(cluster_info_schedulers)) logger.debug('Scheduler detection finished.",
"software # distributed under the License is distributed on an",
"= dict() for el in query['items']: name, pod_ep = self._extract_pod_name_ep(el)",
"# check if all schedulers are registered in ClusterInfoActor actor_client",
"'w') as scheduler_file: scheduler_file.write(','.join(cluster_info_schedulers)) logger.debug('Scheduler detection finished. Result: %r', kube_schedulers)",
"Holding Ltd. # # Licensed under the Apache License, Version",
"return any(cond['type'] == 'Ready' and cond['status'] == 'True' for cond",
"pod_ep = self._extract_pod_name_ep(el) if pod_ep is not None and not",
"os.environ.get('KUBE_API_ADDRESS'): self._k8s_config = client.Configuration() self._k8s_config.host = os.environ['KUBE_API_ADDRESS'] else: self._k8s_config =",
"all(a is not None for a in self._pod_to_ep.values()) def watch(self):",
"error when watching on kubernetes') break obj_dict = event['object'].to_dict() pod_name,",
"config.load_incluster_config() self._k8s_namespace = k8s_namespace or os.environ.get('MARS_K8S_POD_NAMESPACE') or 'default' self._label_selector =",
"noqa: E722 logger.exception('Unexpected error when watching on kubernetes') break obj_dict",
"return pod_data['metadata']['name'], '%s:%s' % (pod_data['status']['pod_ip'], svc_port) @staticmethod def _extract_pod_ready(obj_data): #",
"Alibaba Group Holding Ltd. # # Licensed under the Apache",
"# check if all schedulers are ready using Kubernetes API",
"event['object'].to_dict() pod_name, endpoint = self._extract_pod_name_ep(obj_dict) self._pod_to_ep[pod_name] = endpoint \\ if",
"K8SPodsIPWatcher(object): \"\"\" Pods watcher class, compatible with SchedulerDiscoverer \"\"\" dynamic",
"are ready, both in kubernetes and in ClusterInfoActor \"\"\" from",
"label_selector=self._label_selector).result().to_dict() result = dict() for el in query['items']: name, pod_ep",
"break except: # noqa: E722 logger.exception('Unexpected error when watching on",
"= set(self.get(True)) if new_pods != cur_pods: cur_pods = new_pods yield",
"import SchedulerClusterInfoActor # check if all schedulers are ready using",
"= self.scheduler_discoverer.get() logger.debug('Schedulers all ready in kubernetes, waiting ClusterInfoActor to",
"== set(kube_schedulers): from ...cluster_info import INITIAL_SCHEDULER_FILE with open(INITIAL_SCHEDULER_FILE, 'w') as",
"we refresh faster linger = 10 if self.is_all_ready() else 1",
"class K8SServiceMixin: @staticmethod def write_pid_file(): with open('/tmp/mars-service.pid', 'w') as pid_file:",
"set(kube_schedulers): from ...cluster_info import INITIAL_SCHEDULER_FILE with open(INITIAL_SCHEDULER_FILE, 'w') as scheduler_file:",
"# -*- coding: utf-8 -*- # Copyright 1999-2020 Alibaba Group",
"import random import time from ...actors import new_client, FunctionActor logger",
"all schedulers are registered in ClusterInfoActor actor_client = new_client() while",
"= actor_client.actor_ref( SchedulerClusterInfoActor.default_uid(), address=random.choice(kube_schedulers)) cluster_info_schedulers = cluster_info.get_schedulers() if set(cluster_info_schedulers) ==",
"(ReadTimeoutError, StopIteration): new_pods = set(self.get(True)) if new_pods != cur_pods: cur_pods",
"= self._pool.spawn(self._client.list_namespaced_pod, namespace=self._k8s_namespace, label_selector=self._label_selector).result().to_dict() result = dict() for el in",
"if all schedulers are ready using Kubernetes API sleep_fun =",
"else 1 streamer = w.stream(self._client.list_namespaced_pod, namespace=self._k8s_namespace, label_selector=self._label_selector, timeout_seconds=linger) while True:",
"OF ANY KIND, either express or implied. # See the",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"ANY KIND, either express or implied. # See the License",
"See the License for the specific language governing permissions and",
"kubernetes') break obj_dict = event['object'].to_dict() pod_name, endpoint = self._extract_pod_name_ep(obj_dict) self._pod_to_ep[pod_name]",
"pod_ep return result def get(self, update=False): if self._pod_to_ep is None",
"the License. # You may obtain a copy of the",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"for the specific language governing permissions and # limitations under",
"'%s:%s' % (pod_data['status']['pod_ip'], svc_port) @staticmethod def _extract_pod_ready(obj_data): # if conditions",
"for cond in obj_data['status']['conditions']) def _get_pod_to_ep(self): query = self._pool.spawn(self._client.list_namespaced_pod, namespace=self._k8s_namespace,",
"to in writing, software # distributed under the License is",
"# See the License for the specific language governing permissions",
"not in obj_data['status']: return True return any(cond['type'] == 'Ready' and",
"or agreed to in writing, software # distributed under the",
"= client.Configuration() self._k8s_config.host = os.environ['KUBE_API_ADDRESS'] else: self._k8s_config = config.load_incluster_config() self._k8s_namespace",
"class K8SPodsIPWatcher(object): \"\"\" Pods watcher class, compatible with SchedulerDiscoverer \"\"\"",
"gevent.threadpool import ThreadPool if k8s_config is not None: self._k8s_config =",
"required by applicable law or agreed to in writing, software",
"ready, both in kubernetes and in ClusterInfoActor \"\"\" from ...scheduler.utils",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"with the License. # You may obtain a copy of",
"cond in obj_data['status']['conditions']) def _get_pod_to_ep(self): query = self._pool.spawn(self._client.list_namespaced_pod, namespace=self._k8s_namespace, label_selector=self._label_selector).result().to_dict()",
"sorted(a for a in self._pod_to_ep.values() if a is not None)",
"= self._extract_pod_name_ep(obj_dict) self._pod_to_ep[pod_name] = endpoint \\ if endpoint and self._extract_pod_ready(obj_dict)",
"schedulers are registered in ClusterInfoActor actor_client = new_client() while True:",
"dynamic = True def __init__(self, k8s_config=None, k8s_namespace=None, label_selector=None): from kubernetes",
"@classmethod def default_uid(cls): return 'k:0:%s' % cls.__name__ class K8SServiceMixin: @staticmethod",
"= None def __reduce__(self): return type(self), (self._k8s_config, self._k8s_namespace, self._label_selector) def",
"a in self._pod_to_ep.values() if a is not None) def is_all_ready(self):",
"compliance with the License. # You may obtain a copy",
"while True: cluster_info = actor_client.actor_ref( SchedulerClusterInfoActor.default_uid(), address=random.choice(kube_schedulers)) cluster_info_schedulers = cluster_info.get_schedulers()",
"agreed to in writing, software # distributed under the License",
"are ready using Kubernetes API sleep_fun = (getattr(self, 'pool', None)",
"start \"\"\" @classmethod def default_uid(cls): return 'k:0:%s' % cls.__name__ class",
"self._pod_to_ep = self._get_pod_to_ep() return sorted(a for a in self._pod_to_ep.values() if",
"distributed under the License is distributed on an \"AS IS\"",
"self._label_selector = label_selector self._client = client.CoreV1Api(client.ApiClient(self._k8s_config)) self._pool = ThreadPool(1) self._pod_to_ep",
"query['items']: name, pod_ep = self._extract_pod_name_ep(el) if pod_ep is not None",
"pod_data['metadata']['name'], '%s:%s' % (pod_data['status']['pod_ip'], svc_port) @staticmethod def _extract_pod_ready(obj_data): # if",
"kube_schedulers) break sleep_fun(1) # pragma: no cover def create_scheduler_discoverer(self): self.scheduler_discoverer",
"label_selector=None): from kubernetes import config, client from gevent.threadpool import ThreadPool",
"to be ready') # check if all schedulers are registered",
"ready, we refresh faster linger = 10 if self.is_all_ready() else",
"= k8s_namespace or os.environ.get('MARS_K8S_POD_NAMESPACE') or 'default' self._label_selector = label_selector self._client",
"refresh faster linger = 10 if self.is_all_ready() else 1 streamer",
"express or implied. # See the License for the specific",
"if a is not None) def is_all_ready(self): self.get(True) return all(a",
"except in compliance with the License. # You may obtain",
"K8SServiceMixin: @staticmethod def write_pid_file(): with open('/tmp/mars-service.pid', 'w') as pid_file: pid_file.write(str(os.getpid()))",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"config, client from gevent.threadpool import ThreadPool if k8s_config is not",
"not use this file except in compliance with the License.",
"pod_data): svc_port = pod_data['spec']['containers'][0]['ports'][0]['container_port'] return pod_data['metadata']['name'], '%s:%s' % (pod_data['status']['pod_ip'], svc_port)",
"when watching on kubernetes') break obj_dict = event['object'].to_dict() pod_name, endpoint",
"import os import random import time from ...actors import new_client,",
"writing, software # distributed under the License is distributed on",
"None) or time).sleep while not self.scheduler_discoverer.is_all_ready(): sleep_fun(1) kube_schedulers = self.scheduler_discoverer.get()",
"from kubernetes import watch cur_pods = set(self.get(True)) w = watch.Watch()",
"you may not use this file except in compliance with",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"self._k8s_namespace = k8s_namespace or os.environ.get('MARS_K8S_POD_NAMESPACE') or 'default' self._label_selector = label_selector",
"indicating service start \"\"\" @classmethod def default_uid(cls): return 'k:0:%s' %",
"client.CoreV1Api(client.ApiClient(self._k8s_config)) self._pool = ThreadPool(1) self._pod_to_ep = None def __reduce__(self): return",
"streamer = w.stream(self._client.list_namespaced_pod, namespace=self._k8s_namespace, label_selector=self._label_selector, timeout_seconds=linger) while True: try: event",
"check if all schedulers are ready using Kubernetes API sleep_fun",
"kubernetes import config, client from gevent.threadpool import ThreadPool if k8s_config",
"else None yield self.get(False) class ReadinessActor(FunctionActor): \"\"\" Dummy actor indicating",
"self._pool = ThreadPool(1) self._pod_to_ep = None def __reduce__(self): return type(self),",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"result[name] = pod_ep return result def get(self, update=False): if self._pod_to_ep",
"not None) def is_all_ready(self): self.get(True) return all(a is not None",
"_get_pod_to_ep(self): query = self._pool.spawn(self._client.list_namespaced_pod, namespace=self._k8s_namespace, label_selector=self._label_selector).result().to_dict() result = dict() for",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"True return any(cond['type'] == 'Ready' and cond['status'] == 'True' for",
"utf-8 -*- # Copyright 1999-2020 Alibaba Group Holding Ltd. #",
"label_selector self._client = client.CoreV1Api(client.ApiClient(self._k8s_config)) self._pool = ThreadPool(1) self._pod_to_ep = None",
"self._extract_pod_ready(el): pod_ep = None result[name] = pod_ep return result def",
"self.get(False) class ReadinessActor(FunctionActor): \"\"\" Dummy actor indicating service start \"\"\"",
"'default' self._label_selector = label_selector self._client = client.CoreV1Api(client.ApiClient(self._k8s_config)) self._pool = ThreadPool(1)",
"def watch(self): from urllib3.exceptions import ReadTimeoutError from kubernetes import watch",
"self._extract_pod_name_ep(el) if pod_ep is not None and not self._extract_pod_ready(el): pod_ep",
"k8s_config is not None: self._k8s_config = k8s_config elif os.environ.get('KUBE_API_ADDRESS'): self._k8s_config",
"logger.debug('Scheduler detection finished. Result: %r', kube_schedulers) break sleep_fun(1) # pragma:",
"k8s_namespace=None, label_selector=None): from kubernetes import config, client from gevent.threadpool import",
"or os.environ.get('MARS_K8S_POD_NAMESPACE') or 'default' self._label_selector = label_selector self._client = client.CoreV1Api(client.ApiClient(self._k8s_config))",
"service start \"\"\" @classmethod def default_uid(cls): return 'k:0:%s' % cls.__name__",
"Copyright 1999-2020 Alibaba Group Holding Ltd. # # Licensed under",
"# limitations under the License. import logging import os import",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"for el in query['items']: name, pod_ep = self._extract_pod_name_ep(el) if pod_ep",
"the License is distributed on an \"AS IS\" BASIS, #",
"self._extract_pod_name_ep(obj_dict) self._pod_to_ep[pod_name] = endpoint \\ if endpoint and self._extract_pod_ready(obj_dict) else",
"k8s_config elif os.environ.get('KUBE_API_ADDRESS'): self._k8s_config = client.Configuration() self._k8s_config.host = os.environ['KUBE_API_ADDRESS'] else:",
"in obj_data['status']['conditions']) def _get_pod_to_ep(self): query = self._pool.spawn(self._client.list_namespaced_pod, namespace=self._k8s_namespace, label_selector=self._label_selector).result().to_dict() result",
"governing permissions and # limitations under the License. import logging",
"True if 'status' not in obj_data or 'conditions' not in",
"= set(self.get(True)) w = watch.Watch() while True: # when some",
"pid_file: pid_file.write(str(os.getpid())) def wait_all_schedulers_ready(self): \"\"\" Wait till all containers are",
"= logging.getLogger(__name__) class K8SPodsIPWatcher(object): \"\"\" Pods watcher class, compatible with",
"== 'Ready' and cond['status'] == 'True' for cond in obj_data['status']['conditions'])",
"self.get(False) break except: # noqa: E722 logger.exception('Unexpected error when watching",
"cluster_info.get_schedulers() if set(cluster_info_schedulers) == set(kube_schedulers): from ...cluster_info import INITIAL_SCHEDULER_FILE with",
"all containers are ready, both in kubernetes and in ClusterInfoActor",
"law or agreed to in writing, software # distributed under",
"w.stream(self._client.list_namespaced_pod, namespace=self._k8s_namespace, label_selector=self._label_selector, timeout_seconds=linger) while True: try: event = self._pool.spawn(next,",
"def _get_pod_to_ep(self): query = self._pool.spawn(self._client.list_namespaced_pod, namespace=self._k8s_namespace, label_selector=self._label_selector).result().to_dict() result = dict()",
"schedulers are ready using Kubernetes API sleep_fun = (getattr(self, 'pool',",
"pod_ep is not None and not self._extract_pod_ready(el): pod_ep = None",
"new_client, FunctionActor logger = logging.getLogger(__name__) class K8SPodsIPWatcher(object): \"\"\" Pods watcher",
"os import random import time from ...actors import new_client, FunctionActor",
"Pods watcher class, compatible with SchedulerDiscoverer \"\"\" dynamic = True",
"watcher class, compatible with SchedulerDiscoverer \"\"\" dynamic = True def",
"def default_uid(cls): return 'k:0:%s' % cls.__name__ class K8SServiceMixin: @staticmethod def",
"all schedulers are ready using Kubernetes API sleep_fun = (getattr(self,",
"any(cond['type'] == 'Ready' and cond['status'] == 'True' for cond in",
"cls.__name__ class K8SServiceMixin: @staticmethod def write_pid_file(): with open('/tmp/mars-service.pid', 'w') as",
"in query['items']: name, pod_ep = self._extract_pod_name_ep(el) if pod_ep is not",
"from kubernetes import config, client from gevent.threadpool import ThreadPool if",
"...actors import new_client, FunctionActor logger = logging.getLogger(__name__) class K8SPodsIPWatcher(object): \"\"\"",
"client from gevent.threadpool import ThreadPool if k8s_config is not None:",
"namespace=self._k8s_namespace, label_selector=self._label_selector).result().to_dict() result = dict() for el in query['items']: name,",
"not None: self._k8s_config = k8s_config elif os.environ.get('KUBE_API_ADDRESS'): self._k8s_config = client.Configuration()",
"set(self.get(True)) w = watch.Watch() while True: # when some schedulers",
"ClusterInfoActor actor_client = new_client() while True: cluster_info = actor_client.actor_ref( SchedulerClusterInfoActor.default_uid(),",
"= self._extract_pod_name_ep(el) if pod_ep is not None and not self._extract_pod_ready(el):",
"watch(self): from urllib3.exceptions import ReadTimeoutError from kubernetes import watch cur_pods",
"is StopIteration: raise StopIteration except (ReadTimeoutError, StopIteration): new_pods = set(self.get(True))",
"ready using Kubernetes API sleep_fun = (getattr(self, 'pool', None) or",
"may obtain a copy of the License at # #",
"-*- coding: utf-8 -*- # Copyright 1999-2020 Alibaba Group Holding",
"'w') as pid_file: pid_file.write(str(os.getpid())) def wait_all_schedulers_ready(self): \"\"\" Wait till all",
"import time from ...actors import new_client, FunctionActor logger = logging.getLogger(__name__)",
"cluster_info_schedulers = cluster_info.get_schedulers() if set(cluster_info_schedulers) == set(kube_schedulers): from ...cluster_info import",
"obj_dict = event['object'].to_dict() pod_name, endpoint = self._extract_pod_name_ep(obj_dict) self._pod_to_ep[pod_name] = endpoint",
"= endpoint \\ if endpoint and self._extract_pod_ready(obj_dict) else None yield",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"ClusterInfoActor to be ready') # check if all schedulers are",
"actor indicating service start \"\"\" @classmethod def default_uid(cls): return 'k:0:%s'",
"not ready, we refresh faster linger = 10 if self.is_all_ready()",
"self._k8s_config.host = os.environ['KUBE_API_ADDRESS'] else: self._k8s_config = config.load_incluster_config() self._k8s_namespace = k8s_namespace",
"may not use this file except in compliance with the",
"if self.is_all_ready() else 1 streamer = w.stream(self._client.list_namespaced_pod, namespace=self._k8s_namespace, label_selector=self._label_selector, timeout_seconds=linger)",
"@staticmethod def _extract_pod_ready(obj_data): # if conditions not supported, always return",
"self._get_pod_to_ep() return sorted(a for a in self._pod_to_ep.values() if a is",
"def _extract_pod_name_ep(self, pod_data): svc_port = pod_data['spec']['containers'][0]['ports'][0]['container_port'] return pod_data['metadata']['name'], '%s:%s' %",
"dict() for el in query['items']: name, pod_ep = self._extract_pod_name_ep(el) if",
"True: cluster_info = actor_client.actor_ref( SchedulerClusterInfoActor.default_uid(), address=random.choice(kube_schedulers)) cluster_info_schedulers = cluster_info.get_schedulers() if",
"raise StopIteration except (ReadTimeoutError, StopIteration): new_pods = set(self.get(True)) if new_pods",
"__reduce__(self): return type(self), (self._k8s_config, self._k8s_namespace, self._label_selector) def _extract_pod_name_ep(self, pod_data): svc_port",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"some schedulers are not ready, we refresh faster linger =",
"this file except in compliance with the License. # You",
"schedulers are not ready, we refresh faster linger = 10",
"pid_file.write(str(os.getpid())) def wait_all_schedulers_ready(self): \"\"\" Wait till all containers are ready,",
"actor_client.actor_ref( SchedulerClusterInfoActor.default_uid(), address=random.choice(kube_schedulers)) cluster_info_schedulers = cluster_info.get_schedulers() if set(cluster_info_schedulers) == set(kube_schedulers):",
"and in ClusterInfoActor \"\"\" from ...scheduler.utils import SchedulerClusterInfoActor # check",
"__init__(self, k8s_config=None, k8s_namespace=None, label_selector=None): from kubernetes import config, client from",
"in obj_data['status']: return True return any(cond['type'] == 'Ready' and cond['status']",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"conditions not supported, always return True if 'status' not in",
"# # Licensed under the Apache License, Version 2.0 (the",
"w = watch.Watch() while True: # when some schedulers are",
"file except in compliance with the License. # You may",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"class, compatible with SchedulerDiscoverer \"\"\" dynamic = True def __init__(self,",
"address=random.choice(kube_schedulers)) cluster_info_schedulers = cluster_info.get_schedulers() if set(cluster_info_schedulers) == set(kube_schedulers): from ...cluster_info",
"= os.environ['KUBE_API_ADDRESS'] else: self._k8s_config = config.load_incluster_config() self._k8s_namespace = k8s_namespace or",
"== 'True' for cond in obj_data['status']['conditions']) def _get_pod_to_ep(self): query =",
"if 'status' not in obj_data or 'conditions' not in obj_data['status']:",
"if event is StopIteration: raise StopIteration except (ReadTimeoutError, StopIteration): new_pods",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"FunctionActor logger = logging.getLogger(__name__) class K8SPodsIPWatcher(object): \"\"\" Pods watcher class,",
"for a in self._pod_to_ep.values() if a is not None) def",
"set(self.get(True)) if new_pods != cur_pods: cur_pods = new_pods yield self.get(False)",
"when some schedulers are not ready, we refresh faster linger",
"with open('/tmp/mars-service.pid', 'w') as pid_file: pid_file.write(str(os.getpid())) def wait_all_schedulers_ready(self): \"\"\" Wait",
"wait_all_schedulers_ready(self): \"\"\" Wait till all containers are ready, both in",
"default_uid(cls): return 'k:0:%s' % cls.__name__ class K8SServiceMixin: @staticmethod def write_pid_file():",
"StopIteration): new_pods = set(self.get(True)) if new_pods != cur_pods: cur_pods =",
"= label_selector self._client = client.CoreV1Api(client.ApiClient(self._k8s_config)) self._pool = ThreadPool(1) self._pod_to_ep =",
"Ltd. # # Licensed under the Apache License, Version 2.0",
"if self._pod_to_ep is None or update: self._pod_to_ep = self._get_pod_to_ep() return",
"k8s_config=None, k8s_namespace=None, label_selector=None): from kubernetes import config, client from gevent.threadpool",
"language governing permissions and # limitations under the License. import",
"a is not None) def is_all_ready(self): self.get(True) return all(a is",
"...scheduler.utils import SchedulerClusterInfoActor # check if all schedulers are ready",
"self._k8s_config = k8s_config elif os.environ.get('KUBE_API_ADDRESS'): self._k8s_config = client.Configuration() self._k8s_config.host =",
"# when some schedulers are not ready, we refresh faster",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"os.environ['KUBE_API_ADDRESS'] else: self._k8s_config = config.load_incluster_config() self._k8s_namespace = k8s_namespace or os.environ.get('MARS_K8S_POD_NAMESPACE')",
"as pid_file: pid_file.write(str(os.getpid())) def wait_all_schedulers_ready(self): \"\"\" Wait till all containers",
"event = self._pool.spawn(next, streamer, StopIteration).result() if event is StopIteration: raise",
"import new_client, FunctionActor logger = logging.getLogger(__name__) class K8SPodsIPWatcher(object): \"\"\" Pods",
"namespace=self._k8s_namespace, label_selector=self._label_selector, timeout_seconds=linger) while True: try: event = self._pool.spawn(next, streamer,",
"or time).sleep while not self.scheduler_discoverer.is_all_ready(): sleep_fun(1) kube_schedulers = self.scheduler_discoverer.get() logger.debug('Schedulers",
"% cls.__name__ class K8SServiceMixin: @staticmethod def write_pid_file(): with open('/tmp/mars-service.pid', 'w')",
"or implied. # See the License for the specific language",
"= ThreadPool(1) self._pod_to_ep = None def __reduce__(self): return type(self), (self._k8s_config,",
"ready in kubernetes, waiting ClusterInfoActor to be ready') # check",
"...cluster_info import INITIAL_SCHEDULER_FILE with open(INITIAL_SCHEDULER_FILE, 'w') as scheduler_file: scheduler_file.write(','.join(cluster_info_schedulers)) logger.debug('Scheduler",
"limitations under the License. import logging import os import random",
"KIND, either express or implied. # See the License for",
"specific language governing permissions and # limitations under the License.",
"os.environ.get('MARS_K8S_POD_NAMESPACE') or 'default' self._label_selector = label_selector self._client = client.CoreV1Api(client.ApiClient(self._k8s_config)) self._pool",
"self._label_selector) def _extract_pod_name_ep(self, pod_data): svc_port = pod_data['spec']['containers'][0]['ports'][0]['container_port'] return pod_data['metadata']['name'], '%s:%s'",
"new_client() while True: cluster_info = actor_client.actor_ref( SchedulerClusterInfoActor.default_uid(), address=random.choice(kube_schedulers)) cluster_info_schedulers =",
"pod_ep = None result[name] = pod_ep return result def get(self,",
"registered in ClusterInfoActor actor_client = new_client() while True: cluster_info =",
"set(cluster_info_schedulers) == set(kube_schedulers): from ...cluster_info import INITIAL_SCHEDULER_FILE with open(INITIAL_SCHEDULER_FILE, 'w')",
"and self._extract_pod_ready(obj_dict) else None yield self.get(False) class ReadinessActor(FunctionActor): \"\"\" Dummy",
"# noqa: E722 logger.exception('Unexpected error when watching on kubernetes') break",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"all ready in kubernetes, waiting ClusterInfoActor to be ready') #",
"import ThreadPool if k8s_config is not None: self._k8s_config = k8s_config",
"\"\"\" from ...scheduler.utils import SchedulerClusterInfoActor # check if all schedulers",
"_extract_pod_name_ep(self, pod_data): svc_port = pod_data['spec']['containers'][0]['ports'][0]['container_port'] return pod_data['metadata']['name'], '%s:%s' % (pod_data['status']['pod_ip'],",
"streamer, StopIteration).result() if event is StopIteration: raise StopIteration except (ReadTimeoutError,",
"elif os.environ.get('KUBE_API_ADDRESS'): self._k8s_config = client.Configuration() self._k8s_config.host = os.environ['KUBE_API_ADDRESS'] else: self._k8s_config",
"if all schedulers are registered in ClusterInfoActor actor_client = new_client()",
"while not self.scheduler_discoverer.is_all_ready(): sleep_fun(1) kube_schedulers = self.scheduler_discoverer.get() logger.debug('Schedulers all ready",
"if endpoint and self._extract_pod_ready(obj_dict) else None yield self.get(False) class ReadinessActor(FunctionActor):",
"not in obj_data or 'conditions' not in obj_data['status']: return True",
"\"\"\" Wait till all containers are ready, both in kubernetes",
"and not self._extract_pod_ready(el): pod_ep = None result[name] = pod_ep return",
"'pool', None) or time).sleep while not self.scheduler_discoverer.is_all_ready(): sleep_fun(1) kube_schedulers =",
"from gevent.threadpool import ThreadPool if k8s_config is not None: self._k8s_config",
"(the \"License\"); # you may not use this file except",
"= watch.Watch() while True: # when some schedulers are not",
"are not ready, we refresh faster linger = 10 if",
"# you may not use this file except in compliance",
"time).sleep while not self.scheduler_discoverer.is_all_ready(): sleep_fun(1) kube_schedulers = self.scheduler_discoverer.get() logger.debug('Schedulers all",
"update: self._pod_to_ep = self._get_pod_to_ep() return sorted(a for a in self._pod_to_ep.values()",
"'Ready' and cond['status'] == 'True' for cond in obj_data['status']['conditions']) def",
"watching on kubernetes') break obj_dict = event['object'].to_dict() pod_name, endpoint =",
"write_pid_file(): with open('/tmp/mars-service.pid', 'w') as pid_file: pid_file.write(str(os.getpid())) def wait_all_schedulers_ready(self): \"\"\"",
"self.get(True) return all(a is not None for a in self._pod_to_ep.values())",
"with SchedulerDiscoverer \"\"\" dynamic = True def __init__(self, k8s_config=None, k8s_namespace=None,",
"\"\"\" @classmethod def default_uid(cls): return 'k:0:%s' % cls.__name__ class K8SServiceMixin:",
"self._pool.spawn(self._client.list_namespaced_pod, namespace=self._k8s_namespace, label_selector=self._label_selector).result().to_dict() result = dict() for el in query['items']:",
"from ...scheduler.utils import SchedulerClusterInfoActor # check if all schedulers are",
"= self._pool.spawn(next, streamer, StopIteration).result() if event is StopIteration: raise StopIteration",
"# # Unless required by applicable law or agreed to",
"random import time from ...actors import new_client, FunctionActor logger =",
"= w.stream(self._client.list_namespaced_pod, namespace=self._k8s_namespace, label_selector=self._label_selector, timeout_seconds=linger) while True: try: event =",
"watch cur_pods = set(self.get(True)) w = watch.Watch() while True: #",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"open(INITIAL_SCHEDULER_FILE, 'w') as scheduler_file: scheduler_file.write(','.join(cluster_info_schedulers)) logger.debug('Scheduler detection finished. Result: %r',",
"pod_data['spec']['containers'][0]['ports'][0]['container_port'] return pod_data['metadata']['name'], '%s:%s' % (pod_data['status']['pod_ip'], svc_port) @staticmethod def _extract_pod_ready(obj_data):",
"always return True if 'status' not in obj_data or 'conditions'",
"urllib3.exceptions import ReadTimeoutError from kubernetes import watch cur_pods = set(self.get(True))",
"Version 2.0 (the \"License\"); # you may not use this",
"endpoint = self._extract_pod_name_ep(obj_dict) self._pod_to_ep[pod_name] = endpoint \\ if endpoint and",
"logger.exception('Unexpected error when watching on kubernetes') break obj_dict = event['object'].to_dict()",
"cur_pods = set(self.get(True)) w = watch.Watch() while True: # when",
"the License. import logging import os import random import time",
"client.Configuration() self._k8s_config.host = os.environ['KUBE_API_ADDRESS'] else: self._k8s_config = config.load_incluster_config() self._k8s_namespace =",
"from urllib3.exceptions import ReadTimeoutError from kubernetes import watch cur_pods =",
"= client.CoreV1Api(client.ApiClient(self._k8s_config)) self._pool = ThreadPool(1) self._pod_to_ep = None def __reduce__(self):",
"type(self), (self._k8s_config, self._k8s_namespace, self._label_selector) def _extract_pod_name_ep(self, pod_data): svc_port = pod_data['spec']['containers'][0]['ports'][0]['container_port']",
"implied. # See the License for the specific language governing",
"return type(self), (self._k8s_config, self._k8s_namespace, self._label_selector) def _extract_pod_name_ep(self, pod_data): svc_port =",
"result def get(self, update=False): if self._pod_to_ep is None or update:",
"StopIteration except (ReadTimeoutError, StopIteration): new_pods = set(self.get(True)) if new_pods !=",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"= cluster_info.get_schedulers() if set(cluster_info_schedulers) == set(kube_schedulers): from ...cluster_info import INITIAL_SCHEDULER_FILE",
"return True if 'status' not in obj_data or 'conditions' not",
"kube_schedulers = self.scheduler_discoverer.get() logger.debug('Schedulers all ready in kubernetes, waiting ClusterInfoActor",
"svc_port) @staticmethod def _extract_pod_ready(obj_data): # if conditions not supported, always",
"else: self._k8s_config = config.load_incluster_config() self._k8s_namespace = k8s_namespace or os.environ.get('MARS_K8S_POD_NAMESPACE') or",
"event is StopIteration: raise StopIteration except (ReadTimeoutError, StopIteration): new_pods =",
"%r', kube_schedulers) break sleep_fun(1) # pragma: no cover def create_scheduler_discoverer(self):",
"by applicable law or agreed to in writing, software #",
"logger.debug('Schedulers all ready in kubernetes, waiting ClusterInfoActor to be ready')",
"def __init__(self, k8s_config=None, k8s_namespace=None, label_selector=None): from kubernetes import config, client",
"import INITIAL_SCHEDULER_FILE with open(INITIAL_SCHEDULER_FILE, 'w') as scheduler_file: scheduler_file.write(','.join(cluster_info_schedulers)) logger.debug('Scheduler detection",
"\"\"\" dynamic = True def __init__(self, k8s_config=None, k8s_namespace=None, label_selector=None): from",
"self.scheduler_discoverer.get() logger.debug('Schedulers all ready in kubernetes, waiting ClusterInfoActor to be",
"True: # when some schedulers are not ready, we refresh",
"try: event = self._pool.spawn(next, streamer, StopIteration).result() if event is StopIteration:",
"# Copyright 1999-2020 Alibaba Group Holding Ltd. # # Licensed",
"sleep_fun(1) kube_schedulers = self.scheduler_discoverer.get() logger.debug('Schedulers all ready in kubernetes, waiting",
"while True: try: event = self._pool.spawn(next, streamer, StopIteration).result() if event",
"return 'k:0:%s' % cls.__name__ class K8SServiceMixin: @staticmethod def write_pid_file(): with",
"Group Holding Ltd. # # Licensed under the Apache License,",
"label_selector=self._label_selector, timeout_seconds=linger) while True: try: event = self._pool.spawn(next, streamer, StopIteration).result()",
"(pod_data['status']['pod_ip'], svc_port) @staticmethod def _extract_pod_ready(obj_data): # if conditions not supported,",
"cluster_info = actor_client.actor_ref( SchedulerClusterInfoActor.default_uid(), address=random.choice(kube_schedulers)) cluster_info_schedulers = cluster_info.get_schedulers() if set(cluster_info_schedulers)",
"till all containers are ready, both in kubernetes and in",
"import ReadTimeoutError from kubernetes import watch cur_pods = set(self.get(True)) w",
"= 10 if self.is_all_ready() else 1 streamer = w.stream(self._client.list_namespaced_pod, namespace=self._k8s_namespace,",
"result = dict() for el in query['items']: name, pod_ep =",
"new_pods != cur_pods: cur_pods = new_pods yield self.get(False) break except:",
"time from ...actors import new_client, FunctionActor logger = logging.getLogger(__name__) class",
"compatible with SchedulerDiscoverer \"\"\" dynamic = True def __init__(self, k8s_config=None,",
"in ClusterInfoActor actor_client = new_client() while True: cluster_info = actor_client.actor_ref(",
"Result: %r', kube_schedulers) break sleep_fun(1) # pragma: no cover def",
"def is_all_ready(self): self.get(True) return all(a is not None for a",
"in kubernetes and in ClusterInfoActor \"\"\" from ...scheduler.utils import SchedulerClusterInfoActor",
"waiting ClusterInfoActor to be ready') # check if all schedulers",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"Unless required by applicable law or agreed to in writing,",
"ReadTimeoutError from kubernetes import watch cur_pods = set(self.get(True)) w =",
"return True return any(cond['type'] == 'Ready' and cond['status'] == 'True'",
"break obj_dict = event['object'].to_dict() pod_name, endpoint = self._extract_pod_name_ep(obj_dict) self._pod_to_ep[pod_name] =",
"update=False): if self._pod_to_ep is None or update: self._pod_to_ep = self._get_pod_to_ep()",
"None or update: self._pod_to_ep = self._get_pod_to_ep() return sorted(a for a",
"new_pods yield self.get(False) break except: # noqa: E722 logger.exception('Unexpected error",
"@staticmethod def write_pid_file(): with open('/tmp/mars-service.pid', 'w') as pid_file: pid_file.write(str(os.getpid())) def",
"both in kubernetes and in ClusterInfoActor \"\"\" from ...scheduler.utils import",
"is None or update: self._pod_to_ep = self._get_pod_to_ep() return sorted(a for",
"the specific language governing permissions and # limitations under the",
"k8s_namespace or os.environ.get('MARS_K8S_POD_NAMESPACE') or 'default' self._label_selector = label_selector self._client =",
"None: self._k8s_config = k8s_config elif os.environ.get('KUBE_API_ADDRESS'): self._k8s_config = client.Configuration() self._k8s_config.host",
"finished. Result: %r', kube_schedulers) break sleep_fun(1) # pragma: no cover",
"(self._k8s_config, self._k8s_namespace, self._label_selector) def _extract_pod_name_ep(self, pod_data): svc_port = pod_data['spec']['containers'][0]['ports'][0]['container_port'] return",
"class ReadinessActor(FunctionActor): \"\"\" Dummy actor indicating service start \"\"\" @classmethod",
"applicable law or agreed to in writing, software # distributed",
"self._pod_to_ep[pod_name] = endpoint \\ if endpoint and self._extract_pod_ready(obj_dict) else None",
"ThreadPool if k8s_config is not None: self._k8s_config = k8s_config elif",
"coding: utf-8 -*- # Copyright 1999-2020 Alibaba Group Holding Ltd.",
"logging.getLogger(__name__) class K8SPodsIPWatcher(object): \"\"\" Pods watcher class, compatible with SchedulerDiscoverer",
"ready') # check if all schedulers are registered in ClusterInfoActor",
"= True def __init__(self, k8s_config=None, k8s_namespace=None, label_selector=None): from kubernetes import",
"in writing, software # distributed under the License is distributed",
"a in self._pod_to_ep.values()) def watch(self): from urllib3.exceptions import ReadTimeoutError from",
"and # limitations under the License. import logging import os",
"actor_client = new_client() while True: cluster_info = actor_client.actor_ref( SchedulerClusterInfoActor.default_uid(), address=random.choice(kube_schedulers))",
"License. import logging import os import random import time from",
"1 streamer = w.stream(self._client.list_namespaced_pod, namespace=self._k8s_namespace, label_selector=self._label_selector, timeout_seconds=linger) while True: try:",
"None) def is_all_ready(self): self.get(True) return all(a is not None for",
"el in query['items']: name, pod_ep = self._extract_pod_name_ep(el) if pod_ep is",
"kubernetes import watch cur_pods = set(self.get(True)) w = watch.Watch() while",
"True def __init__(self, k8s_config=None, k8s_namespace=None, label_selector=None): from kubernetes import config,",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"License, Version 2.0 (the \"License\"); # you may not use",
"def write_pid_file(): with open('/tmp/mars-service.pid', 'w') as pid_file: pid_file.write(str(os.getpid())) def wait_all_schedulers_ready(self):",
"with open(INITIAL_SCHEDULER_FILE, 'w') as scheduler_file: scheduler_file.write(','.join(cluster_info_schedulers)) logger.debug('Scheduler detection finished. Result:",
"return sorted(a for a in self._pod_to_ep.values() if a is not",
"def __reduce__(self): return type(self), (self._k8s_config, self._k8s_namespace, self._label_selector) def _extract_pod_name_ep(self, pod_data):",
"# You may obtain a copy of the License at",
"= pod_data['spec']['containers'][0]['ports'][0]['container_port'] return pod_data['metadata']['name'], '%s:%s' % (pod_data['status']['pod_ip'], svc_port) @staticmethod def",
"Kubernetes API sleep_fun = (getattr(self, 'pool', None) or time).sleep while",
"be ready') # check if all schedulers are registered in",
"SchedulerClusterInfoActor.default_uid(), address=random.choice(kube_schedulers)) cluster_info_schedulers = cluster_info.get_schedulers() if set(cluster_info_schedulers) == set(kube_schedulers): from",
"if k8s_config is not None: self._k8s_config = k8s_config elif os.environ.get('KUBE_API_ADDRESS'):",
"= self._get_pod_to_ep() return sorted(a for a in self._pod_to_ep.values() if a",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"not self._extract_pod_ready(el): pod_ep = None result[name] = pod_ep return result",
"SchedulerClusterInfoActor # check if all schedulers are ready using Kubernetes",
"\"\"\" Pods watcher class, compatible with SchedulerDiscoverer \"\"\" dynamic =",
"watch.Watch() while True: # when some schedulers are not ready,",
"cur_pods: cur_pods = new_pods yield self.get(False) break except: # noqa:",
"None for a in self._pod_to_ep.values()) def watch(self): from urllib3.exceptions import",
"= pod_ep return result def get(self, update=False): if self._pod_to_ep is",
"SchedulerDiscoverer \"\"\" dynamic = True def __init__(self, k8s_config=None, k8s_namespace=None, label_selector=None):",
"in ClusterInfoActor \"\"\" from ...scheduler.utils import SchedulerClusterInfoActor # check if",
"_extract_pod_ready(obj_data): # if conditions not supported, always return True if",
"the License for the specific language governing permissions and #",
"API sleep_fun = (getattr(self, 'pool', None) or time).sleep while not",
"None def __reduce__(self): return type(self), (self._k8s_config, self._k8s_namespace, self._label_selector) def _extract_pod_name_ep(self,",
"and cond['status'] == 'True' for cond in obj_data['status']['conditions']) def _get_pod_to_ep(self):",
"self._pool.spawn(next, streamer, StopIteration).result() if event is StopIteration: raise StopIteration except",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"= event['object'].to_dict() pod_name, endpoint = self._extract_pod_name_ep(obj_dict) self._pod_to_ep[pod_name] = endpoint \\",
"either express or implied. # See the License for the",
"import config, client from gevent.threadpool import ThreadPool if k8s_config is",
"self._k8s_config = config.load_incluster_config() self._k8s_namespace = k8s_namespace or os.environ.get('MARS_K8S_POD_NAMESPACE') or 'default'",
"'conditions' not in obj_data['status']: return True return any(cond['type'] == 'Ready'",
"cond['status'] == 'True' for cond in obj_data['status']['conditions']) def _get_pod_to_ep(self): query",
"kubernetes and in ClusterInfoActor \"\"\" from ...scheduler.utils import SchedulerClusterInfoActor #",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"pod_name, endpoint = self._extract_pod_name_ep(obj_dict) self._pod_to_ep[pod_name] = endpoint \\ if endpoint",
"faster linger = 10 if self.is_all_ready() else 1 streamer =",
"None and not self._extract_pod_ready(el): pod_ep = None result[name] = pod_ep",
"obj_data or 'conditions' not in obj_data['status']: return True return any(cond['type']",
"'True' for cond in obj_data['status']['conditions']) def _get_pod_to_ep(self): query = self._pool.spawn(self._client.list_namespaced_pod,",
"= config.load_incluster_config() self._k8s_namespace = k8s_namespace or os.environ.get('MARS_K8S_POD_NAMESPACE') or 'default' self._label_selector",
"self._pod_to_ep is None or update: self._pod_to_ep = self._get_pod_to_ep() return sorted(a",
"or 'conditions' not in obj_data['status']: return True return any(cond['type'] ==",
"E722 logger.exception('Unexpected error when watching on kubernetes') break obj_dict =",
"in obj_data or 'conditions' not in obj_data['status']: return True return",
"self._extract_pod_ready(obj_dict) else None yield self.get(False) class ReadinessActor(FunctionActor): \"\"\" Dummy actor",
"self._pod_to_ep.values()) def watch(self): from urllib3.exceptions import ReadTimeoutError from kubernetes import",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"permissions and # limitations under the License. import logging import",
"scheduler_file.write(','.join(cluster_info_schedulers)) logger.debug('Scheduler detection finished. Result: %r', kube_schedulers) break sleep_fun(1) #",
"on kubernetes') break obj_dict = event['object'].to_dict() pod_name, endpoint = self._extract_pod_name_ep(obj_dict)",
"if pod_ep is not None and not self._extract_pod_ready(el): pod_ep =",
"Wait till all containers are ready, both in kubernetes and",
"Dummy actor indicating service start \"\"\" @classmethod def default_uid(cls): return",
"not None and not self._extract_pod_ready(el): pod_ep = None result[name] =",
"1999-2020 Alibaba Group Holding Ltd. # # Licensed under the",
"in kubernetes, waiting ClusterInfoActor to be ready') # check if",
"not supported, always return True if 'status' not in obj_data",
"\"License\"); # you may not use this file except in",
"using Kubernetes API sleep_fun = (getattr(self, 'pool', None) or time).sleep",
"break sleep_fun(1) # pragma: no cover def create_scheduler_discoverer(self): self.scheduler_discoverer =",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"self._pod_to_ep.values() if a is not None) def is_all_ready(self): self.get(True) return",
"scheduler_file: scheduler_file.write(','.join(cluster_info_schedulers)) logger.debug('Scheduler detection finished. Result: %r', kube_schedulers) break sleep_fun(1)",
"under the License. import logging import os import random import",
"self._client = client.CoreV1Api(client.ApiClient(self._k8s_config)) self._pool = ThreadPool(1) self._pod_to_ep = None def",
"detection finished. Result: %r', kube_schedulers) break sleep_fun(1) # pragma: no",
"is not None and not self._extract_pod_ready(el): pod_ep = None result[name]",
"# distributed under the License is distributed on an \"AS",
"# Unless required by applicable law or agreed to in",
"self._pod_to_ep = None def __reduce__(self): return type(self), (self._k8s_config, self._k8s_namespace, self._label_selector)",
"yield self.get(False) break except: # noqa: E722 logger.exception('Unexpected error when",
"open('/tmp/mars-service.pid', 'w') as pid_file: pid_file.write(str(os.getpid())) def wait_all_schedulers_ready(self): \"\"\" Wait till",
"'k:0:%s' % cls.__name__ class K8SServiceMixin: @staticmethod def write_pid_file(): with open('/tmp/mars-service.pid',",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"% (pod_data['status']['pod_ip'], svc_port) @staticmethod def _extract_pod_ready(obj_data): # if conditions not",
"linger = 10 if self.is_all_ready() else 1 streamer = w.stream(self._client.list_namespaced_pod,",
"None yield self.get(False) class ReadinessActor(FunctionActor): \"\"\" Dummy actor indicating service",
"def wait_all_schedulers_ready(self): \"\"\" Wait till all containers are ready, both",
"except: # noqa: E722 logger.exception('Unexpected error when watching on kubernetes')",
"You may obtain a copy of the License at #",
"except (ReadTimeoutError, StopIteration): new_pods = set(self.get(True)) if new_pods != cur_pods:",
"self.is_all_ready() else 1 streamer = w.stream(self._client.list_namespaced_pod, namespace=self._k8s_namespace, label_selector=self._label_selector, timeout_seconds=linger) while",
"svc_port = pod_data['spec']['containers'][0]['ports'][0]['container_port'] return pod_data['metadata']['name'], '%s:%s' % (pod_data['status']['pod_ip'], svc_port) @staticmethod",
"sleep_fun(1) # pragma: no cover def create_scheduler_discoverer(self): self.scheduler_discoverer = K8SPodsIPWatcher(label_selector='name=marsscheduler')",
"import watch cur_pods = set(self.get(True)) w = watch.Watch() while True:",
"is not None: self._k8s_config = k8s_config elif os.environ.get('KUBE_API_ADDRESS'): self._k8s_config =",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"obj_data['status']: return True return any(cond['type'] == 'Ready' and cond['status'] ==",
"-*- # Copyright 1999-2020 Alibaba Group Holding Ltd. # #",
"are registered in ClusterInfoActor actor_client = new_client() while True: cluster_info",
"self.scheduler_discoverer.is_all_ready(): sleep_fun(1) kube_schedulers = self.scheduler_discoverer.get() logger.debug('Schedulers all ready in kubernetes,",
"10 if self.is_all_ready() else 1 streamer = w.stream(self._client.list_namespaced_pod, namespace=self._k8s_namespace, label_selector=self._label_selector,"
] |
[
"import torch import transformers from model.bert_model import BertModel class TestBertModel(TestCase):",
"num_classes = 3 expected_shape = (batch, sequence_len, num_classes) input_batch =",
"input_batch = torch.randint(low=0, high=vocab_size-1, size=(batch, sequence_len)) config= transformers.BertConfig(vocab_size=vocab_size,hidden_size=10, num_hidden_layers=1, num_attention_heads=1,num_labels=num_classes)",
"20 batch = 32 num_classes = 3 expected_shape = (batch,",
"class TestBertModel(TestCase): def test_forward(self): # Bert Config vocab_size = 10",
"= 3 expected_shape = (batch, sequence_len, num_classes) input_batch = torch.randint(low=0,",
"model.bert_model import BertModel class TestBertModel(TestCase): def test_forward(self): # Bert Config",
"= torch.randint(low=0, high=vocab_size-1, size=(batch, sequence_len)) config= transformers.BertConfig(vocab_size=vocab_size,hidden_size=10, num_hidden_layers=1, num_attention_heads=1,num_labels=num_classes) sut",
"from unittest import TestCase import torch import transformers from model.bert_model",
"import transformers from model.bert_model import BertModel class TestBertModel(TestCase): def test_forward(self):",
"32 num_classes = 3 expected_shape = (batch, sequence_len, num_classes) input_batch",
"test_forward(self): # Bert Config vocab_size = 10 sequence_len = 20",
"def test_forward(self): # Bert Config vocab_size = 10 sequence_len =",
"torch import transformers from model.bert_model import BertModel class TestBertModel(TestCase): def",
"import TestCase import torch import transformers from model.bert_model import BertModel",
"from model.bert_model import BertModel class TestBertModel(TestCase): def test_forward(self): # Bert",
"= 32 num_classes = 3 expected_shape = (batch, sequence_len, num_classes)",
"num_attention_heads=1,num_labels=num_classes) sut = BertModel(None, None, bert_config=config) # Act actual =",
"import BertModel class TestBertModel(TestCase): def test_forward(self): # Bert Config vocab_size",
"(batch, sequence_len, num_classes) input_batch = torch.randint(low=0, high=vocab_size-1, size=(batch, sequence_len)) config=",
"vocab_size = 10 sequence_len = 20 batch = 32 num_classes",
"None, bert_config=config) # Act actual = sut.forward(input_batch)[0] # Assert self.assertEqual(expected_shape,",
"sequence_len = 20 batch = 32 num_classes = 3 expected_shape",
"num_hidden_layers=1, num_attention_heads=1,num_labels=num_classes) sut = BertModel(None, None, bert_config=config) # Act actual",
"Config vocab_size = 10 sequence_len = 20 batch = 32",
"= 20 batch = 32 num_classes = 3 expected_shape =",
"batch = 32 num_classes = 3 expected_shape = (batch, sequence_len,",
"10 sequence_len = 20 batch = 32 num_classes = 3",
"sequence_len, num_classes) input_batch = torch.randint(low=0, high=vocab_size-1, size=(batch, sequence_len)) config= transformers.BertConfig(vocab_size=vocab_size,hidden_size=10,",
"num_classes) input_batch = torch.randint(low=0, high=vocab_size-1, size=(batch, sequence_len)) config= transformers.BertConfig(vocab_size=vocab_size,hidden_size=10, num_hidden_layers=1,",
"= (batch, sequence_len, num_classes) input_batch = torch.randint(low=0, high=vocab_size-1, size=(batch, sequence_len))",
"sut = BertModel(None, None, bert_config=config) # Act actual = sut.forward(input_batch)[0]",
"high=vocab_size-1, size=(batch, sequence_len)) config= transformers.BertConfig(vocab_size=vocab_size,hidden_size=10, num_hidden_layers=1, num_attention_heads=1,num_labels=num_classes) sut = BertModel(None,",
"= 10 sequence_len = 20 batch = 32 num_classes =",
"bert_config=config) # Act actual = sut.forward(input_batch)[0] # Assert self.assertEqual(expected_shape, actual.shape)",
"Bert Config vocab_size = 10 sequence_len = 20 batch =",
"BertModel class TestBertModel(TestCase): def test_forward(self): # Bert Config vocab_size =",
"BertModel(None, None, bert_config=config) # Act actual = sut.forward(input_batch)[0] # Assert",
"= BertModel(None, None, bert_config=config) # Act actual = sut.forward(input_batch)[0] #",
"unittest import TestCase import torch import transformers from model.bert_model import",
"TestCase import torch import transformers from model.bert_model import BertModel class",
"sequence_len)) config= transformers.BertConfig(vocab_size=vocab_size,hidden_size=10, num_hidden_layers=1, num_attention_heads=1,num_labels=num_classes) sut = BertModel(None, None, bert_config=config)",
"TestBertModel(TestCase): def test_forward(self): # Bert Config vocab_size = 10 sequence_len",
"config= transformers.BertConfig(vocab_size=vocab_size,hidden_size=10, num_hidden_layers=1, num_attention_heads=1,num_labels=num_classes) sut = BertModel(None, None, bert_config=config) #",
"size=(batch, sequence_len)) config= transformers.BertConfig(vocab_size=vocab_size,hidden_size=10, num_hidden_layers=1, num_attention_heads=1,num_labels=num_classes) sut = BertModel(None, None,",
"3 expected_shape = (batch, sequence_len, num_classes) input_batch = torch.randint(low=0, high=vocab_size-1,",
"transformers from model.bert_model import BertModel class TestBertModel(TestCase): def test_forward(self): #",
"expected_shape = (batch, sequence_len, num_classes) input_batch = torch.randint(low=0, high=vocab_size-1, size=(batch,",
"torch.randint(low=0, high=vocab_size-1, size=(batch, sequence_len)) config= transformers.BertConfig(vocab_size=vocab_size,hidden_size=10, num_hidden_layers=1, num_attention_heads=1,num_labels=num_classes) sut =",
"# Bert Config vocab_size = 10 sequence_len = 20 batch",
"transformers.BertConfig(vocab_size=vocab_size,hidden_size=10, num_hidden_layers=1, num_attention_heads=1,num_labels=num_classes) sut = BertModel(None, None, bert_config=config) # Act"
] |
[
"\"rendered_dungeon.png\") r = Renderer() r.render(dungeon, file_path=fp) assert os.path.exists(fp) @pytest.mark.slow def",
"from donjuan import Dungeon, DungeonRandomizer, Renderer class RendererTest(TestCase): def setUp(self):",
"is not None def test_scale(self): r = Renderer(scale=3) assert r.scale",
"and check for the file fp = os.path.join(self.TEMP_DIR, \"rendered_dungeon.png\") renderer.render(dungeon,",
"import json import os import tempfile from unittest import TestCase",
"= os.path.abspath(os.path.dirname(__file__)) inpath = os.path.join(inpath, \"fixtures/dummy_dungeon.json\") with open(inpath, \"r\") as",
"os.path.join(inpath, \"fixtures/dummy_dungeon.json\") with open(inpath, \"r\") as f: darr = json.load(f)[\"dungeon\"]",
"TestCase import pytest from donjuan import Dungeon, DungeonRandomizer, Renderer class",
"n_cols=n_cols) for i in range(n_rows): for j in range(n_cols): dungeon.grid.cells[i][j].filled",
"r = Renderer() r.render(dungeon, file_path=fp) assert os.path.exists(fp) @pytest.mark.slow def test_render_dungeon_with_rooms(self):",
"= len(darr) n_cols = len(darr) dungeon = Dungeon(n_rows=n_rows, n_cols=n_cols) for",
"range(n_rows): for j in range(n_cols): dungeon.grid.cells[i][j].filled = bool(darr[i][j]) # Render",
"3 @pytest.mark.slow def test_render_dummy_dungeon(self): inpath = os.path.abspath(os.path.dirname(__file__)) inpath = os.path.join(inpath,",
"test_render_dummy_dungeon(self): inpath = os.path.abspath(os.path.dirname(__file__)) inpath = os.path.join(inpath, \"fixtures/dummy_dungeon.json\") with open(inpath,",
"== 3 @pytest.mark.slow def test_render_dummy_dungeon(self): inpath = os.path.abspath(os.path.dirname(__file__)) inpath =",
"r = Renderer(scale=3) assert r.scale == 3 @pytest.mark.slow def test_render_dummy_dungeon(self):",
"@pytest.mark.slow def test_render_dummy_dungeon(self): inpath = os.path.abspath(os.path.dirname(__file__)) inpath = os.path.join(inpath, \"fixtures/dummy_dungeon.json\")",
"Render and check for the file fp = os.path.join(self.TEMP_DIR, \"rendered_dungeon.png\")",
"import TestCase import pytest from donjuan import Dungeon, DungeonRandomizer, Renderer",
"Renderer() assert r is not None def test_scale(self): r =",
"\"fixtures/dummy_dungeon.json\") with open(inpath, \"r\") as f: darr = json.load(f)[\"dungeon\"] n_rows",
"\"r\") as f: darr = json.load(f)[\"dungeon\"] n_rows = len(darr) n_cols",
"the file fp = os.path.join(self.TEMP_DIR, \"rendered_dungeon.png\") renderer.render(dungeon, file_path=fp) assert os.path.exists(fp)",
"n_cols = len(darr) dungeon = Dungeon(n_rows=n_rows, n_cols=n_cols) for i in",
"test_render_dungeon_with_rooms(self): randomizer = DungeonRandomizer() dungeon = Dungeon(10, 10, randomizers=[randomizer]) dungeon.randomize()",
"= json.load(f)[\"dungeon\"] n_rows = len(darr) n_cols = len(darr) dungeon =",
"= Renderer() assert r is not None def test_scale(self): r",
"Dungeon(n_rows=n_rows, n_cols=n_cols) for i in range(n_rows): for j in range(n_cols):",
"DungeonRandomizer, Renderer class RendererTest(TestCase): def setUp(self): super().setUp() self.TEMP_DIR = tempfile.mkdtemp()",
"donjuan import Dungeon, DungeonRandomizer, Renderer class RendererTest(TestCase): def setUp(self): super().setUp()",
"class RendererTest(TestCase): def setUp(self): super().setUp() self.TEMP_DIR = tempfile.mkdtemp() def test_smoke(self):",
"assert r.scale == 3 @pytest.mark.slow def test_render_dummy_dungeon(self): inpath = os.path.abspath(os.path.dirname(__file__))",
"r.scale == 3 @pytest.mark.slow def test_render_dummy_dungeon(self): inpath = os.path.abspath(os.path.dirname(__file__)) inpath",
"with open(inpath, \"r\") as f: darr = json.load(f)[\"dungeon\"] n_rows =",
"len(darr) dungeon = Dungeon(n_rows=n_rows, n_cols=n_cols) for i in range(n_rows): for",
"Renderer() r.render(dungeon, file_path=fp) assert os.path.exists(fp) @pytest.mark.slow def test_render_dungeon_with_rooms(self): randomizer =",
"darr = json.load(f)[\"dungeon\"] n_rows = len(darr) n_cols = len(darr) dungeon",
"randomizer = DungeonRandomizer() dungeon = Dungeon(10, 10, randomizers=[randomizer]) dungeon.randomize() dungeon.emplace_rooms()",
"json.load(f)[\"dungeon\"] n_rows = len(darr) n_cols = len(darr) dungeon = Dungeon(n_rows=n_rows,",
"os import tempfile from unittest import TestCase import pytest from",
"= bool(darr[i][j]) # Render and check for the file fp",
"check for the file fp = os.path.join(self.TEMP_DIR, \"rendered_dungeon.png\") r =",
"dungeon.randomize() dungeon.emplace_rooms() renderer = Renderer() # Render and check for",
"dungeon.emplace_rooms() renderer = Renderer() # Render and check for the",
"test_scale(self): r = Renderer(scale=3) assert r.scale == 3 @pytest.mark.slow def",
"def test_smoke(self): r = Renderer() assert r is not None",
"for the file fp = os.path.join(self.TEMP_DIR, \"rendered_dungeon.png\") r = Renderer()",
"tempfile from unittest import TestCase import pytest from donjuan import",
"pytest from donjuan import Dungeon, DungeonRandomizer, Renderer class RendererTest(TestCase): def",
"= DungeonRandomizer() dungeon = Dungeon(10, 10, randomizers=[randomizer]) dungeon.randomize() dungeon.emplace_rooms() renderer",
"os.path.abspath(os.path.dirname(__file__)) inpath = os.path.join(inpath, \"fixtures/dummy_dungeon.json\") with open(inpath, \"r\") as f:",
"import os import tempfile from unittest import TestCase import pytest",
"as f: darr = json.load(f)[\"dungeon\"] n_rows = len(darr) n_cols =",
"file fp = os.path.join(self.TEMP_DIR, \"rendered_dungeon.png\") r = Renderer() r.render(dungeon, file_path=fp)",
"assert os.path.exists(fp) @pytest.mark.slow def test_render_dungeon_with_rooms(self): randomizer = DungeonRandomizer() dungeon =",
"Renderer class RendererTest(TestCase): def setUp(self): super().setUp() self.TEMP_DIR = tempfile.mkdtemp() def",
"= Renderer() r.render(dungeon, file_path=fp) assert os.path.exists(fp) @pytest.mark.slow def test_render_dungeon_with_rooms(self): randomizer",
"i in range(n_rows): for j in range(n_cols): dungeon.grid.cells[i][j].filled = bool(darr[i][j])",
"= os.path.join(inpath, \"fixtures/dummy_dungeon.json\") with open(inpath, \"r\") as f: darr =",
"json import os import tempfile from unittest import TestCase import",
"n_rows = len(darr) n_cols = len(darr) dungeon = Dungeon(n_rows=n_rows, n_cols=n_cols)",
"r is not None def test_scale(self): r = Renderer(scale=3) assert",
"for i in range(n_rows): for j in range(n_cols): dungeon.grid.cells[i][j].filled =",
"not None def test_scale(self): r = Renderer(scale=3) assert r.scale ==",
"f: darr = json.load(f)[\"dungeon\"] n_rows = len(darr) n_cols = len(darr)",
"in range(n_cols): dungeon.grid.cells[i][j].filled = bool(darr[i][j]) # Render and check for",
"= len(darr) dungeon = Dungeon(n_rows=n_rows, n_cols=n_cols) for i in range(n_rows):",
"dungeon = Dungeon(n_rows=n_rows, n_cols=n_cols) for i in range(n_rows): for j",
"bool(darr[i][j]) # Render and check for the file fp =",
"Renderer() # Render and check for the file fp =",
"= os.path.join(self.TEMP_DIR, \"rendered_dungeon.png\") r = Renderer() r.render(dungeon, file_path=fp) assert os.path.exists(fp)",
"os.path.exists(fp) @pytest.mark.slow def test_render_dungeon_with_rooms(self): randomizer = DungeonRandomizer() dungeon = Dungeon(10,",
"from unittest import TestCase import pytest from donjuan import Dungeon,",
"open(inpath, \"r\") as f: darr = json.load(f)[\"dungeon\"] n_rows = len(darr)",
"test_smoke(self): r = Renderer() assert r is not None def",
"fp = os.path.join(self.TEMP_DIR, \"rendered_dungeon.png\") r = Renderer() r.render(dungeon, file_path=fp) assert",
"inpath = os.path.join(inpath, \"fixtures/dummy_dungeon.json\") with open(inpath, \"r\") as f: darr",
"check for the file fp = os.path.join(self.TEMP_DIR, \"rendered_dungeon.png\") renderer.render(dungeon, file_path=fp)",
"dungeon.grid.cells[i][j].filled = bool(darr[i][j]) # Render and check for the file",
"range(n_cols): dungeon.grid.cells[i][j].filled = bool(darr[i][j]) # Render and check for the",
"def test_render_dungeon_with_rooms(self): randomizer = DungeonRandomizer() dungeon = Dungeon(10, 10, randomizers=[randomizer])",
"self.TEMP_DIR = tempfile.mkdtemp() def test_smoke(self): r = Renderer() assert r",
"def setUp(self): super().setUp() self.TEMP_DIR = tempfile.mkdtemp() def test_smoke(self): r =",
"super().setUp() self.TEMP_DIR = tempfile.mkdtemp() def test_smoke(self): r = Renderer() assert",
"inpath = os.path.abspath(os.path.dirname(__file__)) inpath = os.path.join(inpath, \"fixtures/dummy_dungeon.json\") with open(inpath, \"r\")",
"# Render and check for the file fp = os.path.join(self.TEMP_DIR,",
"import tempfile from unittest import TestCase import pytest from donjuan",
"setUp(self): super().setUp() self.TEMP_DIR = tempfile.mkdtemp() def test_smoke(self): r = Renderer()",
"= Renderer() # Render and check for the file fp",
"import pytest from donjuan import Dungeon, DungeonRandomizer, Renderer class RendererTest(TestCase):",
"Dungeon, DungeonRandomizer, Renderer class RendererTest(TestCase): def setUp(self): super().setUp() self.TEMP_DIR =",
"file_path=fp) assert os.path.exists(fp) @pytest.mark.slow def test_render_dungeon_with_rooms(self): randomizer = DungeonRandomizer() dungeon",
"j in range(n_cols): dungeon.grid.cells[i][j].filled = bool(darr[i][j]) # Render and check",
"os.path.join(self.TEMP_DIR, \"rendered_dungeon.png\") r = Renderer() r.render(dungeon, file_path=fp) assert os.path.exists(fp) @pytest.mark.slow",
"Renderer(scale=3) assert r.scale == 3 @pytest.mark.slow def test_render_dummy_dungeon(self): inpath =",
"r = Renderer() assert r is not None def test_scale(self):",
"renderer = Renderer() # Render and check for the file",
"for j in range(n_cols): dungeon.grid.cells[i][j].filled = bool(darr[i][j]) # Render and",
"for the file fp = os.path.join(self.TEMP_DIR, \"rendered_dungeon.png\") renderer.render(dungeon, file_path=fp) assert",
"= Dungeon(n_rows=n_rows, n_cols=n_cols) for i in range(n_rows): for j in",
"@pytest.mark.slow def test_render_dungeon_with_rooms(self): randomizer = DungeonRandomizer() dungeon = Dungeon(10, 10,",
"r.render(dungeon, file_path=fp) assert os.path.exists(fp) @pytest.mark.slow def test_render_dungeon_with_rooms(self): randomizer = DungeonRandomizer()",
"= Renderer(scale=3) assert r.scale == 3 @pytest.mark.slow def test_render_dummy_dungeon(self): inpath",
"= Dungeon(10, 10, randomizers=[randomizer]) dungeon.randomize() dungeon.emplace_rooms() renderer = Renderer() #",
"RendererTest(TestCase): def setUp(self): super().setUp() self.TEMP_DIR = tempfile.mkdtemp() def test_smoke(self): r",
"DungeonRandomizer() dungeon = Dungeon(10, 10, randomizers=[randomizer]) dungeon.randomize() dungeon.emplace_rooms() renderer =",
"dungeon = Dungeon(10, 10, randomizers=[randomizer]) dungeon.randomize() dungeon.emplace_rooms() renderer = Renderer()",
"def test_scale(self): r = Renderer(scale=3) assert r.scale == 3 @pytest.mark.slow",
"10, randomizers=[randomizer]) dungeon.randomize() dungeon.emplace_rooms() renderer = Renderer() # Render and",
"unittest import TestCase import pytest from donjuan import Dungeon, DungeonRandomizer,",
"assert r is not None def test_scale(self): r = Renderer(scale=3)",
"in range(n_rows): for j in range(n_cols): dungeon.grid.cells[i][j].filled = bool(darr[i][j]) #",
"the file fp = os.path.join(self.TEMP_DIR, \"rendered_dungeon.png\") r = Renderer() r.render(dungeon,",
"None def test_scale(self): r = Renderer(scale=3) assert r.scale == 3",
"Dungeon(10, 10, randomizers=[randomizer]) dungeon.randomize() dungeon.emplace_rooms() renderer = Renderer() # Render",
"= tempfile.mkdtemp() def test_smoke(self): r = Renderer() assert r is",
"def test_render_dummy_dungeon(self): inpath = os.path.abspath(os.path.dirname(__file__)) inpath = os.path.join(inpath, \"fixtures/dummy_dungeon.json\") with",
"len(darr) n_cols = len(darr) dungeon = Dungeon(n_rows=n_rows, n_cols=n_cols) for i",
"and check for the file fp = os.path.join(self.TEMP_DIR, \"rendered_dungeon.png\") r",
"tempfile.mkdtemp() def test_smoke(self): r = Renderer() assert r is not",
"randomizers=[randomizer]) dungeon.randomize() dungeon.emplace_rooms() renderer = Renderer() # Render and check",
"import Dungeon, DungeonRandomizer, Renderer class RendererTest(TestCase): def setUp(self): super().setUp() self.TEMP_DIR"
] |
[
"validate functions.\"\"\" import logging from .consts import API_URL from .utils.credentials",
"connection.\"\"\" try: credentials = get_env_credential() LOG.debug('Found credentials: %s', credentials) LOG.info('Gate",
"\"\"\"Check Gate connection.\"\"\" try: credentials = get_env_credential() LOG.debug('Found credentials: %s',",
"try: credentials = get_env_credential() LOG.debug('Found credentials: %s', credentials) LOG.info('Gate working.')",
"LOG = logging.getLogger(__name__) def validate_gate(): \"\"\"Check Gate connection.\"\"\" try: credentials",
"%s', API_URL) def validate_all(args): \"\"\"Run all validate steps.\"\"\" LOG.debug('Args: %s',",
"logging.getLogger(__name__) def validate_gate(): \"\"\"Check Gate connection.\"\"\" try: credentials = get_env_credential()",
"= get_env_credential() LOG.debug('Found credentials: %s', credentials) LOG.info('Gate working.') except TypeError:",
"\"\"\"Spinnaker validate functions.\"\"\" import logging from .consts import API_URL from",
"validate steps.\"\"\" LOG.debug('Args: %s', args) LOG.info('Running all validate steps.') validate_gate()",
"import get_env_credential LOG = logging.getLogger(__name__) def validate_gate(): \"\"\"Check Gate connection.\"\"\"",
"connection not valid: API_URL = %s', API_URL) def validate_all(args): \"\"\"Run",
"import API_URL from .utils.credentials import get_env_credential LOG = logging.getLogger(__name__) def",
"import logging from .consts import API_URL from .utils.credentials import get_env_credential",
"= %s', API_URL) def validate_all(args): \"\"\"Run all validate steps.\"\"\" LOG.debug('Args:",
"<gh_stars>100-1000 \"\"\"Spinnaker validate functions.\"\"\" import logging from .consts import API_URL",
"API_URL from .utils.credentials import get_env_credential LOG = logging.getLogger(__name__) def validate_gate():",
"credentials) LOG.info('Gate working.') except TypeError: LOG.fatal('Gate connection not valid: API_URL",
".utils.credentials import get_env_credential LOG = logging.getLogger(__name__) def validate_gate(): \"\"\"Check Gate",
"\"\"\"Run all validate steps.\"\"\" LOG.debug('Args: %s', args) LOG.info('Running all validate",
"validate_gate(): \"\"\"Check Gate connection.\"\"\" try: credentials = get_env_credential() LOG.debug('Found credentials:",
"all validate steps.\"\"\" LOG.debug('Args: %s', args) LOG.info('Running all validate steps.')",
"= logging.getLogger(__name__) def validate_gate(): \"\"\"Check Gate connection.\"\"\" try: credentials =",
"Gate connection.\"\"\" try: credentials = get_env_credential() LOG.debug('Found credentials: %s', credentials)",
"working.') except TypeError: LOG.fatal('Gate connection not valid: API_URL = %s',",
"def validate_all(args): \"\"\"Run all validate steps.\"\"\" LOG.debug('Args: %s', args) LOG.info('Running",
"from .utils.credentials import get_env_credential LOG = logging.getLogger(__name__) def validate_gate(): \"\"\"Check",
"get_env_credential LOG = logging.getLogger(__name__) def validate_gate(): \"\"\"Check Gate connection.\"\"\" try:",
"%s', credentials) LOG.info('Gate working.') except TypeError: LOG.fatal('Gate connection not valid:",
"not valid: API_URL = %s', API_URL) def validate_all(args): \"\"\"Run all",
"validate_all(args): \"\"\"Run all validate steps.\"\"\" LOG.debug('Args: %s', args) LOG.info('Running all",
"logging from .consts import API_URL from .utils.credentials import get_env_credential LOG",
".consts import API_URL from .utils.credentials import get_env_credential LOG = logging.getLogger(__name__)",
"credentials = get_env_credential() LOG.debug('Found credentials: %s', credentials) LOG.info('Gate working.') except",
"functions.\"\"\" import logging from .consts import API_URL from .utils.credentials import",
"except TypeError: LOG.fatal('Gate connection not valid: API_URL = %s', API_URL)",
"TypeError: LOG.fatal('Gate connection not valid: API_URL = %s', API_URL) def",
"def validate_gate(): \"\"\"Check Gate connection.\"\"\" try: credentials = get_env_credential() LOG.debug('Found",
"LOG.debug('Found credentials: %s', credentials) LOG.info('Gate working.') except TypeError: LOG.fatal('Gate connection",
"LOG.fatal('Gate connection not valid: API_URL = %s', API_URL) def validate_all(args):",
"from .consts import API_URL from .utils.credentials import get_env_credential LOG =",
"LOG.info('Gate working.') except TypeError: LOG.fatal('Gate connection not valid: API_URL =",
"get_env_credential() LOG.debug('Found credentials: %s', credentials) LOG.info('Gate working.') except TypeError: LOG.fatal('Gate",
"credentials: %s', credentials) LOG.info('Gate working.') except TypeError: LOG.fatal('Gate connection not",
"valid: API_URL = %s', API_URL) def validate_all(args): \"\"\"Run all validate",
"API_URL) def validate_all(args): \"\"\"Run all validate steps.\"\"\" LOG.debug('Args: %s', args)",
"API_URL = %s', API_URL) def validate_all(args): \"\"\"Run all validate steps.\"\"\""
] |
[
"migrations.CreateModel( name='Form', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('form_id', models.IntegerField()),",
"name='FormSubmission', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('state', models.IntegerField(choices=[(0, 'draft'),",
"name='Validator', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.TextField()), ('regex',",
"('name', models.TextField()), ('description', models.TextField(blank=True)), ('elements', django.contrib.postgres.fields.jsonb.JSONField()), ], options={ 'ordering': ('-version',),",
"django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL),",
"'db_table': 'form', }, ), migrations.CreateModel( name='FormSubmission', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"unicode_literals from django.conf import settings import django.contrib.postgres.fields.jsonb from django.db import",
"fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('form_id', models.IntegerField()), ('version', models.IntegerField()),",
"verbose_name='ID')), ('form_id', models.IntegerField()), ('version', models.IntegerField()), ('name', models.TextField()), ('description', models.TextField(blank=True)), ('elements',",
"models.TextField()), ('description', models.TextField(blank=True)), ('elements', django.contrib.postgres.fields.jsonb.JSONField()), ], options={ 'ordering': ('-version',), 'db_table':",
"options={ 'db_table': 'form_submission', }, ), migrations.CreateModel( name='Validator', fields=[ ('id', models.AutoField(auto_created=True,",
"= True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [",
"models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('state', models.IntegerField(choices=[(0, 'draft'), (1, 'submitted'), (2,",
"django.contrib.postgres.fields.jsonb.JSONField()), ('form', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='constellation_forms.Form')), ('owner', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ],",
"], options={ 'ordering': ('-version',), 'db_table': 'form', }, ), migrations.CreateModel( name='FormSubmission',",
"serialize=False, verbose_name='ID')), ('name', models.TextField()), ('regex', models.TextField()), ], options={ 'db_table': 'validators',",
"__future__ import unicode_literals from django.conf import settings import django.contrib.postgres.fields.jsonb from",
"to=settings.AUTH_USER_MODEL)), ], options={ 'db_table': 'form_submission', }, ), migrations.CreateModel( name='Validator', fields=[",
"models.IntegerField()), ('name', models.TextField()), ('description', models.TextField(blank=True)), ('elements', django.contrib.postgres.fields.jsonb.JSONField()), ], options={ 'ordering':",
"from __future__ import unicode_literals from django.conf import settings import django.contrib.postgres.fields.jsonb",
"('state', models.IntegerField(choices=[(0, 'draft'), (1, 'submitted'), (2, 'approved'), (3, 'denied')])), ('modified',",
"'denied')])), ('modified', models.DateField()), ('submission', django.contrib.postgres.fields.jsonb.JSONField()), ('form', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='constellation_forms.Form')), ('owner', models.ForeignKey(blank=True,",
"-*- coding: utf-8 -*- # Generated by Django 1.10.6 on",
"00:56 from __future__ import unicode_literals from django.conf import settings import",
"[ migrations.CreateModel( name='Form', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('form_id',",
"'draft'), (1, 'submitted'), (2, 'approved'), (3, 'denied')])), ('modified', models.DateField()), ('submission',",
"), migrations.CreateModel( name='Validator', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name',",
"import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [",
"import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True",
"models.IntegerField(choices=[(0, 'draft'), (1, 'submitted'), (2, 'approved'), (3, 'denied')])), ('modified', models.DateField()),",
"('submission', django.contrib.postgres.fields.jsonb.JSONField()), ('form', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='constellation_forms.Form')), ('owner', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),",
"to='constellation_forms.Form')), ('owner', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'db_table': 'form_submission',",
"import unicode_literals from django.conf import settings import django.contrib.postgres.fields.jsonb from django.db",
"migrations.CreateModel( name='FormSubmission', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('state', models.IntegerField(choices=[(0,",
"migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Form', fields=[ ('id', models.AutoField(auto_created=True,",
"1.10.6 on 2017-03-15 00:56 from __future__ import unicode_literals from django.conf",
"models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='constellation_forms.Form')), ('owner', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'db_table':",
"models.TextField()), ], options={ 'db_table': 'validators', }, ), migrations.AlterUniqueTogether( name='form', unique_together=set([('form_id',",
"('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('form_id', models.IntegerField()), ('version', models.IntegerField()), ('name',",
"('version', models.IntegerField()), ('name', models.TextField()), ('description', models.TextField(blank=True)), ('elements', django.contrib.postgres.fields.jsonb.JSONField()), ], options={",
"('description', models.TextField(blank=True)), ('elements', django.contrib.postgres.fields.jsonb.JSONField()), ], options={ 'ordering': ('-version',), 'db_table': 'form',",
"'form_submission', }, ), migrations.CreateModel( name='Validator', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"models.TextField()), ('regex', models.TextField()), ], options={ 'db_table': 'validators', }, ), migrations.AlterUniqueTogether(",
"models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies =",
"django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial =",
"primary_key=True, serialize=False, verbose_name='ID')), ('state', models.IntegerField(choices=[(0, 'draft'), (1, 'submitted'), (2, 'approved'),",
"[ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Form', fields=[ ('id',",
"initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations =",
"settings import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion",
"('-version',), 'db_table': 'form', }, ), migrations.CreateModel( name='FormSubmission', fields=[ ('id', models.AutoField(auto_created=True,",
"}, ), migrations.CreateModel( name='FormSubmission', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"name='Form', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('form_id', models.IntegerField()), ('version',",
"], options={ 'db_table': 'form_submission', }, ), migrations.CreateModel( name='Validator', fields=[ ('id',",
"options={ 'db_table': 'validators', }, ), migrations.AlterUniqueTogether( name='form', unique_together=set([('form_id', 'version')]), ),",
"from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial",
"('form_id', models.IntegerField()), ('version', models.IntegerField()), ('name', models.TextField()), ('description', models.TextField(blank=True)), ('elements', django.contrib.postgres.fields.jsonb.JSONField()),",
"verbose_name='ID')), ('name', models.TextField()), ('regex', models.TextField()), ], options={ 'db_table': 'validators', },",
"Django 1.10.6 on 2017-03-15 00:56 from __future__ import unicode_literals from",
"class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ]",
"('form', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='constellation_forms.Form')), ('owner', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={",
"('regex', models.TextField()), ], options={ 'db_table': 'validators', }, ), migrations.AlterUniqueTogether( name='form',",
"('elements', django.contrib.postgres.fields.jsonb.JSONField()), ], options={ 'ordering': ('-version',), 'db_table': 'form', }, ),",
"('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.TextField()), ('regex', models.TextField()), ],",
"import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion class",
"models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.TextField()), ('regex', models.TextField()), ], options={",
"True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel(",
"<filename>constellation_forms/migrations/0001_initial.py # -*- coding: utf-8 -*- # Generated by Django",
"fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('state', models.IntegerField(choices=[(0, 'draft'), (1,",
"# -*- coding: utf-8 -*- # Generated by Django 1.10.6",
"migrations.CreateModel( name='Validator', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.TextField()),",
"from django.conf import settings import django.contrib.postgres.fields.jsonb from django.db import migrations,",
"= [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Form', fields=[",
"migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies",
"'form', }, ), migrations.CreateModel( name='FormSubmission', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations",
"2017-03-15 00:56 from __future__ import unicode_literals from django.conf import settings",
"verbose_name='ID')), ('state', models.IntegerField(choices=[(0, 'draft'), (1, 'submitted'), (2, 'approved'), (3, 'denied')])),",
"primary_key=True, serialize=False, verbose_name='ID')), ('form_id', models.IntegerField()), ('version', models.IntegerField()), ('name', models.TextField()), ('description',",
"('owner', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'db_table': 'form_submission', },",
"models.IntegerField()), ('version', models.IntegerField()), ('name', models.TextField()), ('description', models.TextField(blank=True)), ('elements', django.contrib.postgres.fields.jsonb.JSONField()), ],",
"('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('state', models.IntegerField(choices=[(0, 'draft'), (1, 'submitted'),",
"primary_key=True, serialize=False, verbose_name='ID')), ('name', models.TextField()), ('regex', models.TextField()), ], options={ 'db_table':",
"import settings import django.contrib.postgres.fields.jsonb from django.db import migrations, models import",
"dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Form',",
"= [ migrations.CreateModel( name='Form', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"}, ), migrations.CreateModel( name='Validator', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"on 2017-03-15 00:56 from __future__ import unicode_literals from django.conf import",
"('name', models.TextField()), ('regex', models.TextField()), ], options={ 'db_table': 'validators', }, ),",
"'ordering': ('-version',), 'db_table': 'form', }, ), migrations.CreateModel( name='FormSubmission', fields=[ ('id',",
"fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.TextField()), ('regex', models.TextField()),",
"(2, 'approved'), (3, 'denied')])), ('modified', models.DateField()), ('submission', django.contrib.postgres.fields.jsonb.JSONField()), ('form', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,",
"Generated by Django 1.10.6 on 2017-03-15 00:56 from __future__ import",
"] operations = [ migrations.CreateModel( name='Form', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"options={ 'ordering': ('-version',), 'db_table': 'form', }, ), migrations.CreateModel( name='FormSubmission', fields=[",
"-*- # Generated by Django 1.10.6 on 2017-03-15 00:56 from",
"# Generated by Django 1.10.6 on 2017-03-15 00:56 from __future__",
"'submitted'), (2, 'approved'), (3, 'denied')])), ('modified', models.DateField()), ('submission', django.contrib.postgres.fields.jsonb.JSONField()), ('form',",
"('modified', models.DateField()), ('submission', django.contrib.postgres.fields.jsonb.JSONField()), ('form', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='constellation_forms.Form')), ('owner', models.ForeignKey(blank=True, null=True,",
"null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'db_table': 'form_submission', }, ), migrations.CreateModel(",
"], options={ 'db_table': 'validators', }, ), migrations.AlterUniqueTogether( name='form', unique_together=set([('form_id', 'version')]),",
"by Django 1.10.6 on 2017-03-15 00:56 from __future__ import unicode_literals",
"serialize=False, verbose_name='ID')), ('form_id', models.IntegerField()), ('version', models.IntegerField()), ('name', models.TextField()), ('description', models.TextField(blank=True)),",
"django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):",
"django.conf import settings import django.contrib.postgres.fields.jsonb from django.db import migrations, models",
"utf-8 -*- # Generated by Django 1.10.6 on 2017-03-15 00:56",
"(1, 'submitted'), (2, 'approved'), (3, 'denied')])), ('modified', models.DateField()), ('submission', django.contrib.postgres.fields.jsonb.JSONField()),",
"models.TextField(blank=True)), ('elements', django.contrib.postgres.fields.jsonb.JSONField()), ], options={ 'ordering': ('-version',), 'db_table': 'form', },",
"), migrations.CreateModel( name='FormSubmission', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('state',",
"'db_table': 'form_submission', }, ), migrations.CreateModel( name='Validator', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('form_id', models.IntegerField()), ('version', models.IntegerField()), ('name', models.TextField()),",
"'approved'), (3, 'denied')])), ('modified', models.DateField()), ('submission', django.contrib.postgres.fields.jsonb.JSONField()), ('form', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='constellation_forms.Form')),",
"'db_table': 'validators', }, ), migrations.AlterUniqueTogether( name='form', unique_together=set([('form_id', 'version')]), ), ]",
"serialize=False, verbose_name='ID')), ('state', models.IntegerField(choices=[(0, 'draft'), (1, 'submitted'), (2, 'approved'), (3,",
"models.DateField()), ('submission', django.contrib.postgres.fields.jsonb.JSONField()), ('form', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='constellation_forms.Form')), ('owner', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE,",
"models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'db_table': 'form_submission', }, ),",
"operations = [ migrations.CreateModel( name='Form', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'db_table': 'form_submission', }, ), migrations.CreateModel( name='Validator',",
"coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-15",
"django.contrib.postgres.fields.jsonb.JSONField()), ], options={ 'ordering': ('-version',), 'db_table': 'form', }, ), migrations.CreateModel(",
"(3, 'denied')])), ('modified', models.DateField()), ('submission', django.contrib.postgres.fields.jsonb.JSONField()), ('form', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='constellation_forms.Form')), ('owner',"
] |
[
"self.cursor.fetchall() return r def showone(self): return self.cursor.fetchone() def __del__(self): self.cursor.close()",
"self.conn = sqlite.connect(osp.abspath(dbname)) except Exception, what: print what sys.exit() self.conn.row_factory",
"def query(self, sql): try: self.cursor.execute(sql) self.conn.commit() except Exception, what: print",
"try: self.cursor.execute(sql) self.conn.commit() except Exception, what: print what def show(self):",
"[com]([url]); ''') print 'create map index' self.conn.commit() def query(self, sql):",
"r = self.cursor.fetchall() return r def showone(self): return self.cursor.fetchone() def",
"-*- coding: utf-8 -*- import sqlite3 as sqlite import os.path",
"<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- import sqlite3",
"print \"create table com \" self.cursor.execute(''' CREATE INDEX IF NOT",
"IF NOT EXISTS [website_idx_url] ON [com]([url]); ''') print 'create map",
"ON [com]([url]); ''') print 'create map index' self.conn.commit() def createTable_58(self):",
"coding: utf-8 -*- import sqlite3 as sqlite import os.path as",
"show(self): r = self.cursor.fetchall() return r def showone(self): return self.cursor.fetchone()",
"def createTable_com(self): self.cursor.execute(''' CREATE TABLE IF NOT EXISTS [com]( [id]",
"sqlite3 as sqlite import os.path as osp import sys class",
"self.cursor.execute(''' CREATE INDEX IF NOT EXISTS [website_idx_url] ON [com]([url]); ''')",
"class Sqli(object): conn = '' cursor = '' def __init__(self,",
"self.conn.commit() def createTable_58(self): self.cursor.execute(''' CREATE TABLE IF NOT EXISTS [com](",
"Exception, what: print what def show(self): r = self.cursor.fetchall() return",
"self.conn.commit() except Exception, what: print what def show(self): r =",
"[website_idx_siteName] ON [website]([siteName]); ''') print 'create website index' self.conn.commit() def",
"what: print what sys.exit() self.conn.row_factory = sqlite.Row self.cursor = self.conn.cursor()",
"INDEX IF NOT EXISTS [website_idx_siteName] ON [website]([siteName]); ''') print 'create",
"''') print \"create table com \" self.cursor.execute(''' CREATE INDEX IF",
"[postUrl] TEXT, [postQuery] TEXT, UNIQUE([siteName])); ''') print \"create table website",
"ON [com]([url]); ''') print 'create map index' self.conn.commit() def query(self,",
"except Exception, what: print what sys.exit() self.conn.row_factory = sqlite.Row self.cursor",
"= sqlite.Row self.cursor = self.conn.cursor() def createTable(self): self.cursor.execute(''' CREATE TABLE",
"'create map index' self.conn.commit() def createTable_58(self): self.cursor.execute(''' CREATE TABLE IF",
"\" self.cursor.execute(''' CREATE INDEX IF NOT EXISTS [website_idx_siteName] ON [website]([siteName]);",
"Sqli(object): conn = '' cursor = '' def __init__(self, dbname):",
"self.conn.cursor() def createTable(self): self.cursor.execute(''' CREATE TABLE IF NOT EXISTS [website](",
"[id] INTEGER PRIMARY KEY, [title] TEXT, [city] TEXT, [url] TEXT,",
"table website \" self.cursor.execute(''' CREATE INDEX IF NOT EXISTS [website_idx_siteName]",
"[website_idx_url] ON [com]([url]); ''') print 'create map index' self.conn.commit() def",
"import os.path as osp import sys class Sqli(object): conn =",
"com \" self.cursor.execute(''' CREATE INDEX IF NOT EXISTS [website_idx_url] ON",
"index' self.conn.commit() def query(self, sql): try: self.cursor.execute(sql) self.conn.commit() except Exception,",
"PRIMARY KEY, [siteName] TEXT, [loginUrl] TEXT, [loginQuery] TEXT, [postUrl] TEXT,",
"[url] TEXT, UNIQUE([url])); ''') print \"create table com \" self.cursor.execute('''",
"sqlite import os.path as osp import sys class Sqli(object): conn",
"'' def __init__(self, dbname): try: self.conn = sqlite.connect(osp.abspath(dbname)) except Exception,",
"sql): try: self.cursor.execute(sql) self.conn.commit() except Exception, what: print what def",
"''') print 'create website index' self.conn.commit() def createTable_com(self): self.cursor.execute(''' CREATE",
"import sqlite3 as sqlite import os.path as osp import sys",
"IF NOT EXISTS [website]( [id] INTEGER PRIMARY KEY, [siteName] TEXT,",
"def createTable(self): self.cursor.execute(''' CREATE TABLE IF NOT EXISTS [website]( [id]",
"def __init__(self, dbname): try: self.conn = sqlite.connect(osp.abspath(dbname)) except Exception, what:",
"website index' self.conn.commit() def createTable_com(self): self.cursor.execute(''' CREATE TABLE IF NOT",
"sys class Sqli(object): conn = '' cursor = '' def",
"CREATE TABLE IF NOT EXISTS [com]( [id] INTEGER PRIMARY KEY,",
"\"create table com \" self.cursor.execute(''' CREATE INDEX IF NOT EXISTS",
"as sqlite import os.path as osp import sys class Sqli(object):",
"self.cursor.execute(''' CREATE TABLE IF NOT EXISTS [com]( [id] INTEGER PRIMARY",
"[website]( [id] INTEGER PRIMARY KEY, [siteName] TEXT, [loginUrl] TEXT, [loginQuery]",
"[id] INTEGER PRIMARY KEY, [siteName] TEXT, [loginUrl] TEXT, [loginQuery] TEXT,",
"website \" self.cursor.execute(''' CREATE INDEX IF NOT EXISTS [website_idx_siteName] ON",
"EXISTS [com]( [id] INTEGER PRIMARY KEY, [title] TEXT, [city] TEXT,",
"KEY, [title] TEXT, [city] TEXT, [url] TEXT, UNIQUE([url])); ''') print",
"table com \" self.cursor.execute(''' CREATE INDEX IF NOT EXISTS [website_idx_url]",
"except Exception, what: print what def show(self): r = self.cursor.fetchall()",
"what: print what def show(self): r = self.cursor.fetchall() return r",
"print what def show(self): r = self.cursor.fetchall() return r def",
"dbname): try: self.conn = sqlite.connect(osp.abspath(dbname)) except Exception, what: print what",
"print 'create map index' self.conn.commit() def createTable_58(self): self.cursor.execute(''' CREATE TABLE",
"self.conn.commit() def createTable_com(self): self.cursor.execute(''' CREATE TABLE IF NOT EXISTS [com](",
"conn = '' cursor = '' def __init__(self, dbname): try:",
"print what sys.exit() self.conn.row_factory = sqlite.Row self.cursor = self.conn.cursor() def",
"osp import sys class Sqli(object): conn = '' cursor =",
"[loginQuery] TEXT, [postUrl] TEXT, [postQuery] TEXT, UNIQUE([siteName])); ''') print \"create",
"import sys class Sqli(object): conn = '' cursor = ''",
"[postQuery] TEXT, UNIQUE([siteName])); ''') print \"create table website \" self.cursor.execute('''",
"-*- import sqlite3 as sqlite import os.path as osp import",
"EXISTS [website_idx_url] ON [com]([url]); ''') print 'create map index' self.conn.commit()",
"utf-8 -*- import sqlite3 as sqlite import os.path as osp",
"'' cursor = '' def __init__(self, dbname): try: self.conn =",
"PRIMARY KEY, [title] TEXT, [city] TEXT, [url] TEXT, UNIQUE([url])); ''')",
"''') print 'create map index' self.conn.commit() def createTable_58(self): self.cursor.execute(''' CREATE",
"CREATE INDEX IF NOT EXISTS [website_idx_siteName] ON [website]([siteName]); ''') print",
"TEXT, [postQuery] TEXT, UNIQUE([siteName])); ''') print \"create table website \"",
"[city] TEXT, [url] TEXT, UNIQUE([url])); ''') print \"create table com",
"CREATE INDEX IF NOT EXISTS [website_idx_url] ON [com]([url]); ''') print",
"self.conn.row_factory = sqlite.Row self.cursor = self.conn.cursor() def createTable(self): self.cursor.execute(''' CREATE",
"'create map index' self.conn.commit() def query(self, sql): try: self.cursor.execute(sql) self.conn.commit()",
"EXISTS [website]( [id] INTEGER PRIMARY KEY, [siteName] TEXT, [loginUrl] TEXT,",
"TEXT, [postUrl] TEXT, [postQuery] TEXT, UNIQUE([siteName])); ''') print \"create table",
"[title] TEXT, [city] TEXT, [url] TEXT, UNIQUE([url])); ''') print \"create",
"= sqlite.connect(osp.abspath(dbname)) except Exception, what: print what sys.exit() self.conn.row_factory =",
"TEXT, [city] TEXT, [url] TEXT, UNIQUE([url])); ''') print \"create table",
"[website]([siteName]); ''') print 'create website index' self.conn.commit() def createTable_com(self): self.cursor.execute('''",
"map index' self.conn.commit() def query(self, sql): try: self.cursor.execute(sql) self.conn.commit() except",
"self.cursor.execute(''' CREATE INDEX IF NOT EXISTS [website_idx_siteName] ON [website]([siteName]); ''')",
"TABLE IF NOT EXISTS [com]( [id] INTEGER PRIMARY KEY, [title]",
"map index' self.conn.commit() def createTable_58(self): self.cursor.execute(''' CREATE TABLE IF NOT",
"self.cursor.execute(''' CREATE TABLE IF NOT EXISTS [website]( [id] INTEGER PRIMARY",
"print 'create website index' self.conn.commit() def createTable_com(self): self.cursor.execute(''' CREATE TABLE",
"createTable_com(self): self.cursor.execute(''' CREATE TABLE IF NOT EXISTS [com]( [id] INTEGER",
"''') print \"create table website \" self.cursor.execute(''' CREATE INDEX IF",
"__init__(self, dbname): try: self.conn = sqlite.connect(osp.abspath(dbname)) except Exception, what: print",
"sqlite.Row self.cursor = self.conn.cursor() def createTable(self): self.cursor.execute(''' CREATE TABLE IF",
"EXISTS [website_idx_siteName] ON [website]([siteName]); ''') print 'create website index' self.conn.commit()",
"createTable_58(self): self.cursor.execute(''' CREATE TABLE IF NOT EXISTS [com]( [id] INTEGER",
"self.cursor = self.conn.cursor() def createTable(self): self.cursor.execute(''' CREATE TABLE IF NOT",
"index' self.conn.commit() def createTable_58(self): self.cursor.execute(''' CREATE TABLE IF NOT EXISTS",
"sqlite.connect(osp.abspath(dbname)) except Exception, what: print what sys.exit() self.conn.row_factory = sqlite.Row",
"INTEGER PRIMARY KEY, [title] TEXT, [city] TEXT, [url] TEXT, UNIQUE([url]));",
"UNIQUE([siteName])); ''') print \"create table website \" self.cursor.execute(''' CREATE INDEX",
"\" self.cursor.execute(''' CREATE INDEX IF NOT EXISTS [website_idx_url] ON [com]([url]);",
"print \"create table website \" self.cursor.execute(''' CREATE INDEX IF NOT",
"INDEX IF NOT EXISTS [website_idx_url] ON [com]([url]); ''') print 'create",
"# -*- coding: utf-8 -*- import sqlite3 as sqlite import",
"NOT EXISTS [website_idx_siteName] ON [website]([siteName]); ''') print 'create website index'",
"self.cursor.execute(sql) self.conn.commit() except Exception, what: print what def show(self): r",
"TABLE IF NOT EXISTS [website]( [id] INTEGER PRIMARY KEY, [siteName]",
"TEXT, [url] TEXT, UNIQUE([url])); ''') print \"create table com \"",
"sys.exit() self.conn.row_factory = sqlite.Row self.cursor = self.conn.cursor() def createTable(self): self.cursor.execute('''",
"try: self.conn = sqlite.connect(osp.abspath(dbname)) except Exception, what: print what sys.exit()",
"= self.conn.cursor() def createTable(self): self.cursor.execute(''' CREATE TABLE IF NOT EXISTS",
"print 'create map index' self.conn.commit() def query(self, sql): try: self.cursor.execute(sql)",
"TEXT, [loginUrl] TEXT, [loginQuery] TEXT, [postUrl] TEXT, [postQuery] TEXT, UNIQUE([siteName]));",
"cursor = '' def __init__(self, dbname): try: self.conn = sqlite.connect(osp.abspath(dbname))",
"[siteName] TEXT, [loginUrl] TEXT, [loginQuery] TEXT, [postUrl] TEXT, [postQuery] TEXT,",
"[loginUrl] TEXT, [loginQuery] TEXT, [postUrl] TEXT, [postQuery] TEXT, UNIQUE([siteName])); ''')",
"return r def showone(self): return self.cursor.fetchone() def __del__(self): self.cursor.close() self.conn.close()",
"[com]( [id] INTEGER PRIMARY KEY, [title] TEXT, [city] TEXT, [url]",
"NOT EXISTS [website_idx_url] ON [com]([url]); ''') print 'create map index'",
"NOT EXISTS [com]( [id] INTEGER PRIMARY KEY, [title] TEXT, [city]",
"TEXT, UNIQUE([url])); ''') print \"create table com \" self.cursor.execute(''' CREATE",
"self.conn.commit() def query(self, sql): try: self.cursor.execute(sql) self.conn.commit() except Exception, what:",
"what sys.exit() self.conn.row_factory = sqlite.Row self.cursor = self.conn.cursor() def createTable(self):",
"os.path as osp import sys class Sqli(object): conn = ''",
"UNIQUE([url])); ''') print \"create table com \" self.cursor.execute(''' CREATE INDEX",
"''') print 'create map index' self.conn.commit() def query(self, sql): try:",
"= self.cursor.fetchall() return r def showone(self): return self.cursor.fetchone() def __del__(self):",
"INTEGER PRIMARY KEY, [siteName] TEXT, [loginUrl] TEXT, [loginQuery] TEXT, [postUrl]",
"def show(self): r = self.cursor.fetchall() return r def showone(self): return",
"= '' cursor = '' def __init__(self, dbname): try: self.conn",
"IF NOT EXISTS [website_idx_siteName] ON [website]([siteName]); ''') print 'create website",
"#!/usr/bin/env python # -*- coding: utf-8 -*- import sqlite3 as",
"NOT EXISTS [website]( [id] INTEGER PRIMARY KEY, [siteName] TEXT, [loginUrl]",
"= '' def __init__(self, dbname): try: self.conn = sqlite.connect(osp.abspath(dbname)) except",
"query(self, sql): try: self.cursor.execute(sql) self.conn.commit() except Exception, what: print what",
"as osp import sys class Sqli(object): conn = '' cursor",
"TEXT, [loginQuery] TEXT, [postUrl] TEXT, [postQuery] TEXT, UNIQUE([siteName])); ''') print",
"index' self.conn.commit() def createTable_com(self): self.cursor.execute(''' CREATE TABLE IF NOT EXISTS",
"CREATE TABLE IF NOT EXISTS [website]( [id] INTEGER PRIMARY KEY,",
"[com]([url]); ''') print 'create map index' self.conn.commit() def createTable_58(self): self.cursor.execute('''",
"python # -*- coding: utf-8 -*- import sqlite3 as sqlite",
"TEXT, UNIQUE([siteName])); ''') print \"create table website \" self.cursor.execute(''' CREATE",
"createTable(self): self.cursor.execute(''' CREATE TABLE IF NOT EXISTS [website]( [id] INTEGER",
"IF NOT EXISTS [com]( [id] INTEGER PRIMARY KEY, [title] TEXT,",
"def createTable_58(self): self.cursor.execute(''' CREATE TABLE IF NOT EXISTS [com]( [id]",
"\"create table website \" self.cursor.execute(''' CREATE INDEX IF NOT EXISTS",
"'create website index' self.conn.commit() def createTable_com(self): self.cursor.execute(''' CREATE TABLE IF",
"KEY, [siteName] TEXT, [loginUrl] TEXT, [loginQuery] TEXT, [postUrl] TEXT, [postQuery]",
"ON [website]([siteName]); ''') print 'create website index' self.conn.commit() def createTable_com(self):",
"Exception, what: print what sys.exit() self.conn.row_factory = sqlite.Row self.cursor =",
"what def show(self): r = self.cursor.fetchall() return r def showone(self):"
] |
[
"center_loss import Centerloss import torch.nn as nn from FocalLoss import",
"loss(pred,label) def Focal_loss(pred,label,num_calss,alaph=None, gamma): loss = Centerloss(num_calss,gamma) return loss(pred,label) def",
"def L1_loss(pred,label): loss = nn.L1Loss(pred,label) return loss def L2_loss(pred,label): loss",
"import FocalLoss def center_loss(pred,label,num_calss,feature): loss = Centerloss(num_calss,feature) return loss(pred,label) def",
"Centerloss(num_calss,feature) return loss(pred,label) def Focal_loss(pred,label,num_calss,alaph=None, gamma): loss = Centerloss(num_calss,gamma) return",
"FocalLoss def center_loss(pred,label,num_calss,feature): loss = Centerloss(num_calss,feature) return loss(pred,label) def Focal_loss(pred,label,num_calss,alaph=None,",
"torch.nn as nn from FocalLoss import FocalLoss def center_loss(pred,label,num_calss,feature): loss",
"return loss(pred,label) def Focal_loss(pred,label,num_calss,alaph=None, gamma): loss = Centerloss(num_calss,gamma) return loss(pred,label)",
"nn.MSELoss(pred,label) return loss def SmoothL1_loss(pred,label): loss = nn.SmoothL1Loss(pred,label) return loss",
"as nn from FocalLoss import FocalLoss def center_loss(pred,label,num_calss,feature): loss =",
"easy way to use losses \"\"\" from center_loss import Centerloss",
"import Centerloss import torch.nn as nn from FocalLoss import FocalLoss",
"nn from FocalLoss import FocalLoss def center_loss(pred,label,num_calss,feature): loss = Centerloss(num_calss,feature)",
"loss = nn.MSELoss(pred,label) return loss def SmoothL1_loss(pred,label): loss = nn.SmoothL1Loss(pred,label)",
"from center_loss import Centerloss import torch.nn as nn from FocalLoss",
"to use losses \"\"\" from center_loss import Centerloss import torch.nn",
"center_loss(pred,label,num_calss,feature): loss = Centerloss(num_calss,feature) return loss(pred,label) def Focal_loss(pred,label,num_calss,alaph=None, gamma): loss",
"Centerloss(num_calss,gamma) return loss(pred,label) def L1_loss(pred,label): loss = nn.L1Loss(pred,label) return loss",
"= nn.MSELoss(pred,label) return loss def SmoothL1_loss(pred,label): loss = nn.SmoothL1Loss(pred,label) return",
"\"\"\" easy way to use losses \"\"\" from center_loss import",
"\"\"\" from center_loss import Centerloss import torch.nn as nn from",
"import torch.nn as nn from FocalLoss import FocalLoss def center_loss(pred,label,num_calss,feature):",
"FocalLoss import FocalLoss def center_loss(pred,label,num_calss,feature): loss = Centerloss(num_calss,feature) return loss(pred,label)",
"losses \"\"\" from center_loss import Centerloss import torch.nn as nn",
"def Focal_loss(pred,label,num_calss,alaph=None, gamma): loss = Centerloss(num_calss,gamma) return loss(pred,label) def L1_loss(pred,label):",
"nn.L1Loss(pred,label) return loss def L2_loss(pred,label): loss = nn.MSELoss(pred,label) return loss",
"return loss def L2_loss(pred,label): loss = nn.MSELoss(pred,label) return loss def",
"loss = Centerloss(num_calss,feature) return loss(pred,label) def Focal_loss(pred,label,num_calss,alaph=None, gamma): loss =",
"use losses \"\"\" from center_loss import Centerloss import torch.nn as",
"gamma): loss = Centerloss(num_calss,gamma) return loss(pred,label) def L1_loss(pred,label): loss =",
"def center_loss(pred,label,num_calss,feature): loss = Centerloss(num_calss,feature) return loss(pred,label) def Focal_loss(pred,label,num_calss,alaph=None, gamma):",
"= nn.L1Loss(pred,label) return loss def L2_loss(pred,label): loss = nn.MSELoss(pred,label) return",
"= Centerloss(num_calss,gamma) return loss(pred,label) def L1_loss(pred,label): loss = nn.L1Loss(pred,label) return",
"L1_loss(pred,label): loss = nn.L1Loss(pred,label) return loss def L2_loss(pred,label): loss =",
"L2_loss(pred,label): loss = nn.MSELoss(pred,label) return loss def SmoothL1_loss(pred,label): loss =",
"def L2_loss(pred,label): loss = nn.MSELoss(pred,label) return loss def SmoothL1_loss(pred,label): loss",
"= Centerloss(num_calss,feature) return loss(pred,label) def Focal_loss(pred,label,num_calss,alaph=None, gamma): loss = Centerloss(num_calss,gamma)",
"Focal_loss(pred,label,num_calss,alaph=None, gamma): loss = Centerloss(num_calss,gamma) return loss(pred,label) def L1_loss(pred,label): loss",
"Centerloss import torch.nn as nn from FocalLoss import FocalLoss def",
"from FocalLoss import FocalLoss def center_loss(pred,label,num_calss,feature): loss = Centerloss(num_calss,feature) return",
"loss = nn.L1Loss(pred,label) return loss def L2_loss(pred,label): loss = nn.MSELoss(pred,label)",
"way to use losses \"\"\" from center_loss import Centerloss import",
"return loss(pred,label) def L1_loss(pred,label): loss = nn.L1Loss(pred,label) return loss def",
"loss = Centerloss(num_calss,gamma) return loss(pred,label) def L1_loss(pred,label): loss = nn.L1Loss(pred,label)",
"loss(pred,label) def L1_loss(pred,label): loss = nn.L1Loss(pred,label) return loss def L2_loss(pred,label):",
"loss def L2_loss(pred,label): loss = nn.MSELoss(pred,label) return loss def SmoothL1_loss(pred,label):"
] |
[
"url, timeout=5) self.assertEqual(200, res.status_code) j = jsonutils.loads(res.text) self.assertIn('hostname', j) self.assertEqual('test.novalocal',",
"self.text = jsonutils.dumps(result) real_request = requests.request def fake_request(obj, url, method,",
"= requests.request('GET', url, timeout=5) self.assertEqual(200, res.status_code) j = jsonutils.loads(res.text) self.assertIn('instance-id',",
"try # and ensure we're passing _some_ data through to",
"jsonschema import os import requests from oslo_serialization import jsonutils from",
"is missing because of # the way we've created the",
"self.flags( vendordata_providers=['DynamicJSON'], vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:125' ], group='api' ) self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request))",
"j['hamster']['a']) self.assertEqual('foo', j['hamster']['b']) def test_lookup_external_service_no_overwrite(self): self.flags( vendordata_providers=['DynamicJSON'], vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:123', 'testing@http://127.0.0.1:124'",
"self.api_fixture = self.useFixture(nova_fixtures.OSMetadataServer()) self.md_url = self.api_fixture.md_url # make sure that",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"the License. import fixtures import jsonschema import os import requests",
"integrated_helpers.InstanceHelperMixin): def setUp(self): super(MetadataTest, self).setUp() fake_image.stub_out_image_service(self) self.addCleanup(fake_image.FakeImageService_reset) self.useFixture(nova_fixtures.NeutronFixture(self)) self.useFixture(func_fixtures.PlacementFixture()) self.start_service('conductor')",
"specific language governing permissions and limitations # under the License.",
"self.start_service('conductor') self.start_service('scheduler') self.api = self.useFixture( nova_fixtures.OSAPIFixture(api_version='v2.1')).api self.start_service('compute') # create a",
"# not use this file except in compliance with the",
"about the # server we created above def fake_get_fixed_ip_by_address(self, ctxt,",
"the external REST # service. self.flags( vendordata_providers=['DynamicJSON'], vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:125' ],",
"the tests server = self._build_server(name='test') server = self.api.post_server({'server': server}) self.server",
"vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:123', 'testing@http://127.0.0.1:124' ], group='api' ) self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request)) url",
"in compliance with the License. You may obtain # a",
"self.assertEqual(1, j['hamster']['a']) self.assertEqual('foo', j['hamster']['b']) def test_lookup_external_service_no_overwrite(self): self.flags( vendordata_providers=['DynamicJSON'], vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:123',",
"j['hamster']['b']) def test_lookup_external_service_no_overwrite(self): self.flags( vendordata_providers=['DynamicJSON'], vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:123', 'testing@http://127.0.0.1:124' ], group='api'",
"def test_lookup_external_service(self): self.flags( vendordata_providers=['StaticJSON', 'DynamicJSON'], vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:123', 'hamster@http://127.0.0.1:123' ], group='api'",
"You may obtain # a copy of the License at",
"Australia # All Rights Reserved. # # Licensed under the",
"j['testing']['b']) self.assertNotIn('c', j['testing']) def test_lookup_external_service_passes_data(self): # Much of the data",
"'b': 'foo'}) if url.startswith('http://127.0.0.1:124'): return fake_result({'c': 3}) if url.startswith('http://127.0.0.1:125'): return",
"\"../../../doc/api_schemas/network_data.json\")) with open(schema_file, 'rb') as f: schema = jsonutils.load(f) jsonschema.validate(res.json(),",
"self.assertNotIn('static', j) self.assertEqual(1, j['testing']['a']) self.assertEqual('foo', j['testing']['b']) self.assertNotIn('c', j['testing']) def test_lookup_external_service_passes_data(self):",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"res.status_code) # load the jsonschema for network_data schema_file = os.path.normpath(os.path.join(",
"fake as fake_image class fake_result(object): def __init__(self, result): self.status_code =",
"# load the jsonschema for network_data schema_file = os.path.normpath(os.path.join( os.path.dirname(os.path.abspath(__file__)),",
"# server we created above def fake_get_fixed_ip_by_address(self, ctxt, address): return",
"nova.tests.functional import integrated_helpers from nova.tests.unit.image import fake as fake_image class",
"Much of the data we pass to the REST service",
"under the License is distributed on an \"AS IS\" BASIS,",
"3}) if url.startswith('http://127.0.0.1:125'): return fake_result(jsonutils.loads(kwargs.get('data', '{}'))) return real_request(method, url, **kwargs)",
"data through to the external REST # service. self.flags( vendordata_providers=['DynamicJSON'],",
"from nova.tests.functional import fixtures as func_fixtures from nova.tests.functional import integrated_helpers",
"200 self.text = jsonutils.dumps(result) real_request = requests.request def fake_request(obj, url,",
"Reserved. # # Licensed under the Apache License, Version 2.0",
"fake_result(jsonutils.loads(kwargs.get('data', '{}'))) return real_request(method, url, **kwargs) class MetadataTest(test.TestCase, integrated_helpers.InstanceHelperMixin): def",
"j = jsonutils.loads(res.text) self.assertEqual({}, j['static']) self.assertEqual(1, j['testing']['a']) self.assertEqual('foo', j['testing']['b']) self.assertEqual(1,",
"this file except in compliance with the License. You may",
"def test_lookup_external_service_passes_data(self): # Much of the data we pass to",
"self.assertEqual(1, j['testing']['a']) self.assertEqual('foo', j['testing']['b']) self.assertNotIn('c', j['testing']) def test_lookup_external_service_passes_data(self): # Much",
"from nova import test from nova.tests import fixtures as nova_fixtures",
"self.assertEqual('foo', j['testing']['b']) self.assertNotIn('c', j['testing']) def test_lookup_external_service_passes_data(self): # Much of the",
"1, 'b': 'foo'}) if url.startswith('http://127.0.0.1:124'): return fake_result({'c': 3}) if url.startswith('http://127.0.0.1:125'):",
"address): return {'instance_uuid': server['id']} self.useFixture( fixtures.MonkeyPatch( 'nova.network.neutron.API.get_fixed_ip_by_address', fake_get_fixed_ip_by_address)) def test_lookup_metadata_root_url(self):",
"'keystoneauth1.session.Session.request', fake_request)) url = '%sopenstack/2016-10-06/vendor_data2.json' % self.md_url res = requests.request('GET',",
"software # distributed under the License is distributed on an",
"(the \"License\"); you may # not use this file except",
"% self.md_url res = requests.request('GET', url, timeout=5, headers={'X-Forwarded-For': '127.0.0.2'}) self.assertEqual(200,",
"self.assertNotIn('c', j['testing']) def test_lookup_external_service_passes_data(self): # Much of the data we",
"self.assertIn('hostname', j['testing']) self.assertEqual(self.server['tenant_id'], j['testing']['project-id']) self.assertIn('metadata', j['testing']) self.assertIn('image-id', j['testing']) self.assertIn('user-data', j['testing'])",
"jsonschema for network_data schema_file = os.path.normpath(os.path.join( os.path.dirname(os.path.abspath(__file__)), \"../../../doc/api_schemas/network_data.json\")) with open(schema_file,",
"self.assertEqual('foo', j['testing']['b']) self.assertEqual(1, j['hamster']['a']) self.assertEqual('foo', j['hamster']['b']) def test_lookup_external_service_no_overwrite(self): self.flags( vendordata_providers=['DynamicJSON'],",
"_some_ data through to the external REST # service. self.flags(",
"file except in compliance with the License. You may obtain",
"tests server = self._build_server(name='test') server = self.api.post_server({'server': server}) self.server =",
"res.status_code) j = jsonutils.loads(res.text) self.assertEqual({}, j['static']) self.assertEqual(1, j['testing']['a']) self.assertEqual('foo', j['testing']['b'])",
"test_lookup_external_service(self): self.flags( vendordata_providers=['StaticJSON', 'DynamicJSON'], vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:123', 'hamster@http://127.0.0.1:123' ], group='api' )",
"OR CONDITIONS OF ANY KIND, either express or implied. See",
"the specific language governing permissions and limitations # under the",
"nova_fixtures.OSAPIFixture(api_version='v2.1')).api self.start_service('compute') # create a server for the tests server",
"of the data we pass to the REST service is",
"self.start_service('scheduler') self.api = self.useFixture( nova_fixtures.OSAPIFixture(api_version='v2.1')).api self.start_service('compute') # create a server",
"timeout=5) self.assertEqual(200, res.status_code) def test_lookup_metadata_openstack_url(self): url = '%sopenstack' % self.md_url",
"under the Apache License, Version 2.0 (the \"License\"); you may",
"test from nova.tests import fixtures as nova_fixtures from nova.tests.functional import",
"'hamster@http://127.0.0.1:123' ], group='api' ) self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request)) url = '%sopenstack/2016-10-06/vendor_data2.json'",
"url.startswith('http://127.0.0.1:124'): return fake_result({'c': 3}) if url.startswith('http://127.0.0.1:125'): return fake_result(jsonutils.loads(kwargs.get('data', '{}'))) return",
"server for the tests server = self._build_server(name='test') server = self.api.post_server({'server':",
"j['testing']['project-id']) self.assertIn('metadata', j['testing']) self.assertIn('image-id', j['testing']) self.assertIn('user-data', j['testing']) def test_network_data_matches_schema(self): self.useFixture(fixtures.MonkeyPatch(",
"but we should at least try # and ensure we're",
"url, **kwargs) class MetadataTest(test.TestCase, integrated_helpers.InstanceHelperMixin): def setUp(self): super(MetadataTest, self).setUp() fake_image.stub_out_image_service(self)",
"under the License. import fixtures import jsonschema import os import",
"nova_fixtures from nova.tests.functional import fixtures as func_fixtures from nova.tests.functional import",
"vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:123', 'hamster@http://127.0.0.1:123' ], group='api' ) self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request)) url",
"j) self.assertEqual('test.novalocal', j['hostname']) def test_lookup_external_service(self): self.flags( vendordata_providers=['StaticJSON', 'DynamicJSON'], vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:123',",
"nova.tests.functional import fixtures as func_fixtures from nova.tests.functional import integrated_helpers from",
"requests.request('GET', url, timeout=5) self.assertEqual(200, res.status_code) # load the jsonschema for",
"j = jsonutils.loads(res.text) self.assertIn('hostname', j) self.assertEqual('test.novalocal', j['hostname']) def test_lookup_external_service(self): self.flags(",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY",
"the metadata service returns information about the # server we",
"through to the external REST # service. self.flags( vendordata_providers=['DynamicJSON'], vendordata_dynamic_targets=[",
"def test_network_data_matches_schema(self): self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request)) url = '%sopenstack/latest/network_data.json' % self.md_url",
"self.useFixture(nova_fixtures.NeutronFixture(self)) self.useFixture(func_fixtures.PlacementFixture()) self.start_service('conductor') self.start_service('scheduler') self.api = self.useFixture( nova_fixtures.OSAPIFixture(api_version='v2.1')).api self.start_service('compute') #",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"we're passing _some_ data through to the external REST #",
"requests.request('GET', url, timeout=5) self.assertEqual(200, res.status_code) j = jsonutils.loads(res.text) self.assertIn('instance-id', j['testing'])",
"to in writing, software # distributed under the License is",
"# under the License. import fixtures import jsonschema import os",
"self.addCleanup(fake_image.FakeImageService_reset) self.useFixture(nova_fixtures.NeutronFixture(self)) self.useFixture(func_fixtures.PlacementFixture()) self.start_service('conductor') self.start_service('scheduler') self.api = self.useFixture( nova_fixtures.OSAPIFixture(api_version='v2.1')).api self.start_service('compute')",
"instance, but we should at least try # and ensure",
"self.assertIn('instance-id', j['testing']) self.assertTrue(uuidutils.is_uuid_like(j['testing']['instance-id'])) self.assertIn('hostname', j['testing']) self.assertEqual(self.server['tenant_id'], j['testing']['project-id']) self.assertIn('metadata', j['testing']) self.assertIn('image-id',",
"vendordata_providers=['DynamicJSON'], vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:125' ], group='api' ) self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request)) url",
"= requests.request('GET', url, timeout=5) self.assertEqual(200, res.status_code) j = jsonutils.loads(res.text) self.assertNotIn('static',",
"created above def fake_get_fixed_ip_by_address(self, ctxt, address): return {'instance_uuid': server['id']} self.useFixture(",
"vendordata_providers=['DynamicJSON'], vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:123', 'testing@http://127.0.0.1:124' ], group='api' ) self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request))",
"or agreed to in writing, software # distributed under the",
"required by applicable law or agreed to in writing, software",
"nova.tests import fixtures as nova_fixtures from nova.tests.functional import fixtures as",
"res.status_code) j = jsonutils.loads(res.text) self.assertIn('instance-id', j['testing']) self.assertTrue(uuidutils.is_uuid_like(j['testing']['instance-id'])) self.assertIn('hostname', j['testing']) self.assertEqual(self.server['tenant_id'],",
"for network_data schema_file = os.path.normpath(os.path.join( os.path.dirname(os.path.abspath(__file__)), \"../../../doc/api_schemas/network_data.json\")) with open(schema_file, 'rb')",
"= requests.request('GET', url, timeout=5) self.assertEqual(200, res.status_code) # load the jsonschema",
"requests from oslo_serialization import jsonutils from oslo_utils import uuidutils from",
"# Copyright 2016 Rackspace Australia # All Rights Reserved. #",
"def fake_request(obj, url, method, **kwargs): if url.startswith('http://127.0.0.1:123'): return fake_result({'a': 1,",
"Rackspace Australia # All Rights Reserved. # # Licensed under",
"Apache License, Version 2.0 (the \"License\"); you may # not",
"jsonutils.loads(res.text) self.assertNotIn('static', j) self.assertEqual(1, j['testing']['a']) self.assertEqual('foo', j['testing']['b']) self.assertNotIn('c', j['testing']) def",
"test_lookup_external_service_no_overwrite(self): self.flags( vendordata_providers=['DynamicJSON'], vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:123', 'testing@http://127.0.0.1:124' ], group='api' ) self.useFixture(fixtures.MonkeyPatch(",
"return fake_result({'a': 1, 'b': 'foo'}) if url.startswith('http://127.0.0.1:124'): return fake_result({'c': 3})",
"self.assertEqual(200, res.status_code) j = jsonutils.loads(res.text) self.assertIn('hostname', j) self.assertEqual('test.novalocal', j['hostname']) def",
"if url.startswith('http://127.0.0.1:124'): return fake_result({'c': 3}) if url.startswith('http://127.0.0.1:125'): return fake_result(jsonutils.loads(kwargs.get('data', '{}')))",
"All Rights Reserved. # # Licensed under the Apache License,",
"agreed to in writing, software # distributed under the License",
"the way we've created the fake instance, but we should",
"fake_request(obj, url, method, **kwargs): if url.startswith('http://127.0.0.1:123'): return fake_result({'a': 1, 'b':",
"'%sopenstack/latest/meta_data.json' % self.md_url res = requests.request('GET', url, timeout=5) self.assertEqual(200, res.status_code)",
"MetadataTest(test.TestCase, integrated_helpers.InstanceHelperMixin): def setUp(self): super(MetadataTest, self).setUp() fake_image.stub_out_image_service(self) self.addCleanup(fake_image.FakeImageService_reset) self.useFixture(nova_fixtures.NeutronFixture(self)) self.useFixture(func_fixtures.PlacementFixture())",
"# Much of the data we pass to the REST",
"distributed under the License is distributed on an \"AS IS\"",
"j['testing']) def test_lookup_external_service_passes_data(self): # Much of the data we pass",
"License, Version 2.0 (the \"License\"); you may # not use",
"CONDITIONS OF ANY KIND, either express or implied. See the",
"a server for the tests server = self._build_server(name='test') server =",
"func_fixtures from nova.tests.functional import integrated_helpers from nova.tests.unit.image import fake as",
"= jsonutils.loads(res.text) self.assertIn('instance-id', j['testing']) self.assertTrue(uuidutils.is_uuid_like(j['testing']['instance-id'])) self.assertIn('hostname', j['testing']) self.assertEqual(self.server['tenant_id'], j['testing']['project-id']) self.assertIn('metadata',",
"passing _some_ data through to the external REST # service.",
"not use this file except in compliance with the License.",
"% self.md_url res = requests.request('GET', url, timeout=5) self.assertEqual(200, res.status_code) #",
"self.md_url = self.api_fixture.md_url # make sure that the metadata service",
"writing, software # distributed under the License is distributed on",
"def test_lookup_metadata_root_url(self): res = requests.request('GET', self.md_url, timeout=5) self.assertEqual(200, res.status_code) def",
"url.startswith('http://127.0.0.1:123'): return fake_result({'a': 1, 'b': 'foo'}) if url.startswith('http://127.0.0.1:124'): return fake_result({'c':",
"fixtures.MonkeyPatch( 'nova.network.neutron.API.get_fixed_ip_by_address', fake_get_fixed_ip_by_address)) def test_lookup_metadata_root_url(self): res = requests.request('GET', self.md_url, timeout=5)",
"self.assertEqual('test.novalocal', j['hostname']) def test_lookup_external_service(self): self.flags( vendordata_providers=['StaticJSON', 'DynamicJSON'], vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:123', 'hamster@http://127.0.0.1:123'",
"return {'instance_uuid': server['id']} self.useFixture( fixtures.MonkeyPatch( 'nova.network.neutron.API.get_fixed_ip_by_address', fake_get_fixed_ip_by_address)) def test_lookup_metadata_root_url(self): res",
"res.status_code) def test_lookup_metadata_openstack_url(self): url = '%sopenstack' % self.md_url res =",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"service returns information about the # server we created above",
"the License. You may obtain # a copy of the",
"server = self.api.post_server({'server': server}) self.server = self._wait_for_state_change(server, 'ACTIVE') self.api_fixture =",
"an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF",
"use this file except in compliance with the License. You",
"jsonutils.loads(res.text) self.assertEqual({}, j['static']) self.assertEqual(1, j['testing']['a']) self.assertEqual('foo', j['testing']['b']) self.assertEqual(1, j['hamster']['a']) self.assertEqual('foo',",
"res = requests.request('GET', url, timeout=5, headers={'X-Forwarded-For': '127.0.0.2'}) self.assertEqual(200, res.status_code) def",
"that the metadata service returns information about the # server",
"self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request)) url = '%sopenstack/2016-10-06/vendor_data2.json' % self.md_url res =",
"missing because of # the way we've created the fake",
"test_lookup_metadata_root_url(self): res = requests.request('GET', self.md_url, timeout=5) self.assertEqual(200, res.status_code) def test_lookup_metadata_openstack_url(self):",
"uuidutils from nova import test from nova.tests import fixtures as",
"def fake_get_fixed_ip_by_address(self, ctxt, address): return {'instance_uuid': server['id']} self.useFixture( fixtures.MonkeyPatch( 'nova.network.neutron.API.get_fixed_ip_by_address',",
"fake_result({'c': 3}) if url.startswith('http://127.0.0.1:125'): return fake_result(jsonutils.loads(kwargs.get('data', '{}'))) return real_request(method, url,",
"server = self._build_server(name='test') server = self.api.post_server({'server': server}) self.server = self._wait_for_state_change(server,",
"self.assertEqual('foo', j['hamster']['b']) def test_lookup_external_service_no_overwrite(self): self.flags( vendordata_providers=['DynamicJSON'], vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:123', 'testing@http://127.0.0.1:124' ],",
"fixtures as func_fixtures from nova.tests.functional import integrated_helpers from nova.tests.unit.image import",
"real_request(method, url, **kwargs) class MetadataTest(test.TestCase, integrated_helpers.InstanceHelperMixin): def setUp(self): super(MetadataTest, self).setUp()",
"j['static']) self.assertEqual(1, j['testing']['a']) self.assertEqual('foo', j['testing']['b']) self.assertEqual(1, j['hamster']['a']) self.assertEqual('foo', j['hamster']['b']) def",
"import fixtures as nova_fixtures from nova.tests.functional import fixtures as func_fixtures",
"test_network_data_matches_schema(self): self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request)) url = '%sopenstack/latest/network_data.json' % self.md_url res",
"License is distributed on an \"AS IS\" BASIS, WITHOUT #",
"KIND, either express or implied. See the # License for",
"the jsonschema for network_data schema_file = os.path.normpath(os.path.join( os.path.dirname(os.path.abspath(__file__)), \"../../../doc/api_schemas/network_data.json\")) with",
"\"License\"); you may # not use this file except in",
"IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,",
"'%sopenstack' % self.md_url res = requests.request('GET', url, timeout=5, headers={'X-Forwarded-For': '127.0.0.2'})",
"fake_request)) url = '%sopenstack/latest/network_data.json' % self.md_url res = requests.request('GET', url,",
"express or implied. See the # License for the specific",
"j['testing']['b']) self.assertEqual(1, j['hamster']['a']) self.assertEqual('foo', j['hamster']['b']) def test_lookup_external_service_no_overwrite(self): self.flags( vendordata_providers=['DynamicJSON'], vendordata_dynamic_targets=[",
"= '%sopenstack' % self.md_url res = requests.request('GET', url, timeout=5, headers={'X-Forwarded-For':",
"information about the # server we created above def fake_get_fixed_ip_by_address(self,",
"= '%sopenstack/2016-10-06/vendor_data2.json' % self.md_url res = requests.request('GET', url, timeout=5) self.assertEqual(200,",
"the Apache License, Version 2.0 (the \"License\"); you may #",
"self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request)) url = '%sopenstack/latest/network_data.json' % self.md_url res =",
"= jsonutils.loads(res.text) self.assertEqual({}, j['static']) self.assertEqual(1, j['testing']['a']) self.assertEqual('foo', j['testing']['b']) self.assertEqual(1, j['hamster']['a'])",
"def test_lookup_external_service_no_overwrite(self): self.flags( vendordata_providers=['DynamicJSON'], vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:123', 'testing@http://127.0.0.1:124' ], group='api' )",
"load the jsonschema for network_data schema_file = os.path.normpath(os.path.join( os.path.dirname(os.path.abspath(__file__)), \"../../../doc/api_schemas/network_data.json\"))",
"timeout=5) self.assertEqual(200, res.status_code) # load the jsonschema for network_data schema_file",
"network_data schema_file = os.path.normpath(os.path.join( os.path.dirname(os.path.abspath(__file__)), \"../../../doc/api_schemas/network_data.json\")) with open(schema_file, 'rb') as",
"See the # License for the specific language governing permissions",
"at least try # and ensure we're passing _some_ data",
"of # the way we've created the fake instance, but",
"self.api = self.useFixture( nova_fixtures.OSAPIFixture(api_version='v2.1')).api self.start_service('compute') # create a server for",
"# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"created the fake instance, but we should at least try",
"self.assertEqual(200, res.status_code) j = jsonutils.loads(res.text) self.assertNotIn('static', j) self.assertEqual(1, j['testing']['a']) self.assertEqual('foo',",
"'%sopenstack/latest/network_data.json' % self.md_url res = requests.request('GET', url, timeout=5) self.assertEqual(200, res.status_code)",
"the data we pass to the REST service is missing",
"law or agreed to in writing, software # distributed under",
"os.path.dirname(os.path.abspath(__file__)), \"../../../doc/api_schemas/network_data.json\")) with open(schema_file, 'rb') as f: schema = jsonutils.load(f)",
"test_lookup_metadata_data_url(self): url = '%sopenstack/latest/meta_data.json' % self.md_url res = requests.request('GET', url,",
"we pass to the REST service is missing because of",
"REST service is missing because of # the way we've",
"implied. See the # License for the specific language governing",
"requests.request('GET', url, timeout=5, headers={'X-Forwarded-For': '127.0.0.2'}) self.assertEqual(200, res.status_code) def test_lookup_metadata_data_url(self): url",
"self.status_code = 200 self.text = jsonutils.dumps(result) real_request = requests.request def",
"jsonutils.loads(res.text) self.assertIn('hostname', j) self.assertEqual('test.novalocal', j['hostname']) def test_lookup_external_service(self): self.flags( vendordata_providers=['StaticJSON', 'DynamicJSON'],",
"self.assertEqual(self.server['tenant_id'], j['testing']['project-id']) self.assertIn('metadata', j['testing']) self.assertIn('image-id', j['testing']) self.assertIn('user-data', j['testing']) def test_network_data_matches_schema(self):",
"service is missing because of # the way we've created",
"res = requests.request('GET', url, timeout=5) self.assertEqual(200, res.status_code) j = jsonutils.loads(res.text)",
"self.api_fixture.md_url # make sure that the metadata service returns information",
"# the way we've created the fake instance, but we",
"url, timeout=5) self.assertEqual(200, res.status_code) j = jsonutils.loads(res.text) self.assertIn('instance-id', j['testing']) self.assertTrue(uuidutils.is_uuid_like(j['testing']['instance-id']))",
"super(MetadataTest, self).setUp() fake_image.stub_out_image_service(self) self.addCleanup(fake_image.FakeImageService_reset) self.useFixture(nova_fixtures.NeutronFixture(self)) self.useFixture(func_fixtures.PlacementFixture()) self.start_service('conductor') self.start_service('scheduler') self.api =",
"above def fake_get_fixed_ip_by_address(self, ctxt, address): return {'instance_uuid': server['id']} self.useFixture( fixtures.MonkeyPatch(",
"j['hostname']) def test_lookup_external_service(self): self.flags( vendordata_providers=['StaticJSON', 'DynamicJSON'], vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:123', 'hamster@http://127.0.0.1:123' ],",
"Copyright 2016 Rackspace Australia # All Rights Reserved. # #",
"import fixtures import jsonschema import os import requests from oslo_serialization",
"jsonutils.dumps(result) real_request = requests.request def fake_request(obj, url, method, **kwargs): if",
"should at least try # and ensure we're passing _some_",
"= jsonutils.loads(res.text) self.assertIn('hostname', j) self.assertEqual('test.novalocal', j['hostname']) def test_lookup_external_service(self): self.flags( vendordata_providers=['StaticJSON',",
"= requests.request('GET', self.md_url, timeout=5) self.assertEqual(200, res.status_code) def test_lookup_metadata_openstack_url(self): url =",
"], group='api' ) self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request)) url = '%sopenstack/2016-10-06/vendor_data2.json' %",
"least try # and ensure we're passing _some_ data through",
"to the REST service is missing because of # the",
"= self.api.post_server({'server': server}) self.server = self._wait_for_state_change(server, 'ACTIVE') self.api_fixture = self.useFixture(nova_fixtures.OSMetadataServer())",
"import fixtures as func_fixtures from nova.tests.functional import integrated_helpers from nova.tests.unit.image",
"= os.path.normpath(os.path.join( os.path.dirname(os.path.abspath(__file__)), \"../../../doc/api_schemas/network_data.json\")) with open(schema_file, 'rb') as f: schema",
"url, timeout=5) self.assertEqual(200, res.status_code) # load the jsonschema for network_data",
"url, timeout=5, headers={'X-Forwarded-For': '127.0.0.2'}) self.assertEqual(200, res.status_code) def test_lookup_metadata_data_url(self): url =",
"j = jsonutils.loads(res.text) self.assertNotIn('static', j) self.assertEqual(1, j['testing']['a']) self.assertEqual('foo', j['testing']['b']) self.assertNotIn('c',",
"we created above def fake_get_fixed_ip_by_address(self, ctxt, address): return {'instance_uuid': server['id']}",
"fake_get_fixed_ip_by_address)) def test_lookup_metadata_root_url(self): res = requests.request('GET', self.md_url, timeout=5) self.assertEqual(200, res.status_code)",
"as nova_fixtures from nova.tests.functional import fixtures as func_fixtures from nova.tests.functional",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR",
"setUp(self): super(MetadataTest, self).setUp() fake_image.stub_out_image_service(self) self.addCleanup(fake_image.FakeImageService_reset) self.useFixture(nova_fixtures.NeutronFixture(self)) self.useFixture(func_fixtures.PlacementFixture()) self.start_service('conductor') self.start_service('scheduler') self.api",
"# # Licensed under the Apache License, Version 2.0 (the",
"fake_result(object): def __init__(self, result): self.status_code = 200 self.text = jsonutils.dumps(result)",
"j['testing']) self.assertIn('image-id', j['testing']) self.assertIn('user-data', j['testing']) def test_network_data_matches_schema(self): self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request))",
"'testing@http://127.0.0.1:125' ], group='api' ) self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request)) url = '%sopenstack/2016-10-06/vendor_data2.json'",
"fake_image class fake_result(object): def __init__(self, result): self.status_code = 200 self.text",
"the REST service is missing because of # the way",
"data we pass to the REST service is missing because",
"vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:125' ], group='api' ) self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request)) url =",
"because of # the way we've created the fake instance,",
"import jsonutils from oslo_utils import uuidutils from nova import test",
"res.status_code) def test_lookup_metadata_data_url(self): url = '%sopenstack/latest/meta_data.json' % self.md_url res =",
"obtain # a copy of the License at # #",
"self.assertIn('metadata', j['testing']) self.assertIn('image-id', j['testing']) self.assertIn('user-data', j['testing']) def test_network_data_matches_schema(self): self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request',",
"Version 2.0 (the \"License\"); you may # not use this",
"= requests.request('GET', url, timeout=5) self.assertEqual(200, res.status_code) j = jsonutils.loads(res.text) self.assertEqual({},",
"timeout=5) self.assertEqual(200, res.status_code) j = jsonutils.loads(res.text) self.assertIn('instance-id', j['testing']) self.assertTrue(uuidutils.is_uuid_like(j['testing']['instance-id'])) self.assertIn('hostname',",
"j['testing']) self.assertIn('user-data', j['testing']) def test_network_data_matches_schema(self): self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request)) url =",
"schema_file = os.path.normpath(os.path.join( os.path.dirname(os.path.abspath(__file__)), \"../../../doc/api_schemas/network_data.json\")) with open(schema_file, 'rb') as f:",
"self.useFixture( nova_fixtures.OSAPIFixture(api_version='v2.1')).api self.start_service('compute') # create a server for the tests",
"**kwargs): if url.startswith('http://127.0.0.1:123'): return fake_result({'a': 1, 'b': 'foo'}) if url.startswith('http://127.0.0.1:124'):",
"License for the specific language governing permissions and limitations #",
"fake_image.stub_out_image_service(self) self.addCleanup(fake_image.FakeImageService_reset) self.useFixture(nova_fixtures.NeutronFixture(self)) self.useFixture(func_fixtures.PlacementFixture()) self.start_service('conductor') self.start_service('scheduler') self.api = self.useFixture( nova_fixtures.OSAPIFixture(api_version='v2.1')).api",
"url, timeout=5) self.assertEqual(200, res.status_code) j = jsonutils.loads(res.text) self.assertEqual({}, j['static']) self.assertEqual(1,",
"on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS",
"j = jsonutils.loads(res.text) self.assertIn('instance-id', j['testing']) self.assertTrue(uuidutils.is_uuid_like(j['testing']['instance-id'])) self.assertIn('hostname', j['testing']) self.assertEqual(self.server['tenant_id'], j['testing']['project-id'])",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"self.useFixture(func_fixtures.PlacementFixture()) self.start_service('conductor') self.start_service('scheduler') self.api = self.useFixture( nova_fixtures.OSAPIFixture(api_version='v2.1')).api self.start_service('compute') # create",
"self.useFixture( fixtures.MonkeyPatch( 'nova.network.neutron.API.get_fixed_ip_by_address', fake_get_fixed_ip_by_address)) def test_lookup_metadata_root_url(self): res = requests.request('GET', self.md_url,",
"class MetadataTest(test.TestCase, integrated_helpers.InstanceHelperMixin): def setUp(self): super(MetadataTest, self).setUp() fake_image.stub_out_image_service(self) self.addCleanup(fake_image.FakeImageService_reset) self.useFixture(nova_fixtures.NeutronFixture(self))",
"oslo_utils import uuidutils from nova import test from nova.tests import",
"headers={'X-Forwarded-For': '127.0.0.2'}) self.assertEqual(200, res.status_code) def test_lookup_metadata_data_url(self): url = '%sopenstack/latest/meta_data.json' %",
"self.md_url res = requests.request('GET', url, timeout=5) self.assertEqual(200, res.status_code) # load",
"jsonutils from oslo_utils import uuidutils from nova import test from",
"self.assertEqual(200, res.status_code) def test_lookup_metadata_data_url(self): url = '%sopenstack/latest/meta_data.json' % self.md_url res",
"Rights Reserved. # # Licensed under the Apache License, Version",
"and limitations # under the License. import fixtures import jsonschema",
"nova.tests.unit.image import fake as fake_image class fake_result(object): def __init__(self, result):",
"Licensed under the Apache License, Version 2.0 (the \"License\"); you",
"self.api.post_server({'server': server}) self.server = self._wait_for_state_change(server, 'ACTIVE') self.api_fixture = self.useFixture(nova_fixtures.OSMetadataServer()) self.md_url",
"self.assertEqual(200, res.status_code) j = jsonutils.loads(res.text) self.assertIn('instance-id', j['testing']) self.assertTrue(uuidutils.is_uuid_like(j['testing']['instance-id'])) self.assertIn('hostname', j['testing'])",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"j['testing']) def test_network_data_matches_schema(self): self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request)) url = '%sopenstack/latest/network_data.json' %",
"governing permissions and limitations # under the License. import fixtures",
"limitations # under the License. import fixtures import jsonschema import",
"= self.api_fixture.md_url # make sure that the metadata service returns",
"res = requests.request('GET', url, timeout=5) self.assertEqual(200, res.status_code) # load the",
"compliance with the License. You may obtain # a copy",
"and ensure we're passing _some_ data through to the external",
"timeout=5, headers={'X-Forwarded-For': '127.0.0.2'}) self.assertEqual(200, res.status_code) def test_lookup_metadata_data_url(self): url = '%sopenstack/latest/meta_data.json'",
"if url.startswith('http://127.0.0.1:125'): return fake_result(jsonutils.loads(kwargs.get('data', '{}'))) return real_request(method, url, **kwargs) class",
"self.assertTrue(uuidutils.is_uuid_like(j['testing']['instance-id'])) self.assertIn('hostname', j['testing']) self.assertEqual(self.server['tenant_id'], j['testing']['project-id']) self.assertIn('metadata', j['testing']) self.assertIn('image-id', j['testing']) self.assertIn('user-data',",
"= requests.request def fake_request(obj, url, method, **kwargs): if url.startswith('http://127.0.0.1:123'): return",
"'{}'))) return real_request(method, url, **kwargs) class MetadataTest(test.TestCase, integrated_helpers.InstanceHelperMixin): def setUp(self):",
"# service. self.flags( vendordata_providers=['DynamicJSON'], vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:125' ], group='api' ) self.useFixture(fixtures.MonkeyPatch(",
"'testing@http://127.0.0.1:124' ], group='api' ) self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request)) url = '%sopenstack/2016-10-06/vendor_data2.json'",
"import integrated_helpers from nova.tests.unit.image import fake as fake_image class fake_result(object):",
"test_lookup_metadata_openstack_url(self): url = '%sopenstack' % self.md_url res = requests.request('GET', url,",
"the # License for the specific language governing permissions and",
"import requests from oslo_serialization import jsonutils from oslo_utils import uuidutils",
"j['testing']['a']) self.assertEqual('foo', j['testing']['b']) self.assertEqual(1, j['hamster']['a']) self.assertEqual('foo', j['hamster']['b']) def test_lookup_external_service_no_overwrite(self): self.flags(",
"# # Unless required by applicable law or agreed to",
"group='api' ) self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request)) url = '%sopenstack/2016-10-06/vendor_data2.json' % self.md_url",
"fake_get_fixed_ip_by_address(self, ctxt, address): return {'instance_uuid': server['id']} self.useFixture( fixtures.MonkeyPatch( 'nova.network.neutron.API.get_fixed_ip_by_address', fake_get_fixed_ip_by_address))",
"url, timeout=5) self.assertEqual(200, res.status_code) j = jsonutils.loads(res.text) self.assertNotIn('static', j) self.assertEqual(1,",
"timeout=5) self.assertEqual(200, res.status_code) j = jsonutils.loads(res.text) self.assertNotIn('static', j) self.assertEqual(1, j['testing']['a'])",
"requests.request def fake_request(obj, url, method, **kwargs): if url.startswith('http://127.0.0.1:123'): return fake_result({'a':",
"make sure that the metadata service returns information about the",
"return real_request(method, url, **kwargs) class MetadataTest(test.TestCase, integrated_helpers.InstanceHelperMixin): def setUp(self): super(MetadataTest,",
"return fake_result(jsonutils.loads(kwargs.get('data', '{}'))) return real_request(method, url, **kwargs) class MetadataTest(test.TestCase, integrated_helpers.InstanceHelperMixin):",
"def test_lookup_metadata_data_url(self): url = '%sopenstack/latest/meta_data.json' % self.md_url res = requests.request('GET',",
"res.status_code) j = jsonutils.loads(res.text) self.assertNotIn('static', j) self.assertEqual(1, j['testing']['a']) self.assertEqual('foo', j['testing']['b'])",
"REST # service. self.flags( vendordata_providers=['DynamicJSON'], vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:125' ], group='api' )",
"self.assertIn('hostname', j) self.assertEqual('test.novalocal', j['hostname']) def test_lookup_external_service(self): self.flags( vendordata_providers=['StaticJSON', 'DynamicJSON'], vendordata_dynamic_targets=[",
"= self.useFixture( nova_fixtures.OSAPIFixture(api_version='v2.1')).api self.start_service('compute') # create a server for the",
"way we've created the fake instance, but we should at",
"2.0 (the \"License\"); you may # not use this file",
"requests.request('GET', self.md_url, timeout=5) self.assertEqual(200, res.status_code) def test_lookup_metadata_openstack_url(self): url = '%sopenstack'",
"res = requests.request('GET', self.md_url, timeout=5) self.assertEqual(200, res.status_code) def test_lookup_metadata_openstack_url(self): url",
"'DynamicJSON'], vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:123', 'hamster@http://127.0.0.1:123' ], group='api' ) self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request))",
"= jsonutils.loads(res.text) self.assertNotIn('static', j) self.assertEqual(1, j['testing']['a']) self.assertEqual('foo', j['testing']['b']) self.assertNotIn('c', j['testing'])",
"fake_request)) url = '%sopenstack/2016-10-06/vendor_data2.json' % self.md_url res = requests.request('GET', url,",
"method, **kwargs): if url.startswith('http://127.0.0.1:123'): return fake_result({'a': 1, 'b': 'foo'}) if",
"url, method, **kwargs): if url.startswith('http://127.0.0.1:123'): return fake_result({'a': 1, 'b': 'foo'})",
"import jsonschema import os import requests from oslo_serialization import jsonutils",
"url = '%sopenstack' % self.md_url res = requests.request('GET', url, timeout=5,",
"with open(schema_file, 'rb') as f: schema = jsonutils.load(f) jsonschema.validate(res.json(), schema)",
"result): self.status_code = 200 self.text = jsonutils.dumps(result) real_request = requests.request",
"by applicable law or agreed to in writing, software #",
"self.assertEqual(200, res.status_code) def test_lookup_metadata_openstack_url(self): url = '%sopenstack' % self.md_url res",
"test_lookup_external_service_passes_data(self): # Much of the data we pass to the",
"self.assertIn('user-data', j['testing']) def test_network_data_matches_schema(self): self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request)) url = '%sopenstack/latest/network_data.json'",
"j['testing']) self.assertEqual(self.server['tenant_id'], j['testing']['project-id']) self.assertIn('metadata', j['testing']) self.assertIn('image-id', j['testing']) self.assertIn('user-data', j['testing']) def",
"# and ensure we're passing _some_ data through to the",
"import test from nova.tests import fixtures as nova_fixtures from nova.tests.functional",
"self.flags( vendordata_providers=['DynamicJSON'], vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:123', 'testing@http://127.0.0.1:124' ], group='api' ) self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request',",
"ctxt, address): return {'instance_uuid': server['id']} self.useFixture( fixtures.MonkeyPatch( 'nova.network.neutron.API.get_fixed_ip_by_address', fake_get_fixed_ip_by_address)) def",
"= '%sopenstack/latest/meta_data.json' % self.md_url res = requests.request('GET', url, timeout=5) self.assertEqual(200,",
"create a server for the tests server = self._build_server(name='test') server",
"BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either",
"class fake_result(object): def __init__(self, result): self.status_code = 200 self.text =",
"License. import fixtures import jsonschema import os import requests from",
"self.assertEqual(1, j['testing']['a']) self.assertEqual('foo', j['testing']['b']) self.assertEqual(1, j['hamster']['a']) self.assertEqual('foo', j['hamster']['b']) def test_lookup_external_service_no_overwrite(self):",
"= self._wait_for_state_change(server, 'ACTIVE') self.api_fixture = self.useFixture(nova_fixtures.OSMetadataServer()) self.md_url = self.api_fixture.md_url #",
"= '%sopenstack/latest/network_data.json' % self.md_url res = requests.request('GET', url, timeout=5) self.assertEqual(200,",
"def test_lookup_metadata_openstack_url(self): url = '%sopenstack' % self.md_url res = requests.request('GET',",
"self.useFixture(nova_fixtures.OSMetadataServer()) self.md_url = self.api_fixture.md_url # make sure that the metadata",
"= requests.request('GET', url, timeout=5, headers={'X-Forwarded-For': '127.0.0.2'}) self.assertEqual(200, res.status_code) def test_lookup_metadata_data_url(self):",
"= self._build_server(name='test') server = self.api.post_server({'server': server}) self.server = self._wait_for_state_change(server, 'ACTIVE')",
"'foo'}) if url.startswith('http://127.0.0.1:124'): return fake_result({'c': 3}) if url.startswith('http://127.0.0.1:125'): return fake_result(jsonutils.loads(kwargs.get('data',",
"res.status_code) j = jsonutils.loads(res.text) self.assertIn('hostname', j) self.assertEqual('test.novalocal', j['hostname']) def test_lookup_external_service(self):",
"import os import requests from oslo_serialization import jsonutils from oslo_utils",
"self.md_url res = requests.request('GET', url, timeout=5, headers={'X-Forwarded-For': '127.0.0.2'}) self.assertEqual(200, res.status_code)",
"'testing@http://127.0.0.1:123', 'testing@http://127.0.0.1:124' ], group='api' ) self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request)) url =",
"from oslo_serialization import jsonutils from oslo_utils import uuidutils from nova",
"permissions and limitations # under the License. import fixtures import",
"may obtain # a copy of the License at #",
"# All Rights Reserved. # # Licensed under the Apache",
"Unless required by applicable law or agreed to in writing,",
"'%sopenstack/2016-10-06/vendor_data2.json' % self.md_url res = requests.request('GET', url, timeout=5) self.assertEqual(200, res.status_code)",
"timeout=5) self.assertEqual(200, res.status_code) j = jsonutils.loads(res.text) self.assertIn('hostname', j) self.assertEqual('test.novalocal', j['hostname'])",
"# make sure that the metadata service returns information about",
"j['testing']['a']) self.assertEqual('foo', j['testing']['b']) self.assertNotIn('c', j['testing']) def test_lookup_external_service_passes_data(self): # Much of",
"ensure we're passing _some_ data through to the external REST",
"% self.md_url res = requests.request('GET', url, timeout=5) self.assertEqual(200, res.status_code) j",
"self.start_service('compute') # create a server for the tests server =",
"self.assertEqual(200, res.status_code) j = jsonutils.loads(res.text) self.assertEqual({}, j['static']) self.assertEqual(1, j['testing']['a']) self.assertEqual('foo',",
"applicable law or agreed to in writing, software # distributed",
"sure that the metadata service returns information about the #",
"requests.request('GET', url, timeout=5) self.assertEqual(200, res.status_code) j = jsonutils.loads(res.text) self.assertEqual({}, j['static'])",
"self.assertIn('image-id', j['testing']) self.assertIn('user-data', j['testing']) def test_network_data_matches_schema(self): self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request)) url",
"OF ANY KIND, either express or implied. See the #",
"fake instance, but we should at least try # and",
"from nova.tests import fixtures as nova_fixtures from nova.tests.functional import fixtures",
"= self.useFixture(nova_fixtures.OSMetadataServer()) self.md_url = self.api_fixture.md_url # make sure that the",
"we've created the fake instance, but we should at least",
"WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"in writing, software # distributed under the License is distributed",
"= 200 self.text = jsonutils.dumps(result) real_request = requests.request def fake_request(obj,",
"external REST # service. self.flags( vendordata_providers=['DynamicJSON'], vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:125' ], group='api'",
"metadata service returns information about the # server we created",
"self._build_server(name='test') server = self.api.post_server({'server': server}) self.server = self._wait_for_state_change(server, 'ACTIVE') self.api_fixture",
"'keystoneauth1.session.Session.request', fake_request)) url = '%sopenstack/latest/network_data.json' % self.md_url res = requests.request('GET',",
"self.assertEqual(200, res.status_code) # load the jsonschema for network_data schema_file =",
"the fake instance, but we should at least try #",
"as fake_image class fake_result(object): def __init__(self, result): self.status_code = 200",
"self).setUp() fake_image.stub_out_image_service(self) self.addCleanup(fake_image.FakeImageService_reset) self.useFixture(nova_fixtures.NeutronFixture(self)) self.useFixture(func_fixtures.PlacementFixture()) self.start_service('conductor') self.start_service('scheduler') self.api = self.useFixture(",
"server['id']} self.useFixture( fixtures.MonkeyPatch( 'nova.network.neutron.API.get_fixed_ip_by_address', fake_get_fixed_ip_by_address)) def test_lookup_metadata_root_url(self): res = requests.request('GET',",
"self._wait_for_state_change(server, 'ACTIVE') self.api_fixture = self.useFixture(nova_fixtures.OSMetadataServer()) self.md_url = self.api_fixture.md_url # make",
"from nova.tests.functional import integrated_helpers from nova.tests.unit.image import fake as fake_image",
"either express or implied. See the # License for the",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"may # not use this file except in compliance with",
"fake_result({'a': 1, 'b': 'foo'}) if url.startswith('http://127.0.0.1:124'): return fake_result({'c': 3}) if",
"real_request = requests.request def fake_request(obj, url, method, **kwargs): if url.startswith('http://127.0.0.1:123'):",
"integrated_helpers from nova.tests.unit.image import fake as fake_image class fake_result(object): def",
"returns information about the # server we created above def",
"'127.0.0.2'}) self.assertEqual(200, res.status_code) def test_lookup_metadata_data_url(self): url = '%sopenstack/latest/meta_data.json' % self.md_url",
"# License for the specific language governing permissions and limitations",
"with the License. You may obtain # a copy of",
"you may # not use this file except in compliance",
"server we created above def fake_get_fixed_ip_by_address(self, ctxt, address): return {'instance_uuid':",
"the # server we created above def fake_get_fixed_ip_by_address(self, ctxt, address):",
"os import requests from oslo_serialization import jsonutils from oslo_utils import",
"def setUp(self): super(MetadataTest, self).setUp() fake_image.stub_out_image_service(self) self.addCleanup(fake_image.FakeImageService_reset) self.useFixture(nova_fixtures.NeutronFixture(self)) self.useFixture(func_fixtures.PlacementFixture()) self.start_service('conductor') self.start_service('scheduler')",
"self.md_url, timeout=5) self.assertEqual(200, res.status_code) def test_lookup_metadata_openstack_url(self): url = '%sopenstack' %",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"as func_fixtures from nova.tests.functional import integrated_helpers from nova.tests.unit.image import fake",
"'ACTIVE') self.api_fixture = self.useFixture(nova_fixtures.OSMetadataServer()) self.md_url = self.api_fixture.md_url # make sure",
"# WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"fixtures as nova_fixtures from nova.tests.functional import fixtures as func_fixtures from",
"j) self.assertEqual(1, j['testing']['a']) self.assertEqual('foo', j['testing']['b']) self.assertNotIn('c', j['testing']) def test_lookup_external_service_passes_data(self): #",
"fixtures import jsonschema import os import requests from oslo_serialization import",
"the License is distributed on an \"AS IS\" BASIS, WITHOUT",
"j['testing']) self.assertTrue(uuidutils.is_uuid_like(j['testing']['instance-id'])) self.assertIn('hostname', j['testing']) self.assertEqual(self.server['tenant_id'], j['testing']['project-id']) self.assertIn('metadata', j['testing']) self.assertIn('image-id', j['testing'])",
"for the tests server = self._build_server(name='test') server = self.api.post_server({'server': server})",
"to the external REST # service. self.flags( vendordata_providers=['DynamicJSON'], vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:125'",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"self.flags( vendordata_providers=['StaticJSON', 'DynamicJSON'], vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:123', 'hamster@http://127.0.0.1:123' ], group='api' ) self.useFixture(fixtures.MonkeyPatch(",
"__init__(self, result): self.status_code = 200 self.text = jsonutils.dumps(result) real_request =",
"requests.request('GET', url, timeout=5) self.assertEqual(200, res.status_code) j = jsonutils.loads(res.text) self.assertNotIn('static', j)",
"import uuidutils from nova import test from nova.tests import fixtures",
"for the specific language governing permissions and limitations # under",
"service. self.flags( vendordata_providers=['DynamicJSON'], vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:125' ], group='api' ) self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request',",
") self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request)) url = '%sopenstack/2016-10-06/vendor_data2.json' % self.md_url res",
"'nova.network.neutron.API.get_fixed_ip_by_address', fake_get_fixed_ip_by_address)) def test_lookup_metadata_root_url(self): res = requests.request('GET', self.md_url, timeout=5) self.assertEqual(200,",
"2016 Rackspace Australia # All Rights Reserved. # # Licensed",
"url = '%sopenstack/2016-10-06/vendor_data2.json' % self.md_url res = requests.request('GET', url, timeout=5)",
"nova import test from nova.tests import fixtures as nova_fixtures from",
"= requests.request('GET', url, timeout=5) self.assertEqual(200, res.status_code) j = jsonutils.loads(res.text) self.assertIn('hostname',",
"self.md_url res = requests.request('GET', url, timeout=5) self.assertEqual(200, res.status_code) j =",
"vendordata_providers=['StaticJSON', 'DynamicJSON'], vendordata_dynamic_targets=[ 'testing@http://127.0.0.1:123', 'hamster@http://127.0.0.1:123' ], group='api' ) self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request',",
"except in compliance with the License. You may obtain #",
"return fake_result({'c': 3}) if url.startswith('http://127.0.0.1:125'): return fake_result(jsonutils.loads(kwargs.get('data', '{}'))) return real_request(method,",
"timeout=5) self.assertEqual(200, res.status_code) j = jsonutils.loads(res.text) self.assertEqual({}, j['static']) self.assertEqual(1, j['testing']['a'])",
"if url.startswith('http://127.0.0.1:123'): return fake_result({'a': 1, 'b': 'foo'}) if url.startswith('http://127.0.0.1:124'): return",
"language governing permissions and limitations # under the License. import",
"def __init__(self, result): self.status_code = 200 self.text = jsonutils.dumps(result) real_request",
"**kwargs) class MetadataTest(test.TestCase, integrated_helpers.InstanceHelperMixin): def setUp(self): super(MetadataTest, self).setUp() fake_image.stub_out_image_service(self) self.addCleanup(fake_image.FakeImageService_reset)",
"License. You may obtain # a copy of the License",
"we should at least try # and ensure we're passing",
"url = '%sopenstack/latest/meta_data.json' % self.md_url res = requests.request('GET', url, timeout=5)",
"ANY KIND, either express or implied. See the # License",
"# distributed under the License is distributed on an \"AS",
"from oslo_utils import uuidutils from nova import test from nova.tests",
"# Unless required by applicable law or agreed to in",
"requests.request('GET', url, timeout=5) self.assertEqual(200, res.status_code) j = jsonutils.loads(res.text) self.assertIn('hostname', j)",
"server}) self.server = self._wait_for_state_change(server, 'ACTIVE') self.api_fixture = self.useFixture(nova_fixtures.OSMetadataServer()) self.md_url =",
"import fake as fake_image class fake_result(object): def __init__(self, result): self.status_code",
"is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES",
"{'instance_uuid': server['id']} self.useFixture( fixtures.MonkeyPatch( 'nova.network.neutron.API.get_fixed_ip_by_address', fake_get_fixed_ip_by_address)) def test_lookup_metadata_root_url(self): res =",
"'testing@http://127.0.0.1:123', 'hamster@http://127.0.0.1:123' ], group='api' ) self.useFixture(fixtures.MonkeyPatch( 'keystoneauth1.session.Session.request', fake_request)) url =",
"self.assertEqual({}, j['static']) self.assertEqual(1, j['testing']['a']) self.assertEqual('foo', j['testing']['b']) self.assertEqual(1, j['hamster']['a']) self.assertEqual('foo', j['hamster']['b'])",
"url = '%sopenstack/latest/network_data.json' % self.md_url res = requests.request('GET', url, timeout=5)",
"from nova.tests.unit.image import fake as fake_image class fake_result(object): def __init__(self,",
"jsonutils.loads(res.text) self.assertIn('instance-id', j['testing']) self.assertTrue(uuidutils.is_uuid_like(j['testing']['instance-id'])) self.assertIn('hostname', j['testing']) self.assertEqual(self.server['tenant_id'], j['testing']['project-id']) self.assertIn('metadata', j['testing'])",
"pass to the REST service is missing because of #",
"url.startswith('http://127.0.0.1:125'): return fake_result(jsonutils.loads(kwargs.get('data', '{}'))) return real_request(method, url, **kwargs) class MetadataTest(test.TestCase,",
"os.path.normpath(os.path.join( os.path.dirname(os.path.abspath(__file__)), \"../../../doc/api_schemas/network_data.json\")) with open(schema_file, 'rb') as f: schema =",
"= jsonutils.dumps(result) real_request = requests.request def fake_request(obj, url, method, **kwargs):",
"oslo_serialization import jsonutils from oslo_utils import uuidutils from nova import",
"self.server = self._wait_for_state_change(server, 'ACTIVE') self.api_fixture = self.useFixture(nova_fixtures.OSMetadataServer()) self.md_url = self.api_fixture.md_url",
"# create a server for the tests server = self._build_server(name='test')",
"or implied. See the # License for the specific language"
] |
[
"if not self.General_Mode: spo_predicate_dict = _spo_list_to_spo_predicate_dict(spo_list) else: spo_predicate_dict = _gen_event_dic(spo_list)",
"find index(first time) of q_list in k_list\"\"\" q_list_length = len(q_list)",
"\"w\", encoding='utf-8') self.token_in_not_UNK_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"token_in_not_UNK.txt\"), \"w\", encoding='utf-8') if",
"= idx return idx_start def _labeling_type(subject_object, so_type): tokener_error_flag = False",
"= self.get_data_input_dir(DATA_INPUT_DIR) self.DATA_OUTPUT_DIR = os.path.join(os.path.dirname(__file__), DATA_OUTPUT_DIR) self.General_Mode = General_Mode def",
"+ so_type elif so_tokened_length >= 3: labeling_list[idx_start + 1: idx_start",
"if flag_A: tokener_error_flag = True #给被bert_tokenizer.tokenize 拆分的词语打上特殊标签[##WordPiece] for idx, token",
"\"\"\"Known q_list in k_list, find index(first time) of q_list in",
"spo_item[\"time\"] res.append(('time',time)) if 'location' in spo_item: location = spo_item[\"location\"] res.append(('location',location))",
"import sys import json sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../bert\"))) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../\"))) import tokenization",
"原句: \"●1981年2月27日,中国人口学会成立\" so_tokened ['1981', '年'] text_tokened ['●', '##19', '##81', '年',",
"= spo_item[\"subject\"] object = spo_item[\"object\"] spo_predicate_dict.setdefault(predicate, []).append((subject, object)) return spo_predicate_dict",
"__init__(self, DATA_INPUT_DIR=\"raw_data\", DATA_OUTPUT_DIR=\"SKE_2019_tokened_labeling\", vocab_file_path=\"vocab.txt\", do_lower_case=True,General_Mode = False): self.bert_tokenizer = tokenization.FullTokenizer(vocab_file=self.get_vocab_file_path(vocab_file_path),",
"\"\\n\") self.bert_tokener_error_log_f.write(str(so_tokened) + \" @@ \" + str(text_tokened) + \"\\n\")",
"encoding='utf-8') self.text_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"text.txt\"), \"w\", encoding='utf-8') self.token_in_f =",
"config import config class Model_data_preparation(object): def __init__(self, DATA_INPUT_DIR=\"raw_data\", DATA_OUTPUT_DIR=\"SKE_2019_tokened_labeling\", vocab_file_path=\"vocab.txt\",",
"file_set_type))) self.token_label_and_one_prdicate_out_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"token_label_and_one_prdicate_out.txt\"), \"w\", encoding='utf-8') self.bert_tokener_error_log_f =",
"spo_item[\"subject\"] object = spo_item[\"object\"] spo_predicate_dict.setdefault(predicate, []).append((subject, object)) return spo_predicate_dict def",
"if all(t): # print(idx) idx_start = idx return idx_start def",
"so_tokened = self.bert_tokenizer.tokenize(subject_object) so_tokened_length = len(so_tokened) idx_start = _index_q_list_in_k_list(q_list=so_tokened, k_list=text_tokened)",
"file_set_type in [\"train\", \"valid\"]: print(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type))) self.token_label_and_one_prdicate_out_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type),",
"self.bert_tokener_error_log_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"bert_tokener_error_log.txt\"), \"w\", encoding='utf-8') self.text_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR,",
"False): self.bert_tokenizer = tokenization.FullTokenizer(vocab_file=self.get_vocab_file_path(vocab_file_path), do_lower_case=do_lower_case) # 初始化 bert_token 工具 self.DATA_INPUT_DIR",
"'time' in spo_item: time = spo_item[\"time\"] res.append(('time',time)) if 'location' in",
"elif file_set_type == \"valid\": path_to_raw_data_file = \"valid.json\" else: pass with",
"if 'object' in spo_item: object = spo_item[\"object\"] res.append(('object',object)) res_d[predicate] =",
"= open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"bert_tokener_error_log.txt\"), \"w\", encoding='utf-8') self.text_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type),",
"spo_item[\"predicate\"] subject = spo_item[\"subject\"] object = spo_item[\"object\"] spo_predicate_dict.setdefault(predicate, []).append((subject, object))",
"\".join(labeling_list)+\"\\t\"+predicate+\"\\n\") self.text_f.write(text + \"\\n\") self.token_in_f.write(\" \".join(text_tokened)+\"\\t\"+predicate+\"\\n\") self.token_in_not_UNK_f.write(\" \".join(text_tokened_not_UNK) + \"\\n\")",
"= spo_item[\"object\"] spo_predicate_dict.setdefault(predicate, []).append((subject, object)) return spo_predicate_dict def _gen_event_dic(spo_list): res",
"_labeling_type(item[1],item[0]) if flag_A: tokener_error_flag = True #给被bert_tokenizer.tokenize 拆分的词语打上特殊标签[##WordPiece] for idx,",
"spo_item[\"event\"] if 'time' in spo_item: time = spo_item[\"time\"] res.append(('time',time)) if",
"# print(idx, t) if all(t): # print(idx) idx_start = idx",
"sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../\"))) import tokenization from config import config class Model_data_preparation(object):",
"\"\\n\") def separate_raw_data_and_token_labeling(self): if not os.path.exists(self.DATA_OUTPUT_DIR): os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, \"train\")) os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, \"valid\"))",
"= spo_item[\"denoter\"] res.append(('denoter',denoter)) if 'object' in spo_item: object = spo_item[\"object\"]",
"self.DATA_OUTPUT_DIR = os.path.join(os.path.dirname(__file__), DATA_OUTPUT_DIR) self.General_Mode = General_Mode def get_data_input_dir(self, DATA_INPUT_DIR):",
"len(q_list) k_list_length = len(k_list) for idx in range(k_list_length - q_list_length",
"if file_set_type == \"train\": path_to_raw_data_file = \"train.json\" elif file_set_type ==",
"#flag_B = _labeling_type(spo_object, \"OBJ\") if flag_A or flag_B: tokener_error_flag =",
"def separate_raw_data_and_token_labeling(self): if not os.path.exists(self.DATA_OUTPUT_DIR): os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, \"train\")) os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, \"valid\")) os.makedirs(os.path.join(self.DATA_OUTPUT_DIR,",
"in spo_predicate_dict.items(): tokener_error_flag = False labeling_list = [\"O\"] * len(text_tokened)",
"\"w\", encoding='utf-8') self.token_in_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"token_in.txt\"), \"w\", encoding='utf-8') self.token_in_not_UNK_f",
"path_to_raw_data_file = \"train.json\" elif file_set_type == \"valid\": path_to_raw_data_file = \"valid.json\"",
"self.bert_tokener_error_log_f.write(str(so_tokened) + \" @@ \" + str(text_tokened) + \"\\n\") else:",
"zip(q_list, k_list[idx: idx + q_list_length])] # print(idx, t) if all(t):",
"in spo_list: predicate = spo_item[\"event\"] if 'time' in spo_item: time",
"flag_A or flag_B: tokener_error_flag = True else: for item in",
"_index_q_list_in_k_list(q_list=so_tokened, k_list=text_tokened) if idx_start is None: tokener_error_flag = True '''",
"self.subject_object_labeling(spo_list=spo_list, text=text) else: break print(\"all numbers\", count_numbers) self.text_f.close() self.token_in_f.close() self.token_in_not_UNK_f.close()",
"vocab_file_path=\"vocab.txt\", do_lower_case=True,General_Mode = False): self.bert_tokenizer = tokenization.FullTokenizer(vocab_file=self.get_vocab_file_path(vocab_file_path), do_lower_case=do_lower_case) # 初始化",
"[\"I-\" + so_type] * (so_tokened_length - 1) return tokener_error_flag text_tokened",
"config.data_dir DATA_OUTPUT_DIR = \"sequence_labeling_data\" Vocab_Path = config.bert_vocab_dir General_Mode = False",
"return idx_start def _labeling_type(subject_object, so_type): tokener_error_flag = False so_tokened =",
"q_list in k_list\"\"\" q_list_length = len(q_list) k_list_length = len(k_list) for",
"_index_q_list_in_k_list(q_list, k_list): \"\"\"Known q_list in k_list, find index(first time) of",
"def _index_q_list_in_k_list(q_list, k_list): \"\"\"Known q_list in k_list, find index(first time)",
"k for q, k in zip(q_list, k_list[idx: idx + q_list_length])]",
"True ''' 实体: \"1981年\" 原句: \"●1981年2月27日,中国人口学会成立\" so_tokened ['1981', '年'] text_tokened",
"\".join(text_tokened)+\"\\t\"+predicate+\"\\n\") self.token_in_not_UNK_f.write(\" \".join(text_tokened_not_UNK) + \"\\n\") def separate_raw_data_and_token_labeling(self): if not os.path.exists(self.DATA_OUTPUT_DIR):",
"if 'denoter' in spo_item: denoter = spo_item[\"denoter\"] res.append(('denoter',denoter)) if 'object'",
"= [] res_d = {} predicate = \"\" for spo_item",
"self.token_in_not_UNK_f.write(\" \".join(text_tokened_not_UNK) + \"\\n\") def separate_raw_data_and_token_labeling(self): if not os.path.exists(self.DATA_OUTPUT_DIR): os.makedirs(os.path.join(self.DATA_OUTPUT_DIR,",
">= 3: labeling_list[idx_start + 1: idx_start + so_tokened_length] = [\"I-\"",
"找到!原因是bert_tokenizer.tokenize 分词增添 “##” 所致! ''' self.bert_tokener_error_log_f.write(subject_object + \" @@ \"",
"object = spo_item[\"object\"] spo_predicate_dict.setdefault(predicate, []).append((subject, object)) return spo_predicate_dict def _gen_event_dic(spo_list):",
"if idx_start is None: tokener_error_flag = True ''' 实体: \"1981年\"",
"os.path.exists(self.DATA_OUTPUT_DIR): os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, \"train\")) os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, \"valid\")) os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, \"test\")) for file_set_type in",
"spo_predicate_dict = _gen_event_dic(spo_list) for predicate, spo_list_form in spo_predicate_dict.items(): tokener_error_flag =",
"+ 1): t = [q == k for q, k",
"\".join(text_tokened_not_UNK) + \"\\n\") def separate_raw_data_and_token_labeling(self): if not os.path.exists(self.DATA_OUTPUT_DIR): os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, \"train\"))",
"spo_list = r[\"spo_list\"] self.subject_object_labeling(spo_list=spo_list, text=text) else: break print(\"all numbers\", count_numbers)",
"so_tokened_length] = [\"I-\" + so_type] * (so_tokened_length - 1) return",
"in [\"train\", \"valid\"]: print(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type))) self.token_label_and_one_prdicate_out_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"token_label_and_one_prdicate_out.txt\"),",
"for idx, token in enumerate(text_tokened): \"\"\"标注被 bert_tokenizer.tokenize 拆分的词语\"\"\" if token.startswith(\"##\"):",
"+ \" @@ \" + str(text_tokened) + \"\\n\") else: #给实体开始处标",
"so_tokened_length = len(so_tokened) idx_start = _index_q_list_in_k_list(q_list=so_tokened, k_list=text_tokened) if idx_start is",
"_gen_event_dic(spo_list) for predicate, spo_list_form in spo_predicate_dict.items(): tokener_error_flag = False labeling_list",
"DATA_OUTPUT_DIR) self.General_Mode = General_Mode def get_data_input_dir(self, DATA_INPUT_DIR): DATAself_INPUT_DIR = os.path.join(",
"t) if all(t): # print(idx) idx_start = idx return idx_start",
"spo_list: predicate = spo_item[\"event\"] if 'time' in spo_item: time =",
"+ \"\\n\") self.token_in_f.write(\" \".join(text_tokened)+\"\\t\"+predicate+\"\\n\") self.token_in_not_UNK_f.write(\" \".join(text_tokened_not_UNK) + \"\\n\") def separate_raw_data_and_token_labeling(self):",
"Vocab_Path = config.bert_vocab_dir General_Mode = False model_data = Model_data_preparation(General_Mode =",
"self.token_label_and_one_prdicate_out_f.write(\" \".join(labeling_list)+\"\\t\"+predicate+\"\\n\") self.text_f.write(text + \"\\n\") self.token_in_f.write(\" \".join(text_tokened)+\"\\t\"+predicate+\"\\n\") self.token_in_not_UNK_f.write(\" \".join(text_tokened_not_UNK) +",
"in zip(q_list, k_list[idx: idx + q_list_length])] # print(idx, t) if",
"\"valid\": path_to_raw_data_file = \"valid.json\" else: pass with open(os.path.join(self.DATA_INPUT_DIR, path_to_raw_data_file), 'r',",
"_labeling_type(spo_object, \"OBJ\") if flag_A or flag_B: tokener_error_flag = True else:",
"spo_list: predicate = spo_item[\"predicate\"] subject = spo_item[\"subject\"] object = spo_item[\"object\"]",
"tokenization.FullTokenizer(vocab_file=self.get_vocab_file_path(vocab_file_path), do_lower_case=do_lower_case) # 初始化 bert_token 工具 self.DATA_INPUT_DIR = self.get_data_input_dir(DATA_INPUT_DIR) self.DATA_OUTPUT_DIR",
"spo_predicate_dict.items(): tokener_error_flag = False labeling_list = [\"O\"] * len(text_tokened) if",
"in spo_item: location = spo_item[\"location\"] res.append(('location',location)) if 'participant' in spo_item:",
"object)) return spo_predicate_dict def _gen_event_dic(spo_list): res = [] res_d =",
"\"\" for spo_item in spo_list: predicate = spo_item[\"event\"] if 'time'",
"predicate = spo_item[\"event\"] if 'time' in spo_item: time = spo_item[\"time\"]",
"idx_start is None: tokener_error_flag = True ''' 实体: \"1981年\" 原句:",
"',', '中', '国', '人', '口', '学', '会', '成', '立'] so_tokened",
"continue flag_A = _labeling_type(item[1],item[0]) if flag_A: tokener_error_flag = True #给被bert_tokenizer.tokenize",
"self.bert_tokenizer.tokenize_not_UNK(text) if not self.General_Mode: spo_predicate_dict = _spo_list_to_spo_predicate_dict(spo_list) else: spo_predicate_dict =",
"count_numbers = 0 while True: line = f.readline() if line:",
"open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"token_in.txt\"), \"w\", encoding='utf-8') self.token_in_not_UNK_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"token_in_not_UNK.txt\"),",
"print(idx, t) if all(t): # print(idx) idx_start = idx return",
"so_tokened_length == 2: labeling_list[idx_start + 1] = \"I-\" + so_type",
"self.text_f.close() self.token_in_f.close() self.token_in_not_UNK_f.close() self.token_label_and_one_prdicate_out_f.close() self.bert_tokener_error_log_f.close() if __name__==\"__main__\": DATA_INPUT_DIR = config.data_dir",
"os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, \"test\")) for file_set_type in [\"train\", \"valid\"]: print(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type))) self.token_label_and_one_prdicate_out_f",
"- 1) return tokener_error_flag text_tokened = self.bert_tokenizer.tokenize(text) text_tokened_not_UNK = self.bert_tokenizer.tokenize_not_UNK(text)",
"\" @@ \" + str(text_tokened) + \"\\n\") else: #给实体开始处标 B",
"+ so_type if so_tokened_length == 2: labeling_list[idx_start + 1] =",
"file_set_type), \"token_in_not_UNK.txt\"), \"w\", encoding='utf-8') if file_set_type == \"train\": path_to_raw_data_file =",
"k_list, find index(first time) of q_list in k_list\"\"\" q_list_length =",
"index(first time) of q_list in k_list\"\"\" q_list_length = len(q_list) k_list_length",
"['●', '##19', '##81', '年', '2', '月', '27', '日', ',', '中',",
"if token.startswith(\"##\"): labeling_list[idx] = \"[##WordPiece]\" if not tokener_error_flag: self.token_label_and_one_prdicate_out_f.write(\" \".join(labeling_list)+\"\\t\"+predicate+\"\\n\")",
"= {} predicate = \"\" for spo_item in spo_list: predicate",
"= open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"token_in.txt\"), \"w\", encoding='utf-8') self.token_in_not_UNK_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type),",
"2: labeling_list[idx_start + 1] = \"I-\" + so_type elif so_tokened_length",
"'location' in spo_item: location = spo_item[\"location\"] res.append(('location',location)) if 'participant' in",
"count_numbers) self.text_f.close() self.token_in_f.close() self.token_in_not_UNK_f.close() self.token_label_and_one_prdicate_out_f.close() self.bert_tokener_error_log_f.close() if __name__==\"__main__\": DATA_INPUT_DIR =",
"res = [] res_d = {} predicate = \"\" for",
"else: #给实体开始处标 B 其它位置标 I labeling_list[idx_start] = \"B-\" + so_type",
"spo_item[\"object\"] res.append(('object',object)) res_d[predicate] = res return res_d def _index_q_list_in_k_list(q_list, k_list):",
"bert_token 工具 self.DATA_INPUT_DIR = self.get_data_input_dir(DATA_INPUT_DIR) self.DATA_OUTPUT_DIR = os.path.join(os.path.dirname(__file__), DATA_OUTPUT_DIR) self.General_Mode",
"+ so_type] * (so_tokened_length - 1) return tokener_error_flag text_tokened =",
"else: break print(\"all numbers\", count_numbers) self.text_f.close() self.token_in_f.close() self.token_in_not_UNK_f.close() self.token_label_and_one_prdicate_out_f.close() self.bert_tokener_error_log_f.close()",
"工具 self.DATA_INPUT_DIR = self.get_data_input_dir(DATA_INPUT_DIR) self.DATA_OUTPUT_DIR = os.path.join(os.path.dirname(__file__), DATA_OUTPUT_DIR) self.General_Mode =",
"elif so_tokened_length >= 3: labeling_list[idx_start + 1: idx_start + so_tokened_length]",
"open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"token_label_and_one_prdicate_out.txt\"), \"w\", encoding='utf-8') self.bert_tokener_error_log_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"bert_tokener_error_log.txt\"),",
"len(k_list) for idx in range(k_list_length - q_list_length + 1): t",
"'27', '日', ',', '中', '国', '人', '口', '学', '会', '成',",
"\"OBJ\") if flag_A or flag_B: tokener_error_flag = True else: for",
"'r', encoding='utf-8') as f: count_numbers = 0 while True: line",
"res.append(('denoter',denoter)) if 'object' in spo_item: object = spo_item[\"object\"] res.append(('object',object)) res_d[predicate]",
"for spo_item in spo_list: predicate = spo_item[\"event\"] if 'time' in",
"so_type] * (so_tokened_length - 1) return tokener_error_flag text_tokened = self.bert_tokenizer.tokenize(text)",
"if item[1]== None: continue flag_A = _labeling_type(item[1],item[0]) if flag_A: tokener_error_flag",
"DATA_INPUT_DIR=\"raw_data\", DATA_OUTPUT_DIR=\"SKE_2019_tokened_labeling\", vocab_file_path=\"vocab.txt\", do_lower_case=True,General_Mode = False): self.bert_tokenizer = tokenization.FullTokenizer(vocab_file=self.get_vocab_file_path(vocab_file_path), do_lower_case=do_lower_case)",
"spo_item: denoter = spo_item[\"denoter\"] res.append(('denoter',denoter)) if 'object' in spo_item: object",
"location = spo_item[\"location\"] res.append(('location',location)) if 'participant' in spo_item: participant =",
"= _index_q_list_in_k_list(q_list=so_tokened, k_list=text_tokened) if idx_start is None: tokener_error_flag = True",
"for spo_item in spo_list: predicate = spo_item[\"predicate\"] subject = spo_item[\"subject\"]",
"self.token_in_f.write(\" \".join(text_tokened)+\"\\t\"+predicate+\"\\n\") self.token_in_not_UNK_f.write(\" \".join(text_tokened_not_UNK) + \"\\n\") def separate_raw_data_and_token_labeling(self): if not",
"['1981', '年'] text_tokened ['●', '##19', '##81', '年', '2', '月', '27',",
"spo_list_form: flag_A = _labeling_type(spo_subject, \"SUB\") #flag_B = _labeling_type(spo_object, \"OBJ\") if",
"in spo_item: time = spo_item[\"time\"] res.append(('time',time)) if 'location' in spo_item:",
"os.path.join( os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../\")), DATA_INPUT_DIR) return DATA_INPUT_DIR def get_vocab_file_path(self, vocab_file_path): print(vocab_file_path)",
"1) return tokener_error_flag text_tokened = self.bert_tokenizer.tokenize(text) text_tokened_not_UNK = self.bert_tokenizer.tokenize_not_UNK(text) if",
"return vocab_file_path def subject_object_labeling(self, spo_list, text): def _spo_list_to_spo_predicate_dict(spo_list): spo_predicate_dict =",
"self.General_Mode = General_Mode def get_data_input_dir(self, DATA_INPUT_DIR): DATAself_INPUT_DIR = os.path.join( os.path.abspath(os.path.join(os.path.dirname(__file__),",
"'日', ',', '中', '国', '人', '口', '学', '会', '成', '立']",
"in spo_list: predicate = spo_item[\"predicate\"] subject = spo_item[\"subject\"] object =",
"text=text) else: break print(\"all numbers\", count_numbers) self.text_f.close() self.token_in_f.close() self.token_in_not_UNK_f.close() self.token_label_and_one_prdicate_out_f.close()",
"so_type): tokener_error_flag = False so_tokened = self.bert_tokenizer.tokenize(subject_object) so_tokened_length = len(so_tokened)",
"1] = \"I-\" + so_type elif so_tokened_length >= 3: labeling_list[idx_start",
"labeling_list[idx_start + 1: idx_start + so_tokened_length] = [\"I-\" + so_type]",
"def get_data_input_dir(self, DATA_INPUT_DIR): DATAself_INPUT_DIR = os.path.join( os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../\")), DATA_INPUT_DIR) return",
"def _gen_event_dic(spo_list): res = [] res_d = {} predicate =",
"labeling_list[idx] = \"[##WordPiece]\" if not tokener_error_flag: self.token_label_and_one_prdicate_out_f.write(\" \".join(labeling_list)+\"\\t\"+predicate+\"\\n\") self.text_f.write(text +",
"\"train\")) os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, \"valid\")) os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, \"test\")) for file_set_type in [\"train\", \"valid\"]:",
"= [q == k for q, k in zip(q_list, k_list[idx:",
"get_data_input_dir(self, DATA_INPUT_DIR): DATAself_INPUT_DIR = os.path.join( os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../\")), DATA_INPUT_DIR) return DATA_INPUT_DIR",
"= spo_item[\"time\"] res.append(('time',time)) if 'location' in spo_item: location = spo_item[\"location\"]",
"if __name__==\"__main__\": DATA_INPUT_DIR = config.data_dir DATA_OUTPUT_DIR = \"sequence_labeling_data\" Vocab_Path =",
"print(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type))) self.token_label_and_one_prdicate_out_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"token_label_and_one_prdicate_out.txt\"), \"w\", encoding='utf-8') self.bert_tokener_error_log_f",
"self.DATA_INPUT_DIR = self.get_data_input_dir(DATA_INPUT_DIR) self.DATA_OUTPUT_DIR = os.path.join(os.path.dirname(__file__), DATA_OUTPUT_DIR) self.General_Mode = General_Mode",
"'年', '2', '月', '27', '日', ',', '中', '国', '人', '口',",
"self.bert_tokenizer.tokenize(text) text_tokened_not_UNK = self.bert_tokenizer.tokenize_not_UNK(text) if not self.General_Mode: spo_predicate_dict = _spo_list_to_spo_predicate_dict(spo_list)",
"= False labeling_list = [\"O\"] * len(text_tokened) if not self.General_Mode:",
"+ 1: idx_start + so_tokened_length] = [\"I-\" + so_type] *",
"predicate, spo_list_form in spo_predicate_dict.items(): tokener_error_flag = False labeling_list = [\"O\"]",
"pass with open(os.path.join(self.DATA_INPUT_DIR, path_to_raw_data_file), 'r', encoding='utf-8') as f: count_numbers =",
"res.append(('object',object)) res_d[predicate] = res return res_d def _index_q_list_in_k_list(q_list, k_list): \"\"\"Known",
"len(so_tokened) idx_start = _index_q_list_in_k_list(q_list=so_tokened, k_list=text_tokened) if idx_start is None: tokener_error_flag",
"DATA_INPUT_DIR) return DATA_INPUT_DIR def get_vocab_file_path(self, vocab_file_path): print(vocab_file_path) return vocab_file_path def",
"+= 1 r = json.loads(line) text = r[\"text\"] spo_list =",
"* len(text_tokened) if not self.General_Mode: for (spo_subject, spo_object) in spo_list_form:",
"in spo_item: object = spo_item[\"object\"] res.append(('object',object)) res_d[predicate] = res return",
"== 2: labeling_list[idx_start + 1] = \"I-\" + so_type elif",
"= False so_tokened = self.bert_tokenizer.tokenize(subject_object) so_tokened_length = len(so_tokened) idx_start =",
"text = r[\"text\"] spo_list = r[\"spo_list\"] self.subject_object_labeling(spo_list=spo_list, text=text) else: break",
"spo_item[\"participant\"] res.append(('participant',participant)) if 'denoter' in spo_item: denoter = spo_item[\"denoter\"] res.append(('denoter',denoter))",
"r[\"spo_list\"] self.subject_object_labeling(spo_list=spo_list, text=text) else: break print(\"all numbers\", count_numbers) self.text_f.close() self.token_in_f.close()",
"so_tokened ['1981', '年'] text_tokened ['●', '##19', '##81', '年', '2', '月',",
"if flag_A or flag_B: tokener_error_flag = True else: for item",
"'2', '月', '27', '日', ',', '中', '国', '人', '口', '学',",
"= len(q_list) k_list_length = len(k_list) for idx in range(k_list_length -",
"\"token_in_not_UNK.txt\"), \"w\", encoding='utf-8') if file_set_type == \"train\": path_to_raw_data_file = \"train.json\"",
"q_list_length = len(q_list) k_list_length = len(k_list) for idx in range(k_list_length",
"participant = spo_item[\"participant\"] res.append(('participant',participant)) if 'denoter' in spo_item: denoter =",
"+ \"\\n\") self.bert_tokener_error_log_f.write(str(so_tokened) + \" @@ \" + str(text_tokened) +",
"= \"[##WordPiece]\" if not tokener_error_flag: self.token_label_and_one_prdicate_out_f.write(\" \".join(labeling_list)+\"\\t\"+predicate+\"\\n\") self.text_f.write(text + \"\\n\")",
"not tokener_error_flag: self.token_label_and_one_prdicate_out_f.write(\" \".join(labeling_list)+\"\\t\"+predicate+\"\\n\") self.text_f.write(text + \"\\n\") self.token_in_f.write(\" \".join(text_tokened)+\"\\t\"+predicate+\"\\n\") self.token_in_not_UNK_f.write(\"",
"+ text + \"\\n\") self.bert_tokener_error_log_f.write(str(so_tokened) + \" @@ \" +",
"k_list=text_tokened) if idx_start is None: tokener_error_flag = True ''' 实体:",
"in spo_item: participant = spo_item[\"participant\"] res.append(('participant',participant)) if 'denoter' in spo_item:",
"'participant' in spo_item: participant = spo_item[\"participant\"] res.append(('participant',participant)) if 'denoter' in",
"_gen_event_dic(spo_list): res = [] res_d = {} predicate = \"\"",
"= os.path.join(os.path.dirname(__file__), DATA_OUTPUT_DIR) self.General_Mode = General_Mode def get_data_input_dir(self, DATA_INPUT_DIR): DATAself_INPUT_DIR",
"\"[##WordPiece]\" if not tokener_error_flag: self.token_label_and_one_prdicate_out_f.write(\" \".join(labeling_list)+\"\\t\"+predicate+\"\\n\") self.text_f.write(text + \"\\n\") self.token_in_f.write(\"",
"'人', '口', '学', '会', '成', '立'] so_tokened 无法在 text_tokened 找到!原因是bert_tokenizer.tokenize",
"+ \"\\n\") else: #给实体开始处标 B 其它位置标 I labeling_list[idx_start] = \"B-\"",
"separate_raw_data_and_token_labeling(self): if not os.path.exists(self.DATA_OUTPUT_DIR): os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, \"train\")) os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, \"valid\")) os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, \"test\"))",
"= \"train.json\" elif file_set_type == \"valid\": path_to_raw_data_file = \"valid.json\" else:",
"self.bert_tokener_error_log_f.write(subject_object + \" @@ \" + text + \"\\n\") self.bert_tokener_error_log_f.write(str(so_tokened)",
"DATAself_INPUT_DIR = os.path.join( os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../\")), DATA_INPUT_DIR) return DATA_INPUT_DIR def get_vocab_file_path(self,",
"'denoter' in spo_item: denoter = spo_item[\"denoter\"] res.append(('denoter',denoter)) if 'object' in",
"labeling_list = [\"O\"] * len(text_tokened) if not self.General_Mode: for (spo_subject,",
"r[\"text\"] spo_list = r[\"spo_list\"] self.subject_object_labeling(spo_list=spo_list, text=text) else: break print(\"all numbers\",",
"object = spo_item[\"object\"] res.append(('object',object)) res_d[predicate] = res return res_d def",
"''' self.bert_tokener_error_log_f.write(subject_object + \" @@ \" + text + \"\\n\")",
"\"I-\" + so_type elif so_tokened_length >= 3: labeling_list[idx_start + 1:",
"@@ \" + text + \"\\n\") self.bert_tokener_error_log_f.write(str(so_tokened) + \" @@",
"t = [q == k for q, k in zip(q_list,",
"def subject_object_labeling(self, spo_list, text): def _spo_list_to_spo_predicate_dict(spo_list): spo_predicate_dict = dict() for",
"in k_list\"\"\" q_list_length = len(q_list) k_list_length = len(k_list) for idx",
"line = f.readline() if line: count_numbers += 1 r =",
"range(k_list_length - q_list_length + 1): t = [q == k",
"os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../\")), DATA_INPUT_DIR) return DATA_INPUT_DIR def get_vocab_file_path(self, vocab_file_path): print(vocab_file_path) return",
"'月', '27', '日', ',', '中', '国', '人', '口', '学', '会',",
"'##19', '##81', '年', '2', '月', '27', '日', ',', '中', '国',",
"= True #给被bert_tokenizer.tokenize 拆分的词语打上特殊标签[##WordPiece] for idx, token in enumerate(text_tokened): \"\"\"标注被",
"flag_A = _labeling_type(spo_subject, \"SUB\") #flag_B = _labeling_type(spo_object, \"OBJ\") if flag_A",
"res.append(('participant',participant)) if 'denoter' in spo_item: denoter = spo_item[\"denoter\"] res.append(('denoter',denoter)) if",
"numbers\", count_numbers) self.text_f.close() self.token_in_f.close() self.token_in_not_UNK_f.close() self.token_label_and_one_prdicate_out_f.close() self.bert_tokener_error_log_f.close() if __name__==\"__main__\": DATA_INPUT_DIR",
"= f.readline() if line: count_numbers += 1 r = json.loads(line)",
"idx, token in enumerate(text_tokened): \"\"\"标注被 bert_tokenizer.tokenize 拆分的词语\"\"\" if token.startswith(\"##\"): labeling_list[idx]",
"'学', '会', '成', '立'] so_tokened 无法在 text_tokened 找到!原因是bert_tokenizer.tokenize 分词增添 “##”",
"idx + q_list_length])] # print(idx, t) if all(t): # print(idx)",
"# print(idx) idx_start = idx return idx_start def _labeling_type(subject_object, so_type):",
"= spo_item[\"event\"] if 'time' in spo_item: time = spo_item[\"time\"] res.append(('time',time))",
"denoter = spo_item[\"denoter\"] res.append(('denoter',denoter)) if 'object' in spo_item: object =",
"= _labeling_type(spo_object, \"OBJ\") if flag_A or flag_B: tokener_error_flag = True",
"self.token_label_and_one_prdicate_out_f.close() self.bert_tokener_error_log_f.close() if __name__==\"__main__\": DATA_INPUT_DIR = config.data_dir DATA_OUTPUT_DIR = \"sequence_labeling_data\"",
"if so_tokened_length == 2: labeling_list[idx_start + 1] = \"I-\" +",
"for file_set_type in [\"train\", \"valid\"]: print(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type))) self.token_label_and_one_prdicate_out_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR,",
"tokener_error_flag = True ''' 实体: \"1981年\" 原句: \"●1981年2月27日,中国人口学会成立\" so_tokened ['1981',",
"idx_start = _index_q_list_in_k_list(q_list=so_tokened, k_list=text_tokened) if idx_start is None: tokener_error_flag =",
"= \"sequence_labeling_data\" Vocab_Path = config.bert_vocab_dir General_Mode = False model_data =",
"@@ \" + str(text_tokened) + \"\\n\") else: #给实体开始处标 B 其它位置标",
"subject_object_labeling(self, spo_list, text): def _spo_list_to_spo_predicate_dict(spo_list): spo_predicate_dict = dict() for spo_item",
"os.path.join(os.path.dirname(__file__), DATA_OUTPUT_DIR) self.General_Mode = General_Mode def get_data_input_dir(self, DATA_INPUT_DIR): DATAself_INPUT_DIR =",
"flag_A: tokener_error_flag = True #给被bert_tokenizer.tokenize 拆分的词语打上特殊标签[##WordPiece] for idx, token in",
"True #给被bert_tokenizer.tokenize 拆分的词语打上特殊标签[##WordPiece] for idx, token in enumerate(text_tokened): \"\"\"标注被 bert_tokenizer.tokenize",
"\"\\n\") else: #给实体开始处标 B 其它位置标 I labeling_list[idx_start] = \"B-\" +",
"time = spo_item[\"time\"] res.append(('time',time)) if 'location' in spo_item: location =",
"3: labeling_list[idx_start + 1: idx_start + so_tokened_length] = [\"I-\" +",
"in spo_list_form: if item[1]== None: continue flag_A = _labeling_type(item[1],item[0]) if",
"k_list[idx: idx + q_list_length])] # print(idx, t) if all(t): #",
"= [\"I-\" + so_type] * (so_tokened_length - 1) return tokener_error_flag",
"'成', '立'] so_tokened 无法在 text_tokened 找到!原因是bert_tokenizer.tokenize 分词增添 “##” 所致! '''",
"as f: count_numbers = 0 while True: line = f.readline()",
"= True ''' 实体: \"1981年\" 原句: \"●1981年2月27日,中国人口学会成立\" so_tokened ['1981', '年']",
"无法在 text_tokened 找到!原因是bert_tokenizer.tokenize 分词增添 “##” 所致! ''' self.bert_tokener_error_log_f.write(subject_object + \"",
"k_list_length = len(k_list) for idx in range(k_list_length - q_list_length +",
"\"text.txt\"), \"w\", encoding='utf-8') self.token_in_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"token_in.txt\"), \"w\", encoding='utf-8')",
"time) of q_list in k_list\"\"\" q_list_length = len(q_list) k_list_length =",
"idx_start + so_tokened_length] = [\"I-\" + so_type] * (so_tokened_length -",
"I labeling_list[idx_start] = \"B-\" + so_type if so_tokened_length == 2:",
"text_tokened = self.bert_tokenizer.tokenize(text) text_tokened_not_UNK = self.bert_tokenizer.tokenize_not_UNK(text) if not self.General_Mode: spo_predicate_dict",
"import os import sys import json sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../bert\"))) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../\")))",
"False labeling_list = [\"O\"] * len(text_tokened) if not self.General_Mode: for",
"__name__==\"__main__\": DATA_INPUT_DIR = config.data_dir DATA_OUTPUT_DIR = \"sequence_labeling_data\" Vocab_Path = config.bert_vocab_dir",
"not self.General_Mode: for (spo_subject, spo_object) in spo_list_form: flag_A = _labeling_type(spo_subject,",
"config.bert_vocab_dir General_Mode = False model_data = Model_data_preparation(General_Mode = General_Mode,DATA_INPUT_DIR=DATA_INPUT_DIR, DATA_OUTPUT_DIR=DATA_OUTPUT_DIR,vocab_file_path=Vocab_Path)",
"''' 实体: \"1981年\" 原句: \"●1981年2月27日,中国人口学会成立\" so_tokened ['1981', '年'] text_tokened ['●',",
"spo_predicate_dict = _spo_list_to_spo_predicate_dict(spo_list) else: spo_predicate_dict = _gen_event_dic(spo_list) for predicate, spo_list_form",
"os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, \"valid\")) os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, \"test\")) for file_set_type in [\"train\", \"valid\"]: print(os.path.join(os.path.join(self.DATA_OUTPUT_DIR,",
"\"test\")) for file_set_type in [\"train\", \"valid\"]: print(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type))) self.token_label_and_one_prdicate_out_f =",
"get_vocab_file_path(self, vocab_file_path): print(vocab_file_path) return vocab_file_path def subject_object_labeling(self, spo_list, text): def",
"idx return idx_start def _labeling_type(subject_object, so_type): tokener_error_flag = False so_tokened",
"idx in range(k_list_length - q_list_length + 1): t = [q",
"text_tokened ['●', '##19', '##81', '年', '2', '月', '27', '日', ',',",
"= config.bert_vocab_dir General_Mode = False model_data = Model_data_preparation(General_Mode = General_Mode,DATA_INPUT_DIR=DATA_INPUT_DIR,",
"if 'participant' in spo_item: participant = spo_item[\"participant\"] res.append(('participant',participant)) if 'denoter'",
"return DATA_INPUT_DIR def get_vocab_file_path(self, vocab_file_path): print(vocab_file_path) return vocab_file_path def subject_object_labeling(self,",
"f: count_numbers = 0 while True: line = f.readline() if",
"item[1]== None: continue flag_A = _labeling_type(item[1],item[0]) if flag_A: tokener_error_flag =",
"labeling_list[idx_start] = \"B-\" + so_type if so_tokened_length == 2: labeling_list[idx_start",
"not os.path.exists(self.DATA_OUTPUT_DIR): os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, \"train\")) os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, \"valid\")) os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, \"test\")) for file_set_type",
"'中', '国', '人', '口', '学', '会', '成', '立'] so_tokened 无法在",
"k_list): \"\"\"Known q_list in k_list, find index(first time) of q_list",
"\"1981年\" 原句: \"●1981年2月27日,中国人口学会成立\" so_tokened ['1981', '年'] text_tokened ['●', '##19', '##81',",
"do_lower_case=do_lower_case) # 初始化 bert_token 工具 self.DATA_INPUT_DIR = self.get_data_input_dir(DATA_INPUT_DIR) self.DATA_OUTPUT_DIR =",
"= [\"O\"] * len(text_tokened) if not self.General_Mode: for (spo_subject, spo_object)",
"self.get_data_input_dir(DATA_INPUT_DIR) self.DATA_OUTPUT_DIR = os.path.join(os.path.dirname(__file__), DATA_OUTPUT_DIR) self.General_Mode = General_Mode def get_data_input_dir(self,",
"os import sys import json sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../bert\"))) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../\"))) import",
"def _labeling_type(subject_object, so_type): tokener_error_flag = False so_tokened = self.bert_tokenizer.tokenize(subject_object) so_tokened_length",
"file_set_type == \"valid\": path_to_raw_data_file = \"valid.json\" else: pass with open(os.path.join(self.DATA_INPUT_DIR,",
"in enumerate(text_tokened): \"\"\"标注被 bert_tokenizer.tokenize 拆分的词语\"\"\" if token.startswith(\"##\"): labeling_list[idx] = \"[##WordPiece]\"",
"拆分的词语打上特殊标签[##WordPiece] for idx, token in enumerate(text_tokened): \"\"\"标注被 bert_tokenizer.tokenize 拆分的词语\"\"\" if",
"= len(k_list) for idx in range(k_list_length - q_list_length + 1):",
"= _spo_list_to_spo_predicate_dict(spo_list) else: spo_predicate_dict = _gen_event_dic(spo_list) for predicate, spo_list_form in",
"os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, \"train\")) os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, \"valid\")) os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, \"test\")) for file_set_type in [\"train\",",
"self.General_Mode: for (spo_subject, spo_object) in spo_list_form: flag_A = _labeling_type(spo_subject, \"SUB\")",
"== \"train\": path_to_raw_data_file = \"train.json\" elif file_set_type == \"valid\": path_to_raw_data_file",
"open(os.path.join(self.DATA_INPUT_DIR, path_to_raw_data_file), 'r', encoding='utf-8') as f: count_numbers = 0 while",
"= self.bert_tokenizer.tokenize(text) text_tokened_not_UNK = self.bert_tokenizer.tokenize_not_UNK(text) if not self.General_Mode: spo_predicate_dict =",
"text): def _spo_list_to_spo_predicate_dict(spo_list): spo_predicate_dict = dict() for spo_item in spo_list:",
"else: for item in spo_list_form: if item[1]== None: continue flag_A",
"sys import json sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../bert\"))) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../\"))) import tokenization from",
"else: pass with open(os.path.join(self.DATA_INPUT_DIR, path_to_raw_data_file), 'r', encoding='utf-8') as f: count_numbers",
"so_tokened_length >= 3: labeling_list[idx_start + 1: idx_start + so_tokened_length] =",
"'立'] so_tokened 无法在 text_tokened 找到!原因是bert_tokenizer.tokenize 分词增添 “##” 所致! ''' self.bert_tokener_error_log_f.write(subject_object",
"= tokenization.FullTokenizer(vocab_file=self.get_vocab_file_path(vocab_file_path), do_lower_case=do_lower_case) # 初始化 bert_token 工具 self.DATA_INPUT_DIR = self.get_data_input_dir(DATA_INPUT_DIR)",
"def _spo_list_to_spo_predicate_dict(spo_list): spo_predicate_dict = dict() for spo_item in spo_list: predicate",
"open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"text.txt\"), \"w\", encoding='utf-8') self.token_in_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"token_in.txt\"),",
"dict() for spo_item in spo_list: predicate = spo_item[\"predicate\"] subject =",
"count_numbers += 1 r = json.loads(line) text = r[\"text\"] spo_list",
"# 初始化 bert_token 工具 self.DATA_INPUT_DIR = self.get_data_input_dir(DATA_INPUT_DIR) self.DATA_OUTPUT_DIR = os.path.join(os.path.dirname(__file__),",
"'年'] text_tokened ['●', '##19', '##81', '年', '2', '月', '27', '日',",
"for (spo_subject, spo_object) in spo_list_form: flag_A = _labeling_type(spo_subject, \"SUB\") #flag_B",
"其它位置标 I labeling_list[idx_start] = \"B-\" + so_type if so_tokened_length ==",
"with open(os.path.join(self.DATA_INPUT_DIR, path_to_raw_data_file), 'r', encoding='utf-8') as f: count_numbers = 0",
"\" + text + \"\\n\") self.bert_tokener_error_log_f.write(str(so_tokened) + \" @@ \"",
"if line: count_numbers += 1 r = json.loads(line) text =",
"_spo_list_to_spo_predicate_dict(spo_list) else: spo_predicate_dict = _gen_event_dic(spo_list) for predicate, spo_list_form in spo_predicate_dict.items():",
"_spo_list_to_spo_predicate_dict(spo_list): spo_predicate_dict = dict() for spo_item in spo_list: predicate =",
"= spo_item[\"participant\"] res.append(('participant',participant)) if 'denoter' in spo_item: denoter = spo_item[\"denoter\"]",
"\"●1981年2月27日,中国人口学会成立\" so_tokened ['1981', '年'] text_tokened ['●', '##19', '##81', '年', '2',",
"all(t): # print(idx) idx_start = idx return idx_start def _labeling_type(subject_object,",
"self.bert_tokener_error_log_f.close() if __name__==\"__main__\": DATA_INPUT_DIR = config.data_dir DATA_OUTPUT_DIR = \"sequence_labeling_data\" Vocab_Path",
"self.text_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"text.txt\"), \"w\", encoding='utf-8') self.token_in_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR,",
"tokener_error_flag text_tokened = self.bert_tokenizer.tokenize(text) text_tokened_not_UNK = self.bert_tokenizer.tokenize_not_UNK(text) if not self.General_Mode:",
"str(text_tokened) + \"\\n\") else: #给实体开始处标 B 其它位置标 I labeling_list[idx_start] =",
"+ so_tokened_length] = [\"I-\" + so_type] * (so_tokened_length - 1)",
"= os.path.join( os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../\")), DATA_INPUT_DIR) return DATA_INPUT_DIR def get_vocab_file_path(self, vocab_file_path):",
"text_tokened_not_UNK = self.bert_tokenizer.tokenize_not_UNK(text) if not self.General_Mode: spo_predicate_dict = _spo_list_to_spo_predicate_dict(spo_list) else:",
"= len(so_tokened) idx_start = _index_q_list_in_k_list(q_list=so_tokened, k_list=text_tokened) if idx_start is None:",
"res_d[predicate] = res return res_d def _index_q_list_in_k_list(q_list, k_list): \"\"\"Known q_list",
"q_list_length])] # print(idx, t) if all(t): # print(idx) idx_start =",
"== k for q, k in zip(q_list, k_list[idx: idx +",
"encoding='utf-8') self.token_in_not_UNK_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"token_in_not_UNK.txt\"), \"w\", encoding='utf-8') if file_set_type",
"from config import config class Model_data_preparation(object): def __init__(self, DATA_INPUT_DIR=\"raw_data\", DATA_OUTPUT_DIR=\"SKE_2019_tokened_labeling\",",
"file_set_type == \"train\": path_to_raw_data_file = \"train.json\" elif file_set_type == \"valid\":",
"for q, k in zip(q_list, k_list[idx: idx + q_list_length])] #",
"return tokener_error_flag text_tokened = self.bert_tokenizer.tokenize(text) text_tokened_not_UNK = self.bert_tokenizer.tokenize_not_UNK(text) if not",
"predicate = spo_item[\"predicate\"] subject = spo_item[\"subject\"] object = spo_item[\"object\"] spo_predicate_dict.setdefault(predicate,",
"1 r = json.loads(line) text = r[\"text\"] spo_list = r[\"spo_list\"]",
"flag_B: tokener_error_flag = True else: for item in spo_list_form: if",
"= _labeling_type(spo_subject, \"SUB\") #flag_B = _labeling_type(spo_object, \"OBJ\") if flag_A or",
"tokenization from config import config class Model_data_preparation(object): def __init__(self, DATA_INPUT_DIR=\"raw_data\",",
"if not os.path.exists(self.DATA_OUTPUT_DIR): os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, \"train\")) os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, \"valid\")) os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, \"test\")) for",
"\"bert_tokener_error_log.txt\"), \"w\", encoding='utf-8') self.text_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"text.txt\"), \"w\", encoding='utf-8')",
"= open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"text.txt\"), \"w\", encoding='utf-8') self.token_in_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type),",
"import config class Model_data_preparation(object): def __init__(self, DATA_INPUT_DIR=\"raw_data\", DATA_OUTPUT_DIR=\"SKE_2019_tokened_labeling\", vocab_file_path=\"vocab.txt\", do_lower_case=True,General_Mode",
"分词增添 “##” 所致! ''' self.bert_tokener_error_log_f.write(subject_object + \" @@ \" +",
"f.readline() if line: count_numbers += 1 r = json.loads(line) text",
"else: spo_predicate_dict = _gen_event_dic(spo_list) for predicate, spo_list_form in spo_predicate_dict.items(): tokener_error_flag",
"or flag_B: tokener_error_flag = True else: for item in spo_list_form:",
"file_set_type), \"bert_tokener_error_log.txt\"), \"w\", encoding='utf-8') self.text_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"text.txt\"), \"w\",",
"spo_list, text): def _spo_list_to_spo_predicate_dict(spo_list): spo_predicate_dict = dict() for spo_item in",
"self.bert_tokenizer = tokenization.FullTokenizer(vocab_file=self.get_vocab_file_path(vocab_file_path), do_lower_case=do_lower_case) # 初始化 bert_token 工具 self.DATA_INPUT_DIR =",
"json.loads(line) text = r[\"text\"] spo_list = r[\"spo_list\"] self.subject_object_labeling(spo_list=spo_list, text=text) else:",
"encoding='utf-8') as f: count_numbers = 0 while True: line =",
"encoding='utf-8') self.bert_tokener_error_log_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"bert_tokener_error_log.txt\"), \"w\", encoding='utf-8') self.text_f =",
"初始化 bert_token 工具 self.DATA_INPUT_DIR = self.get_data_input_dir(DATA_INPUT_DIR) self.DATA_OUTPUT_DIR = os.path.join(os.path.dirname(__file__), DATA_OUTPUT_DIR)",
"'国', '人', '口', '学', '会', '成', '立'] so_tokened 无法在 text_tokened",
"\" + str(text_tokened) + \"\\n\") else: #给实体开始处标 B 其它位置标 I",
"+ str(text_tokened) + \"\\n\") else: #给实体开始处标 B 其它位置标 I labeling_list[idx_start]",
"\"sequence_labeling_data\" Vocab_Path = config.bert_vocab_dir General_Mode = False model_data = Model_data_preparation(General_Mode",
"in k_list, find index(first time) of q_list in k_list\"\"\" q_list_length",
"= _gen_event_dic(spo_list) for predicate, spo_list_form in spo_predicate_dict.items(): tokener_error_flag = False",
"self.General_Mode: spo_predicate_dict = _spo_list_to_spo_predicate_dict(spo_list) else: spo_predicate_dict = _gen_event_dic(spo_list) for predicate,",
"self.token_in_not_UNK_f.close() self.token_label_and_one_prdicate_out_f.close() self.bert_tokener_error_log_f.close() if __name__==\"__main__\": DATA_INPUT_DIR = config.data_dir DATA_OUTPUT_DIR =",
"= True else: for item in spo_list_form: if item[1]== None:",
"\"w\", encoding='utf-8') self.bert_tokener_error_log_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"bert_tokener_error_log.txt\"), \"w\", encoding='utf-8') self.text_f",
"text + \"\\n\") self.bert_tokener_error_log_f.write(str(so_tokened) + \" @@ \" + str(text_tokened)",
"in spo_list_form: flag_A = _labeling_type(spo_subject, \"SUB\") #flag_B = _labeling_type(spo_object, \"OBJ\")",
"so_type if so_tokened_length == 2: labeling_list[idx_start + 1] = \"I-\"",
"len(text_tokened) if not self.General_Mode: for (spo_subject, spo_object) in spo_list_form: flag_A",
"\"SUB\") #flag_B = _labeling_type(spo_object, \"OBJ\") if flag_A or flag_B: tokener_error_flag",
"subject = spo_item[\"subject\"] object = spo_item[\"object\"] spo_predicate_dict.setdefault(predicate, []).append((subject, object)) return",
"spo_predicate_dict def _gen_event_dic(spo_list): res = [] res_d = {} predicate",
"= open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"token_in_not_UNK.txt\"), \"w\", encoding='utf-8') if file_set_type == \"train\":",
"\"valid\")) os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, \"test\")) for file_set_type in [\"train\", \"valid\"]: print(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type)))",
"line: count_numbers += 1 r = json.loads(line) text = r[\"text\"]",
"DATA_INPUT_DIR = config.data_dir DATA_OUTPUT_DIR = \"sequence_labeling_data\" Vocab_Path = config.bert_vocab_dir General_Mode",
"class Model_data_preparation(object): def __init__(self, DATA_INPUT_DIR=\"raw_data\", DATA_OUTPUT_DIR=\"SKE_2019_tokened_labeling\", vocab_file_path=\"vocab.txt\", do_lower_case=True,General_Mode = False):",
"k in zip(q_list, k_list[idx: idx + q_list_length])] # print(idx, t)",
"\"w\", encoding='utf-8') self.text_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"text.txt\"), \"w\", encoding='utf-8') self.token_in_f",
"idx_start = idx return idx_start def _labeling_type(subject_object, so_type): tokener_error_flag =",
"self.token_in_not_UNK_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"token_in_not_UNK.txt\"), \"w\", encoding='utf-8') if file_set_type ==",
"while True: line = f.readline() if line: count_numbers += 1",
"file_set_type), \"token_label_and_one_prdicate_out.txt\"), \"w\", encoding='utf-8') self.bert_tokener_error_log_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"bert_tokener_error_log.txt\"), \"w\",",
"self.text_f.write(text + \"\\n\") self.token_in_f.write(\" \".join(text_tokened)+\"\\t\"+predicate+\"\\n\") self.token_in_not_UNK_f.write(\" \".join(text_tokened_not_UNK) + \"\\n\") def",
"res_d = {} predicate = \"\" for spo_item in spo_list:",
"import json sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../bert\"))) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../\"))) import tokenization from config",
"DATA_OUTPUT_DIR = \"sequence_labeling_data\" Vocab_Path = config.bert_vocab_dir General_Mode = False model_data",
"\"w\", encoding='utf-8') if file_set_type == \"train\": path_to_raw_data_file = \"train.json\" elif",
"spo_item[\"denoter\"] res.append(('denoter',denoter)) if 'object' in spo_item: object = spo_item[\"object\"] res.append(('object',object))",
"sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../bert\"))) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../\"))) import tokenization from config import config",
"\"../../\"))) import tokenization from config import config class Model_data_preparation(object): def",
"res.append(('location',location)) if 'participant' in spo_item: participant = spo_item[\"participant\"] res.append(('participant',participant)) if",
"spo_item: object = spo_item[\"object\"] res.append(('object',object)) res_d[predicate] = res return res_d",
"spo_predicate_dict.setdefault(predicate, []).append((subject, object)) return spo_predicate_dict def _gen_event_dic(spo_list): res = []",
"'会', '成', '立'] so_tokened 无法在 text_tokened 找到!原因是bert_tokenizer.tokenize 分词增添 “##” 所致!",
"+ \"\\n\") def separate_raw_data_and_token_labeling(self): if not os.path.exists(self.DATA_OUTPUT_DIR): os.makedirs(os.path.join(self.DATA_OUTPUT_DIR, \"train\")) os.makedirs(os.path.join(self.DATA_OUTPUT_DIR,",
"#给实体开始处标 B 其它位置标 I labeling_list[idx_start] = \"B-\" + so_type if",
"= spo_item[\"location\"] res.append(('location',location)) if 'participant' in spo_item: participant = spo_item[\"participant\"]",
"for idx in range(k_list_length - q_list_length + 1): t =",
"True else: for item in spo_list_form: if item[1]== None: continue",
"q_list_length + 1): t = [q == k for q,",
"so_type elif so_tokened_length >= 3: labeling_list[idx_start + 1: idx_start +",
"not self.General_Mode: spo_predicate_dict = _spo_list_to_spo_predicate_dict(spo_list) else: spo_predicate_dict = _gen_event_dic(spo_list) for",
"for item in spo_list_form: if item[1]== None: continue flag_A =",
"vocab_file_path def subject_object_labeling(self, spo_list, text): def _spo_list_to_spo_predicate_dict(spo_list): spo_predicate_dict = dict()",
"\"../../\")), DATA_INPUT_DIR) return DATA_INPUT_DIR def get_vocab_file_path(self, vocab_file_path): print(vocab_file_path) return vocab_file_path",
"None: tokener_error_flag = True ''' 实体: \"1981年\" 原句: \"●1981年2月27日,中国人口学会成立\" so_tokened",
"\"train\": path_to_raw_data_file = \"train.json\" elif file_set_type == \"valid\": path_to_raw_data_file =",
"= \"\" for spo_item in spo_list: predicate = spo_item[\"event\"] if",
"json sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../bert\"))) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../\"))) import tokenization from config import",
"= r[\"text\"] spo_list = r[\"spo_list\"] self.subject_object_labeling(spo_list=spo_list, text=text) else: break print(\"all",
"\"\\n\") self.token_in_f.write(\" \".join(text_tokened)+\"\\t\"+predicate+\"\\n\") self.token_in_not_UNK_f.write(\" \".join(text_tokened_not_UNK) + \"\\n\") def separate_raw_data_and_token_labeling(self): if",
"k_list\"\"\" q_list_length = len(q_list) k_list_length = len(k_list) for idx in",
"q, k in zip(q_list, k_list[idx: idx + q_list_length])] # print(idx,",
"spo_item in spo_list: predicate = spo_item[\"predicate\"] subject = spo_item[\"subject\"] object",
"enumerate(text_tokened): \"\"\"标注被 bert_tokenizer.tokenize 拆分的词语\"\"\" if token.startswith(\"##\"): labeling_list[idx] = \"[##WordPiece]\" if",
"def __init__(self, DATA_INPUT_DIR=\"raw_data\", DATA_OUTPUT_DIR=\"SKE_2019_tokened_labeling\", vocab_file_path=\"vocab.txt\", do_lower_case=True,General_Mode = False): self.bert_tokenizer =",
"idx_start def _labeling_type(subject_object, so_type): tokener_error_flag = False so_tokened = self.bert_tokenizer.tokenize(subject_object)",
"so_tokened 无法在 text_tokened 找到!原因是bert_tokenizer.tokenize 分词增添 “##” 所致! ''' self.bert_tokener_error_log_f.write(subject_object +",
"if not self.General_Mode: for (spo_subject, spo_object) in spo_list_form: flag_A =",
"vocab_file_path): print(vocab_file_path) return vocab_file_path def subject_object_labeling(self, spo_list, text): def _spo_list_to_spo_predicate_dict(spo_list):",
"in spo_item: denoter = spo_item[\"denoter\"] res.append(('denoter',denoter)) if 'object' in spo_item:",
"of q_list in k_list\"\"\" q_list_length = len(q_list) k_list_length = len(k_list)",
"= json.loads(line) text = r[\"text\"] spo_list = r[\"spo_list\"] self.subject_object_labeling(spo_list=spo_list, text=text)",
"= \"B-\" + so_type if so_tokened_length == 2: labeling_list[idx_start +",
"file_set_type), \"text.txt\"), \"w\", encoding='utf-8') self.token_in_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"token_in.txt\"), \"w\",",
"spo_predicate_dict = dict() for spo_item in spo_list: predicate = spo_item[\"predicate\"]",
"path_to_raw_data_file = \"valid.json\" else: pass with open(os.path.join(self.DATA_INPUT_DIR, path_to_raw_data_file), 'r', encoding='utf-8')",
"import tokenization from config import config class Model_data_preparation(object): def __init__(self,",
"[\"train\", \"valid\"]: print(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type))) self.token_label_and_one_prdicate_out_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"token_label_and_one_prdicate_out.txt\"), \"w\",",
"= 0 while True: line = f.readline() if line: count_numbers",
"text_tokened 找到!原因是bert_tokenizer.tokenize 分词增添 “##” 所致! ''' self.bert_tokener_error_log_f.write(subject_object + \" @@",
"= _labeling_type(item[1],item[0]) if flag_A: tokener_error_flag = True #给被bert_tokenizer.tokenize 拆分的词语打上特殊标签[##WordPiece] for",
"DATA_OUTPUT_DIR=\"SKE_2019_tokened_labeling\", vocab_file_path=\"vocab.txt\", do_lower_case=True,General_Mode = False): self.bert_tokenizer = tokenization.FullTokenizer(vocab_file=self.get_vocab_file_path(vocab_file_path), do_lower_case=do_lower_case) #",
"\"valid\"]: print(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type))) self.token_label_and_one_prdicate_out_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"token_label_and_one_prdicate_out.txt\"), \"w\", encoding='utf-8')",
"0 while True: line = f.readline() if line: count_numbers +=",
"self.bert_tokenizer.tokenize(subject_object) so_tokened_length = len(so_tokened) idx_start = _index_q_list_in_k_list(q_list=so_tokened, k_list=text_tokened) if idx_start",
"token.startswith(\"##\"): labeling_list[idx] = \"[##WordPiece]\" if not tokener_error_flag: self.token_label_and_one_prdicate_out_f.write(\" \".join(labeling_list)+\"\\t\"+predicate+\"\\n\") self.text_f.write(text",
"open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"bert_tokener_error_log.txt\"), \"w\", encoding='utf-8') self.text_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"text.txt\"),",
"res.append(('time',time)) if 'location' in spo_item: location = spo_item[\"location\"] res.append(('location',location)) if",
"spo_item[\"location\"] res.append(('location',location)) if 'participant' in spo_item: participant = spo_item[\"participant\"] res.append(('participant',participant))",
"= spo_item[\"object\"] res.append(('object',object)) res_d[predicate] = res return res_d def _index_q_list_in_k_list(q_list,",
"- q_list_length + 1): t = [q == k for",
"'口', '学', '会', '成', '立'] so_tokened 无法在 text_tokened 找到!原因是bert_tokenizer.tokenize 分词增添",
"token in enumerate(text_tokened): \"\"\"标注被 bert_tokenizer.tokenize 拆分的词语\"\"\" if token.startswith(\"##\"): labeling_list[idx] =",
"item in spo_list_form: if item[1]== None: continue flag_A = _labeling_type(item[1],item[0])",
"config class Model_data_preparation(object): def __init__(self, DATA_INPUT_DIR=\"raw_data\", DATA_OUTPUT_DIR=\"SKE_2019_tokened_labeling\", vocab_file_path=\"vocab.txt\", do_lower_case=True,General_Mode =",
"1: idx_start + so_tokened_length] = [\"I-\" + so_type] * (so_tokened_length",
"tokener_error_flag = False so_tokened = self.bert_tokenizer.tokenize(subject_object) so_tokened_length = len(so_tokened) idx_start",
"Model_data_preparation(object): def __init__(self, DATA_INPUT_DIR=\"raw_data\", DATA_OUTPUT_DIR=\"SKE_2019_tokened_labeling\", vocab_file_path=\"vocab.txt\", do_lower_case=True,General_Mode = False): self.bert_tokenizer",
"tokener_error_flag = True #给被bert_tokenizer.tokenize 拆分的词语打上特殊标签[##WordPiece] for idx, token in enumerate(text_tokened):",
"print(vocab_file_path) return vocab_file_path def subject_object_labeling(self, spo_list, text): def _spo_list_to_spo_predicate_dict(spo_list): spo_predicate_dict",
"in range(k_list_length - q_list_length + 1): t = [q ==",
"encoding='utf-8') if file_set_type == \"train\": path_to_raw_data_file = \"train.json\" elif file_set_type",
"= False): self.bert_tokenizer = tokenization.FullTokenizer(vocab_file=self.get_vocab_file_path(vocab_file_path), do_lower_case=do_lower_case) # 初始化 bert_token 工具",
"= open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"token_label_and_one_prdicate_out.txt\"), \"w\", encoding='utf-8') self.bert_tokener_error_log_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type),",
"print(\"all numbers\", count_numbers) self.text_f.close() self.token_in_f.close() self.token_in_not_UNK_f.close() self.token_label_and_one_prdicate_out_f.close() self.bert_tokener_error_log_f.close() if __name__==\"__main__\":",
"\"token_label_and_one_prdicate_out.txt\"), \"w\", encoding='utf-8') self.bert_tokener_error_log_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"bert_tokener_error_log.txt\"), \"w\", encoding='utf-8')",
"True: line = f.readline() if line: count_numbers += 1 r",
"(so_tokened_length - 1) return tokener_error_flag text_tokened = self.bert_tokenizer.tokenize(text) text_tokened_not_UNK =",
"(spo_subject, spo_object) in spo_list_form: flag_A = _labeling_type(spo_subject, \"SUB\") #flag_B =",
"General_Mode def get_data_input_dir(self, DATA_INPUT_DIR): DATAself_INPUT_DIR = os.path.join( os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../\")), DATA_INPUT_DIR)",
"'object' in spo_item: object = spo_item[\"object\"] res.append(('object',object)) res_d[predicate] = res",
"{} predicate = \"\" for spo_item in spo_list: predicate =",
"所致! ''' self.bert_tokener_error_log_f.write(subject_object + \" @@ \" + text +",
"for predicate, spo_list_form in spo_predicate_dict.items(): tokener_error_flag = False labeling_list =",
"if 'time' in spo_item: time = spo_item[\"time\"] res.append(('time',time)) if 'location'",
"+ 1] = \"I-\" + so_type elif so_tokened_length >= 3:",
"bert_tokenizer.tokenize 拆分的词语\"\"\" if token.startswith(\"##\"): labeling_list[idx] = \"[##WordPiece]\" if not tokener_error_flag:",
"= General_Mode def get_data_input_dir(self, DATA_INPUT_DIR): DATAself_INPUT_DIR = os.path.join( os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../\")),",
"return res_d def _index_q_list_in_k_list(q_list, k_list): \"\"\"Known q_list in k_list, find",
"\" @@ \" + text + \"\\n\") self.bert_tokener_error_log_f.write(str(so_tokened) + \"",
"= spo_item[\"predicate\"] subject = spo_item[\"subject\"] object = spo_item[\"object\"] spo_predicate_dict.setdefault(predicate, []).append((subject,",
"labeling_list[idx_start + 1] = \"I-\" + so_type elif so_tokened_length >=",
"self.token_in_f.close() self.token_in_not_UNK_f.close() self.token_label_and_one_prdicate_out_f.close() self.bert_tokener_error_log_f.close() if __name__==\"__main__\": DATA_INPUT_DIR = config.data_dir DATA_OUTPUT_DIR",
"实体: \"1981年\" 原句: \"●1981年2月27日,中国人口学会成立\" so_tokened ['1981', '年'] text_tokened ['●', '##19',",
"if not tokener_error_flag: self.token_label_and_one_prdicate_out_f.write(\" \".join(labeling_list)+\"\\t\"+predicate+\"\\n\") self.text_f.write(text + \"\\n\") self.token_in_f.write(\" \".join(text_tokened)+\"\\t\"+predicate+\"\\n\")",
"== \"valid\": path_to_raw_data_file = \"valid.json\" else: pass with open(os.path.join(self.DATA_INPUT_DIR, path_to_raw_data_file),",
"res_d def _index_q_list_in_k_list(q_list, k_list): \"\"\"Known q_list in k_list, find index(first",
"“##” 所致! ''' self.bert_tokener_error_log_f.write(subject_object + \" @@ \" + text",
"spo_item: participant = spo_item[\"participant\"] res.append(('participant',participant)) if 'denoter' in spo_item: denoter",
"print(idx) idx_start = idx return idx_start def _labeling_type(subject_object, so_type): tokener_error_flag",
"= \"I-\" + so_type elif so_tokened_length >= 3: labeling_list[idx_start +",
"#给被bert_tokenizer.tokenize 拆分的词语打上特殊标签[##WordPiece] for idx, token in enumerate(text_tokened): \"\"\"标注被 bert_tokenizer.tokenize 拆分的词语\"\"\"",
"q_list in k_list, find index(first time) of q_list in k_list\"\"\"",
"= self.bert_tokenizer.tokenize(subject_object) so_tokened_length = len(so_tokened) idx_start = _index_q_list_in_k_list(q_list=so_tokened, k_list=text_tokened) if",
"'##81', '年', '2', '月', '27', '日', ',', '中', '国', '人',",
"[\"O\"] * len(text_tokened) if not self.General_Mode: for (spo_subject, spo_object) in",
"open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"token_in_not_UNK.txt\"), \"w\", encoding='utf-8') if file_set_type == \"train\": path_to_raw_data_file",
"\"valid.json\" else: pass with open(os.path.join(self.DATA_INPUT_DIR, path_to_raw_data_file), 'r', encoding='utf-8') as f:",
"拆分的词语\"\"\" if token.startswith(\"##\"): labeling_list[idx] = \"[##WordPiece]\" if not tokener_error_flag: self.token_label_and_one_prdicate_out_f.write(\"",
"DATA_INPUT_DIR): DATAself_INPUT_DIR = os.path.join( os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../\")), DATA_INPUT_DIR) return DATA_INPUT_DIR def",
"= \"valid.json\" else: pass with open(os.path.join(self.DATA_INPUT_DIR, path_to_raw_data_file), 'r', encoding='utf-8') as",
"_labeling_type(subject_object, so_type): tokener_error_flag = False so_tokened = self.bert_tokenizer.tokenize(subject_object) so_tokened_length =",
"spo_list_form: if item[1]== None: continue flag_A = _labeling_type(item[1],item[0]) if flag_A:",
"r = json.loads(line) text = r[\"text\"] spo_list = r[\"spo_list\"] self.subject_object_labeling(spo_list=spo_list,",
"= r[\"spo_list\"] self.subject_object_labeling(spo_list=spo_list, text=text) else: break print(\"all numbers\", count_numbers) self.text_f.close()",
"= res return res_d def _index_q_list_in_k_list(q_list, k_list): \"\"\"Known q_list in",
"\"B-\" + so_type if so_tokened_length == 2: labeling_list[idx_start + 1]",
"spo_list_form in spo_predicate_dict.items(): tokener_error_flag = False labeling_list = [\"O\"] *",
"break print(\"all numbers\", count_numbers) self.text_f.close() self.token_in_f.close() self.token_in_not_UNK_f.close() self.token_label_and_one_prdicate_out_f.close() self.bert_tokener_error_log_f.close() if",
"\"../../bert\"))) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../\"))) import tokenization from config import config class",
"General_Mode = False model_data = Model_data_preparation(General_Mode = General_Mode,DATA_INPUT_DIR=DATA_INPUT_DIR, DATA_OUTPUT_DIR=DATA_OUTPUT_DIR,vocab_file_path=Vocab_Path) model_data.separate_raw_data_and_token_labeling()",
"encoding='utf-8') self.token_in_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"token_in.txt\"), \"w\", encoding='utf-8') self.token_in_not_UNK_f =",
"B 其它位置标 I labeling_list[idx_start] = \"B-\" + so_type if so_tokened_length",
"None: continue flag_A = _labeling_type(item[1],item[0]) if flag_A: tokener_error_flag = True",
"def get_vocab_file_path(self, vocab_file_path): print(vocab_file_path) return vocab_file_path def subject_object_labeling(self, spo_list, text):",
"is None: tokener_error_flag = True ''' 实体: \"1981年\" 原句: \"●1981年2月27日,中国人口学会成立\"",
"flag_A = _labeling_type(item[1],item[0]) if flag_A: tokener_error_flag = True #给被bert_tokenizer.tokenize 拆分的词语打上特殊标签[##WordPiece]",
"file_set_type), \"token_in.txt\"), \"w\", encoding='utf-8') self.token_in_not_UNK_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"token_in_not_UNK.txt\"), \"w\",",
"[] res_d = {} predicate = \"\" for spo_item in",
"tokener_error_flag = True else: for item in spo_list_form: if item[1]==",
"[]).append((subject, object)) return spo_predicate_dict def _gen_event_dic(spo_list): res = [] res_d",
"self.token_label_and_one_prdicate_out_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"token_label_and_one_prdicate_out.txt\"), \"w\", encoding='utf-8') self.bert_tokener_error_log_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR,",
"= self.bert_tokenizer.tokenize_not_UNK(text) if not self.General_Mode: spo_predicate_dict = _spo_list_to_spo_predicate_dict(spo_list) else: spo_predicate_dict",
"\"train.json\" elif file_set_type == \"valid\": path_to_raw_data_file = \"valid.json\" else: pass",
"= dict() for spo_item in spo_list: predicate = spo_item[\"predicate\"] subject",
"_labeling_type(spo_subject, \"SUB\") #flag_B = _labeling_type(spo_object, \"OBJ\") if flag_A or flag_B:",
"predicate = \"\" for spo_item in spo_list: predicate = spo_item[\"event\"]",
"return spo_predicate_dict def _gen_event_dic(spo_list): res = [] res_d = {}",
"* (so_tokened_length - 1) return tokener_error_flag text_tokened = self.bert_tokenizer.tokenize(text) text_tokened_not_UNK",
"spo_item in spo_list: predicate = spo_item[\"event\"] if 'time' in spo_item:",
"self.token_in_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"token_in.txt\"), \"w\", encoding='utf-8') self.token_in_not_UNK_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR,",
"+ q_list_length])] # print(idx, t) if all(t): # print(idx) idx_start",
"res return res_d def _index_q_list_in_k_list(q_list, k_list): \"\"\"Known q_list in k_list,",
"1): t = [q == k for q, k in",
"DATA_INPUT_DIR def get_vocab_file_path(self, vocab_file_path): print(vocab_file_path) return vocab_file_path def subject_object_labeling(self, spo_list,",
"\"\"\"标注被 bert_tokenizer.tokenize 拆分的词语\"\"\" if token.startswith(\"##\"): labeling_list[idx] = \"[##WordPiece]\" if not",
"if 'location' in spo_item: location = spo_item[\"location\"] res.append(('location',location)) if 'participant'",
"False so_tokened = self.bert_tokenizer.tokenize(subject_object) so_tokened_length = len(so_tokened) idx_start = _index_q_list_in_k_list(q_list=so_tokened,",
"spo_item: location = spo_item[\"location\"] res.append(('location',location)) if 'participant' in spo_item: participant",
"spo_item[\"object\"] spo_predicate_dict.setdefault(predicate, []).append((subject, object)) return spo_predicate_dict def _gen_event_dic(spo_list): res =",
"spo_object) in spo_list_form: flag_A = _labeling_type(spo_subject, \"SUB\") #flag_B = _labeling_type(spo_object,",
"+ \" @@ \" + text + \"\\n\") self.bert_tokener_error_log_f.write(str(so_tokened) +",
"\"token_in.txt\"), \"w\", encoding='utf-8') self.token_in_not_UNK_f = open(os.path.join(os.path.join(self.DATA_OUTPUT_DIR, file_set_type), \"token_in_not_UNK.txt\"), \"w\", encoding='utf-8')",
"path_to_raw_data_file), 'r', encoding='utf-8') as f: count_numbers = 0 while True:",
"do_lower_case=True,General_Mode = False): self.bert_tokenizer = tokenization.FullTokenizer(vocab_file=self.get_vocab_file_path(vocab_file_path), do_lower_case=do_lower_case) # 初始化 bert_token",
"spo_item: time = spo_item[\"time\"] res.append(('time',time)) if 'location' in spo_item: location",
"tokener_error_flag = False labeling_list = [\"O\"] * len(text_tokened) if not",
"[q == k for q, k in zip(q_list, k_list[idx: idx",
"tokener_error_flag: self.token_label_and_one_prdicate_out_f.write(\" \".join(labeling_list)+\"\\t\"+predicate+\"\\n\") self.text_f.write(text + \"\\n\") self.token_in_f.write(\" \".join(text_tokened)+\"\\t\"+predicate+\"\\n\") self.token_in_not_UNK_f.write(\" \".join(text_tokened_not_UNK)",
"= config.data_dir DATA_OUTPUT_DIR = \"sequence_labeling_data\" Vocab_Path = config.bert_vocab_dir General_Mode ="
] |
[
"{} else: json_object = self._ValueMessageToJsonObject(fields[key]) ret[key] = json_object return ret",
"field.containing_oneof): continue if self.preserving_proto_field_name: name = field.name else: name =",
"continue if self.preserving_proto_field_name: name = field.name else: name = field.json_name",
"_IsMapEntry(field): js[name] = {} elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED: js[name] =",
"import Message # noqa from clarifai.rest.grpc.proto.clarifai.api.utils import extensions_pb2 def protobuf_to_dict(object_protobuf,",
"However, by default, empty objects {} get converted to null.",
"-> dict # printer = _CustomPrinter( printer = _CustomPrinter( including_default_value_fields=False,",
"Converts Struct message according to Proto3 JSON Specification. However, by",
"def __init__(self, including_default_value_fields, preserving_proto_field_name, use_integers_for_enums, ignore_show_empty): super(_CustomPrinter, self).__init__(including_default_value_fields, preserving_proto_field_name, use_integers_for_enums)",
"= message.DESCRIPTOR for field in message_descriptor.fields: if (self._ignore_show_empty and not",
"use_integers_for_enums) self._ignore_show_empty = ignore_show_empty def _RegularMessageToJsonObject(self, message, js): \"\"\" Because",
"as I know this is the only case this condition",
"if ((field.label != descriptor.FieldDescriptor.LABEL_REPEATED and field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE) or field.containing_oneof):",
"{} elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED: js[name] = [] else: js[name]",
"know this is the only case this condition will be",
"self).__init__(including_default_value_fields, preserving_proto_field_name, use_integers_for_enums) self._ignore_show_empty = ignore_show_empty def _RegularMessageToJsonObject(self, message, js):",
"the only case this condition will be true. If not,",
"the custom extension `cl_show_if_empty`, we need to adjust the original's",
"I know this is the only case this condition will",
"if fields[key].WhichOneof('kind') is None: json_object = {} else: json_object =",
"condition will hold True. # Far as I know this",
"we need to adjust the original's method's return JSON object",
"needs to be amended. if fields[key].WhichOneof('kind') is None: json_object =",
"js[name] = [] else: js[name] = self._FieldToJsonObject(field, field.default_value) return js",
"{} get converted to {}. \"\"\" fields = message.fields ret",
"= [] else: js[name] = self._FieldToJsonObject(field, field.default_value) return js def",
"with an empty Struct field, this condition will hold True.",
"field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE) or field.containing_oneof): continue if self.preserving_proto_field_name: name =",
"be affected. if ((field.label != descriptor.FieldDescriptor.LABEL_REPEATED and field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE)",
"including_default_value_fields=False, preserving_proto_field_name=True, use_integers_for_enums=use_integers_for_enums, ignore_show_empty=ignore_show_empty) # pylint: disable=protected-access return printer._MessageToJsonObject(object_protobuf) class",
"# printer = _CustomPrinter( printer = _CustomPrinter( including_default_value_fields=False, preserving_proto_field_name=True, use_integers_for_enums=use_integers_for_enums,",
"{} get converted to null. We overwrite this behavior so",
"to Proto3 JSON Specification. However, by default, empty objects {}",
"= field.json_name if name in js: # Skip the field",
"message_descriptor = message.DESCRIPTOR for field in message_descriptor.fields: if (self._ignore_show_empty and",
"= {} elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED: js[name] = [] else:",
"these fields. \"\"\" js = super(_CustomPrinter, self)._RegularMessageToJsonObject(message, js) message_descriptor =",
"\"\"\" Converts Struct message according to Proto3 JSON Specification. However,",
"by default, empty objects {} get converted to null. We",
"def _RegularMessageToJsonObject(self, message, js): \"\"\" Because of the fields with",
"preserving_proto_field_name, use_integers_for_enums) self._ignore_show_empty = ignore_show_empty def _RegularMessageToJsonObject(self, message, js): \"\"\"",
"original's method's return JSON object and keep these fields. \"\"\"",
"True. # Far as I know this is the only",
"Skip the field which has been serialized already. continue if",
"super(_CustomPrinter, self)._RegularMessageToJsonObject(message, js) message_descriptor = message.DESCRIPTOR for field in message_descriptor.fields:",
"fields will not be affected. if ((field.label != descriptor.FieldDescriptor.LABEL_REPEATED and",
"overwrite this behavior so {} get converted to {}. \"\"\"",
"from google.protobuf.json_format import _IsMapEntry, _Printer from google.protobuf.message import Message #",
"message_descriptor.fields: if (self._ignore_show_empty and not field.GetOptions().Extensions[extensions_pb2.cl_default_float]): continue if not field.GetOptions().Extensions[extensions_pb2.cl_show_if_empty]:",
"_CustomPrinter( including_default_value_fields=False, preserving_proto_field_name=True, use_integers_for_enums=use_integers_for_enums, ignore_show_empty=ignore_show_empty) # pylint: disable=protected-access return printer._MessageToJsonObject(object_protobuf)",
"name = field.json_name if name in js: # Skip the",
"will not be affected. if ((field.label != descriptor.FieldDescriptor.LABEL_REPEATED and field.cpp_type",
"json_object = {} else: json_object = self._ValueMessageToJsonObject(fields[key]) ret[key] = json_object",
"disable=protected-access return printer._MessageToJsonObject(object_protobuf) class _CustomPrinter(_Printer): def __init__(self, including_default_value_fields, preserving_proto_field_name, use_integers_for_enums,",
"(self._ignore_show_empty and not field.GetOptions().Extensions[extensions_pb2.cl_default_float]): continue if not field.GetOptions().Extensions[extensions_pb2.cl_show_if_empty]: continue #",
"and field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE) or field.containing_oneof): continue if self.preserving_proto_field_name: name",
"= message.fields ret = {} for key in fields: #",
"from google.protobuf import descriptor from google.protobuf.json_format import _IsMapEntry, _Printer from",
"= self._FieldToJsonObject(field, field.default_value) return js def _StructMessageToJsonObject(self, message): \"\"\" Converts",
"Struct message according to Proto3 JSON Specification. However, by default,",
"\"\"\" js = super(_CustomPrinter, self)._RegularMessageToJsonObject(message, js) message_descriptor = message.DESCRIPTOR for",
"custom extension `cl_show_if_empty`, we need to adjust the original's method's",
"empty Struct field, this condition will hold True. # Far",
"to be amended. if fields[key].WhichOneof('kind') is None: json_object = {}",
"fields with the custom extension `cl_show_if_empty`, we need to adjust",
"name in js: # Skip the field which has been",
"and oneof fields will not be affected. if ((field.label !=",
"message.fields ret = {} for key in fields: # When",
"preserving_proto_field_name, use_integers_for_enums, ignore_show_empty): super(_CustomPrinter, self).__init__(including_default_value_fields, preserving_proto_field_name, use_integers_for_enums) self._ignore_show_empty = ignore_show_empty",
"# pylint: disable=protected-access return printer._MessageToJsonObject(object_protobuf) class _CustomPrinter(_Printer): def __init__(self, including_default_value_fields,",
"name = field.name else: name = field.json_name if name in",
"pylint: disable=protected-access return printer._MessageToJsonObject(object_protobuf) class _CustomPrinter(_Printer): def __init__(self, including_default_value_fields, preserving_proto_field_name,",
"use_integers_for_enums=True, ignore_show_empty=False): # type: (Message, typing.Optional[bool], typing.Optional[bool]) -> dict #",
"fields. \"\"\" js = super(_CustomPrinter, self)._RegularMessageToJsonObject(message, js) message_descriptor = message.DESCRIPTOR",
"empty objects {} get converted to null. We overwrite this",
"_StructMessageToJsonObject(self, message): \"\"\" Converts Struct message according to Proto3 JSON",
"for field in message_descriptor.fields: if (self._ignore_show_empty and not field.GetOptions().Extensions[extensions_pb2.cl_default_float]): continue",
"def protobuf_to_dict(object_protobuf, use_integers_for_enums=True, ignore_show_empty=False): # type: (Message, typing.Optional[bool], typing.Optional[bool]) ->",
"_CustomPrinter(_Printer): def __init__(self, including_default_value_fields, preserving_proto_field_name, use_integers_for_enums, ignore_show_empty): super(_CustomPrinter, self).__init__(including_default_value_fields, preserving_proto_field_name,",
"return printer._MessageToJsonObject(object_protobuf) class _CustomPrinter(_Printer): def __init__(self, including_default_value_fields, preserving_proto_field_name, use_integers_for_enums, ignore_show_empty):",
"been serialized already. continue if _IsMapEntry(field): js[name] = {} elif",
"super(_CustomPrinter, self).__init__(including_default_value_fields, preserving_proto_field_name, use_integers_for_enums) self._ignore_show_empty = ignore_show_empty def _RegularMessageToJsonObject(self, message,",
"_RegularMessageToJsonObject(self, message, js): \"\"\" Because of the fields with the",
"this condition will hold True. # Far as I know",
"js = super(_CustomPrinter, self)._RegularMessageToJsonObject(message, js) message_descriptor = message.DESCRIPTOR for field",
"js[name] = self._FieldToJsonObject(field, field.default_value) return js def _StructMessageToJsonObject(self, message): \"\"\"",
"continue # Singular message fields and oneof fields will not",
"behavior so {} get converted to {}. \"\"\" fields =",
"self._ignore_show_empty = ignore_show_empty def _RegularMessageToJsonObject(self, message, js): \"\"\" Because of",
"Singular message fields and oneof fields will not be affected.",
"preserving_proto_field_name=True, use_integers_for_enums=use_integers_for_enums, ignore_show_empty=ignore_show_empty) # pylint: disable=protected-access return printer._MessageToJsonObject(object_protobuf) class _CustomPrinter(_Printer):",
"When there's a Struct with an empty Struct field, this",
"adjust the original's method's return JSON object and keep these",
"= {} else: json_object = self._ValueMessageToJsonObject(fields[key]) ret[key] = json_object return",
"== descriptor.FieldDescriptor.CPPTYPE_MESSAGE) or field.containing_oneof): continue if self.preserving_proto_field_name: name = field.name",
"not field.GetOptions().Extensions[extensions_pb2.cl_show_if_empty]: continue # Singular message fields and oneof fields",
"message according to Proto3 JSON Specification. However, by default, empty",
"Because of the fields with the custom extension `cl_show_if_empty`, we",
"return JSON object and keep these fields. \"\"\" js =",
"the original's method's return JSON object and keep these fields.",
"JSON object and keep these fields. \"\"\" js = super(_CustomPrinter,",
"be amended. if fields[key].WhichOneof('kind') is None: json_object = {} else:",
"field which has been serialized already. continue if _IsMapEntry(field): js[name]",
"has been serialized already. continue if _IsMapEntry(field): js[name] = {}",
"not, this condition # needs to be amended. if fields[key].WhichOneof('kind')",
"if name in js: # Skip the field which has",
"continue if not field.GetOptions().Extensions[extensions_pb2.cl_show_if_empty]: continue # Singular message fields and",
"field.name else: name = field.json_name if name in js: #",
"fields and oneof fields will not be affected. if ((field.label",
"amended. if fields[key].WhichOneof('kind') is None: json_object = {} else: json_object",
"method's return JSON object and keep these fields. \"\"\" js",
"the field which has been serialized already. continue if _IsMapEntry(field):",
"class _CustomPrinter(_Printer): def __init__(self, including_default_value_fields, preserving_proto_field_name, use_integers_for_enums, ignore_show_empty): super(_CustomPrinter, self).__init__(including_default_value_fields,",
"message, js): \"\"\" Because of the fields with the custom",
"\"\"\" Because of the fields with the custom extension `cl_show_if_empty`,",
"an empty Struct field, this condition will hold True. #",
"and keep these fields. \"\"\" js = super(_CustomPrinter, self)._RegularMessageToJsonObject(message, js)",
"# Skip the field which has been serialized already. continue",
"extensions_pb2 def protobuf_to_dict(object_protobuf, use_integers_for_enums=True, ignore_show_empty=False): # type: (Message, typing.Optional[bool], typing.Optional[bool])",
"# Far as I know this is the only case",
"will be true. If not, this condition # needs to",
"be true. If not, this condition # needs to be",
"If not, this condition # needs to be amended. if",
"# needs to be amended. if fields[key].WhichOneof('kind') is None: json_object",
"get converted to null. We overwrite this behavior so {}",
"import typing # noqa from google.protobuf import descriptor from google.protobuf.json_format",
"((field.label != descriptor.FieldDescriptor.LABEL_REPEATED and field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE) or field.containing_oneof): continue",
"== descriptor.FieldDescriptor.LABEL_REPEATED: js[name] = [] else: js[name] = self._FieldToJsonObject(field, field.default_value)",
"ignore_show_empty=ignore_show_empty) # pylint: disable=protected-access return printer._MessageToJsonObject(object_protobuf) class _CustomPrinter(_Printer): def __init__(self,",
"protobuf_to_dict(object_protobuf, use_integers_for_enums=True, ignore_show_empty=False): # type: (Message, typing.Optional[bool], typing.Optional[bool]) -> dict",
"if not field.GetOptions().Extensions[extensions_pb2.cl_show_if_empty]: continue # Singular message fields and oneof",
"in message_descriptor.fields: if (self._ignore_show_empty and not field.GetOptions().Extensions[extensions_pb2.cl_default_float]): continue if not",
"converted to {}. \"\"\" fields = message.fields ret = {}",
"= {} for key in fields: # When there's a",
"condition # needs to be amended. if fields[key].WhichOneof('kind') is None:",
"= ignore_show_empty def _RegularMessageToJsonObject(self, message, js): \"\"\" Because of the",
"this is the only case this condition will be true.",
"!= descriptor.FieldDescriptor.LABEL_REPEATED and field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE) or field.containing_oneof): continue if",
"_CustomPrinter( printer = _CustomPrinter( including_default_value_fields=False, preserving_proto_field_name=True, use_integers_for_enums=use_integers_for_enums, ignore_show_empty=ignore_show_empty) # pylint:",
"Struct field, this condition will hold True. # Far as",
"including_default_value_fields, preserving_proto_field_name, use_integers_for_enums, ignore_show_empty): super(_CustomPrinter, self).__init__(including_default_value_fields, preserving_proto_field_name, use_integers_for_enums) self._ignore_show_empty =",
"_Printer from google.protobuf.message import Message # noqa from clarifai.rest.grpc.proto.clarifai.api.utils import",
"printer = _CustomPrinter( including_default_value_fields=False, preserving_proto_field_name=True, use_integers_for_enums=use_integers_for_enums, ignore_show_empty=ignore_show_empty) # pylint: disable=protected-access",
"case this condition will be true. If not, this condition",
"js): \"\"\" Because of the fields with the custom extension",
"condition will be true. If not, this condition # needs",
"null. We overwrite this behavior so {} get converted to",
"noqa from google.protobuf import descriptor from google.protobuf.json_format import _IsMapEntry, _Printer",
"this condition # needs to be amended. if fields[key].WhichOneof('kind') is",
"is the only case this condition will be true. If",
"typing.Optional[bool], typing.Optional[bool]) -> dict # printer = _CustomPrinter( printer =",
"already. continue if _IsMapEntry(field): js[name] = {} elif field.label ==",
"We overwrite this behavior so {} get converted to {}.",
"else: js[name] = self._FieldToJsonObject(field, field.default_value) return js def _StructMessageToJsonObject(self, message):",
"type: (Message, typing.Optional[bool], typing.Optional[bool]) -> dict # printer = _CustomPrinter(",
"clarifai.rest.grpc.proto.clarifai.api.utils import extensions_pb2 def protobuf_to_dict(object_protobuf, use_integers_for_enums=True, ignore_show_empty=False): # type: (Message,",
"descriptor.FieldDescriptor.CPPTYPE_MESSAGE) or field.containing_oneof): continue if self.preserving_proto_field_name: name = field.name else:",
"field in message_descriptor.fields: if (self._ignore_show_empty and not field.GetOptions().Extensions[extensions_pb2.cl_default_float]): continue if",
"<reponame>Taik/clarifai-python import typing # noqa from google.protobuf import descriptor from",
"in js: # Skip the field which has been serialized",
"google.protobuf.message import Message # noqa from clarifai.rest.grpc.proto.clarifai.api.utils import extensions_pb2 def",
"ignore_show_empty def _RegularMessageToJsonObject(self, message, js): \"\"\" Because of the fields",
"field.default_value) return js def _StructMessageToJsonObject(self, message): \"\"\" Converts Struct message",
"message): \"\"\" Converts Struct message according to Proto3 JSON Specification.",
"printer._MessageToJsonObject(object_protobuf) class _CustomPrinter(_Printer): def __init__(self, including_default_value_fields, preserving_proto_field_name, use_integers_for_enums, ignore_show_empty): super(_CustomPrinter,",
"import _IsMapEntry, _Printer from google.protobuf.message import Message # noqa from",
"# noqa from google.protobuf import descriptor from google.protobuf.json_format import _IsMapEntry,",
"so {} get converted to {}. \"\"\" fields = message.fields",
"get converted to {}. \"\"\" fields = message.fields ret =",
"according to Proto3 JSON Specification. However, by default, empty objects",
"# type: (Message, typing.Optional[bool], typing.Optional[bool]) -> dict # printer =",
"fields: # When there's a Struct with an empty Struct",
"google.protobuf import descriptor from google.protobuf.json_format import _IsMapEntry, _Printer from google.protobuf.message",
"typing.Optional[bool]) -> dict # printer = _CustomPrinter( printer = _CustomPrinter(",
"this condition will be true. If not, this condition #",
"field, this condition will hold True. # Far as I",
"= field.name else: name = field.json_name if name in js:",
"printer = _CustomPrinter( printer = _CustomPrinter( including_default_value_fields=False, preserving_proto_field_name=True, use_integers_for_enums=use_integers_for_enums, ignore_show_empty=ignore_show_empty)",
"Specification. However, by default, empty objects {} get converted to",
"oneof fields will not be affected. if ((field.label != descriptor.FieldDescriptor.LABEL_REPEATED",
"elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED: js[name] = [] else: js[name] =",
"fields[key].WhichOneof('kind') is None: json_object = {} else: json_object = self._ValueMessageToJsonObject(fields[key])",
"there's a Struct with an empty Struct field, this condition",
"field.GetOptions().Extensions[extensions_pb2.cl_default_float]): continue if not field.GetOptions().Extensions[extensions_pb2.cl_show_if_empty]: continue # Singular message fields",
"and not field.GetOptions().Extensions[extensions_pb2.cl_default_float]): continue if not field.GetOptions().Extensions[extensions_pb2.cl_show_if_empty]: continue # Singular",
"js) message_descriptor = message.DESCRIPTOR for field in message_descriptor.fields: if (self._ignore_show_empty",
"`cl_show_if_empty`, we need to adjust the original's method's return JSON",
"field.label == descriptor.FieldDescriptor.LABEL_REPEATED: js[name] = [] else: js[name] = self._FieldToJsonObject(field,",
"\"\"\" fields = message.fields ret = {} for key in",
"need to adjust the original's method's return JSON object and",
"will hold True. # Far as I know this is",
"if (self._ignore_show_empty and not field.GetOptions().Extensions[extensions_pb2.cl_default_float]): continue if not field.GetOptions().Extensions[extensions_pb2.cl_show_if_empty]: continue",
"not field.GetOptions().Extensions[extensions_pb2.cl_default_float]): continue if not field.GetOptions().Extensions[extensions_pb2.cl_show_if_empty]: continue # Singular message",
"hold True. # Far as I know this is the",
"Proto3 JSON Specification. However, by default, empty objects {} get",
"import extensions_pb2 def protobuf_to_dict(object_protobuf, use_integers_for_enums=True, ignore_show_empty=False): # type: (Message, typing.Optional[bool],",
"of the fields with the custom extension `cl_show_if_empty`, we need",
"field.json_name if name in js: # Skip the field which",
"fields = message.fields ret = {} for key in fields:",
"field.GetOptions().Extensions[extensions_pb2.cl_show_if_empty]: continue # Singular message fields and oneof fields will",
"this behavior so {} get converted to {}. \"\"\" fields",
"only case this condition will be true. If not, this",
"message.DESCRIPTOR for field in message_descriptor.fields: if (self._ignore_show_empty and not field.GetOptions().Extensions[extensions_pb2.cl_default_float]):",
"ret = {} for key in fields: # When there's",
"the fields with the custom extension `cl_show_if_empty`, we need to",
"use_integers_for_enums=use_integers_for_enums, ignore_show_empty=ignore_show_empty) # pylint: disable=protected-access return printer._MessageToJsonObject(object_protobuf) class _CustomPrinter(_Printer): def",
"descriptor from google.protobuf.json_format import _IsMapEntry, _Printer from google.protobuf.message import Message",
"def _StructMessageToJsonObject(self, message): \"\"\" Converts Struct message according to Proto3",
"{}. \"\"\" fields = message.fields ret = {} for key",
"true. If not, this condition # needs to be amended.",
"None: json_object = {} else: json_object = self._ValueMessageToJsonObject(fields[key]) ret[key] =",
"self.preserving_proto_field_name: name = field.name else: name = field.json_name if name",
"key in fields: # When there's a Struct with an",
"= _CustomPrinter( including_default_value_fields=False, preserving_proto_field_name=True, use_integers_for_enums=use_integers_for_enums, ignore_show_empty=ignore_show_empty) # pylint: disable=protected-access return",
"typing # noqa from google.protobuf import descriptor from google.protobuf.json_format import",
"__init__(self, including_default_value_fields, preserving_proto_field_name, use_integers_for_enums, ignore_show_empty): super(_CustomPrinter, self).__init__(including_default_value_fields, preserving_proto_field_name, use_integers_for_enums) self._ignore_show_empty",
"from clarifai.rest.grpc.proto.clarifai.api.utils import extensions_pb2 def protobuf_to_dict(object_protobuf, use_integers_for_enums=True, ignore_show_empty=False): # type:",
"google.protobuf.json_format import _IsMapEntry, _Printer from google.protobuf.message import Message # noqa",
"descriptor.FieldDescriptor.LABEL_REPEATED and field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE) or field.containing_oneof): continue if self.preserving_proto_field_name:",
"objects {} get converted to null. We overwrite this behavior",
"self)._RegularMessageToJsonObject(message, js) message_descriptor = message.DESCRIPTOR for field in message_descriptor.fields: if",
"js: # Skip the field which has been serialized already.",
"# noqa from clarifai.rest.grpc.proto.clarifai.api.utils import extensions_pb2 def protobuf_to_dict(object_protobuf, use_integers_for_enums=True, ignore_show_empty=False):",
"if self.preserving_proto_field_name: name = field.name else: name = field.json_name if",
"continue if _IsMapEntry(field): js[name] = {} elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:",
"from google.protobuf.message import Message # noqa from clarifai.rest.grpc.proto.clarifai.api.utils import extensions_pb2",
"(Message, typing.Optional[bool], typing.Optional[bool]) -> dict # printer = _CustomPrinter( printer",
"message fields and oneof fields will not be affected. if",
"affected. if ((field.label != descriptor.FieldDescriptor.LABEL_REPEATED and field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE) or",
"else: name = field.json_name if name in js: # Skip",
"serialized already. continue if _IsMapEntry(field): js[name] = {} elif field.label",
"[] else: js[name] = self._FieldToJsonObject(field, field.default_value) return js def _StructMessageToJsonObject(self,",
"noqa from clarifai.rest.grpc.proto.clarifai.api.utils import extensions_pb2 def protobuf_to_dict(object_protobuf, use_integers_for_enums=True, ignore_show_empty=False): #",
"to adjust the original's method's return JSON object and keep",
"which has been serialized already. continue if _IsMapEntry(field): js[name] =",
"is None: json_object = {} else: json_object = self._ValueMessageToJsonObject(fields[key]) ret[key]",
"a Struct with an empty Struct field, this condition will",
"= _CustomPrinter( printer = _CustomPrinter( including_default_value_fields=False, preserving_proto_field_name=True, use_integers_for_enums=use_integers_for_enums, ignore_show_empty=ignore_show_empty) #",
"default, empty objects {} get converted to null. We overwrite",
"keep these fields. \"\"\" js = super(_CustomPrinter, self)._RegularMessageToJsonObject(message, js) message_descriptor",
"JSON Specification. However, by default, empty objects {} get converted",
"js def _StructMessageToJsonObject(self, message): \"\"\" Converts Struct message according to",
"{} for key in fields: # When there's a Struct",
"ignore_show_empty): super(_CustomPrinter, self).__init__(including_default_value_fields, preserving_proto_field_name, use_integers_for_enums) self._ignore_show_empty = ignore_show_empty def _RegularMessageToJsonObject(self,",
"not be affected. if ((field.label != descriptor.FieldDescriptor.LABEL_REPEATED and field.cpp_type ==",
"Struct with an empty Struct field, this condition will hold",
"descriptor.FieldDescriptor.LABEL_REPEATED: js[name] = [] else: js[name] = self._FieldToJsonObject(field, field.default_value) return",
"use_integers_for_enums, ignore_show_empty): super(_CustomPrinter, self).__init__(including_default_value_fields, preserving_proto_field_name, use_integers_for_enums) self._ignore_show_empty = ignore_show_empty def",
"to null. We overwrite this behavior so {} get converted",
"js[name] = {} elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED: js[name] = []",
"if _IsMapEntry(field): js[name] = {} elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED: js[name]",
"extension `cl_show_if_empty`, we need to adjust the original's method's return",
"with the custom extension `cl_show_if_empty`, we need to adjust the",
"converted to null. We overwrite this behavior so {} get",
"in fields: # When there's a Struct with an empty",
"object and keep these fields. \"\"\" js = super(_CustomPrinter, self)._RegularMessageToJsonObject(message,",
"for key in fields: # When there's a Struct with",
"to {}. \"\"\" fields = message.fields ret = {} for",
"Far as I know this is the only case this",
"self._FieldToJsonObject(field, field.default_value) return js def _StructMessageToJsonObject(self, message): \"\"\" Converts Struct",
"# When there's a Struct with an empty Struct field,",
"import descriptor from google.protobuf.json_format import _IsMapEntry, _Printer from google.protobuf.message import",
"return js def _StructMessageToJsonObject(self, message): \"\"\" Converts Struct message according",
"Message # noqa from clarifai.rest.grpc.proto.clarifai.api.utils import extensions_pb2 def protobuf_to_dict(object_protobuf, use_integers_for_enums=True,",
"ignore_show_empty=False): # type: (Message, typing.Optional[bool], typing.Optional[bool]) -> dict # printer",
"or field.containing_oneof): continue if self.preserving_proto_field_name: name = field.name else: name",
"# Singular message fields and oneof fields will not be",
"= super(_CustomPrinter, self)._RegularMessageToJsonObject(message, js) message_descriptor = message.DESCRIPTOR for field in",
"_IsMapEntry, _Printer from google.protobuf.message import Message # noqa from clarifai.rest.grpc.proto.clarifai.api.utils",
"dict # printer = _CustomPrinter( printer = _CustomPrinter( including_default_value_fields=False, preserving_proto_field_name=True,"
] |
[] |
[
"req = Request(None) req.setcommand(\"1\", CmdCode.DETECT_DEVICE, None) print \"=======================================#1\" kdmate.writeblk(req) print",
"\"opentime\" : (1, \"short\"), \"closetime\" : (1, \"short\"), \"EC\": (2,",
"\"dk\" : (2,40241,[\"opid\",\"status\"],45041,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"206\", \"dk\" :",
"+ str(info)) else: noti = Notice(None, NotiCode.DETECT_UNKNOWN_PROTOCOL_VER, devid=tempid) # unknown",
"to connect with tcp\" code = NotiCode.TCP_WAITING if ret else",
"ret == False: self._logger.warn(msg) noti = Notice(None, NotiCode.RTU_FAILED_CONNECTION) # detection",
"\"detect_node\", unit, registers compcode = registers[0] nodecode = registers[2] size",
": (2,40281,[\"opid\",\"status\"],45081,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"} ] }, { \"id\" : \"301\",",
"\"dk\" : '[1,40311,[\"value\",\"status\"]]', \"dt\": \"sen\"} ]} ]} ] devinfo =",
"ResCode.FAIL else: self._logger.warn(\"Unknown Error. \" + str(blk) + \", \"",
"\"int\"), \"ratio\": (1, \"short\"), \"position\" : (1, \"short\"), \"remain-time\" :",
"= \"failed to connect with tcp\" code = NotiCode.TCP_WAITING if",
"info}) # found a node detected[unit] = info noti.setkeyvalue(\"opid\", self._detection[\"opid\"])",
"\"act/switch/level0\"}, #{\"id\" : \"204\", \"dk\" : (2,40231,[\"opid\",\"status\"],45031,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\"",
"operation # need to convert by case params[\"opid\"] = request.getopid()",
"readmsg(self): self._msgq = [] for gw in self._devinfo: for nd",
"read dev status.\") else: self.sendnoticeforactuatorstatus(msg) return ResCode.OK def writeblk(self, blk):",
"3 == 0: self.sendnoticeforactuatorstatus(ret) ret[\"act\"] = {} self.sendnoticeforactuatorstatus(ret) def sendobservation(self,",
"True def stop(self): super(KSX3267MateV2, self).stop() return True def getsize(self, lst):",
"in (NodeType.SENNODE, NodeType.ACTNODE, NodeType.INTNODE): # device type if res.registers[3] ==",
"# need to convert by case properparams = CmdCode.getparams(operation) +",
"devinfo, \"1\", None) mate = Mate ({}, [], \"1\", None)",
"ProtoVer.TTA_1: info = self.detect_node(conn, unit, res.registers) self._logger.info (\"Found a nutrient",
"conn = None else: msg = \"It's a wrong connection",
"+ str(res)) elif res.registers[1] in (NodeType.SENNODE, NodeType.ACTNODE, NodeType.INTNODE): # device",
": (1, \"short\"), \"alert\" : (1, \"alert\"), \"hold-time\" : (2,",
"DevType.isnode(dev['dt']): # modbus code = self.processrequest(dev, blk, nd) self._logger.info(\"Actuator processed",
"nutrient system : \" + str(unit) + \" \" +",
"port, conn in self._conn.iteritems(): if self._isdetecting == False or self.isexecuting()",
"\"208\", \"dk\" : (2,40271,[\"opid\",\"status\"],45071,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"209\", \"dk\"",
"= [{ \"id\" : \"1\", \"dk\" : \"JND2\", \"dt\": \"gw\",",
"print \"=======================================#3\" kdmate.writeblk(req) print \"=======================================#3\" time.sleep(1) req = Request(None) req.setcommand(\"1\",",
"{\"id\" : \"112\", \"dk\" : '[1,40301,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" :",
"# {\"id\" : \"102\", \"dk\" : '[1,40202,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #",
"= self.detect_node(conn, unit, res.registers) self._logger.info (\"Found a node : \"",
"to dev.\" + str(dev) + \",\" + str(res) + \":\"",
"] }] }] \"\"\" if isnutri: kdmate = KSX3267MateV2(opt, nutriinfo,",
"continue to read other device\") return ret def readactnodeinfo(self, node):",
"str(unit) + \" \" + str(addr) + \" \" +",
"kdmate = KSX3267MateV2(opt, nutriinfo, \"1\", None) else: kdmate = KSX3267MateV2(opt,",
"if msg is None: self._logger.warn(\"Fail to read dev status.\") else:",
"conn, dev): size = self.getsize(self.getdk(dev, 2)) #for _ in range(3):",
"[ {\"id\" : \"202\", \"dk\" : '[2,40202,[\"opid\",\"status\",\"state-hold-time\",\"remain-time\"],40206,[\"operation\",\"opid\",\"time\"]]', \"dt\": \"act/retractable/level1\"}, {\"id\"",
"Request(201) req.setcommand(202, CmdCode.TIMED_CLOSE, {\"time\":10}) kdmate.writeblk(req) time.sleep(5) req = Request(201) req.setcommand(202,",
"\"epoch\" : (2, \"int\"), \"vfloat\": (2, \"float\"), \"vint\" : (2,",
"DevType from mblock import MBlock, BlkType, StatCode, ResCode, CmdCode, Observation,",
"in self.getdk(dev, 4): if key not in properparams: # key",
"print \"=======================================#3\" time.sleep(1) req = Request(None) req.setcommand(\"1\", CmdCode.CANCEL_DETECT, {}) print",
"opt[\"port\"]: conn = ModbusTcpClient(timeout=self._timeout) conn.socket = clisoc self._conn[opt[\"port\"]] = conn",
"key in self.getdk(dev, 4): if key not in properparams: #",
"to find a node else: noti = Notice(None, NotiCode.DETECT_NODE_DETECTED, devid=port,",
"return ret def readactnodeinfo(self, node): ret = self.readnodeinfo(node) for dev",
"StatCode.ERROR.value obsblk = Observation(ndinfo[\"id\"]) obsblk.setobservation(ndinfo[\"id\"], 0, StatCode(ndinfo[\"nd\"][\"status\"])) for devid, info",
"req.setcommand(202, CmdCode.OFF, {}) kdmate.writeblk(req) \"\"\" time.sleep(30) kdmate.stop() print \"mate stopped\"",
"self.getdk(dev, 4): if key not in properparams: # key param",
"from mate import Mate, ThreadMate, DevType from mblock import MBlock,",
"ndinfo): blk = Notice(ndinfo[\"id\"], NotiCode.ACTUATOR_STATUS, ndinfo[\"id\"], ndinfo[\"nd\"]) for devid, info",
"size = size + KSX3267MateV2._KEYWORDS[k][0] else: self._logger.warn(\"wrong keyword : \"",
"== \"__main__\": isnutri = False opt = { 'conn' :",
"node): ret = self.readnodeinfo(node) for dev in node['children']: if DevType.issensor(dev[\"dt\"])",
"else: noti = Notice(None, NotiCode.DETECT_NODE_DETECTED, devid=port, content={unit : info}) #",
"== 'tcpcs': self._logger.info(\"It would wait for a while to connect",
"unknown protocol version else: noti = Notice(unit, NotiCode.DETECT_UNKNOWN_NODE, devid=tempid) #",
"\" + str(size) + \" \" + str(len(res.registers))) return None",
"ResCode.FAIL_NO_DEVICE elif DevType.ispropercommand(dev['dt'], cmd) is False: self._logger.warn(\"The request is not",
"= self.readinfofromdev(ret[\"conn\"], dev) if info: ret[\"act\"][dev[\"id\"]] = info else: self._logger.warn(\"fail",
"\"204\", \"dk\" : (2,40231,[\"opid\",\"status\"],45031,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"205\", \"dk\"",
"= NotiCode.TCP_WAITING if ret else NotiCode.RTU_FAILED_CONNECTION conn = None else:",
": (1, \"operation\"), \"time\" : (2, \"int\"), \"opentime\" : (1,",
"\"dt\": \"act/switch/level0\"}, #{\"id\" : \"207\", \"dk\" : (2,40261,[\"opid\",\"status\"],45061,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"},",
"+ str(params['operation']) + \", \" + str(key)) # return ResCode.FAIL_WRONG_KEYWORD",
"NotiCode, Notice from pymodbus.client.sync import ModbusSerialClient from pymodbus.client.sync import ModbusTcpClient",
"kdmate.writeblk(req) print \"=======================================#1\" \"\"\" time.sleep(1) req = Request(None) req.setcommand(\"1\", CmdCode.CANCEL_DETECT,",
"return False response = Response(blk) cmd = blk.getcommand() nd =",
"= KSX3267MateV2._KEYWORDS[nm] if vtype == \"float\": val = struct.unpack('f', struct.pack('HH',",
"if ret == False: self._logger.warn(msg) noti = Notice(None, NotiCode.RTU_FAILED_CONNECTION) #",
"info = self.readinfofromdev(ret[\"conn\"], act) if info: ret[\"act\"][act[\"id\"]] = info else:",
"connect a client.\") ret = self.listen(opt) msg = \"failed to",
"self.getsize(self.getdk(dev, 2)) #for _ in range(3): res = self.readregister(conn, self.getdk(dev,",
"readregister(self, conn, addr, count, unit): print \"....... before lock for",
"noti = Notice(None, NotiCode.RTU_FAILED_CONNECTION) # detection is canceled else: noti",
"12): for unit in range(self._detection[\"saddr\"], self._detection[\"eaddr\"]): if self._isdetecting == False",
"{}) print \"=======================================#4\" kdmate.writeblk(req) print \"=======================================#4\" time.sleep(10) req = Request(201)",
"self._conn[gw[\"dk\"]].write_registers(self.getdk(dev, 3), registers, unit=unit) if res.isError(): self._logger.warn(\"Fail to write a",
"{\"id\" : \"102\", \"dk\" : '[1,40202,[\"value\",\"status\"]]', \"dt\": \"sen\"}, # {\"id\"",
"tcp\" code = NotiCode.TCP_CONNECTED if ret else NotiCode.RTU_FAILED_CONNECTION elif opt['method']",
"'tcpcs': self._logger.info(\"It would wait for a while to connect a",
"in rsoc: if sock == servsoc: clisoc, address = servsoc.accept()",
"import hashlib import json from enum import IntEnum from threading",
"= NotiCode.RTU_CONNECTED if ret else NotiCode.RTU_FAILED_CONNECTION elif opt['method'] == 'tcpc':",
"CmdCode.OPEN, {}) kdmate.writeblk(req) time.sleep(5) req = Request(201) req.setcommand(202, CmdCode.OFF, {})",
"i % 3 == 0: self.sendnoticeforactuatorstatus(ret) ret[\"act\"] = {} self.sendnoticeforactuatorstatus(ret)",
": '[1,40271,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"109\", \"dk\" : '[1,40281,[\"value\",\"status\"]]',",
"\", \" + str(dev)) code = ResCode.FAIL response.setresult(code) self._logger.info(\"write response:",
"= struct.unpack('i', struct.pack('HH', values[idx], values[idx+1]))[0] else: val = values[idx] ret[nm]",
"data is not matched. 6 \" + str(len(res.registers))) continue break",
"if k in KSX3267MateV2._KEYWORDS: size = size + KSX3267MateV2._KEYWORDS[k][0] else:",
"key not in properparams: # key param is not used",
"\"short\"), \"state-hold-time\" : (2, \"int\"), \"ratio\": (1, \"short\"), \"position\" :",
"self.readinfofromdev(ret[\"conn\"], dev) if info: ret[\"act\"][dev[\"id\"]] = info else: self._logger.warn(\"fail to",
"key param is not used for this operation # However,",
"StatCode(info[\"status\"])) # do not send observation for actuator #for devid,",
"conn super(KSX3267MateV2, self).connect() return ret def closeone(self, port): self._conn[port].close() def",
"isnutri = False opt = { 'conn' : [{ 'method':",
"values[idx+1]))[0] elif vtype == \"int\": val = struct.unpack('i', struct.pack('HH', values[idx],",
": \"103\", \"dk\" : '[1,40205,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"104\",",
"if cmd == CmdCode.DETECT_DEVICE: print \"detect device\" code = self.startdetection(params,",
"else: self._logger.warn(\"wrong keyword : \" + str(k)) return -1 return",
"'[1,40271,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"109\", \"dk\" : '[1,40281,[\"value\",\"status\"]]', \"dt\":",
"size of data is not matched. \" + str(size) +",
"in self._msgq: if msg is None: continue self.sendobservation(msg) def sendnoti(self):",
"port, info in detected.iteritems(): noti.setcontent(port, info) self.writecb(noti) self.setdetection(False) def detectone(self,",
"to read other device\") return ret def readactnodeinfo(self, node): ret",
"self._detection[\"opid\"] = opid def startdetection(self, params, opid): if self._detection[\"opid\"] !=",
"logger) self._timeout = 3 if \"timeout\" not in option else",
"+ size print \"parsed\", ret return ret def readinfofromdev(self, conn,",
"actuator info : \" + str(act) + \" however continue",
"\"control\",\"EC\",\"pH\", \"start-area\", \"stop-area\", \"on-sec\"]]', \"dt\": \"nutrient-supply/level1\"}, {\"id\" : \"103\", \"dk\"",
"(2,40251,[\"opid\",\"status\"],45051,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"207\", \"dk\" : (2,40261,[\"opid\",\"status\"],45061,[\"operation\",\"opid\"]), \"dt\":",
"\"children\" : [ # { # \"id\" : \"101\", \"dk\"",
"time.sleep(5) req = Request(201) req.setcommand(202, CmdCode.OFF, {}) kdmate.writeblk(req) \"\"\" time.sleep(30)",
"\"105\", \"dk\" : '[1,40241,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"106\", \"dk\"",
": \"\", \"dt\": \"gw\", \"children\" : [{ \"id\" : \"101\",",
"time.sleep(1) req = Request(None) req.setcommand(\"1\", CmdCode.CANCEL_DETECT, {}) print \"=======================================#2\" kdmate.writeblk(req)",
"DevType.isactuator(dev['dt']) or DevType.isnode(dev['dt']): # modbus code = self.processrequest(dev, blk, nd)",
"\" + str(res)) # continue else: if len(res.registers) == size:",
"to read holding registers. : \" + str(ex)) return None",
"= blk.getcommand() nd = self._devinfo.finddevbyid(blk.getnodeid()) dev = self._devinfo.finddevbyid(blk.getdevid()) if blk.getdevid()",
"'[1,40261,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"108\", \"dk\" : '[1,40271,[\"value\",\"status\"]]', \"dt\":",
"tmp = {\"thd\" : Thread(target=self._listen, args=(opt)), \"status\": 0, \"port\":opt['port']} self._tempthd.append(tmp)",
"addr, count, unit): print \"....... before lock for read\" with",
"{\"id\" : \"102\", \"dk\" : '[1,40211,[\"control\",\"status\",\"area\",\"alert\",\"opid\"],45001,[\"operation\", \"opid\", \"control\",\"EC\",\"pH\", \"start-area\", \"stop-area\",",
"device\") return ret def readactnodeinfo(self, node): ret = self.readnodeinfo(node) for",
"0, StatCode(ndinfo[\"nd\"][\"status\"])) for devid, info in ndinfo[\"sen\"].iteritems(): if StatCode.has_value(info[\"status\"]) ==",
"[ {\"id\" : \"102\", \"dk\" : '[1,40211,[\"control\",\"status\",\"area\",\"alert\",\"opid\"],45001,[\"operation\", \"opid\", \"control\",\"EC\",\"pH\", \"start-area\",",
"str(dev) + \" however continue to read other device\") return",
"read node info : \" + str(node)) return ret def",
"in self._conn.keys(): self.closeone(port) super(KSX3267MateV2, self).close() def readmsg(self): self._msgq = []",
"conn info = self.readinfofromdev(conn, node) if info: ret[\"nd\"] = info",
"\"dk\" : (2,40271,[\"opid\",\"status\"],45071,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"209\", \"dk\" :",
"ret[\"act\"][dev[\"id\"]] = info else: self._logger.warn(\"fail to read actuator info :",
"self._logger.warn(\"fail to read actuator info : \" + str(dev) +",
"sendobservation(self, ndinfo): if StatCode.has_value(ndinfo[\"nd\"][\"status\"]) == False: ndinfo[\"nd\"][\"status\"] = StatCode.ERROR.value obsblk",
"in gw[\"children\"]: ret = self.readnodeinfo(node) i = 1 for dev",
"res.registers) self._logger.info (\"Found a nutrient system : \" + str(unit)",
"\"dt\": \"sen\"}, #{\"id\" : \"109\", \"dk\" : '[1,40281,[\"value\",\"status\"]]', \"dt\": \"sen\"},",
"else: val = values[idx] ret[nm] = val idx = idx",
"\" + str(dev) + \" however continue to read other",
"to read other device\") return ret def sendobs(self): for msg",
"req.setcommand(\"1\", CmdCode.CANCEL_DETECT, {}) print \"=======================================#4\" kdmate.writeblk(req) print \"=======================================#4\" time.sleep(10) req",
"clisoc self._conn[opt[\"port\"]] = conn tmp[\"status\"] = 10 # connected executing",
"or self.isexecuting() == False: self._logger.info(\"Total detection is canceled.\") break info",
"\"nd\", \"children\" : [ #{\"id\" : \"102\", \"dk\" : '[1,41010,[\"value\",\"status\"]]',",
"if res.registers[3] == ProtoVer.KS_X_3267_2020 or res.registers[3] == ProtoVer.KS_X_3267_2018: info =",
"if StatCode.has_value(info[\"status\"]) == False: # info[\"status\"] = StatCode.ERROR.value # obsblk.setobservation(devid,",
"\"dk\" : '[1,40281,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"110\", \"dk\" :",
": '/dev/ttyJND2', 'baudrate' : 9600, 'timeout': 5 }] } nutriinfo",
"self).__init__(option, devinfo, coupleid, logger) self._timeout = 3 if \"timeout\" not",
"registers[4] while True: res = self.readregister(conn, KSX3267MateV2._DEVCODEREG, size, unit) if",
"for read\" with self._lock: time.sleep(KSX3267MateV2._SLEEP) #mrchoi87 self._logger.info(\"read_holding_registers: \" + str(unit)",
"ret = conn.connect() msg = \"failed to connect with tcp\"",
"for a while to connect a client.\") ret = self.listen(opt)",
"def sendnoticeforactuatorstatus(self, ndinfo): blk = Notice(ndinfo[\"id\"], NotiCode.ACTUATOR_STATUS, ndinfo[\"id\"], ndinfo[\"nd\"]) for",
"\"110\", \"dk\" : '[1,40291,[\"value\",\"status\"]]', \"dt\": \"sen\"} # ] # }",
"in detected.iteritems(): noti.setcontent(port, info) self.writecb(noti) self.setdetection(False) def detectone(self, port, conn):",
"import ModbusSerialClient from pymodbus.client.sync import ModbusTcpClient class NodeType(IntEnum): SENNODE =",
"self._devinfo.findgateway(request.getnodeid()) unit = self.getdk(dev, 0) operation = request.getcommand() params =",
"lst): size =0 for k in lst: if k in",
"'rtu', 'port' : '/dev/ttyJND2', 'baudrate' : 9600, 'timeout': 5 }]",
"Detection Started if noti: noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) self.writecb(noti) noti = None",
"str(node)) return ret def readsensornodeinfo(self, node): ret = self.readnodeinfo(node) for",
"cmd == CmdCode.CANCEL_DETECT: print \"cancel to detect device\" code =",
"with tcp\" code = NotiCode.TCP_CONNECTED if ret else NotiCode.RTU_FAILED_CONNECTION elif",
"would wait for a while to connect a client.\") ret",
"registers[0] nodecode = registers[2] size = registers[4] while True: res",
"2018 JiNong, Inc. # All right reserved. # import struct",
"unit): print \"....... before lock for read\" with self._lock: time.sleep(KSX3267MateV2._SLEEP)",
"\"short\"), \"remain-time\" : (2, \"int\"), \"control\": (1, \"control\"), \"area\" :",
"(1, \"short\"), \"closetime\" : (1, \"short\"), \"EC\": (2, \"float\"), \"pH\":",
"opid=0): self._isdetecting = flag self._detection[\"opid\"] = opid def startdetection(self, params,",
"(3,40221,[\"opid\",\"status\"],45021,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"}, {\"id\" : \"304\", \"dk\" : (3,40231,[\"opid\",\"status\"],45031,[\"operation\",\"opid\"]), \"dt\":",
"if isnutri: kdmate = KSX3267MateV2(opt, nutriinfo, \"1\", None) else: kdmate",
"+ str(len(res.registers))) continue break if res is None or res.isError():",
"in node['children']: if DevType.issensor(dev[\"dt\"]): info = self.readinfofromdev(ret[\"conn\"], dev) if info:",
"ret else NotiCode.RTU_FAILED_CONNECTION elif opt['method'] == 'tcpcs': self._logger.info(\"It would wait",
"properparams: # key param is not used for this operation",
"ret else NotiCode.RTU_FAILED_CONNECTION conn = None else: msg = \"It's",
"\"dt\": \"sen\"}, {\"id\" : \"106\", \"dk\" : '[1,40251,[\"value\",\"status\"]]', \"dt\": \"sen\"},",
"\"103\", \"dk\" : '[1,40205,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"104\", \"dk\"",
": (2,40251,[\"opid\",\"status\"],45051,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"207\", \"dk\" : (2,40261,[\"opid\",\"status\"],45061,[\"operation\",\"opid\"]),",
"\" + str(count)) print \"read register\", unit, addr, count try:",
": \" + str(ex)) return None def detect(self): detected =",
"of data is not matched. \" + str(size) + \"",
"def closeone(self, port): self._conn[port].close() def close(self): for port in self._conn.keys():",
"else: noti = Notice(None, NotiCode.RTU_CONNECTED) # detection is canceled self.writecb(noti)",
"self.writecb(blk) def start(self, writecb): super(KSX3267MateV2, self).start(writecb) return True def stop(self):",
"\"sen\"}, {\"id\" : \"105\", \"dk\" : '[1,40241,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\"",
": '[2,40202,[\"opid\",\"status\",\"state-hold-time\",\"remain-time\"],40206,[\"operation\",\"opid\",\"time\"]]', \"dt\": \"act/retractable/level1\"}, {\"id\" : \"202\", \"dk\" : '[2,40209,[\"opid\",\"status\",\"state-hold-time\",\"remain-time\"],40213,[\"operation\",\"opid\",\"time\"]]',",
"req.setcommand(\"1\", CmdCode.DETECT_DEVICE, None) print \"=======================================#3\" kdmate.writeblk(req) print \"=======================================#3\" time.sleep(1) req",
": (2, \"int\"), \"vfloat\": (2, \"float\"), \"vint\" : (2, \"int\")}",
"method. \" + str(opt['method']) if ret == False: self._logger.warn(msg) noti",
"content={unit : info}) # found a node detected[unit] = info",
"= 10 KS_X_3267_2018 = 101 TTA_1 = 201 class KSX3267MateV2(ThreadMate):",
"found a node detected[unit] = info noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) print \"noti\",",
"noti is None: if info is None: noti = Notice(None,",
"str(info)) else: noti = Notice(None, NotiCode.DETECT_UNKNOWN_PROTOCOL_VER, devid=tempid) # unknown protocol",
"\"sen\"}, # {\"id\" : \"105\", \"dk\" : '[1,40211,[\"value\",\"status\"]]', \"dt\": \"sen\"},",
"res.registers[3] == ProtoVer.KS_X_3267_2020 or res.registers[3] == ProtoVer.KS_X_3267_2018: info = self.detect_node(conn,",
"params['port'] else: self._detection[\"saddr\"] = 1 self._detection[\"eaddr\"] = 12 self._detection[\"port\"] =",
"= Notice(None, NotiCode.DETECT_UNKNOWN_PROTOCOL_VER, devid=tempid) # unknown protocol version else: noti",
"DevType.issensor(dev[\"dt\"]) == False: info = self.readinfofromdev(ret[\"conn\"], dev) if info: ret[\"act\"][dev[\"id\"]]",
"ret else NotiCode.RTU_FAILED_CONNECTION elif opt['method'] == 'tcpc': conn = ModbusTcpClient(opt['host'],",
"\"id\" : \"1\", \"dk\" : \"\", \"dt\": \"gw\", \"children\" :",
"NodeType(IntEnum): SENNODE = 1 ACTNODE = 2 INTNODE = 3",
"Notice(None, NotiCode.DETECT_FINISHED) # Detection Started if noti: noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) for",
"\"dk\" : '[1,41010,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"103\", \"dk\" :",
"elif res.isError(): self._logger.info(\"retry to get status from \" + str(dev['dk'])",
"print \"detect device\" code = self.startdetection(params, blk.getopid()) elif cmd ==",
"\"107\", \"dk\" : '[1,40261,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"109\", \"dk\"",
"status.\") else: self.sendnoticeforactuatorstatus(msg) return ResCode.OK def writeblk(self, blk): print \"received",
"= info #else: # self._logger.warn(\"fail to read sensor info :",
": '[1,40291,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"112\", \"dk\" : '[1,40301,[\"value\",\"status\"]]',",
"else: self._detection[\"saddr\"] = 1 self._detection[\"eaddr\"] = 12 self._detection[\"port\"] = None",
"is no device. \" + str(blk.getdevid())) code = ResCode.FAIL_NO_DEVICE elif",
"= ResCode.FAIL elif dev is None: self._logger.warn(\"There is no device.",
"range(3): res = self.readregister(conn, self.getdk(dev, 1), size, self.getdk(dev, 0)) if",
"time.sleep(10) req = Request(201) req.setcommand(202, CmdCode.OPEN, {}) kdmate.writeblk(req) time.sleep(5) req",
"elif KSX3267MateV2._KEYWORDS[key][1] == \"int\": registers.extend(struct.unpack('HH', struct.pack('i', val))) elif KSX3267MateV2._KEYWORDS[key][1] ==",
"= Notice(None, NotiCode.DETECT_FINISHED) # Detection Started if noti: noti.setkeyvalue(\"opid\", self._detection[\"opid\"])",
"(1, \"operation\"), \"time\" : (2, \"int\"), \"opentime\" : (1, \"short\"),",
"mate import Mate, ThreadMate, DevType from mblock import MBlock, BlkType,",
"= conn super(KSX3267MateV2, self).connect() return ret def closeone(self, port): self._conn[port].close()",
": \"302\", \"dk\" : (3,40211,[\"opid\",\"status\"],45011,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"}, {\"id\" : \"303\",",
"}, { \"id\" : \"201\", \"dk\" : '[2,40201,[\"status\"],45001,[\"operation\",\"opid\"]]', \"dt\": \"nd\",",
"#else: # self._logger.warn(\"fail to read sensor info : \" +",
"] devinfo = [{ \"id\" : \"1\", \"dk\" : \"JND2\",",
": \"303\", \"dk\" : (3,40221,[\"opid\",\"status\"],45021,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"}, {\"id\" : \"304\",",
": \"304\", \"dk\" : (3,40231,[\"opid\",\"status\"],45031,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"}, {\"id\" : \"305\",",
"convert by case params[\"opid\"] = request.getopid() # need to convert",
"Started if noti: noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) self.writecb(noti) noti = None info",
"\"=======================================#3\" time.sleep(1) req = Request(None) req.setcommand(\"1\", CmdCode.CANCEL_DETECT, {}) print \"=======================================#4\"",
"ResCode.OK else False def parseregisters(self, names, values): idx = 0",
"Request(None) req.setcommand(\"1\", CmdCode.DETECT_DEVICE, None) print \"=======================================#1\" kdmate.writeblk(req) print \"=======================================#1\" \"\"\"",
"= self.readregister(conn, KSX3267MateV2._DEVCODEREG, size, unit) if res is None or",
"lst: if k in KSX3267MateV2._KEYWORDS: size = size + KSX3267MateV2._KEYWORDS[k][0]",
"\"113\", \"dk\" : '[1,40311,[\"value\",\"status\"]]', \"dt\": \"sen\"} ]} ]} ] devinfo",
"continue else: if len(res.registers) == size: return self.parseregisters(self.getdk(dev, 2), res.registers)",
"self.checktempthreads() def processrequest(self, dev, request, node): gw = self._devinfo.findgateway(request.getnodeid()) unit",
"struct.pack('f', val))) #else: # self._logger.warn(\"This param is needed for this",
"\"dt\": \"sen\"}, {\"id\" : \"109\", \"dk\" : '[1,40271,[\"value\",\"status\"]]', \"dt\": \"sen\"},",
"\"102\", \"dk\" : '[1,41010,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"103\", \"dk\"",
"req.setcommand(202, CmdCode.OFF, {}) kdmate.writeblk(req) time.sleep(10) req = Request(201) req.setcommand(202, CmdCode.TIMED_OPEN,",
"= False conn = None if opt['method'] == 'rtu': conn",
"= self._conn[gw[\"dk\"]].write_registers(self.getdk(dev, 3), registers, unit=unit) if res.isError(): self._logger.warn(\"Fail to write",
"self._detection[\"saddr\"] = params['saddr'] self._detection[\"eaddr\"] = params['eaddr'] self._detection[\"port\"] = params['port'] else:",
"Notice(None, NotiCode.DETECT_CANCELED) # detection is canceled noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) self.writecb(noti) self.setdetection(False)",
"conn.connect() msg = \"failed to connect with rtu\" code =",
"+ \", \" + str(key)) # return ResCode.FAIL_WRONG_KEYWORD print \".......",
"\"dt\": \"act/switch/level0\"} ] }, { \"id\" : \"301\", \"dk\" :",
"registers = [] for key in self.getdk(dev, 4): if key",
"4 class ProtoVer(IntEnum): KS_X_3267_2020 = 10 KS_X_3267_2018 = 101 TTA_1",
"\"sen\"}, {\"id\" : \"109\", \"dk\" : '[1,40271,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\"",
"proper. \" + str(cmd) + \" \" + str(dev['dt'])) code",
": (1, \"status\"), \"opid\" : (1, \"short\"), \"state-hold-time\" : (2,",
"#{\"id\" : \"106\", \"dk\" : '[1,40251,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" :",
"the register should be filled. val = 0 elif key",
"return ret def readsensornodeinfo(self, node): ret = self.readnodeinfo(node) for dev",
"ret[\"act\"][act[\"id\"]] = info else: self._logger.warn(\"fail to read actuator info :",
"str(act) + \" however continue to read other device\") return",
"#mrchoi87 #for unit in range(self._detection[\"saddr\"], 12): for unit in range(self._detection[\"saddr\"],",
"1 if i % 3 == 0: self.sendnoticeforactuatorstatus(ret) ret[\"act\"] =",
"3), registers, unit=unit) if res.isError(): self._logger.warn(\"Fail to write a request",
"CmdCode.CANCEL_DETECT, {}) print \"=======================================#2\" kdmate.writeblk(req) print \"=======================================#2\" time.sleep(1) req =",
"def readinfofromdev(self, conn, dev): size = self.getsize(self.getdk(dev, 2)) #for _",
"servsoc: clisoc, address = servsoc.accept() self._logger.info(\"client connected from \" +",
"str(blk.gettype())) return False response = Response(blk) cmd = blk.getcommand() nd",
"if key not in properparams: # key param is not",
"self._logger.warn(\" port [\" + str(opt[\"port\"]) + \"] exception : \"",
"version else: noti = Notice(unit, NotiCode.DETECT_UNKNOWN_NODE, devid=tempid) # unknown device",
"val))) elif KSX3267MateV2._KEYWORDS[key][1] == \"float\": registers.extend(struct.unpack('HH', struct.pack('f', val))) #else: #",
": '[2,40219,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"203\", \"dk\" : (2,40221,[\"opid\",\"status\"],45021,[\"operation\",\"opid\"]),",
"#!/usr/bin/env python # # -*- coding: utf-8 -*- # #",
"args=(opt)), \"status\": 0, \"port\":opt['port']} self._tempthd.append(tmp) tmp[\"thd\"].start() def checktempthreads(self): for tmp",
"to connect a client.\") ret = self.listen(opt) msg = \"failed",
"\"status\" : (1, \"status\"), \"opid\" : (1, \"short\"), \"state-hold-time\" :",
"read actuator info : \" + str(dev) + \" however",
"NodeType.INTNODE): # device type if res.registers[3] == ProtoVer.KS_X_3267_2020 or res.registers[3]",
"\" + str(size) + \" \" + str(len(res.registers))) continue return",
"1), size, self.getdk(dev, 0)) if res is None: self._logger.warn(\"fail to",
"CmdCode.DETECT_DEVICE: print \"detect device\" code = self.startdetection(params, blk.getopid()) elif cmd",
"self.writecb(noti) return conn def connect(self): ret = False for opt",
"values[idx] ret[nm] = val idx = idx + size print",
"else: self._logger.warn(\"Unknown Error. \" + str(blk) + \", \" +",
"3 NUTNODE = 4 class ProtoVer(IntEnum): KS_X_3267_2020 = 10 KS_X_3267_2018",
"(1, \"alert\"), \"hold-time\" : (2, \"int\"), \"operation\" : (1, \"operation\"),",
"kdmate.writeblk(req) time.sleep(5) req = Request(201) req.setcommand(202, CmdCode.OFF, {}) kdmate.writeblk(req) time.sleep(10)",
"Request(201) req.setcommand(202, CmdCode.TIMED_OPEN, {\"time\":10}) kdmate.writeblk(req) time.sleep(15) req = Request(201) req.setcommand(202,",
"if ret else NotiCode.RTU_FAILED_CONNECTION elif opt['method'] == 'tcpcs': self._logger.info(\"It would",
"\" + str(ex)) tmp[\"status\"] = 5 # error def listen(self,",
"return ret def readactinfo(self, node, act): ret = self.readnodeinfo(node) info",
"#if code == ResCode.OK else False def parseregisters(self, names, values):",
"+ str(act) + \" however continue to read other device\")",
"{} for port, conn in self._conn.iteritems(): if self._isdetecting == False",
"ret = self.listen(opt) msg = \"failed to connect with tcp\"",
"info in ndinfo[\"act\"].iteritems(): # if StatCode.has_value(info[\"status\"]) == False: # info[\"status\"]",
": \"205\", \"dk\" : (2,40241,[\"opid\",\"status\"],45041,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"206\",",
"devices from \" + str(unit) + \" \" + str(res))",
"= select.select([servsoc], [], [], 10) for sock in rsoc: if",
"self._logger.info (\"Fail to get information from a node : \"",
"size + KSX3267MateV2._KEYWORDS[k][0] else: self._logger.warn(\"wrong keyword : \" + str(k))",
"KSX3267MateV2._KEYWORDS[k][0] else: self._logger.warn(\"wrong keyword : \" + str(k)) return -1",
"if self._detection[\"opid\"] != 0: self._logger.info(\"detection is processing.... so this command",
"elif KSX3267MateV2._KEYWORDS[key][1] == \"float\": registers.extend(struct.unpack('HH', struct.pack('f', val))) #else: # self._logger.warn(\"This",
"+ str(port) + \" detection is canceled.\") break tempid =",
"\"dt\": \"sen\"}, {\"id\" : \"111\", \"dk\" : '[1,40291,[\"value\",\"status\"]]', \"dt\": \"sen\"},",
"+ str(unit) + \" \" + str(res)) elif res.registers[1] in",
"+ \" \" + str(count)) print \"read register\", unit, addr,",
"= {} for nm in names: (size, vtype) = KSX3267MateV2._KEYWORDS[nm]",
"= None for _ in range(3): res = self.readregister(conn, KSX3267MateV2._DEVINFOREG,",
"\" \" + str(len(res.registers))) return None def readnodeinfo(self, node): ret",
"== False: self._logger.warn(msg) noti = Notice(None, NotiCode.RTU_FAILED_CONNECTION) # detection is",
"if info is None: noti = Notice(None, NotiCode.DETECT_WRONG_DEVICE, devid=tempid) #",
": '[1,40231,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"105\", \"dk\" : '[1,40241,[\"value\",\"status\"]]',",
"2)) #for _ in range(3): res = self.readregister(conn, self.getdk(dev, 1),",
"[] self._isdetecting = False self._detection = {\"port\": [], \"saddr\":0, \"eaddr\":0,",
"unit in range(self._detection[\"saddr\"], self._detection[\"eaddr\"]): if self._isdetecting == False or self.isexecuting()",
"CmdCode.TIMED_CLOSE, {\"time\":10}) kdmate.writeblk(req) time.sleep(5) req = Request(201) req.setcommand(202, CmdCode.OFF, {})",
"registers. : \" + str(ex)) return None def detect(self): detected",
"wrong connection method. \" + str(opt['method']) if ret == False:",
"params = request.getparams() params[\"operation\"] = operation # need to convert",
"\" + str(opt['method']) if ret == False: self._logger.warn(msg) noti =",
"\"operation\"), \"time\" : (2, \"int\"), \"opentime\" : (1, \"short\"), \"closetime\"",
"+ str(unit) noti = Notice(None, NotiCode.DETECT_NODE_STARTED, devid=tempid) # Detection Started",
"== ProtoVer.TTA_1: info = self.detect_node(conn, unit, res.registers) self._logger.info (\"Found a",
"servsoc.accept() self._logger.info(\"client connected from \" + str(address)) for tmp in",
"or res.isError(): noti = Notice(None, NotiCode.DETECT_NO_NODE, devid=tempid) # Detection Started",
"= Mate ({}, [], \"1\", None) kdmate.start (mate.writeblk) print \"mate",
"ACTNODE = 2 INTNODE = 3 NUTNODE = 4 class",
"def readsensornodeinfo(self, node): ret = self.readnodeinfo(node) for dev in node['children']:",
"is None: noti = Notice(None, NotiCode.DETECT_WRONG_DEVICE, devid=tempid) # fail to",
": (3,40241,[\"opid\",\"status\"],45041,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"} ] }] }] \"\"\" if isnutri:",
"canceled else: noti = Notice(None, NotiCode.RTU_CONNECTED) # detection is canceled",
"params: val = params[key] else: self._logger.warn(\"Wrong Keyword : \" +",
": \"113\", \"dk\" : '[1,40311,[\"value\",\"status\"]]', \"dt\": \"sen\"} ]} ]} ]",
"KSX3267MateV2._KEYWORDS[key][1] == \"float\": registers.extend(struct.unpack('HH', struct.pack('f', val))) #else: # self._logger.warn(\"This param",
"\"JND2\", \"dt\": \"gw\", \"children\" : [ # { # \"id\"",
"\"nd\", \"children\" : [ {\"id\" : \"202\", \"dk\" : '[2,40202,[\"opid\",\"status\",\"state-hold-time\",\"remain-time\"],40206,[\"operation\",\"opid\",\"time\"]]',",
": '[1,210,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"103\", \"dk\" : '[1,220,[\"value\",\"status\"]]',",
"= flag self._detection[\"opid\"] = opid def startdetection(self, params, opid): if",
"val = values[idx] ret[nm] = val idx = idx +",
"Request(None) req.setcommand(\"1\", CmdCode.CANCEL_DETECT, {}) print \"=======================================#4\" kdmate.writeblk(req) print \"=======================================#4\" time.sleep(10)",
"\"302\", \"dk\" : (3,40211,[\"opid\",\"status\"],45011,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"}, {\"id\" : \"303\", \"dk\"",
"\"111\", \"dk\" : '[1,40291,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"112\", \"dk\"",
"{ \"id\" : \"201\", \"dk\" : '[2,40201,[\"status\"],45001,[\"operation\",\"opid\"]]', \"dt\": \"nd\", \"children\"",
"\"101\", \"dk\" : '[1,40201,[\"status\"],45001,[\"operation\",\"opid\"]]', \"dt\": \"nd\", \"children\" : [ {\"id\"",
"(1, \"short\"), \"position\" : (1, \"short\"), \"remain-time\" : (2, \"int\"),",
"\"] exception : \" + str(ex)) tmp[\"status\"] = 5 #",
"close(self): for port in self._conn.keys(): self.closeone(port) super(KSX3267MateV2, self).close() def readmsg(self):",
"used for this operation # However, the register should be",
"Thread, Lock from mate import Mate, ThreadMate, DevType from mblock",
"hashlib import json from enum import IntEnum from threading import",
"False: self._logger.warn(\"The message is not request. \" + str(blk.gettype())) return",
"Request(None) req.setcommand(\"1\", CmdCode.CANCEL_DETECT, {}) print \"=======================================#2\" kdmate.writeblk(req) print \"=======================================#2\" time.sleep(1)",
"= socket.socket(socket.AF_INET, socket.SOCK_STREAM) servsoc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) servsoc.bind((opt['host'], opt['port'])) servsoc.listen(1) self._logger.info(\"listen",
"kdmate.writeblk(req) print \"=======================================#4\" time.sleep(10) req = Request(201) req.setcommand(202, CmdCode.OPEN, {})",
": '[1,40301,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"113\", \"dk\" : '[1,40311,[\"value\",\"status\"]]',",
"= KSX3267MateV2(opt, devinfo, \"1\", None) mate = Mate ({}, [],",
"1 ACTNODE = 2 INTNODE = 3 NUTNODE = 4",
": \"102\", \"dk\" : '[1,40202,[\"value\",\"status\"]]', \"dt\": \"sen\"}, # {\"id\" :",
"return conn.read_holding_registers(addr, count, unit=unit) except Exception as ex: self._logger.warn(\"fail to",
"0: self.sendnoticeforactuatorstatus(ret) ret[\"act\"] = {} self.sendnoticeforactuatorstatus(ret) def sendobservation(self, ndinfo): if",
"obsblk.setobservation(devid, 0, StatCode(info[\"status\"])) self.writecb(obsblk) def sendnoticeforactuatorstatus(self, ndinfo): blk = Notice(ndinfo[\"id\"],",
"self.readactinfo(node, dev) if msg is None: self._logger.warn(\"Fail to read dev",
"except Exception as ex: self._logger.warn(\"fail to read holding registers. :",
"# Copyright (c) 2018 JiNong, Inc. # All right reserved.",
"= ModbusTcpClient(opt['host'], port=opt['port'], timeout=self._timeout) ret = conn.connect() msg = \"failed",
"is not request. \" + str(blk.gettype())) return False response =",
"None or res.isError(): self._logger.warn(\"Fail to get devices from \" +",
"= self._devinfo.finddevbyid(blk.getnodeid()) dev = self._devinfo.finddevbyid(blk.getdevid()) if blk.getdevid() == self._coupleid: params",
"+ str(opt['method']) if ret == False: self._logger.warn(msg) noti = Notice(None,",
"# import struct import time import socket import select import",
"request, node): gw = self._devinfo.findgateway(request.getnodeid()) unit = self.getdk(dev, 0) operation",
"stop(self): super(KSX3267MateV2, self).stop() return True def getsize(self, lst): size =0",
"in ndinfo[\"act\"].iteritems(): blk.setcontent(devid, info) self.writecb(blk) def start(self, writecb): super(KSX3267MateV2, self).start(writecb)",
": \"JND2\", \"dt\": \"gw\", \"children\" : [ # { #",
"msg = \"failed to connect with rtu\" code = NotiCode.RTU_CONNECTED",
"in self._tempthd: if tmp[\"port\"] == opt[\"port\"]: conn = ModbusTcpClient(timeout=self._timeout) conn.socket",
"{} if self._detection[\"port\"] is not None and port not in",
"None) print \"=======================================#1\" kdmate.writeblk(req) print \"=======================================#1\" \"\"\" time.sleep(1) req =",
"info: ret[\"sen\"][dev[\"id\"]] = info #else: # self._logger.warn(\"fail to read sensor",
"to get devices from \" + str(unit) + \" \"",
"info is None: noti = Notice(None, NotiCode.DETECT_WRONG_DEVICE, devid=tempid) # fail",
": \"109\", \"dk\" : '[1,40271,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"110\",",
"{\"id\" : \"111\", \"dk\" : '[1,40291,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" :",
"self.readnodeinfo(node) i = 1 for dev in node['children']: if DevType.issensor(dev[\"dt\"])",
"\"short\"), \"EC\": (2, \"float\"), \"pH\": (2, \"float\"), \"on-sec\" : (1,",
"conn) detected[port] = info self._logger.info (\"finished to detect devices :",
"DevType.ispropercommand(dev['dt'], cmd) is False: self._logger.warn(\"The request is not proper. \"",
"\"dk\" : '[1,40271,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"109\", \"dk\" :",
": \"107\", \"dk\" : '[1,40261,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"109\",",
"port): self._conn[port].close() def close(self): for port in self._conn.keys(): self.closeone(port) super(KSX3267MateV2,",
"return detected #mrchoi87 #for unit in range(self._detection[\"saddr\"], 12): for unit",
"StatCode.ERROR.value # obsblk.setobservation(devid, 0, StatCode(info[\"status\"])) self.writecb(obsblk) def sendnoticeforactuatorstatus(self, ndinfo): blk",
"tmp[\"thd\"].join() def connectone(self, opt): ret = False conn = None",
"conn, addr, count, unit): print \"....... before lock for read\"",
"'rtu': conn = ModbusSerialClient(method='rtu', port=opt['port'], timeout=self._timeout, baudrate=opt['baudrate']) ret = conn.connect()",
"= Request(None) req.setcommand(\"1\", CmdCode.DETECT_DEVICE, None) print \"=======================================#1\" kdmate.writeblk(req) print \"=======================================#1\"",
"#{\"id\" : \"109\", \"dk\" : '[1,40281,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" :",
"code = ResCode.FAIL_NOT_PROPER_COMMAND elif DevType.isactuator(dev['dt']) or DevType.isnode(dev['dt']): # modbus code",
"KSX3267MateV2._DEVINFOREG, 6, unit) if res is None or res.isError(): continue",
"port=opt['port'], timeout=self._timeout, baudrate=opt['baudrate']) ret = conn.connect() msg = \"failed to",
"res is None or res.isError(): continue if len(res.registers) != 6:",
"req.setcommand(202, CmdCode.TIMED_CLOSE, {\"time\":10}) kdmate.writeblk(req) time.sleep(5) req = Request(201) req.setcommand(202, CmdCode.OFF,",
"for devid, info in ndinfo[\"sen\"].iteritems(): if StatCode.has_value(info[\"status\"]) == False: info[\"status\"]",
"return True #if code == ResCode.OK else False def parseregisters(self,",
": \"109\", \"dk\" : '[1,40281,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"110\",",
"str(res)) return None if len(res.registers) != size: self._logger.info(\"retry to get",
"need to convert by case properparams = CmdCode.getparams(operation) + [\"operation\",",
"10 KS_X_3267_2018 = 101 TTA_1 = 201 class KSX3267MateV2(ThreadMate): _SLEEP",
"== False or self.isexecuting() == False: self._logger.info(\"Total detection is canceled.\")",
"values[idx], values[idx+1]))[0] else: val = values[idx] ret[nm] = val idx",
"\"on-sec\"]]', \"dt\": \"nutrient-supply/level1\"}, {\"id\" : \"103\", \"dk\" : '[1,40221,[\"value\",\"status\"]]', \"dt\":",
"#{\"id\" : \"206\", \"dk\" : (2,40251,[\"opid\",\"status\"],45051,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" :",
"time.sleep(5) req = Request(201) req.setcommand(202, CmdCode.OFF, {}) kdmate.writeblk(req) time.sleep(10) req",
"_SLEEP = 0.5 _VERSION = \"KSX3267_0.1\" _KEYWORDS = {\"value\" :",
"= ModbusSerialClient(method='rtu', port=opt['port'], timeout=self._timeout, baudrate=opt['baudrate']) ret = conn.connect() msg =",
"str(blk) + \", \" + str(dev)) code = ResCode.FAIL elif",
"6 \" + str(len(res.registers))) continue break if res is None",
"= Request(None) req.setcommand(\"1\", CmdCode.DETECT_DEVICE, None) print \"=======================================#3\" kdmate.writeblk(req) print \"=======================================#3\"",
"'[1,40291,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"112\", \"dk\" : '[1,40301,[\"value\",\"status\"]]', \"dt\":",
"read\" with self._lock: time.sleep(KSX3267MateV2._SLEEP) #mrchoi87 self._logger.info(\"read_holding_registers: \" + str(unit) +",
"self._tempthd = [] self._isdetecting = False self._detection = {\"port\": [],",
"info) self.writecb(noti) self.setdetection(False) def detectone(self, port, conn): detected = {}",
"def stop(self): super(KSX3267MateV2, self).stop() return True def getsize(self, lst): size",
"# \"id\" : \"101\", \"dk\" : '[1,201,[\"status\"],301,[\"operation\",\"opid\"]]', \"dt\": \"nd\", \"children\"",
"conn = self.connectone(opt) if conn: self._conn[opt[\"port\"][8:]] = conn super(KSX3267MateV2, self).connect()",
"device\") return ret def sendobs(self): for msg in self._msgq: if",
"self._detection[\"port\"] = None return ResCode.OK def readregister(self, conn, addr, count,",
"right reserved. # import struct import time import socket import",
"self._isdetecting == False or self.isexecuting() == False: self._logger.info(\"A port \"",
"a node else: noti = Notice(None, NotiCode.DETECT_NODE_DETECTED, devid=port, content={unit :",
"= self.readnodeinfo(node) for dev in node['children']: if DevType.issensor(dev[\"dt\"]) == False:",
"\"sen\"} # ] # } ] }] \"\"\" }, {",
"\"act/retractable/level0\"}, {\"id\" : \"304\", \"dk\" : (3,40231,[\"opid\",\"status\"],45031,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"}, {\"id\"",
"return True def getsize(self, lst): size =0 for k in",
"def startdetection(self, params, opid): if self._detection[\"opid\"] != 0: self._logger.info(\"detection is",
"\" + str(port) + \" detection is canceled.\") break tempid",
"\"sen\"}, #{\"id\" : \"203\", \"dk\" : (2,40221,[\"opid\",\"status\"],45021,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\"",
"\"dt\": \"sen\"}, {\"id\" : \"105\", \"dk\" : '[1,40241,[\"value\",\"status\"]]', \"dt\": \"sen\"},",
"\"act/retractable/level1\"}, {\"id\" : \"203\", \"dk\" : '[2,40216,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\"",
"is False: self._logger.warn(\"The message is not request. \" + str(blk.gettype()))",
"def processrequest(self, dev, request, node): gw = self._devinfo.findgateway(request.getnodeid()) unit =",
"\"dt\": \"sen\"}, #{\"id\" : \"104\", \"dk\" : '[1,40208,[\"value\",\"status\"]]', \"dt\": \"sen\"},",
"NotiCode.RTU_FAILED_CONNECTION elif opt['method'] == 'tcpc': conn = ModbusTcpClient(opt['host'], port=opt['port'], timeout=self._timeout)",
"({}, [], \"1\", None) kdmate.start (mate.writeblk) print \"mate started\" time.sleep(10)",
"\"\", \"dt\": \"gw\", \"children\" : [{ \"id\" : \"101\", \"dk\"",
"#{\"id\" : \"108\", \"dk\" : '[1,40271,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" :",
"ResCode.FAIL_TO_WRITE msg = self.readactinfo(node, dev) if msg is None: self._logger.warn(\"Fail",
"print \"....... befor lock for write\" with self._lock: time.sleep(KSX3267MateV2._SLEEP) print",
"= 10 # connected executing = False except Exception as",
"if msg is None: continue self.sendobservation(msg) def sendnoti(self): for gw",
"registers): print \"detect_node\", unit, registers compcode = registers[0] nodecode =",
"size: return self.parseregisters(self.getdk(dev, 2), res.registers) else: self._logger.info(\"retry to get data",
"= params['port'] else: self._detection[\"saddr\"] = 1 self._detection[\"eaddr\"] = 12 self._detection[\"port\"]",
"+ str(blk.gettype())) return False response = Response(blk) cmd = blk.getcommand()",
"= conn.connect() msg = \"failed to connect with tcp\" code",
"\"dt\": \"sen\"}, #{\"id\" : \"103\", \"dk\" : '[1,220,[\"value\",\"status\"]]', \"dt\": \"sen\"}",
"\"207\", \"dk\" : (2,40261,[\"opid\",\"status\"],45061,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"208\", \"dk\"",
"or self.isexecuting() == False: self._logger.info(\"A port \" + str(port) +",
"None info = None res = None for _ in",
"'method': 'rtu', 'port' : '/dev/ttyJND2', 'baudrate' : 9600, 'timeout': 5",
"is canceled noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) self.writecb(noti) self.setdetection(False) return ResCode.OK def _listen(self,",
"device type if res.registers[3] == ProtoVer.KS_X_3267_2020 or res.registers[3] == ProtoVer.KS_X_3267_2018:",
"(1, \"short\"), \"remain-time\" : (2, \"int\"), \"control\": (1, \"control\"), \"area\"",
"(mate.writeblk) print \"mate started\" time.sleep(10) req = Request(None) req.setcommand(\"1\", CmdCode.DETECT_DEVICE,",
"operation. \" + str(params['operation']) + \", \" + str(key)) #",
"opt['method'] == 'rtu': conn = ModbusSerialClient(method='rtu', port=opt['port'], timeout=self._timeout, baudrate=opt['baudrate']) ret",
"True while executing: self._logger.info(\"waiting a client~\") rsoc, wsoc, esoc =",
"__init__(self, option, devinfo, coupleid, logger): super(KSX3267MateV2, self).__init__(option, devinfo, coupleid, logger)",
"= operation # need to convert by case params[\"opid\"] =",
": \" + str(code)) elif DevType.isgateway(dev['dt']): self._logger.info(\"Gateway does not receive",
"\" \" + str(res)) # continue else: if len(res.registers) ==",
"tmp[\"port\"] == opt[\"port\"]: conn = ModbusTcpClient(timeout=self._timeout) conn.socket = clisoc self._conn[opt[\"port\"]]",
"1: registers.append(val) elif KSX3267MateV2._KEYWORDS[key][1] == \"int\": registers.extend(struct.unpack('HH', struct.pack('i', val))) elif",
"] # } ] }] \"\"\" }, { \"id\" :",
"size print \"parsed\", ret return ret def readinfofromdev(self, conn, dev):",
"4): if key not in properparams: # key param is",
"since size of data is not matched. 6 \" +",
"0: self._logger.info(\"detection is processing.... so this command would be ignored.\")",
"if ret else NotiCode.RTU_FAILED_CONNECTION conn = None else: msg =",
"self.detect_node(conn, unit, res.registers) self._logger.info (\"Found a nutrient system : \"",
"def sendnoti(self): for gw in self._devinfo: for node in gw[\"children\"]:",
"dk[idx] def setdetection(self, flag, opid=0): self._isdetecting = flag self._detection[\"opid\"] =",
"should be filled. val = 0 elif key in params:",
"elif res.registers[1] == NodeType.NUTNODE: if res.registers[3] == ProtoVer.TTA_1: info =",
"read holding registers. : \" + str(ex)) return None def",
"self.readregister(conn, self.getdk(dev, 1), size, self.getdk(dev, 0)) if res is None:",
"elif key in params: val = params[key] else: self._logger.warn(\"Wrong Keyword",
": (2,40271,[\"opid\",\"status\"],45071,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"209\", \"dk\" : (2,40281,[\"opid\",\"status\"],45081,[\"operation\",\"opid\"]),",
"\"dk\" : '[1,41020,[\"value\",\"status\"]]', \"dt\": \"sen\"} # {\"id\" : \"102\", \"dk\"",
"\"sen\"}, {\"id\" : \"113\", \"dk\" : '[1,40311,[\"value\",\"status\"]]', \"dt\": \"sen\"} ]}",
"StatCode.has_value(info[\"status\"]) == False: info[\"status\"] = StatCode.ERROR.value obsblk.setobservation(devid, info[\"value\"], StatCode(info[\"status\"])) #",
"+ str(node)) return ret def readsensornodeinfo(self, node): ret = self.readnodeinfo(node)",
"[ #{\"id\" : \"102\", \"dk\" : '[1,41010,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\"",
"dk = json.loads(dev[\"dk\"]) return dk[idx] def setdetection(self, flag, opid=0): self._isdetecting",
"6, unit) if res is None or res.isError(): continue if",
"\"=======================================#1\" kdmate.writeblk(req) print \"=======================================#1\" \"\"\" time.sleep(1) req = Request(None) req.setcommand(\"1\",",
"# obsblk.setobservation(devid, 0, StatCode(info[\"status\"])) self.writecb(obsblk) def sendnoticeforactuatorstatus(self, ndinfo): blk =",
"{} self._tempthd = [] self._isdetecting = False self._detection = {\"port\":",
"self._conn.iteritems(): if self._isdetecting == False or self.isexecuting() == False: self._logger.info(\"Total",
"conn in self._conn.iteritems(): if self._isdetecting == False or self.isexecuting() ==",
"info = self.detect_node(conn, unit, res.registers) self._logger.info (\"Found a node :",
"option else option[\"timeout\"] self._conn = {} self._tempthd = [] self._isdetecting",
"properparams = CmdCode.getparams(operation) + [\"operation\", \"opid\"] registers = [] for",
"for write\", self.getdk(dev, 3), registers res = self._conn[gw[\"dk\"]].write_registers(self.getdk(dev, 3), registers,",
"to get status from \" + str(dev['dk'])) # break elif",
"0, \"port\":opt['port']} self._tempthd.append(tmp) tmp[\"thd\"].start() def checktempthreads(self): for tmp in self._tempthd:",
"== \"float\": registers.extend(struct.unpack('HH', struct.pack('f', val))) #else: # self._logger.warn(\"This param is",
": \"102\", \"dk\" : '[1,40211,[\"control\",\"status\",\"area\",\"alert\",\"opid\"],45001,[\"operation\", \"opid\", \"control\",\"EC\",\"pH\", \"start-area\", \"stop-area\", \"on-sec\"]]',",
"from \" + str(unit) + \" \" + str(res)) return",
"not matched. \" + str(size) + \" \" + str(len(res.registers)))",
"# ] # } ] }] \"\"\" }, { \"id\"",
"info in ndinfo[\"sen\"].iteritems(): if StatCode.has_value(info[\"status\"]) == False: info[\"status\"] = StatCode.ERROR.value",
"(c) 2018 JiNong, Inc. # All right reserved. # import",
"Started.\") def detect_node(self, conn, unit, registers): print \"detect_node\", unit, registers",
"KSX3267MateV2(opt, devinfo, \"1\", None) mate = Mate ({}, [], \"1\",",
": '[1,40205,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"104\", \"dk\" : '[1,40208,[\"value\",\"status\"]]',",
"self._devinfo: for node in gw[\"children\"]: ret = self.readnodeinfo(node) i =",
"\"int\"), \"control\": (1, \"control\"), \"area\" : (1, \"short\"), \"alert\" :",
"def setdetection(self, flag, opid=0): self._isdetecting = flag self._detection[\"opid\"] = opid",
"to detect device\" code = self.canceldetection(params) else: self._logger.warn(\"Unknown Error. \"",
"tmp[\"status\"] > 2: tmp[\"thd\"].stop() tmp[\"thd\"].join() def connectone(self, opt): ret =",
": (2,40261,[\"opid\",\"status\"],45061,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"208\", \"dk\" : (2,40271,[\"opid\",\"status\"],45071,[\"operation\",\"opid\"]),",
"\"control\"), \"area\" : (1, \"short\"), \"alert\" : (1, \"alert\"), \"hold-time\"",
"else: self._logger.warn(\"fail to read node info : \" + str(node))",
"= { 'conn' : [{ 'method': 'rtu', 'port' : '/dev/ttyJND2',",
"{\"id\" : \"105\", \"dk\" : '[1,40241,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" :",
"[ {\"id\" : \"302\", \"dk\" : (3,40211,[\"opid\",\"status\"],45011,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"}, {\"id\"",
"import Thread, Lock from mate import Mate, ThreadMate, DevType from",
"elif DevType.isgateway(dev['dt']): self._logger.info(\"Gateway does not receive a request\") code =",
"Thread(target=self._listen, args=(opt)), \"status\": 0, \"port\":opt['port']} self._tempthd.append(tmp) tmp[\"thd\"].start() def checktempthreads(self): for",
"a request\") code = ResCode.FAIL else: self._logger.warn(\"Unknown Error. \" +",
"= info noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) print \"noti\", noti.stringify() self.writecb(noti) time.sleep(0.1) return",
"self._detection[\"eaddr\"]): if self._isdetecting == False or self.isexecuting() == False: self._logger.info(\"A",
"== False: self._logger.info(\"A port \" + str(port) + \" detection",
": (1, \"short\"), \"stop-area\": (1, \"short\"), \"epoch\" : (2, \"int\"),",
"param is needed for this operation. \" + str(params['operation']) +",
": '[1,40241,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"106\", \"dk\" : '[1,40251,[\"value\",\"status\"]]',",
"\"dt\": \"nd\", \"children\" : [ {\"id\" : \"302\", \"dk\" :",
"(2, \"float\"), \"vint\" : (2, \"int\")} _DEVINFOREG = 2 _DEVCODEREG",
"+ str(code)) elif DevType.isgateway(dev['dt']): self._logger.info(\"Gateway does not receive a request\")",
"exception : \" + str(ex)) tmp[\"status\"] = 5 # error",
"getsize(self, lst): size =0 for k in lst: if k",
"'[1,40291,[\"value\",\"status\"]]', \"dt\": \"sen\"} # ] # } ] }] \"\"\"",
"\"dk\" : '[1,40202,[\"value\",\"status\"]]', \"dt\": \"sen\"}, # {\"id\" : \"103\", \"dk\"",
"= self.canceldetection(params) else: self._logger.warn(\"Unknown Error. \" + str(blk) + \",",
"\"ratio\": (1, \"short\"), \"position\" : (1, \"short\"), \"remain-time\" : (2,",
"keyword : \" + str(k)) return -1 return size if",
"str(params['operation']) + \", \" + str(key)) # return ResCode.FAIL_WRONG_KEYWORD print",
"= StatCode.ERROR.value # obsblk.setobservation(devid, 0, StatCode(info[\"status\"])) self.writecb(obsblk) def sendnoticeforactuatorstatus(self, ndinfo):",
"parseregisters(self, names, values): idx = 0 ret = {} for",
"= Notice(None, NotiCode.RTU_FAILED_CONNECTION) # detection is canceled else: noti =",
"#{\"id\" : \"207\", \"dk\" : (2,40261,[\"opid\",\"status\"],45061,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" :",
"'timeout': 5 }] } nutriinfo = [{ \"id\" : \"1\",",
": '[1,40261,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"108\", \"dk\" : '[1,40271,[\"value\",\"status\"]]',",
"kdmate.writeblk(req) print \"=======================================#2\" time.sleep(1) req = Request(None) req.setcommand(\"1\", CmdCode.DETECT_DEVICE, None)",
"+ str(ex)) return None def detect(self): detected = {} for",
"is None: self._logger.warn(\"There is no device. \" + str(blk.getdevid())) code",
"= self.processrequest(dev, blk, nd) self._logger.info(\"Actuator processed : \" + str(code))",
"'[1,40205,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"104\", \"dk\" : '[1,40208,[\"value\",\"status\"]]', \"dt\":",
"Notice(None, NotiCode.DETECT_NO_NODE, devid=tempid) # Detection Started self._logger.info (\"Fail to get",
"NotiCode.TCP_CONNECTED if ret else NotiCode.RTU_FAILED_CONNECTION elif opt['method'] == 'tcpcs': self._logger.info(\"It",
"tmp in self._tempthd: if tmp[\"port\"] == opt[\"port\"]: conn = ModbusTcpClient(timeout=self._timeout)",
"\"start-area\", \"stop-area\", \"on-sec\"]]', \"dt\": \"nutrient-supply/level1\"}, {\"id\" : \"103\", \"dk\" :",
"\"205\", \"dk\" : (2,40241,[\"opid\",\"status\"],45041,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"206\", \"dk\"",
"self._devinfo.finddevbyid(blk.getnodeid()) dev = self._devinfo.finddevbyid(blk.getdevid()) if blk.getdevid() == self._coupleid: params =",
"\"=======================================#2\" time.sleep(1) req = Request(None) req.setcommand(\"1\", CmdCode.DETECT_DEVICE, None) print \"=======================================#3\"",
"connect with tcp\" code = NotiCode.TCP_WAITING if ret else NotiCode.RTU_FAILED_CONNECTION",
"self.setdetection(True, opid) if params: self._detection[\"saddr\"] = params['saddr'] self._detection[\"eaddr\"] = params['eaddr']",
"ResCode.OK def writeblk(self, blk): print \"received message\", blk.getdevid(), self._coupleid if",
"ndinfo[\"act\"].iteritems(): blk.setcontent(devid, info) self.writecb(blk) def start(self, writecb): super(KSX3267MateV2, self).start(writecb) return",
"else NotiCode.RTU_FAILED_CONNECTION elif opt['method'] == 'tcpc': conn = ModbusTcpClient(opt['host'], port=opt['port'],",
"\" \" + str(addr) + \" \" + str(count)) print",
"\"dt\": \"act/retractable/level0\"}, {\"id\" : \"305\", \"dk\" : (3,40241,[\"opid\",\"status\"],45041,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"}",
"+ \" \" + str(res)) # continue else: if len(res.registers)",
"NUTNODE = 4 class ProtoVer(IntEnum): KS_X_3267_2020 = 10 KS_X_3267_2018 =",
"detected[port] = info self._logger.info (\"finished to detect devices : \"",
"continue to read other device\") return ret def readactinfo(self, node,",
"\"act/switch/level0\"}, #{\"id\" : \"208\", \"dk\" : (2,40271,[\"opid\",\"status\"],45071,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\"",
"act) if info: ret[\"act\"][act[\"id\"]] = info else: self._logger.warn(\"fail to read",
"is False: self._logger.warn(\"The request is not proper. \" + str(cmd)",
": [ {\"id\" : \"202\", \"dk\" : '[2,40202,[\"opid\",\"status\",\"state-hold-time\",\"remain-time\"],40206,[\"operation\",\"opid\",\"time\"]]', \"dt\": \"act/retractable/level1\"},",
"res.isError(): self._logger.warn(\"Fail to get devices from \" + str(unit) +",
"def checktempthreads(self): for tmp in self._tempthd: if tmp[\"status\"] > 2:",
"self.readregister(conn, KSX3267MateV2._DEVCODEREG, size, unit) if res is None or res.isError():",
"is None or res.isError(): continue if len(res.registers) != 6: self._logger.info(\"retry",
"if ret else NotiCode.RTU_FAILED_CONNECTION elif opt['method'] == 'tcpc': conn =",
"= val idx = idx + size print \"parsed\", ret",
": '[1,40208,[\"value\",\"status\"]]', \"dt\": \"sen\"}, # {\"id\" : \"105\", \"dk\" :",
"\" + str(len(res.registers))) continue return {\"compcode\" : compcode, \"nodecode\" :",
"== \"float\": val = struct.unpack('f', struct.pack('HH', values[idx], values[idx+1]))[0] elif vtype",
": [{ 'method': 'rtu', 'port' : '/dev/ttyJND2', 'baudrate' : 9600,",
"+ str(addr) + \" \" + str(count)) print \"read register\",",
"(3,40211,[\"opid\",\"status\"],45011,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"}, {\"id\" : \"303\", \"dk\" : (3,40221,[\"opid\",\"status\"],45021,[\"operation\",\"opid\"]), \"dt\":",
"\"nd\", \"children\" : [ {\"id\" : \"102\", \"dk\" : '[1,40211,[\"control\",\"status\",\"area\",\"alert\",\"opid\"],45001,[\"operation\",",
"{\"id\" : \"202\", \"dk\" : '[2,40202,[\"opid\",\"status\",\"state-hold-time\",\"remain-time\"],40206,[\"operation\",\"opid\",\"time\"]]', \"dt\": \"act/retractable/level1\"}, {\"id\" :",
"detected[unit] = info noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) print \"noti\", noti.stringify() self.writecb(noti) time.sleep(0.1)",
"res is None or res.isError(): self._logger.warn(\"Fail to get devices from",
"\"short\"), \"epoch\" : (2, \"int\"), \"vfloat\": (2, \"float\"), \"vint\" :",
"\"opid\":0} #self._nodes = self._devinfo.getgw()[\"children\"] self._lock = Lock() self._logger.info(\"KSX3267MateV2 Started.\") def",
"print \"=======================================#1\" \"\"\" time.sleep(1) req = Request(None) req.setcommand(\"1\", CmdCode.CANCEL_DETECT, {})",
"vtype == \"int\": val = struct.unpack('i', struct.pack('HH', values[idx], values[idx+1]))[0] else:",
"9600, 'timeout': 5 }] } nutriinfo = [{ \"id\" :",
"= Observation(ndinfo[\"id\"]) obsblk.setobservation(ndinfo[\"id\"], 0, StatCode(ndinfo[\"nd\"][\"status\"])) for devid, info in ndinfo[\"sen\"].iteritems():",
"INTNODE = 3 NUTNODE = 4 class ProtoVer(IntEnum): KS_X_3267_2020 =",
"= Notice(None, NotiCode.DETECT_NODE_DETECTED, devid=port, content={unit : info}) # found a",
": \"206\", \"dk\" : (2,40251,[\"opid\",\"status\"],45051,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"207\",",
"# return ResCode.FAIL_WRONG_KEYWORD print \"....... befor lock for write\" with",
"to read dev status.\") else: self.sendnoticeforactuatorstatus(msg) return ResCode.OK def writeblk(self,",
"socket.SO_REUSEADDR, 1) servsoc.bind((opt['host'], opt['port'])) servsoc.listen(1) self._logger.info(\"listen : \" + str(opt))",
"operation # However, the register should be filled. val =",
"\"201\", \"dk\" : '[2,40201,[\"status\"],45001,[\"operation\",\"opid\"]]', \"dt\": \"nd\", \"children\" : [ {\"id\"",
"None) else: kdmate = KSX3267MateV2(opt, devinfo, \"1\", None) mate =",
"NotiCode.DETECT_UNKNOWN_PROTOCOL_VER, devid=tempid) # unknown protocol version else: noti = Notice(unit,",
"= Notice(None, NotiCode.DETECT_NO_NODE, devid=tempid) # Detection Started self._logger.info (\"Fail to",
"else: noti = Notice(unit, NotiCode.DETECT_UNKNOWN_NODE, devid=tempid) # unknown device if",
"= Request(201) req.setcommand(202, CmdCode.OFF, {}) kdmate.writeblk(req) \"\"\" time.sleep(30) kdmate.stop() print",
"\"position\" : (1, \"short\"), \"remain-time\" : (2, \"int\"), \"control\": (1,",
": \"305\", \"dk\" : (3,40241,[\"opid\",\"status\"],45041,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"} ] }] }]",
"self.isexecuting() == False: self._logger.info(\"Total detection is canceled.\") break info =",
"\"dt\": \"sen\"}, # {\"id\" : \"103\", \"dk\" : '[1,40205,[\"value\",\"status\"]]', \"dt\":",
"(1, \"short\"), \"start-area\" : (1, \"short\"), \"stop-area\": (1, \"short\"), \"epoch\"",
"self.detect_node(conn, unit, res.registers) self._logger.info (\"Found a node : \" +",
"] }] \"\"\" }, { \"id\" : \"201\", \"dk\" :",
"= 12 self._detection[\"port\"] = None return ResCode.OK def readregister(self, conn,",
"\"int\": registers.extend(struct.unpack('HH', struct.pack('i', val))) elif KSX3267MateV2._KEYWORDS[key][1] == \"float\": registers.extend(struct.unpack('HH', struct.pack('f',",
"opt in self._option['conn']: conn = self.connectone(opt) if conn: self._conn[opt[\"port\"][8:]] =",
"device\" code = self.canceldetection(params) else: self._logger.warn(\"Unknown Error. \" + str(blk)",
"\"on-sec\" : (1, \"short\"), \"start-area\" : (1, \"short\"), \"stop-area\": (1,",
"idx = 0 ret = {} for nm in names:",
"1 for dev in node['children']: if DevType.issensor(dev[\"dt\"]) == False: info",
"is canceled self.writecb(noti) return conn def connect(self): ret = False",
"= self.readinfofromdev(ret[\"conn\"], dev) if info: ret[\"sen\"][dev[\"id\"]] = info #else: #",
"ndinfo[\"act\"].iteritems(): # if StatCode.has_value(info[\"status\"]) == False: # info[\"status\"] = StatCode.ERROR.value",
"= info else: self._logger.warn(\"fail to read actuator info : \"",
"continue if len(res.registers) != 6: self._logger.info(\"retry to get data since",
"rtu\" code = NotiCode.RTU_CONNECTED if ret else NotiCode.RTU_FAILED_CONNECTION elif opt['method']",
"sendnoticeforactuatorstatus(self, ndinfo): blk = Notice(ndinfo[\"id\"], NotiCode.ACTUATOR_STATUS, ndinfo[\"id\"], ndinfo[\"nd\"]) for devid,",
"\"sen\"}, {\"id\" : \"106\", \"dk\" : '[1,40251,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\"",
"(1, \"short\"), \"state-hold-time\" : (2, \"int\"), \"ratio\": (1, \"short\"), \"position\"",
"res.registers[3] == ProtoVer.KS_X_3267_2018: info = self.detect_node(conn, unit, res.registers) self._logger.info (\"Found",
"noti = Notice(None, NotiCode.DETECT_NODE_DETECTED, devid=port, content={unit : info}) # found",
"nd) self._logger.info(\"Actuator processed : \" + str(code)) elif DevType.isgateway(dev['dt']): self._logger.info(\"Gateway",
"in names: (size, vtype) = KSX3267MateV2._KEYWORDS[nm] if vtype == \"float\":",
"= json.loads(dev[\"dk\"]) return dk[idx] def setdetection(self, flag, opid=0): self._isdetecting =",
"# connected executing = False except Exception as ex: servsoc.close()",
"CmdCode.CANCEL_DETECT: print \"cancel to detect device\" code = self.canceldetection(params) else:",
"data is not matched. \" + str(size) + \" \"",
"\"dk\" : '[2,40201,[\"status\"],45001,[\"operation\",\"opid\"]]', \"dt\": \"nd\", \"children\" : [ {\"id\" :",
"!= 6: self._logger.info(\"retry to get data since size of data",
"self._devinfo.findgateway(node[\"id\"]) conn = self._conn[gw[\"dk\"]] ret[\"conn\"] = conn info = self.readinfofromdev(conn,",
"ret[\"act\"] = {} self.sendnoticeforactuatorstatus(ret) def sendobservation(self, ndinfo): if StatCode.has_value(ndinfo[\"nd\"][\"status\"]) ==",
"\"act/retractable/level0\"} ] }] }] \"\"\" if isnutri: kdmate = KSX3267MateV2(opt,",
"'[1,40201,[\"status\"],45001,[\"operation\",\"opid\"]]', \"dt\": \"nd\", \"children\" : [ #{\"id\" : \"102\", \"dk\"",
"coding: utf-8 -*- # # Copyright (c) 2018 JiNong, Inc.",
": \"208\", \"dk\" : (2,40271,[\"opid\",\"status\"],45071,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"209\",",
": {}, \"nd\" : {\"status\":StatCode.ERROR.value}} gw = self._devinfo.findgateway(node[\"id\"]) conn =",
"return detected def canceldetection(self, params): time.sleep(self._timeout) noti = Notice(None, NotiCode.DETECT_CANCELED)",
"else NotiCode.RTU_FAILED_CONNECTION elif opt['method'] == 'tcpcs': self._logger.info(\"It would wait for",
"#{\"id\" : \"204\", \"dk\" : (2,40231,[\"opid\",\"status\"],45031,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" :",
"\"dt\": \"act/retractable/level0\"}, {\"id\" : \"303\", \"dk\" : (3,40221,[\"opid\",\"status\"],45021,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"},",
"read other device\") return ret def sendobs(self): for msg in",
"servsoc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) servsoc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) servsoc.bind((opt['host'], opt['port'])) servsoc.listen(1)",
"None) mate = Mate ({}, [], \"1\", None) kdmate.start (mate.writeblk)",
"time.sleep(1) req = Request(None) req.setcommand(\"1\", CmdCode.CANCEL_DETECT, {}) print \"=======================================#4\" kdmate.writeblk(req)",
"detect devices : \" + str(detected)) noti = Notice(None, NotiCode.DETECT_FINISHED)",
"res.registers[1] in (NodeType.SENNODE, NodeType.ACTNODE, NodeType.INTNODE): # device type if res.registers[3]",
"# # Copyright (c) 2018 JiNong, Inc. # All right",
"0)) if res is None: self._logger.warn(\"fail to get status from",
"info : \" + str(act) + \" however continue to",
": '[1,40281,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"111\", \"dk\" : '[1,40291,[\"value\",\"status\"]]',",
"\"opid\"] registers = [] for key in self.getdk(dev, 4): if",
"ret def sendobs(self): for msg in self._msgq: if msg is",
"node : \" + str(unit) + \" \" + str(info))",
"\"children\" : [ {\"id\" : \"102\", \"dk\" : '[1,40211,[\"control\",\"status\",\"area\",\"alert\",\"opid\"],45001,[\"operation\", \"opid\",",
"self._logger.info(\"retry to get status from \" + str(dev['dk']) + \"",
"str(unit) + \" \" + str(res)) return None if len(res.registers)",
"no device. \" + str(blk.getdevid())) code = ResCode.FAIL_NO_DEVICE elif DevType.ispropercommand(dev['dt'],",
"unit, res.registers) self._logger.info (\"Found a nutrient system : \" +",
"'[2,40209,[\"opid\",\"status\",\"state-hold-time\",\"remain-time\"],40213,[\"operation\",\"opid\",\"time\"]]', \"dt\": \"act/retractable/level1\"}, {\"id\" : \"203\", \"dk\" : '[2,40216,[\"value\",\"status\"]]', \"dt\":",
"def _listen(self, opt): try: servsoc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) servsoc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,",
"JiNong, Inc. # All right reserved. # import struct import",
"self._option['conn']: conn = self.connectone(opt) if conn: self._conn[opt[\"port\"][8:]] = conn super(KSX3267MateV2,",
"dev is None: self._logger.warn(\"There is no device. \" + str(blk.getdevid()))",
"str(ex)) return None def detect(self): detected = {} for port,",
"!= size: self._logger.info(\"retry to get data since size of data",
"elif res.registers[1] in (NodeType.SENNODE, NodeType.ACTNODE, NodeType.INTNODE): # device type if",
"(2, \"int\"), \"control\": (1, \"control\"), \"area\" : (1, \"short\"), \"alert\"",
"connectone(self, opt): ret = False conn = None if opt['method']",
"in option else option[\"timeout\"] self._conn = {} self._tempthd = []",
": '[1,40291,[\"value\",\"status\"]]', \"dt\": \"sen\"} # ] # } ] }]",
": (3,40201,[\"opid\",\"status\"],45001,[\"operation\",\"opid\"]), \"dt\": \"nd\", \"children\" : [ {\"id\" : \"302\",",
"NotiCode.RTU_FAILED_CONNECTION) # detection is canceled else: noti = Notice(None, NotiCode.RTU_CONNECTED)",
"0) operation = request.getcommand() params = request.getparams() params[\"operation\"] = operation",
"KS_X_3267_2020 = 10 KS_X_3267_2018 = 101 TTA_1 = 201 class",
"size if __name__ == \"__main__\": isnutri = False opt =",
"\" + str(address)) for tmp in self._tempthd: if tmp[\"port\"] ==",
"\"101\", \"dk\" : '[1,40201,[\"status\"],45001,[\"operation\",\"opid\"]]', \"dt\": \"nd\", \"children\" : [ #{\"id\"",
"\" + str(cmd) + \" \" + str(dev['dt'])) code =",
"not in properparams: # key param is not used for",
"{\"id\" : \"103\", \"dk\" : '[1,40205,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" :",
"str(opt)) executing = True while executing: self._logger.info(\"waiting a client~\") rsoc,",
"Notice(unit, NotiCode.DETECT_UNKNOWN_NODE, devid=tempid) # unknown device if noti is None:",
"opt): tmp = {\"thd\" : Thread(target=self._listen, args=(opt)), \"status\": 0, \"port\":opt['port']}",
"for dev in node['children']: if DevType.issensor(dev[\"dt\"]) == False: info =",
"def readactinfo(self, node, act): ret = self.readnodeinfo(node) info = self.readinfofromdev(ret[\"conn\"],",
"msg = \"failed to connect with tcp\" code = NotiCode.TCP_CONNECTED",
"\"303\", \"dk\" : (3,40221,[\"opid\",\"status\"],45021,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"}, {\"id\" : \"304\", \"dk\"",
"params[\"operation\"] = operation # need to convert by case params[\"opid\"]",
"\", \" + str(key)) # return ResCode.FAIL_WRONG_KEYWORD print \"....... befor",
"'[2,40216,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"204\", \"dk\" : '[2,40219,[\"value\",\"status\"]]', \"dt\":",
"\"106\", \"dk\" : '[1,40251,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"107\", \"dk\"",
": (2, \"int\"), \"ratio\": (1, \"short\"), \"position\" : (1, \"short\"),",
"== 'tcpc': conn = ModbusTcpClient(opt['host'], port=opt['port'], timeout=self._timeout) ret = conn.connect()",
"False: info[\"status\"] = StatCode.ERROR.value obsblk.setobservation(devid, info[\"value\"], StatCode(info[\"status\"])) # do not",
"\"float\": val = struct.unpack('f', struct.pack('HH', values[idx], values[idx+1]))[0] elif vtype ==",
"self._tempthd: if tmp[\"status\"] > 2: tmp[\"thd\"].stop() tmp[\"thd\"].join() def connectone(self, opt):",
"ret = self.readnodeinfo(node) i = 1 for dev in node['children']:",
"self._logger.warn(\"wrong keyword : \" + str(k)) return -1 return size",
"get status from \" + str(dev['dk']) + \" \" +",
"connection method. \" + str(opt['method']) if ret == False: self._logger.warn(msg)",
"if KSX3267MateV2._KEYWORDS[key][0] == 1: registers.append(val) elif KSX3267MateV2._KEYWORDS[key][1] == \"int\": registers.extend(struct.unpack('HH',",
"_listen(self, opt): try: servsoc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) servsoc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)",
"self.sendnoticeforactuatorstatus(msg) return ResCode.OK def writeblk(self, blk): print \"received message\", blk.getdevid(),",
"\" + str(dev)) code = ResCode.FAIL response.setresult(code) self._logger.info(\"write response: \"",
"vtype) = KSX3267MateV2._KEYWORDS[nm] if vtype == \"float\": val = struct.unpack('f',",
"#{\"id\" : \"110\", \"dk\" : '[1,40291,[\"value\",\"status\"]]', \"dt\": \"sen\"} # ]",
"str(dev) + \",\" + str(res) + \":\" + str(request)) return",
"[] for gw in self._devinfo: for nd in gw[\"children\"]: self._msgq.append(self.readsensornodeinfo(nd))",
"info #else: # self._logger.warn(\"fail to read sensor info : \"",
"for nd in gw[\"children\"]: self._msgq.append(self.readsensornodeinfo(nd)) if self._isdetecting: self.detect() self.checktempthreads() def",
"req = Request(201) req.setcommand(202, CmdCode.OFF, {}) kdmate.writeblk(req) \"\"\" time.sleep(30) kdmate.stop()",
"threading import Thread, Lock from mate import Mate, ThreadMate, DevType",
"DevType.isgateway(dev['dt']): self._logger.info(\"Gateway does not receive a request\") code = ResCode.FAIL",
"detectone(self, port, conn): detected = {} if self._detection[\"port\"] is not",
"return ret def sendobs(self): for msg in self._msgq: if msg",
"gw = self._devinfo.findgateway(request.getnodeid()) unit = self.getdk(dev, 0) operation = request.getcommand()",
"'[1,40261,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"109\", \"dk\" : '[1,40271,[\"value\",\"status\"]]', \"dt\":",
"else: noti = Notice(None, NotiCode.DETECT_UNKNOWN_PROTOCOL_VER, devid=tempid) # unknown protocol version",
": '[1,201,[\"status\"],301,[\"operation\",\"opid\"]]', \"dt\": \"nd\", \"children\" : [ #{\"id\" : \"102\",",
"\"dk\" : (3,40241,[\"opid\",\"status\"],45041,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"} ] }] }] \"\"\" if",
"to get information from a node : \" + str(unit)",
"in self._devinfo: for nd in gw[\"children\"]: self._msgq.append(self.readsensornodeinfo(nd)) if self._isdetecting: self.detect()",
"kdmate = KSX3267MateV2(opt, devinfo, \"1\", None) mate = Mate ({},",
"else: self.sendnoticeforactuatorstatus(msg) return ResCode.OK def writeblk(self, blk): print \"received message\",",
"KSX3267MateV2._KEYWORDS[nm] if vtype == \"float\": val = struct.unpack('f', struct.pack('HH', values[idx],",
"val idx = idx + size print \"parsed\", ret return",
"= StatCode.ERROR.value obsblk.setobservation(devid, info[\"value\"], StatCode(info[\"status\"])) # do not send observation",
"# info[\"status\"] = StatCode.ERROR.value # obsblk.setobservation(devid, 0, StatCode(info[\"status\"])) self.writecb(obsblk) def",
"registers compcode = registers[0] nodecode = registers[2] size = registers[4]",
"ModbusSerialClient from pymodbus.client.sync import ModbusTcpClient class NodeType(IntEnum): SENNODE = 1",
"for tmp in self._tempthd: if tmp[\"status\"] > 2: tmp[\"thd\"].stop() tmp[\"thd\"].join()",
"if info: ret[\"act\"][dev[\"id\"]] = info i = i + 1",
"rsoc, wsoc, esoc = select.select([servsoc], [], [], 10) for sock",
"time.sleep(10) req = Request(201) req.setcommand(202, CmdCode.TIMED_OPEN, {\"time\":10}) kdmate.writeblk(req) time.sleep(15) req",
"= conn info = self.readinfofromdev(conn, node) if info: ret[\"nd\"] =",
"+ \" \" + str(dev['dt'])) code = ResCode.FAIL_NOT_PROPER_COMMAND elif DevType.isactuator(dev['dt'])",
"while executing: self._logger.info(\"waiting a client~\") rsoc, wsoc, esoc = select.select([servsoc],",
"devinfo = [{ \"id\" : \"1\", \"dk\" : \"JND2\", \"dt\":",
"node): ret = {\"id\" : node[\"id\"], \"sen\" : {}, \"act\"",
"\"detect device\" code = self.startdetection(params, blk.getopid()) elif cmd == CmdCode.CANCEL_DETECT:",
"registers[2] size = registers[4] while True: res = self.readregister(conn, KSX3267MateV2._DEVCODEREG,",
"to read other device\") return ret def readactinfo(self, node, act):",
"is canceled else: noti = Notice(None, NotiCode.RTU_CONNECTED) # detection is",
"a wrong connection method. \" + str(opt['method']) if ret ==",
"gw in self._devinfo: for node in gw[\"children\"]: ret = self.readnodeinfo(node)",
"= \"KSX3267_0.1\" _KEYWORDS = {\"value\" : (2, \"float\"), \"status\" :",
"== ProtoVer.KS_X_3267_2018: info = self.detect_node(conn, unit, res.registers) self._logger.info (\"Found a",
"Observation(ndinfo[\"id\"]) obsblk.setobservation(ndinfo[\"id\"], 0, StatCode(ndinfo[\"nd\"][\"status\"])) for devid, info in ndinfo[\"sen\"].iteritems(): if",
"opt['method'] == 'tcpcs': self._logger.info(\"It would wait for a while to",
"readsensornodeinfo(self, node): ret = self.readnodeinfo(node) for dev in node['children']: if",
"\"children\" : [ #{\"id\" : \"102\", \"dk\" : '[1,210,[\"value\",\"status\"]]', \"dt\":",
"range(self._detection[\"saddr\"], 12): for unit in range(self._detection[\"saddr\"], self._detection[\"eaddr\"]): if self._isdetecting ==",
"super(KSX3267MateV2, self).close() def readmsg(self): self._msgq = [] for gw in",
"= Lock() self._logger.info(\"KSX3267MateV2 Started.\") def detect_node(self, conn, unit, registers): print",
"\", \" + str(dev)) code = ResCode.FAIL elif dev is",
"= idx + size print \"parsed\", ret return ret def",
"size = registers[4] while True: res = self.readregister(conn, KSX3267MateV2._DEVCODEREG, size,",
"in params: val = params[key] else: self._logger.warn(\"Wrong Keyword : \"",
"other device\") return ret def readactinfo(self, node, act): ret =",
"print \"=======================================#2\" kdmate.writeblk(req) print \"=======================================#2\" time.sleep(1) req = Request(None) req.setcommand(\"1\",",
"\"dk\" : '[1,40241,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"106\", \"dk\" :",
"sendobs(self): for msg in self._msgq: if msg is None: continue",
"devinfo, coupleid, logger): super(KSX3267MateV2, self).__init__(option, devinfo, coupleid, logger) self._timeout =",
"\" + str(dev['dk']) + \" \" + str(res)) # continue",
"\"=======================================#2\" kdmate.writeblk(req) print \"=======================================#2\" time.sleep(1) req = Request(None) req.setcommand(\"1\", CmdCode.DETECT_DEVICE,",
"\"id\" : \"101\", \"dk\" : '[1,40201,[\"status\"],45001,[\"operation\",\"opid\"]]', \"dt\": \"nd\", \"children\" :",
"\"sen\"}, #{\"id\" : \"110\", \"dk\" : '[1,40291,[\"value\",\"status\"]]', \"dt\": \"sen\"} #",
"devid=port, content={unit : info}) # found a node detected[unit] =",
"\"act/switch/level0\"} ] }, { \"id\" : \"301\", \"dk\" : (3,40201,[\"opid\",\"status\"],45001,[\"operation\",\"opid\"]),",
"#{\"id\" : \"205\", \"dk\" : (2,40241,[\"opid\",\"status\"],45041,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" :",
"return ResCode.OK def writeblk(self, blk): print \"received message\", blk.getdevid(), self._coupleid",
"IntEnum from threading import Thread, Lock from mate import Mate,",
"class ProtoVer(IntEnum): KS_X_3267_2020 = 10 KS_X_3267_2018 = 101 TTA_1 =",
"# key param is not used for this operation #",
"obsblk = Observation(ndinfo[\"id\"]) obsblk.setobservation(ndinfo[\"id\"], 0, StatCode(ndinfo[\"nd\"][\"status\"])) for devid, info in",
"+ str(request)) return ResCode.FAIL_TO_WRITE msg = self.readactinfo(node, dev) if msg",
"message is not request. \" + str(blk.gettype())) return False response",
"\" + str(unit) + \" \" + str(res)) elif res.registers[1]",
"in node['children']: if DevType.issensor(dev[\"dt\"]) == False: info = self.readinfofromdev(ret[\"conn\"], dev)",
"= self.detect_node(conn, unit, res.registers) self._logger.info (\"Found a nutrient system :",
"do not send observation for actuator #for devid, info in",
"\"dk\" : '[2,40202,[\"opid\",\"status\",\"state-hold-time\",\"remain-time\"],40206,[\"operation\",\"opid\",\"time\"]]', \"dt\": \"act/retractable/level1\"}, {\"id\" : \"202\", \"dk\" :",
"\"EC\": (2, \"float\"), \"pH\": (2, \"float\"), \"on-sec\" : (1, \"short\"),",
"info in detected.iteritems(): noti.setcontent(port, info) self.writecb(noti) self.setdetection(False) def detectone(self, port,",
"self._devinfo.finddevbyid(blk.getdevid()) if blk.getdevid() == self._coupleid: params = blk.getparams() if cmd",
"'[1,40211,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"106\", \"dk\" : '[1,40251,[\"value\",\"status\"]]', \"dt\":",
"Lock from mate import Mate, ThreadMate, DevType from mblock import",
"\"time\" : (2, \"int\"), \"opentime\" : (1, \"short\"), \"closetime\" :",
"\" \" + str(len(res.registers))) continue return {\"compcode\" : compcode, \"nodecode\"",
"if self._isdetecting == False or self.isexecuting() == False: self._logger.info(\"Total detection",
"if DevType.issensor(dev[\"dt\"]) == False: info = self.readinfofromdev(ret[\"conn\"], dev) if info:",
"ret def readactinfo(self, node, act): ret = self.readnodeinfo(node) info =",
"len(res.registers) != size: self._logger.info(\"retry to get data since size of",
"'[1,40201,[\"status\"],45001,[\"operation\",\"opid\"]]', \"dt\": \"nd\", \"children\" : [ {\"id\" : \"102\", \"dk\"",
"noti = Notice(unit, NotiCode.DETECT_UNKNOWN_NODE, devid=tempid) # unknown device if noti",
"struct.pack('i', val))) elif KSX3267MateV2._KEYWORDS[key][1] == \"float\": registers.extend(struct.unpack('HH', struct.pack('f', val))) #else:",
"\"dk\" : '[1,40271,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"110\", \"dk\" :",
"blk.getparams() if cmd == CmdCode.DETECT_DEVICE: print \"detect device\" code =",
"\"children\" : [{ \"id\" : \"101\", \"dk\" : '[1,40201,[\"status\"],45001,[\"operation\",\"opid\"]]', \"dt\":",
"+ \",\" + str(res) + \":\" + str(request)) return ResCode.FAIL_TO_WRITE",
"node): ret = self.readnodeinfo(node) for dev in node['children']: if DevType.issensor(dev[\"dt\"]):",
"self.readinfofromdev(ret[\"conn\"], dev) if info: ret[\"sen\"][dev[\"id\"]] = info #else: # self._logger.warn(\"fail",
"CmdCode.DETECT_DEVICE, None) print \"=======================================#1\" kdmate.writeblk(req) print \"=======================================#1\" \"\"\" time.sleep(1) req",
"return None if len(res.registers) != size: self._logger.info(\"retry to get data",
"# All right reserved. # import struct import time import",
"(2,40241,[\"opid\",\"status\"],45041,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"206\", \"dk\" : (2,40251,[\"opid\",\"status\"],45051,[\"operation\",\"opid\"]), \"dt\":",
"is not matched. \" + str(size) + \" \" +",
"= None else: msg = \"It's a wrong connection method.",
"def readactnodeinfo(self, node): ret = self.readnodeinfo(node) for dev in node['children']:",
"setdetection(self, flag, opid=0): self._isdetecting = flag self._detection[\"opid\"] = opid def",
"continue to read other device\") return ret def sendobs(self): for",
"write\", self.getdk(dev, 3), registers res = self._conn[gw[\"dk\"]].write_registers(self.getdk(dev, 3), registers, unit=unit)",
"ndinfo[\"id\"], ndinfo[\"nd\"]) for devid, info in ndinfo[\"act\"].iteritems(): blk.setcontent(devid, info) self.writecb(blk)",
"print \"received message\", blk.getdevid(), self._coupleid if BlkType.isrequest(blk.gettype()) is False: self._logger.warn(\"The",
"sensor info : \" + str(dev) + \" however continue",
"None) kdmate.start (mate.writeblk) print \"mate started\" time.sleep(10) req = Request(None)",
"info: ret[\"act\"][act[\"id\"]] = info else: self._logger.warn(\"fail to read actuator info",
"elif opt['method'] == 'tcpcs': self._logger.info(\"It would wait for a while",
"devid=tempid) # Detection Started self._logger.info (\"Fail to get information from",
"range(3): res = self.readregister(conn, KSX3267MateV2._DEVINFOREG, 6, unit) if res is",
"= {\"port\": [], \"saddr\":0, \"eaddr\":0, \"opid\":0} #self._nodes = self._devinfo.getgw()[\"children\"] self._lock",
"self._logger.info(\"KSX3267MateV2 Started.\") def detect_node(self, conn, unit, registers): print \"detect_node\", unit,",
"= self.readactinfo(node, dev) if msg is None: self._logger.warn(\"Fail to read",
"detection is canceled.\") break info = self.detectone(port, conn) detected[port] =",
"a client~\") rsoc, wsoc, esoc = select.select([servsoc], [], [], 10)",
"json.loads(dev[\"dk\"]) return dk[idx] def setdetection(self, flag, opid=0): self._isdetecting = flag",
"if info: ret[\"sen\"][dev[\"id\"]] = info #else: # self._logger.warn(\"fail to read",
"information from a node : \" + str(unit) + \"",
"import select import traceback import hashlib import json from enum",
"+ str(res) + \":\" + str(request)) return ResCode.FAIL_TO_WRITE msg =",
"= StatCode.ERROR.value obsblk = Observation(ndinfo[\"id\"]) obsblk.setobservation(ndinfo[\"id\"], 0, StatCode(ndinfo[\"nd\"][\"status\"])) for devid,",
"\"control\": (1, \"control\"), \"area\" : (1, \"short\"), \"alert\" : (1,",
"\"209\", \"dk\" : (2,40281,[\"opid\",\"status\"],45081,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"} ] }, { \"id\"",
"False or self.isexecuting() == False: self._logger.info(\"Total detection is canceled.\") break",
"tmp[\"port\"] == opt[\"port\"]: self._logger.warn(\" port [\" + str(opt[\"port\"]) + \"]",
"if self._detection[\"port\"] is not None and port not in self._detection[\"port\"]:",
"\"dt\": \"sen\"} ]} ]} ] devinfo = [{ \"id\" :",
"-*- # # Copyright (c) 2018 JiNong, Inc. # All",
"self.readinfofromdev(ret[\"conn\"], act) if info: ret[\"act\"][act[\"id\"]] = info else: self._logger.warn(\"fail to",
"tmp[\"thd\"].stop() tmp[\"thd\"].join() def connectone(self, opt): ret = False conn =",
"\"103\", \"dk\" : '[1,41020,[\"value\",\"status\"]]', \"dt\": \"sen\"} # {\"id\" : \"102\",",
"+ str(blk) + \", \" + str(dev)) code = ResCode.FAIL",
"i = i + 1 if i % 3 ==",
"'[1,210,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"103\", \"dk\" : '[1,220,[\"value\",\"status\"]]', \"dt\":",
"(2, \"float\"), \"pH\": (2, \"float\"), \"on-sec\" : (1, \"short\"), \"start-area\"",
"# device type if res.registers[3] == ProtoVer.KS_X_3267_2020 or res.registers[3] ==",
"str(opt['method']) if ret == False: self._logger.warn(msg) noti = Notice(None, NotiCode.RTU_FAILED_CONNECTION)",
"{\"id\" : \"110\", \"dk\" : '[1,40281,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" :",
"class KSX3267MateV2(ThreadMate): _SLEEP = 0.5 _VERSION = \"KSX3267_0.1\" _KEYWORDS =",
"ResCode.FAIL response.setresult(code) self._logger.info(\"write response: \" + str(response)) self.writecb(response) return True",
"connect(self): ret = False for opt in self._option['conn']: conn =",
"101 TTA_1 = 201 class KSX3267MateV2(ThreadMate): _SLEEP = 0.5 _VERSION",
"KSX3267MateV2._KEYWORDS[key][0] == 1: registers.append(val) elif KSX3267MateV2._KEYWORDS[key][1] == \"int\": registers.extend(struct.unpack('HH', struct.pack('i',",
"\"act\" : {}, \"nd\" : {\"status\":StatCode.ERROR.value}} gw = self._devinfo.findgateway(node[\"id\"]) conn",
"Exception as ex: servsoc.close() for tmp in self._tempthd: if tmp[\"port\"]",
"\"dt\": \"act/switch/level0\"}, #{\"id\" : \"204\", \"dk\" : (2,40231,[\"opid\",\"status\"],45031,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"},",
"(1, \"short\"), \"epoch\" : (2, \"int\"), \"vfloat\": (2, \"float\"), \"vint\"",
"detect(self): detected = {} for port, conn in self._conn.iteritems(): if",
"not in option else option[\"timeout\"] self._conn = {} self._tempthd =",
"unit, registers): print \"detect_node\", unit, registers compcode = registers[0] nodecode",
"detected = {} if self._detection[\"port\"] is not None and port",
"\"short\"), \"closetime\" : (1, \"short\"), \"EC\": (2, \"float\"), \"pH\": (2,",
"error def listen(self, opt): tmp = {\"thd\" : Thread(target=self._listen, args=(opt)),",
"== ResCode.OK else False def parseregisters(self, names, values): idx =",
"ret = self.readnodeinfo(node) for dev in node['children']: if DevType.issensor(dev[\"dt\"]): info",
"CmdCode.DETECT_DEVICE, None) print \"=======================================#3\" kdmate.writeblk(req) print \"=======================================#3\" time.sleep(1) req =",
"self._conn[opt[\"port\"]] = conn tmp[\"status\"] = 10 # connected executing =",
"client~\") rsoc, wsoc, esoc = select.select([servsoc], [], [], 10) for",
"json from enum import IntEnum from threading import Thread, Lock",
"== False: ndinfo[\"nd\"][\"status\"] = StatCode.ERROR.value obsblk = Observation(ndinfo[\"id\"]) obsblk.setobservation(ndinfo[\"id\"], 0,",
"self._logger.info (\"finished to detect devices : \" + str(detected)) noti",
"for this operation. \" + str(params['operation']) + \", \" +",
"False: self._logger.warn(\"The request is not proper. \" + str(cmd) +",
"def listen(self, opt): tmp = {\"thd\" : Thread(target=self._listen, args=(opt)), \"status\":",
"\"saddr\":0, \"eaddr\":0, \"opid\":0} #self._nodes = self._devinfo.getgw()[\"children\"] self._lock = Lock() self._logger.info(\"KSX3267MateV2",
"connect with rtu\" code = NotiCode.RTU_CONNECTED if ret else NotiCode.RTU_FAILED_CONNECTION",
"= self.readnodeinfo(node) i = 1 for dev in node['children']: if",
"node) if info: ret[\"nd\"] = info else: self._logger.warn(\"fail to read",
"\"dk\" : (2,40281,[\"opid\",\"status\"],45081,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"} ] }, { \"id\" :",
": '[1,40202,[\"value\",\"status\"]]', \"dt\": \"sen\"}, # {\"id\" : \"103\", \"dk\" :",
"or res.registers[3] == ProtoVer.KS_X_3267_2018: info = self.detect_node(conn, unit, res.registers) self._logger.info",
"self._conn.keys(): self.closeone(port) super(KSX3267MateV2, self).close() def readmsg(self): self._msgq = [] for",
"\"1\", \"dk\" : \"JND2\", \"dt\": \"gw\", \"children\" : [ #",
"(\"finished to detect devices : \" + str(detected)) noti =",
"self._logger.warn(\"The request is not proper. \" + str(cmd) + \"",
"devid=tempid) # unknown protocol version elif res.registers[1] == NodeType.NUTNODE: if",
"for key in self.getdk(dev, 4): if key not in properparams:",
"{\"id\" : \"109\", \"dk\" : '[1,40271,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" :",
"res.registers) else: self._logger.info(\"retry to get data since size of data",
"\"204\", \"dk\" : '[2,40219,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"203\", \"dk\"",
"info = self.detectone(port, conn) detected[port] = info self._logger.info (\"finished to",
"\" however continue to read other device\") return ret def",
"system : \" + str(unit) + \" \" + str(info))",
"= None res = None for _ in range(3): res",
"write\" with self._lock: time.sleep(KSX3267MateV2._SLEEP) print \"....... lock for write\", self.getdk(dev,",
"\" + str(key)) # return ResCode.FAIL_WRONG_KEYWORD print \"....... befor lock",
"# break elif res.isError(): self._logger.info(\"retry to get status from \"",
"in range(self._detection[\"saddr\"], self._detection[\"eaddr\"]): if self._isdetecting == False or self.isexecuting() ==",
"self._logger.info(\"client connected from \" + str(address)) for tmp in self._tempthd:",
"node else: noti = Notice(None, NotiCode.DETECT_NODE_DETECTED, devid=port, content={unit : info})",
"however continue to read other device\") return ret def sendobs(self):",
"CmdCode.CANCEL_DETECT, {}) print \"=======================================#4\" kdmate.writeblk(req) print \"=======================================#4\" time.sleep(10) req =",
"+ 1 if i % 3 == 0: self.sendnoticeforactuatorstatus(ret) ret[\"act\"]",
"str(size) + \" \" + str(len(res.registers))) return None def readnodeinfo(self,",
"self._devinfo.getgw()[\"children\"] self._lock = Lock() self._logger.info(\"KSX3267MateV2 Started.\") def detect_node(self, conn, unit,",
"else NotiCode.RTU_FAILED_CONNECTION conn = None else: msg = \"It's a",
"req.setcommand(\"1\", CmdCode.CANCEL_DETECT, {}) print \"=======================================#2\" kdmate.writeblk(req) print \"=======================================#2\" time.sleep(1) req",
"req = Request(201) req.setcommand(202, CmdCode.OPEN, {}) kdmate.writeblk(req) time.sleep(5) req =",
"+ \" \" + str(info)) else: noti = Notice(None, NotiCode.DETECT_UNKNOWN_PROTOCOL_VER,",
"# unknown device if noti is None: if info is",
"request.getopid() # need to convert by case properparams = CmdCode.getparams(operation)",
"+ str(count)) print \"read register\", unit, addr, count try: return",
"self._conn[gw[\"dk\"]] ret[\"conn\"] = conn info = self.readinfofromdev(conn, node) if info:",
"\"1\", None) else: kdmate = KSX3267MateV2(opt, devinfo, \"1\", None) mate",
"= Notice(None, NotiCode.DETECT_UNKNOWN_PROTOCOL_VER, devid=tempid) # unknown protocol version elif res.registers[1]",
"noti = Notice(None, NotiCode.DETECT_WRONG_DEVICE, devid=tempid) # fail to find a",
"= ResCode.FAIL else: self._logger.warn(\"Unknown Error. \" + str(blk) + \",",
"is not proper. \" + str(cmd) + \" \" +",
"Copyright (c) 2018 JiNong, Inc. # All right reserved. #",
"\"pH\": (2, \"float\"), \"on-sec\" : (1, \"short\"), \"start-area\" : (1,",
"registers.append(val) elif KSX3267MateV2._KEYWORDS[key][1] == \"int\": registers.extend(struct.unpack('HH', struct.pack('i', val))) elif KSX3267MateV2._KEYWORDS[key][1]",
"info = self.detect_node(conn, unit, res.registers) self._logger.info (\"Found a nutrient system",
"{\"id\" : \"105\", \"dk\" : '[1,40211,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" :",
"self.writecb(noti) self.setdetection(False) return ResCode.OK def _listen(self, opt): try: servsoc =",
": \"102\", \"dk\" : '[1,41010,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"103\",",
"\"dt\": \"sen\"}, # {\"id\" : \"105\", \"dk\" : '[1,40211,[\"value\",\"status\"]]', \"dt\":",
"str(dev['dk'])) # break elif res.isError(): self._logger.info(\"retry to get status from",
"201 class KSX3267MateV2(ThreadMate): _SLEEP = 0.5 _VERSION = \"KSX3267_0.1\" _KEYWORDS",
"= CmdCode.getparams(operation) + [\"operation\", \"opid\"] registers = [] for key",
"to read node info : \" + str(node)) return ret",
"+ str(cmd) + \" \" + str(dev['dt'])) code = ResCode.FAIL_NOT_PROPER_COMMAND",
"# need to convert by case params[\"opid\"] = request.getopid() #",
"\"dt\": \"nd\", \"children\" : [ {\"id\" : \"202\", \"dk\" :",
": \"1\", \"dk\" : \"JND2\", \"dt\": \"gw\", \"children\" : [",
"+ str(unit) + \" \" + str(res)) return None if",
"before lock for read\" with self._lock: time.sleep(KSX3267MateV2._SLEEP) #mrchoi87 self._logger.info(\"read_holding_registers: \"",
"\"203\", \"dk\" : '[2,40216,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"204\", \"dk\"",
"self._msgq = [] for gw in self._devinfo: for nd in",
"NotiCode.RTU_FAILED_CONNECTION conn = None else: msg = \"It's a wrong",
"import socket import select import traceback import hashlib import json",
"+ [\"operation\", \"opid\"] registers = [] for key in self.getdk(dev,",
"False: # info[\"status\"] = StatCode.ERROR.value # obsblk.setobservation(devid, 0, StatCode(info[\"status\"])) self.writecb(obsblk)",
"def __init__(self, option, devinfo, coupleid, logger): super(KSX3267MateV2, self).__init__(option, devinfo, coupleid,",
"#{\"id\" : \"104\", \"dk\" : '[1,40208,[\"value\",\"status\"]]', \"dt\": \"sen\"}, # {\"id\"",
"res.registers[3] == ProtoVer.TTA_1: info = self.detect_node(conn, unit, res.registers) self._logger.info (\"Found",
"params, opid): if self._detection[\"opid\"] != 0: self._logger.info(\"detection is processing.... so",
"in self._conn.iteritems(): if self._isdetecting == False or self.isexecuting() == False:",
"Notice(None, NotiCode.RTU_CONNECTED) # detection is canceled self.writecb(noti) return conn def",
"detected def canceldetection(self, params): time.sleep(self._timeout) noti = Notice(None, NotiCode.DETECT_CANCELED) #",
"\"int\"), \"opentime\" : (1, \"short\"), \"closetime\" : (1, \"short\"), \"EC\":",
"False: self._logger.warn(msg) noti = Notice(None, NotiCode.RTU_FAILED_CONNECTION) # detection is canceled",
"registers res = self._conn[gw[\"dk\"]].write_registers(self.getdk(dev, 3), registers, unit=unit) if res.isError(): self._logger.warn(\"Fail",
"\"dt\": \"gw\", \"children\" : [{ \"id\" : \"101\", \"dk\" :",
"time.sleep(1) req = Request(None) req.setcommand(\"1\", CmdCode.DETECT_DEVICE, None) print \"=======================================#3\" kdmate.writeblk(req)",
"Notice(None, NotiCode.DETECT_UNKNOWN_PROTOCOL_VER, devid=tempid) # unknown protocol version else: noti =",
"self._tempthd: if tmp[\"port\"] == opt[\"port\"]: self._logger.warn(\" port [\" + str(opt[\"port\"])",
"StatCode(ndinfo[\"nd\"][\"status\"])) for devid, info in ndinfo[\"sen\"].iteritems(): if StatCode.has_value(info[\"status\"]) == False:",
"\"nodecode\" : nodecode, \"devcodes\": res.registers} def getdk(self, dev, idx): dk",
"\" \" + str(info)) else: noti = Notice(None, NotiCode.DETECT_UNKNOWN_PROTOCOL_VER, devid=tempid)",
"fail to find a node else: noti = Notice(None, NotiCode.DETECT_NODE_DETECTED,",
"else: self._logger.warn(\"fail to read actuator info : \" + str(dev)",
"noti = Notice(None, NotiCode.DETECT_UNKNOWN_PROTOCOL_VER, devid=tempid) # unknown protocol version else:",
": (2, \"int\"), \"opentime\" : (1, \"short\"), \"closetime\" : (1,",
": \"203\", \"dk\" : (2,40221,[\"opid\",\"status\"],45021,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"204\",",
"'[1,40281,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"111\", \"dk\" : '[1,40291,[\"value\",\"status\"]]', \"dt\":",
"val = struct.unpack('i', struct.pack('HH', values[idx], values[idx+1]))[0] else: val = values[idx]",
"+ \" \" + str(addr) + \" \" + str(count))",
"self.writecb(noti) self.setdetection(False) def detectone(self, port, conn): detected = {} if",
"python # # -*- coding: utf-8 -*- # # Copyright",
": \" + str(opt)) executing = True while executing: self._logger.info(\"waiting",
"other device\") return ret def sendobs(self): for msg in self._msgq:",
"self.readinfofromdev(conn, node) if info: ret[\"nd\"] = info else: self._logger.warn(\"fail to",
"\"dt\": \"sen\"}, {\"id\" : \"113\", \"dk\" : '[1,40311,[\"value\",\"status\"]]', \"dt\": \"sen\"}",
"= Response(blk) cmd = blk.getcommand() nd = self._devinfo.finddevbyid(blk.getnodeid()) dev =",
"time import socket import select import traceback import hashlib import",
"(1, \"control\"), \"area\" : (1, \"short\"), \"alert\" : (1, \"alert\"),",
"protocol version else: noti = Notice(unit, NotiCode.DETECT_UNKNOWN_NODE, devid=tempid) # unknown",
"unit in range(self._detection[\"saddr\"], 12): for unit in range(self._detection[\"saddr\"], self._detection[\"eaddr\"]): if",
"for devid, info in ndinfo[\"act\"].iteritems(): blk.setcontent(devid, info) self.writecb(blk) def start(self,",
"= 2 _DEVCODEREG = 101 def __init__(self, option, devinfo, coupleid,",
"+ \" detection is canceled.\") break tempid = port +",
"self._detection[\"port\"]: return detected #mrchoi87 #for unit in range(self._detection[\"saddr\"], 12): for",
"NotiCode.DETECT_CANCELED) # detection is canceled noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) self.writecb(noti) self.setdetection(False) return",
"super(KSX3267MateV2, self).start(writecb) return True def stop(self): super(KSX3267MateV2, self).stop() return True",
"return True def stop(self): super(KSX3267MateV2, self).stop() return True def getsize(self,",
"read other device\") return ret def readactnodeinfo(self, node): ret =",
"# However, the register should be filled. val = 0",
"devid=tempid) # fail to find a node else: noti =",
"+ str(len(res.registers))) continue return {\"compcode\" : compcode, \"nodecode\" : nodecode,",
"self._detection[\"opid\"]) for port, info in detected.iteritems(): noti.setcontent(port, info) self.writecb(noti) self.setdetection(False)",
"else: self._logger.warn(\"Wrong Keyword : \" + str(key)) return ResCode.FAIL_WRONG_KEYWORD if",
"if tmp[\"port\"] == opt[\"port\"]: self._logger.warn(\" port [\" + str(opt[\"port\"]) +",
"CmdCode, Observation, Request, Response, NotiCode, Notice from pymodbus.client.sync import ModbusSerialClient",
"connected from \" + str(address)) for tmp in self._tempthd: if",
"devid=tempid) # Detection Started if noti: noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) self.writecb(noti) noti",
"Keyword : \" + str(key)) return ResCode.FAIL_WRONG_KEYWORD if KSX3267MateV2._KEYWORDS[key][0] ==",
"self._isdetecting = False self._detection = {\"port\": [], \"saddr\":0, \"eaddr\":0, \"opid\":0}",
"\"gw\", \"children\" : [ # { # \"id\" : \"101\",",
"= \"failed to connect with tcp\" code = NotiCode.TCP_CONNECTED if",
"# # -*- coding: utf-8 -*- # # Copyright (c)",
"\"112\", \"dk\" : '[1,40301,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"113\", \"dk\"",
"self.writecb(response) return True #if code == ResCode.OK else False def",
"return None def detect(self): detected = {} for port, conn",
"port not in self._detection[\"port\"]: return detected #mrchoi87 #for unit in",
"\" + str(blk.getdevid())) code = ResCode.FAIL_NO_DEVICE elif DevType.ispropercommand(dev['dt'], cmd) is",
"= i + 1 if i % 3 == 0:",
"\"dk\" : '[2,40209,[\"opid\",\"status\",\"state-hold-time\",\"remain-time\"],40213,[\"operation\",\"opid\",\"time\"]]', \"dt\": \"act/retractable/level1\"}, {\"id\" : \"203\", \"dk\" :",
"+ str(detected)) noti = Notice(None, NotiCode.DETECT_FINISHED) # Detection Started if",
"self.readnodeinfo(node) info = self.readinfofromdev(ret[\"conn\"], act) if info: ret[\"act\"][act[\"id\"]] = info",
"device\") return ret def readactinfo(self, node, act): ret = self.readnodeinfo(node)",
"None if opt['method'] == 'rtu': conn = ModbusSerialClient(method='rtu', port=opt['port'], timeout=self._timeout,",
"None: self._logger.warn(\"fail to get status from \" + str(dev['dk'])) #",
"len(res.registers) == size: return self.parseregisters(self.getdk(dev, 2), res.registers) else: self._logger.info(\"retry to",
"wait for a while to connect a client.\") ret =",
"print \"=======================================#1\" kdmate.writeblk(req) print \"=======================================#1\" \"\"\" time.sleep(1) req = Request(None)",
"res is None or res.isError(): noti = Notice(None, NotiCode.DETECT_NO_NODE, devid=tempid)",
"register should be filled. val = 0 elif key in",
"-*- coding: utf-8 -*- # # Copyright (c) 2018 JiNong,",
"= port + \"-\" + str(unit) noti = Notice(None, NotiCode.DETECT_NODE_STARTED,",
"{\"id\" : \"202\", \"dk\" : '[2,40209,[\"opid\",\"status\",\"state-hold-time\",\"remain-time\"],40213,[\"operation\",\"opid\",\"time\"]]', \"dt\": \"act/retractable/level1\"}, {\"id\" :",
"== False: # info[\"status\"] = StatCode.ERROR.value # obsblk.setobservation(devid, 0, StatCode(info[\"status\"]))",
"for tmp in self._tempthd: if tmp[\"port\"] == opt[\"port\"]: self._logger.warn(\" port",
"if len(res.registers) != 6: self._logger.info(\"retry to get data since size",
"try: servsoc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) servsoc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) servsoc.bind((opt['host'], opt['port']))",
"conn): detected = {} if self._detection[\"port\"] is not None and",
"self._msgq.append(self.readsensornodeinfo(nd)) if self._isdetecting: self.detect() self.checktempthreads() def processrequest(self, dev, request, node):",
"with rtu\" code = NotiCode.RTU_CONNECTED if ret else NotiCode.RTU_FAILED_CONNECTION elif",
"if info: ret[\"nd\"] = info else: self._logger.warn(\"fail to read node",
"\"KSX3267_0.1\" _KEYWORDS = {\"value\" : (2, \"float\"), \"status\" : (1,",
"str(len(res.registers))) continue return {\"compcode\" : compcode, \"nodecode\" : nodecode, \"devcodes\":",
"if \"timeout\" not in option else option[\"timeout\"] self._conn = {}",
"KSX3267MateV2(ThreadMate): _SLEEP = 0.5 _VERSION = \"KSX3267_0.1\" _KEYWORDS = {\"value\"",
"get data since size of data is not matched. \"",
"\"sen\"}, #{\"id\" : \"103\", \"dk\" : '[1,220,[\"value\",\"status\"]]', \"dt\": \"sen\"} #",
"= info i = i + 1 if i %",
"data since size of data is not matched. 6 \"",
"Mate ({}, [], \"1\", None) kdmate.start (mate.writeblk) print \"mate started\"",
"\"dt\": \"sen\"}, #{\"id\" : \"110\", \"dk\" : '[1,40291,[\"value\",\"status\"]]', \"dt\": \"sen\"}",
"params[\"opid\"] = request.getopid() # need to convert by case properparams",
"# \"id\" : \"101\", \"dk\" : '[1,40201,[\"status\"],45001,[\"operation\",\"opid\"]]', \"dt\": \"nd\", \"children\"",
"ignored.\") return ResCode.FAIL self.setdetection(True, opid) if params: self._detection[\"saddr\"] = params['saddr']",
"+ str(dev['dt'])) code = ResCode.FAIL_NOT_PROPER_COMMAND elif DevType.isactuator(dev['dt']) or DevType.isnode(dev['dt']): #",
"\"sen\"} # \"id\" : \"101\", \"dk\" : '[1,40201,[\"status\"],45001,[\"operation\",\"opid\"]]', \"dt\": \"nd\",",
"conn = None if opt['method'] == 'rtu': conn = ModbusSerialClient(method='rtu',",
"\"dt\": \"nd\", \"children\" : [ {\"id\" : \"102\", \"dk\" :",
"matched. \" + str(size) + \" \" + str(len(res.registers))) continue",
"or res.isError(): continue if len(res.registers) != 6: self._logger.info(\"retry to get",
": \"106\", \"dk\" : '[1,40251,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"107\",",
"a request to dev.\" + str(dev) + \",\" + str(res)",
"\"dt\": \"sen\"}, {\"id\" : \"107\", \"dk\" : '[1,40261,[\"value\",\"status\"]]', \"dt\": \"sen\"},",
"\"float\": registers.extend(struct.unpack('HH', struct.pack('f', val))) #else: # self._logger.warn(\"This param is needed",
"\"dt\": \"sen\"} # ] # } ] }] \"\"\" },",
"rsoc: if sock == servsoc: clisoc, address = servsoc.accept() self._logger.info(\"client",
"nodecode = registers[2] size = registers[4] while True: res =",
"self._logger.warn(\"fail to read actuator info : \" + str(act) +",
"= Request(201) req.setcommand(202, CmdCode.TIMED_OPEN, {\"time\":10}) kdmate.writeblk(req) time.sleep(15) req = Request(201)",
"str(unit) + \" \" + str(info)) else: noti = Notice(None,",
"connect with tcp\" code = NotiCode.TCP_CONNECTED if ret else NotiCode.RTU_FAILED_CONNECTION",
"info else: self._logger.warn(\"fail to read node info : \" +",
"str(blk.getdevid())) code = ResCode.FAIL_NO_DEVICE elif DevType.ispropercommand(dev['dt'], cmd) is False: self._logger.warn(\"The",
"is not matched. 6 \" + str(len(res.registers))) continue break if",
"req.setcommand(202, CmdCode.OPEN, {}) kdmate.writeblk(req) time.sleep(5) req = Request(201) req.setcommand(202, CmdCode.OFF,",
"\"read register\", unit, addr, count try: return conn.read_holding_registers(addr, count, unit=unit)",
"convert by case properparams = CmdCode.getparams(operation) + [\"operation\", \"opid\"] registers",
"find a node else: noti = Notice(None, NotiCode.DETECT_NODE_DETECTED, devid=port, content={unit",
"= conn tmp[\"status\"] = 10 # connected executing = False",
"ResCode.OK def _listen(self, opt): try: servsoc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) servsoc.setsockopt(socket.SOL_SOCKET,",
"started\" time.sleep(10) req = Request(None) req.setcommand(\"1\", CmdCode.DETECT_DEVICE, None) print \"=======================================#1\"",
"Detection Started if noti: noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) for port, info in",
"SENNODE = 1 ACTNODE = 2 INTNODE = 3 NUTNODE",
"= {\"id\" : node[\"id\"], \"sen\" : {}, \"act\" : {},",
"req = Request(None) req.setcommand(\"1\", CmdCode.DETECT_DEVICE, None) print \"=======================================#3\" kdmate.writeblk(req) print",
"struct.pack('HH', values[idx], values[idx+1]))[0] elif vtype == \"int\": val = struct.unpack('i',",
"from \" + str(dev['dk'])) # break elif res.isError(): self._logger.info(\"retry to",
": \"203\", \"dk\" : '[2,40216,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"204\",",
": (1, \"short\"), \"closetime\" : (1, \"short\"), \"EC\": (2, \"float\"),",
"\"sen\" : {}, \"act\" : {}, \"nd\" : {\"status\":StatCode.ERROR.value}} gw",
"None) print \"=======================================#3\" kdmate.writeblk(req) print \"=======================================#3\" time.sleep(1) req = Request(None)",
": \" + str(node)) return ret def readsensornodeinfo(self, node): ret",
"val = 0 elif key in params: val = params[key]",
"size of data is not matched. 6 \" + str(len(res.registers)))",
"{\"id\" : \"107\", \"dk\" : '[1,40261,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" :",
"ret[\"nd\"] = info else: self._logger.warn(\"fail to read node info :",
"0 ret = {} for nm in names: (size, vtype)",
"if StatCode.has_value(ndinfo[\"nd\"][\"status\"]) == False: ndinfo[\"nd\"][\"status\"] = StatCode.ERROR.value obsblk = Observation(ndinfo[\"id\"])",
"values[idx], values[idx+1]))[0] elif vtype == \"int\": val = struct.unpack('i', struct.pack('HH',",
"blk.getdevid() == self._coupleid: params = blk.getparams() if cmd == CmdCode.DETECT_DEVICE:",
"if res is None or res.isError(): continue if len(res.registers) !=",
": [ {\"id\" : \"102\", \"dk\" : '[1,40211,[\"control\",\"status\",\"area\",\"alert\",\"opid\"],45001,[\"operation\", \"opid\", \"control\",\"EC\",\"pH\",",
"= size + KSX3267MateV2._KEYWORDS[k][0] else: self._logger.warn(\"wrong keyword : \" +",
"== \"int\": registers.extend(struct.unpack('HH', struct.pack('i', val))) elif KSX3267MateV2._KEYWORDS[key][1] == \"float\": registers.extend(struct.unpack('HH',",
"_KEYWORDS = {\"value\" : (2, \"float\"), \"status\" : (1, \"status\"),",
"ret def readinfofromdev(self, conn, dev): size = self.getsize(self.getdk(dev, 2)) #for",
"self.getdk(dev, 0)) if res is None: self._logger.warn(\"fail to get status",
"ret = {\"id\" : node[\"id\"], \"sen\" : {}, \"act\" :",
"info : \" + str(dev) + \" however continue to",
"CmdCode.getparams(operation) + [\"operation\", \"opid\"] registers = [] for key in",
"ret = False for opt in self._option['conn']: conn = self.connectone(opt)",
"self.writecb(noti) noti = None info = None res = None",
": \"1\", \"dk\" : \"\", \"dt\": \"gw\", \"children\" : [{",
"KSX3267MateV2._KEYWORDS: size = size + KSX3267MateV2._KEYWORDS[k][0] else: self._logger.warn(\"wrong keyword :",
"info[\"value\"], StatCode(info[\"status\"])) # do not send observation for actuator #for",
"\",\" + str(res) + \":\" + str(request)) return ResCode.FAIL_TO_WRITE msg",
"\"state-hold-time\" : (2, \"int\"), \"ratio\": (1, \"short\"), \"position\" : (1,",
"\"cancel to detect device\" code = self.canceldetection(params) else: self._logger.warn(\"Unknown Error.",
"(2,40231,[\"opid\",\"status\"],45031,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"205\", \"dk\" : (2,40241,[\"opid\",\"status\"],45041,[\"operation\",\"opid\"]), \"dt\":",
"self._logger.info(\"detection is processing.... so this command would be ignored.\") return",
"(1, \"short\"), \"alert\" : (1, \"alert\"), \"hold-time\" : (2, \"int\"),",
"would be ignored.\") return ResCode.FAIL self.setdetection(True, opid) if params: self._detection[\"saddr\"]",
"[\" + str(opt[\"port\"]) + \"] exception : \" + str(ex))",
"12 self._detection[\"port\"] = None return ResCode.OK def readregister(self, conn, addr,",
"range(self._detection[\"saddr\"], self._detection[\"eaddr\"]): if self._isdetecting == False or self.isexecuting() == False:",
": \"103\", \"dk\" : '[1,40221,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"104\",",
"is processing.... so this command would be ignored.\") return ResCode.FAIL",
"\"int\")} _DEVINFOREG = 2 _DEVCODEREG = 101 def __init__(self, option,",
"True #if code == ResCode.OK else False def parseregisters(self, names,",
"= request.getopid() # need to convert by case properparams =",
"{ 'conn' : [{ 'method': 'rtu', 'port' : '/dev/ttyJND2', 'baudrate'",
"None and port not in self._detection[\"port\"]: return detected #mrchoi87 #for",
"+ str(opt)) executing = True while executing: self._logger.info(\"waiting a client~\")",
"# unknown protocol version elif res.registers[1] == NodeType.NUTNODE: if res.registers[3]",
"socket import select import traceback import hashlib import json from",
"self._detection[\"eaddr\"] = 12 self._detection[\"port\"] = None return ResCode.OK def readregister(self,",
"\"failed to connect with rtu\" code = NotiCode.RTU_CONNECTED if ret",
"except Exception as ex: servsoc.close() for tmp in self._tempthd: if",
"{\"id\" : \"305\", \"dk\" : (3,40241,[\"opid\",\"status\"],45041,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"} ] }]",
"select.select([servsoc], [], [], 10) for sock in rsoc: if sock",
"req.setcommand(\"1\", CmdCode.DETECT_DEVICE, None) print \"=======================================#1\" kdmate.writeblk(req) print \"=======================================#1\" \"\"\" time.sleep(1)",
"size, self.getdk(dev, 0)) if res is None: self._logger.warn(\"fail to get",
"\"dk\" : '[2,40219,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"203\", \"dk\" :",
"super(KSX3267MateV2, self).connect() return ret def closeone(self, port): self._conn[port].close() def close(self):",
"names: (size, vtype) = KSX3267MateV2._KEYWORDS[nm] if vtype == \"float\": val",
"'[2,40201,[\"status\"],45001,[\"operation\",\"opid\"]]', \"dt\": \"nd\", \"children\" : [ {\"id\" : \"202\", \"dk\"",
"\"children\" : [ {\"id\" : \"302\", \"dk\" : (3,40211,[\"opid\",\"status\"],45011,[\"operation\",\"opid\"]), \"dt\":",
"# do not send observation for actuator #for devid, info",
"executing = False except Exception as ex: servsoc.close() for tmp",
"tmp in self._tempthd: if tmp[\"port\"] == opt[\"port\"]: self._logger.warn(\" port [\"",
"Request(201) req.setcommand(202, CmdCode.OPEN, {}) kdmate.writeblk(req) time.sleep(5) req = Request(201) req.setcommand(202,",
"\"1\", None) kdmate.start (mate.writeblk) print \"mate started\" time.sleep(10) req =",
": [{ \"id\" : \"101\", \"dk\" : '[1,40201,[\"status\"],45001,[\"operation\",\"opid\"]]', \"dt\": \"nd\",",
"request to dev.\" + str(dev) + \",\" + str(res) +",
": (2,40231,[\"opid\",\"status\"],45031,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"205\", \"dk\" : (2,40241,[\"opid\",\"status\"],45041,[\"operation\",\"opid\"]),",
"self._logger.warn(msg) noti = Notice(None, NotiCode.RTU_FAILED_CONNECTION) # detection is canceled else:",
"BlkType.isrequest(blk.gettype()) is False: self._logger.warn(\"The message is not request. \" +",
"processing.... so this command would be ignored.\") return ResCode.FAIL self.setdetection(True,",
"break tempid = port + \"-\" + str(unit) noti =",
"noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) self.writecb(noti) noti = None info = None res",
"\"dt\": \"sen\"}, #{\"id\" : \"107\", \"dk\" : '[1,40261,[\"value\",\"status\"]]', \"dt\": \"sen\"},",
"'[1,40208,[\"value\",\"status\"]]', \"dt\": \"sen\"}, # {\"id\" : \"105\", \"dk\" : '[1,40211,[\"value\",\"status\"]]',",
"executing = True while executing: self._logger.info(\"waiting a client~\") rsoc, wsoc,",
"{\"id\" : \"103\", \"dk\" : '[1,40221,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" :",
"= self.readnodeinfo(node) info = self.readinfofromdev(ret[\"conn\"], act) if info: ret[\"act\"][act[\"id\"]] =",
"by case params[\"opid\"] = request.getopid() # need to convert by",
"\"children\" : [ #{\"id\" : \"102\", \"dk\" : '[1,41010,[\"value\",\"status\"]]', \"dt\":",
"self._lock = Lock() self._logger.info(\"KSX3267MateV2 Started.\") def detect_node(self, conn, unit, registers):",
"self._logger.warn(\"Fail to read dev status.\") else: self.sendnoticeforactuatorstatus(msg) return ResCode.OK def",
"count try: return conn.read_holding_registers(addr, count, unit=unit) except Exception as ex:",
"= self.readinfofromdev(ret[\"conn\"], act) if info: ret[\"act\"][act[\"id\"]] = info else: self._logger.warn(\"fail",
"+ KSX3267MateV2._KEYWORDS[k][0] else: self._logger.warn(\"wrong keyword : \" + str(k)) return",
"ResCode.FAIL self.setdetection(True, opid) if params: self._detection[\"saddr\"] = params['saddr'] self._detection[\"eaddr\"] =",
"k in KSX3267MateV2._KEYWORDS: size = size + KSX3267MateV2._KEYWORDS[k][0] else: self._logger.warn(\"wrong",
"self).stop() return True def getsize(self, lst): size =0 for k",
"time.sleep(0.1) return detected def canceldetection(self, params): time.sleep(self._timeout) noti = Notice(None,",
"\"dt\": \"act/switch/level0\"}, #{\"id\" : \"205\", \"dk\" : (2,40241,[\"opid\",\"status\"],45041,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"},",
"+ \" \" + str(len(res.registers))) continue return {\"compcode\" : compcode,",
"detection is canceled noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) self.writecb(noti) self.setdetection(False) return ResCode.OK def",
"i = 1 for dev in node['children']: if DevType.issensor(dev[\"dt\"]) ==",
"== False: info[\"status\"] = StatCode.ERROR.value obsblk.setobservation(devid, info[\"value\"], StatCode(info[\"status\"])) # do",
"= self.detectone(port, conn) detected[port] = info self._logger.info (\"finished to detect",
"message\", blk.getdevid(), self._coupleid if BlkType.isrequest(blk.gettype()) is False: self._logger.warn(\"The message is",
"be ignored.\") return ResCode.FAIL self.setdetection(True, opid) if params: self._detection[\"saddr\"] =",
"\"float\"), \"status\" : (1, \"status\"), \"opid\" : (1, \"short\"), \"state-hold-time\"",
"\"short\"), \"stop-area\": (1, \"short\"), \"epoch\" : (2, \"int\"), \"vfloat\": (2,",
"params: self._detection[\"saddr\"] = params['saddr'] self._detection[\"eaddr\"] = params['eaddr'] self._detection[\"port\"] = params['port']",
"str(dev)) code = ResCode.FAIL elif dev is None: self._logger.warn(\"There is",
"\"202\", \"dk\" : '[2,40202,[\"opid\",\"status\",\"state-hold-time\",\"remain-time\"],40206,[\"operation\",\"opid\",\"time\"]]', \"dt\": \"act/retractable/level1\"}, {\"id\" : \"202\", \"dk\"",
"+ str(unit) + \" \" + str(addr) + \" \"",
"msg is None: self._logger.warn(\"Fail to read dev status.\") else: self.sendnoticeforactuatorstatus(msg)",
"elif DevType.ispropercommand(dev['dt'], cmd) is False: self._logger.warn(\"The request is not proper.",
"actuator info : \" + str(dev) + \" however continue",
"True def getsize(self, lst): size =0 for k in lst:",
"if res is None or res.isError(): noti = Notice(None, NotiCode.DETECT_NO_NODE,",
"'port' : '/dev/ttyJND2', 'baudrate' : 9600, 'timeout': 5 }] }",
"#for _ in range(3): res = self.readregister(conn, self.getdk(dev, 1), size,",
"to detect devices : \" + str(detected)) noti = Notice(None,",
"in properparams: # key param is not used for this",
"is None: self._logger.warn(\"Fail to read dev status.\") else: self.sendnoticeforactuatorstatus(msg) return",
"self._logger.warn(\"There is no device. \" + str(blk.getdevid())) code = ResCode.FAIL_NO_DEVICE",
"gw[\"children\"]: ret = self.readnodeinfo(node) i = 1 for dev in",
": (2, \"int\"), \"operation\" : (1, \"operation\"), \"time\" : (2,",
"[ #{\"id\" : \"102\", \"dk\" : '[1,210,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\"",
"+ \"] exception : \" + str(ex)) tmp[\"status\"] = 5",
"\"int\"), \"vfloat\": (2, \"float\"), \"vint\" : (2, \"int\")} _DEVINFOREG =",
"None for _ in range(3): res = self.readregister(conn, KSX3267MateV2._DEVINFOREG, 6,",
"\" + str(detected)) noti = Notice(None, NotiCode.DETECT_FINISHED) # Detection Started",
"option[\"timeout\"] self._conn = {} self._tempthd = [] self._isdetecting = False",
"unit=unit) except Exception as ex: self._logger.warn(\"fail to read holding registers.",
"= params['saddr'] self._detection[\"eaddr\"] = params['eaddr'] self._detection[\"port\"] = params['port'] else: self._detection[\"saddr\"]",
"\"closetime\" : (1, \"short\"), \"EC\": (2, \"float\"), \"pH\": (2, \"float\"),",
"conn.connect() msg = \"failed to connect with tcp\" code =",
"self._logger.warn(\"fail to read holding registers. : \" + str(ex)) return",
"val = params[key] else: self._logger.warn(\"Wrong Keyword : \" + str(key))",
"+ str(len(res.registers))) return None def readnodeinfo(self, node): ret = {\"id\"",
"StatCode(info[\"status\"])) self.writecb(obsblk) def sendnoticeforactuatorstatus(self, ndinfo): blk = Notice(ndinfo[\"id\"], NotiCode.ACTUATOR_STATUS, ndinfo[\"id\"],",
"blk = Notice(ndinfo[\"id\"], NotiCode.ACTUATOR_STATUS, ndinfo[\"id\"], ndinfo[\"nd\"]) for devid, info in",
"req = Request(201) req.setcommand(202, CmdCode.OFF, {}) kdmate.writeblk(req) time.sleep(10) req =",
"\" \" + str(res)) return None if len(res.registers) != size:",
"blk.setcontent(devid, info) self.writecb(blk) def start(self, writecb): super(KSX3267MateV2, self).start(writecb) return True",
"\"304\", \"dk\" : (3,40231,[\"opid\",\"status\"],45031,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"}, {\"id\" : \"305\", \"dk\"",
"self._isdetecting == False or self.isexecuting() == False: self._logger.info(\"Total detection is",
"# Detection Started self._logger.info (\"Fail to get information from a",
"to convert by case params[\"opid\"] = request.getopid() # need to",
"canceled self.writecb(noti) return conn def connect(self): ret = False for",
"size: self._logger.info(\"retry to get data since size of data is",
"k in lst: if k in KSX3267MateV2._KEYWORDS: size = size",
"Inc. # All right reserved. # import struct import time",
"devid=tempid) # unknown device if noti is None: if info",
"else False def parseregisters(self, names, values): idx = 0 ret",
"\"dk\" : '[1,220,[\"value\",\"status\"]]', \"dt\": \"sen\"} # \"id\" : \"101\", \"dk\"",
"this command would be ignored.\") return ResCode.FAIL self.setdetection(True, opid) if",
"Request(201) req.setcommand(202, CmdCode.OFF, {}) kdmate.writeblk(req) time.sleep(10) req = Request(201) req.setcommand(202,",
"a client.\") ret = self.listen(opt) msg = \"failed to connect",
"\"=======================================#1\" \"\"\" time.sleep(1) req = Request(None) req.setcommand(\"1\", CmdCode.CANCEL_DETECT, {}) print",
"+ str(dev)) code = ResCode.FAIL response.setresult(code) self._logger.info(\"write response: \" +",
"\"float\"), \"vint\" : (2, \"int\")} _DEVINFOREG = 2 _DEVCODEREG =",
"operation = request.getcommand() params = request.getparams() params[\"operation\"] = operation #",
"def writeblk(self, blk): print \"received message\", blk.getdevid(), self._coupleid if BlkType.isrequest(blk.gettype())",
"a while to connect a client.\") ret = self.listen(opt) msg",
"\"dk\" : (3,40221,[\"opid\",\"status\"],45021,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"}, {\"id\" : \"304\", \"dk\" :",
"readnodeinfo(self, node): ret = {\"id\" : node[\"id\"], \"sen\" : {},",
"self.sendobservation(msg) def sendnoti(self): for gw in self._devinfo: for node in",
"info[\"status\"] = StatCode.ERROR.value # obsblk.setobservation(devid, 0, StatCode(info[\"status\"])) self.writecb(obsblk) def sendnoticeforactuatorstatus(self,",
"# found a node detected[unit] = info noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) print",
"this operation # However, the register should be filled. val",
"\"It's a wrong connection method. \" + str(opt['method']) if ret",
"+ str(res)) # continue else: if len(res.registers) == size: return",
"return ret def closeone(self, port): self._conn[port].close() def close(self): for port",
"def sendobs(self): for msg in self._msgq: if msg is None:",
"in KSX3267MateV2._KEYWORDS: size = size + KSX3267MateV2._KEYWORDS[k][0] else: self._logger.warn(\"wrong keyword",
"= Notice(None, NotiCode.DETECT_NODE_STARTED, devid=tempid) # Detection Started if noti: noti.setkeyvalue(\"opid\",",
"detection is canceled else: noti = Notice(None, NotiCode.RTU_CONNECTED) # detection",
"\"sen\"}, {\"id\" : \"107\", \"dk\" : '[1,40261,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\"",
"\"int\": val = struct.unpack('i', struct.pack('HH', values[idx], values[idx+1]))[0] else: val =",
"detect_node(self, conn, unit, registers): print \"detect_node\", unit, registers compcode =",
"self.sendnoticeforactuatorstatus(ret) ret[\"act\"] = {} self.sendnoticeforactuatorstatus(ret) def sendobservation(self, ndinfo): if StatCode.has_value(ndinfo[\"nd\"][\"status\"])",
"\"dk\" : '[1,40291,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"112\", \"dk\" :",
"ret[\"conn\"] = conn info = self.readinfofromdev(conn, node) if info: ret[\"nd\"]",
"else: self._logger.info(\"retry to get data since size of data is",
"Mate, ThreadMate, DevType from mblock import MBlock, BlkType, StatCode, ResCode,",
"{\"thd\" : Thread(target=self._listen, args=(opt)), \"status\": 0, \"port\":opt['port']} self._tempthd.append(tmp) tmp[\"thd\"].start() def",
"flag, opid=0): self._isdetecting = flag self._detection[\"opid\"] = opid def startdetection(self,",
"ret return ret def readinfofromdev(self, conn, dev): size = self.getsize(self.getdk(dev,",
"\" + str(len(res.registers))) return None def readnodeinfo(self, node): ret =",
"address = servsoc.accept() self._logger.info(\"client connected from \" + str(address)) for",
"if res is None or res.isError(): self._logger.warn(\"Fail to get devices",
"2 _DEVCODEREG = 101 def __init__(self, option, devinfo, coupleid, logger):",
"= False for opt in self._option['conn']: conn = self.connectone(opt) if",
"enum import IntEnum from threading import Thread, Lock from mate",
"if info: ret[\"act\"][dev[\"id\"]] = info else: self._logger.warn(\"fail to read actuator",
"NodeType.NUTNODE: if res.registers[3] == ProtoVer.TTA_1: info = self.detect_node(conn, unit, res.registers)",
"info i = i + 1 if i % 3",
"devid=tempid) # unknown protocol version else: noti = Notice(unit, NotiCode.DETECT_UNKNOWN_NODE,",
"[{ \"id\" : \"101\", \"dk\" : '[1,40201,[\"status\"],45001,[\"operation\",\"opid\"]]', \"dt\": \"nd\", \"children\"",
"in self._detection[\"port\"]: return detected #mrchoi87 #for unit in range(self._detection[\"saddr\"], 12):",
"start(self, writecb): super(KSX3267MateV2, self).start(writecb) return True def stop(self): super(KSX3267MateV2, self).stop()",
"conn = self._conn[gw[\"dk\"]] ret[\"conn\"] = conn info = self.readinfofromdev(conn, node)",
"== False or self.isexecuting() == False: self._logger.info(\"A port \" +",
"blk.getdevid(), self._coupleid if BlkType.isrequest(blk.gettype()) is False: self._logger.warn(\"The message is not",
"holding registers. : \" + str(ex)) return None def detect(self):",
"\"106\", \"dk\" : '[1,40251,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"107\", \"dk\"",
"# detection is canceled noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) self.writecb(noti) self.setdetection(False) return ResCode.OK",
"case params[\"opid\"] = request.getopid() # need to convert by case",
"coupleid, logger): super(KSX3267MateV2, self).__init__(option, devinfo, coupleid, logger) self._timeout = 3",
"utf-8 -*- # # Copyright (c) 2018 JiNong, Inc. #",
"res = self._conn[gw[\"dk\"]].write_registers(self.getdk(dev, 3), registers, unit=unit) if res.isError(): self._logger.warn(\"Fail to",
"= conn.connect() msg = \"failed to connect with rtu\" code",
"return ResCode.FAIL self.setdetection(True, opid) if params: self._detection[\"saddr\"] = params['saddr'] self._detection[\"eaddr\"]",
"nm in names: (size, vtype) = KSX3267MateV2._KEYWORDS[nm] if vtype ==",
"\"area\" : (1, \"short\"), \"alert\" : (1, \"alert\"), \"hold-time\" :",
"\"\"\" if isnutri: kdmate = KSX3267MateV2(opt, nutriinfo, \"1\", None) else:",
"= [{ \"id\" : \"1\", \"dk\" : \"\", \"dt\": \"gw\",",
"(2,40271,[\"opid\",\"status\"],45071,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"209\", \"dk\" : (2,40281,[\"opid\",\"status\"],45081,[\"operation\",\"opid\"]), \"dt\":",
"ex: self._logger.warn(\"fail to read holding registers. : \" + str(ex))",
"(2, \"float\"), \"status\" : (1, \"status\"), \"opid\" : (1, \"short\"),",
": '[1,41020,[\"value\",\"status\"]]', \"dt\": \"sen\"} # {\"id\" : \"102\", \"dk\" :",
"ret = self.readnodeinfo(node) for dev in node['children']: if DevType.issensor(dev[\"dt\"]) ==",
"\"dt\": \"act/retractable/level1\"}, {\"id\" : \"203\", \"dk\" : '[2,40216,[\"value\",\"status\"]]', \"dt\": \"sen\"},",
": (2, \"int\")} _DEVINFOREG = 2 _DEVCODEREG = 101 def",
"= struct.unpack('f', struct.pack('HH', values[idx], values[idx+1]))[0] elif vtype == \"int\": val",
"\"dt\": \"sen\"}, {\"id\" : \"104\", \"dk\" : '[1,40231,[\"value\",\"status\"]]', \"dt\": \"sen\"},",
"str(dev['dk']) + \" \" + str(res)) # continue else: if",
"for opt in self._option['conn']: conn = self.connectone(opt) if conn: self._conn[opt[\"port\"][8:]]",
"\"children\" : [ {\"id\" : \"202\", \"dk\" : '[2,40202,[\"opid\",\"status\",\"state-hold-time\",\"remain-time\"],40206,[\"operation\",\"opid\",\"time\"]]', \"dt\":",
"ThreadMate, DevType from mblock import MBlock, BlkType, StatCode, ResCode, CmdCode,",
"canceled.\") break tempid = port + \"-\" + str(unit) noti",
"get devices from \" + str(unit) + \" \" +",
"False except Exception as ex: servsoc.close() for tmp in self._tempthd:",
"for gw in self._devinfo: for nd in gw[\"children\"]: self._msgq.append(self.readsensornodeinfo(nd)) if",
"params['eaddr'] self._detection[\"port\"] = params['port'] else: self._detection[\"saddr\"] = 1 self._detection[\"eaddr\"] =",
"return conn def connect(self): ret = False for opt in",
"'conn' : [{ 'method': 'rtu', 'port' : '/dev/ttyJND2', 'baudrate' :",
"self._isdetecting: self.detect() self.checktempthreads() def processrequest(self, dev, request, node): gw =",
"\" + str(dev)) code = ResCode.FAIL elif dev is None:",
"\"sen\"}, {\"id\" : \"110\", \"dk\" : '[1,40281,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\"",
"\"id\" : \"101\", \"dk\" : '[1,201,[\"status\"],301,[\"operation\",\"opid\"]]', \"dt\": \"nd\", \"children\" :",
"a node detected[unit] = info noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) print \"noti\", noti.stringify()",
"res = None for _ in range(3): res = self.readregister(conn,",
"getdk(self, dev, idx): dk = json.loads(dev[\"dk\"]) return dk[idx] def setdetection(self,",
"opt[\"port\"]: self._logger.warn(\" port [\" + str(opt[\"port\"]) + \"] exception :",
"\"dk\" : \"JND2\", \"dt\": \"gw\", \"children\" : [ # {",
"\"opid\", \"control\",\"EC\",\"pH\", \"start-area\", \"stop-area\", \"on-sec\"]]', \"dt\": \"nutrient-supply/level1\"}, {\"id\" : \"103\",",
"= opid def startdetection(self, params, opid): if self._detection[\"opid\"] != 0:",
"# self._logger.warn(\"This param is needed for this operation. \" +",
"= None return ResCode.OK def readregister(self, conn, addr, count, unit):",
"noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) self.writecb(noti) self.setdetection(False) return ResCode.OK def _listen(self, opt): try:",
"\" + str(node)) return ret def readsensornodeinfo(self, node): ret =",
"if __name__ == \"__main__\": isnutri = False opt = {",
"== NodeType.NUTNODE: if res.registers[3] == ProtoVer.TTA_1: info = self.detect_node(conn, unit,",
"str(detected)) noti = Notice(None, NotiCode.DETECT_FINISHED) # Detection Started if noti:",
"# Detection Started if noti: noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) for port, info",
"+ str(res)) return None if len(res.registers) != size: self._logger.info(\"retry to",
"6: self._logger.info(\"retry to get data since size of data is",
": (1, \"alert\"), \"hold-time\" : (2, \"int\"), \"operation\" : (1,",
"canceled.\") break info = self.detectone(port, conn) detected[port] = info self._logger.info",
"Response(blk) cmd = blk.getcommand() nd = self._devinfo.finddevbyid(blk.getnodeid()) dev = self._devinfo.finddevbyid(blk.getdevid())",
"\"dk\" : '[1,40251,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"107\", \"dk\" :",
"self._detection[\"port\"] = params['port'] else: self._detection[\"saddr\"] = 1 self._detection[\"eaddr\"] = 12",
"\"sen\"}, {\"id\" : \"112\", \"dk\" : '[1,40301,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\"",
"ResCode.FAIL_WRONG_KEYWORD if KSX3267MateV2._KEYWORDS[key][0] == 1: registers.append(val) elif KSX3267MateV2._KEYWORDS[key][1] == \"int\":",
"self._tempthd.append(tmp) tmp[\"thd\"].start() def checktempthreads(self): for tmp in self._tempthd: if tmp[\"status\"]",
": \" + str(dev) + \" however continue to read",
"return size if __name__ == \"__main__\": isnutri = False opt",
"not receive a request\") code = ResCode.FAIL else: self._logger.warn(\"Unknown Error.",
": (3,40231,[\"opid\",\"status\"],45031,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"}, {\"id\" : \"305\", \"dk\" : (3,40241,[\"opid\",\"status\"],45041,[\"operation\",\"opid\"]),",
"'baudrate' : 9600, 'timeout': 5 }] } nutriinfo = [{",
"+ str(dev['dk'])) # break elif res.isError(): self._logger.info(\"retry to get status",
"str(res)) # continue else: if len(res.registers) == size: return self.parseregisters(self.getdk(dev,",
"However, the register should be filled. val = 0 elif",
"'[1,40281,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"110\", \"dk\" : '[1,40291,[\"value\",\"status\"]]', \"dt\":",
"} ] }] \"\"\" }, { \"id\" : \"201\", \"dk\"",
"tmp[\"thd\"].start() def checktempthreads(self): for tmp in self._tempthd: if tmp[\"status\"] >",
": \"105\", \"dk\" : '[1,40211,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"106\",",
"= KSX3267MateV2(opt, nutriinfo, \"1\", None) else: kdmate = KSX3267MateV2(opt, devinfo,",
"\"-\" + str(unit) noti = Notice(None, NotiCode.DETECT_NODE_STARTED, devid=tempid) # Detection",
": {}, \"act\" : {}, \"nd\" : {\"status\":StatCode.ERROR.value}} gw =",
"Response, NotiCode, Notice from pymodbus.client.sync import ModbusSerialClient from pymodbus.client.sync import",
"\"vint\" : (2, \"int\")} _DEVINFOREG = 2 _DEVCODEREG = 101",
"for sock in rsoc: if sock == servsoc: clisoc, address",
"StatCode.has_value(info[\"status\"]) == False: # info[\"status\"] = StatCode.ERROR.value # obsblk.setobservation(devid, 0,",
"nodecode, \"devcodes\": res.registers} def getdk(self, dev, idx): dk = json.loads(dev[\"dk\"])",
"else: if len(res.registers) == size: return self.parseregisters(self.getdk(dev, 2), res.registers) else:",
"noti = Notice(None, NotiCode.DETECT_CANCELED) # detection is canceled noti.setkeyvalue(\"opid\", self._detection[\"opid\"])",
"code = self.startdetection(params, blk.getopid()) elif cmd == CmdCode.CANCEL_DETECT: print \"cancel",
"info: ret[\"nd\"] = info else: self._logger.warn(\"fail to read node info",
"opt): ret = False conn = None if opt['method'] ==",
"\"dk\" : '[1,210,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"103\", \"dk\" :",
"print \"parsed\", ret return ret def readinfofromdev(self, conn, dev): size",
"_VERSION = \"KSX3267_0.1\" _KEYWORDS = {\"value\" : (2, \"float\"), \"status\"",
"{\"id\" : node[\"id\"], \"sen\" : {}, \"act\" : {}, \"nd\"",
"ret def readsensornodeinfo(self, node): ret = self.readnodeinfo(node) for dev in",
"self).start(writecb) return True def stop(self): super(KSX3267MateV2, self).stop() return True def",
"\"remain-time\" : (2, \"int\"), \"control\": (1, \"control\"), \"area\" : (1,",
"= self.readnodeinfo(node) for dev in node['children']: if DevType.issensor(dev[\"dt\"]): info =",
"# detection is canceled self.writecb(noti) return conn def connect(self): ret",
"NotiCode.DETECT_FINISHED) # Detection Started if noti: noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) for port,",
"DevType.issensor(dev[\"dt\"]): info = self.readinfofromdev(ret[\"conn\"], dev) if info: ret[\"sen\"][dev[\"id\"]] = info",
"\"dk\" : (3,40211,[\"opid\",\"status\"],45011,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"}, {\"id\" : \"303\", \"dk\" :",
"2), res.registers) else: self._logger.info(\"retry to get data since size of",
"self.startdetection(params, blk.getopid()) elif cmd == CmdCode.CANCEL_DETECT: print \"cancel to detect",
": '[1,40211,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"106\", \"dk\" : '[1,40251,[\"value\",\"status\"]]',",
"None: noti = Notice(None, NotiCode.DETECT_WRONG_DEVICE, devid=tempid) # fail to find",
": \"202\", \"dk\" : '[2,40202,[\"opid\",\"status\",\"state-hold-time\",\"remain-time\"],40206,[\"operation\",\"opid\",\"time\"]]', \"dt\": \"act/retractable/level1\"}, {\"id\" : \"202\",",
"-1 return size if __name__ == \"__main__\": isnutri = False",
"detect device\" code = self.canceldetection(params) else: self._logger.warn(\"Unknown Error. \" +",
"\"sen\"}, {\"id\" : \"104\", \"dk\" : '[1,40231,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\"",
"ret = self.readnodeinfo(node) info = self.readinfofromdev(ret[\"conn\"], act) if info: ret[\"act\"][act[\"id\"]]",
"print \"=======================================#2\" time.sleep(1) req = Request(None) req.setcommand(\"1\", CmdCode.DETECT_DEVICE, None) print",
"type if res.registers[3] == ProtoVer.KS_X_3267_2020 or res.registers[3] == ProtoVer.KS_X_3267_2018: info",
"to convert by case properparams = CmdCode.getparams(operation) + [\"operation\", \"opid\"]",
"#mrchoi87 self._logger.info(\"read_holding_registers: \" + str(unit) + \" \" + str(addr)",
"tmp[\"status\"] = 10 # connected executing = False except Exception",
"def readnodeinfo(self, node): ret = {\"id\" : node[\"id\"], \"sen\" :",
"obsblk.setobservation(devid, info[\"value\"], StatCode(info[\"status\"])) # do not send observation for actuator",
"{} self.sendnoticeforactuatorstatus(ret) def sendobservation(self, ndinfo): if StatCode.has_value(ndinfo[\"nd\"][\"status\"]) == False: ndinfo[\"nd\"][\"status\"]",
"#{\"id\" : \"102\", \"dk\" : '[1,210,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" :",
"for this operation # However, the register should be filled.",
"\" \" + str(count)) print \"read register\", unit, addr, count",
": info}) # found a node detected[unit] = info noti.setkeyvalue(\"opid\",",
"= registers[4] while True: res = self.readregister(conn, KSX3267MateV2._DEVCODEREG, size, unit)",
"continue break if res is None or res.isError(): noti =",
"{ \"id\" : \"301\", \"dk\" : (3,40201,[\"opid\",\"status\"],45001,[\"operation\",\"opid\"]), \"dt\": \"nd\", \"children\"",
"\"status\": 0, \"port\":opt['port']} self._tempthd.append(tmp) tmp[\"thd\"].start() def checktempthreads(self): for tmp in",
"'[1,201,[\"status\"],301,[\"operation\",\"opid\"]]', \"dt\": \"nd\", \"children\" : [ #{\"id\" : \"102\", \"dk\"",
"cmd = blk.getcommand() nd = self._devinfo.finddevbyid(blk.getnodeid()) dev = self._devinfo.finddevbyid(blk.getdevid()) if",
"self._logger.info(\"It would wait for a while to connect a client.\")",
"= Notice(unit, NotiCode.DETECT_UNKNOWN_NODE, devid=tempid) # unknown device if noti is",
"All right reserved. # import struct import time import socket",
"\"dk\" : '[1,201,[\"status\"],301,[\"operation\",\"opid\"]]', \"dt\": \"nd\", \"children\" : [ #{\"id\" :",
"str(port) + \" detection is canceled.\") break tempid = port",
"= {\"value\" : (2, \"float\"), \"status\" : (1, \"status\"), \"opid\"",
"listen(self, opt): tmp = {\"thd\" : Thread(target=self._listen, args=(opt)), \"status\": 0,",
"'[1,40251,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"107\", \"dk\" : '[1,40261,[\"value\",\"status\"]]', \"dt\":",
"\"dt\": \"act/retractable/level1\"}, {\"id\" : \"202\", \"dk\" : '[2,40209,[\"opid\",\"status\",\"state-hold-time\",\"remain-time\"],40213,[\"operation\",\"opid\",\"time\"]]', \"dt\": \"act/retractable/level1\"},",
"# { # \"id\" : \"101\", \"dk\" : '[1,201,[\"status\"],301,[\"operation\",\"opid\"]]', \"dt\":",
"str(size) + \" \" + str(len(res.registers))) continue return {\"compcode\" :",
"{\"id\" : \"113\", \"dk\" : '[1,40311,[\"value\",\"status\"]]', \"dt\": \"sen\"} ]} ]}",
"'[2,40202,[\"opid\",\"status\",\"state-hold-time\",\"remain-time\"],40206,[\"operation\",\"opid\",\"time\"]]', \"dt\": \"act/retractable/level1\"}, {\"id\" : \"202\", \"dk\" : '[2,40209,[\"opid\",\"status\",\"state-hold-time\",\"remain-time\"],40213,[\"operation\",\"opid\",\"time\"]]', \"dt\":",
"res.isError(): continue if len(res.registers) != 6: self._logger.info(\"retry to get data",
"= info else: self._logger.warn(\"fail to read node info : \"",
"None def readnodeinfo(self, node): ret = {\"id\" : node[\"id\"], \"sen\"",
"\"start-area\" : (1, \"short\"), \"stop-area\": (1, \"short\"), \"epoch\" : (2,",
": \" + str(detected)) noti = Notice(None, NotiCode.DETECT_FINISHED) # Detection",
"+ str(dev) + \",\" + str(res) + \":\" + str(request))",
"for k in lst: if k in KSX3267MateV2._KEYWORDS: size =",
"\"stop-area\": (1, \"short\"), \"epoch\" : (2, \"int\"), \"vfloat\": (2, \"float\"),",
"dev) if msg is None: self._logger.warn(\"Fail to read dev status.\")",
"info = self.readinfofromdev(ret[\"conn\"], dev) if info: ret[\"sen\"][dev[\"id\"]] = info #else:",
": (3,40211,[\"opid\",\"status\"],45011,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"}, {\"id\" : \"303\", \"dk\" : (3,40221,[\"opid\",\"status\"],45021,[\"operation\",\"opid\"]),",
": \" + str(key)) return ResCode.FAIL_WRONG_KEYWORD if KSX3267MateV2._KEYWORDS[key][0] == 1:",
"conn, unit, registers): print \"detect_node\", unit, registers compcode = registers[0]",
": (2,40241,[\"opid\",\"status\"],45041,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"206\", \"dk\" : (2,40251,[\"opid\",\"status\"],45051,[\"operation\",\"opid\"]),",
": [ #{\"id\" : \"102\", \"dk\" : '[1,210,[\"value\",\"status\"]]', \"dt\": \"sen\"},",
"code == ResCode.OK else False def parseregisters(self, names, values): idx",
"= Notice(ndinfo[\"id\"], NotiCode.ACTUATOR_STATUS, ndinfo[\"id\"], ndinfo[\"nd\"]) for devid, info in ndinfo[\"act\"].iteritems():",
"dev in node['children']: if DevType.issensor(dev[\"dt\"]): info = self.readinfofromdev(ret[\"conn\"], dev) if",
"self.setdetection(False) return ResCode.OK def _listen(self, opt): try: servsoc = socket.socket(socket.AF_INET,",
"response = Response(blk) cmd = blk.getcommand() nd = self._devinfo.finddevbyid(blk.getnodeid()) dev",
"5 # error def listen(self, opt): tmp = {\"thd\" :",
"def start(self, writecb): super(KSX3267MateV2, self).start(writecb) return True def stop(self): super(KSX3267MateV2,",
"is canceled.\") break tempid = port + \"-\" + str(unit)",
"noti = Notice(None, NotiCode.DETECT_FINISHED) # Detection Started if noti: noti.setkeyvalue(\"opid\",",
"is needed for this operation. \" + str(params['operation']) + \",",
"str(response)) self.writecb(response) return True #if code == ResCode.OK else False",
"[{ \"id\" : \"1\", \"dk\" : \"\", \"dt\": \"gw\", \"children\"",
": \"102\", \"dk\" : '[1,210,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"103\",",
"\"dt\": \"act/retractable/level0\"}, {\"id\" : \"304\", \"dk\" : (3,40231,[\"opid\",\"status\"],45031,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"},",
": \"209\", \"dk\" : (2,40281,[\"opid\",\"status\"],45081,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"} ] }, {",
"= request.getcommand() params = request.getparams() params[\"operation\"] = operation # need",
"to connect with rtu\" code = NotiCode.RTU_CONNECTED if ret else",
"None: if info is None: noti = Notice(None, NotiCode.DETECT_WRONG_DEVICE, devid=tempid)",
"\" + str(params['operation']) + \", \" + str(key)) # return",
"res = self.readregister(conn, KSX3267MateV2._DEVINFOREG, 6, unit) if res is None",
"\"act/switch/level0\"}, #{\"id\" : \"207\", \"dk\" : (2,40261,[\"opid\",\"status\"],45061,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\"",
"\"noti\", noti.stringify() self.writecb(noti) time.sleep(0.1) return detected def canceldetection(self, params): time.sleep(self._timeout)",
"\":\" + str(request)) return ResCode.FAIL_TO_WRITE msg = self.readactinfo(node, dev) if",
"\"sen\"}, #{\"id\" : \"106\", \"dk\" : '[1,40251,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\"",
"== self._coupleid: params = blk.getparams() if cmd == CmdCode.DETECT_DEVICE: print",
"self._logger.warn(\"Fail to get devices from \" + str(unit) + \"",
"= self.readinfofromdev(ret[\"conn\"], dev) if info: ret[\"act\"][dev[\"id\"]] = info i =",
"info noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) print \"noti\", noti.stringify() self.writecb(noti) time.sleep(0.1) return detected",
"= {} for port, conn in self._conn.iteritems(): if self._isdetecting ==",
"continue self.sendobservation(msg) def sendnoti(self): for gw in self._devinfo: for node",
"(1, \"status\"), \"opid\" : (1, \"short\"), \"state-hold-time\" : (2, \"int\"),",
"params[key] else: self._logger.warn(\"Wrong Keyword : \" + str(key)) return ResCode.FAIL_WRONG_KEYWORD",
"= 0.5 _VERSION = \"KSX3267_0.1\" _KEYWORDS = {\"value\" : (2,",
"def getsize(self, lst): size =0 for k in lst: if",
"\"104\", \"dk\" : '[1,40208,[\"value\",\"status\"]]', \"dt\": \"sen\"}, # {\"id\" : \"105\",",
"ndinfo[\"nd\"][\"status\"] = StatCode.ERROR.value obsblk = Observation(ndinfo[\"id\"]) obsblk.setobservation(ndinfo[\"id\"], 0, StatCode(ndinfo[\"nd\"][\"status\"])) for",
"[], [], 10) for sock in rsoc: if sock ==",
"KSX3267MateV2._DEVCODEREG, size, unit) if res is None or res.isError(): self._logger.warn(\"Fail",
"= \"failed to connect with rtu\" code = NotiCode.RTU_CONNECTED if",
"= 1 for dev in node['children']: if DevType.issensor(dev[\"dt\"]) == False:",
"tmp in self._tempthd: if tmp[\"status\"] > 2: tmp[\"thd\"].stop() tmp[\"thd\"].join() def",
": '[1,220,[\"value\",\"status\"]]', \"dt\": \"sen\"} # \"id\" : \"101\", \"dk\" :",
"struct.pack('HH', values[idx], values[idx+1]))[0] else: val = values[idx] ret[nm] = val",
"registers, unit=unit) if res.isError(): self._logger.warn(\"Fail to write a request to",
"\" + str(code)) elif DevType.isgateway(dev['dt']): self._logger.info(\"Gateway does not receive a",
"ProtoVer.KS_X_3267_2018: info = self.detect_node(conn, unit, res.registers) self._logger.info (\"Found a node",
"for port in self._conn.keys(): self.closeone(port) super(KSX3267MateV2, self).close() def readmsg(self): self._msgq",
"+ \" however continue to read other device\") return ret",
"status from \" + str(dev['dk']) + \" \" + str(res))",
"= self.readregister(conn, self.getdk(dev, 1), size, self.getdk(dev, 0)) if res is",
"Notice(None, NotiCode.DETECT_NODE_STARTED, devid=tempid) # Detection Started if noti: noti.setkeyvalue(\"opid\", self._detection[\"opid\"])",
": '[1,40251,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"107\", \"dk\" : '[1,40261,[\"value\",\"status\"]]',",
"= 3 if \"timeout\" not in option else option[\"timeout\"] self._conn",
"\"dk\" : '[1,40201,[\"status\"],45001,[\"operation\",\"opid\"]]', \"dt\": \"nd\", \"children\" : [ #{\"id\" :",
"3 if \"timeout\" not in option else option[\"timeout\"] self._conn =",
"\"....... befor lock for write\" with self._lock: time.sleep(KSX3267MateV2._SLEEP) print \".......",
"res = self.readregister(conn, KSX3267MateV2._DEVCODEREG, size, unit) if res is None",
"socket.SOCK_STREAM) servsoc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) servsoc.bind((opt['host'], opt['port'])) servsoc.listen(1) self._logger.info(\"listen : \"",
"device if noti is None: if info is None: noti",
"lock for read\" with self._lock: time.sleep(KSX3267MateV2._SLEEP) #mrchoi87 self._logger.info(\"read_holding_registers: \" +",
"elif DevType.isactuator(dev['dt']) or DevType.isnode(dev['dt']): # modbus code = self.processrequest(dev, blk,",
"\" + str(key)) return ResCode.FAIL_WRONG_KEYWORD if KSX3267MateV2._KEYWORDS[key][0] == 1: registers.append(val)",
"\"=======================================#4\" time.sleep(10) req = Request(201) req.setcommand(202, CmdCode.OPEN, {}) kdmate.writeblk(req) time.sleep(5)",
"opt = { 'conn' : [{ 'method': 'rtu', 'port' :",
"needed for this operation. \" + str(params['operation']) + \", \"",
"readinfofromdev(self, conn, dev): size = self.getsize(self.getdk(dev, 2)) #for _ in",
"= self._conn[gw[\"dk\"]] ret[\"conn\"] = conn info = self.readinfofromdev(conn, node) if",
"is None: continue self.sendobservation(msg) def sendnoti(self): for gw in self._devinfo:",
"(\"Found a node : \" + str(unit) + \" \"",
"\"id\" : \"1\", \"dk\" : \"JND2\", \"dt\": \"gw\", \"children\" :",
": \" + str(ex)) tmp[\"status\"] = 5 # error def",
"time.sleep(KSX3267MateV2._SLEEP) #mrchoi87 self._logger.info(\"read_holding_registers: \" + str(unit) + \" \" +",
"to read sensor info : \" + str(dev) + \"",
"0 elif key in params: val = params[key] else: self._logger.warn(\"Wrong",
"client.\") ret = self.listen(opt) msg = \"failed to connect with",
": \"103\", \"dk\" : '[1,41020,[\"value\",\"status\"]]', \"dt\": \"sen\"} # {\"id\" :",
"if vtype == \"float\": val = struct.unpack('f', struct.pack('HH', values[idx], values[idx+1]))[0]",
"from \" + str(dev['dk']) + \" \" + str(res)) #",
"port \" + str(port) + \" detection is canceled.\") break",
"\"float\"), \"pH\": (2, \"float\"), \"on-sec\" : (1, \"short\"), \"start-area\" :",
": \" + str(act) + \" however continue to read",
"= Request(None) req.setcommand(\"1\", CmdCode.CANCEL_DETECT, {}) print \"=======================================#4\" kdmate.writeblk(req) print \"=======================================#4\"",
"Started if noti: noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) for port, info in detected.iteritems():",
"False response = Response(blk) cmd = blk.getcommand() nd = self._devinfo.finddevbyid(blk.getnodeid())",
"Exception as ex: self._logger.warn(\"fail to read holding registers. : \"",
"\"dk\" : (2,40221,[\"opid\",\"status\"],45021,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"204\", \"dk\" :",
"= \"It's a wrong connection method. \" + str(opt['method']) if",
"(1, \"short\"), \"stop-area\": (1, \"short\"), \"epoch\" : (2, \"int\"), \"vfloat\":",
"if i % 3 == 0: self.sendnoticeforactuatorstatus(ret) ret[\"act\"] = {}",
": (1, \"short\"), \"remain-time\" : (2, \"int\"), \"control\": (1, \"control\"),",
"blk, nd) self._logger.info(\"Actuator processed : \" + str(code)) elif DevType.isgateway(dev['dt']):",
"print \"....... lock for write\", self.getdk(dev, 3), registers res =",
"\"act/switch/level0\"}, #{\"id\" : \"205\", \"dk\" : (2,40241,[\"opid\",\"status\"],45041,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\"",
"ndinfo): if StatCode.has_value(ndinfo[\"nd\"][\"status\"]) == False: ndinfo[\"nd\"][\"status\"] = StatCode.ERROR.value obsblk =",
"str(key)) # return ResCode.FAIL_WRONG_KEYWORD print \"....... befor lock for write\"",
"(2, \"float\"), \"on-sec\" : (1, \"short\"), \"start-area\" : (1, \"short\"),",
"2: tmp[\"thd\"].stop() tmp[\"thd\"].join() def connectone(self, opt): ret = False conn",
"msg = self.readactinfo(node, dev) if msg is None: self._logger.warn(\"Fail to",
"reserved. # import struct import time import socket import select",
"= Request(None) req.setcommand(\"1\", CmdCode.CANCEL_DETECT, {}) print \"=======================================#2\" kdmate.writeblk(req) print \"=======================================#2\"",
"befor lock for write\" with self._lock: time.sleep(KSX3267MateV2._SLEEP) print \"....... lock",
"val = struct.unpack('f', struct.pack('HH', values[idx], values[idx+1]))[0] elif vtype == \"int\":",
"mate = Mate ({}, [], \"1\", None) kdmate.start (mate.writeblk) print",
"False conn = None if opt['method'] == 'rtu': conn =",
"\"dk\" : '[1,40251,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"107\", \"dk\" :",
"get status from \" + str(dev['dk'])) # break elif res.isError():",
"== opt[\"port\"]: self._logger.warn(\" port [\" + str(opt[\"port\"]) + \"] exception",
"TTA_1 = 201 class KSX3267MateV2(ThreadMate): _SLEEP = 0.5 _VERSION =",
"\"operation\" : (1, \"operation\"), \"time\" : (2, \"int\"), \"opentime\" :",
"ModbusTcpClient(timeout=self._timeout) conn.socket = clisoc self._conn[opt[\"port\"]] = conn tmp[\"status\"] = 10",
"#self._nodes = self._devinfo.getgw()[\"children\"] self._lock = Lock() self._logger.info(\"KSX3267MateV2 Started.\") def detect_node(self,",
"\"received message\", blk.getdevid(), self._coupleid if BlkType.isrequest(blk.gettype()) is False: self._logger.warn(\"The message",
"info = self.readinfofromdev(ret[\"conn\"], dev) if info: ret[\"act\"][dev[\"id\"]] = info else:",
": '[2,40209,[\"opid\",\"status\",\"state-hold-time\",\"remain-time\"],40213,[\"operation\",\"opid\",\"time\"]]', \"dt\": \"act/retractable/level1\"}, {\"id\" : \"203\", \"dk\" : '[2,40216,[\"value\",\"status\"]]',",
"self._detection[\"opid\"]) self.writecb(noti) self.setdetection(False) return ResCode.OK def _listen(self, opt): try: servsoc",
"unit) if res is None or res.isError(): continue if len(res.registers)",
"+ \", \" + str(dev)) code = ResCode.FAIL elif dev",
"is None or res.isError(): self._logger.warn(\"Fail to get devices from \"",
"a node : \" + str(unit) + \" \" +",
"\"104\", \"dk\" : '[1,40231,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"105\", \"dk\"",
"code = NotiCode.TCP_CONNECTED if ret else NotiCode.RTU_FAILED_CONNECTION elif opt['method'] ==",
"+ str(size) + \" \" + str(len(res.registers))) return None def",
"self.detectone(port, conn) detected[port] = info self._logger.info (\"finished to detect devices",
"self._logger.warn(\"Fail to write a request to dev.\" + str(dev) +",
"ResCode, CmdCode, Observation, Request, Response, NotiCode, Notice from pymodbus.client.sync import",
"self._conn[opt[\"port\"][8:]] = conn super(KSX3267MateV2, self).connect() return ret def closeone(self, port):",
"node['children']: if DevType.issensor(dev[\"dt\"]): info = self.readinfofromdev(ret[\"conn\"], dev) if info: ret[\"sen\"][dev[\"id\"]]",
": '[1,40201,[\"status\"],45001,[\"operation\",\"opid\"]]', \"dt\": \"nd\", \"children\" : [ #{\"id\" : \"102\",",
"\"act/retractable/level0\"}, {\"id\" : \"303\", \"dk\" : (3,40221,[\"opid\",\"status\"],45021,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"}, {\"id\"",
"print \"read register\", unit, addr, count try: return conn.read_holding_registers(addr, count,",
"False for opt in self._option['conn']: conn = self.connectone(opt) if conn:",
"None or res.isError(): noti = Notice(None, NotiCode.DETECT_NO_NODE, devid=tempid) # Detection",
"None res = None for _ in range(3): res =",
"self._logger.warn(\"fail to get status from \" + str(dev['dk'])) # break",
"'[1,40231,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"105\", \"dk\" : '[1,40241,[\"value\",\"status\"]]', \"dt\":",
"if noti: noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) self.writecb(noti) noti = None info =",
"# } ] }] \"\"\" }, { \"id\" : \"201\",",
"data since size of data is not matched. \" +",
"if len(res.registers) == size: return self.parseregisters(self.getdk(dev, 2), res.registers) else: self._logger.info(\"retry",
"self._logger.warn(\"fail to read sensor info : \" + str(dev) +",
"devid, info in ndinfo[\"act\"].iteritems(): blk.setcontent(devid, info) self.writecb(blk) def start(self, writecb):",
"ModbusTcpClient class NodeType(IntEnum): SENNODE = 1 ACTNODE = 2 INTNODE",
"def sendobservation(self, ndinfo): if StatCode.has_value(ndinfo[\"nd\"][\"status\"]) == False: ndinfo[\"nd\"][\"status\"] = StatCode.ERROR.value",
"\"id\" : \"301\", \"dk\" : (3,40201,[\"opid\",\"status\"],45001,[\"operation\",\"opid\"]), \"dt\": \"nd\", \"children\" :",
"or res.isError(): self._logger.warn(\"Fail to get devices from \" + str(unit)",
"ndinfo[\"sen\"].iteritems(): if StatCode.has_value(info[\"status\"]) == False: info[\"status\"] = StatCode.ERROR.value obsblk.setobservation(devid, info[\"value\"],",
"\"dt\": \"sen\"}, #{\"id\" : \"106\", \"dk\" : '[1,40251,[\"value\",\"status\"]]', \"dt\": \"sen\"},",
"{\"id\" : \"302\", \"dk\" : (3,40211,[\"opid\",\"status\"],45011,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"}, {\"id\" :",
"with self._lock: time.sleep(KSX3267MateV2._SLEEP) #mrchoi87 self._logger.info(\"read_holding_registers: \" + str(unit) + \"",
"self._logger.warn(\"The message is not request. \" + str(blk.gettype())) return False",
"mblock import MBlock, BlkType, StatCode, ResCode, CmdCode, Observation, Request, Response,",
"str(blk) + \", \" + str(dev)) code = ResCode.FAIL response.setresult(code)",
"\" + str(dev['dk'])) # break elif res.isError(): self._logger.info(\"retry to get",
"unit) if res is None or res.isError(): self._logger.warn(\"Fail to get",
": '[1,40221,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"104\", \"dk\" : '[1,40231,[\"value\",\"status\"]]',",
"NotiCode.DETECT_NODE_STARTED, devid=tempid) # Detection Started if noti: noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) self.writecb(noti)",
"None: self._logger.warn(\"There is no device. \" + str(blk.getdevid())) code =",
"self).connect() return ret def closeone(self, port): self._conn[port].close() def close(self): for",
"self._coupleid if BlkType.isrequest(blk.gettype()) is False: self._logger.warn(\"The message is not request.",
"conn.socket = clisoc self._conn[opt[\"port\"]] = conn tmp[\"status\"] = 10 #",
"return -1 return size if __name__ == \"__main__\": isnutri =",
"self._lock: time.sleep(KSX3267MateV2._SLEEP) print \"....... lock for write\", self.getdk(dev, 3), registers",
"print \"noti\", noti.stringify() self.writecb(noti) time.sleep(0.1) return detected def canceldetection(self, params):",
"return None def readnodeinfo(self, node): ret = {\"id\" : node[\"id\"],",
"NotiCode.DETECT_NO_NODE, devid=tempid) # Detection Started self._logger.info (\"Fail to get information",
"ret[nm] = val idx = idx + size print \"parsed\",",
"\"dk\" : '[1,40211,[\"control\",\"status\",\"area\",\"alert\",\"opid\"],45001,[\"operation\", \"opid\", \"control\",\"EC\",\"pH\", \"start-area\", \"stop-area\", \"on-sec\"]]', \"dt\": \"nutrient-supply/level1\"},",
"flag self._detection[\"opid\"] = opid def startdetection(self, params, opid): if self._detection[\"opid\"]",
"dev, request, node): gw = self._devinfo.findgateway(request.getnodeid()) unit = self.getdk(dev, 0)",
"while to connect a client.\") ret = self.listen(opt) msg =",
"self.sendnoticeforactuatorstatus(ret) def sendobservation(self, ndinfo): if StatCode.has_value(ndinfo[\"nd\"][\"status\"]) == False: ndinfo[\"nd\"][\"status\"] =",
"port in self._conn.keys(): self.closeone(port) super(KSX3267MateV2, self).close() def readmsg(self): self._msgq =",
"\"dk\" : '[1,40221,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"104\", \"dk\" :",
"sock == servsoc: clisoc, address = servsoc.accept() self._logger.info(\"client connected from",
"\" \" + str(res)) elif res.registers[1] in (NodeType.SENNODE, NodeType.ACTNODE, NodeType.INTNODE):",
"\"1\", \"dk\" : \"\", \"dt\": \"gw\", \"children\" : [{ \"id\"",
"== CmdCode.CANCEL_DETECT: print \"cancel to detect device\" code = self.canceldetection(params)",
"+ str(key)) return ResCode.FAIL_WRONG_KEYWORD if KSX3267MateV2._KEYWORDS[key][0] == 1: registers.append(val) elif",
"res.registers} def getdk(self, dev, idx): dk = json.loads(dev[\"dk\"]) return dk[idx]",
"= [] for key in self.getdk(dev, 4): if key not",
"tmp[\"status\"] = 5 # error def listen(self, opt): tmp =",
"\"dk\" : '[1,40301,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"113\", \"dk\" :",
"= self._devinfo.getgw()[\"children\"] self._lock = Lock() self._logger.info(\"KSX3267MateV2 Started.\") def detect_node(self, conn,",
": \"103\", \"dk\" : '[1,220,[\"value\",\"status\"]]', \"dt\": \"sen\"} # \"id\" :",
"#else: # self._logger.warn(\"This param is needed for this operation. \"",
"\" + str(dev['dt'])) code = ResCode.FAIL_NOT_PROPER_COMMAND elif DevType.isactuator(dev['dt']) or DevType.isnode(dev['dt']):",
": (2, \"float\"), \"status\" : (1, \"status\"), \"opid\" : (1,",
"\"102\", \"dk\" : '[1,210,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"103\", \"dk\"",
": (2,40221,[\"opid\",\"status\"],45021,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"204\", \"dk\" : (2,40231,[\"opid\",\"status\"],45031,[\"operation\",\"opid\"]),",
"\"dk\" : '[1,40261,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"109\", \"dk\" :",
"(2, \"int\"), \"opentime\" : (1, \"short\"), \"closetime\" : (1, \"short\"),",
"\"sen\"} ]} ]} ] devinfo = [{ \"id\" : \"1\",",
"self._detection[\"opid\"]) self.writecb(noti) noti = None info = None res =",
"\"202\", \"dk\" : '[2,40209,[\"opid\",\"status\",\"state-hold-time\",\"remain-time\"],40213,[\"operation\",\"opid\",\"time\"]]', \"dt\": \"act/retractable/level1\"}, {\"id\" : \"203\", \"dk\"",
"print \"mate started\" time.sleep(10) req = Request(None) req.setcommand(\"1\", CmdCode.DETECT_DEVICE, None)",
"size = self.getsize(self.getdk(dev, 2)) #for _ in range(3): res =",
"False: self._logger.info(\"Total detection is canceled.\") break info = self.detectone(port, conn)",
"if DevType.issensor(dev[\"dt\"]): info = self.readinfofromdev(ret[\"conn\"], dev) if info: ret[\"sen\"][dev[\"id\"]] =",
"in ndinfo[\"sen\"].iteritems(): if StatCode.has_value(info[\"status\"]) == False: info[\"status\"] = StatCode.ERROR.value obsblk.setobservation(devid,",
"kdmate.writeblk(req) time.sleep(10) req = Request(201) req.setcommand(202, CmdCode.TIMED_OPEN, {\"time\":10}) kdmate.writeblk(req) time.sleep(15)",
"self._detection[\"eaddr\"] = params['eaddr'] self._detection[\"port\"] = params['port'] else: self._detection[\"saddr\"] = 1",
"devices : \" + str(detected)) noti = Notice(None, NotiCode.DETECT_FINISHED) #",
"ResCode.FAIL_NOT_PROPER_COMMAND elif DevType.isactuator(dev['dt']) or DevType.isnode(dev['dt']): # modbus code = self.processrequest(dev,",
"= self.getdk(dev, 0) operation = request.getcommand() params = request.getparams() params[\"operation\"]",
": '[1,40211,[\"control\",\"status\",\"area\",\"alert\",\"opid\"],45001,[\"operation\", \"opid\", \"control\",\"EC\",\"pH\", \"start-area\", \"stop-area\", \"on-sec\"]]', \"dt\": \"nutrient-supply/level1\"}, {\"id\"",
"time.sleep(10) req = Request(None) req.setcommand(\"1\", CmdCode.DETECT_DEVICE, None) print \"=======================================#1\" kdmate.writeblk(req)",
"== ProtoVer.KS_X_3267_2020 or res.registers[3] == ProtoVer.KS_X_3267_2018: info = self.detect_node(conn, unit,",
"unit, registers compcode = registers[0] nodecode = registers[2] size =",
"to get status from \" + str(dev['dk']) + \" \"",
"port, conn): detected = {} if self._detection[\"port\"] is not None",
"None: continue self.sendobservation(msg) def sendnoti(self): for gw in self._devinfo: for",
"0, StatCode(info[\"status\"])) self.writecb(obsblk) def sendnoticeforactuatorstatus(self, ndinfo): blk = Notice(ndinfo[\"id\"], NotiCode.ACTUATOR_STATUS,",
"break info = self.detectone(port, conn) detected[port] = info self._logger.info (\"finished",
"{}, \"act\" : {}, \"nd\" : {\"status\":StatCode.ERROR.value}} gw = self._devinfo.findgateway(node[\"id\"])",
"return ResCode.OK def _listen(self, opt): try: servsoc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)",
"read actuator info : \" + str(act) + \" however",
"{\"compcode\" : compcode, \"nodecode\" : nodecode, \"devcodes\": res.registers} def getdk(self,",
"\"dk\" : '[1,40208,[\"value\",\"status\"]]', \"dt\": \"sen\"}, # {\"id\" : \"105\", \"dk\"",
"node : \" + str(unit) + \" \" + str(res))",
"<filename>gate/mate_ksx3267v2.py #!/usr/bin/env python # # -*- coding: utf-8 -*- #",
"else: kdmate = KSX3267MateV2(opt, devinfo, \"1\", None) mate = Mate",
"noti: noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) self.writecb(noti) noti = None info = None",
"= Notice(None, NotiCode.RTU_CONNECTED) # detection is canceled self.writecb(noti) return conn",
"gw in self._devinfo: for nd in gw[\"children\"]: self._msgq.append(self.readsensornodeinfo(nd)) if self._isdetecting:",
"\"dt\": \"sen\"}, {\"id\" : \"110\", \"dk\" : '[1,40281,[\"value\",\"status\"]]', \"dt\": \"sen\"},",
"\"sen\"}, #{\"id\" : \"108\", \"dk\" : '[1,40271,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\"",
"info self._logger.info (\"finished to detect devices : \" + str(detected))",
"param is not used for this operation # However, the",
"code = NotiCode.TCP_WAITING if ret else NotiCode.RTU_FAILED_CONNECTION conn = None",
"\"dk\" : (3,40201,[\"opid\",\"status\"],45001,[\"operation\",\"opid\"]), \"dt\": \"nd\", \"children\" : [ {\"id\" :",
"\" + str(res)) elif res.registers[1] in (NodeType.SENNODE, NodeType.ACTNODE, NodeType.INTNODE): #",
"wsoc, esoc = select.select([servsoc], [], [], 10) for sock in",
": [ {\"id\" : \"302\", \"dk\" : (3,40211,[\"opid\",\"status\"],45011,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"},",
"= Request(201) req.setcommand(202, CmdCode.OPEN, {}) kdmate.writeblk(req) time.sleep(5) req = Request(201)",
"elif dev is None: self._logger.warn(\"There is no device. \" +",
"= False except Exception as ex: servsoc.close() for tmp in",
"count, unit=unit) except Exception as ex: self._logger.warn(\"fail to read holding",
"\"dk\" : '[1,40291,[\"value\",\"status\"]]', \"dt\": \"sen\"} # ] # } ]",
"{}) print \"=======================================#2\" kdmate.writeblk(req) print \"=======================================#2\" time.sleep(1) req = Request(None)",
"continue return {\"compcode\" : compcode, \"nodecode\" : nodecode, \"devcodes\": res.registers}",
"import traceback import hashlib import json from enum import IntEnum",
": \"207\", \"dk\" : (2,40261,[\"opid\",\"status\"],45061,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"208\",",
"req = Request(None) req.setcommand(\"1\", CmdCode.CANCEL_DETECT, {}) print \"=======================================#2\" kdmate.writeblk(req) print",
"for actuator #for devid, info in ndinfo[\"act\"].iteritems(): # if StatCode.has_value(info[\"status\"])",
"= ResCode.FAIL response.setresult(code) self._logger.info(\"write response: \" + str(response)) self.writecb(response) return",
"req = Request(201) req.setcommand(202, CmdCode.TIMED_CLOSE, {\"time\":10}) kdmate.writeblk(req) time.sleep(5) req =",
"[], \"saddr\":0, \"eaddr\":0, \"opid\":0} #self._nodes = self._devinfo.getgw()[\"children\"] self._lock = Lock()",
"#{\"id\" : \"103\", \"dk\" : '[1,41020,[\"value\",\"status\"]]', \"dt\": \"sen\"} # {\"id\"",
"str(len(res.registers))) return None def readnodeinfo(self, node): ret = {\"id\" :",
"Request, Response, NotiCode, Notice from pymodbus.client.sync import ModbusSerialClient from pymodbus.client.sync",
"for unit in range(self._detection[\"saddr\"], self._detection[\"eaddr\"]): if self._isdetecting == False or",
"\"dk\" : '[2,40216,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"204\", \"dk\" :",
"send observation for actuator #for devid, info in ndinfo[\"act\"].iteritems(): #",
": (2, \"int\"), \"control\": (1, \"control\"), \"area\" : (1, \"short\"),",
"\"dk\" : '[1,40281,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"111\", \"dk\" :",
"pymodbus.client.sync import ModbusSerialClient from pymodbus.client.sync import ModbusTcpClient class NodeType(IntEnum): SENNODE",
"register\", unit, addr, count try: return conn.read_holding_registers(addr, count, unit=unit) except",
"port [\" + str(opt[\"port\"]) + \"] exception : \" +",
"res.registers[1] == NodeType.NUTNODE: if res.registers[3] == ProtoVer.TTA_1: info = self.detect_node(conn,",
"KS_X_3267_2018 = 101 TTA_1 = 201 class KSX3267MateV2(ThreadMate): _SLEEP =",
"\"opid\" : (1, \"short\"), \"state-hold-time\" : (2, \"int\"), \"ratio\": (1,",
"info: ret[\"act\"][dev[\"id\"]] = info i = i + 1 if",
"None or res.isError(): continue if len(res.registers) != 6: self._logger.info(\"retry to",
"for port, conn in self._conn.iteritems(): if self._isdetecting == False or",
"tempid = port + \"-\" + str(unit) noti = Notice(None,",
"Notice(None, NotiCode.DETECT_UNKNOWN_PROTOCOL_VER, devid=tempid) # unknown protocol version elif res.registers[1] ==",
"\"hold-time\" : (2, \"int\"), \"operation\" : (1, \"operation\"), \"time\" :",
"\"sen\"}, {\"id\" : \"111\", \"dk\" : '[1,40291,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\"",
"\"dk\" : '[1,40211,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"106\", \"dk\" :",
"in range(3): res = self.readregister(conn, KSX3267MateV2._DEVINFOREG, 6, unit) if res",
"str(dev)) code = ResCode.FAIL response.setresult(code) self._logger.info(\"write response: \" + str(response))",
"devinfo, coupleid, logger) self._timeout = 3 if \"timeout\" not in",
"def connect(self): ret = False for opt in self._option['conn']: conn",
"0.5 _VERSION = \"KSX3267_0.1\" _KEYWORDS = {\"value\" : (2, \"float\"),",
"res is None: self._logger.warn(\"fail to get status from \" +",
"import MBlock, BlkType, StatCode, ResCode, CmdCode, Observation, Request, Response, NotiCode,",
"\"=======================================#4\" kdmate.writeblk(req) print \"=======================================#4\" time.sleep(10) req = Request(201) req.setcommand(202, CmdCode.OPEN,",
": [ # { # \"id\" : \"101\", \"dk\" :",
": \"108\", \"dk\" : '[1,40271,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"109\",",
"receive a request\") code = ResCode.FAIL else: self._logger.warn(\"Unknown Error. \"",
"= 0 ret = {} for nm in names: (size,",
"dev in node['children']: if DevType.issensor(dev[\"dt\"]) == False: info = self.readinfofromdev(ret[\"conn\"],",
"self._logger.info(\"A port \" + str(port) + \" detection is canceled.\")",
"str(code)) elif DevType.isgateway(dev['dt']): self._logger.info(\"Gateway does not receive a request\") code",
"(1, \"short\"), \"EC\": (2, \"float\"), \"pH\": (2, \"float\"), \"on-sec\" :",
"Notice(None, NotiCode.DETECT_WRONG_DEVICE, devid=tempid) # fail to find a node else:",
"self.getdk(dev, 3), registers res = self._conn[gw[\"dk\"]].write_registers(self.getdk(dev, 3), registers, unit=unit) if",
"\"dt\": \"nd\", \"children\" : [ #{\"id\" : \"102\", \"dk\" :",
"'[2,40219,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"203\", \"dk\" : (2,40221,[\"opid\",\"status\"],45021,[\"operation\",\"opid\"]), \"dt\":",
"self._logger.info(\"read_holding_registers: \" + str(unit) + \" \" + str(addr) +",
"for nm in names: (size, vtype) = KSX3267MateV2._KEYWORDS[nm] if vtype",
"self._msgq: if msg is None: continue self.sendobservation(msg) def sendnoti(self): for",
"} nutriinfo = [{ \"id\" : \"1\", \"dk\" : \"\",",
"\"devcodes\": res.registers} def getdk(self, dev, idx): dk = json.loads(dev[\"dk\"]) return",
"{\"id\" : \"106\", \"dk\" : '[1,40251,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" :",
": \" + str(unit) + \" \" + str(info)) else:",
"device. \" + str(blk.getdevid())) code = ResCode.FAIL_NO_DEVICE elif DevType.ispropercommand(dev['dt'], cmd)",
"\"id\" : \"201\", \"dk\" : '[2,40201,[\"status\"],45001,[\"operation\",\"opid\"]]', \"dt\": \"nd\", \"children\" :",
"self.isexecuting() == False: self._logger.info(\"A port \" + str(port) + \"",
"detected = {} for port, conn in self._conn.iteritems(): if self._isdetecting",
"= 1 self._detection[\"eaddr\"] = 12 self._detection[\"port\"] = None return ResCode.OK",
"dev status.\") else: self.sendnoticeforactuatorstatus(msg) return ResCode.OK def writeblk(self, blk): print",
"\"103\", \"dk\" : '[1,40221,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"104\", \"dk\"",
": '[1,40251,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"107\", \"dk\" : '[1,40261,[\"value\",\"status\"]]',",
"unit=unit) if res.isError(): self._logger.warn(\"Fail to write a request to dev.\"",
"'[1,40311,[\"value\",\"status\"]]', \"dt\": \"sen\"} ]} ]} ] devinfo = [{ \"id\"",
"str(res) + \":\" + str(request)) return ResCode.FAIL_TO_WRITE msg = self.readactinfo(node,",
"= 1 ACTNODE = 2 INTNODE = 3 NUTNODE =",
"import Mate, ThreadMate, DevType from mblock import MBlock, BlkType, StatCode,",
"= True while executing: self._logger.info(\"waiting a client~\") rsoc, wsoc, esoc",
"self._tempthd: if tmp[\"port\"] == opt[\"port\"]: conn = ModbusTcpClient(timeout=self._timeout) conn.socket =",
"{}, \"nd\" : {\"status\":StatCode.ERROR.value}} gw = self._devinfo.findgateway(node[\"id\"]) conn = self._conn[gw[\"dk\"]]",
"executing: self._logger.info(\"waiting a client~\") rsoc, wsoc, esoc = select.select([servsoc], [],",
"False: self._logger.info(\"A port \" + str(port) + \" detection is",
"Detection Started self._logger.info (\"Fail to get information from a node",
"{ # \"id\" : \"101\", \"dk\" : '[1,201,[\"status\"],301,[\"operation\",\"opid\"]]', \"dt\": \"nd\",",
"\"109\", \"dk\" : '[1,40271,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"110\", \"dk\"",
"\"dt\": \"sen\"}, {\"id\" : \"112\", \"dk\" : '[1,40301,[\"value\",\"status\"]]', \"dt\": \"sen\"},",
"\"act/retractable/level1\"}, {\"id\" : \"202\", \"dk\" : '[2,40209,[\"opid\",\"status\",\"state-hold-time\",\"remain-time\"],40213,[\"operation\",\"opid\",\"time\"]]', \"dt\": \"act/retractable/level1\"}, {\"id\"",
"Notice(None, NotiCode.RTU_FAILED_CONNECTION) # detection is canceled else: noti = Notice(None,",
"KSX3267MateV2._KEYWORDS[key][1] == \"int\": registers.extend(struct.unpack('HH', struct.pack('i', val))) elif KSX3267MateV2._KEYWORDS[key][1] == \"float\":",
"+ str(k)) return -1 return size if __name__ == \"__main__\":",
"NotiCode.RTU_CONNECTED) # detection is canceled self.writecb(noti) return conn def connect(self):",
"\" + str(ex)) return None def detect(self): detected = {}",
"def readmsg(self): self._msgq = [] for gw in self._devinfo: for",
"in lst: if k in KSX3267MateV2._KEYWORDS: size = size +",
"= blk.getparams() if cmd == CmdCode.DETECT_DEVICE: print \"detect device\" code",
"registers.extend(struct.unpack('HH', struct.pack('f', val))) #else: # self._logger.warn(\"This param is needed for",
"\"short\"), \"start-area\" : (1, \"short\"), \"stop-area\": (1, \"short\"), \"epoch\" :",
"\"eaddr\":0, \"opid\":0} #self._nodes = self._devinfo.getgw()[\"children\"] self._lock = Lock() self._logger.info(\"KSX3267MateV2 Started.\")",
"compcode, \"nodecode\" : nodecode, \"devcodes\": res.registers} def getdk(self, dev, idx):",
"[\"operation\", \"opid\"] registers = [] for key in self.getdk(dev, 4):",
"conn tmp[\"status\"] = 10 # connected executing = False except",
"NotiCode.ACTUATOR_STATUS, ndinfo[\"id\"], ndinfo[\"nd\"]) for devid, info in ndinfo[\"act\"].iteritems(): blk.setcontent(devid, info)",
": (1, \"short\"), \"state-hold-time\" : (2, \"int\"), \"ratio\": (1, \"short\"),",
"(\"Found a nutrient system : \" + str(unit) + \"",
"\"....... lock for write\", self.getdk(dev, 3), registers res = self._conn[gw[\"dk\"]].write_registers(self.getdk(dev,",
"noti = None info = None res = None for",
"def close(self): for port in self._conn.keys(): self.closeone(port) super(KSX3267MateV2, self).close() def",
": (3,40221,[\"opid\",\"status\"],45021,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"}, {\"id\" : \"304\", \"dk\" : (3,40231,[\"opid\",\"status\"],45031,[\"operation\",\"opid\"]),",
"str(unit) + \" \" + str(res)) elif res.registers[1] in (NodeType.SENNODE,",
"def detect(self): detected = {} for port, conn in self._conn.iteritems():",
"False: info = self.readinfofromdev(ret[\"conn\"], dev) if info: ret[\"act\"][dev[\"id\"]] = info",
"nd = self._devinfo.finddevbyid(blk.getnodeid()) dev = self._devinfo.finddevbyid(blk.getdevid()) if blk.getdevid() == self._coupleid:",
"\"gw\", \"children\" : [{ \"id\" : \"101\", \"dk\" : '[1,40201,[\"status\"],45001,[\"operation\",\"opid\"]]',",
"self._conn = {} self._tempthd = [] self._isdetecting = False self._detection",
"gw[\"children\"]: self._msgq.append(self.readsensornodeinfo(nd)) if self._isdetecting: self.detect() self.checktempthreads() def processrequest(self, dev, request,",
"size =0 for k in lst: if k in KSX3267MateV2._KEYWORDS:",
"#{\"id\" : \"209\", \"dk\" : (2,40281,[\"opid\",\"status\"],45081,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"} ] },",
"\"int\"), \"operation\" : (1, \"operation\"), \"time\" : (2, \"int\"), \"opentime\"",
"'[1,220,[\"value\",\"status\"]]', \"dt\": \"sen\"} # \"id\" : \"101\", \"dk\" : '[1,40201,[\"status\"],45001,[\"operation\",\"opid\"]]',",
"canceled noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) self.writecb(noti) self.setdetection(False) return ResCode.OK def _listen(self, opt):",
"Observation, Request, Response, NotiCode, Notice from pymodbus.client.sync import ModbusSerialClient from",
"+ str(blk.getdevid())) code = ResCode.FAIL_NO_DEVICE elif DevType.ispropercommand(dev['dt'], cmd) is False:",
"= Notice(None, NotiCode.DETECT_WRONG_DEVICE, devid=tempid) # fail to find a node",
"= {} if self._detection[\"port\"] is not None and port not",
": \"110\", \"dk\" : '[1,40281,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"111\",",
"for gw in self._devinfo: for node in gw[\"children\"]: ret =",
"sock in rsoc: if sock == servsoc: clisoc, address =",
"params = blk.getparams() if cmd == CmdCode.DETECT_DEVICE: print \"detect device\"",
"return ret def readinfofromdev(self, conn, dev): size = self.getsize(self.getdk(dev, 2))",
"info = None res = None for _ in range(3):",
"get information from a node : \" + str(unit) +",
"\"sen\"}, {\"id\" : \"204\", \"dk\" : '[2,40219,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\"",
"= 5 # error def listen(self, opt): tmp = {\"thd\"",
"processed : \" + str(code)) elif DevType.isgateway(dev['dt']): self._logger.info(\"Gateway does not",
"nd in gw[\"children\"]: self._msgq.append(self.readsensornodeinfo(nd)) if self._isdetecting: self.detect() self.checktempthreads() def processrequest(self,",
"== 0: self.sendnoticeforactuatorstatus(ret) ret[\"act\"] = {} self.sendnoticeforactuatorstatus(ret) def sendobservation(self, ndinfo):",
"Lock() self._logger.info(\"KSX3267MateV2 Started.\") def detect_node(self, conn, unit, registers): print \"detect_node\",",
"\"dk\" : '[1,40261,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"108\", \"dk\" :",
"'[1,40241,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"106\", \"dk\" : '[1,40251,[\"value\",\"status\"]]', \"dt\":",
"noti.stringify() self.writecb(noti) time.sleep(0.1) return detected def canceldetection(self, params): time.sleep(self._timeout) noti",
"str(dev['dt'])) code = ResCode.FAIL_NOT_PROPER_COMMAND elif DevType.isactuator(dev['dt']) or DevType.isnode(dev['dt']): # modbus",
": \"202\", \"dk\" : '[2,40209,[\"opid\",\"status\",\"state-hold-time\",\"remain-time\"],40213,[\"operation\",\"opid\",\"time\"]]', \"dt\": \"act/retractable/level1\"}, {\"id\" : \"203\",",
"# unknown protocol version else: noti = Notice(unit, NotiCode.DETECT_UNKNOWN_NODE, devid=tempid)",
"== opt[\"port\"]: conn = ModbusTcpClient(timeout=self._timeout) conn.socket = clisoc self._conn[opt[\"port\"]] =",
"(\"Fail to get information from a node : \" +",
"if params: self._detection[\"saddr\"] = params['saddr'] self._detection[\"eaddr\"] = params['eaddr'] self._detection[\"port\"] =",
"kdmate.writeblk(req) print \"=======================================#3\" time.sleep(1) req = Request(None) req.setcommand(\"1\", CmdCode.CANCEL_DETECT, {})",
"+ \", \" + str(dev)) code = ResCode.FAIL response.setresult(code) self._logger.info(\"write",
"str(count)) print \"read register\", unit, addr, count try: return conn.read_holding_registers(addr,",
"opt['port'])) servsoc.listen(1) self._logger.info(\"listen : \" + str(opt)) executing = True",
"\"nutrient-supply/level1\"}, {\"id\" : \"103\", \"dk\" : '[1,40221,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\"",
"= params[key] else: self._logger.warn(\"Wrong Keyword : \" + str(key)) return",
": \" + str(unit) + \" \" + str(res)) elif",
"ProtoVer.KS_X_3267_2020 or res.registers[3] == ProtoVer.KS_X_3267_2018: info = self.detect_node(conn, unit, res.registers)",
"if blk.getdevid() == self._coupleid: params = blk.getparams() if cmd ==",
"# Detection Started if noti: noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) self.writecb(noti) noti =",
"#for unit in range(self._detection[\"saddr\"], 12): for unit in range(self._detection[\"saddr\"], self._detection[\"eaddr\"]):",
"compcode = registers[0] nodecode = registers[2] size = registers[4] while",
"== \"int\": val = struct.unpack('i', struct.pack('HH', values[idx], values[idx+1]))[0] else: val",
": \"101\", \"dk\" : '[1,40201,[\"status\"],45001,[\"operation\",\"opid\"]]', \"dt\": \"nd\", \"children\" : [",
": '[1,40261,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"109\", \"dk\" : '[1,40271,[\"value\",\"status\"]]',",
"self._logger.info(\"Gateway does not receive a request\") code = ResCode.FAIL else:",
"== False: info = self.readinfofromdev(ret[\"conn\"], dev) if info: ret[\"act\"][dev[\"id\"]] =",
"def parseregisters(self, names, values): idx = 0 ret = {}",
"noti = Notice(None, NotiCode.RTU_CONNECTED) # detection is canceled self.writecb(noti) return",
"(3,40241,[\"opid\",\"status\"],45041,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"} ] }] }] \"\"\" if isnutri: kdmate",
"10 # connected executing = False except Exception as ex:",
"in range(self._detection[\"saddr\"], 12): for unit in range(self._detection[\"saddr\"], self._detection[\"eaddr\"]): if self._isdetecting",
"BlkType, StatCode, ResCode, CmdCode, Observation, Request, Response, NotiCode, Notice from",
"struct.unpack('f', struct.pack('HH', values[idx], values[idx+1]))[0] elif vtype == \"int\": val =",
"however continue to read other device\") return ret def readactinfo(self,",
"modbus code = self.processrequest(dev, blk, nd) self._logger.info(\"Actuator processed : \"",
": nodecode, \"devcodes\": res.registers} def getdk(self, dev, idx): dk =",
"def detectone(self, port, conn): detected = {} if self._detection[\"port\"] is",
"time.sleep(KSX3267MateV2._SLEEP) print \"....... lock for write\", self.getdk(dev, 3), registers res",
"self.readnodeinfo(node) for dev in node['children']: if DevType.issensor(dev[\"dt\"]): info = self.readinfofromdev(ret[\"conn\"],",
"self._logger.info(\"write response: \" + str(response)) self.writecb(response) return True #if code",
"'[1,41010,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"103\", \"dk\" : '[1,41020,[\"value\",\"status\"]]', \"dt\":",
"> 2: tmp[\"thd\"].stop() tmp[\"thd\"].join() def connectone(self, opt): ret = False",
"\"dt\": \"sen\"}, #{\"id\" : \"103\", \"dk\" : '[1,41020,[\"value\",\"status\"]]', \"dt\": \"sen\"}",
"str(ex)) tmp[\"status\"] = 5 # error def listen(self, opt): tmp",
"from enum import IntEnum from threading import Thread, Lock from",
"however continue to read other device\") return ret def readactnodeinfo(self,",
"[ # { # \"id\" : \"101\", \"dk\" : '[1,201,[\"status\"],301,[\"operation\",\"opid\"]]',",
"self._logger.info(\"listen : \" + str(opt)) executing = True while executing:",
"#{\"id\" : \"102\", \"dk\" : '[1,41010,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" :",
"\"dt\": \"sen\"} # {\"id\" : \"102\", \"dk\" : '[1,40202,[\"value\",\"status\"]]', \"dt\":",
"Notice(ndinfo[\"id\"], NotiCode.ACTUATOR_STATUS, ndinfo[\"id\"], ndinfo[\"nd\"]) for devid, info in ndinfo[\"act\"].iteritems(): blk.setcontent(devid,",
"write a request to dev.\" + str(dev) + \",\" +",
"if sock == servsoc: clisoc, address = servsoc.accept() self._logger.info(\"client connected",
"return self.parseregisters(self.getdk(dev, 2), res.registers) else: self._logger.info(\"retry to get data since",
"if tmp[\"port\"] == opt[\"port\"]: conn = ModbusTcpClient(timeout=self._timeout) conn.socket = clisoc",
"1 self._detection[\"eaddr\"] = 12 self._detection[\"port\"] = None return ResCode.OK def",
"ret def closeone(self, port): self._conn[port].close() def close(self): for port in",
"to read actuator info : \" + str(act) + \"",
"\" + str(blk.gettype())) return False response = Response(blk) cmd =",
": \"301\", \"dk\" : (3,40201,[\"opid\",\"status\"],45001,[\"operation\",\"opid\"]), \"dt\": \"nd\", \"children\" : [",
"(size, vtype) = KSX3267MateV2._KEYWORDS[nm] if vtype == \"float\": val =",
"+ \"-\" + str(unit) noti = Notice(None, NotiCode.DETECT_NODE_STARTED, devid=tempid) #",
"tcp\" code = NotiCode.TCP_WAITING if ret else NotiCode.RTU_FAILED_CONNECTION conn =",
"(2, \"int\"), \"vfloat\": (2, \"float\"), \"vint\" : (2, \"int\")} _DEVINFOREG",
"print \"....... before lock for read\" with self._lock: time.sleep(KSX3267MateV2._SLEEP) #mrchoi87",
": '[1,40311,[\"value\",\"status\"]]', \"dt\": \"sen\"} ]} ]} ] devinfo = [{",
"from a node : \" + str(unit) + \" \"",
"res.isError(): noti = Notice(None, NotiCode.DETECT_NO_NODE, devid=tempid) # Detection Started self._logger.info",
"= Request(201) req.setcommand(202, CmdCode.TIMED_CLOSE, {\"time\":10}) kdmate.writeblk(req) time.sleep(5) req = Request(201)",
"this operation. \" + str(params['operation']) + \", \" + str(key))",
"\"103\", \"dk\" : '[1,220,[\"value\",\"status\"]]', \"dt\": \"sen\"} # \"id\" : \"101\",",
"idx = idx + size print \"parsed\", ret return ret",
"cmd) is False: self._logger.warn(\"The request is not proper. \" +",
"detected #mrchoi87 #for unit in range(self._detection[\"saddr\"], 12): for unit in",
"self._detection[\"saddr\"] = 1 self._detection[\"eaddr\"] = 12 self._detection[\"port\"] = None return",
"\"float\"), \"on-sec\" : (1, \"short\"), \"start-area\" : (1, \"short\"), \"stop-area\":",
"None def detect(self): detected = {} for port, conn in",
"super(KSX3267MateV2, self).stop() return True def getsize(self, lst): size =0 for",
": {\"status\":StatCode.ERROR.value}} gw = self._devinfo.findgateway(node[\"id\"]) conn = self._conn[gw[\"dk\"]] ret[\"conn\"] =",
"kdmate.writeblk(req) time.sleep(15) req = Request(201) req.setcommand(202, CmdCode.TIMED_CLOSE, {\"time\":10}) kdmate.writeblk(req) time.sleep(5)",
"self.getdk(dev, 0) operation = request.getcommand() params = request.getparams() params[\"operation\"] =",
"\"sen\"}, # {\"id\" : \"103\", \"dk\" : '[1,40205,[\"value\",\"status\"]]', \"dt\": \"sen\"},",
"NotiCode.DETECT_NODE_DETECTED, devid=port, content={unit : info}) # found a node detected[unit]",
"ret[\"act\"][dev[\"id\"]] = info i = i + 1 if i",
"esoc = select.select([servsoc], [], [], 10) for sock in rsoc:",
"registers.extend(struct.unpack('HH', struct.pack('i', val))) elif KSX3267MateV2._KEYWORDS[key][1] == \"float\": registers.extend(struct.unpack('HH', struct.pack('f', val)))",
"code = self.canceldetection(params) else: self._logger.warn(\"Unknown Error. \" + str(blk) +",
"kdmate.writeblk(req) time.sleep(5) req = Request(201) req.setcommand(202, CmdCode.OFF, {}) kdmate.writeblk(req) \"\"\"",
"\"203\", \"dk\" : (2,40221,[\"opid\",\"status\"],45021,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"204\", \"dk\"",
"with tcp\" code = NotiCode.TCP_WAITING if ret else NotiCode.RTU_FAILED_CONNECTION conn",
"unit = self.getdk(dev, 0) operation = request.getcommand() params = request.getparams()",
"# if StatCode.has_value(info[\"status\"]) == False: # info[\"status\"] = StatCode.ERROR.value #",
"gw = self._devinfo.findgateway(node[\"id\"]) conn = self._conn[gw[\"dk\"]] ret[\"conn\"] = conn info",
"\"nd\", \"children\" : [ {\"id\" : \"302\", \"dk\" : (3,40211,[\"opid\",\"status\"],45011,[\"operation\",\"opid\"]),",
"return {\"compcode\" : compcode, \"nodecode\" : nodecode, \"devcodes\": res.registers} def",
"info[\"status\"] = StatCode.ERROR.value obsblk.setobservation(devid, info[\"value\"], StatCode(info[\"status\"])) # do not send",
"in gw[\"children\"]: self._msgq.append(self.readsensornodeinfo(nd)) if self._isdetecting: self.detect() self.checktempthreads() def processrequest(self, dev,",
"[{ \"id\" : \"1\", \"dk\" : \"JND2\", \"dt\": \"gw\", \"children\"",
"\" + str(opt)) executing = True while executing: self._logger.info(\"waiting a",
"connected executing = False except Exception as ex: servsoc.close() for",
"# continue else: if len(res.registers) == size: return self.parseregisters(self.getdk(dev, 2),",
"(2,40221,[\"opid\",\"status\"],45021,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"204\", \"dk\" : (2,40231,[\"opid\",\"status\"],45031,[\"operation\",\"opid\"]), \"dt\":",
"NotiCode.RTU_FAILED_CONNECTION elif opt['method'] == 'tcpcs': self._logger.info(\"It would wait for a",
"nutriinfo, \"1\", None) else: kdmate = KSX3267MateV2(opt, devinfo, \"1\", None)",
"Error. \" + str(blk) + \", \" + str(dev)) code",
"CmdCode.TIMED_OPEN, {\"time\":10}) kdmate.writeblk(req) time.sleep(15) req = Request(201) req.setcommand(202, CmdCode.TIMED_CLOSE, {\"time\":10})",
"None return ResCode.OK def readregister(self, conn, addr, count, unit): print",
"\"sen\"}, #{\"id\" : \"107\", \"dk\" : '[1,40261,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\"",
"= registers[2] size = registers[4] while True: res = self.readregister(conn,",
"by case properparams = CmdCode.getparams(operation) + [\"operation\", \"opid\"] registers =",
"self._isdetecting = flag self._detection[\"opid\"] = opid def startdetection(self, params, opid):",
"self.detect() self.checktempthreads() def processrequest(self, dev, request, node): gw = self._devinfo.findgateway(request.getnodeid())",
"print \"detect_node\", unit, registers compcode = registers[0] nodecode = registers[2]",
"names, values): idx = 0 ret = {} for nm",
"ModbusSerialClient(method='rtu', port=opt['port'], timeout=self._timeout, baudrate=opt['baudrate']) ret = conn.connect() msg = \"failed",
"self._devinfo: for nd in gw[\"children\"]: self._msgq.append(self.readsensornodeinfo(nd)) if self._isdetecting: self.detect() self.checktempthreads()",
"and port not in self._detection[\"port\"]: return detected #mrchoi87 #for unit",
": (1, \"short\"), \"start-area\" : (1, \"short\"), \"stop-area\": (1, \"short\"),",
"#for devid, info in ndinfo[\"act\"].iteritems(): # if StatCode.has_value(info[\"status\"]) == False:",
"\"status\"), \"opid\" : (1, \"short\"), \"state-hold-time\" : (2, \"int\"), \"ratio\":",
"not used for this operation # However, the register should",
"self.readnodeinfo(node) for dev in node['children']: if DevType.issensor(dev[\"dt\"]) == False: info",
"self._logger.info(\"Total detection is canceled.\") break info = self.detectone(port, conn) detected[port]",
"if opt['method'] == 'rtu': conn = ModbusSerialClient(method='rtu', port=opt['port'], timeout=self._timeout, baudrate=opt['baudrate'])",
"code = ResCode.FAIL response.setresult(code) self._logger.info(\"write response: \" + str(response)) self.writecb(response)",
"startdetection(self, params, opid): if self._detection[\"opid\"] != 0: self._logger.info(\"detection is processing....",
"unit, res.registers) self._logger.info (\"Found a node : \" + str(unit)",
"version elif res.registers[1] == NodeType.NUTNODE: if res.registers[3] == ProtoVer.TTA_1: info",
"\"timeout\" not in option else option[\"timeout\"] self._conn = {} self._tempthd",
"self._detection[\"opid\"]) print \"noti\", noti.stringify() self.writecb(noti) time.sleep(0.1) return detected def canceldetection(self,",
"device\" code = self.startdetection(params, blk.getopid()) elif cmd == CmdCode.CANCEL_DETECT: print",
"self._detection = {\"port\": [], \"saddr\":0, \"eaddr\":0, \"opid\":0} #self._nodes = self._devinfo.getgw()[\"children\"]",
"select import traceback import hashlib import json from enum import",
"noti: noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) for port, info in detected.iteritems(): noti.setcontent(port, info)",
"in self._tempthd: if tmp[\"port\"] == opt[\"port\"]: self._logger.warn(\" port [\" +",
"\"dt\": \"act/retractable/level0\"} ] }] }] \"\"\" if isnutri: kdmate =",
"= [] self._isdetecting = False self._detection = {\"port\": [], \"saddr\":0,",
"self._logger.warn(\"fail to read node info : \" + str(node)) return",
"of data is not matched. 6 \" + str(len(res.registers))) continue",
"self.setdetection(False) def detectone(self, port, conn): detected = {} if self._detection[\"port\"]",
"= registers[0] nodecode = registers[2] size = registers[4] while True:",
"command would be ignored.\") return ResCode.FAIL self.setdetection(True, opid) if params:",
"not None and port not in self._detection[\"port\"]: return detected #mrchoi87",
"dev.\" + str(dev) + \",\" + str(res) + \":\" +",
"need to convert by case params[\"opid\"] = request.getopid() # need",
"info = self.readinfofromdev(conn, node) if info: ret[\"nd\"] = info else:",
": \"110\", \"dk\" : '[1,40291,[\"value\",\"status\"]]', \"dt\": \"sen\"} # ] #",
": \"201\", \"dk\" : '[2,40201,[\"status\"],45001,[\"operation\",\"opid\"]]', \"dt\": \"nd\", \"children\" : [",
"info in ndinfo[\"act\"].iteritems(): blk.setcontent(devid, info) self.writecb(blk) def start(self, writecb): super(KSX3267MateV2,",
"\"act/retractable/level0\"}, {\"id\" : \"305\", \"dk\" : (3,40241,[\"opid\",\"status\"],45041,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"} ]",
": '[1,40201,[\"status\"],45001,[\"operation\",\"opid\"]]', \"dt\": \"nd\", \"children\" : [ {\"id\" : \"102\",",
"{\"id\" : \"303\", \"dk\" : (3,40221,[\"opid\",\"status\"],45021,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"}, {\"id\" :",
"10) for sock in rsoc: if sock == servsoc: clisoc,",
"\"105\", \"dk\" : '[1,40211,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"106\", \"dk\"",
"Request(201) req.setcommand(202, CmdCode.OFF, {}) kdmate.writeblk(req) \"\"\" time.sleep(30) kdmate.stop() print \"mate",
"as ex: self._logger.warn(\"fail to read holding registers. : \" +",
"'[1,40202,[\"value\",\"status\"]]', \"dt\": \"sen\"}, # {\"id\" : \"103\", \"dk\" : '[1,40205,[\"value\",\"status\"]]',",
"'[1,40271,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"110\", \"dk\" : '[1,40281,[\"value\",\"status\"]]', \"dt\":",
"\" + str(k)) return -1 return size if __name__ ==",
"= ResCode.FAIL_NO_DEVICE elif DevType.ispropercommand(dev['dt'], cmd) is False: self._logger.warn(\"The request is",
"req.setcommand(202, CmdCode.TIMED_OPEN, {\"time\":10}) kdmate.writeblk(req) time.sleep(15) req = Request(201) req.setcommand(202, CmdCode.TIMED_CLOSE,",
"import struct import time import socket import select import traceback",
"'[1,41020,[\"value\",\"status\"]]', \"dt\": \"sen\"} # {\"id\" : \"102\", \"dk\" : '[1,40202,[\"value\",\"status\"]]',",
"\"102\", \"dk\" : '[1,40211,[\"control\",\"status\",\"area\",\"alert\",\"opid\"],45001,[\"operation\", \"opid\", \"control\",\"EC\",\"pH\", \"start-area\", \"stop-area\", \"on-sec\"]]', \"dt\":",
"print \"cancel to detect device\" code = self.canceldetection(params) else: self._logger.warn(\"Unknown",
"self.parseregisters(self.getdk(dev, 2), res.registers) else: self._logger.info(\"retry to get data since size",
"\"dk\" : '[1,40205,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"104\", \"dk\" :",
"timeout=self._timeout) ret = conn.connect() msg = \"failed to connect with",
"\"port\":opt['port']} self._tempthd.append(tmp) tmp[\"thd\"].start() def checktempthreads(self): for tmp in self._tempthd: if",
"servsoc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) servsoc.bind((opt['host'], opt['port'])) servsoc.listen(1) self._logger.info(\"listen : \" +",
"request is not proper. \" + str(cmd) + \" \"",
"if noti is None: if info is None: noti =",
": \"111\", \"dk\" : '[1,40291,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"112\",",
"struct import time import socket import select import traceback import",
"\"dt\": \"nutrient-supply/level1\"}, {\"id\" : \"103\", \"dk\" : '[1,40221,[\"value\",\"status\"]]', \"dt\": \"sen\"},",
"False or self.isexecuting() == False: self._logger.info(\"A port \" + str(port)",
"StatCode.ERROR.value obsblk.setobservation(devid, info[\"value\"], StatCode(info[\"status\"])) # do not send observation for",
"\"110\", \"dk\" : '[1,40281,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"111\", \"dk\"",
"self._logger.warn(\"This param is needed for this operation. \" + str(params['operation'])",
"option, devinfo, coupleid, logger): super(KSX3267MateV2, self).__init__(option, devinfo, coupleid, logger) self._timeout",
"}] \"\"\" }, { \"id\" : \"201\", \"dk\" : '[2,40201,[\"status\"],45001,[\"operation\",\"opid\"]]',",
"key in params: val = params[key] else: self._logger.warn(\"Wrong Keyword :",
"#{\"id\" : \"203\", \"dk\" : (2,40221,[\"opid\",\"status\"],45021,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" :",
": \"107\", \"dk\" : '[1,40261,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"108\",",
"break elif res.isError(): self._logger.info(\"retry to get status from \" +",
"== False: self._logger.info(\"Total detection is canceled.\") break info = self.detectone(port,",
"is canceled.\") break info = self.detectone(port, conn) detected[port] = info",
"\"dt\": \"sen\"}, #{\"id\" : \"108\", \"dk\" : '[1,40271,[\"value\",\"status\"]]', \"dt\": \"sen\"},",
"self._timeout = 3 if \"timeout\" not in option else option[\"timeout\"]",
"}] } nutriinfo = [{ \"id\" : \"1\", \"dk\" :",
"#{\"id\" : \"103\", \"dk\" : '[1,220,[\"value\",\"status\"]]', \"dt\": \"sen\"} # \"id\"",
"timeout=self._timeout, baudrate=opt['baudrate']) ret = conn.connect() msg = \"failed to connect",
"+ str(dev) + \" however continue to read other device\")",
"if conn: self._conn[opt[\"port\"][8:]] = conn super(KSX3267MateV2, self).connect() return ret def",
"for dev in node['children']: if DevType.issensor(dev[\"dt\"]): info = self.readinfofromdev(ret[\"conn\"], dev)",
"}, { \"id\" : \"301\", \"dk\" : (3,40201,[\"opid\",\"status\"],45001,[\"operation\",\"opid\"]), \"dt\": \"nd\",",
"Notice(None, NotiCode.DETECT_NODE_DETECTED, devid=port, content={unit : info}) # found a node",
"NotiCode.TCP_WAITING if ret else NotiCode.RTU_FAILED_CONNECTION conn = None else: msg",
"port=opt['port'], timeout=self._timeout) ret = conn.connect() msg = \"failed to connect",
": node[\"id\"], \"sen\" : {}, \"act\" : {}, \"nd\" :",
"\"dt\": \"sen\"}, #{\"id\" : \"203\", \"dk\" : (2,40221,[\"opid\",\"status\"],45021,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"},",
"matched. 6 \" + str(len(res.registers))) continue break if res is",
"= False self._detection = {\"port\": [], \"saddr\":0, \"eaddr\":0, \"opid\":0} #self._nodes",
"req = Request(201) req.setcommand(202, CmdCode.TIMED_OPEN, {\"time\":10}) kdmate.writeblk(req) time.sleep(15) req =",
"if res.registers[3] == ProtoVer.TTA_1: info = self.detect_node(conn, unit, res.registers) self._logger.info",
"noti = Notice(None, NotiCode.DETECT_UNKNOWN_PROTOCOL_VER, devid=tempid) # unknown protocol version elif",
"ret = False conn = None if opt['method'] == 'rtu':",
"devid, info in ndinfo[\"act\"].iteritems(): # if StatCode.has_value(info[\"status\"]) == False: #",
"baudrate=opt['baudrate']) ret = conn.connect() msg = \"failed to connect with",
"{}) kdmate.writeblk(req) time.sleep(5) req = Request(201) req.setcommand(202, CmdCode.OFF, {}) kdmate.writeblk(req)",
"sendnoti(self): for gw in self._devinfo: for node in gw[\"children\"]: ret",
"in range(3): res = self.readregister(conn, self.getdk(dev, 1), size, self.getdk(dev, 0))",
"self.listen(opt) msg = \"failed to connect with tcp\" code =",
"\"301\", \"dk\" : (3,40201,[\"opid\",\"status\"],45001,[\"operation\",\"opid\"]), \"dt\": \"nd\", \"children\" : [ {\"id\"",
"matched. \" + str(size) + \" \" + str(len(res.registers))) return",
"None if len(res.registers) != size: self._logger.info(\"retry to get data since",
"{\"status\":StatCode.ERROR.value}} gw = self._devinfo.findgateway(node[\"id\"]) conn = self._conn[gw[\"dk\"]] ret[\"conn\"] = conn",
"}] \"\"\" if isnutri: kdmate = KSX3267MateV2(opt, nutriinfo, \"1\", None)",
"self.writecb(noti) time.sleep(0.1) return detected def canceldetection(self, params): time.sleep(self._timeout) noti =",
"NotiCode.RTU_CONNECTED if ret else NotiCode.RTU_FAILED_CONNECTION elif opt['method'] == 'tcpc': conn",
"filled. val = 0 elif key in params: val =",
"return ResCode.FAIL_WRONG_KEYWORD print \"....... befor lock for write\" with self._lock:",
"for node in gw[\"children\"]: ret = self.readnodeinfo(node) i = 1",
"checktempthreads(self): for tmp in self._tempthd: if tmp[\"status\"] > 2: tmp[\"thd\"].stop()",
"\"sen\"}, #{\"id\" : \"109\", \"dk\" : '[1,40281,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\"",
"for write\" with self._lock: time.sleep(KSX3267MateV2._SLEEP) print \"....... lock for write\",",
"}] }] \"\"\" if isnutri: kdmate = KSX3267MateV2(opt, nutriinfo, \"1\",",
"servsoc.bind((opt['host'], opt['port'])) servsoc.listen(1) self._logger.info(\"listen : \" + str(opt)) executing =",
"import time import socket import select import traceback import hashlib",
"{\"id\" : \"204\", \"dk\" : '[2,40219,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" :",
"[] for key in self.getdk(dev, 4): if key not in",
"101 def __init__(self, option, devinfo, coupleid, logger): super(KSX3267MateV2, self).__init__(option, devinfo,",
"node info : \" + str(node)) return ret def readsensornodeinfo(self,",
"% 3 == 0: self.sendnoticeforactuatorstatus(ret) ret[\"act\"] = {} self.sendnoticeforactuatorstatus(ret) def",
"False: ndinfo[\"nd\"][\"status\"] = StatCode.ERROR.value obsblk = Observation(ndinfo[\"id\"]) obsblk.setobservation(ndinfo[\"id\"], 0, StatCode(ndinfo[\"nd\"][\"status\"]))",
"to read actuator info : \" + str(dev) + \"",
"+ str(address)) for tmp in self._tempthd: if tmp[\"port\"] == opt[\"port\"]:",
"self._logger.warn(\"Unknown Error. \" + str(blk) + \", \" + str(dev))",
"{\"port\": [], \"saddr\":0, \"eaddr\":0, \"opid\":0} #self._nodes = self._devinfo.getgw()[\"children\"] self._lock =",
"+ str(key)) # return ResCode.FAIL_WRONG_KEYWORD print \"....... befor lock for",
"(3,40231,[\"opid\",\"status\"],45031,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"}, {\"id\" : \"305\", \"dk\" : (3,40241,[\"opid\",\"status\"],45041,[\"operation\",\"opid\"]), \"dt\":",
"\"short\"), \"alert\" : (1, \"alert\"), \"hold-time\" : (2, \"int\"), \"operation\"",
": compcode, \"nodecode\" : nodecode, \"devcodes\": res.registers} def getdk(self, dev,",
"code = ResCode.FAIL else: self._logger.warn(\"Unknown Error. \" + str(blk) +",
"info : \" + str(node)) return ret def readsensornodeinfo(self, node):",
"'[1,40301,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"113\", \"dk\" : '[1,40311,[\"value\",\"status\"]]', \"dt\":",
"return ResCode.FAIL_WRONG_KEYWORD if KSX3267MateV2._KEYWORDS[key][0] == 1: registers.append(val) elif KSX3267MateV2._KEYWORDS[key][1] ==",
"code = ResCode.FAIL elif dev is None: self._logger.warn(\"There is no",
"ret = conn.connect() msg = \"failed to connect with rtu\"",
"self._conn[port].close() def close(self): for port in self._conn.keys(): self.closeone(port) super(KSX3267MateV2, self).close()",
"\"305\", \"dk\" : (3,40241,[\"opid\",\"status\"],45041,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"} ] }] }] \"\"\"",
"\"act/switch/level0\"}, #{\"id\" : \"209\", \"dk\" : (2,40281,[\"opid\",\"status\"],45081,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"} ]",
"is not used for this operation # However, the register",
"to connect with tcp\" code = NotiCode.TCP_CONNECTED if ret else",
"\"dt\": \"sen\"} # \"id\" : \"101\", \"dk\" : '[1,40201,[\"status\"],45001,[\"operation\",\"opid\"]]', \"dt\":",
"\"dt\": \"act/switch/level0\"}, #{\"id\" : \"209\", \"dk\" : (2,40281,[\"opid\",\"status\"],45081,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}",
"\" + str(blk) + \", \" + str(dev)) code =",
"msg in self._msgq: if msg is None: continue self.sendobservation(msg) def",
"\"=======================================#3\" kdmate.writeblk(req) print \"=======================================#3\" time.sleep(1) req = Request(None) req.setcommand(\"1\", CmdCode.CANCEL_DETECT,",
"detected.iteritems(): noti.setcontent(port, info) self.writecb(noti) self.setdetection(False) def detectone(self, port, conn): detected",
"not proper. \" + str(cmd) + \" \" + str(dev['dt']))",
"is None or res.isError(): noti = Notice(None, NotiCode.DETECT_NO_NODE, devid=tempid) #",
"self._logger.info(\"Actuator processed : \" + str(code)) elif DevType.isgateway(dev['dt']): self._logger.info(\"Gateway does",
"coupleid, logger) self._timeout = 3 if \"timeout\" not in option",
"\"dk\" : '[1,40201,[\"status\"],45001,[\"operation\",\"opid\"]]', \"dt\": \"nd\", \"children\" : [ {\"id\" :",
"= self.readinfofromdev(conn, node) if info: ret[\"nd\"] = info else: self._logger.warn(\"fail",
"= {} self._tempthd = [] self._isdetecting = False self._detection =",
"msg = \"failed to connect with tcp\" code = NotiCode.TCP_WAITING",
"# fail to find a node else: noti = Notice(None,",
"= Request(201) req.setcommand(202, CmdCode.OFF, {}) kdmate.writeblk(req) time.sleep(10) req = Request(201)",
"code = self.processrequest(dev, blk, nd) self._logger.info(\"Actuator processed : \" +",
"_ in range(3): res = self.readregister(conn, self.getdk(dev, 1), size, self.getdk(dev,",
"\"stop-area\", \"on-sec\"]]', \"dt\": \"nutrient-supply/level1\"}, {\"id\" : \"103\", \"dk\" : '[1,40221,[\"value\",\"status\"]]',",
"= self._devinfo.findgateway(node[\"id\"]) conn = self._conn[gw[\"dk\"]] ret[\"conn\"] = conn info =",
"\"108\", \"dk\" : '[1,40271,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"109\", \"dk\"",
"\" + str(info)) else: noti = Notice(None, NotiCode.DETECT_UNKNOWN_PROTOCOL_VER, devid=tempid) #",
"protocol version elif res.registers[1] == NodeType.NUTNODE: if res.registers[3] == ProtoVer.TTA_1:",
"val))) #else: # self._logger.warn(\"This param is needed for this operation.",
"other device\") return ret def readactnodeinfo(self, node): ret = self.readnodeinfo(node)",
"if BlkType.isrequest(blk.gettype()) is False: self._logger.warn(\"The message is not request. \"",
"\"dk\" : (2,40261,[\"opid\",\"status\"],45061,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"208\", \"dk\" :",
"self.canceldetection(params) else: self._logger.warn(\"Unknown Error. \" + str(blk) + \", \"",
"not send observation for actuator #for devid, info in ndinfo[\"act\"].iteritems():",
"msg = \"It's a wrong connection method. \" + str(opt['method'])",
"not request. \" + str(blk.gettype())) return False response = Response(blk)",
"size, unit) if res is None or res.isError(): self._logger.warn(\"Fail to",
"= servsoc.accept() self._logger.info(\"client connected from \" + str(address)) for tmp",
"try: return conn.read_holding_registers(addr, count, unit=unit) except Exception as ex: self._logger.warn(\"fail",
"+ str(unit) + \" \" + str(info)) else: noti =",
"class NodeType(IntEnum): SENNODE = 1 ACTNODE = 2 INTNODE =",
"for _ in range(3): res = self.readregister(conn, KSX3267MateV2._DEVINFOREG, 6, unit)",
": (1, \"short\"), \"EC\": (2, \"float\"), \"pH\": (2, \"float\"), \"on-sec\"",
"[], 10) for sock in rsoc: if sock == servsoc:",
"\"206\", \"dk\" : (2,40251,[\"opid\",\"status\"],45051,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"207\", \"dk\"",
"\" + str(unit) + \" \" + str(addr) + \"",
"str(cmd) + \" \" + str(dev['dt'])) code = ResCode.FAIL_NOT_PROPER_COMMAND elif",
"'tcpc': conn = ModbusTcpClient(opt['host'], port=opt['port'], timeout=self._timeout) ret = conn.connect() msg",
"noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) print \"noti\", noti.stringify() self.writecb(noti) time.sleep(0.1) return detected def",
"\"102\", \"dk\" : '[1,40202,[\"value\",\"status\"]]', \"dt\": \"sen\"}, # {\"id\" : \"103\",",
"self.processrequest(dev, blk, nd) self._logger.info(\"Actuator processed : \" + str(code)) elif",
"= info self._logger.info (\"finished to detect devices : \" +",
"act): ret = self.readnodeinfo(node) info = self.readinfofromdev(ret[\"conn\"], act) if info:",
"\" detection is canceled.\") break tempid = port + \"-\"",
"= 4 class ProtoVer(IntEnum): KS_X_3267_2020 = 10 KS_X_3267_2018 = 101",
"\"dk\" : (2,40251,[\"opid\",\"status\"],45051,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"207\", \"dk\" :",
"conn = ModbusTcpClient(opt['host'], port=opt['port'], timeout=self._timeout) ret = conn.connect() msg =",
"code = NotiCode.RTU_CONNECTED if ret else NotiCode.RTU_FAILED_CONNECTION elif opt['method'] ==",
"to get data since size of data is not matched.",
"\" \" + str(dev['dt'])) code = ResCode.FAIL_NOT_PROPER_COMMAND elif DevType.isactuator(dev['dt']) or",
"if info: ret[\"act\"][act[\"id\"]] = info else: self._logger.warn(\"fail to read actuator",
"self.connectone(opt) if conn: self._conn[opt[\"port\"][8:]] = conn super(KSX3267MateV2, self).connect() return ret",
": [ #{\"id\" : \"102\", \"dk\" : '[1,41010,[\"value\",\"status\"]]', \"dt\": \"sen\"},",
"_ in range(3): res = self.readregister(conn, KSX3267MateV2._DEVINFOREG, 6, unit) if",
"{}) kdmate.writeblk(req) time.sleep(10) req = Request(201) req.setcommand(202, CmdCode.TIMED_OPEN, {\"time\":10}) kdmate.writeblk(req)",
"\"nd\", \"children\" : [ #{\"id\" : \"102\", \"dk\" : '[1,210,[\"value\",\"status\"]]',",
"from pymodbus.client.sync import ModbusTcpClient class NodeType(IntEnum): SENNODE = 1 ACTNODE",
"res.isError(): self._logger.info(\"retry to get status from \" + str(dev['dk']) +",
"unknown protocol version elif res.registers[1] == NodeType.NUTNODE: if res.registers[3] ==",
"self._logger.info(\"retry to get data since size of data is not",
"= self.getsize(self.getdk(dev, 2)) #for _ in range(3): res = self.readregister(conn,",
"{\"id\" : \"203\", \"dk\" : '[2,40216,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" :",
": Thread(target=self._listen, args=(opt)), \"status\": 0, \"port\":opt['port']} self._tempthd.append(tmp) tmp[\"thd\"].start() def checktempthreads(self):",
"code = ResCode.FAIL_NO_DEVICE elif DevType.ispropercommand(dev['dt'], cmd) is False: self._logger.warn(\"The request",
"\" + str(unit) + \" \" + str(info)) else: noti",
"in self._devinfo: for node in gw[\"children\"]: ret = self.readnodeinfo(node) i",
"5 }] } nutriinfo = [{ \"id\" : \"1\", \"dk\"",
"node, act): ret = self.readnodeinfo(node) info = self.readinfofromdev(ret[\"conn\"], act) if",
"else: msg = \"It's a wrong connection method. \" +",
"= Notice(None, NotiCode.DETECT_CANCELED) # detection is canceled noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) self.writecb(noti)",
"\"dt\": \"gw\", \"children\" : [ # { # \"id\" :",
"print \"=======================================#4\" kdmate.writeblk(req) print \"=======================================#4\" time.sleep(10) req = Request(201) req.setcommand(202,",
"traceback import hashlib import json from enum import IntEnum from",
"KSX3267MateV2(opt, nutriinfo, \"1\", None) else: kdmate = KSX3267MateV2(opt, devinfo, \"1\",",
"True: res = self.readregister(conn, KSX3267MateV2._DEVCODEREG, size, unit) if res is",
"unknown device if noti is None: if info is None:",
"count, unit): print \"....... before lock for read\" with self._lock:",
"if res is None: self._logger.warn(\"fail to get status from \"",
"'[1,40221,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"104\", \"dk\" : '[1,40231,[\"value\",\"status\"]]', \"dt\":",
"readactnodeinfo(self, node): ret = self.readnodeinfo(node) for dev in node['children']: if",
"not matched. 6 \" + str(len(res.registers))) continue break if res",
"]} ] devinfo = [{ \"id\" : \"1\", \"dk\" :",
": '[1,40281,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"110\", \"dk\" : '[1,40291,[\"value\",\"status\"]]',",
"import json from enum import IntEnum from threading import Thread,",
": \"204\", \"dk\" : (2,40231,[\"opid\",\"status\"],45031,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"205\",",
"if StatCode.has_value(info[\"status\"]) == False: info[\"status\"] = StatCode.ERROR.value obsblk.setobservation(devid, info[\"value\"], StatCode(info[\"status\"]))",
"in ndinfo[\"act\"].iteritems(): # if StatCode.has_value(info[\"status\"]) == False: # info[\"status\"] =",
"'[1,40211,[\"control\",\"status\",\"area\",\"alert\",\"opid\"],45001,[\"operation\", \"opid\", \"control\",\"EC\",\"pH\", \"start-area\", \"stop-area\", \"on-sec\"]]', \"dt\": \"nutrient-supply/level1\"}, {\"id\" :",
"_DEVINFOREG = 2 _DEVCODEREG = 101 def __init__(self, option, devinfo,",
"= 101 def __init__(self, option, devinfo, coupleid, logger): super(KSX3267MateV2, self).__init__(option,",
"!= 0: self._logger.info(\"detection is processing.... so this command would be",
"(3,40201,[\"opid\",\"status\"],45001,[\"operation\",\"opid\"]), \"dt\": \"nd\", \"children\" : [ {\"id\" : \"302\", \"dk\"",
"+ \" \" + str(res)) return None if len(res.registers) !=",
"ProtoVer(IntEnum): KS_X_3267_2020 = 10 KS_X_3267_2018 = 101 TTA_1 = 201",
"elif cmd == CmdCode.CANCEL_DETECT: print \"cancel to detect device\" code",
"\" + str(act) + \" however continue to read other",
"Request(None) req.setcommand(\"1\", CmdCode.DETECT_DEVICE, None) print \"=======================================#3\" kdmate.writeblk(req) print \"=======================================#3\" time.sleep(1)",
"{\"id\" : \"304\", \"dk\" : (3,40231,[\"opid\",\"status\"],45031,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"}, {\"id\" :",
"\"....... before lock for read\" with self._lock: time.sleep(KSX3267MateV2._SLEEP) #mrchoi87 self._logger.info(\"read_holding_registers:",
"str(len(res.registers))) continue break if res is None or res.isError(): noti",
"writecb): super(KSX3267MateV2, self).start(writecb) return True def stop(self): super(KSX3267MateV2, self).stop() return",
"response: \" + str(response)) self.writecb(response) return True #if code ==",
"{\"time\":10}) kdmate.writeblk(req) time.sleep(5) req = Request(201) req.setcommand(202, CmdCode.OFF, {}) kdmate.writeblk(req)",
"be filled. val = 0 elif key in params: val",
"res.registers) self._logger.info (\"Found a node : \" + str(unit) +",
"= {\"thd\" : Thread(target=self._listen, args=(opt)), \"status\": 0, \"port\":opt['port']} self._tempthd.append(tmp) tmp[\"thd\"].start()",
"{} for nm in names: (size, vtype) = KSX3267MateV2._KEYWORDS[nm] if",
"request.getcommand() params = request.getparams() params[\"operation\"] = operation # need to",
"res.isError(): self._logger.warn(\"Fail to write a request to dev.\" + str(dev)",
": \"106\", \"dk\" : '[1,40251,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"107\",",
"\"failed to connect with tcp\" code = NotiCode.TCP_WAITING if ret",
"self._logger.info (\"Found a nutrient system : \" + str(unit) +",
"\"mate started\" time.sleep(10) req = Request(None) req.setcommand(\"1\", CmdCode.DETECT_DEVICE, None) print",
"== CmdCode.DETECT_DEVICE: print \"detect device\" code = self.startdetection(params, blk.getopid()) elif",
"port + \"-\" + str(unit) noti = Notice(None, NotiCode.DETECT_NODE_STARTED, devid=tempid)",
"pymodbus.client.sync import ModbusTcpClient class NodeType(IntEnum): SENNODE = 1 ACTNODE =",
"return ResCode.OK def readregister(self, conn, addr, count, unit): print \".......",
"== servsoc: clisoc, address = servsoc.accept() self._logger.info(\"client connected from \"",
"\"alert\"), \"hold-time\" : (2, \"int\"), \"operation\" : (1, \"operation\"), \"time\"",
"blk.getcommand() nd = self._devinfo.finddevbyid(blk.getnodeid()) dev = self._devinfo.finddevbyid(blk.getdevid()) if blk.getdevid() ==",
"as ex: servsoc.close() for tmp in self._tempthd: if tmp[\"port\"] ==",
"to write a request to dev.\" + str(dev) + \",\"",
"'/dev/ttyJND2', 'baudrate' : 9600, 'timeout': 5 }] } nutriinfo =",
"= request.getparams() params[\"operation\"] = operation # need to convert by",
"dev = self._devinfo.finddevbyid(blk.getdevid()) if blk.getdevid() == self._coupleid: params = blk.getparams()",
"conn = ModbusTcpClient(timeout=self._timeout) conn.socket = clisoc self._conn[opt[\"port\"]] = conn tmp[\"status\"]",
"def canceldetection(self, params): time.sleep(self._timeout) noti = Notice(None, NotiCode.DETECT_CANCELED) # detection",
"ex: servsoc.close() for tmp in self._tempthd: if tmp[\"port\"] == opt[\"port\"]:",
"Notice from pymodbus.client.sync import ModbusSerialClient from pymodbus.client.sync import ModbusTcpClient class",
"str(request)) return ResCode.FAIL_TO_WRITE msg = self.readactinfo(node, dev) if msg is",
"self.getdk(dev, 1), size, self.getdk(dev, 0)) if res is None: self._logger.warn(\"fail",
": \"104\", \"dk\" : '[1,40208,[\"value\",\"status\"]]', \"dt\": \"sen\"}, # {\"id\" :",
"= clisoc self._conn[opt[\"port\"]] = conn tmp[\"status\"] = 10 # connected",
"# {\"id\" : \"105\", \"dk\" : '[1,40211,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\"",
"MBlock, BlkType, StatCode, ResCode, CmdCode, Observation, Request, Response, NotiCode, Notice",
"StatCode, ResCode, CmdCode, Observation, Request, Response, NotiCode, Notice from pymodbus.client.sync",
"\"dk\" : '[1,40231,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"105\", \"dk\" :",
"self._logger.info(\"waiting a client~\") rsoc, wsoc, esoc = select.select([servsoc], [], [],",
"closeone(self, port): self._conn[port].close() def close(self): for port in self._conn.keys(): self.closeone(port)",
"__name__ == \"__main__\": isnutri = False opt = { 'conn'",
"from threading import Thread, Lock from mate import Mate, ThreadMate,",
"str(k)) return -1 return size if __name__ == \"__main__\": isnutri",
"def readregister(self, conn, addr, count, unit): print \"....... before lock",
"obsblk.setobservation(ndinfo[\"id\"], 0, StatCode(ndinfo[\"nd\"][\"status\"])) for devid, info in ndinfo[\"sen\"].iteritems(): if StatCode.has_value(info[\"status\"])",
"+ str(dev)) code = ResCode.FAIL elif dev is None: self._logger.warn(\"There",
"ModbusTcpClient(opt['host'], port=opt['port'], timeout=self._timeout) ret = conn.connect() msg = \"failed to",
"# {\"id\" : \"103\", \"dk\" : '[1,40205,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\"",
"\" + str(len(res.registers))) continue break if res is None or",
"\"dk\" : (3,40231,[\"opid\",\"status\"],45031,[\"operation\",\"opid\"]), \"dt\": \"act/retractable/level0\"}, {\"id\" : \"305\", \"dk\" :",
"self.writecb(obsblk) def sendnoticeforactuatorstatus(self, ndinfo): blk = Notice(ndinfo[\"id\"], NotiCode.ACTUATOR_STATUS, ndinfo[\"id\"], ndinfo[\"nd\"])",
"def getdk(self, dev, idx): dk = json.loads(dev[\"dk\"]) return dk[idx] def",
"# -*- coding: utf-8 -*- # # Copyright (c) 2018",
"logger): super(KSX3267MateV2, self).__init__(option, devinfo, coupleid, logger) self._timeout = 3 if",
"str(res)) elif res.registers[1] in (NodeType.SENNODE, NodeType.ACTNODE, NodeType.INTNODE): # device type",
"(NodeType.SENNODE, NodeType.ACTNODE, NodeType.INTNODE): # device type if res.registers[3] == ProtoVer.KS_X_3267_2020",
"ndinfo[\"nd\"]) for devid, info in ndinfo[\"act\"].iteritems(): blk.setcontent(devid, info) self.writecb(blk) def",
"False self._detection = {\"port\": [], \"saddr\":0, \"eaddr\":0, \"opid\":0} #self._nodes =",
": '[1,40271,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"110\", \"dk\" : '[1,40281,[\"value\",\"status\"]]',",
"return dk[idx] def setdetection(self, flag, opid=0): self._isdetecting = flag self._detection[\"opid\"]",
"\"parsed\", ret return ret def readinfofromdev(self, conn, dev): size =",
"info) self.writecb(blk) def start(self, writecb): super(KSX3267MateV2, self).start(writecb) return True def",
"#{\"id\" : \"107\", \"dk\" : '[1,40261,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" :",
"\"dk\" : \"\", \"dt\": \"gw\", \"children\" : [{ \"id\" :",
"from \" + str(address)) for tmp in self._tempthd: if tmp[\"port\"]",
"req = Request(None) req.setcommand(\"1\", CmdCode.CANCEL_DETECT, {}) print \"=======================================#4\" kdmate.writeblk(req) print",
"\"short\"), \"position\" : (1, \"short\"), \"remain-time\" : (2, \"int\"), \"control\":",
"if len(res.registers) != size: self._logger.info(\"retry to get data since size",
"== 1: registers.append(val) elif KSX3267MateV2._KEYWORDS[key][1] == \"int\": registers.extend(struct.unpack('HH', struct.pack('i', val)))",
": \"204\", \"dk\" : '[2,40219,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"203\",",
"not in self._detection[\"port\"]: return detected #mrchoi87 #for unit in range(self._detection[\"saddr\"],",
"= self._devinfo.finddevbyid(blk.getdevid()) if blk.getdevid() == self._coupleid: params = blk.getparams() if",
"\" + str(addr) + \" \" + str(count)) print \"read",
"\"vfloat\": (2, \"float\"), \"vint\" : (2, \"int\")} _DEVINFOREG = 2",
"with self._lock: time.sleep(KSX3267MateV2._SLEEP) print \"....... lock for write\", self.getdk(dev, 3),",
"= 101 TTA_1 = 201 class KSX3267MateV2(ThreadMate): _SLEEP = 0.5",
"node in gw[\"children\"]: ret = self.readnodeinfo(node) i = 1 for",
": \"101\", \"dk\" : '[1,201,[\"status\"],301,[\"operation\",\"opid\"]]', \"dt\": \"nd\", \"children\" : [",
"readactinfo(self, node, act): ret = self.readnodeinfo(node) info = self.readinfofromdev(ret[\"conn\"], act)",
"time.sleep(15) req = Request(201) req.setcommand(202, CmdCode.TIMED_CLOSE, {\"time\":10}) kdmate.writeblk(req) time.sleep(5) req",
"for msg in self._msgq: if msg is None: continue self.sendobservation(msg)",
"elif vtype == \"int\": val = struct.unpack('i', struct.pack('HH', values[idx], values[idx+1]))[0]",
"idx): dk = json.loads(dev[\"dk\"]) return dk[idx] def setdetection(self, flag, opid=0):",
"len(res.registers) != 6: self._logger.info(\"retry to get data since size of",
"case properparams = CmdCode.getparams(operation) + [\"operation\", \"opid\"] registers = []",
"blk.getopid()) elif cmd == CmdCode.CANCEL_DETECT: print \"cancel to detect device\"",
"kdmate.start (mate.writeblk) print \"mate started\" time.sleep(10) req = Request(None) req.setcommand(\"1\",",
"import ModbusTcpClient class NodeType(IntEnum): SENNODE = 1 ACTNODE = 2",
"conn = ModbusSerialClient(method='rtu', port=opt['port'], timeout=self._timeout, baudrate=opt['baudrate']) ret = conn.connect() msg",
"processrequest(self, dev, request, node): gw = self._devinfo.findgateway(request.getnodeid()) unit = self.getdk(dev,",
"+ str(ex)) tmp[\"status\"] = 5 # error def listen(self, opt):",
"\"1\", None) mate = Mate ({}, [], \"1\", None) kdmate.start",
"str(addr) + \" \" + str(count)) print \"read register\", unit,",
"for tmp in self._tempthd: if tmp[\"port\"] == opt[\"port\"]: conn =",
"noti.setcontent(port, info) self.writecb(noti) self.setdetection(False) def detectone(self, port, conn): detected =",
": \"112\", \"dk\" : '[1,40301,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"113\",",
"vtype == \"float\": val = struct.unpack('f', struct.pack('HH', values[idx], values[idx+1]))[0] elif",
"self._logger.warn(\"Wrong Keyword : \" + str(key)) return ResCode.FAIL_WRONG_KEYWORD if KSX3267MateV2._KEYWORDS[key][0]",
"lock for write\" with self._lock: time.sleep(KSX3267MateV2._SLEEP) print \"....... lock for",
"ResCode.FAIL_WRONG_KEYWORD print \"....... befor lock for write\" with self._lock: time.sleep(KSX3267MateV2._SLEEP)",
"NotiCode.DETECT_UNKNOWN_PROTOCOL_VER, devid=tempid) # unknown protocol version elif res.registers[1] == NodeType.NUTNODE:",
"dev) if info: ret[\"act\"][dev[\"id\"]] = info i = i +",
"(2,40261,[\"opid\",\"status\"],45061,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"208\", \"dk\" : (2,40271,[\"opid\",\"status\"],45071,[\"operation\",\"opid\"]), \"dt\":",
"if noti: noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) for port, info in detected.iteritems(): noti.setcontent(port,",
"socket.socket(socket.AF_INET, socket.SOCK_STREAM) servsoc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) servsoc.bind((opt['host'], opt['port'])) servsoc.listen(1) self._logger.info(\"listen :",
"writeblk(self, blk): print \"received message\", blk.getdevid(), self._coupleid if BlkType.isrequest(blk.gettype()) is",
"elif opt['method'] == 'tcpc': conn = ModbusTcpClient(opt['host'], port=opt['port'], timeout=self._timeout) ret",
"msg is None: continue self.sendobservation(msg) def sendnoti(self): for gw in",
": '[2,40216,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"204\", \"dk\" : '[2,40219,[\"value\",\"status\"]]',",
"(2, \"int\")} _DEVINFOREG = 2 _DEVCODEREG = 101 def __init__(self,",
"i + 1 if i % 3 == 0: self.sendnoticeforactuatorstatus(ret)",
"+ str(dev['dk']) + \" \" + str(res)) # continue else:",
"\"dt\": \"sen\"}, {\"id\" : \"204\", \"dk\" : '[2,40219,[\"value\",\"status\"]]', \"dt\": \"sen\"},",
"isnutri: kdmate = KSX3267MateV2(opt, nutriinfo, \"1\", None) else: kdmate =",
"_DEVCODEREG = 101 def __init__(self, option, devinfo, coupleid, logger): super(KSX3267MateV2,",
"# modbus code = self.processrequest(dev, blk, nd) self._logger.info(\"Actuator processed :",
"opid def startdetection(self, params, opid): if self._detection[\"opid\"] != 0: self._logger.info(\"detection",
"self.readregister(conn, KSX3267MateV2._DEVINFOREG, 6, unit) if res is None or res.isError():",
"values[idx+1]))[0] else: val = values[idx] ret[nm] = val idx =",
"\" + str(unit) + \" \" + str(res)) return None",
"is None: if info is None: noti = Notice(None, NotiCode.DETECT_WRONG_DEVICE,",
"\" + str(response)) self.writecb(response) return True #if code == ResCode.OK",
"(2,40281,[\"opid\",\"status\"],45081,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"} ] }, { \"id\" : \"301\", \"dk\"",
"\"alert\" : (1, \"alert\"), \"hold-time\" : (2, \"int\"), \"operation\" :",
"= self._devinfo.findgateway(request.getnodeid()) unit = self.getdk(dev, 0) operation = request.getcommand() params",
"== size: return self.parseregisters(self.getdk(dev, 2), res.registers) else: self._logger.info(\"retry to get",
"= params['eaddr'] self._detection[\"port\"] = params['port'] else: self._detection[\"saddr\"] = 1 self._detection[\"eaddr\"]",
"self._logger.info (\"Found a node : \" + str(unit) + \"",
"servsoc.listen(1) self._logger.info(\"listen : \" + str(opt)) executing = True while",
"idx + size print \"parsed\", ret return ret def readinfofromdev(self,",
"\"\"\" }, { \"id\" : \"201\", \"dk\" : '[2,40201,[\"status\"],45001,[\"operation\",\"opid\"]]', \"dt\":",
"= {} self.sendnoticeforactuatorstatus(ret) def sendobservation(self, ndinfo): if StatCode.has_value(ndinfo[\"nd\"][\"status\"]) == False:",
"\"101\", \"dk\" : '[1,201,[\"status\"],301,[\"operation\",\"opid\"]]', \"dt\": \"nd\", \"children\" : [ #{\"id\"",
"+ str(size) + \" \" + str(len(res.registers))) continue return {\"compcode\"",
"noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) for port, info in detected.iteritems(): noti.setcontent(port, info) self.writecb(noti)",
"= 0 elif key in params: val = params[key] else:",
"= None info = None res = None for _",
"struct.unpack('i', struct.pack('HH', values[idx], values[idx+1]))[0] else: val = values[idx] ret[nm] =",
"(2, \"int\"), \"operation\" : (1, \"operation\"), \"time\" : (2, \"int\"),",
"+ \":\" + str(request)) return ResCode.FAIL_TO_WRITE msg = self.readactinfo(node, dev)",
"super(KSX3267MateV2, self).__init__(option, devinfo, coupleid, logger) self._timeout = 3 if \"timeout\"",
"= NotiCode.TCP_CONNECTED if ret else NotiCode.RTU_FAILED_CONNECTION elif opt['method'] == 'tcpcs':",
"+ str(response)) self.writecb(response) return True #if code == ResCode.OK else",
"{\"id\" : \"104\", \"dk\" : '[1,40231,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" :",
"blk): print \"received message\", blk.getdevid(), self._coupleid if BlkType.isrequest(blk.gettype()) is False:",
"if tmp[\"status\"] > 2: tmp[\"thd\"].stop() tmp[\"thd\"].join() def connectone(self, opt): ret",
"or DevType.isnode(dev['dt']): # modbus code = self.processrequest(dev, blk, nd) self._logger.info(\"Actuator",
"detection is canceled self.writecb(noti) return conn def connect(self): ret =",
"in self._option['conn']: conn = self.connectone(opt) if conn: self._conn[opt[\"port\"][8:]] = conn",
"str(opt[\"port\"]) + \"] exception : \" + str(ex)) tmp[\"status\"] =",
"does not receive a request\") code = ResCode.FAIL else: self._logger.warn(\"Unknown",
"is None: self._logger.warn(\"fail to get status from \" + str(dev['dk']))",
"ret[\"sen\"][dev[\"id\"]] = info #else: # self._logger.warn(\"fail to read sensor info",
"\"sen\"}, #{\"id\" : \"103\", \"dk\" : '[1,41020,[\"value\",\"status\"]]', \"dt\": \"sen\"} #",
"= 201 class KSX3267MateV2(ThreadMate): _SLEEP = 0.5 _VERSION = \"KSX3267_0.1\"",
"in self._tempthd: if tmp[\"status\"] > 2: tmp[\"thd\"].stop() tmp[\"thd\"].join() def connectone(self,",
"a nutrient system : \" + str(unit) + \" \"",
"\"sen\"} # {\"id\" : \"102\", \"dk\" : '[1,40202,[\"value\",\"status\"]]', \"dt\": \"sen\"},",
"None: self._logger.warn(\"Fail to read dev status.\") else: self.sendnoticeforactuatorstatus(msg) return ResCode.OK",
"self.readinfofromdev(ret[\"conn\"], dev) if info: ret[\"act\"][dev[\"id\"]] = info i = i",
"from pymodbus.client.sync import ModbusSerialClient from pymodbus.client.sync import ModbusTcpClient class NodeType(IntEnum):",
"] }, { \"id\" : \"301\", \"dk\" : (3,40201,[\"opid\",\"status\"],45001,[\"operation\",\"opid\"]), \"dt\":",
"is not None and port not in self._detection[\"port\"]: return detected",
"\"act/switch/level0\"}, #{\"id\" : \"206\", \"dk\" : (2,40251,[\"opid\",\"status\"],45051,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\"",
"'[1,40251,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"107\", \"dk\" : '[1,40261,[\"value\",\"status\"]]', \"dt\":",
"NodeType.ACTNODE, NodeType.INTNODE): # device type if res.registers[3] == ProtoVer.KS_X_3267_2020 or",
"self.closeone(port) super(KSX3267MateV2, self).close() def readmsg(self): self._msgq = [] for gw",
"\"__main__\": isnutri = False opt = { 'conn' : [{",
"self._detection[\"opid\"] != 0: self._logger.info(\"detection is processing.... so this command would",
"+ \" \" + str(res)) elif res.registers[1] in (NodeType.SENNODE, NodeType.ACTNODE,",
"node['children']: if DevType.issensor(dev[\"dt\"]) == False: info = self.readinfofromdev(ret[\"conn\"], dev) if",
"info: ret[\"act\"][dev[\"id\"]] = info else: self._logger.warn(\"fail to read actuator info",
"node detected[unit] = info noti.setkeyvalue(\"opid\", self._detection[\"opid\"]) print \"noti\", noti.stringify() self.writecb(noti)",
"params): time.sleep(self._timeout) noti = Notice(None, NotiCode.DETECT_CANCELED) # detection is canceled",
"conn: self._conn[opt[\"port\"][8:]] = conn super(KSX3267MateV2, self).connect() return ret def closeone(self,",
"while True: res = self.readregister(conn, KSX3267MateV2._DEVCODEREG, size, unit) if res",
"NotiCode.DETECT_WRONG_DEVICE, devid=tempid) # fail to find a node else: noti",
"opt): try: servsoc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) servsoc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) servsoc.bind((opt['host'],",
"ret = {} for nm in names: (size, vtype) =",
": \" + str(k)) return -1 return size if __name__",
"request.getparams() params[\"operation\"] = operation # need to convert by case",
"\"109\", \"dk\" : '[1,40281,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"110\", \"dk\"",
"for port, info in detected.iteritems(): noti.setcontent(port, info) self.writecb(noti) self.setdetection(False) def",
"since size of data is not matched. \" + str(size)",
"\"\"\" time.sleep(1) req = Request(None) req.setcommand(\"1\", CmdCode.CANCEL_DETECT, {}) print \"=======================================#2\"",
"params['saddr'] self._detection[\"eaddr\"] = params['eaddr'] self._detection[\"port\"] = params['port'] else: self._detection[\"saddr\"] =",
"noti = Notice(None, NotiCode.DETECT_NODE_STARTED, devid=tempid) # Detection Started if noti:",
"devid, info in ndinfo[\"sen\"].iteritems(): if StatCode.has_value(info[\"status\"]) == False: info[\"status\"] =",
"dev) if info: ret[\"act\"][dev[\"id\"]] = info else: self._logger.warn(\"fail to read",
"\"dk\" : (2,40231,[\"opid\",\"status\"],45031,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" : \"205\", \"dk\" :",
"dev): size = self.getsize(self.getdk(dev, 2)) #for _ in range(3): res",
"str(address)) for tmp in self._tempthd: if tmp[\"port\"] == opt[\"port\"]: conn",
"self._lock: time.sleep(KSX3267MateV2._SLEEP) #mrchoi87 self._logger.info(\"read_holding_registers: \" + str(unit) + \" \"",
"self).close() def readmsg(self): self._msgq = [] for gw in self._devinfo:",
"opt['method'] == 'tcpc': conn = ModbusTcpClient(opt['host'], port=opt['port'], timeout=self._timeout) ret =",
"print \"=======================================#4\" time.sleep(10) req = Request(201) req.setcommand(202, CmdCode.OPEN, {}) kdmate.writeblk(req)",
"StatCode.has_value(ndinfo[\"nd\"][\"status\"]) == False: ndinfo[\"nd\"][\"status\"] = StatCode.ERROR.value obsblk = Observation(ndinfo[\"id\"]) obsblk.setobservation(ndinfo[\"id\"],",
"=0 for k in lst: if k in KSX3267MateV2._KEYWORDS: size",
"= ModbusTcpClient(timeout=self._timeout) conn.socket = clisoc self._conn[opt[\"port\"]] = conn tmp[\"status\"] =",
"lock for write\", self.getdk(dev, 3), registers res = self._conn[gw[\"dk\"]].write_registers(self.getdk(dev, 3),",
"1) servsoc.bind((opt['host'], opt['port'])) servsoc.listen(1) self._logger.info(\"listen : \" + str(opt)) executing",
"addr, count try: return conn.read_holding_registers(addr, count, unit=unit) except Exception as",
"detection is canceled.\") break tempid = port + \"-\" +",
"= [] for gw in self._devinfo: for nd in gw[\"children\"]:",
"CmdCode.OFF, {}) kdmate.writeblk(req) time.sleep(10) req = Request(201) req.setcommand(202, CmdCode.TIMED_OPEN, {\"time\":10})",
"\"failed to connect with tcp\" code = NotiCode.TCP_CONNECTED if ret",
"= False opt = { 'conn' : [{ 'method': 'rtu',",
"get data since size of data is not matched. 6",
"nutriinfo = [{ \"id\" : \"1\", \"dk\" : \"\", \"dt\":",
"NotiCode.DETECT_UNKNOWN_NODE, devid=tempid) # unknown device if noti is None: if",
"canceldetection(self, params): time.sleep(self._timeout) noti = Notice(None, NotiCode.DETECT_CANCELED) # detection is",
"\"107\", \"dk\" : '[1,40261,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"108\", \"dk\"",
"None else: msg = \"It's a wrong connection method. \"",
"{\"time\":10}) kdmate.writeblk(req) time.sleep(15) req = Request(201) req.setcommand(202, CmdCode.TIMED_CLOSE, {\"time\":10}) kdmate.writeblk(req)",
"3), registers res = self._conn[gw[\"dk\"]].write_registers(self.getdk(dev, 3), registers, unit=unit) if res.isError():",
"ret def readactnodeinfo(self, node): ret = self.readnodeinfo(node) for dev in",
"else: self._logger.warn(\"fail to read actuator info : \" + str(act)",
"+ str(opt[\"port\"]) + \"] exception : \" + str(ex)) tmp[\"status\"]",
"{\"value\" : (2, \"float\"), \"status\" : (1, \"status\"), \"opid\" :",
"servsoc.close() for tmp in self._tempthd: if tmp[\"port\"] == opt[\"port\"]: self._logger.warn(\"",
"read sensor info : \" + str(dev) + \" however",
"False opt = { 'conn' : [{ 'method': 'rtu', 'port'",
"response.setresult(code) self._logger.info(\"write response: \" + str(response)) self.writecb(response) return True #if",
"= 3 NUTNODE = 4 class ProtoVer(IntEnum): KS_X_3267_2020 = 10",
"self._detection[\"port\"] is not None and port not in self._detection[\"port\"]: return",
"node): gw = self._devinfo.findgateway(request.getnodeid()) unit = self.getdk(dev, 0) operation =",
"info else: self._logger.warn(\"fail to read actuator info : \" +",
"2 INTNODE = 3 NUTNODE = 4 class ProtoVer(IntEnum): KS_X_3267_2020",
"def connectone(self, opt): ret = False conn = None if",
"from mblock import MBlock, BlkType, StatCode, ResCode, CmdCode, Observation, Request,",
"str(key)) return ResCode.FAIL_WRONG_KEYWORD if KSX3267MateV2._KEYWORDS[key][0] == 1: registers.append(val) elif KSX3267MateV2._KEYWORDS[key][1]",
": 9600, 'timeout': 5 }] } nutriinfo = [{ \"id\"",
"if self._isdetecting == False or self.isexecuting() == False: self._logger.info(\"A port",
"if res.isError(): self._logger.warn(\"Fail to write a request to dev.\" +",
"actuator #for devid, info in ndinfo[\"act\"].iteritems(): # if StatCode.has_value(info[\"status\"]) ==",
"dev, idx): dk = json.loads(dev[\"dk\"]) return dk[idx] def setdetection(self, flag,",
"request\") code = ResCode.FAIL else: self._logger.warn(\"Unknown Error. \" + str(blk)",
"import IntEnum from threading import Thread, Lock from mate import",
"conn.read_holding_registers(addr, count, unit=unit) except Exception as ex: self._logger.warn(\"fail to read",
"= 2 INTNODE = 3 NUTNODE = 4 class ProtoVer(IntEnum):",
"def detect_node(self, conn, unit, registers): print \"detect_node\", unit, registers compcode",
"\" + str(res)) return None if len(res.registers) != size: self._logger.info(\"retry",
"= self.listen(opt) msg = \"failed to connect with tcp\" code",
"self._coupleid: params = blk.getparams() if cmd == CmdCode.DETECT_DEVICE: print \"detect",
": '[1,41010,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #{\"id\" : \"103\", \"dk\" : '[1,41020,[\"value\",\"status\"]]',",
"]} ]} ] devinfo = [{ \"id\" : \"1\", \"dk\"",
"unit, addr, count try: return conn.read_holding_registers(addr, count, unit=unit) except Exception",
"noti = Notice(None, NotiCode.DETECT_NO_NODE, devid=tempid) # Detection Started self._logger.info (\"Fail",
"# self._logger.warn(\"fail to read sensor info : \" + str(dev)",
"\"dt\": \"act/switch/level0\"}, #{\"id\" : \"206\", \"dk\" : (2,40251,[\"opid\",\"status\"],45051,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"},",
"request. \" + str(blk.gettype())) return False response = Response(blk) cmd",
"= ResCode.FAIL_NOT_PROPER_COMMAND elif DevType.isactuator(dev['dt']) or DevType.isnode(dev['dt']): # modbus code =",
": '[2,40201,[\"status\"],45001,[\"operation\",\"opid\"]]', \"dt\": \"nd\", \"children\" : [ {\"id\" : \"202\",",
"\"dt\": \"act/switch/level0\"}, #{\"id\" : \"208\", \"dk\" : (2,40271,[\"opid\",\"status\"],45071,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"},",
"+ \" \" + str(len(res.registers))) return None def readnodeinfo(self, node):",
"values): idx = 0 ret = {} for nm in",
"= values[idx] ret[nm] = val idx = idx + size",
"[{ 'method': 'rtu', 'port' : '/dev/ttyJND2', 'baudrate' : 9600, 'timeout':",
"ResCode.OK def readregister(self, conn, addr, count, unit): print \"....... before",
"= self.connectone(opt) if conn: self._conn[opt[\"port\"][8:]] = conn super(KSX3267MateV2, self).connect() return",
"opid): if self._detection[\"opid\"] != 0: self._logger.info(\"detection is processing.... so this",
"ResCode.FAIL elif dev is None: self._logger.warn(\"There is no device. \"",
"(2, \"int\"), \"ratio\": (1, \"short\"), \"position\" : (1, \"short\"), \"remain-time\"",
"Started self._logger.info (\"Fail to get information from a node :",
"opid) if params: self._detection[\"saddr\"] = params['saddr'] self._detection[\"eaddr\"] = params['eaddr'] self._detection[\"port\"]",
"status from \" + str(dev['dk'])) # break elif res.isError(): self._logger.info(\"retry",
"# error def listen(self, opt): tmp = {\"thd\" : Thread(target=self._listen,",
"res = self.readregister(conn, self.getdk(dev, 1), size, self.getdk(dev, 0)) if res",
"read other device\") return ret def readactinfo(self, node, act): ret",
"info = self.readinfofromdev(ret[\"conn\"], dev) if info: ret[\"act\"][dev[\"id\"]] = info i",
"observation for actuator #for devid, info in ndinfo[\"act\"].iteritems(): # if",
"time.sleep(self._timeout) noti = Notice(None, NotiCode.DETECT_CANCELED) # detection is canceled noti.setkeyvalue(\"opid\",",
"[], \"1\", None) kdmate.start (mate.writeblk) print \"mate started\" time.sleep(10) req",
"else option[\"timeout\"] self._conn = {} self._tempthd = [] self._isdetecting =",
"== 'rtu': conn = ModbusSerialClient(method='rtu', port=opt['port'], timeout=self._timeout, baudrate=opt['baudrate']) ret =",
"str(unit) noti = Notice(None, NotiCode.DETECT_NODE_STARTED, devid=tempid) # Detection Started if",
"return ResCode.FAIL_TO_WRITE msg = self.readactinfo(node, dev) if msg is None:",
"= self.startdetection(params, blk.getopid()) elif cmd == CmdCode.CANCEL_DETECT: print \"cancel to",
"clisoc, address = servsoc.accept() self._logger.info(\"client connected from \" + str(address))",
"= self.readregister(conn, KSX3267MateV2._DEVINFOREG, 6, unit) if res is None or",
"if self._isdetecting: self.detect() self.checktempthreads() def processrequest(self, dev, request, node): gw",
"dev) if info: ret[\"sen\"][dev[\"id\"]] = info #else: # self._logger.warn(\"fail to",
"break if res is None or res.isError(): noti = Notice(None,",
"#{\"id\" : \"208\", \"dk\" : (2,40271,[\"opid\",\"status\"],45071,[\"operation\",\"opid\"]), \"dt\": \"act/switch/level0\"}, #{\"id\" :",
"False def parseregisters(self, names, values): idx = 0 ret =",
"so this command would be ignored.\") return ResCode.FAIL self.setdetection(True, opid)",
"\"nd\" : {\"status\":StatCode.ERROR.value}} gw = self._devinfo.findgateway(node[\"id\"]) conn = self._conn[gw[\"dk\"]] ret[\"conn\"]",
"= None if opt['method'] == 'rtu': conn = ModbusSerialClient(method='rtu', port=opt['port'],",
": \"105\", \"dk\" : '[1,40241,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"106\",",
"node[\"id\"], \"sen\" : {}, \"act\" : {}, \"nd\" : {\"status\":StatCode.ERROR.value}}",
"# detection is canceled else: noti = Notice(None, NotiCode.RTU_CONNECTED) #",
": \"104\", \"dk\" : '[1,40231,[\"value\",\"status\"]]', \"dt\": \"sen\"}, {\"id\" : \"105\",",
"\"sen\"}, #{\"id\" : \"104\", \"dk\" : '[1,40208,[\"value\",\"status\"]]', \"dt\": \"sen\"}, #",
"conn def connect(self): ret = False for opt in self._option['conn']:",
"cmd == CmdCode.DETECT_DEVICE: print \"detect device\" code = self.startdetection(params, blk.getopid())"
] |
[
"#from sets import Set def getfailedcases(withBundle = True): xmlfile='build/reports/junit.xml' tree",
"skipingtests) exit_code = runtest(testarguments + skipingtests, projectPath, schemeName, projectName, destination,",
"\"\" if 'excludetests' in test: for skipingtest in test['excludetests']: skipingtests",
"testcase in testsuite.findall('.//testcase[failure]'): suitename = testsuite.get('name') casename = testcase.get('name') if",
"projectName) testcommand +=\" \" + otherargments; rawoutput = open('raw.log','w') exit_code",
"= runningConfigure['projectName'] projectPath = runningConfigure['projectPath'] schemeName = runningConfigure['schemeName'] sdkName =",
"the test\") testresult = 1 else: print(\"Test succeed\") print(\"testresult:\", testresult)",
"xcpretty.log {0}/{1}/xcpretty.log'.format(test_result_folder,testname)) runcommand('cp build/reports/junit.xml {0}/{1}/junit.xml'.format(test_result_folder,testname)) ignorefailure = False ; if",
"= testcase.get('name') if withBundle: failedtests.add(testbundle + '/' + suitename +",
"in testgroup.keys(): schemeName = testgroup['schemeName'] print(\"projectName, projectPath, schemeName, destination\", projectName,",
"rawoutput.close() print(\"Formatting test result .......\") xcprettycommand = \"cat raw.log |",
"if 'schemeName' in testgroup.keys(): schemeName = testgroup['schemeName'] print(\"projectName, projectPath, schemeName,",
"== 0 : print(\"test command return an error code, but",
"and failedtests : ignoreFailures = set(test['ignoreFailures']) if failedtests.issubset(ignoreFailures): print(\"There are",
">> {0}/{1}/exitcode.log'.format(test_result_folder,testname,exit_code)) runcommand('mv raw.log {0}/{1}/raw.log'.format(test_result_folder,testname)) runcommand('mv xcpretty.log {0}/{1}/xcpretty.log'.format(test_result_folder,testname)) runcommand('cp build/reports/junit.xml",
"print('retriabletimes:', retriabletimes) while retrytimes <= retriabletimes and exit_code > 0:",
"projectPath = runningConfigure['projectPath'] schemeName = runningConfigure['schemeName'] sdkName = runningConfigure['sdkName'] print(\"group",
"+ failed retrytimes += 1 exit_code = runtest(testarguments,projectPath, schemeName, projectName,",
"junit | tee xcpretty.log\" runcommand(xcprettycommand) return exit_code ########################## main function",
"projectPath, schemeName, projectName, destination, derivedDataPath) print(testname, \"exit code:\", exit_code) #",
"test and failedtests : ignoreFailures = set(test['ignoreFailures']) if failedtests.issubset(ignoreFailures): print(\"There",
"+ testname+ \"/\" + skipingtest print(\"excludetests:\", skipingtests) exit_code = runtest(testarguments",
"runtest(testarguments + skipingtests, projectPath, schemeName, projectName, destination, derivedDataPath) print(testname, \"exit",
"| tee xcpretty.log\" runcommand(xcprettycommand) return exit_code ########################## main function ###############################",
"testgroup = testConfigure[group_name] testlist = testgroup['test_list'] if 'projectName' in testgroup.keys()",
"+= ' -skip-testing:' + testname+ \"/\" + skipingtest print(\"excludetests:\", skipingtests)",
"retrytimes, \" times\") testarguments = \"\" for failed in faileds:",
"testcases that cannot be ignored: \", failedtests - ignoreFailures )",
"= True; else : print(\"Failed testcases that cannot be ignored:",
"= testgroup['schemeName'] print(\"projectName, projectPath, schemeName, destination\", projectName, projectPath, schemeName, destination)",
"tests can be retried if exit_code == 65: retriabletimes =",
"= set(test['ignoreFailures']) if failedtests.issubset(ignoreFailures): print(\"There are failed testcases that can",
"command return an error code, but the failed test cases",
"-r junit | tee xcpretty.log\" runcommand(xcprettycommand) return exit_code ########################## main",
"\"export testresult=0\" >> $BASH_ENV') testresult = 0 for testname in",
"' -only-testing:' + testname #create skipping tests parameters skipingtests =",
"path> <test result location> <group name>\".format(sys.argv[0])) ; exit(1) jsonfilename=sys.argv[1] test_result_folder=sys.argv[2]",
"can filter with condtion for testsuite in root.findall(\".//testsuite\"): for testcase",
"; if exit_code == 65 : failedtests = getfailedcases(False) print(\"failedtests:\",",
"testcases that can be ignored\") ignorefailure = True; else :",
"import subprocess import xml.etree.ElementTree as ET import os from datetime",
"if not ignorefailure: print(\"There are faillures in the test\") testresult",
"skipingtest in test['excludetests']: skipingtests += ' -skip-testing:' + testname+ \"/\"",
"'-h' or sys.argv[1] == '-h') : print(\"Usage: \\r\\n {0} <integrationTestsConfiguration",
"= True): xmlfile='build/reports/junit.xml' tree = ET.parse(xmlfile) root = tree.getroot() testbundle",
"65 : failedtests = getfailedcases(False) print(\"failedtests:\", failedtests) if 'ignoreFailures' in",
"runcommand #from sets import Set def getfailedcases(withBundle = True): xmlfile='build/reports/junit.xml'",
"exit_code) break; print(\"failed tests:\",faileds) retrytimes = 1 print('retriabletimes:', retriabletimes) while",
"ignorefailure = False ; if exit_code == 65 : failedtests",
"print(\"exit code:\", exit_code) runcommand('mkdir -p {0}/{1}'.format(test_result_folder,testname)) runcommand('echo \"{2}\" >> {0}/{1}/exitcode.log'.format(test_result_folder,testname,exit_code))",
"ET import os from datetime import datetime from functions import",
"xcpretty.log\") testcommand = \"xcodebuild test-without-building -project {0} -scheme {1} -sdk",
"tee xcpretty.log\" runcommand(xcprettycommand) return exit_code ########################## main function ############################### #",
"testname, \"for \", retrytimes, \" times\") testarguments = \"\" for",
"= 1 print('retriabletimes:', retriabletimes) while retrytimes <= retriabletimes and exit_code",
"import demjson import sys from subprocess import Popen, PIPE import",
"in test: retriabletimes = test['retriabletimes'] if retriabletimes > 1: #get",
"build/reports/junit.xml {0}/{1}/junit.xml'.format(test_result_folder,testname)) ignorefailure = False ; if exit_code == 65",
"getfailedcases(withBundle = True): xmlfile='build/reports/junit.xml' tree = ET.parse(xmlfile) root = tree.getroot()",
"schemeName, projectName, destination, derivedDataPath); print(\"retry exit code:\", exit_code) if(exit_code !=",
"test: retriabletimes = test['retriabletimes'] if retriabletimes > 1: #get all",
"can be retried if exit_code == 65: retriabletimes = 3",
"if 'retriabletimes' in test: retriabletimes = test['retriabletimes'] if retriabletimes >",
"= runtest(testarguments + skipingtests, projectPath, schemeName, projectName, destination, derivedDataPath) print(testname,",
"runcommand('mv raw.log {0}/{1}/raw.log'.format(test_result_folder,testname)) runcommand('mv xcpretty.log {0}/{1}/xcpretty.log'.format(test_result_folder,testname)) runcommand('cp build/reports/junit.xml {0}/{1}/junit.xml'.format(test_result_folder,testname)) ignorefailure",
"suitename = testsuite.get('name') casename = testcase.get('name') if withBundle: failedtests.add(testbundle +",
"{schemeName} -sdk {sdkName} -destination 'platform={paltformName},name={deviceName},OS={osVersion}'\" # testcommandtail = \" |",
"datetime import datetime from functions import runcommand #from sets import",
"group_name = sys.argv[3] destination = sys.argv[4] derivedDataPath = sys.argv[5] with",
"{3}/{4}\".format(projectPath,schemeName, destination, derivedDataPath, projectName) testcommand +=\" \" + otherargments; rawoutput",
"-project {projectName} -scheme {schemeName} -sdk {sdkName} -destination 'platform={paltformName},name={deviceName},OS={osVersion}'\" # testcommandtail",
"\" | tee raw.log | xcpretty -r junit | tee",
">> $BASH_ENV') testresult = 0 for testname in testlist: print(\"-------------------------------\",",
"testsuite.findall('.//testcase[failure]'): suitename = testsuite.get('name') casename = testcase.get('name') if withBundle: failedtests.add(testbundle",
"= rawoutput) rawoutput.close() print(\"Formatting test result .......\") xcprettycommand = \"cat",
"testresult=0\" >> $BASH_ENV') testresult = 0 for testname in testlist:",
"+= ' -only-testing:' + failed retrytimes += 1 exit_code =",
"True; else : print(\"Failed testcases that cannot be ignored: \",",
"{0}/{1}/exitcode.log'.format(test_result_folder,testname,exit_code)) runcommand('mv raw.log {0}/{1}/raw.log'.format(test_result_folder,testname)) runcommand('mv xcpretty.log {0}/{1}/xcpretty.log'.format(test_result_folder,testname)) runcommand('cp build/reports/junit.xml {0}/{1}/junit.xml'.format(test_result_folder,testname))",
"'/' + casename) else: failedtests.add(suitename + '/' + casename) return",
"(len(sys.argv) < 3 or sys.argv[1] == '-h' or sys.argv[1] ==",
": print(\"Usage: \\r\\n {0} <integrationTestsConfiguration json file path> <test result",
"print(\"-------------------------------\", testname , \"-------------------------------\"); test = testlist[testname] testarguments = '",
"{0} <integrationTestsConfiguration json file path> <test result location> <group name>\".format(sys.argv[0]))",
"if(exit_code != 0 ): faileds = getfailedcases() if exit_code !=",
"\" times\") testarguments = \"\" for failed in faileds: testarguments",
"or sys.argv[1] == '-h') : print(\"Usage: \\r\\n {0} <integrationTestsConfiguration json",
"= jsonfile.read() testConfigure = demjson.decode(jsonstring) runningConfigure = testConfigure['runningConfigure'] projectName =",
"print(\"exit code:\", exit_code) break; print(\"failed tests:\",faileds) retrytimes = 1 print('retriabletimes:',",
"runtest(otherargments, projectPath, schemeName, projectName, destination, derivedDataPath, timeout = 0): runcommand(\"rm",
"ET.parse(xmlfile) root = tree.getroot() testbundle = root.get('name') testbundle = testbundle[0:len(testbundle)",
"set() #TODO we can filter with condtion for testsuite in",
"-only-testing:' + testname #create skipping tests parameters skipingtests = \"\"",
"if 'projectName' in testgroup.keys() : projectName = testgroup['projectName'] if 'projectPath'",
"rawoutput = open('raw.log','w') exit_code = runcommand(testcommand,timeout, pipeout = rawoutput) rawoutput.close()",
"with condtion for testsuite in root.findall(\".//testsuite\"): for testcase in testsuite.findall('.//testcase[failure]'):",
"3 or sys.argv[1] == '-h' or sys.argv[1] == '-h') :",
"= \" | tee raw.log | xcpretty -r junit |",
"sets import Set def getfailedcases(withBundle = True): xmlfile='build/reports/junit.xml' tree =",
"withBundle: failedtests.add(testbundle + '/' + suitename + '/' + casename)",
"{1} -sdk iphonesimulator -destination '{2}' -derivedDataPath {3}/{4}\".format(projectPath,schemeName, destination, derivedDataPath, projectName)",
"xcpretty -r junit | tee xcpretty.log\" runcommand('echo \"export testresult=0\" >>",
"as ET import os from datetime import datetime from functions",
"all failed test cases faileds = getfailedcases() if len(faileds) ==",
"> 0: print(\"retry \", testname, \"for \", retrytimes, \" times\")",
"print(\"group name:\", group_name) testgroup = testConfigure[group_name] testlist = testgroup['test_list'] if",
"from functions import runcommand #from sets import Set def getfailedcases(withBundle",
"= testbundle[0:len(testbundle) - 7] failedtests = set() #TODO we can",
") if not ignorefailure: print(\"There are faillures in the test\")",
"test-without-building -project {0} -scheme {1} -sdk iphonesimulator -destination '{2}' -derivedDataPath",
"' -only-testing:' + failed retrytimes += 1 exit_code = runtest(testarguments,projectPath,",
"runcommand('cp build/reports/junit.xml {0}/{1}/junit.xml'.format(test_result_folder,testname)) ignorefailure = False ; if exit_code ==",
"#create skipping tests parameters skipingtests = \"\" if 'excludetests' in",
"print(testname, \"exit code:\", exit_code) # if test fails, check if",
"testgroup['schemeName'] print(\"projectName, projectPath, schemeName, destination\", projectName, projectPath, schemeName, destination) #",
"retriabletimes > 1: #get all failed test cases faileds =",
"testarguments = \"\" for failed in faileds: testarguments += '",
"'projectPath' in testgroup.keys(): projectPath = testgroup['projectPath'] if 'schemeName' in testgroup.keys():",
"-sdk iphonesimulator -destination '{2}' -derivedDataPath {3}/{4}\".format(projectPath,schemeName, destination, derivedDataPath, projectName) testcommand",
"failed tests can be retried if exit_code == 65: retriabletimes",
"faileds = getfailedcases() if exit_code != 0 : print(\"exit code:\",",
"failedtests.issubset(ignoreFailures): print(\"There are failed testcases that can be ignored\") ignorefailure",
"+ casename) else: failedtests.add(suitename + '/' + casename) return failedtests",
"= getfailedcases() if exit_code != 0 : print(\"exit code:\", exit_code)",
"{0}/{1}/raw.log'.format(test_result_folder,testname)) runcommand('mv xcpretty.log {0}/{1}/xcpretty.log'.format(test_result_folder,testname)) runcommand('cp build/reports/junit.xml {0}/{1}/junit.xml'.format(test_result_folder,testname)) ignorefailure = False",
"name>\".format(sys.argv[0])) ; exit(1) jsonfilename=sys.argv[1] test_result_folder=sys.argv[2] group_name = sys.argv[3] destination =",
"- 7] failedtests = set() #TODO we can filter with",
"= 0): runcommand(\"rm raw.log\") runcommand(\"rm xcpretty.log\") testcommand = \"xcodebuild test-without-building",
"in root.findall(\".//testsuite\"): for testcase in testsuite.findall('.//testcase[failure]'): suitename = testsuite.get('name') casename",
"in testgroup.keys() : projectName = testgroup['projectName'] if 'projectPath' in testgroup.keys():",
"test['excludetests']: skipingtests += ' -skip-testing:' + testname+ \"/\" + skipingtest",
"False ; if exit_code == 65 : failedtests = getfailedcases(False)",
"= getfailedcases() if len(faileds) == 0 : print(\"test command return",
"+=\" \" + otherargments; rawoutput = open('raw.log','w') exit_code = runcommand(testcommand,timeout,",
"Set def getfailedcases(withBundle = True): xmlfile='build/reports/junit.xml' tree = ET.parse(xmlfile) root",
"casename) return failedtests #run test def runtest(otherargments, projectPath, schemeName, projectName,",
"in testgroup.keys(): projectPath = testgroup['projectPath'] if 'schemeName' in testgroup.keys(): schemeName",
"runcommand(\"rm xcpretty.log\") testcommand = \"xcodebuild test-without-building -project {0} -scheme {1}",
"function ############################### # a command will like if (len(sys.argv) <",
"<group name>\".format(sys.argv[0])) ; exit(1) jsonfilename=sys.argv[1] test_result_folder=sys.argv[2] group_name = sys.argv[3] destination",
"testlist = testgroup['test_list'] if 'projectName' in testgroup.keys() : projectName =",
"set(test['ignoreFailures']) if failedtests.issubset(ignoreFailures): print(\"There are failed testcases that can be",
"print(\"retry \", testname, \"for \", retrytimes, \" times\") testarguments =",
"test_result_folder=sys.argv[2] group_name = sys.argv[3] destination = sys.argv[4] derivedDataPath = sys.argv[5]",
"{0}/{1}/junit.xml'.format(test_result_folder,testname)) ignorefailure = False ; if exit_code == 65 :",
"len(faileds) == 0 : print(\"test command return an error code,",
"xmlfile='build/reports/junit.xml' tree = ET.parse(xmlfile) root = tree.getroot() testbundle = root.get('name')",
"the failed tests can be retried if exit_code == 65:",
"destination, derivedDataPath, projectName) testcommand +=\" \" + otherargments; rawoutput =",
"schemeName = testgroup['schemeName'] print(\"projectName, projectPath, schemeName, destination\", projectName, projectPath, schemeName,",
"if failedtests.issubset(ignoreFailures): print(\"There are failed testcases that can be ignored\")",
"3 ; if 'retriabletimes' in test: retriabletimes = test['retriabletimes'] if",
"be ignored\") ignorefailure = True; else : print(\"Failed testcases that",
"runcommand(xcprettycommand) return exit_code ########################## main function ############################### # a command",
"with open(jsonfilename, 'r') as jsonfile: jsonstring = jsonfile.read() testConfigure =",
"'projectName' in testgroup.keys() : projectName = testgroup['projectName'] if 'projectPath' in",
"are failed testcases that can be ignored\") ignorefailure = True;",
"or sys.argv[1] == '-h' or sys.argv[1] == '-h') : print(\"Usage:",
"= f\"xcodebuild test-without-building -project {projectName} -scheme {schemeName} -sdk {sdkName} -destination",
"= testConfigure[group_name] testlist = testgroup['test_list'] if 'projectName' in testgroup.keys() :",
"import Set def getfailedcases(withBundle = True): xmlfile='build/reports/junit.xml' tree = ET.parse(xmlfile)",
"raw.log | xcpretty -r junit | tee xcpretty.log\" runcommand(xcprettycommand) return",
"raw.log {0}/{1}/raw.log'.format(test_result_folder,testname)) runcommand('mv xcpretty.log {0}/{1}/xcpretty.log'.format(test_result_folder,testname)) runcommand('cp build/reports/junit.xml {0}/{1}/junit.xml'.format(test_result_folder,testname)) ignorefailure =",
"'schemeName' in testgroup.keys(): schemeName = testgroup['schemeName'] print(\"projectName, projectPath, schemeName, destination\",",
"\"/\" + skipingtest print(\"excludetests:\", skipingtests) exit_code = runtest(testarguments + skipingtests,",
"'retriabletimes' in test: retriabletimes = test['retriabletimes'] if retriabletimes > 1:",
"runcommand(\"rm raw.log\") runcommand(\"rm xcpretty.log\") testcommand = \"xcodebuild test-without-building -project {0}",
"json file path> <test result location> <group name>\".format(sys.argv[0])) ; exit(1)",
"+ '/' + suitename + '/' + casename) else: failedtests.add(suitename",
"projectPath = testgroup['projectPath'] if 'schemeName' in testgroup.keys(): schemeName = testgroup['schemeName']",
"else : print(\"Failed testcases that cannot be ignored: \", failedtests",
": ignoreFailures = set(test['ignoreFailures']) if failedtests.issubset(ignoreFailures): print(\"There are failed testcases",
"root = tree.getroot() testbundle = root.get('name') testbundle = testbundle[0:len(testbundle) -",
"runcommand(testcommand,timeout, pipeout = rawoutput) rawoutput.close() print(\"Formatting test result .......\") xcprettycommand",
"#get all failed test cases faileds = getfailedcases() if len(faileds)",
"-scheme {schemeName} -sdk {sdkName} -destination 'platform={paltformName},name={deviceName},OS={osVersion}'\" # testcommandtail = \"",
"testgroup['projectPath'] if 'schemeName' in testgroup.keys(): schemeName = testgroup['schemeName'] print(\"projectName, projectPath,",
": print(\"Failed testcases that cannot be ignored: \", failedtests -",
"in test and failedtests : ignoreFailures = set(test['ignoreFailures']) if failedtests.issubset(ignoreFailures):",
"tests parameters skipingtests = \"\" if 'excludetests' in test: for",
"in the test\") testresult = 1 else: print(\"Test succeed\") print(\"testresult:\",",
"tee raw.log | xcpretty -r junit | tee xcpretty.log\" runcommand('echo",
"retrytimes += 1 exit_code = runtest(testarguments,projectPath, schemeName, projectName, destination, derivedDataPath);",
"timeout = 0): runcommand(\"rm raw.log\") runcommand(\"rm xcpretty.log\") testcommand = \"xcodebuild",
"'-h') : print(\"Usage: \\r\\n {0} <integrationTestsConfiguration json file path> <test",
"ignored: \", failedtests - ignoreFailures ) if not ignorefailure: print(\"There",
"skipingtests += ' -skip-testing:' + testname+ \"/\" + skipingtest print(\"excludetests:\",",
"for skipingtest in test['excludetests']: skipingtests += ' -skip-testing:' + testname+",
"def getfailedcases(withBundle = True): xmlfile='build/reports/junit.xml' tree = ET.parse(xmlfile) root =",
"= runcommand(testcommand,timeout, pipeout = rawoutput) rawoutput.close() print(\"Formatting test result .......\")",
"PIPE import subprocess import xml.etree.ElementTree as ET import os from",
"in testsuite.findall('.//testcase[failure]'): suitename = testsuite.get('name') casename = testcase.get('name') if withBundle:",
"' -skip-testing:' + testname+ \"/\" + skipingtest print(\"excludetests:\", skipingtests) exit_code",
"test cases is 0\") print(\"exit code:\", exit_code) break; print(\"failed tests:\",faileds)",
"testConfigure[group_name] testlist = testgroup['test_list'] if 'projectName' in testgroup.keys() : projectName",
"print(\"Usage: \\r\\n {0} <integrationTestsConfiguration json file path> <test result location>",
"print(\"projectName, projectPath, schemeName, destination\", projectName, projectPath, schemeName, destination) # testcommandhead",
"failedtests - ignoreFailures ) if not ignorefailure: print(\"There are faillures",
"############################### # a command will like if (len(sys.argv) < 3",
"# if test fails, check if the failed tests can",
"testresult = 1 else: print(\"Test succeed\") print(\"testresult:\", testresult) runcommand('echo \"export",
"failedtests) if 'ignoreFailures' in test and failedtests : ignoreFailures =",
"-project {0} -scheme {1} -sdk iphonesimulator -destination '{2}' -derivedDataPath {3}/{4}\".format(projectPath,schemeName,",
"# testcommandtail = \" | tee raw.log | xcpretty -r",
"ignorefailure = True; else : print(\"Failed testcases that cannot be",
"{sdkName} -destination 'platform={paltformName},name={deviceName},OS={osVersion}'\" # testcommandtail = \" | tee raw.log",
"import os from datetime import datetime from functions import runcommand",
"0): runcommand(\"rm raw.log\") runcommand(\"rm xcpretty.log\") testcommand = \"xcodebuild test-without-building -project",
"{0}/{1}'.format(test_result_folder,testname)) runcommand('echo \"{2}\" >> {0}/{1}/exitcode.log'.format(test_result_folder,testname,exit_code)) runcommand('mv raw.log {0}/{1}/raw.log'.format(test_result_folder,testname)) runcommand('mv xcpretty.log",
"= testgroup['projectName'] if 'projectPath' in testgroup.keys(): projectPath = testgroup['projectPath'] if",
"projectName, destination, derivedDataPath) print(testname, \"exit code:\", exit_code) # if test",
"code:\", exit_code) # if test fails, check if the failed",
"failedtests.add(suitename + '/' + casename) return failedtests #run test def",
"\"\" for failed in faileds: testarguments += ' -only-testing:' +",
"failedtests : ignoreFailures = set(test['ignoreFailures']) if failedtests.issubset(ignoreFailures): print(\"There are failed",
"derivedDataPath, timeout = 0): runcommand(\"rm raw.log\") runcommand(\"rm xcpretty.log\") testcommand =",
"ignoreFailures = set(test['ignoreFailures']) if failedtests.issubset(ignoreFailures): print(\"There are failed testcases that",
"be retried if exit_code == 65: retriabletimes = 3 ;",
"testcommand = \"xcodebuild test-without-building -project {0} -scheme {1} -sdk iphonesimulator",
"ignorefailure: print(\"There are faillures in the test\") testresult = 1",
"): faileds = getfailedcases() if exit_code != 0 : print(\"exit",
"return failedtests #run test def runtest(otherargments, projectPath, schemeName, projectName, destination,",
"testConfigure = demjson.decode(jsonstring) runningConfigure = testConfigure['runningConfigure'] projectName = runningConfigure['projectName'] projectPath",
"= \"cat raw.log | xcpretty -r junit | tee xcpretty.log\"",
"!= 0 : print(\"exit code:\", exit_code) runcommand('mkdir -p {0}/{1}'.format(test_result_folder,testname)) runcommand('echo",
"root.get('name') testbundle = testbundle[0:len(testbundle) - 7] failedtests = set() #TODO",
"0 : print(\"test command return an error code, but the",
"testgroup.keys(): projectPath = testgroup['projectPath'] if 'schemeName' in testgroup.keys(): schemeName =",
"else: failedtests.add(suitename + '/' + casename) return failedtests #run test",
"<= retriabletimes and exit_code > 0: print(\"retry \", testname, \"for",
"tee xcpretty.log\" runcommand('echo \"export testresult=0\" >> $BASH_ENV') testresult = 0",
"retriabletimes and exit_code > 0: print(\"retry \", testname, \"for \",",
"faileds = getfailedcases() if len(faileds) == 0 : print(\"test command",
"open(jsonfilename, 'r') as jsonfile: jsonstring = jsonfile.read() testConfigure = demjson.decode(jsonstring)",
"= sys.argv[4] derivedDataPath = sys.argv[5] with open(jsonfilename, 'r') as jsonfile:",
"\"exit code:\", exit_code) # if test fails, check if the",
"test cases faileds = getfailedcases() if len(faileds) == 0 :",
"< 3 or sys.argv[1] == '-h' or sys.argv[1] == '-h')",
": print(\"exit code:\", exit_code) runcommand('mkdir -p {0}/{1}'.format(test_result_folder,testname)) runcommand('echo \"{2}\" >>",
"derivedDataPath) print(testname, \"exit code:\", exit_code) # if test fails, check",
"-destination '{2}' -derivedDataPath {3}/{4}\".format(projectPath,schemeName, destination, derivedDataPath, projectName) testcommand +=\" \"",
"getfailedcases(False) print(\"failedtests:\", failedtests) if 'ignoreFailures' in test and failedtests :",
"result location> <group name>\".format(sys.argv[0])) ; exit(1) jsonfilename=sys.argv[1] test_result_folder=sys.argv[2] group_name =",
"in test['excludetests']: skipingtests += ' -skip-testing:' + testname+ \"/\" +",
"can be ignored\") ignorefailure = True; else : print(\"Failed testcases",
"import sys from subprocess import Popen, PIPE import subprocess import",
"faileds: testarguments += ' -only-testing:' + failed retrytimes += 1",
"error code, but the failed test cases is 0\") print(\"exit",
"testname #create skipping tests parameters skipingtests = \"\" if 'excludetests'",
"xcpretty.log\" runcommand('echo \"export testresult=0\" >> $BASH_ENV') testresult = 0 for",
"an error code, but the failed test cases is 0\")",
"schemeName, projectName, destination, derivedDataPath) print(testname, \"exit code:\", exit_code) # if",
"schemeName, destination) # testcommandhead = f\"xcodebuild test-without-building -project {projectName} -scheme",
"xcpretty -r junit | tee xcpretty.log\" runcommand(xcprettycommand) return exit_code ##########################",
"= sys.argv[3] destination = sys.argv[4] derivedDataPath = sys.argv[5] with open(jsonfilename,",
"'excludetests' in test: for skipingtest in test['excludetests']: skipingtests += '",
"skipingtests, projectPath, schemeName, projectName, destination, derivedDataPath) print(testname, \"exit code:\", exit_code)",
"exit_code != 0 : print(\"exit code:\", exit_code) runcommand('mkdir -p {0}/{1}'.format(test_result_folder,testname))",
"+ '/' + casename) else: failedtests.add(suitename + '/' + casename)",
"name:\", group_name) testgroup = testConfigure[group_name] testlist = testgroup['test_list'] if 'projectName'",
"runningConfigure = testConfigure['runningConfigure'] projectName = runningConfigure['projectName'] projectPath = runningConfigure['projectPath'] schemeName",
"tree = ET.parse(xmlfile) root = tree.getroot() testbundle = root.get('name') testbundle",
"'/' + casename) return failedtests #run test def runtest(otherargments, projectPath,",
"== 65: retriabletimes = 3 ; if 'retriabletimes' in test:",
"sys.argv[1] == '-h' or sys.argv[1] == '-h') : print(\"Usage: \\r\\n",
"test fails, check if the failed tests can be retried",
"jsonstring = jsonfile.read() testConfigure = demjson.decode(jsonstring) runningConfigure = testConfigure['runningConfigure'] projectName",
"destination, derivedDataPath, timeout = 0): runcommand(\"rm raw.log\") runcommand(\"rm xcpretty.log\") testcommand",
"> 1: #get all failed test cases faileds = getfailedcases()",
"derivedDataPath, projectName) testcommand +=\" \" + otherargments; rawoutput = open('raw.log','w')",
"exit code:\", exit_code) if(exit_code != 0 ): faileds = getfailedcases()",
"= \"\" if 'excludetests' in test: for skipingtest in test['excludetests']:",
"will like if (len(sys.argv) < 3 or sys.argv[1] == '-h'",
"= testConfigure['runningConfigure'] projectName = runningConfigure['projectName'] projectPath = runningConfigure['projectPath'] schemeName =",
"projectPath, schemeName, projectName, destination, derivedDataPath, timeout = 0): runcommand(\"rm raw.log\")",
"testbundle[0:len(testbundle) - 7] failedtests = set() #TODO we can filter",
"derivedDataPath = sys.argv[5] with open(jsonfilename, 'r') as jsonfile: jsonstring =",
"skipingtest print(\"excludetests:\", skipingtests) exit_code = runtest(testarguments + skipingtests, projectPath, schemeName,",
"exit_code > 0: print(\"retry \", testname, \"for \", retrytimes, \"",
"!= 0 ): faileds = getfailedcases() if exit_code != 0",
"raw.log | xcpretty -r junit | tee xcpretty.log\" runcommand('echo \"export",
"skipingtests = \"\" if 'excludetests' in test: for skipingtest in",
"\", failedtests - ignoreFailures ) if not ignorefailure: print(\"There are",
"raw.log\") runcommand(\"rm xcpretty.log\") testcommand = \"xcodebuild test-without-building -project {0} -scheme",
"runcommand('echo \"{2}\" >> {0}/{1}/exitcode.log'.format(test_result_folder,testname,exit_code)) runcommand('mv raw.log {0}/{1}/raw.log'.format(test_result_folder,testname)) runcommand('mv xcpretty.log {0}/{1}/xcpretty.log'.format(test_result_folder,testname))",
"we can filter with condtion for testsuite in root.findall(\".//testsuite\"): for",
"ignoreFailures ) if not ignorefailure: print(\"There are faillures in the",
"ignored\") ignorefailure = True; else : print(\"Failed testcases that cannot",
"faillures in the test\") testresult = 1 else: print(\"Test succeed\")",
"from datetime import datetime from functions import runcommand #from sets",
"testsuite in root.findall(\".//testsuite\"): for testcase in testsuite.findall('.//testcase[failure]'): suitename = testsuite.get('name')",
"location> <group name>\".format(sys.argv[0])) ; exit(1) jsonfilename=sys.argv[1] test_result_folder=sys.argv[2] group_name = sys.argv[3]",
"| xcpretty -r junit | tee xcpretty.log\" runcommand(xcprettycommand) return exit_code",
"sys from subprocess import Popen, PIPE import subprocess import xml.etree.ElementTree",
"test\") testresult = 1 else: print(\"Test succeed\") print(\"testresult:\", testresult) runcommand('echo",
"if retriabletimes > 1: #get all failed test cases faileds",
"= runningConfigure['schemeName'] sdkName = runningConfigure['sdkName'] print(\"group name:\", group_name) testgroup =",
"if withBundle: failedtests.add(testbundle + '/' + suitename + '/' +",
"failed test cases is 0\") print(\"exit code:\", exit_code) break; print(\"failed",
"exit_code) # if test fails, check if the failed tests",
"test = testlist[testname] testarguments = ' -only-testing:' + testname #create",
"testgroup.keys(): schemeName = testgroup['schemeName'] print(\"projectName, projectPath, schemeName, destination\", projectName, projectPath,",
"-scheme {1} -sdk iphonesimulator -destination '{2}' -derivedDataPath {3}/{4}\".format(projectPath,schemeName, destination, derivedDataPath,",
"65: retriabletimes = 3 ; if 'retriabletimes' in test: retriabletimes",
"failedtests = set() #TODO we can filter with condtion for",
"condtion for testsuite in root.findall(\".//testsuite\"): for testcase in testsuite.findall('.//testcase[failure]'): suitename",
"the failed test cases is 0\") print(\"exit code:\", exit_code) break;",
"getfailedcases() if len(faileds) == 0 : print(\"test command return an",
"if exit_code == 65 : failedtests = getfailedcases(False) print(\"failedtests:\", failedtests)",
": projectName = testgroup['projectName'] if 'projectPath' in testgroup.keys(): projectPath =",
"exit_code) runcommand('mkdir -p {0}/{1}'.format(test_result_folder,testname)) runcommand('echo \"{2}\" >> {0}/{1}/exitcode.log'.format(test_result_folder,testname,exit_code)) runcommand('mv raw.log",
"schemeName, projectName, destination, derivedDataPath, timeout = 0): runcommand(\"rm raw.log\") runcommand(\"rm",
"test result .......\") xcprettycommand = \"cat raw.log | xcpretty -r",
"print(\"failed tests:\",faileds) retrytimes = 1 print('retriabletimes:', retriabletimes) while retrytimes <=",
"= testgroup['test_list'] if 'projectName' in testgroup.keys() : projectName = testgroup['projectName']",
"projectPath, schemeName, destination\", projectName, projectPath, schemeName, destination) # testcommandhead =",
"a command will like if (len(sys.argv) < 3 or sys.argv[1]",
"testresult = 0 for testname in testlist: print(\"-------------------------------\", testname ,",
"projectName, destination, derivedDataPath); print(\"retry exit code:\", exit_code) if(exit_code != 0",
"'{2}' -derivedDataPath {3}/{4}\".format(projectPath,schemeName, destination, derivedDataPath, projectName) testcommand +=\" \" +",
"testlist: print(\"-------------------------------\", testname , \"-------------------------------\"); test = testlist[testname] testarguments =",
", \"-------------------------------\"); test = testlist[testname] testarguments = ' -only-testing:' +",
"cannot be ignored: \", failedtests - ignoreFailures ) if not",
"import datetime from functions import runcommand #from sets import Set",
"runcommand('echo \"export testresult=0\" >> $BASH_ENV') testresult = 0 for testname",
"print(\"Failed testcases that cannot be ignored: \", failedtests - ignoreFailures",
"schemeName = runningConfigure['schemeName'] sdkName = runningConfigure['sdkName'] print(\"group name:\", group_name) testgroup",
"testgroup['test_list'] if 'projectName' in testgroup.keys() : projectName = testgroup['projectName'] if",
"junit | tee xcpretty.log\" runcommand('echo \"export testresult=0\" >> $BASH_ENV') testresult",
"like if (len(sys.argv) < 3 or sys.argv[1] == '-h' or",
"retrytimes <= retriabletimes and exit_code > 0: print(\"retry \", testname,",
"= testgroup['projectPath'] if 'schemeName' in testgroup.keys(): schemeName = testgroup['schemeName'] print(\"projectName,",
"root.findall(\".//testsuite\"): for testcase in testsuite.findall('.//testcase[failure]'): suitename = testsuite.get('name') casename =",
"skipping tests parameters skipingtests = \"\" if 'excludetests' in test:",
"-destination 'platform={paltformName},name={deviceName},OS={osVersion}'\" # testcommandtail = \" | tee raw.log |",
"is 0\") print(\"exit code:\", exit_code) break; print(\"failed tests:\",faileds) retrytimes =",
"open('raw.log','w') exit_code = runcommand(testcommand,timeout, pipeout = rawoutput) rawoutput.close() print(\"Formatting test",
"cases faileds = getfailedcases() if len(faileds) == 0 : print(\"test",
"filter with condtion for testsuite in root.findall(\".//testsuite\"): for testcase in",
"\", testname, \"for \", retrytimes, \" times\") testarguments = \"\"",
"print(\"failedtests:\", failedtests) if 'ignoreFailures' in test and failedtests : ignoreFailures",
"import runcommand #from sets import Set def getfailedcases(withBundle = True):",
"testbundle = testbundle[0:len(testbundle) - 7] failedtests = set() #TODO we",
"testcase.get('name') if withBundle: failedtests.add(testbundle + '/' + suitename + '/'",
"testarguments = ' -only-testing:' + testname #create skipping tests parameters",
"jsonfile.read() testConfigure = demjson.decode(jsonstring) runningConfigure = testConfigure['runningConfigure'] projectName = runningConfigure['projectName']",
": print(\"test command return an error code, but the failed",
"testsuite.get('name') casename = testcase.get('name') if withBundle: failedtests.add(testbundle + '/' +",
"testname in testlist: print(\"-------------------------------\", testname , \"-------------------------------\"); test = testlist[testname]",
"code:\", exit_code) runcommand('mkdir -p {0}/{1}'.format(test_result_folder,testname)) runcommand('echo \"{2}\" >> {0}/{1}/exitcode.log'.format(test_result_folder,testname,exit_code)) runcommand('mv",
"= ET.parse(xmlfile) root = tree.getroot() testbundle = root.get('name') testbundle =",
"testcommand +=\" \" + otherargments; rawoutput = open('raw.log','w') exit_code =",
"failed retrytimes += 1 exit_code = runtest(testarguments,projectPath, schemeName, projectName, destination,",
"{0}/{1}/xcpretty.log'.format(test_result_folder,testname)) runcommand('cp build/reports/junit.xml {0}/{1}/junit.xml'.format(test_result_folder,testname)) ignorefailure = False ; if exit_code",
"exit_code == 65 : failedtests = getfailedcases(False) print(\"failedtests:\", failedtests) if",
"########################## main function ############################### # a command will like if",
"derivedDataPath); print(\"retry exit code:\", exit_code) if(exit_code != 0 ): faileds",
"exit_code = runtest(testarguments + skipingtests, projectPath, schemeName, projectName, destination, derivedDataPath)",
"runningConfigure['sdkName'] print(\"group name:\", group_name) testgroup = testConfigure[group_name] testlist = testgroup['test_list']",
"sys.argv[4] derivedDataPath = sys.argv[5] with open(jsonfilename, 'r') as jsonfile: jsonstring",
"testcommandtail = \" | tee raw.log | xcpretty -r junit",
"+ testname #create skipping tests parameters skipingtests = \"\" if",
"'r') as jsonfile: jsonstring = jsonfile.read() testConfigure = demjson.decode(jsonstring) runningConfigure",
"destination, derivedDataPath) print(testname, \"exit code:\", exit_code) # if test fails,",
"exit_code = runcommand(testcommand,timeout, pipeout = rawoutput) rawoutput.close() print(\"Formatting test result",
"print(\"excludetests:\", skipingtests) exit_code = runtest(testarguments + skipingtests, projectPath, schemeName, projectName,",
"test def runtest(otherargments, projectPath, schemeName, projectName, destination, derivedDataPath, timeout =",
"sys.argv[1] == '-h') : print(\"Usage: \\r\\n {0} <integrationTestsConfiguration json file",
"runningConfigure['schemeName'] sdkName = runningConfigure['sdkName'] print(\"group name:\", group_name) testgroup = testConfigure[group_name]",
"- ignoreFailures ) if not ignorefailure: print(\"There are faillures in",
"= runningConfigure['sdkName'] print(\"group name:\", group_name) testgroup = testConfigure[group_name] testlist =",
"{0} -scheme {1} -sdk iphonesimulator -destination '{2}' -derivedDataPath {3}/{4}\".format(projectPath,schemeName, destination,",
"= 1 else: print(\"Test succeed\") print(\"testresult:\", testresult) runcommand('echo \"export testresult={0}\"",
"== '-h') : print(\"Usage: \\r\\n {0} <integrationTestsConfiguration json file path>",
"#TODO we can filter with condtion for testsuite in root.findall(\".//testsuite\"):",
"1: #get all failed test cases faileds = getfailedcases() if",
"for failed in faileds: testarguments += ' -only-testing:' + failed",
"1 else: print(\"Test succeed\") print(\"testresult:\", testresult) runcommand('echo \"export testresult={0}\" >>",
"+ otherargments; rawoutput = open('raw.log','w') exit_code = runcommand(testcommand,timeout, pipeout =",
"testConfigure['runningConfigure'] projectName = runningConfigure['projectName'] projectPath = runningConfigure['projectPath'] schemeName = runningConfigure['schemeName']",
"+ casename) return failedtests #run test def runtest(otherargments, projectPath, schemeName,",
"= 3 ; if 'retriabletimes' in test: retriabletimes = test['retriabletimes']",
"cases is 0\") print(\"exit code:\", exit_code) break; print(\"failed tests:\",faileds) retrytimes",
"tree.getroot() testbundle = root.get('name') testbundle = testbundle[0:len(testbundle) - 7] failedtests",
"= testlist[testname] testarguments = ' -only-testing:' + testname #create skipping",
"0 : print(\"exit code:\", exit_code) runcommand('mkdir -p {0}/{1}'.format(test_result_folder,testname)) runcommand('echo \"{2}\"",
"+ '/' + casename) return failedtests #run test def runtest(otherargments,",
"= \"xcodebuild test-without-building -project {0} -scheme {1} -sdk iphonesimulator -destination",
"break; print(\"failed tests:\",faileds) retrytimes = 1 print('retriabletimes:', retriabletimes) while retrytimes",
"Popen, PIPE import subprocess import xml.etree.ElementTree as ET import os",
"sys.argv[5] with open(jsonfilename, 'r') as jsonfile: jsonstring = jsonfile.read() testConfigure",
"tests:\",faileds) retrytimes = 1 print('retriabletimes:', retriabletimes) while retrytimes <= retriabletimes",
"code:\", exit_code) if(exit_code != 0 ): faileds = getfailedcases() if",
"+ skipingtests, projectPath, schemeName, projectName, destination, derivedDataPath) print(testname, \"exit code:\",",
"exit_code ########################## main function ############################### # a command will like",
"0: print(\"retry \", testname, \"for \", retrytimes, \" times\") testarguments",
"-sdk {sdkName} -destination 'platform={paltformName},name={deviceName},OS={osVersion}'\" # testcommandtail = \" | tee",
"if 'ignoreFailures' in test and failedtests : ignoreFailures = set(test['ignoreFailures'])",
"= runtest(testarguments,projectPath, schemeName, projectName, destination, derivedDataPath); print(\"retry exit code:\", exit_code)",
"schemeName, destination\", projectName, projectPath, schemeName, destination) # testcommandhead = f\"xcodebuild",
"failed test cases faileds = getfailedcases() if len(faileds) == 0",
"datetime from functions import runcommand #from sets import Set def",
": failedtests = getfailedcases(False) print(\"failedtests:\", failedtests) if 'ignoreFailures' in test",
"not ignorefailure: print(\"There are faillures in the test\") testresult =",
"+= 1 exit_code = runtest(testarguments,projectPath, schemeName, projectName, destination, derivedDataPath); print(\"retry",
"jsonfile: jsonstring = jsonfile.read() testConfigure = demjson.decode(jsonstring) runningConfigure = testConfigure['runningConfigure']",
"\" + otherargments; rawoutput = open('raw.log','w') exit_code = runcommand(testcommand,timeout, pipeout",
"if (len(sys.argv) < 3 or sys.argv[1] == '-h' or sys.argv[1]",
"| tee raw.log | xcpretty -r junit | tee xcpretty.log\"",
"in testlist: print(\"-------------------------------\", testname , \"-------------------------------\"); test = testlist[testname] testarguments",
"getfailedcases() if exit_code != 0 : print(\"exit code:\", exit_code) runcommand('mkdir",
"if the failed tests can be retried if exit_code ==",
"testname+ \"/\" + skipingtest print(\"excludetests:\", skipingtests) exit_code = runtest(testarguments +",
"'platform={paltformName},name={deviceName},OS={osVersion}'\" # testcommandtail = \" | tee raw.log | xcpretty",
"print(\"Formatting test result .......\") xcprettycommand = \"cat raw.log | xcpretty",
"{projectName} -scheme {schemeName} -sdk {sdkName} -destination 'platform={paltformName},name={deviceName},OS={osVersion}'\" # testcommandtail =",
"testname , \"-------------------------------\"); test = testlist[testname] testarguments = ' -only-testing:'",
"\", retrytimes, \" times\") testarguments = \"\" for failed in",
"testcommandhead = f\"xcodebuild test-without-building -project {projectName} -scheme {schemeName} -sdk {sdkName}",
"runningConfigure['projectName'] projectPath = runningConfigure['projectPath'] schemeName = runningConfigure['schemeName'] sdkName = runningConfigure['sdkName']",
"import Popen, PIPE import subprocess import xml.etree.ElementTree as ET import",
"from subprocess import Popen, PIPE import subprocess import xml.etree.ElementTree as",
"group_name) testgroup = testConfigure[group_name] testlist = testgroup['test_list'] if 'projectName' in",
"runcommand('mkdir -p {0}/{1}'.format(test_result_folder,testname)) runcommand('echo \"{2}\" >> {0}/{1}/exitcode.log'.format(test_result_folder,testname,exit_code)) runcommand('mv raw.log {0}/{1}/raw.log'.format(test_result_folder,testname))",
"that can be ignored\") ignorefailure = True; else : print(\"Failed",
"# testcommandhead = f\"xcodebuild test-without-building -project {projectName} -scheme {schemeName} -sdk",
"= ' -only-testing:' + testname #create skipping tests parameters skipingtests",
"jsonfilename=sys.argv[1] test_result_folder=sys.argv[2] group_name = sys.argv[3] destination = sys.argv[4] derivedDataPath =",
"test['retriabletimes'] if retriabletimes > 1: #get all failed test cases",
"pipeout = rawoutput) rawoutput.close() print(\"Formatting test result .......\") xcprettycommand =",
"testarguments += ' -only-testing:' + failed retrytimes += 1 exit_code",
"import xml.etree.ElementTree as ET import os from datetime import datetime",
"+ skipingtest print(\"excludetests:\", skipingtests) exit_code = runtest(testarguments + skipingtests, projectPath,",
"testlist[testname] testarguments = ' -only-testing:' + testname #create skipping tests",
"if exit_code != 0 : print(\"exit code:\", exit_code) runcommand('mkdir -p",
"failedtests #run test def runtest(otherargments, projectPath, schemeName, projectName, destination, derivedDataPath,",
"print(\"retry exit code:\", exit_code) if(exit_code != 0 ): faileds =",
"if 'projectPath' in testgroup.keys(): projectPath = testgroup['projectPath'] if 'schemeName' in",
"retriabletimes = test['retriabletimes'] if retriabletimes > 1: #get all failed",
"in test: for skipingtest in test['excludetests']: skipingtests += ' -skip-testing:'",
"= sys.argv[5] with open(jsonfilename, 'r') as jsonfile: jsonstring = jsonfile.read()",
"+ suitename + '/' + casename) else: failedtests.add(suitename + '/'",
"demjson.decode(jsonstring) runningConfigure = testConfigure['runningConfigure'] projectName = runningConfigure['projectName'] projectPath = runningConfigure['projectPath']",
"in faileds: testarguments += ' -only-testing:' + failed retrytimes +=",
"7] failedtests = set() #TODO we can filter with condtion",
"test-without-building -project {projectName} -scheme {schemeName} -sdk {sdkName} -destination 'platform={paltformName},name={deviceName},OS={osVersion}'\" #",
"print(\"test command return an error code, but the failed test",
"for testcase in testsuite.findall('.//testcase[failure]'): suitename = testsuite.get('name') casename = testcase.get('name')",
"parameters skipingtests = \"\" if 'excludetests' in test: for skipingtest",
"= 0 for testname in testlist: print(\"-------------------------------\", testname , \"-------------------------------\");",
"failedtests = getfailedcases(False) print(\"failedtests:\", failedtests) if 'ignoreFailures' in test and",
"destination = sys.argv[4] derivedDataPath = sys.argv[5] with open(jsonfilename, 'r') as",
"return an error code, but the failed test cases is",
"rawoutput) rawoutput.close() print(\"Formatting test result .......\") xcprettycommand = \"cat raw.log",
"= root.get('name') testbundle = testbundle[0:len(testbundle) - 7] failedtests = set()",
"exit_code == 65: retriabletimes = 3 ; if 'retriabletimes' in",
"runtest(testarguments,projectPath, schemeName, projectName, destination, derivedDataPath); print(\"retry exit code:\", exit_code) if(exit_code",
"-only-testing:' + failed retrytimes += 1 exit_code = runtest(testarguments,projectPath, schemeName,",
"print(\"There are failed testcases that can be ignored\") ignorefailure =",
"test: for skipingtest in test['excludetests']: skipingtests += ' -skip-testing:' +",
"| tee xcpretty.log\" runcommand('echo \"export testresult=0\" >> $BASH_ENV') testresult =",
"code, but the failed test cases is 0\") print(\"exit code:\",",
"failedtests.add(testbundle + '/' + suitename + '/' + casename) else:",
"exit_code) if(exit_code != 0 ): faileds = getfailedcases() if exit_code",
"== '-h' or sys.argv[1] == '-h') : print(\"Usage: \\r\\n {0}",
"and exit_code > 0: print(\"retry \", testname, \"for \", retrytimes,",
"runningConfigure['projectPath'] schemeName = runningConfigure['schemeName'] sdkName = runningConfigure['sdkName'] print(\"group name:\", group_name)",
"<integrationTestsConfiguration json file path> <test result location> <group name>\".format(sys.argv[0])) ;",
"= runningConfigure['projectPath'] schemeName = runningConfigure['schemeName'] sdkName = runningConfigure['sdkName'] print(\"group name:\",",
"if exit_code == 65: retriabletimes = 3 ; if 'retriabletimes'",
"return exit_code ########################## main function ############################### # a command will",
"destination\", projectName, projectPath, schemeName, destination) # testcommandhead = f\"xcodebuild test-without-building",
"projectName = runningConfigure['projectName'] projectPath = runningConfigure['projectPath'] schemeName = runningConfigure['schemeName'] sdkName",
"failed in faileds: testarguments += ' -only-testing:' + failed retrytimes",
"demjson import sys from subprocess import Popen, PIPE import subprocess",
"; exit(1) jsonfilename=sys.argv[1] test_result_folder=sys.argv[2] group_name = sys.argv[3] destination = sys.argv[4]",
"exit(1) jsonfilename=sys.argv[1] test_result_folder=sys.argv[2] group_name = sys.argv[3] destination = sys.argv[4] derivedDataPath",
"projectName, destination, derivedDataPath, timeout = 0): runcommand(\"rm raw.log\") runcommand(\"rm xcpretty.log\")",
"= \"\" for failed in faileds: testarguments += ' -only-testing:'",
"check if the failed tests can be retried if exit_code",
"main function ############################### # a command will like if (len(sys.argv)",
"retried if exit_code == 65: retriabletimes = 3 ; if",
"= testsuite.get('name') casename = testcase.get('name') if withBundle: failedtests.add(testbundle + '/'",
"projectName = testgroup['projectName'] if 'projectPath' in testgroup.keys(): projectPath = testgroup['projectPath']",
"times\") testarguments = \"\" for failed in faileds: testarguments +=",
"casename) else: failedtests.add(suitename + '/' + casename) return failedtests #run",
"== 65 : failedtests = getfailedcases(False) print(\"failedtests:\", failedtests) if 'ignoreFailures'",
"= test['retriabletimes'] if retriabletimes > 1: #get all failed test",
"-derivedDataPath {3}/{4}\".format(projectPath,schemeName, destination, derivedDataPath, projectName) testcommand +=\" \" + otherargments;",
"while retrytimes <= retriabletimes and exit_code > 0: print(\"retry \",",
"destination, derivedDataPath); print(\"retry exit code:\", exit_code) if(exit_code != 0 ):",
"retrytimes = 1 print('retriabletimes:', retriabletimes) while retrytimes <= retriabletimes and",
"testgroup['projectName'] if 'projectPath' in testgroup.keys(): projectPath = testgroup['projectPath'] if 'schemeName'",
"but the failed test cases is 0\") print(\"exit code:\", exit_code)",
"xcpretty.log\" runcommand(xcprettycommand) return exit_code ########################## main function ############################### # a",
"True): xmlfile='build/reports/junit.xml' tree = ET.parse(xmlfile) root = tree.getroot() testbundle =",
"iphonesimulator -destination '{2}' -derivedDataPath {3}/{4}\".format(projectPath,schemeName, destination, derivedDataPath, projectName) testcommand +=\"",
"= set() #TODO we can filter with condtion for testsuite",
"<test result location> <group name>\".format(sys.argv[0])) ; exit(1) jsonfilename=sys.argv[1] test_result_folder=sys.argv[2] group_name",
"0\") print(\"exit code:\", exit_code) break; print(\"failed tests:\",faileds) retrytimes = 1",
"= open('raw.log','w') exit_code = runcommand(testcommand,timeout, pipeout = rawoutput) rawoutput.close() print(\"Formatting",
"<filename>CircleciScripts/run_integrationtests.py import demjson import sys from subprocess import Popen, PIPE",
"projectName, projectPath, schemeName, destination) # testcommandhead = f\"xcodebuild test-without-building -project",
"as jsonfile: jsonstring = jsonfile.read() testConfigure = demjson.decode(jsonstring) runningConfigure =",
"$BASH_ENV') testresult = 0 for testname in testlist: print(\"-------------------------------\", testname",
"'ignoreFailures' in test and failedtests : ignoreFailures = set(test['ignoreFailures']) if",
"retriabletimes) while retrytimes <= retriabletimes and exit_code > 0: print(\"retry",
"= False ; if exit_code == 65 : failedtests =",
"0 for testname in testlist: print(\"-------------------------------\", testname , \"-------------------------------\"); test",
"if len(faileds) == 0 : print(\"test command return an error",
"-r junit | tee xcpretty.log\" runcommand('echo \"export testresult=0\" >> $BASH_ENV')",
"are faillures in the test\") testresult = 1 else: print(\"Test",
"= demjson.decode(jsonstring) runningConfigure = testConfigure['runningConfigure'] projectName = runningConfigure['projectName'] projectPath =",
"for testsuite in root.findall(\".//testsuite\"): for testcase in testsuite.findall('.//testcase[failure]'): suitename =",
"functions import runcommand #from sets import Set def getfailedcases(withBundle =",
"-skip-testing:' + testname+ \"/\" + skipingtest print(\"excludetests:\", skipingtests) exit_code =",
"suitename + '/' + casename) else: failedtests.add(suitename + '/' +",
"| xcpretty -r junit | tee xcpretty.log\" runcommand('echo \"export testresult=0\"",
"be ignored: \", failedtests - ignoreFailures ) if not ignorefailure:",
"file path> <test result location> <group name>\".format(sys.argv[0])) ; exit(1) jsonfilename=sys.argv[1]",
"xml.etree.ElementTree as ET import os from datetime import datetime from",
"\"xcodebuild test-without-building -project {0} -scheme {1} -sdk iphonesimulator -destination '{2}'",
"0 ): faileds = getfailedcases() if exit_code != 0 :",
"#run test def runtest(otherargments, projectPath, schemeName, projectName, destination, derivedDataPath, timeout",
"otherargments; rawoutput = open('raw.log','w') exit_code = runcommand(testcommand,timeout, pipeout = rawoutput)",
"xcprettycommand = \"cat raw.log | xcpretty -r junit | tee",
"that cannot be ignored: \", failedtests - ignoreFailures ) if",
"\"for \", retrytimes, \" times\") testarguments = \"\" for failed",
"\"-------------------------------\"); test = testlist[testname] testarguments = ' -only-testing:' + testname",
"subprocess import Popen, PIPE import subprocess import xml.etree.ElementTree as ET",
"runcommand('mv xcpretty.log {0}/{1}/xcpretty.log'.format(test_result_folder,testname)) runcommand('cp build/reports/junit.xml {0}/{1}/junit.xml'.format(test_result_folder,testname)) ignorefailure = False ;",
"1 exit_code = runtest(testarguments,projectPath, schemeName, projectName, destination, derivedDataPath); print(\"retry exit",
"# a command will like if (len(sys.argv) < 3 or",
"fails, check if the failed tests can be retried if",
"\"cat raw.log | xcpretty -r junit | tee xcpretty.log\" runcommand(xcprettycommand)",
"\"{2}\" >> {0}/{1}/exitcode.log'.format(test_result_folder,testname,exit_code)) runcommand('mv raw.log {0}/{1}/raw.log'.format(test_result_folder,testname)) runcommand('mv xcpretty.log {0}/{1}/xcpretty.log'.format(test_result_folder,testname)) runcommand('cp",
"else: print(\"Test succeed\") print(\"testresult:\", testresult) runcommand('echo \"export testresult={0}\" >> $BASH_ENV'.format(testresult))",
"for testname in testlist: print(\"-------------------------------\", testname , \"-------------------------------\"); test =",
"projectPath, schemeName, destination) # testcommandhead = f\"xcodebuild test-without-building -project {projectName}",
"testgroup.keys() : projectName = testgroup['projectName'] if 'projectPath' in testgroup.keys(): projectPath",
"code:\", exit_code) break; print(\"failed tests:\",faileds) retrytimes = 1 print('retriabletimes:', retriabletimes)",
"= tree.getroot() testbundle = root.get('name') testbundle = testbundle[0:len(testbundle) - 7]",
"if 'excludetests' in test: for skipingtest in test['excludetests']: skipingtests +=",
"casename = testcase.get('name') if withBundle: failedtests.add(testbundle + '/' + suitename",
"result .......\") xcprettycommand = \"cat raw.log | xcpretty -r junit",
"1 print('retriabletimes:', retriabletimes) while retrytimes <= retriabletimes and exit_code >",
"f\"xcodebuild test-without-building -project {projectName} -scheme {schemeName} -sdk {sdkName} -destination 'platform={paltformName},name={deviceName},OS={osVersion}'\"",
"retriabletimes = 3 ; if 'retriabletimes' in test: retriabletimes =",
"; if 'retriabletimes' in test: retriabletimes = test['retriabletimes'] if retriabletimes",
"os from datetime import datetime from functions import runcommand #from",
"if test fails, check if the failed tests can be",
"command will like if (len(sys.argv) < 3 or sys.argv[1] ==",
"testbundle = root.get('name') testbundle = testbundle[0:len(testbundle) - 7] failedtests =",
"= getfailedcases(False) print(\"failedtests:\", failedtests) if 'ignoreFailures' in test and failedtests",
".......\") xcprettycommand = \"cat raw.log | xcpretty -r junit |",
"sys.argv[3] destination = sys.argv[4] derivedDataPath = sys.argv[5] with open(jsonfilename, 'r')",
"sdkName = runningConfigure['sdkName'] print(\"group name:\", group_name) testgroup = testConfigure[group_name] testlist",
"exit_code = runtest(testarguments,projectPath, schemeName, projectName, destination, derivedDataPath); print(\"retry exit code:\",",
"destination) # testcommandhead = f\"xcodebuild test-without-building -project {projectName} -scheme {schemeName}",
"'/' + suitename + '/' + casename) else: failedtests.add(suitename +",
"failed testcases that can be ignored\") ignorefailure = True; else",
"def runtest(otherargments, projectPath, schemeName, projectName, destination, derivedDataPath, timeout = 0):",
"subprocess import xml.etree.ElementTree as ET import os from datetime import",
"\\r\\n {0} <integrationTestsConfiguration json file path> <test result location> <group",
"print(\"There are faillures in the test\") testresult = 1 else:",
"-p {0}/{1}'.format(test_result_folder,testname)) runcommand('echo \"{2}\" >> {0}/{1}/exitcode.log'.format(test_result_folder,testname,exit_code)) runcommand('mv raw.log {0}/{1}/raw.log'.format(test_result_folder,testname)) runcommand('mv"
] |