code
stringlengths
13
6.09M
order_type
stringclasses
2 values
original_example
dict
step_ids
listlengths
1
5
# CIS 117 Python Programming - Lab 10 # Bryce DesBrisay def middle(string): characters = list(string) length = len(characters) middleNum = round((length + .5) / 2) if length % 2 == 0: return characters[middleNum - 1] + characters[middleNum] else: return characters[middleNum - 1] def countVowels(string): count = 0 vowels = ['a','e','i','o','u','y'] for vowel in vowels: count += string.count(vowel) return count def reverse(string): return string[::-1] def isPalindrome(string): return reverse(string) == string def main(): count = 5 while count > 0: string = input('Enter a string: ') print('The middle character(s) is/are: ' + middle(string)) print('The string reversed is: ' + reverse(string)) print('The string contains ' + str(countVowels(string)) + ' vowels.') if isPalindrome(string): print('That is a palindrome.\n') else: print('That is not palindrome.\n') count -= 1 main() ''' Enter a string: racecar The middle character(s) is/are: e The string reversed is: racecar The string contains 3 vowels. That is a palindrome. Enter a string: apple The middle character(s) is/are: p The string reversed is: elppa The string contains 2 vowels. That is not palindrome. Enter a string: civic The middle character(s) is/are: v The string reversed is: civic The string contains 2 vowels. That is a palindrome. Enter a string: bottle The middle character(s) is/are: tt The string reversed is: elttob The string contains 2 vowels. That is not palindrome. Enter a string: noon The middle character(s) is/are: oo The string reversed is: noon The string contains 2 vowels. That is a palindrome. '''
normal
{ "blob_id": "d60690892eddda656c11470aacd1fdc9d07a721a", "index": 3563, "step-1": "<mask token>\n\n\ndef countVowels(string):\n count = 0\n vowels = ['a', 'e', 'i', 'o', 'u', 'y']\n for vowel in vowels:\n count += string.count(vowel)\n return count\n\n\n<mask token>\n\n\ndef isPalindrome(string):\n return reverse(string) == string\n\n\ndef main():\n count = 5\n while count > 0:\n string = input('Enter a string: ')\n print('The middle character(s) is/are: ' + middle(string))\n print('The string reversed is: ' + reverse(string))\n print('The string contains ' + str(countVowels(string)) + ' vowels.')\n if isPalindrome(string):\n print('That is a palindrome.\\n')\n else:\n print('That is not palindrome.\\n')\n count -= 1\n\n\n<mask token>\n", "step-2": "def middle(string):\n characters = list(string)\n length = len(characters)\n middleNum = round((length + 0.5) / 2)\n if length % 2 == 0:\n return characters[middleNum - 1] + characters[middleNum]\n else:\n return characters[middleNum - 1]\n\n\ndef countVowels(string):\n count = 0\n vowels = ['a', 'e', 'i', 'o', 'u', 'y']\n for vowel in vowels:\n count += string.count(vowel)\n return count\n\n\n<mask token>\n\n\ndef isPalindrome(string):\n return reverse(string) == string\n\n\ndef main():\n count = 5\n while count > 0:\n string = input('Enter a string: ')\n print('The middle character(s) is/are: ' + middle(string))\n print('The string reversed is: ' + reverse(string))\n print('The string contains ' + str(countVowels(string)) + ' vowels.')\n if isPalindrome(string):\n print('That is a palindrome.\\n')\n else:\n print('That is not palindrome.\\n')\n count -= 1\n\n\n<mask token>\n", "step-3": "def middle(string):\n characters = list(string)\n length = len(characters)\n middleNum = round((length + 0.5) / 2)\n if length % 2 == 0:\n return characters[middleNum - 1] + characters[middleNum]\n else:\n return characters[middleNum - 1]\n\n\ndef countVowels(string):\n count = 0\n vowels = ['a', 'e', 'i', 'o', 'u', 'y']\n for vowel in vowels:\n count += string.count(vowel)\n return count\n\n\ndef reverse(string):\n return string[::-1]\n\n\ndef isPalindrome(string):\n return reverse(string) == string\n\n\ndef main():\n count = 5\n while count > 0:\n string = input('Enter a string: ')\n print('The middle character(s) is/are: ' + middle(string))\n print('The string reversed is: ' + reverse(string))\n print('The string contains ' + str(countVowels(string)) + ' vowels.')\n if isPalindrome(string):\n print('That is a palindrome.\\n')\n else:\n print('That is not palindrome.\\n')\n count -= 1\n\n\n<mask token>\n", "step-4": "def middle(string):\n characters = list(string)\n length = len(characters)\n middleNum = round((length + 0.5) / 2)\n if length % 2 == 0:\n return characters[middleNum - 1] + characters[middleNum]\n else:\n return characters[middleNum - 1]\n\n\ndef countVowels(string):\n count = 0\n vowels = ['a', 'e', 'i', 'o', 'u', 'y']\n for vowel in vowels:\n count += string.count(vowel)\n return count\n\n\ndef reverse(string):\n return string[::-1]\n\n\ndef isPalindrome(string):\n return reverse(string) == string\n\n\ndef main():\n count = 5\n while count > 0:\n string = input('Enter a string: ')\n print('The middle character(s) is/are: ' + middle(string))\n print('The string reversed is: ' + reverse(string))\n print('The string contains ' + str(countVowels(string)) + ' vowels.')\n if isPalindrome(string):\n print('That is a palindrome.\\n')\n else:\n print('That is not palindrome.\\n')\n count -= 1\n\n\nmain()\n<mask token>\n", "step-5": "# CIS 117 Python Programming - Lab 10\n# Bryce DesBrisay\n\ndef middle(string):\n characters = list(string)\n length = len(characters)\n middleNum = round((length + .5) / 2)\n if length % 2 == 0:\n return characters[middleNum - 1] + characters[middleNum]\n else:\n return characters[middleNum - 1]\n\ndef countVowels(string):\n count = 0\n vowels = ['a','e','i','o','u','y']\n for vowel in vowels:\n count += string.count(vowel)\n return count\n\ndef reverse(string):\n return string[::-1]\n\ndef isPalindrome(string):\n return reverse(string) == string\n\ndef main():\n count = 5\n while count > 0:\n string = input('Enter a string: ')\n print('The middle character(s) is/are: ' + middle(string))\n print('The string reversed is: ' + reverse(string))\n print('The string contains ' + str(countVowels(string)) + ' vowels.')\n if isPalindrome(string):\n print('That is a palindrome.\\n')\n else:\n print('That is not palindrome.\\n')\n count -= 1\n\nmain()\n\n'''\nEnter a string: racecar\nThe middle character(s) is/are: e\nThe string reversed is: racecar\nThe string contains 3 vowels.\nThat is a palindrome.\n\nEnter a string: apple\nThe middle character(s) is/are: p\nThe string reversed is: elppa\nThe string contains 2 vowels.\nThat is not palindrome.\n\nEnter a string: civic\nThe middle character(s) is/are: v\nThe string reversed is: civic\nThe string contains 2 vowels.\nThat is a palindrome.\n\nEnter a string: bottle\nThe middle character(s) is/are: tt\nThe string reversed is: elttob\nThe string contains 2 vowels.\nThat is not palindrome.\n\nEnter a string: noon\nThe middle character(s) is/are: oo\nThe string reversed is: noon\nThe string contains 2 vowels.\nThat is a palindrome.\n'''\n\n", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> PyInstaller.__main__.run(['--clean', '--onefile', '--workpath', workPath, '--distpath', outPath, '--hidden-import', 'win32timezone', os.path.join (srcPath, 'service.py'), os.path.join(srcPath, 'bridge.py')]) shutil.copy2(os.path.join(srcPath, 'bridge.cfg'), outPath) shutil.copy2(os.path.join(srcPath, 'groups.cfg'), outPath) shutil.rmtree(workPath) <|reserved_special_token_1|> <|reserved_special_token_0|> basePath = os.path.realpath(os.path.join(os.path.dirname(__file__), os.path .pardir)) srcPath = os.path.join(basePath, 'src') outPath = os.path.join(basePath, 'out') workPath = os.path.join(outPath, 'work') PyInstaller.__main__.run(['--clean', '--onefile', '--workpath', workPath, '--distpath', outPath, '--hidden-import', 'win32timezone', os.path.join (srcPath, 'service.py'), os.path.join(srcPath, 'bridge.py')]) shutil.copy2(os.path.join(srcPath, 'bridge.cfg'), outPath) shutil.copy2(os.path.join(srcPath, 'groups.cfg'), outPath) shutil.rmtree(workPath) <|reserved_special_token_1|> import PyInstaller.__main__ import os import shutil basePath = os.path.realpath(os.path.join(os.path.dirname(__file__), os.path .pardir)) srcPath = os.path.join(basePath, 'src') outPath = os.path.join(basePath, 'out') workPath = os.path.join(outPath, 'work') PyInstaller.__main__.run(['--clean', '--onefile', '--workpath', workPath, '--distpath', outPath, '--hidden-import', 'win32timezone', os.path.join (srcPath, 'service.py'), os.path.join(srcPath, 'bridge.py')]) shutil.copy2(os.path.join(srcPath, 'bridge.cfg'), outPath) shutil.copy2(os.path.join(srcPath, 'groups.cfg'), outPath) shutil.rmtree(workPath) <|reserved_special_token_1|> import PyInstaller.__main__ import os import shutil # Paths basePath = os.path.realpath(os.path.join(os.path.dirname(__file__), os.path.pardir)) srcPath = os.path.join(basePath, 'src') outPath = os.path.join(basePath, 'out') workPath = os.path.join(outPath, 'work') # Bundle PyInstaller.__main__.run([ '--clean', '--onefile', '--workpath', workPath, '--distpath', outPath, '--hidden-import', 'win32timezone', os.path.join(srcPath, 'service.py'), os.path.join(srcPath, 'bridge.py'), ]) # Copy config files shutil.copy2(os.path.join(srcPath, 'bridge.cfg'), outPath) shutil.copy2(os.path.join(srcPath, 'groups.cfg'), outPath) # Remove build artifacts shutil.rmtree(workPath)
flexible
{ "blob_id": "16a95573c4fccc10bdc5e37b307d0c85714b328c", "index": 3548, "step-1": "<mask token>\n", "step-2": "<mask token>\nPyInstaller.__main__.run(['--clean', '--onefile', '--workpath', workPath,\n '--distpath', outPath, '--hidden-import', 'win32timezone', os.path.join\n (srcPath, 'service.py'), os.path.join(srcPath, 'bridge.py')])\nshutil.copy2(os.path.join(srcPath, 'bridge.cfg'), outPath)\nshutil.copy2(os.path.join(srcPath, 'groups.cfg'), outPath)\nshutil.rmtree(workPath)\n", "step-3": "<mask token>\nbasePath = os.path.realpath(os.path.join(os.path.dirname(__file__), os.path\n .pardir))\nsrcPath = os.path.join(basePath, 'src')\noutPath = os.path.join(basePath, 'out')\nworkPath = os.path.join(outPath, 'work')\nPyInstaller.__main__.run(['--clean', '--onefile', '--workpath', workPath,\n '--distpath', outPath, '--hidden-import', 'win32timezone', os.path.join\n (srcPath, 'service.py'), os.path.join(srcPath, 'bridge.py')])\nshutil.copy2(os.path.join(srcPath, 'bridge.cfg'), outPath)\nshutil.copy2(os.path.join(srcPath, 'groups.cfg'), outPath)\nshutil.rmtree(workPath)\n", "step-4": "import PyInstaller.__main__\nimport os\nimport shutil\nbasePath = os.path.realpath(os.path.join(os.path.dirname(__file__), os.path\n .pardir))\nsrcPath = os.path.join(basePath, 'src')\noutPath = os.path.join(basePath, 'out')\nworkPath = os.path.join(outPath, 'work')\nPyInstaller.__main__.run(['--clean', '--onefile', '--workpath', workPath,\n '--distpath', outPath, '--hidden-import', 'win32timezone', os.path.join\n (srcPath, 'service.py'), os.path.join(srcPath, 'bridge.py')])\nshutil.copy2(os.path.join(srcPath, 'bridge.cfg'), outPath)\nshutil.copy2(os.path.join(srcPath, 'groups.cfg'), outPath)\nshutil.rmtree(workPath)\n", "step-5": "import PyInstaller.__main__\nimport os\nimport shutil\n\n# Paths\nbasePath = os.path.realpath(os.path.join(os.path.dirname(__file__), os.path.pardir))\nsrcPath = os.path.join(basePath, 'src')\noutPath = os.path.join(basePath, 'out')\nworkPath = os.path.join(outPath, 'work')\n\n# Bundle\nPyInstaller.__main__.run([\n '--clean',\n '--onefile',\n '--workpath', workPath,\n '--distpath', outPath,\n '--hidden-import', 'win32timezone',\n os.path.join(srcPath, 'service.py'),\n os.path.join(srcPath, 'bridge.py'),\n])\n\n# Copy config files\nshutil.copy2(os.path.join(srcPath, 'bridge.cfg'), outPath)\nshutil.copy2(os.path.join(srcPath, 'groups.cfg'), outPath)\n\n# Remove build artifacts\nshutil.rmtree(workPath)", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
n, k = raw_input().split() n = int(n) k = int(k) div = 0 for i in range(n): new = int(raw_input()) if (new % k) == 0: div += 1 print div
normal
{ "blob_id": "68e1e39f193537367d899c5fd01c1361ed93ef29", "index": 7668, "step-1": "n, k = raw_input().split()\nn = int(n)\nk = int(k)\n\ndiv = 0\n\nfor i in range(n):\n new = int(raw_input())\n if (new % k) == 0:\n div += 1\n\nprint div", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
<|reserved_special_token_0|> class EMPTY: <|reserved_special_token_0|> pass class Config: """ Configuration management entity. Args: name (str): Name of config environment. fallback (bool): Indicate if configuration should fallback to base. """ no_config_err = 'No such config variable {}' def __init__(self, name, fallback): from importlib import import_module from os import listdir from os.path import dirname self.config_path = dirname(__file__) self.name = name self.fallback = fallback self.config_modules = set([i.strip('.py') for i in listdir(self. config_path) if '.py' in i and i != '__init__.py']) if name not in self.config_modules: err = 'Config environment {} does not exist'.format(name) raise AttributeError(err) if self.fallback: self.base = import_module('illume.config.base') self.module = import_module('illume.config.{}'.format(self.name)) def get(self, name, default): """Get config value""" value = getattr(self.module, name, default) if value != EMPTY: return value elif value == EMPTY and not self.fallback: raise AttributeError(self.no_config_err.format(name)) elif value == EMPTY and self.fallback: value = getattr(self.base, name, default) if value == EMPTY: raise AttributeError(self.no_config_err.format(name)) return value <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class EMPTY: """ Signifies that a default value was not set. Should trigger an error if default is set to EMPTY and an attribute does not exist. """ pass class Config: """ Configuration management entity. Args: name (str): Name of config environment. fallback (bool): Indicate if configuration should fallback to base. """ no_config_err = 'No such config variable {}' def __init__(self, name, fallback): from importlib import import_module from os import listdir from os.path import dirname self.config_path = dirname(__file__) self.name = name self.fallback = fallback self.config_modules = set([i.strip('.py') for i in listdir(self. config_path) if '.py' in i and i != '__init__.py']) if name not in self.config_modules: err = 'Config environment {} does not exist'.format(name) raise AttributeError(err) if self.fallback: self.base = import_module('illume.config.base') self.module = import_module('illume.config.{}'.format(self.name)) def get(self, name, default): """Get config value""" value = getattr(self.module, name, default) if value != EMPTY: return value elif value == EMPTY and not self.fallback: raise AttributeError(self.no_config_err.format(name)) elif value == EMPTY and self.fallback: value = getattr(self.base, name, default) if value == EMPTY: raise AttributeError(self.no_config_err.format(name)) return value <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class EMPTY: """ Signifies that a default value was not set. Should trigger an error if default is set to EMPTY and an attribute does not exist. """ pass class Config: """ Configuration management entity. Args: name (str): Name of config environment. fallback (bool): Indicate if configuration should fallback to base. """ no_config_err = 'No such config variable {}' def __init__(self, name, fallback): from importlib import import_module from os import listdir from os.path import dirname self.config_path = dirname(__file__) self.name = name self.fallback = fallback self.config_modules = set([i.strip('.py') for i in listdir(self. config_path) if '.py' in i and i != '__init__.py']) if name not in self.config_modules: err = 'Config environment {} does not exist'.format(name) raise AttributeError(err) if self.fallback: self.base = import_module('illume.config.base') self.module = import_module('illume.config.{}'.format(self.name)) def get(self, name, default): """Get config value""" value = getattr(self.module, name, default) if value != EMPTY: return value elif value == EMPTY and not self.fallback: raise AttributeError(self.no_config_err.format(name)) elif value == EMPTY and self.fallback: value = getattr(self.base, name, default) if value == EMPTY: raise AttributeError(self.no_config_err.format(name)) return value <|reserved_special_token_0|> def get(name, default=EMPTY): """Get configuration variable.""" config_class = ENV.get(CONFIG_KEY, None) if config_class is None: raise AttributeError('Config environment not set.') return config_class.get(name, default) <|reserved_special_token_1|> <|reserved_special_token_0|> class EMPTY: """ Signifies that a default value was not set. Should trigger an error if default is set to EMPTY and an attribute does not exist. """ pass class Config: """ Configuration management entity. Args: name (str): Name of config environment. fallback (bool): Indicate if configuration should fallback to base. """ no_config_err = 'No such config variable {}' def __init__(self, name, fallback): from importlib import import_module from os import listdir from os.path import dirname self.config_path = dirname(__file__) self.name = name self.fallback = fallback self.config_modules = set([i.strip('.py') for i in listdir(self. config_path) if '.py' in i and i != '__init__.py']) if name not in self.config_modules: err = 'Config environment {} does not exist'.format(name) raise AttributeError(err) if self.fallback: self.base = import_module('illume.config.base') self.module = import_module('illume.config.{}'.format(self.name)) def get(self, name, default): """Get config value""" value = getattr(self.module, name, default) if value != EMPTY: return value elif value == EMPTY and not self.fallback: raise AttributeError(self.no_config_err.format(name)) elif value == EMPTY and self.fallback: value = getattr(self.base, name, default) if value == EMPTY: raise AttributeError(self.no_config_err.format(name)) return value def setenv(name, fallback=True): """Set configuration environment.""" if CONFIG_KEY in ENV: raise AttributeError('Config environment already set.') config_class = Config(name, fallback) ENV[CONFIG_KEY] = config_class def get(name, default=EMPTY): """Get configuration variable.""" config_class = ENV.get(CONFIG_KEY, None) if config_class is None: raise AttributeError('Config environment not set.') return config_class.get(name, default) <|reserved_special_token_1|> """ Configuration management. Environment must be set before use. Call .get() to obtain configuration variable. If the variable does not exist in the set environment, then """ CONFIG_KEY = "config_class" ENV = {} class EMPTY: """ Signifies that a default value was not set. Should trigger an error if default is set to EMPTY and an attribute does not exist. """ pass class Config: """ Configuration management entity. Args: name (str): Name of config environment. fallback (bool): Indicate if configuration should fallback to base. """ no_config_err = "No such config variable {}" def __init__(self, name, fallback): from importlib import import_module from os import listdir from os.path import dirname self.config_path = dirname(__file__) self.name = name self.fallback = fallback # List of config modules available self.config_modules = set([ i.strip(".py") for i in listdir(self.config_path) if ".py" in i and i != "__init__.py" ]) if name not in self.config_modules: err = "Config environment {} does not exist".format(name) raise AttributeError(err) if self.fallback: # Fallback configuration module. self.base = import_module("illume.config.base") # Desired configuration module. self.module = import_module("illume.config.{}".format(self.name)) def get(self, name, default): """Get config value""" value = getattr(self.module, name, default) if value != EMPTY: return value elif value == EMPTY and not self.fallback: raise AttributeError(self.no_config_err.format(name)) elif value == EMPTY and self.fallback: value = getattr(self.base, name, default) if value == EMPTY: raise AttributeError(self.no_config_err.format(name)) return value def setenv(name, fallback=True): """Set configuration environment.""" if CONFIG_KEY in ENV: raise AttributeError("Config environment already set.") config_class = Config(name, fallback) ENV[CONFIG_KEY] = config_class def get(name, default=EMPTY): """Get configuration variable.""" config_class = ENV.get(CONFIG_KEY, None) if config_class is None: raise AttributeError("Config environment not set.") return config_class.get(name, default)
flexible
{ "blob_id": "263d2fe43cf8747f20fd51897ba003c9c4cb4280", "index": 9907, "step-1": "<mask token>\n\n\nclass EMPTY:\n <mask token>\n pass\n\n\nclass Config:\n \"\"\"\n Configuration management entity.\n\n Args:\n name (str): Name of config environment.\n fallback (bool): Indicate if configuration should fallback to base.\n \"\"\"\n no_config_err = 'No such config variable {}'\n\n def __init__(self, name, fallback):\n from importlib import import_module\n from os import listdir\n from os.path import dirname\n self.config_path = dirname(__file__)\n self.name = name\n self.fallback = fallback\n self.config_modules = set([i.strip('.py') for i in listdir(self.\n config_path) if '.py' in i and i != '__init__.py'])\n if name not in self.config_modules:\n err = 'Config environment {} does not exist'.format(name)\n raise AttributeError(err)\n if self.fallback:\n self.base = import_module('illume.config.base')\n self.module = import_module('illume.config.{}'.format(self.name))\n\n def get(self, name, default):\n \"\"\"Get config value\"\"\"\n value = getattr(self.module, name, default)\n if value != EMPTY:\n return value\n elif value == EMPTY and not self.fallback:\n raise AttributeError(self.no_config_err.format(name))\n elif value == EMPTY and self.fallback:\n value = getattr(self.base, name, default)\n if value == EMPTY:\n raise AttributeError(self.no_config_err.format(name))\n return value\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass EMPTY:\n \"\"\"\n Signifies that a default value was not set. Should trigger an error if\n default is set to EMPTY and an attribute does not exist.\n \"\"\"\n pass\n\n\nclass Config:\n \"\"\"\n Configuration management entity.\n\n Args:\n name (str): Name of config environment.\n fallback (bool): Indicate if configuration should fallback to base.\n \"\"\"\n no_config_err = 'No such config variable {}'\n\n def __init__(self, name, fallback):\n from importlib import import_module\n from os import listdir\n from os.path import dirname\n self.config_path = dirname(__file__)\n self.name = name\n self.fallback = fallback\n self.config_modules = set([i.strip('.py') for i in listdir(self.\n config_path) if '.py' in i and i != '__init__.py'])\n if name not in self.config_modules:\n err = 'Config environment {} does not exist'.format(name)\n raise AttributeError(err)\n if self.fallback:\n self.base = import_module('illume.config.base')\n self.module = import_module('illume.config.{}'.format(self.name))\n\n def get(self, name, default):\n \"\"\"Get config value\"\"\"\n value = getattr(self.module, name, default)\n if value != EMPTY:\n return value\n elif value == EMPTY and not self.fallback:\n raise AttributeError(self.no_config_err.format(name))\n elif value == EMPTY and self.fallback:\n value = getattr(self.base, name, default)\n if value == EMPTY:\n raise AttributeError(self.no_config_err.format(name))\n return value\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass EMPTY:\n \"\"\"\n Signifies that a default value was not set. Should trigger an error if\n default is set to EMPTY and an attribute does not exist.\n \"\"\"\n pass\n\n\nclass Config:\n \"\"\"\n Configuration management entity.\n\n Args:\n name (str): Name of config environment.\n fallback (bool): Indicate if configuration should fallback to base.\n \"\"\"\n no_config_err = 'No such config variable {}'\n\n def __init__(self, name, fallback):\n from importlib import import_module\n from os import listdir\n from os.path import dirname\n self.config_path = dirname(__file__)\n self.name = name\n self.fallback = fallback\n self.config_modules = set([i.strip('.py') for i in listdir(self.\n config_path) if '.py' in i and i != '__init__.py'])\n if name not in self.config_modules:\n err = 'Config environment {} does not exist'.format(name)\n raise AttributeError(err)\n if self.fallback:\n self.base = import_module('illume.config.base')\n self.module = import_module('illume.config.{}'.format(self.name))\n\n def get(self, name, default):\n \"\"\"Get config value\"\"\"\n value = getattr(self.module, name, default)\n if value != EMPTY:\n return value\n elif value == EMPTY and not self.fallback:\n raise AttributeError(self.no_config_err.format(name))\n elif value == EMPTY and self.fallback:\n value = getattr(self.base, name, default)\n if value == EMPTY:\n raise AttributeError(self.no_config_err.format(name))\n return value\n\n\n<mask token>\n\n\ndef get(name, default=EMPTY):\n \"\"\"Get configuration variable.\"\"\"\n config_class = ENV.get(CONFIG_KEY, None)\n if config_class is None:\n raise AttributeError('Config environment not set.')\n return config_class.get(name, default)\n", "step-4": "<mask token>\n\n\nclass EMPTY:\n \"\"\"\n Signifies that a default value was not set. Should trigger an error if\n default is set to EMPTY and an attribute does not exist.\n \"\"\"\n pass\n\n\nclass Config:\n \"\"\"\n Configuration management entity.\n\n Args:\n name (str): Name of config environment.\n fallback (bool): Indicate if configuration should fallback to base.\n \"\"\"\n no_config_err = 'No such config variable {}'\n\n def __init__(self, name, fallback):\n from importlib import import_module\n from os import listdir\n from os.path import dirname\n self.config_path = dirname(__file__)\n self.name = name\n self.fallback = fallback\n self.config_modules = set([i.strip('.py') for i in listdir(self.\n config_path) if '.py' in i and i != '__init__.py'])\n if name not in self.config_modules:\n err = 'Config environment {} does not exist'.format(name)\n raise AttributeError(err)\n if self.fallback:\n self.base = import_module('illume.config.base')\n self.module = import_module('illume.config.{}'.format(self.name))\n\n def get(self, name, default):\n \"\"\"Get config value\"\"\"\n value = getattr(self.module, name, default)\n if value != EMPTY:\n return value\n elif value == EMPTY and not self.fallback:\n raise AttributeError(self.no_config_err.format(name))\n elif value == EMPTY and self.fallback:\n value = getattr(self.base, name, default)\n if value == EMPTY:\n raise AttributeError(self.no_config_err.format(name))\n return value\n\n\ndef setenv(name, fallback=True):\n \"\"\"Set configuration environment.\"\"\"\n if CONFIG_KEY in ENV:\n raise AttributeError('Config environment already set.')\n config_class = Config(name, fallback)\n ENV[CONFIG_KEY] = config_class\n\n\ndef get(name, default=EMPTY):\n \"\"\"Get configuration variable.\"\"\"\n config_class = ENV.get(CONFIG_KEY, None)\n if config_class is None:\n raise AttributeError('Config environment not set.')\n return config_class.get(name, default)\n", "step-5": "\"\"\"\nConfiguration management.\n\nEnvironment must be set before use.\n\nCall .get() to obtain configuration variable. If the variable does not exist\nin the set environment, then\n\"\"\"\n\n\nCONFIG_KEY = \"config_class\"\nENV = {}\n\n\nclass EMPTY:\n\n \"\"\"\n Signifies that a default value was not set. Should trigger an error if\n default is set to EMPTY and an attribute does not exist.\n \"\"\"\n\n pass\n\n\nclass Config:\n\n \"\"\"\n Configuration management entity.\n\n Args:\n name (str): Name of config environment.\n fallback (bool): Indicate if configuration should fallback to base.\n \"\"\"\n\n no_config_err = \"No such config variable {}\"\n\n def __init__(self, name, fallback):\n from importlib import import_module\n from os import listdir\n from os.path import dirname\n\n self.config_path = dirname(__file__)\n self.name = name\n self.fallback = fallback\n\n # List of config modules available\n self.config_modules = set([\n i.strip(\".py\")\n for i in listdir(self.config_path)\n if \".py\" in i and i != \"__init__.py\"\n ])\n\n if name not in self.config_modules:\n err = \"Config environment {} does not exist\".format(name)\n\n raise AttributeError(err)\n\n if self.fallback:\n # Fallback configuration module.\n self.base = import_module(\"illume.config.base\")\n\n # Desired configuration module.\n self.module = import_module(\"illume.config.{}\".format(self.name))\n\n def get(self, name, default):\n \"\"\"Get config value\"\"\"\n value = getattr(self.module, name, default)\n\n if value != EMPTY:\n return value\n elif value == EMPTY and not self.fallback:\n raise AttributeError(self.no_config_err.format(name))\n elif value == EMPTY and self.fallback:\n value = getattr(self.base, name, default)\n\n if value == EMPTY:\n raise AttributeError(self.no_config_err.format(name))\n\n return value\n\n\ndef setenv(name, fallback=True):\n \"\"\"Set configuration environment.\"\"\"\n if CONFIG_KEY in ENV:\n raise AttributeError(\"Config environment already set.\")\n\n config_class = Config(name, fallback)\n\n ENV[CONFIG_KEY] = config_class\n\n\ndef get(name, default=EMPTY):\n \"\"\"Get configuration variable.\"\"\"\n config_class = ENV.get(CONFIG_KEY, None)\n\n if config_class is None:\n raise AttributeError(\"Config environment not set.\")\n\n return config_class.get(name, default)\n", "step-ids": [ 6, 7, 8, 9, 11 ] }
[ 6, 7, 8, 9, 11 ]
import time import jax.numpy as jnp def tick(): return time.perf_counter() def tock(t0, dat=None): if dat is not None: try: _ = dat.block_until_ready() except AttributeError: _ = jnp.array(dat).block_until_ready() return time.perf_counter() - t0
normal
{ "blob_id": "e58dbb4f67c93abf3564dc0f38df8852313338f0", "index": 5520, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef tock(t0, dat=None):\n if dat is not None:\n try:\n _ = dat.block_until_ready()\n except AttributeError:\n _ = jnp.array(dat).block_until_ready()\n return time.perf_counter() - t0\n", "step-3": "<mask token>\n\n\ndef tick():\n return time.perf_counter()\n\n\ndef tock(t0, dat=None):\n if dat is not None:\n try:\n _ = dat.block_until_ready()\n except AttributeError:\n _ = jnp.array(dat).block_until_ready()\n return time.perf_counter() - t0\n", "step-4": "import time\nimport jax.numpy as jnp\n\n\ndef tick():\n return time.perf_counter()\n\n\ndef tock(t0, dat=None):\n if dat is not None:\n try:\n _ = dat.block_until_ready()\n except AttributeError:\n _ = jnp.array(dat).block_until_ready()\n return time.perf_counter() - t0\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
#!flask/bin/python import os, json import requests SENDGRID_API_KEY = os.environ.get('SENDGRID_API_KEY', default=None) FROM_EMAIL = os.environ.get('FROM_EMAIL', default=None) TO_EMAIL = os.environ.get('TO_EMAIL', default=None) if not SENDGRID_API_KEY: raise ValueError("Need to set Sendgrid API Key (SENDGRID_API_KEY)") if not FROM_EMAIL or not TO_EMAIL: raise ValueError("Need to set email info (FROM_EMAIL and TO_EMAIL") sendgrid_url = 'https://api.sendgrid.com/v3/mail/send' def build_request_body(email): from_email = email['email'] name = email['name'] subject = email['subject'] body = email['body'] if not from_email: from_email = FROM_EMAIL if not name: name = "Anonymous" if not subject: subject = "Portfolio contact form message" req_body = json.dumps({ "personalizations": [ { "to": [ { "email": TO_EMAIL } ], "subject": subject } ], "from": { "email": from_email, "name": name }, "content": [ { "type": "text/plain", "value": body } ] }) return req_body def send_mail(email): headers = { "Authorization": f"Bearer {SENDGRID_API_KEY}", "Content-Type": "application/json" } email_body = build_request_body(email) response = requests.post(sendgrid_url, headers=headers, data=email_body) print(response.text) return response
normal
{ "blob_id": "cb29ee8687b469923896ceb7d5a6cd7f54b2c34e", "index": 6207, "step-1": "<mask token>\n\n\ndef build_request_body(email):\n from_email = email['email']\n name = email['name']\n subject = email['subject']\n body = email['body']\n if not from_email:\n from_email = FROM_EMAIL\n if not name:\n name = 'Anonymous'\n if not subject:\n subject = 'Portfolio contact form message'\n req_body = json.dumps({'personalizations': [{'to': [{'email': TO_EMAIL}\n ], 'subject': subject}], 'from': {'email': from_email, 'name': name\n }, 'content': [{'type': 'text/plain', 'value': body}]})\n return req_body\n\n\ndef send_mail(email):\n headers = {'Authorization': f'Bearer {SENDGRID_API_KEY}',\n 'Content-Type': 'application/json'}\n email_body = build_request_body(email)\n response = requests.post(sendgrid_url, headers=headers, data=email_body)\n print(response.text)\n return response\n", "step-2": "<mask token>\nif not SENDGRID_API_KEY:\n raise ValueError('Need to set Sendgrid API Key (SENDGRID_API_KEY)')\nif not FROM_EMAIL or not TO_EMAIL:\n raise ValueError('Need to set email info (FROM_EMAIL and TO_EMAIL')\n<mask token>\n\n\ndef build_request_body(email):\n from_email = email['email']\n name = email['name']\n subject = email['subject']\n body = email['body']\n if not from_email:\n from_email = FROM_EMAIL\n if not name:\n name = 'Anonymous'\n if not subject:\n subject = 'Portfolio contact form message'\n req_body = json.dumps({'personalizations': [{'to': [{'email': TO_EMAIL}\n ], 'subject': subject}], 'from': {'email': from_email, 'name': name\n }, 'content': [{'type': 'text/plain', 'value': body}]})\n return req_body\n\n\ndef send_mail(email):\n headers = {'Authorization': f'Bearer {SENDGRID_API_KEY}',\n 'Content-Type': 'application/json'}\n email_body = build_request_body(email)\n response = requests.post(sendgrid_url, headers=headers, data=email_body)\n print(response.text)\n return response\n", "step-3": "<mask token>\nSENDGRID_API_KEY = os.environ.get('SENDGRID_API_KEY', default=None)\nFROM_EMAIL = os.environ.get('FROM_EMAIL', default=None)\nTO_EMAIL = os.environ.get('TO_EMAIL', default=None)\nif not SENDGRID_API_KEY:\n raise ValueError('Need to set Sendgrid API Key (SENDGRID_API_KEY)')\nif not FROM_EMAIL or not TO_EMAIL:\n raise ValueError('Need to set email info (FROM_EMAIL and TO_EMAIL')\nsendgrid_url = 'https://api.sendgrid.com/v3/mail/send'\n\n\ndef build_request_body(email):\n from_email = email['email']\n name = email['name']\n subject = email['subject']\n body = email['body']\n if not from_email:\n from_email = FROM_EMAIL\n if not name:\n name = 'Anonymous'\n if not subject:\n subject = 'Portfolio contact form message'\n req_body = json.dumps({'personalizations': [{'to': [{'email': TO_EMAIL}\n ], 'subject': subject}], 'from': {'email': from_email, 'name': name\n }, 'content': [{'type': 'text/plain', 'value': body}]})\n return req_body\n\n\ndef send_mail(email):\n headers = {'Authorization': f'Bearer {SENDGRID_API_KEY}',\n 'Content-Type': 'application/json'}\n email_body = build_request_body(email)\n response = requests.post(sendgrid_url, headers=headers, data=email_body)\n print(response.text)\n return response\n", "step-4": "import os, json\nimport requests\nSENDGRID_API_KEY = os.environ.get('SENDGRID_API_KEY', default=None)\nFROM_EMAIL = os.environ.get('FROM_EMAIL', default=None)\nTO_EMAIL = os.environ.get('TO_EMAIL', default=None)\nif not SENDGRID_API_KEY:\n raise ValueError('Need to set Sendgrid API Key (SENDGRID_API_KEY)')\nif not FROM_EMAIL or not TO_EMAIL:\n raise ValueError('Need to set email info (FROM_EMAIL and TO_EMAIL')\nsendgrid_url = 'https://api.sendgrid.com/v3/mail/send'\n\n\ndef build_request_body(email):\n from_email = email['email']\n name = email['name']\n subject = email['subject']\n body = email['body']\n if not from_email:\n from_email = FROM_EMAIL\n if not name:\n name = 'Anonymous'\n if not subject:\n subject = 'Portfolio contact form message'\n req_body = json.dumps({'personalizations': [{'to': [{'email': TO_EMAIL}\n ], 'subject': subject}], 'from': {'email': from_email, 'name': name\n }, 'content': [{'type': 'text/plain', 'value': body}]})\n return req_body\n\n\ndef send_mail(email):\n headers = {'Authorization': f'Bearer {SENDGRID_API_KEY}',\n 'Content-Type': 'application/json'}\n email_body = build_request_body(email)\n response = requests.post(sendgrid_url, headers=headers, data=email_body)\n print(response.text)\n return response\n", "step-5": "#!flask/bin/python\nimport os, json\nimport requests\n\nSENDGRID_API_KEY = os.environ.get('SENDGRID_API_KEY', default=None)\nFROM_EMAIL = os.environ.get('FROM_EMAIL', default=None)\nTO_EMAIL = os.environ.get('TO_EMAIL', default=None)\n\nif not SENDGRID_API_KEY:\n raise ValueError(\"Need to set Sendgrid API Key (SENDGRID_API_KEY)\")\n\nif not FROM_EMAIL or not TO_EMAIL:\n raise ValueError(\"Need to set email info (FROM_EMAIL and TO_EMAIL\")\n\nsendgrid_url = 'https://api.sendgrid.com/v3/mail/send'\n\ndef build_request_body(email):\n from_email = email['email']\n name = email['name']\n subject = email['subject']\n body = email['body']\n if not from_email:\n from_email = FROM_EMAIL\n if not name:\n name = \"Anonymous\"\n if not subject:\n subject = \"Portfolio contact form message\"\n req_body = json.dumps({\n \"personalizations\": [\n {\n \"to\": [\n {\n \"email\": TO_EMAIL\n }\n ],\n \"subject\": subject\n }\n ],\n \"from\": {\n \"email\": from_email,\n \"name\": name\n },\n \"content\": [\n {\n \"type\": \"text/plain\",\n \"value\": body\n }\n ]\n })\n return req_body\n\ndef send_mail(email):\n headers = {\n \"Authorization\": f\"Bearer {SENDGRID_API_KEY}\",\n \"Content-Type\": \"application/json\"\n }\n email_body = build_request_body(email)\n response = requests.post(sendgrid_url, headers=headers, data=email_body)\n print(response.text)\n return response\n", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
<|reserved_special_token_0|> class LocalizationTests(unittest.TestCase): def test_default(self): logging.info('*** default ***') localization = Localization() text = 'hello world' self.assertEqual(localization._(text), text) <|reserved_special_token_0|> def test_global(self): logging.info('*** global ***') settings = {'localized': {'hello world': "What'up, Doc?", 'another string': 'Bye!'}, 'space': {'title': 'space name', 'participants': ['[email protected]']}, 'server': {'url': 'http://to.no.where', 'hook': '/hook', 'binding': '0.0.0.0', 'port': 8080}} context = Context(settings) l10n.set_context(context) self.assertEqual(l10n.actual_strings, {}) self.assertEqual(_('hello world'), "What'up, Doc?") self.assertEqual(l10n.actual_strings, {'hello world': "What'up, Doc?"}) self.assertEqual(_('not localized'), 'not localized') self.assertEqual(l10n.actual_strings, {'hello world': "What'up, Doc?", 'not localized': 'not localized'}) self.assertEqual(_('another string'), 'Bye!') self.assertEqual(l10n.actual_strings, {'hello world': "What'up, Doc?", 'another string': 'Bye!', 'not localized': 'not localized'}) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class LocalizationTests(unittest.TestCase): def test_default(self): logging.info('*** default ***') localization = Localization() text = 'hello world' self.assertEqual(localization._(text), text) def test_init(self): logging.info('*** init ***') settings = {'localized': {'hello world': "What'up, Doc?", 'another string': 'Bye!'}, 'space': {'title': 'space name', 'participants': ['[email protected]']}, 'server': {'url': 'http://to.no.where', 'hook': '/hook', 'binding': '0.0.0.0', 'port': 8080}} context = Context(settings) my_localization = Localization(context) self.assertEqual(my_localization.context, context) self.assertEqual(my_localization._('hello world'), "What'up, Doc?") self.assertEqual(my_localization._('not localized'), 'not localized') self.assertEqual(my_localization.actual_strings, {'hello world': "What'up, Doc?", 'not localized': 'not localized'}) def test_global(self): logging.info('*** global ***') settings = {'localized': {'hello world': "What'up, Doc?", 'another string': 'Bye!'}, 'space': {'title': 'space name', 'participants': ['[email protected]']}, 'server': {'url': 'http://to.no.where', 'hook': '/hook', 'binding': '0.0.0.0', 'port': 8080}} context = Context(settings) l10n.set_context(context) self.assertEqual(l10n.actual_strings, {}) self.assertEqual(_('hello world'), "What'up, Doc?") self.assertEqual(l10n.actual_strings, {'hello world': "What'up, Doc?"}) self.assertEqual(_('not localized'), 'not localized') self.assertEqual(l10n.actual_strings, {'hello world': "What'up, Doc?", 'not localized': 'not localized'}) self.assertEqual(_('another string'), 'Bye!') self.assertEqual(l10n.actual_strings, {'hello world': "What'up, Doc?", 'another string': 'Bye!', 'not localized': 'not localized'}) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class LocalizationTests(unittest.TestCase): def test_default(self): logging.info('*** default ***') localization = Localization() text = 'hello world' self.assertEqual(localization._(text), text) def test_init(self): logging.info('*** init ***') settings = {'localized': {'hello world': "What'up, Doc?", 'another string': 'Bye!'}, 'space': {'title': 'space name', 'participants': ['[email protected]']}, 'server': {'url': 'http://to.no.where', 'hook': '/hook', 'binding': '0.0.0.0', 'port': 8080}} context = Context(settings) my_localization = Localization(context) self.assertEqual(my_localization.context, context) self.assertEqual(my_localization._('hello world'), "What'up, Doc?") self.assertEqual(my_localization._('not localized'), 'not localized') self.assertEqual(my_localization.actual_strings, {'hello world': "What'up, Doc?", 'not localized': 'not localized'}) def test_global(self): logging.info('*** global ***') settings = {'localized': {'hello world': "What'up, Doc?", 'another string': 'Bye!'}, 'space': {'title': 'space name', 'participants': ['[email protected]']}, 'server': {'url': 'http://to.no.where', 'hook': '/hook', 'binding': '0.0.0.0', 'port': 8080}} context = Context(settings) l10n.set_context(context) self.assertEqual(l10n.actual_strings, {}) self.assertEqual(_('hello world'), "What'up, Doc?") self.assertEqual(l10n.actual_strings, {'hello world': "What'up, Doc?"}) self.assertEqual(_('not localized'), 'not localized') self.assertEqual(l10n.actual_strings, {'hello world': "What'up, Doc?", 'not localized': 'not localized'}) self.assertEqual(_('another string'), 'Bye!') self.assertEqual(l10n.actual_strings, {'hello world': "What'up, Doc?", 'another string': 'Bye!', 'not localized': 'not localized'}) if __name__ == '__main__': Context.set_logger() sys.exit(unittest.main()) <|reserved_special_token_1|> import unittest import gc import logging import os import mock import sys import time from shellbot import Context, Engine from shellbot.i18n import Localization, localization as l10n, _ class LocalizationTests(unittest.TestCase): def test_default(self): logging.info('*** default ***') localization = Localization() text = 'hello world' self.assertEqual(localization._(text), text) def test_init(self): logging.info('*** init ***') settings = {'localized': {'hello world': "What'up, Doc?", 'another string': 'Bye!'}, 'space': {'title': 'space name', 'participants': ['[email protected]']}, 'server': {'url': 'http://to.no.where', 'hook': '/hook', 'binding': '0.0.0.0', 'port': 8080}} context = Context(settings) my_localization = Localization(context) self.assertEqual(my_localization.context, context) self.assertEqual(my_localization._('hello world'), "What'up, Doc?") self.assertEqual(my_localization._('not localized'), 'not localized') self.assertEqual(my_localization.actual_strings, {'hello world': "What'up, Doc?", 'not localized': 'not localized'}) def test_global(self): logging.info('*** global ***') settings = {'localized': {'hello world': "What'up, Doc?", 'another string': 'Bye!'}, 'space': {'title': 'space name', 'participants': ['[email protected]']}, 'server': {'url': 'http://to.no.where', 'hook': '/hook', 'binding': '0.0.0.0', 'port': 8080}} context = Context(settings) l10n.set_context(context) self.assertEqual(l10n.actual_strings, {}) self.assertEqual(_('hello world'), "What'up, Doc?") self.assertEqual(l10n.actual_strings, {'hello world': "What'up, Doc?"}) self.assertEqual(_('not localized'), 'not localized') self.assertEqual(l10n.actual_strings, {'hello world': "What'up, Doc?", 'not localized': 'not localized'}) self.assertEqual(_('another string'), 'Bye!') self.assertEqual(l10n.actual_strings, {'hello world': "What'up, Doc?", 'another string': 'Bye!', 'not localized': 'not localized'}) if __name__ == '__main__': Context.set_logger() sys.exit(unittest.main()) <|reserved_special_token_1|> #!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import gc import logging import os import mock import sys import time from shellbot import Context, Engine from shellbot.i18n import Localization, localization as l10n, _ class LocalizationTests(unittest.TestCase): def test_default(self): logging.info('*** default ***') localization = Localization() text = 'hello world' self.assertEqual(localization._(text), text) def test_init(self): logging.info('*** init ***') settings = { 'localized': { 'hello world': "What'up, Doc?", 'another string': 'Bye!', }, 'space': { 'title': 'space name', 'participants': ['[email protected]'], }, 'server': { 'url': 'http://to.no.where', 'hook': '/hook', 'binding': '0.0.0.0', 'port': 8080, }, } context=Context(settings) my_localization = Localization(context) self.assertEqual(my_localization.context, context) self.assertEqual(my_localization._('hello world'), "What'up, Doc?") self.assertEqual(my_localization._('not localized'), 'not localized') self.assertEqual(my_localization.actual_strings, {'hello world': "What'up, Doc?", 'not localized': 'not localized'}) def test_global(self): logging.info('*** global ***') settings = { 'localized': { 'hello world': "What'up, Doc?", 'another string': 'Bye!', }, 'space': { 'title': 'space name', 'participants': ['[email protected]'], }, 'server': { 'url': 'http://to.no.where', 'hook': '/hook', 'binding': '0.0.0.0', 'port': 8080, }, } context=Context(settings) l10n.set_context(context) self.assertEqual(l10n.actual_strings, {}) self.assertEqual(_('hello world'), "What'up, Doc?") self.assertEqual(l10n.actual_strings, {'hello world': "What'up, Doc?"}) self.assertEqual(_('not localized'), 'not localized') self.assertEqual(l10n.actual_strings, {'hello world': "What'up, Doc?", 'not localized': 'not localized'}) self.assertEqual(_('another string'), 'Bye!') self.assertEqual(l10n.actual_strings, {'hello world': "What'up, Doc?", 'another string': 'Bye!', 'not localized': 'not localized'}) if __name__ == '__main__': Context.set_logger() sys.exit(unittest.main())
flexible
{ "blob_id": "debd51b923a6fc3b278a5083478bfb271a5913a8", "index": 162, "step-1": "<mask token>\n\n\nclass LocalizationTests(unittest.TestCase):\n\n def test_default(self):\n logging.info('*** default ***')\n localization = Localization()\n text = 'hello world'\n self.assertEqual(localization._(text), text)\n <mask token>\n\n def test_global(self):\n logging.info('*** global ***')\n settings = {'localized': {'hello world': \"What'up, Doc?\",\n 'another string': 'Bye!'}, 'space': {'title': 'space name',\n 'participants': ['[email protected]']}, 'server': {'url':\n 'http://to.no.where', 'hook': '/hook', 'binding': '0.0.0.0',\n 'port': 8080}}\n context = Context(settings)\n l10n.set_context(context)\n self.assertEqual(l10n.actual_strings, {})\n self.assertEqual(_('hello world'), \"What'up, Doc?\")\n self.assertEqual(l10n.actual_strings, {'hello world': \"What'up, Doc?\"})\n self.assertEqual(_('not localized'), 'not localized')\n self.assertEqual(l10n.actual_strings, {'hello world':\n \"What'up, Doc?\", 'not localized': 'not localized'})\n self.assertEqual(_('another string'), 'Bye!')\n self.assertEqual(l10n.actual_strings, {'hello world':\n \"What'up, Doc?\", 'another string': 'Bye!', 'not localized':\n 'not localized'})\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass LocalizationTests(unittest.TestCase):\n\n def test_default(self):\n logging.info('*** default ***')\n localization = Localization()\n text = 'hello world'\n self.assertEqual(localization._(text), text)\n\n def test_init(self):\n logging.info('*** init ***')\n settings = {'localized': {'hello world': \"What'up, Doc?\",\n 'another string': 'Bye!'}, 'space': {'title': 'space name',\n 'participants': ['[email protected]']}, 'server': {'url':\n 'http://to.no.where', 'hook': '/hook', 'binding': '0.0.0.0',\n 'port': 8080}}\n context = Context(settings)\n my_localization = Localization(context)\n self.assertEqual(my_localization.context, context)\n self.assertEqual(my_localization._('hello world'), \"What'up, Doc?\")\n self.assertEqual(my_localization._('not localized'), 'not localized')\n self.assertEqual(my_localization.actual_strings, {'hello world':\n \"What'up, Doc?\", 'not localized': 'not localized'})\n\n def test_global(self):\n logging.info('*** global ***')\n settings = {'localized': {'hello world': \"What'up, Doc?\",\n 'another string': 'Bye!'}, 'space': {'title': 'space name',\n 'participants': ['[email protected]']}, 'server': {'url':\n 'http://to.no.where', 'hook': '/hook', 'binding': '0.0.0.0',\n 'port': 8080}}\n context = Context(settings)\n l10n.set_context(context)\n self.assertEqual(l10n.actual_strings, {})\n self.assertEqual(_('hello world'), \"What'up, Doc?\")\n self.assertEqual(l10n.actual_strings, {'hello world': \"What'up, Doc?\"})\n self.assertEqual(_('not localized'), 'not localized')\n self.assertEqual(l10n.actual_strings, {'hello world':\n \"What'up, Doc?\", 'not localized': 'not localized'})\n self.assertEqual(_('another string'), 'Bye!')\n self.assertEqual(l10n.actual_strings, {'hello world':\n \"What'up, Doc?\", 'another string': 'Bye!', 'not localized':\n 'not localized'})\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass LocalizationTests(unittest.TestCase):\n\n def test_default(self):\n logging.info('*** default ***')\n localization = Localization()\n text = 'hello world'\n self.assertEqual(localization._(text), text)\n\n def test_init(self):\n logging.info('*** init ***')\n settings = {'localized': {'hello world': \"What'up, Doc?\",\n 'another string': 'Bye!'}, 'space': {'title': 'space name',\n 'participants': ['[email protected]']}, 'server': {'url':\n 'http://to.no.where', 'hook': '/hook', 'binding': '0.0.0.0',\n 'port': 8080}}\n context = Context(settings)\n my_localization = Localization(context)\n self.assertEqual(my_localization.context, context)\n self.assertEqual(my_localization._('hello world'), \"What'up, Doc?\")\n self.assertEqual(my_localization._('not localized'), 'not localized')\n self.assertEqual(my_localization.actual_strings, {'hello world':\n \"What'up, Doc?\", 'not localized': 'not localized'})\n\n def test_global(self):\n logging.info('*** global ***')\n settings = {'localized': {'hello world': \"What'up, Doc?\",\n 'another string': 'Bye!'}, 'space': {'title': 'space name',\n 'participants': ['[email protected]']}, 'server': {'url':\n 'http://to.no.where', 'hook': '/hook', 'binding': '0.0.0.0',\n 'port': 8080}}\n context = Context(settings)\n l10n.set_context(context)\n self.assertEqual(l10n.actual_strings, {})\n self.assertEqual(_('hello world'), \"What'up, Doc?\")\n self.assertEqual(l10n.actual_strings, {'hello world': \"What'up, Doc?\"})\n self.assertEqual(_('not localized'), 'not localized')\n self.assertEqual(l10n.actual_strings, {'hello world':\n \"What'up, Doc?\", 'not localized': 'not localized'})\n self.assertEqual(_('another string'), 'Bye!')\n self.assertEqual(l10n.actual_strings, {'hello world':\n \"What'up, Doc?\", 'another string': 'Bye!', 'not localized':\n 'not localized'})\n\n\nif __name__ == '__main__':\n Context.set_logger()\n sys.exit(unittest.main())\n", "step-4": "import unittest\nimport gc\nimport logging\nimport os\nimport mock\nimport sys\nimport time\nfrom shellbot import Context, Engine\nfrom shellbot.i18n import Localization, localization as l10n, _\n\n\nclass LocalizationTests(unittest.TestCase):\n\n def test_default(self):\n logging.info('*** default ***')\n localization = Localization()\n text = 'hello world'\n self.assertEqual(localization._(text), text)\n\n def test_init(self):\n logging.info('*** init ***')\n settings = {'localized': {'hello world': \"What'up, Doc?\",\n 'another string': 'Bye!'}, 'space': {'title': 'space name',\n 'participants': ['[email protected]']}, 'server': {'url':\n 'http://to.no.where', 'hook': '/hook', 'binding': '0.0.0.0',\n 'port': 8080}}\n context = Context(settings)\n my_localization = Localization(context)\n self.assertEqual(my_localization.context, context)\n self.assertEqual(my_localization._('hello world'), \"What'up, Doc?\")\n self.assertEqual(my_localization._('not localized'), 'not localized')\n self.assertEqual(my_localization.actual_strings, {'hello world':\n \"What'up, Doc?\", 'not localized': 'not localized'})\n\n def test_global(self):\n logging.info('*** global ***')\n settings = {'localized': {'hello world': \"What'up, Doc?\",\n 'another string': 'Bye!'}, 'space': {'title': 'space name',\n 'participants': ['[email protected]']}, 'server': {'url':\n 'http://to.no.where', 'hook': '/hook', 'binding': '0.0.0.0',\n 'port': 8080}}\n context = Context(settings)\n l10n.set_context(context)\n self.assertEqual(l10n.actual_strings, {})\n self.assertEqual(_('hello world'), \"What'up, Doc?\")\n self.assertEqual(l10n.actual_strings, {'hello world': \"What'up, Doc?\"})\n self.assertEqual(_('not localized'), 'not localized')\n self.assertEqual(l10n.actual_strings, {'hello world':\n \"What'up, Doc?\", 'not localized': 'not localized'})\n self.assertEqual(_('another string'), 'Bye!')\n self.assertEqual(l10n.actual_strings, {'hello world':\n \"What'up, Doc?\", 'another string': 'Bye!', 'not localized':\n 'not localized'})\n\n\nif __name__ == '__main__':\n Context.set_logger()\n sys.exit(unittest.main())\n", "step-5": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport unittest\nimport gc\nimport logging\nimport os\nimport mock\nimport sys\nimport time\n\nfrom shellbot import Context, Engine\nfrom shellbot.i18n import Localization, localization as l10n, _\n\nclass LocalizationTests(unittest.TestCase):\n\n def test_default(self):\n\n logging.info('*** default ***')\n\n localization = Localization()\n text = 'hello world'\n self.assertEqual(localization._(text), text)\n\n def test_init(self):\n\n logging.info('*** init ***')\n\n settings = {\n\n 'localized': {\n 'hello world': \"What'up, Doc?\",\n 'another string': 'Bye!',\n },\n\n 'space': {\n 'title': 'space name',\n 'participants': ['[email protected]'],\n },\n\n 'server': {\n 'url': 'http://to.no.where',\n 'hook': '/hook',\n 'binding': '0.0.0.0',\n 'port': 8080,\n },\n\n }\n context=Context(settings)\n\n my_localization = Localization(context)\n self.assertEqual(my_localization.context, context)\n\n self.assertEqual(my_localization._('hello world'), \"What'up, Doc?\")\n self.assertEqual(my_localization._('not localized'), 'not localized')\n self.assertEqual(my_localization.actual_strings,\n {'hello world': \"What'up, Doc?\",\n 'not localized': 'not localized'})\n\n def test_global(self):\n\n logging.info('*** global ***')\n\n settings = {\n\n 'localized': {\n 'hello world': \"What'up, Doc?\",\n 'another string': 'Bye!',\n },\n\n 'space': {\n 'title': 'space name',\n 'participants': ['[email protected]'],\n },\n\n 'server': {\n 'url': 'http://to.no.where',\n 'hook': '/hook',\n 'binding': '0.0.0.0',\n 'port': 8080,\n },\n\n }\n context=Context(settings)\n\n l10n.set_context(context)\n self.assertEqual(l10n.actual_strings, {})\n\n self.assertEqual(_('hello world'), \"What'up, Doc?\")\n self.assertEqual(l10n.actual_strings,\n {'hello world': \"What'up, Doc?\"})\n\n self.assertEqual(_('not localized'), 'not localized')\n self.assertEqual(l10n.actual_strings,\n {'hello world': \"What'up, Doc?\",\n 'not localized': 'not localized'})\n\n self.assertEqual(_('another string'), 'Bye!')\n self.assertEqual(l10n.actual_strings,\n {'hello world': \"What'up, Doc?\",\n 'another string': 'Bye!',\n 'not localized': 'not localized'})\n\n\nif __name__ == '__main__':\n\n Context.set_logger()\n sys.exit(unittest.main())\n", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
<|reserved_special_token_0|> def right_permutation(arr): if len(arr) == 1: return True for i in range(len(arr) - 1): if arr[i + 1] < arr[i]: break elif i == len(arr) - 2: return True return False def worstsort(arr): sort_arr = [] check = False while check == False: sort_arr = np.random.permutation(arr) check = right_permutation(sort_arr) return sort_arr <|reserved_special_token_0|> def factorial(n): result = 1 for i in range(n): result = result * (i + 1) return result <|reserved_special_token_0|> def median_finder(arr, x): tried = 0 if abs(x) <= 0.5: lower = np.percentile(arr, 50 - x / 2) upper = np.percentile(arr, 50 + x / 2) while tried < 10000: find = np.random.randint(0, len(arr)) if lower <= arr[find] and arr[find] <= upper: return arr[find] else: tried += 1 return 'Tried enough times, still cannot find the value' else: return 'x not in the domain' <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def right_permutation(arr): if len(arr) == 1: return True for i in range(len(arr) - 1): if arr[i + 1] < arr[i]: break elif i == len(arr) - 2: return True return False def worstsort(arr): sort_arr = [] check = False while check == False: sort_arr = np.random.permutation(arr) check = right_permutation(sort_arr) return sort_arr <|reserved_special_token_0|> print(worstsort(test1)) print(worstsort(test2)) print(worstsort(test3)) print(worstsort(test4)) def factorial(n): result = 1 for i in range(n): result = result * (i + 1) return result <|reserved_special_token_0|> plt.plot(x, y_factorial, label='Factorial of n') plt.plot(x, y_compare, label='n square') plt.title('Complexity comparison') plt.legend() def median_finder(arr, x): tried = 0 if abs(x) <= 0.5: lower = np.percentile(arr, 50 - x / 2) upper = np.percentile(arr, 50 + x / 2) while tried < 10000: find = np.random.randint(0, len(arr)) if lower <= arr[find] and arr[find] <= upper: return arr[find] else: tried += 1 return 'Tried enough times, still cannot find the value' else: return 'x not in the domain' <|reserved_special_token_0|> print(median_finder(test1, 0.5)) print(median_finder(test2, 0.5)) print(median_finder(test2, 0)) print(median_finder(test3, 0.5)) print(median_finder(test4, 0)) print(median_finder(test4, 0.5)) <|reserved_special_token_0|> for i in range(200, 1200, 50): testlist = list(np.random.permutation(i)) time = timeit.timeit(stmt='median_finder(testlist,0.5)', setup= 'from __main__ import median_finder,testlist', number=100) time = time / 100 stack = np.array((time, i)) data = np.vstack((data, stack)) <|reserved_special_token_0|> plt.figure() plt.ylim(0, 0.01) plt.scatter(x=data[:, 1], y=data[:, 0]) plt.xlabel('Inputsize') plt.ylabel('Running time') plt.title('Median finder running time') <|reserved_special_token_1|> <|reserved_special_token_0|> def right_permutation(arr): if len(arr) == 1: return True for i in range(len(arr) - 1): if arr[i + 1] < arr[i]: break elif i == len(arr) - 2: return True return False def worstsort(arr): sort_arr = [] check = False while check == False: sort_arr = np.random.permutation(arr) check = right_permutation(sort_arr) return sort_arr test1 = [5, 4, 3, 2, 1] test2 = [1, 2, 3, 4, 5] test3 = [2, 2, 2, 2, 2] test4 = [2] print(worstsort(test1)) print(worstsort(test2)) print(worstsort(test3)) print(worstsort(test4)) def factorial(n): result = 1 for i in range(n): result = result * (i + 1) return result x = np.arange(0, 7, 1) y_factorial = list(map(factorial, x)) y_compare = x * x plt.plot(x, y_factorial, label='Factorial of n') plt.plot(x, y_compare, label='n square') plt.title('Complexity comparison') plt.legend() def median_finder(arr, x): tried = 0 if abs(x) <= 0.5: lower = np.percentile(arr, 50 - x / 2) upper = np.percentile(arr, 50 + x / 2) while tried < 10000: find = np.random.randint(0, len(arr)) if lower <= arr[find] and arr[find] <= upper: return arr[find] else: tried += 1 return 'Tried enough times, still cannot find the value' else: return 'x not in the domain' test1 = list(np.random.permutation(200)) test2 = [4] * 100 test3 = [5] * 1000 test4 = test2 + test3 print(median_finder(test1, 0.5)) print(median_finder(test2, 0.5)) print(median_finder(test2, 0)) print(median_finder(test3, 0.5)) print(median_finder(test4, 0)) print(median_finder(test4, 0.5)) data = np.empty((1, 2)) for i in range(200, 1200, 50): testlist = list(np.random.permutation(i)) time = timeit.timeit(stmt='median_finder(testlist,0.5)', setup= 'from __main__ import median_finder,testlist', number=100) time = time / 100 stack = np.array((time, i)) data = np.vstack((data, stack)) data = data[1:] plt.figure() plt.ylim(0, 0.01) plt.scatter(x=data[:, 1], y=data[:, 0]) plt.xlabel('Inputsize') plt.ylabel('Running time') plt.title('Median finder running time') <|reserved_special_token_1|> <|reserved_special_token_0|> import numpy as np import matplotlib.pyplot as plt import timeit def right_permutation(arr): if len(arr) == 1: return True for i in range(len(arr) - 1): if arr[i + 1] < arr[i]: break elif i == len(arr) - 2: return True return False def worstsort(arr): sort_arr = [] check = False while check == False: sort_arr = np.random.permutation(arr) check = right_permutation(sort_arr) return sort_arr test1 = [5, 4, 3, 2, 1] test2 = [1, 2, 3, 4, 5] test3 = [2, 2, 2, 2, 2] test4 = [2] print(worstsort(test1)) print(worstsort(test2)) print(worstsort(test3)) print(worstsort(test4)) def factorial(n): result = 1 for i in range(n): result = result * (i + 1) return result x = np.arange(0, 7, 1) y_factorial = list(map(factorial, x)) y_compare = x * x plt.plot(x, y_factorial, label='Factorial of n') plt.plot(x, y_compare, label='n square') plt.title('Complexity comparison') plt.legend() def median_finder(arr, x): tried = 0 if abs(x) <= 0.5: lower = np.percentile(arr, 50 - x / 2) upper = np.percentile(arr, 50 + x / 2) while tried < 10000: find = np.random.randint(0, len(arr)) if lower <= arr[find] and arr[find] <= upper: return arr[find] else: tried += 1 return 'Tried enough times, still cannot find the value' else: return 'x not in the domain' test1 = list(np.random.permutation(200)) test2 = [4] * 100 test3 = [5] * 1000 test4 = test2 + test3 print(median_finder(test1, 0.5)) print(median_finder(test2, 0.5)) print(median_finder(test2, 0)) print(median_finder(test3, 0.5)) print(median_finder(test4, 0)) print(median_finder(test4, 0.5)) data = np.empty((1, 2)) for i in range(200, 1200, 50): testlist = list(np.random.permutation(i)) time = timeit.timeit(stmt='median_finder(testlist,0.5)', setup= 'from __main__ import median_finder,testlist', number=100) time = time / 100 stack = np.array((time, i)) data = np.vstack((data, stack)) data = data[1:] plt.figure() plt.ylim(0, 0.01) plt.scatter(x=data[:, 1], y=data[:, 0]) plt.xlabel('Inputsize') plt.ylabel('Running time') plt.title('Median finder running time') <|reserved_special_token_1|> #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 11 14:55:12 2019 @author: Furankyyy """ import numpy as np import matplotlib.pyplot as plt import timeit ###worst sort function### #define the function that checks whether the list is in ascending order def right_permutation(arr): if len(arr)==1: #if there's only one element, then the order is always correct return True for i in range(len(arr)-1): #check every elements from the first to the second to the last if arr[i+1]<arr[i]: #if the i+1th element is smaller than ith, the order is wrong, break the loop and return false break else: if i == len(arr)-2: #if the i+1th element is greater than/equal to ith, check if we have already checked all the elements return True #if we've already checked all the elements (i.e. i==len(arr)-2), return true; if not, continue the loop return False #define the worst sort function def worstsort(arr): sort_arr=[] #initialize output check = False #initialize the result of right_permutation() while check == False: #while the order is wrong, generate a new permyutation and check if its order is correct sort_arr = np.random.permutation(arr) check = right_permutation(sort_arr) return sort_arr #test cases test1=[5,4,3,2,1] test2=[1,2,3,4,5] #best case test3=[2,2,2,2,2] #best case as well! test4=[2] #only one element print(worstsort(test1)) print(worstsort(test2)) print(worstsort(test3)) print(worstsort(test4)) #the best case is when the input list is already sorted, in this case, we only need to run the right_permutation once #we have a for loop in right_permutation, so the best case complexity is O(n) #given a random input of size n, the chance that the input x_k is correctly sorted is Pr(x_k) = 1/P_n = 1/n! #since in this worst algorithm, we do not "remember" the permutations that we've already checked #so each time, the Pr(sorted) remains the same 1/n! #Then we would expect to have n! times to have the corrected sorted list #the reason is that we have E[Pr(x1)+Pr(x2)+...+Pr(x_k)]=1, since Pr(x_k)=1/n!, we would expect k = n! #this reasoning is the same as the random indicator variable in the book, where we have the pr(I) for each choice (permutation) and we sum them to find the expected value #so the averaage case complexity is O(n!) #to calculate what n is best for this function def factorial(n): result=1 for i in range(n): result=result*(i+1) return result x=np.arange(0,7,1) y_factorial=list(map(factorial,x)) y_compare=x*x plt.plot(x,y_factorial,label="Factorial of n") plt.plot(x,y_compare,label="n square") plt.title("Complexity comparison") plt.legend() #from the plot we can see that for algorithms with comlexity of O(n^2) and O(n!), the difference comes when n=5 #when n=4, the two algorithms do not vary that much, but when n=5, they have a >100 times difference #therefore, this method is feasible when n<=4 #p.s. constants are discounted (they are relatively unimportant) ###median finder### #the worst case for the median finder is that the elements in the input list are unique #the best case is that all elements are the same --> no matter which we choose, it is the median #to consider the times we try before stopping, we need to consider the worst case --> all elements are different #then the chance to find the exact median is 1/n #the number of elements lying in the input deviation range x is x//(100/n)+1 for this worst case #explanation: divide the 100% to n parts, if all elements are different then each element takes the 1 part, the x//(range for 1 part)+1 is the num of elements lying in the range #therefore, the probability of choosing the element in the range given by x is (x//(100/n)+1)/n #I want to try the expected times of choosing the correct element(s) for the worst case #Pr(failure) for 1 try is 1-(x//(100/n)+1)/n #Pr(failure) for the first k try is (1-(x//(100/n)+1)/n)^k, which scales with x and n. #so the Pr(at least one success) for the first k try is 1-Pr(failure)=1-(1-(x//(100/n)+1)/n)^k #we want to find a k taht makes this Pr large enough #so we want to find a small k minimizing Pr(failure) for the first k try #to simplify the problem, we regard x as constant and assume the "//" is "/" #(1-(x//(100/n)+1)/n)^k = ((n-xn/100-1)/n)^k =(1-x/100-1/n)^k #x/100 is a constant #-->(1-1/n)^k #when n is sufficiently large, (1-1/n) is nearly 1 #it is extremely hard to succeed if n is very large, I set the limit of k at 10000, simply because my laptop's computational ability def median_finder(arr,x): tried = 0 #record the number of times of choosing the random element if abs(x) <= 0.5: #when x is valid lower=np.percentile(arr,50-x/2) upper=np.percentile(arr,50+x/2) while tried <10000: find = np.random.randint(0,len(arr)) #find a new element if lower<=arr[find] and arr[find]<=upper: #if the chosen element is in the range, return it return arr[find] else: tried += 1 return "Tried enough times, still cannot find the value" else: return "x not in the domain" #test cases test1=list(np.random.permutation(200)) test2=[4]*100 test3=[5]*1000 test4=test2+test3 print(median_finder(test1,0.5)) #worst case, exactly 2 elements in the range print(median_finder(test2,0.5)) #best case print(median_finder(test2,0)) #best case print(median_finder(test3,0.5)) #best case print(median_finder(test4,0)) #1000/1100 probability print(median_finder(test4,0.5)) #same as above. #time complexity #best case running time is O(1) #the time complexity of the worst case running time is E[k]=Sum(E[ki]) #E[ki]=Pr(correct)=(x//(100/n)+1)/n #sum is from 1 to the limit tried k #since x is between 0 and 0.5, we simply regard it as constant #we also assume the "//" is "/" #then the expression becomes: E[k]= k*(xn/100+1)/n #as n goes to infinity, we can solve this by trying to use L'Hopital's rule #the result is kx/100, which is a constant #O(1) data=np.empty((1,2)) for i in range(200,1200,50): testlist=list(np.random.permutation(i)) time=timeit.timeit(stmt="median_finder(testlist,0.5)",setup="from __main__ import median_finder,testlist",number=100) time=time/100 stack=np.array((time,i)) data=np.vstack((data,stack)) data=data[1:] plt.figure() plt.ylim(0,0.01) plt.scatter(x=data[:,1],y=data[:,0]) plt.xlabel("Inputsize") plt.ylabel("Running time") plt.title("Median finder running time") #from the plot we can see that the running time is almost constant --> O(1) #space complexity is O(n), because each time we just store the (sorted) list of length n
flexible
{ "blob_id": "7c82565a4184b2e779e2bb6ba70b497cc287af35", "index": 5285, "step-1": "<mask token>\n\n\ndef right_permutation(arr):\n if len(arr) == 1:\n return True\n for i in range(len(arr) - 1):\n if arr[i + 1] < arr[i]:\n break\n elif i == len(arr) - 2:\n return True\n return False\n\n\ndef worstsort(arr):\n sort_arr = []\n check = False\n while check == False:\n sort_arr = np.random.permutation(arr)\n check = right_permutation(sort_arr)\n return sort_arr\n\n\n<mask token>\n\n\ndef factorial(n):\n result = 1\n for i in range(n):\n result = result * (i + 1)\n return result\n\n\n<mask token>\n\n\ndef median_finder(arr, x):\n tried = 0\n if abs(x) <= 0.5:\n lower = np.percentile(arr, 50 - x / 2)\n upper = np.percentile(arr, 50 + x / 2)\n while tried < 10000:\n find = np.random.randint(0, len(arr))\n if lower <= arr[find] and arr[find] <= upper:\n return arr[find]\n else:\n tried += 1\n return 'Tried enough times, still cannot find the value'\n else:\n return 'x not in the domain'\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef right_permutation(arr):\n if len(arr) == 1:\n return True\n for i in range(len(arr) - 1):\n if arr[i + 1] < arr[i]:\n break\n elif i == len(arr) - 2:\n return True\n return False\n\n\ndef worstsort(arr):\n sort_arr = []\n check = False\n while check == False:\n sort_arr = np.random.permutation(arr)\n check = right_permutation(sort_arr)\n return sort_arr\n\n\n<mask token>\nprint(worstsort(test1))\nprint(worstsort(test2))\nprint(worstsort(test3))\nprint(worstsort(test4))\n\n\ndef factorial(n):\n result = 1\n for i in range(n):\n result = result * (i + 1)\n return result\n\n\n<mask token>\nplt.plot(x, y_factorial, label='Factorial of n')\nplt.plot(x, y_compare, label='n square')\nplt.title('Complexity comparison')\nplt.legend()\n\n\ndef median_finder(arr, x):\n tried = 0\n if abs(x) <= 0.5:\n lower = np.percentile(arr, 50 - x / 2)\n upper = np.percentile(arr, 50 + x / 2)\n while tried < 10000:\n find = np.random.randint(0, len(arr))\n if lower <= arr[find] and arr[find] <= upper:\n return arr[find]\n else:\n tried += 1\n return 'Tried enough times, still cannot find the value'\n else:\n return 'x not in the domain'\n\n\n<mask token>\nprint(median_finder(test1, 0.5))\nprint(median_finder(test2, 0.5))\nprint(median_finder(test2, 0))\nprint(median_finder(test3, 0.5))\nprint(median_finder(test4, 0))\nprint(median_finder(test4, 0.5))\n<mask token>\nfor i in range(200, 1200, 50):\n testlist = list(np.random.permutation(i))\n time = timeit.timeit(stmt='median_finder(testlist,0.5)', setup=\n 'from __main__ import median_finder,testlist', number=100)\n time = time / 100\n stack = np.array((time, i))\n data = np.vstack((data, stack))\n<mask token>\nplt.figure()\nplt.ylim(0, 0.01)\nplt.scatter(x=data[:, 1], y=data[:, 0])\nplt.xlabel('Inputsize')\nplt.ylabel('Running time')\nplt.title('Median finder running time')\n", "step-3": "<mask token>\n\n\ndef right_permutation(arr):\n if len(arr) == 1:\n return True\n for i in range(len(arr) - 1):\n if arr[i + 1] < arr[i]:\n break\n elif i == len(arr) - 2:\n return True\n return False\n\n\ndef worstsort(arr):\n sort_arr = []\n check = False\n while check == False:\n sort_arr = np.random.permutation(arr)\n check = right_permutation(sort_arr)\n return sort_arr\n\n\ntest1 = [5, 4, 3, 2, 1]\ntest2 = [1, 2, 3, 4, 5]\ntest3 = [2, 2, 2, 2, 2]\ntest4 = [2]\nprint(worstsort(test1))\nprint(worstsort(test2))\nprint(worstsort(test3))\nprint(worstsort(test4))\n\n\ndef factorial(n):\n result = 1\n for i in range(n):\n result = result * (i + 1)\n return result\n\n\nx = np.arange(0, 7, 1)\ny_factorial = list(map(factorial, x))\ny_compare = x * x\nplt.plot(x, y_factorial, label='Factorial of n')\nplt.plot(x, y_compare, label='n square')\nplt.title('Complexity comparison')\nplt.legend()\n\n\ndef median_finder(arr, x):\n tried = 0\n if abs(x) <= 0.5:\n lower = np.percentile(arr, 50 - x / 2)\n upper = np.percentile(arr, 50 + x / 2)\n while tried < 10000:\n find = np.random.randint(0, len(arr))\n if lower <= arr[find] and arr[find] <= upper:\n return arr[find]\n else:\n tried += 1\n return 'Tried enough times, still cannot find the value'\n else:\n return 'x not in the domain'\n\n\ntest1 = list(np.random.permutation(200))\ntest2 = [4] * 100\ntest3 = [5] * 1000\ntest4 = test2 + test3\nprint(median_finder(test1, 0.5))\nprint(median_finder(test2, 0.5))\nprint(median_finder(test2, 0))\nprint(median_finder(test3, 0.5))\nprint(median_finder(test4, 0))\nprint(median_finder(test4, 0.5))\ndata = np.empty((1, 2))\nfor i in range(200, 1200, 50):\n testlist = list(np.random.permutation(i))\n time = timeit.timeit(stmt='median_finder(testlist,0.5)', setup=\n 'from __main__ import median_finder,testlist', number=100)\n time = time / 100\n stack = np.array((time, i))\n data = np.vstack((data, stack))\ndata = data[1:]\nplt.figure()\nplt.ylim(0, 0.01)\nplt.scatter(x=data[:, 1], y=data[:, 0])\nplt.xlabel('Inputsize')\nplt.ylabel('Running time')\nplt.title('Median finder running time')\n", "step-4": "<mask token>\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport timeit\n\n\ndef right_permutation(arr):\n if len(arr) == 1:\n return True\n for i in range(len(arr) - 1):\n if arr[i + 1] < arr[i]:\n break\n elif i == len(arr) - 2:\n return True\n return False\n\n\ndef worstsort(arr):\n sort_arr = []\n check = False\n while check == False:\n sort_arr = np.random.permutation(arr)\n check = right_permutation(sort_arr)\n return sort_arr\n\n\ntest1 = [5, 4, 3, 2, 1]\ntest2 = [1, 2, 3, 4, 5]\ntest3 = [2, 2, 2, 2, 2]\ntest4 = [2]\nprint(worstsort(test1))\nprint(worstsort(test2))\nprint(worstsort(test3))\nprint(worstsort(test4))\n\n\ndef factorial(n):\n result = 1\n for i in range(n):\n result = result * (i + 1)\n return result\n\n\nx = np.arange(0, 7, 1)\ny_factorial = list(map(factorial, x))\ny_compare = x * x\nplt.plot(x, y_factorial, label='Factorial of n')\nplt.plot(x, y_compare, label='n square')\nplt.title('Complexity comparison')\nplt.legend()\n\n\ndef median_finder(arr, x):\n tried = 0\n if abs(x) <= 0.5:\n lower = np.percentile(arr, 50 - x / 2)\n upper = np.percentile(arr, 50 + x / 2)\n while tried < 10000:\n find = np.random.randint(0, len(arr))\n if lower <= arr[find] and arr[find] <= upper:\n return arr[find]\n else:\n tried += 1\n return 'Tried enough times, still cannot find the value'\n else:\n return 'x not in the domain'\n\n\ntest1 = list(np.random.permutation(200))\ntest2 = [4] * 100\ntest3 = [5] * 1000\ntest4 = test2 + test3\nprint(median_finder(test1, 0.5))\nprint(median_finder(test2, 0.5))\nprint(median_finder(test2, 0))\nprint(median_finder(test3, 0.5))\nprint(median_finder(test4, 0))\nprint(median_finder(test4, 0.5))\ndata = np.empty((1, 2))\nfor i in range(200, 1200, 50):\n testlist = list(np.random.permutation(i))\n time = timeit.timeit(stmt='median_finder(testlist,0.5)', setup=\n 'from __main__ import median_finder,testlist', number=100)\n time = time / 100\n stack = np.array((time, i))\n data = np.vstack((data, stack))\ndata = data[1:]\nplt.figure()\nplt.ylim(0, 0.01)\nplt.scatter(x=data[:, 1], y=data[:, 0])\nplt.xlabel('Inputsize')\nplt.ylabel('Running time')\nplt.title('Median finder running time')\n", "step-5": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 11 14:55:12 2019\n\n@author: Furankyyy\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport timeit\n\n###worst sort function###\n\n#define the function that checks whether the list is in ascending order\ndef right_permutation(arr):\n if len(arr)==1: #if there's only one element, then the order is always correct\n return True\n for i in range(len(arr)-1): #check every elements from the first to the second to the last\n if arr[i+1]<arr[i]: #if the i+1th element is smaller than ith, the order is wrong, break the loop and return false\n break\n else:\n if i == len(arr)-2: #if the i+1th element is greater than/equal to ith, check if we have already checked all the elements\n return True #if we've already checked all the elements (i.e. i==len(arr)-2), return true; if not, continue the loop\n return False\n \n \n#define the worst sort function\ndef worstsort(arr):\n sort_arr=[] #initialize output\n check = False #initialize the result of right_permutation()\n while check == False: #while the order is wrong, generate a new permyutation and check if its order is correct\n sort_arr = np.random.permutation(arr)\n check = right_permutation(sort_arr)\n return sort_arr\n\n#test cases\ntest1=[5,4,3,2,1]\ntest2=[1,2,3,4,5] #best case\ntest3=[2,2,2,2,2] #best case as well!\ntest4=[2] #only one element\nprint(worstsort(test1))\nprint(worstsort(test2))\nprint(worstsort(test3))\nprint(worstsort(test4))\n\n\n#the best case is when the input list is already sorted, in this case, we only need to run the right_permutation once\n#we have a for loop in right_permutation, so the best case complexity is O(n)\n\n\n#given a random input of size n, the chance that the input x_k is correctly sorted is Pr(x_k) = 1/P_n = 1/n! \n#since in this worst algorithm, we do not \"remember\" the permutations that we've already checked\n#so each time, the Pr(sorted) remains the same 1/n!\n#Then we would expect to have n! times to have the corrected sorted list \n#the reason is that we have E[Pr(x1)+Pr(x2)+...+Pr(x_k)]=1, since Pr(x_k)=1/n!, we would expect k = n!\n#this reasoning is the same as the random indicator variable in the book, where we have the pr(I) for each choice (permutation) and we sum them to find the expected value\n#so the averaage case complexity is O(n!)\n\n\n#to calculate what n is best for this function\n\ndef factorial(n):\n result=1\n for i in range(n):\n result=result*(i+1)\n return result\n\nx=np.arange(0,7,1)\ny_factorial=list(map(factorial,x))\ny_compare=x*x\n\nplt.plot(x,y_factorial,label=\"Factorial of n\")\nplt.plot(x,y_compare,label=\"n square\")\nplt.title(\"Complexity comparison\")\nplt.legend()\n\n#from the plot we can see that for algorithms with comlexity of O(n^2) and O(n!), the difference comes when n=5\n#when n=4, the two algorithms do not vary that much, but when n=5, they have a >100 times difference\n#therefore, this method is feasible when n<=4\n#p.s. constants are discounted (they are relatively unimportant)\n\n\n\n\n###median finder###\n\n#the worst case for the median finder is that the elements in the input list are unique\n#the best case is that all elements are the same --> no matter which we choose, it is the median\n\n#to consider the times we try before stopping, we need to consider the worst case --> all elements are different\n#then the chance to find the exact median is 1/n\n#the number of elements lying in the input deviation range x is x//(100/n)+1 for this worst case\n#explanation: divide the 100% to n parts, if all elements are different then each element takes the 1 part, the x//(range for 1 part)+1 is the num of elements lying in the range\n#therefore, the probability of choosing the element in the range given by x is (x//(100/n)+1)/n\n#I want to try the expected times of choosing the correct element(s) for the worst case\n\n#Pr(failure) for 1 try is 1-(x//(100/n)+1)/n\n#Pr(failure) for the first k try is (1-(x//(100/n)+1)/n)^k, which scales with x and n.\n\n#so the Pr(at least one success) for the first k try is 1-Pr(failure)=1-(1-(x//(100/n)+1)/n)^k\n#we want to find a k taht makes this Pr large enough\n#so we want to find a small k minimizing Pr(failure) for the first k try\n#to simplify the problem, we regard x as constant and assume the \"//\" is \"/\"\n#(1-(x//(100/n)+1)/n)^k = ((n-xn/100-1)/n)^k =(1-x/100-1/n)^k\n#x/100 is a constant\n#-->(1-1/n)^k\n#when n is sufficiently large, (1-1/n) is nearly 1\n#it is extremely hard to succeed if n is very large, I set the limit of k at 10000, simply because my laptop's computational ability\n\ndef median_finder(arr,x):\n tried = 0 #record the number of times of choosing the random element\n if abs(x) <= 0.5: #when x is valid\n lower=np.percentile(arr,50-x/2)\n upper=np.percentile(arr,50+x/2)\n while tried <10000:\n find = np.random.randint(0,len(arr)) #find a new element\n if lower<=arr[find] and arr[find]<=upper: #if the chosen element is in the range, return it\n return arr[find]\n else: \n tried += 1 \n return \"Tried enough times, still cannot find the value\"\n else:\n return \"x not in the domain\"\n\n#test cases\ntest1=list(np.random.permutation(200))\ntest2=[4]*100\ntest3=[5]*1000\ntest4=test2+test3\n\nprint(median_finder(test1,0.5)) #worst case, exactly 2 elements in the range\nprint(median_finder(test2,0.5)) #best case\nprint(median_finder(test2,0)) #best case\nprint(median_finder(test3,0.5)) #best case\nprint(median_finder(test4,0)) #1000/1100 probability \nprint(median_finder(test4,0.5)) #same as above.\n\n\n#time complexity\n\n#best case running time is O(1)\n\n#the time complexity of the worst case running time is E[k]=Sum(E[ki])\n#E[ki]=Pr(correct)=(x//(100/n)+1)/n\n#sum is from 1 to the limit tried k\n#since x is between 0 and 0.5, we simply regard it as constant\n#we also assume the \"//\" is \"/\"\n#then the expression becomes: E[k]= k*(xn/100+1)/n\n#as n goes to infinity, we can solve this by trying to use L'Hopital's rule\n#the result is kx/100, which is a constant\n#O(1)\n\n\ndata=np.empty((1,2))\n\nfor i in range(200,1200,50): \n testlist=list(np.random.permutation(i))\n time=timeit.timeit(stmt=\"median_finder(testlist,0.5)\",setup=\"from __main__ import median_finder,testlist\",number=100)\n time=time/100\n stack=np.array((time,i))\n\n data=np.vstack((data,stack))\n\ndata=data[1:]\n\nplt.figure()\nplt.ylim(0,0.01)\nplt.scatter(x=data[:,1],y=data[:,0])\nplt.xlabel(\"Inputsize\")\nplt.ylabel(\"Running time\")\nplt.title(\"Median finder running time\")\n\n#from the plot we can see that the running time is almost constant --> O(1)\n\n\n#space complexity is O(n), because each time we just store the (sorted) list of length n", "step-ids": [ 4, 5, 6, 7, 8 ] }
[ 4, 5, 6, 7, 8 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> admin.site.register(Doggo) admin.site.register(Profile) <|reserved_special_token_1|> from django.contrib import admin from apap.models import * admin.site.register(Doggo) admin.site.register(Profile) <|reserved_special_token_1|> from django.contrib import admin from apap.models import * # Register your models here. admin.site.register(Doggo) admin.site.register(Profile)
flexible
{ "blob_id": "22504b466cdeb380b976e23e2708e94131722e11", "index": 8147, "step-1": "<mask token>\n", "step-2": "<mask token>\nadmin.site.register(Doggo)\nadmin.site.register(Profile)\n", "step-3": "from django.contrib import admin\nfrom apap.models import *\nadmin.site.register(Doggo)\nadmin.site.register(Profile)\n", "step-4": "from django.contrib import admin\nfrom apap.models import *\n# Register your models here.\n\nadmin.site.register(Doggo)\nadmin.site.register(Profile)", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import time from numba import njit import scipy.sparse as sparse import scipy.sparse.linalg as sparse_alg L = 12 Nup = 6 Ndown = 6 t = -2.0 U = 10.0 hoppings = [(i, j, t) for i in range(L) for j in range(L) if abs(i - j) == 1] @njit def hammingWeight(n): res = 0 for i in range(32): if n & (1 << i): res += 1 return res @njit def getStates(): spinUpStates = [i for i in range(1 << L) if hammingWeight(i) == Nup] spinDownStates = [i for i in range(1 << L) if hammingWeight(i) == Ndown] states = [(spinUp << L) + (spinDown) for spinUp in spinUpStates for spinDown in spinDownStates] return states @njit def doubleOccNum(state): spinUpState = state >> L spinDownState = state & ((1 << L) - 1) return hammingWeight(spinUpState & spinDownState) def Hamiltonian(states): n = len(states) H = sparse.lil_matrix((n,n)) stateIdxMap = {} for i in range(n): stateIdxMap[states[i]] = i for i in range(n): H[i, i] = U * doubleOccNum(states[i]) for a, b, t in hoppings: for s in range(2): if (states[i] & (1 << (s * L) << b)) and not (states[i] & (1 << (s * L) << a)): state = states[i] ^ (1 << (s * L) << b) ^ (1 << (s * L) << a) j = stateIdxMap[state] H[j, i] = t return H if __name__ == '__main__': start = time.time() states = getStates() end = time.time() print("Constructing State Cost = %s" % (end - start)) start = time.time() H = Hamiltonian(states) end = time.time() print("Constructing Hamiltonian Cost = %s" % (end - start)) start = time.time() E,V=sparse_alg.eigsh(H.tocsr(),1,which='SA') end = time.time() print("Solve EigenValue Cost = %s" % (end - start)) print(E)
normal
{ "blob_id": "325cc2fd82c44d0b7e291384159bd48d068e60f1", "index": 1428, "step-1": "<mask token>\n\n\n@njit\ndef hammingWeight(n):\n res = 0\n for i in range(32):\n if n & 1 << i:\n res += 1\n return res\n\n\n@njit\ndef getStates():\n spinUpStates = [i for i in range(1 << L) if hammingWeight(i) == Nup]\n spinDownStates = [i for i in range(1 << L) if hammingWeight(i) == Ndown]\n states = [((spinUp << L) + spinDown) for spinUp in spinUpStates for\n spinDown in spinDownStates]\n return states\n\n\n@njit\ndef doubleOccNum(state):\n spinUpState = state >> L\n spinDownState = state & (1 << L) - 1\n return hammingWeight(spinUpState & spinDownState)\n\n\ndef Hamiltonian(states):\n n = len(states)\n H = sparse.lil_matrix((n, n))\n stateIdxMap = {}\n for i in range(n):\n stateIdxMap[states[i]] = i\n for i in range(n):\n H[i, i] = U * doubleOccNum(states[i])\n for a, b, t in hoppings:\n for s in range(2):\n if states[i] & 1 << s * L << b and not states[i\n ] & 1 << s * L << a:\n state = states[i] ^ 1 << s * L << b ^ 1 << s * L << a\n j = stateIdxMap[state]\n H[j, i] = t\n return H\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\n@njit\ndef hammingWeight(n):\n res = 0\n for i in range(32):\n if n & 1 << i:\n res += 1\n return res\n\n\n@njit\ndef getStates():\n spinUpStates = [i for i in range(1 << L) if hammingWeight(i) == Nup]\n spinDownStates = [i for i in range(1 << L) if hammingWeight(i) == Ndown]\n states = [((spinUp << L) + spinDown) for spinUp in spinUpStates for\n spinDown in spinDownStates]\n return states\n\n\n@njit\ndef doubleOccNum(state):\n spinUpState = state >> L\n spinDownState = state & (1 << L) - 1\n return hammingWeight(spinUpState & spinDownState)\n\n\ndef Hamiltonian(states):\n n = len(states)\n H = sparse.lil_matrix((n, n))\n stateIdxMap = {}\n for i in range(n):\n stateIdxMap[states[i]] = i\n for i in range(n):\n H[i, i] = U * doubleOccNum(states[i])\n for a, b, t in hoppings:\n for s in range(2):\n if states[i] & 1 << s * L << b and not states[i\n ] & 1 << s * L << a:\n state = states[i] ^ 1 << s * L << b ^ 1 << s * L << a\n j = stateIdxMap[state]\n H[j, i] = t\n return H\n\n\nif __name__ == '__main__':\n start = time.time()\n states = getStates()\n end = time.time()\n print('Constructing State Cost = %s' % (end - start))\n start = time.time()\n H = Hamiltonian(states)\n end = time.time()\n print('Constructing Hamiltonian Cost = %s' % (end - start))\n start = time.time()\n E, V = sparse_alg.eigsh(H.tocsr(), 1, which='SA')\n end = time.time()\n print('Solve EigenValue Cost = %s' % (end - start))\n print(E)\n", "step-3": "<mask token>\nL = 12\nNup = 6\nNdown = 6\nt = -2.0\nU = 10.0\nhoppings = [(i, j, t) for i in range(L) for j in range(L) if abs(i - j) == 1]\n\n\n@njit\ndef hammingWeight(n):\n res = 0\n for i in range(32):\n if n & 1 << i:\n res += 1\n return res\n\n\n@njit\ndef getStates():\n spinUpStates = [i for i in range(1 << L) if hammingWeight(i) == Nup]\n spinDownStates = [i for i in range(1 << L) if hammingWeight(i) == Ndown]\n states = [((spinUp << L) + spinDown) for spinUp in spinUpStates for\n spinDown in spinDownStates]\n return states\n\n\n@njit\ndef doubleOccNum(state):\n spinUpState = state >> L\n spinDownState = state & (1 << L) - 1\n return hammingWeight(spinUpState & spinDownState)\n\n\ndef Hamiltonian(states):\n n = len(states)\n H = sparse.lil_matrix((n, n))\n stateIdxMap = {}\n for i in range(n):\n stateIdxMap[states[i]] = i\n for i in range(n):\n H[i, i] = U * doubleOccNum(states[i])\n for a, b, t in hoppings:\n for s in range(2):\n if states[i] & 1 << s * L << b and not states[i\n ] & 1 << s * L << a:\n state = states[i] ^ 1 << s * L << b ^ 1 << s * L << a\n j = stateIdxMap[state]\n H[j, i] = t\n return H\n\n\nif __name__ == '__main__':\n start = time.time()\n states = getStates()\n end = time.time()\n print('Constructing State Cost = %s' % (end - start))\n start = time.time()\n H = Hamiltonian(states)\n end = time.time()\n print('Constructing Hamiltonian Cost = %s' % (end - start))\n start = time.time()\n E, V = sparse_alg.eigsh(H.tocsr(), 1, which='SA')\n end = time.time()\n print('Solve EigenValue Cost = %s' % (end - start))\n print(E)\n", "step-4": "import time\nfrom numba import njit\nimport scipy.sparse as sparse\nimport scipy.sparse.linalg as sparse_alg\nL = 12\nNup = 6\nNdown = 6\nt = -2.0\nU = 10.0\nhoppings = [(i, j, t) for i in range(L) for j in range(L) if abs(i - j) == 1]\n\n\n@njit\ndef hammingWeight(n):\n res = 0\n for i in range(32):\n if n & 1 << i:\n res += 1\n return res\n\n\n@njit\ndef getStates():\n spinUpStates = [i for i in range(1 << L) if hammingWeight(i) == Nup]\n spinDownStates = [i for i in range(1 << L) if hammingWeight(i) == Ndown]\n states = [((spinUp << L) + spinDown) for spinUp in spinUpStates for\n spinDown in spinDownStates]\n return states\n\n\n@njit\ndef doubleOccNum(state):\n spinUpState = state >> L\n spinDownState = state & (1 << L) - 1\n return hammingWeight(spinUpState & spinDownState)\n\n\ndef Hamiltonian(states):\n n = len(states)\n H = sparse.lil_matrix((n, n))\n stateIdxMap = {}\n for i in range(n):\n stateIdxMap[states[i]] = i\n for i in range(n):\n H[i, i] = U * doubleOccNum(states[i])\n for a, b, t in hoppings:\n for s in range(2):\n if states[i] & 1 << s * L << b and not states[i\n ] & 1 << s * L << a:\n state = states[i] ^ 1 << s * L << b ^ 1 << s * L << a\n j = stateIdxMap[state]\n H[j, i] = t\n return H\n\n\nif __name__ == '__main__':\n start = time.time()\n states = getStates()\n end = time.time()\n print('Constructing State Cost = %s' % (end - start))\n start = time.time()\n H = Hamiltonian(states)\n end = time.time()\n print('Constructing Hamiltonian Cost = %s' % (end - start))\n start = time.time()\n E, V = sparse_alg.eigsh(H.tocsr(), 1, which='SA')\n end = time.time()\n print('Solve EigenValue Cost = %s' % (end - start))\n print(E)\n", "step-5": "import time\n\nfrom numba import njit\nimport scipy.sparse as sparse\nimport scipy.sparse.linalg as sparse_alg\n\n\nL = 12\nNup = 6\nNdown = 6\nt = -2.0\nU = 10.0\nhoppings = [(i, j, t) for i in range(L) for j in range(L) if abs(i - j) == 1]\n\n@njit\ndef hammingWeight(n):\n res = 0\n for i in range(32):\n if n & (1 << i):\n res += 1\n return res\n\n@njit\ndef getStates():\n spinUpStates = [i for i in range(1 << L) if hammingWeight(i) == Nup]\n spinDownStates = [i for i in range(1 << L) if hammingWeight(i) == Ndown]\n states = [(spinUp << L) + (spinDown) for spinUp in spinUpStates for spinDown in spinDownStates]\n return states\n\n@njit\ndef doubleOccNum(state):\n spinUpState = state >> L\n spinDownState = state & ((1 << L) - 1)\n return hammingWeight(spinUpState & spinDownState)\n\n\ndef Hamiltonian(states):\n n = len(states)\n H = sparse.lil_matrix((n,n))\n stateIdxMap = {}\n for i in range(n):\n stateIdxMap[states[i]] = i\n for i in range(n):\n H[i, i] = U * doubleOccNum(states[i])\n for a, b, t in hoppings:\n for s in range(2):\n if (states[i] & (1 << (s * L) << b)) and not (states[i] & (1 << (s * L) << a)):\n state = states[i] ^ (1 << (s * L) << b) ^ (1 << (s * L) << a)\n j = stateIdxMap[state]\n H[j, i] = t\n return H\n\nif __name__ == '__main__':\n start = time.time()\n states = getStates()\n end = time.time()\n print(\"Constructing State Cost = %s\" % (end - start))\n\n start = time.time()\n H = Hamiltonian(states)\n end = time.time()\n print(\"Constructing Hamiltonian Cost = %s\" % (end - start))\n\n start = time.time()\n E,V=sparse_alg.eigsh(H.tocsr(),1,which='SA')\n end = time.time()\n print(\"Solve EigenValue Cost = %s\" % (end - start))\n print(E)\n \n\n\n\n\n\n\n\n\n\n\n", "step-ids": [ 4, 5, 6, 7, 8 ] }
[ 4, 5, 6, 7, 8 ]
<|reserved_special_token_0|> class Post(models.Model): class Meta: db_table = 'bl_post' <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> class Content(models.Model): class Meta: db_table = 'bl_content' post = models.OneToOneField(Post, to_field='id') content = models.TextField(null=False) def __repr__(self): return '<Content {} {} {} >'.format(self.id, self.post.id, self. content[:40]) __str__ = __repr__ <|reserved_special_token_1|> <|reserved_special_token_0|> class Post(models.Model): class Meta: db_table = 'bl_post' <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def __repr__(self): return '<Post {} {} {} {} [{}] >'.format(self.id, self.title, self. author, self.content, self.author.id) <|reserved_special_token_0|> class Content(models.Model): class Meta: db_table = 'bl_content' post = models.OneToOneField(Post, to_field='id') content = models.TextField(null=False) def __repr__(self): return '<Content {} {} {} >'.format(self.id, self.post.id, self. content[:40]) __str__ = __repr__ <|reserved_special_token_1|> <|reserved_special_token_0|> class Post(models.Model): class Meta: db_table = 'bl_post' id = models.AutoField(primary_key=True) title = models.CharField(max_length=200, null=False) pubdate = models.DateTimeField(null=False) author = models.ForeignKey(User) def __repr__(self): return '<Post {} {} {} {} [{}] >'.format(self.id, self.title, self. author, self.content, self.author.id) __str__ = __repr__ class Content(models.Model): class Meta: db_table = 'bl_content' post = models.OneToOneField(Post, to_field='id') content = models.TextField(null=False) def __repr__(self): return '<Content {} {} {} >'.format(self.id, self.post.id, self. content[:40]) __str__ = __repr__ <|reserved_special_token_1|> from django.db import models from user.models import User class Post(models.Model): class Meta: db_table = 'bl_post' id = models.AutoField(primary_key=True) title = models.CharField(max_length=200, null=False) pubdate = models.DateTimeField(null=False) author = models.ForeignKey(User) def __repr__(self): return '<Post {} {} {} {} [{}] >'.format(self.id, self.title, self. author, self.content, self.author.id) __str__ = __repr__ class Content(models.Model): class Meta: db_table = 'bl_content' post = models.OneToOneField(Post, to_field='id') content = models.TextField(null=False) def __repr__(self): return '<Content {} {} {} >'.format(self.id, self.post.id, self. content[:40]) __str__ = __repr__ <|reserved_special_token_1|> from django.db import models # Create your models here. from user.models import User class Post(models.Model): class Meta: db_table = 'bl_post' id = models.AutoField(primary_key=True) title = models.CharField(max_length=200, null=False) pubdate = models.DateTimeField(null=False) # 作者 # author_id = models.IntegerField(null=False) author = models.ForeignKey(User) # 内容 def __repr__(self): return "<Post {} {} {} {} [{}] >".format(self.id, self.title,self.author,self.content,self.author.id) __str__ = __repr__ class Content(models.Model): class Meta: db_table = 'bl_content' # id 可以不写,主键django帮你创建一个pk post = models.OneToOneField(Post, to_field='id') # post_id content = models.TextField(null=False) def __repr__(self): return "<Content {} {} {} >".format(self.id,self.post.id, self.content[:40]) __str__ = __repr__
flexible
{ "blob_id": "34a523b31e5567d2a8aec95c5820792d1ae80892", "index": 5335, "step-1": "<mask token>\n\n\nclass Post(models.Model):\n\n\n class Meta:\n db_table = 'bl_post'\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Content(models.Model):\n\n\n class Meta:\n db_table = 'bl_content'\n post = models.OneToOneField(Post, to_field='id')\n content = models.TextField(null=False)\n\n def __repr__(self):\n return '<Content {} {} {} >'.format(self.id, self.post.id, self.\n content[:40])\n __str__ = __repr__\n", "step-2": "<mask token>\n\n\nclass Post(models.Model):\n\n\n class Meta:\n db_table = 'bl_post'\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __repr__(self):\n return '<Post {} {} {} {} [{}] >'.format(self.id, self.title, self.\n author, self.content, self.author.id)\n <mask token>\n\n\nclass Content(models.Model):\n\n\n class Meta:\n db_table = 'bl_content'\n post = models.OneToOneField(Post, to_field='id')\n content = models.TextField(null=False)\n\n def __repr__(self):\n return '<Content {} {} {} >'.format(self.id, self.post.id, self.\n content[:40])\n __str__ = __repr__\n", "step-3": "<mask token>\n\n\nclass Post(models.Model):\n\n\n class Meta:\n db_table = 'bl_post'\n id = models.AutoField(primary_key=True)\n title = models.CharField(max_length=200, null=False)\n pubdate = models.DateTimeField(null=False)\n author = models.ForeignKey(User)\n\n def __repr__(self):\n return '<Post {} {} {} {} [{}] >'.format(self.id, self.title, self.\n author, self.content, self.author.id)\n __str__ = __repr__\n\n\nclass Content(models.Model):\n\n\n class Meta:\n db_table = 'bl_content'\n post = models.OneToOneField(Post, to_field='id')\n content = models.TextField(null=False)\n\n def __repr__(self):\n return '<Content {} {} {} >'.format(self.id, self.post.id, self.\n content[:40])\n __str__ = __repr__\n", "step-4": "from django.db import models\nfrom user.models import User\n\n\nclass Post(models.Model):\n\n\n class Meta:\n db_table = 'bl_post'\n id = models.AutoField(primary_key=True)\n title = models.CharField(max_length=200, null=False)\n pubdate = models.DateTimeField(null=False)\n author = models.ForeignKey(User)\n\n def __repr__(self):\n return '<Post {} {} {} {} [{}] >'.format(self.id, self.title, self.\n author, self.content, self.author.id)\n __str__ = __repr__\n\n\nclass Content(models.Model):\n\n\n class Meta:\n db_table = 'bl_content'\n post = models.OneToOneField(Post, to_field='id')\n content = models.TextField(null=False)\n\n def __repr__(self):\n return '<Content {} {} {} >'.format(self.id, self.post.id, self.\n content[:40])\n __str__ = __repr__\n", "step-5": "from django.db import models\n\n# Create your models here.\nfrom user.models import User\n\n\nclass Post(models.Model):\n class Meta:\n db_table = 'bl_post'\n\n id = models.AutoField(primary_key=True)\n title = models.CharField(max_length=200, null=False)\n pubdate = models.DateTimeField(null=False)\n # 作者\n # author_id = models.IntegerField(null=False)\n author = models.ForeignKey(User)\n\n # 内容\n\n def __repr__(self):\n return \"<Post {} {} {} {} [{}] >\".format(self.id, self.title,self.author,self.content,self.author.id)\n\n __str__ = __repr__\n\n\nclass Content(models.Model):\n class Meta:\n db_table = 'bl_content'\n\n # id 可以不写,主键django帮你创建一个pk\n post = models.OneToOneField(Post, to_field='id') # post_id\n content = models.TextField(null=False)\n\n def __repr__(self):\n return \"<Content {} {} {} >\".format(self.id,self.post.id, self.content[:40])\n\n __str__ = __repr__\n", "step-ids": [ 4, 5, 6, 7, 8 ] }
[ 4, 5, 6, 7, 8 ]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 26 18:39:26 2020 @author: Fanny Fredriksson and Karen Marie Sandø Ambrosen """ import numpy as np import matplotlib.pyplot as plt import pandas as pd from tqdm import tqdm #count ffor loops import math from sklearn.model_selection import GridSearchCV, StratifiedKFold from sklearn import preprocessing from sklearn.utils import shuffle from sklearn.linear_model import Lasso from utils_runOnce_classification import getEgillX, getEgillParameters from utils_runOnce_classification import significant_connected_areasBAitaSigX, getBAitaSigParameters, getBAitaParameters import seaborn as sns from utils_joint import getNewestFolderDate, get_Xy import pdb #{} #[] ############################################################################## def leaveKout_CV(X, y, n_scz_te, rep, perms, classifiers, parameters, count, freq_bands, x_size, auc, nz_coef_idx, nz_coef_val, n_BAitaSig = None): """ Calculates the leave K out cross validation. Parameters ---------- X : array of arrays Matrix containing a vector with all the features for each subject. Dimension (number of subjects)x(number of features). y : array A vector containing the class-information. Remember: 1 = healty controls, 0 = schizophrenic n_scz_te : int Desired number of schizophrenic patients in each test set. rep : integer The number of repition that has been used so far. perms : range(*) Range with desired number (*) of permutations. *=1 indicates no permutations. classifiers : dictionary Dictionary containing classifiers. E.g. {'lasso' : Lasso(max_iter = 10000)} parameters : dictionary Dictionary containing parameters to the classifiers as in "classifiers" count : integer Used to know how many loops that have been made due to the pre allocated space for AUC. freq_bands : list of strings Either ['all'] or ['detla','theta','alpha','beta1','beta2','gamma']. x_size : integer The size each X has which changes depending on freq_bands. auc : dictionary Contains the auc-scores for each loop, either divided into bands or with the key "all". nz_coef_idx : dictionary Contains the non-zero coefficient indices for each loop, either divided into bands or with the key "all". nz_coef_val : dictionary Contains the non-zero coefficient values (the weights) for each loop, either divided into bands or with the key "all". n_BAitaSig : list of integers, optional The number of connections in each band when BAitaSig is used. The default is None. Returns ------- auc : dictionary Contains the updated auc-scores for each loop, either divided into bands or with the key "all". nz_coef_idx : dictionary Contains the updated non-zero coefficient indices for each loop, either divided into bands or with the key "all". nz_coef_val : dictionary Contains the updated non-zero coefficient values (the weights) for each loop, either divided into bands or with the key "all". count : integer Used to know how many loops that have been made due to the pre allocated space for AUC. """ skf = StratifiedKFold(n_splits=int(sum(y==0)//n_scz_te),shuffle=True, random_state = rep) count_plt = 0 fig, ax = plt.subplots(2,3 , figsize=(10,6.5)) for tr_idx, te_idx in skf.split(X,y): # Compute test and train targets y_tr = np.ravel(y[tr_idx]) y_te = np.ravel(y[te_idx]) # Make gridsearch function clf_name = list(classifiers.keys())[0] count += 1 sns.set(font_scale=1.5) for i in range(1): #range(len(freq_bands)): if count_plt == 6: plt.suptitle('Example of line search for the regularization parameter', fontsize= 18) plt.tight_layout() plt.subplots_adjust(top = 0.84, bottom = 0.15, hspace = 0.5, wspace = 0.45) fig.legend(['Train', 'Validation'], bbox_to_anchor = (0.5, 0.89), borderaxespad = 0., loc = 'upper center', ncol = 2) plt.show() fig.savefig('/share/FannyMaster/PythonNew/Figures/LineSearchEx.jpg', bbox_inches = 'tight') sns.reset_orig() raise NameError('This is just a dumb way of stopping the code after 6 iterations') i = 1 clf = GridSearchCV(classifiers[clf_name], {'alpha' :parameters[freq_bands[i]]}, cv = StratifiedKFold(n_splits = int(sum(y_tr==0)//n_scz_te)), scoring = 'roc_auc', n_jobs = -1, return_train_score=True) # Compute test and train sets if n_BAitaSig == None: X_tr = X[tr_idx, x_size*i:x_size*(i+1)] X_te = X[te_idx, x_size*i:x_size*(i+1)] else: if x_size == sum(n_BAitaSig): X_tr = X[tr_idx, :] X_te = X[te_idx, :] else: n_temp = [0] n_temp.extend(np.cumsum(n_BAitaSig)) X_tr = X[tr_idx, n_temp[i]:n_temp[i+1]] X_te = X[te_idx, n_temp[i]:n_temp[i+1]] # Standardize scaler_out = preprocessing.StandardScaler().fit(X_tr) X_tr = scaler_out.transform(X_tr) X_te = scaler_out.transform(X_te) # Fit data and save auc scores fit = clf.fit(X_tr, y_tr) auc[freq_bands[i]][count] = fit.score(X_te, y_te) # Make parameter plot #plot_grid_search(clf.cv_results_, 'score', parameters[freq_bands[i]], 'log($\lambda$) ' + freq_bands[i]) cv_results = clf.cv_results_ metric = 'score' grid_param_1 = parameters[freq_bands[i]] scores_mean = cv_results[('mean_test_' + metric)] # scores_sd = cv_results[('std_test_' + metric)] scores_mean_tr = cv_results[('mean_train_' + metric)] # Set plot style #plt.style.use('seaborn') # Plot Grid search scores sns.set(font_scale=1.5) df1 = pd.DataFrame({'log($\lambda$)':[math.log(i) for i in grid_param_1], 'CV Average AUC' : scores_mean_tr, 'type' : ['train']*len(scores_mean_tr)}) df2 = pd.DataFrame({'log($\lambda$)':[math.log(i) for i in grid_param_1], 'CV Average AUC' : scores_mean, 'type' : ['test']*len(scores_mean_tr)}) sns.lineplot(x = 'log($\lambda$)', y = 'CV Average AUC', style='type', legend = False, markers = "o", data = df1, ax = ax[count_plt//3][count_plt%3]) sns.lineplot(x = 'log($\lambda$)', y = 'CV Average AUC', style='type', legend = False, markers = "o", data = df2, ax = ax[count_plt//3][count_plt%3]) ax[count_plt//3][count_plt%3].set_xlabel('log($\lambda$)', fontsize=14) ax[count_plt//3][count_plt%3].set_ylabel('CV Average AUC' , fontsize=14) #pprint(clf.cv_results_) #pdb.set_trace() # Type "exit" to get out, type "c" to continue count_plt += 1 if len(perms) == 1: coef_idx = np.nonzero(fit.best_estimator_.coef_) nz_coef_idx[freq_bands[i]].append(coef_idx) nz_coef_val[freq_bands[i]].append(fit.best_estimator_.coef_[coef_idx]) return auc, nz_coef_idx, nz_coef_val, count ############################################################################## def CV_classifier(X, y, n_scz_te, reps, separate_bands, perms, dir_save, classifiers, parameters, n_BAitaSig = None): """ Parameters ---------- X : np.array Matrix with dimension (subjects)x(feature vector). y : np.array Vector with classifications (0: healthy, 1: schizo). n_scz_te : int Desired number of schizophrenic patients in each test set. reps : range(*) Range with desired number (*) of extra times the code should run. separate_bands : boolean True = seperate data into frequency bands. False = don't separate. perms : range(*) Range with desired number (*) of permutations. *=1 indicates no permutations. dir_save : string Directory path to where the results should be saved. classifiers : dictionary Dictionary containing classifiers. E.g. {'lasso' : Lasso(max_iter = 10000)} parameters : dictionary Dictionary containing parameters to the classifiers as in "classifiers" Notes ------- Saves three different values in the dir_save path: auc : dictionary Contains the auc-scores for each loop, either divided into bands or with the key "all". nz_coef_idx : dictionary Contains the non-zero coefficient indices for each loop, either divided into bands or with the key "all". nz_coef_val : dictionary Contains the non-zero coefficient values (the weights) for each loop, either divided into bands or with the key "all". """ # Check if data should be seperated into bands or not: if separate_bands: freq_bands = ['delta', 'theta', 'alpha', 'beta1', 'beta2', 'gamma'] else: freq_bands = ['all'] if len(perms) > 1: y_org = y tqdm_perms = tqdm(perms) tqdm_reps = reps else: tqdm_perms = perms tqdm_reps = tqdm(reps) # Initialize space for values auc = {} nz_coef_idx= {} nz_coef_val= {} nb_loops = len(reps)*(sum(y==0)//n_scz_te)*len(perms) # Define the size of X x_size = int(X.shape[1]/len(freq_bands)) for i in freq_bands: auc[i] = np.zeros(nb_loops) # e.g. auc = {'delta':[] , 'theta': [], 'alpha': [], ....} nz_coef_idx[i] = [] nz_coef_val[i] = [] count = -1 for perm in tqdm_perms: if len(perms) > 1: y = shuffle(y_org, random_state=perm).reset_index(drop=True) for rep in tqdm_reps: auc, nz_coef_idx, nz_coef_val, count = leaveKout_CV(X, y, n_scz_te, rep, perms, classifiers, parameters, count, freq_bands, x_size, auc, nz_coef_idx, nz_coef_val, n_BAitaSig) #%% con_type = 'lps' separate_bands = True # False = All bands together partialData = True atlas = 'BAita' # DKEgill, BAita, BAitaSig sns.set(font_scale=1.5) freq_band_type = 'DiLorenzo' # Directories dir_folders = r'/share/FannyMaster/PythonNew/' + atlas + '_timeseries_' newest_date = getNewestFolderDate(dir_folders) dir_features = dir_folders + newest_date + '/' + freq_band_type + '/Features' dir_y_ID = r'/share/FannyMaster/PythonNew/Age_Gender.csv' n_scz_te = 2 reps = range(1) classifiers = {'lasso' : Lasso(max_iter = 10000)} dir_save = dir_folders + newest_date + '/' + freq_band_type + '/classificationResults/' + con_type.capitalize() X,y = get_Xy(dir_features, dir_y_ID, con_type, partialData) if atlas == 'DKEgill': X = getEgillX(X) n_BAitaSig = None parameters = getEgillParameters(con_type, separate_bands) elif atlas == 'BAitaSig': X, n_BAitaSig = significant_connected_areasBAitaSigX(X) parameters = getBAitaSigParameters(con_type, separate_bands) elif atlas == 'BAita': parameters = getBAitaParameters(con_type, separate_bands) n_BAitaSig = None perms = range(1) # 1 = No permutations CV_classifier(X, y, n_scz_te, reps, separate_bands, perms, dir_save, classifiers, parameters)
normal
{ "blob_id": "69511933697905fb4f365c895264596f19dc1d8d", "index": 5021, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef leaveKout_CV(X, y, n_scz_te, rep, perms, classifiers, parameters, count,\n freq_bands, x_size, auc, nz_coef_idx, nz_coef_val, n_BAitaSig=None):\n \"\"\"\n Calculates the leave K out cross validation. \n\n Parameters\n ----------\n X : array of arrays\n Matrix containing a vector with all the features for each subject.\n Dimension (number of subjects)x(number of features).\n y : array\n A vector containing the class-information. \n Remember: 1 = healty controls, 0 = schizophrenic \n n_scz_te : int\n Desired number of schizophrenic patients in each test set.\n rep : integer\n The number of repition that has been used so far.\n perms : range(*)\n Range with desired number (*) of permutations. \n *=1 indicates no permutations.\n classifiers : dictionary\n Dictionary containing classifiers. E.g. {'lasso' : Lasso(max_iter = 10000)}\n parameters : dictionary\n Dictionary containing parameters to the classifiers as in \"classifiers\"\n count : integer\n Used to know how many loops that have been made due to the pre \n allocated space for AUC.\n freq_bands : list of strings\n Either ['all'] or ['detla','theta','alpha','beta1','beta2','gamma'].\n x_size : integer\n The size each X has which changes depending on freq_bands.\n auc : dictionary\n Contains the auc-scores for each loop, either divided into bands or \n with the key \"all\".\n nz_coef_idx : dictionary\n Contains the non-zero coefficient indices for each loop, either \n divided into bands or with the key \"all\".\n nz_coef_val : dictionary\n Contains the non-zero coefficient values (the weights) for each \n loop, either divided into bands or with the key \"all\".\n n_BAitaSig : list of integers, optional\n The number of connections in each band when BAitaSig is used. \n The default is None.\n Returns\n -------\n auc : dictionary\n Contains the updated auc-scores for each loop, either divided into \n bands or with the key \"all\".\n nz_coef_idx : dictionary\n Contains the updated non-zero coefficient indices for each loop, \n either divided into bands or with the key \"all\".\n nz_coef_val : dictionary\n Contains the updated non-zero coefficient values (the weights) for \n each loop, either divided into bands or with the key \"all\".\n count : integer\n Used to know how many loops that have been made due to the pre \n allocated space for AUC.\n\n \"\"\"\n skf = StratifiedKFold(n_splits=int(sum(y == 0) // n_scz_te), shuffle=\n True, random_state=rep)\n count_plt = 0\n fig, ax = plt.subplots(2, 3, figsize=(10, 6.5))\n for tr_idx, te_idx in skf.split(X, y):\n y_tr = np.ravel(y[tr_idx])\n y_te = np.ravel(y[te_idx])\n clf_name = list(classifiers.keys())[0]\n count += 1\n sns.set(font_scale=1.5)\n for i in range(1):\n if count_plt == 6:\n plt.suptitle(\n 'Example of line search for the regularization parameter',\n fontsize=18)\n plt.tight_layout()\n plt.subplots_adjust(top=0.84, bottom=0.15, hspace=0.5,\n wspace=0.45)\n fig.legend(['Train', 'Validation'], bbox_to_anchor=(0.5, \n 0.89), borderaxespad=0.0, loc='upper center', ncol=2)\n plt.show()\n fig.savefig(\n '/share/FannyMaster/PythonNew/Figures/LineSearchEx.jpg',\n bbox_inches='tight')\n sns.reset_orig()\n raise NameError(\n 'This is just a dumb way of stopping the code after 6 iterations'\n )\n i = 1\n clf = GridSearchCV(classifiers[clf_name], {'alpha': parameters[\n freq_bands[i]]}, cv=StratifiedKFold(n_splits=int(sum(y_tr ==\n 0) // n_scz_te)), scoring='roc_auc', n_jobs=-1,\n return_train_score=True)\n if n_BAitaSig == None:\n X_tr = X[tr_idx, x_size * i:x_size * (i + 1)]\n X_te = X[te_idx, x_size * i:x_size * (i + 1)]\n elif x_size == sum(n_BAitaSig):\n X_tr = X[tr_idx, :]\n X_te = X[te_idx, :]\n else:\n n_temp = [0]\n n_temp.extend(np.cumsum(n_BAitaSig))\n X_tr = X[tr_idx, n_temp[i]:n_temp[i + 1]]\n X_te = X[te_idx, n_temp[i]:n_temp[i + 1]]\n scaler_out = preprocessing.StandardScaler().fit(X_tr)\n X_tr = scaler_out.transform(X_tr)\n X_te = scaler_out.transform(X_te)\n fit = clf.fit(X_tr, y_tr)\n auc[freq_bands[i]][count] = fit.score(X_te, y_te)\n cv_results = clf.cv_results_\n metric = 'score'\n grid_param_1 = parameters[freq_bands[i]]\n scores_mean = cv_results['mean_test_' + metric]\n scores_mean_tr = cv_results['mean_train_' + metric]\n sns.set(font_scale=1.5)\n df1 = pd.DataFrame({'log($\\\\lambda$)': [math.log(i) for i in\n grid_param_1], 'CV Average AUC': scores_mean_tr, 'type': [\n 'train'] * len(scores_mean_tr)})\n df2 = pd.DataFrame({'log($\\\\lambda$)': [math.log(i) for i in\n grid_param_1], 'CV Average AUC': scores_mean, 'type': [\n 'test'] * len(scores_mean_tr)})\n sns.lineplot(x='log($\\\\lambda$)', y='CV Average AUC', style=\n 'type', legend=False, markers='o', data=df1, ax=ax[\n count_plt // 3][count_plt % 3])\n sns.lineplot(x='log($\\\\lambda$)', y='CV Average AUC', style=\n 'type', legend=False, markers='o', data=df2, ax=ax[\n count_plt // 3][count_plt % 3])\n ax[count_plt // 3][count_plt % 3].set_xlabel('log($\\\\lambda$)',\n fontsize=14)\n ax[count_plt // 3][count_plt % 3].set_ylabel('CV Average AUC',\n fontsize=14)\n count_plt += 1\n if len(perms) == 1:\n coef_idx = np.nonzero(fit.best_estimator_.coef_)\n nz_coef_idx[freq_bands[i]].append(coef_idx)\n nz_coef_val[freq_bands[i]].append(fit.best_estimator_.coef_\n [coef_idx])\n return auc, nz_coef_idx, nz_coef_val, count\n\n\ndef CV_classifier(X, y, n_scz_te, reps, separate_bands, perms, dir_save,\n classifiers, parameters, n_BAitaSig=None):\n \"\"\"\n Parameters\n ----------\n X : np.array \n Matrix with dimension (subjects)x(feature vector).\n y : np.array\n Vector with classifications (0: healthy, 1: schizo).\n n_scz_te : int\n Desired number of schizophrenic patients in each test set.\n reps : range(*)\n Range with desired number (*) of extra times the code should run.\n separate_bands : boolean\n True = seperate data into frequency bands. False = don't separate.\n perms : range(*)\n Range with desired number (*) of permutations. \n *=1 indicates no permutations.\n dir_save : string\n Directory path to where the results should be saved.\n classifiers : dictionary\n Dictionary containing classifiers. E.g. {'lasso' : Lasso(max_iter = 10000)}\n parameters : dictionary\n Dictionary containing parameters to the classifiers as in \"classifiers\"\n\n Notes\n -------\n Saves three different values in the dir_save path: \n auc : dictionary\n Contains the auc-scores for each loop, either divided into bands or \n with the key \"all\".\n nz_coef_idx : dictionary\n Contains the non-zero coefficient indices for each loop, either \n divided into bands or with the key \"all\".\n nz_coef_val : dictionary\n Contains the non-zero coefficient values (the weights) for each \n loop, either divided into bands or with the key \"all\".\n \n \"\"\"\n if separate_bands:\n freq_bands = ['delta', 'theta', 'alpha', 'beta1', 'beta2', 'gamma']\n else:\n freq_bands = ['all']\n if len(perms) > 1:\n y_org = y\n tqdm_perms = tqdm(perms)\n tqdm_reps = reps\n else:\n tqdm_perms = perms\n tqdm_reps = tqdm(reps)\n auc = {}\n nz_coef_idx = {}\n nz_coef_val = {}\n nb_loops = len(reps) * (sum(y == 0) // n_scz_te) * len(perms)\n x_size = int(X.shape[1] / len(freq_bands))\n for i in freq_bands:\n auc[i] = np.zeros(nb_loops)\n nz_coef_idx[i] = []\n nz_coef_val[i] = []\n count = -1\n for perm in tqdm_perms:\n if len(perms) > 1:\n y = shuffle(y_org, random_state=perm).reset_index(drop=True)\n for rep in tqdm_reps:\n auc, nz_coef_idx, nz_coef_val, count = leaveKout_CV(X, y,\n n_scz_te, rep, perms, classifiers, parameters, count,\n freq_bands, x_size, auc, nz_coef_idx, nz_coef_val, n_BAitaSig)\n\n\n<mask token>\nsns.set(font_scale=1.5)\n<mask token>\nif atlas == 'DKEgill':\n X = getEgillX(X)\n n_BAitaSig = None\n parameters = getEgillParameters(con_type, separate_bands)\nelif atlas == 'BAitaSig':\n X, n_BAitaSig = significant_connected_areasBAitaSigX(X)\n parameters = getBAitaSigParameters(con_type, separate_bands)\nelif atlas == 'BAita':\n parameters = getBAitaParameters(con_type, separate_bands)\n n_BAitaSig = None\n<mask token>\nCV_classifier(X, y, n_scz_te, reps, separate_bands, perms, dir_save,\n classifiers, parameters)\n", "step-3": "<mask token>\n\n\ndef leaveKout_CV(X, y, n_scz_te, rep, perms, classifiers, parameters, count,\n freq_bands, x_size, auc, nz_coef_idx, nz_coef_val, n_BAitaSig=None):\n \"\"\"\n Calculates the leave K out cross validation. \n\n Parameters\n ----------\n X : array of arrays\n Matrix containing a vector with all the features for each subject.\n Dimension (number of subjects)x(number of features).\n y : array\n A vector containing the class-information. \n Remember: 1 = healty controls, 0 = schizophrenic \n n_scz_te : int\n Desired number of schizophrenic patients in each test set.\n rep : integer\n The number of repition that has been used so far.\n perms : range(*)\n Range with desired number (*) of permutations. \n *=1 indicates no permutations.\n classifiers : dictionary\n Dictionary containing classifiers. E.g. {'lasso' : Lasso(max_iter = 10000)}\n parameters : dictionary\n Dictionary containing parameters to the classifiers as in \"classifiers\"\n count : integer\n Used to know how many loops that have been made due to the pre \n allocated space for AUC.\n freq_bands : list of strings\n Either ['all'] or ['detla','theta','alpha','beta1','beta2','gamma'].\n x_size : integer\n The size each X has which changes depending on freq_bands.\n auc : dictionary\n Contains the auc-scores for each loop, either divided into bands or \n with the key \"all\".\n nz_coef_idx : dictionary\n Contains the non-zero coefficient indices for each loop, either \n divided into bands or with the key \"all\".\n nz_coef_val : dictionary\n Contains the non-zero coefficient values (the weights) for each \n loop, either divided into bands or with the key \"all\".\n n_BAitaSig : list of integers, optional\n The number of connections in each band when BAitaSig is used. \n The default is None.\n Returns\n -------\n auc : dictionary\n Contains the updated auc-scores for each loop, either divided into \n bands or with the key \"all\".\n nz_coef_idx : dictionary\n Contains the updated non-zero coefficient indices for each loop, \n either divided into bands or with the key \"all\".\n nz_coef_val : dictionary\n Contains the updated non-zero coefficient values (the weights) for \n each loop, either divided into bands or with the key \"all\".\n count : integer\n Used to know how many loops that have been made due to the pre \n allocated space for AUC.\n\n \"\"\"\n skf = StratifiedKFold(n_splits=int(sum(y == 0) // n_scz_te), shuffle=\n True, random_state=rep)\n count_plt = 0\n fig, ax = plt.subplots(2, 3, figsize=(10, 6.5))\n for tr_idx, te_idx in skf.split(X, y):\n y_tr = np.ravel(y[tr_idx])\n y_te = np.ravel(y[te_idx])\n clf_name = list(classifiers.keys())[0]\n count += 1\n sns.set(font_scale=1.5)\n for i in range(1):\n if count_plt == 6:\n plt.suptitle(\n 'Example of line search for the regularization parameter',\n fontsize=18)\n plt.tight_layout()\n plt.subplots_adjust(top=0.84, bottom=0.15, hspace=0.5,\n wspace=0.45)\n fig.legend(['Train', 'Validation'], bbox_to_anchor=(0.5, \n 0.89), borderaxespad=0.0, loc='upper center', ncol=2)\n plt.show()\n fig.savefig(\n '/share/FannyMaster/PythonNew/Figures/LineSearchEx.jpg',\n bbox_inches='tight')\n sns.reset_orig()\n raise NameError(\n 'This is just a dumb way of stopping the code after 6 iterations'\n )\n i = 1\n clf = GridSearchCV(classifiers[clf_name], {'alpha': parameters[\n freq_bands[i]]}, cv=StratifiedKFold(n_splits=int(sum(y_tr ==\n 0) // n_scz_te)), scoring='roc_auc', n_jobs=-1,\n return_train_score=True)\n if n_BAitaSig == None:\n X_tr = X[tr_idx, x_size * i:x_size * (i + 1)]\n X_te = X[te_idx, x_size * i:x_size * (i + 1)]\n elif x_size == sum(n_BAitaSig):\n X_tr = X[tr_idx, :]\n X_te = X[te_idx, :]\n else:\n n_temp = [0]\n n_temp.extend(np.cumsum(n_BAitaSig))\n X_tr = X[tr_idx, n_temp[i]:n_temp[i + 1]]\n X_te = X[te_idx, n_temp[i]:n_temp[i + 1]]\n scaler_out = preprocessing.StandardScaler().fit(X_tr)\n X_tr = scaler_out.transform(X_tr)\n X_te = scaler_out.transform(X_te)\n fit = clf.fit(X_tr, y_tr)\n auc[freq_bands[i]][count] = fit.score(X_te, y_te)\n cv_results = clf.cv_results_\n metric = 'score'\n grid_param_1 = parameters[freq_bands[i]]\n scores_mean = cv_results['mean_test_' + metric]\n scores_mean_tr = cv_results['mean_train_' + metric]\n sns.set(font_scale=1.5)\n df1 = pd.DataFrame({'log($\\\\lambda$)': [math.log(i) for i in\n grid_param_1], 'CV Average AUC': scores_mean_tr, 'type': [\n 'train'] * len(scores_mean_tr)})\n df2 = pd.DataFrame({'log($\\\\lambda$)': [math.log(i) for i in\n grid_param_1], 'CV Average AUC': scores_mean, 'type': [\n 'test'] * len(scores_mean_tr)})\n sns.lineplot(x='log($\\\\lambda$)', y='CV Average AUC', style=\n 'type', legend=False, markers='o', data=df1, ax=ax[\n count_plt // 3][count_plt % 3])\n sns.lineplot(x='log($\\\\lambda$)', y='CV Average AUC', style=\n 'type', legend=False, markers='o', data=df2, ax=ax[\n count_plt // 3][count_plt % 3])\n ax[count_plt // 3][count_plt % 3].set_xlabel('log($\\\\lambda$)',\n fontsize=14)\n ax[count_plt // 3][count_plt % 3].set_ylabel('CV Average AUC',\n fontsize=14)\n count_plt += 1\n if len(perms) == 1:\n coef_idx = np.nonzero(fit.best_estimator_.coef_)\n nz_coef_idx[freq_bands[i]].append(coef_idx)\n nz_coef_val[freq_bands[i]].append(fit.best_estimator_.coef_\n [coef_idx])\n return auc, nz_coef_idx, nz_coef_val, count\n\n\ndef CV_classifier(X, y, n_scz_te, reps, separate_bands, perms, dir_save,\n classifiers, parameters, n_BAitaSig=None):\n \"\"\"\n Parameters\n ----------\n X : np.array \n Matrix with dimension (subjects)x(feature vector).\n y : np.array\n Vector with classifications (0: healthy, 1: schizo).\n n_scz_te : int\n Desired number of schizophrenic patients in each test set.\n reps : range(*)\n Range with desired number (*) of extra times the code should run.\n separate_bands : boolean\n True = seperate data into frequency bands. False = don't separate.\n perms : range(*)\n Range with desired number (*) of permutations. \n *=1 indicates no permutations.\n dir_save : string\n Directory path to where the results should be saved.\n classifiers : dictionary\n Dictionary containing classifiers. E.g. {'lasso' : Lasso(max_iter = 10000)}\n parameters : dictionary\n Dictionary containing parameters to the classifiers as in \"classifiers\"\n\n Notes\n -------\n Saves three different values in the dir_save path: \n auc : dictionary\n Contains the auc-scores for each loop, either divided into bands or \n with the key \"all\".\n nz_coef_idx : dictionary\n Contains the non-zero coefficient indices for each loop, either \n divided into bands or with the key \"all\".\n nz_coef_val : dictionary\n Contains the non-zero coefficient values (the weights) for each \n loop, either divided into bands or with the key \"all\".\n \n \"\"\"\n if separate_bands:\n freq_bands = ['delta', 'theta', 'alpha', 'beta1', 'beta2', 'gamma']\n else:\n freq_bands = ['all']\n if len(perms) > 1:\n y_org = y\n tqdm_perms = tqdm(perms)\n tqdm_reps = reps\n else:\n tqdm_perms = perms\n tqdm_reps = tqdm(reps)\n auc = {}\n nz_coef_idx = {}\n nz_coef_val = {}\n nb_loops = len(reps) * (sum(y == 0) // n_scz_te) * len(perms)\n x_size = int(X.shape[1] / len(freq_bands))\n for i in freq_bands:\n auc[i] = np.zeros(nb_loops)\n nz_coef_idx[i] = []\n nz_coef_val[i] = []\n count = -1\n for perm in tqdm_perms:\n if len(perms) > 1:\n y = shuffle(y_org, random_state=perm).reset_index(drop=True)\n for rep in tqdm_reps:\n auc, nz_coef_idx, nz_coef_val, count = leaveKout_CV(X, y,\n n_scz_te, rep, perms, classifiers, parameters, count,\n freq_bands, x_size, auc, nz_coef_idx, nz_coef_val, n_BAitaSig)\n\n\ncon_type = 'lps'\nseparate_bands = True\npartialData = True\natlas = 'BAita'\nsns.set(font_scale=1.5)\nfreq_band_type = 'DiLorenzo'\ndir_folders = '/share/FannyMaster/PythonNew/' + atlas + '_timeseries_'\nnewest_date = getNewestFolderDate(dir_folders)\ndir_features = dir_folders + newest_date + '/' + freq_band_type + '/Features'\ndir_y_ID = '/share/FannyMaster/PythonNew/Age_Gender.csv'\nn_scz_te = 2\nreps = range(1)\nclassifiers = {'lasso': Lasso(max_iter=10000)}\ndir_save = (dir_folders + newest_date + '/' + freq_band_type +\n '/classificationResults/' + con_type.capitalize())\nX, y = get_Xy(dir_features, dir_y_ID, con_type, partialData)\nif atlas == 'DKEgill':\n X = getEgillX(X)\n n_BAitaSig = None\n parameters = getEgillParameters(con_type, separate_bands)\nelif atlas == 'BAitaSig':\n X, n_BAitaSig = significant_connected_areasBAitaSigX(X)\n parameters = getBAitaSigParameters(con_type, separate_bands)\nelif atlas == 'BAita':\n parameters = getBAitaParameters(con_type, separate_bands)\n n_BAitaSig = None\nperms = range(1)\nCV_classifier(X, y, n_scz_te, reps, separate_bands, perms, dir_save,\n classifiers, parameters)\n", "step-4": "<mask token>\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom tqdm import tqdm\nimport math\nfrom sklearn.model_selection import GridSearchCV, StratifiedKFold\nfrom sklearn import preprocessing\nfrom sklearn.utils import shuffle\nfrom sklearn.linear_model import Lasso\nfrom utils_runOnce_classification import getEgillX, getEgillParameters\nfrom utils_runOnce_classification import significant_connected_areasBAitaSigX, getBAitaSigParameters, getBAitaParameters\nimport seaborn as sns\nfrom utils_joint import getNewestFolderDate, get_Xy\nimport pdb\n\n\ndef leaveKout_CV(X, y, n_scz_te, rep, perms, classifiers, parameters, count,\n freq_bands, x_size, auc, nz_coef_idx, nz_coef_val, n_BAitaSig=None):\n \"\"\"\n Calculates the leave K out cross validation. \n\n Parameters\n ----------\n X : array of arrays\n Matrix containing a vector with all the features for each subject.\n Dimension (number of subjects)x(number of features).\n y : array\n A vector containing the class-information. \n Remember: 1 = healty controls, 0 = schizophrenic \n n_scz_te : int\n Desired number of schizophrenic patients in each test set.\n rep : integer\n The number of repition that has been used so far.\n perms : range(*)\n Range with desired number (*) of permutations. \n *=1 indicates no permutations.\n classifiers : dictionary\n Dictionary containing classifiers. E.g. {'lasso' : Lasso(max_iter = 10000)}\n parameters : dictionary\n Dictionary containing parameters to the classifiers as in \"classifiers\"\n count : integer\n Used to know how many loops that have been made due to the pre \n allocated space for AUC.\n freq_bands : list of strings\n Either ['all'] or ['detla','theta','alpha','beta1','beta2','gamma'].\n x_size : integer\n The size each X has which changes depending on freq_bands.\n auc : dictionary\n Contains the auc-scores for each loop, either divided into bands or \n with the key \"all\".\n nz_coef_idx : dictionary\n Contains the non-zero coefficient indices for each loop, either \n divided into bands or with the key \"all\".\n nz_coef_val : dictionary\n Contains the non-zero coefficient values (the weights) for each \n loop, either divided into bands or with the key \"all\".\n n_BAitaSig : list of integers, optional\n The number of connections in each band when BAitaSig is used. \n The default is None.\n Returns\n -------\n auc : dictionary\n Contains the updated auc-scores for each loop, either divided into \n bands or with the key \"all\".\n nz_coef_idx : dictionary\n Contains the updated non-zero coefficient indices for each loop, \n either divided into bands or with the key \"all\".\n nz_coef_val : dictionary\n Contains the updated non-zero coefficient values (the weights) for \n each loop, either divided into bands or with the key \"all\".\n count : integer\n Used to know how many loops that have been made due to the pre \n allocated space for AUC.\n\n \"\"\"\n skf = StratifiedKFold(n_splits=int(sum(y == 0) // n_scz_te), shuffle=\n True, random_state=rep)\n count_plt = 0\n fig, ax = plt.subplots(2, 3, figsize=(10, 6.5))\n for tr_idx, te_idx in skf.split(X, y):\n y_tr = np.ravel(y[tr_idx])\n y_te = np.ravel(y[te_idx])\n clf_name = list(classifiers.keys())[0]\n count += 1\n sns.set(font_scale=1.5)\n for i in range(1):\n if count_plt == 6:\n plt.suptitle(\n 'Example of line search for the regularization parameter',\n fontsize=18)\n plt.tight_layout()\n plt.subplots_adjust(top=0.84, bottom=0.15, hspace=0.5,\n wspace=0.45)\n fig.legend(['Train', 'Validation'], bbox_to_anchor=(0.5, \n 0.89), borderaxespad=0.0, loc='upper center', ncol=2)\n plt.show()\n fig.savefig(\n '/share/FannyMaster/PythonNew/Figures/LineSearchEx.jpg',\n bbox_inches='tight')\n sns.reset_orig()\n raise NameError(\n 'This is just a dumb way of stopping the code after 6 iterations'\n )\n i = 1\n clf = GridSearchCV(classifiers[clf_name], {'alpha': parameters[\n freq_bands[i]]}, cv=StratifiedKFold(n_splits=int(sum(y_tr ==\n 0) // n_scz_te)), scoring='roc_auc', n_jobs=-1,\n return_train_score=True)\n if n_BAitaSig == None:\n X_tr = X[tr_idx, x_size * i:x_size * (i + 1)]\n X_te = X[te_idx, x_size * i:x_size * (i + 1)]\n elif x_size == sum(n_BAitaSig):\n X_tr = X[tr_idx, :]\n X_te = X[te_idx, :]\n else:\n n_temp = [0]\n n_temp.extend(np.cumsum(n_BAitaSig))\n X_tr = X[tr_idx, n_temp[i]:n_temp[i + 1]]\n X_te = X[te_idx, n_temp[i]:n_temp[i + 1]]\n scaler_out = preprocessing.StandardScaler().fit(X_tr)\n X_tr = scaler_out.transform(X_tr)\n X_te = scaler_out.transform(X_te)\n fit = clf.fit(X_tr, y_tr)\n auc[freq_bands[i]][count] = fit.score(X_te, y_te)\n cv_results = clf.cv_results_\n metric = 'score'\n grid_param_1 = parameters[freq_bands[i]]\n scores_mean = cv_results['mean_test_' + metric]\n scores_mean_tr = cv_results['mean_train_' + metric]\n sns.set(font_scale=1.5)\n df1 = pd.DataFrame({'log($\\\\lambda$)': [math.log(i) for i in\n grid_param_1], 'CV Average AUC': scores_mean_tr, 'type': [\n 'train'] * len(scores_mean_tr)})\n df2 = pd.DataFrame({'log($\\\\lambda$)': [math.log(i) for i in\n grid_param_1], 'CV Average AUC': scores_mean, 'type': [\n 'test'] * len(scores_mean_tr)})\n sns.lineplot(x='log($\\\\lambda$)', y='CV Average AUC', style=\n 'type', legend=False, markers='o', data=df1, ax=ax[\n count_plt // 3][count_plt % 3])\n sns.lineplot(x='log($\\\\lambda$)', y='CV Average AUC', style=\n 'type', legend=False, markers='o', data=df2, ax=ax[\n count_plt // 3][count_plt % 3])\n ax[count_plt // 3][count_plt % 3].set_xlabel('log($\\\\lambda$)',\n fontsize=14)\n ax[count_plt // 3][count_plt % 3].set_ylabel('CV Average AUC',\n fontsize=14)\n count_plt += 1\n if len(perms) == 1:\n coef_idx = np.nonzero(fit.best_estimator_.coef_)\n nz_coef_idx[freq_bands[i]].append(coef_idx)\n nz_coef_val[freq_bands[i]].append(fit.best_estimator_.coef_\n [coef_idx])\n return auc, nz_coef_idx, nz_coef_val, count\n\n\ndef CV_classifier(X, y, n_scz_te, reps, separate_bands, perms, dir_save,\n classifiers, parameters, n_BAitaSig=None):\n \"\"\"\n Parameters\n ----------\n X : np.array \n Matrix with dimension (subjects)x(feature vector).\n y : np.array\n Vector with classifications (0: healthy, 1: schizo).\n n_scz_te : int\n Desired number of schizophrenic patients in each test set.\n reps : range(*)\n Range with desired number (*) of extra times the code should run.\n separate_bands : boolean\n True = seperate data into frequency bands. False = don't separate.\n perms : range(*)\n Range with desired number (*) of permutations. \n *=1 indicates no permutations.\n dir_save : string\n Directory path to where the results should be saved.\n classifiers : dictionary\n Dictionary containing classifiers. E.g. {'lasso' : Lasso(max_iter = 10000)}\n parameters : dictionary\n Dictionary containing parameters to the classifiers as in \"classifiers\"\n\n Notes\n -------\n Saves three different values in the dir_save path: \n auc : dictionary\n Contains the auc-scores for each loop, either divided into bands or \n with the key \"all\".\n nz_coef_idx : dictionary\n Contains the non-zero coefficient indices for each loop, either \n divided into bands or with the key \"all\".\n nz_coef_val : dictionary\n Contains the non-zero coefficient values (the weights) for each \n loop, either divided into bands or with the key \"all\".\n \n \"\"\"\n if separate_bands:\n freq_bands = ['delta', 'theta', 'alpha', 'beta1', 'beta2', 'gamma']\n else:\n freq_bands = ['all']\n if len(perms) > 1:\n y_org = y\n tqdm_perms = tqdm(perms)\n tqdm_reps = reps\n else:\n tqdm_perms = perms\n tqdm_reps = tqdm(reps)\n auc = {}\n nz_coef_idx = {}\n nz_coef_val = {}\n nb_loops = len(reps) * (sum(y == 0) // n_scz_te) * len(perms)\n x_size = int(X.shape[1] / len(freq_bands))\n for i in freq_bands:\n auc[i] = np.zeros(nb_loops)\n nz_coef_idx[i] = []\n nz_coef_val[i] = []\n count = -1\n for perm in tqdm_perms:\n if len(perms) > 1:\n y = shuffle(y_org, random_state=perm).reset_index(drop=True)\n for rep in tqdm_reps:\n auc, nz_coef_idx, nz_coef_val, count = leaveKout_CV(X, y,\n n_scz_te, rep, perms, classifiers, parameters, count,\n freq_bands, x_size, auc, nz_coef_idx, nz_coef_val, n_BAitaSig)\n\n\ncon_type = 'lps'\nseparate_bands = True\npartialData = True\natlas = 'BAita'\nsns.set(font_scale=1.5)\nfreq_band_type = 'DiLorenzo'\ndir_folders = '/share/FannyMaster/PythonNew/' + atlas + '_timeseries_'\nnewest_date = getNewestFolderDate(dir_folders)\ndir_features = dir_folders + newest_date + '/' + freq_band_type + '/Features'\ndir_y_ID = '/share/FannyMaster/PythonNew/Age_Gender.csv'\nn_scz_te = 2\nreps = range(1)\nclassifiers = {'lasso': Lasso(max_iter=10000)}\ndir_save = (dir_folders + newest_date + '/' + freq_band_type +\n '/classificationResults/' + con_type.capitalize())\nX, y = get_Xy(dir_features, dir_y_ID, con_type, partialData)\nif atlas == 'DKEgill':\n X = getEgillX(X)\n n_BAitaSig = None\n parameters = getEgillParameters(con_type, separate_bands)\nelif atlas == 'BAitaSig':\n X, n_BAitaSig = significant_connected_areasBAitaSigX(X)\n parameters = getBAitaSigParameters(con_type, separate_bands)\nelif atlas == 'BAita':\n parameters = getBAitaParameters(con_type, separate_bands)\n n_BAitaSig = None\nperms = range(1)\nCV_classifier(X, y, n_scz_te, reps, separate_bands, perms, dir_save,\n classifiers, parameters)\n", "step-5": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 26 18:39:26 2020\n\n@author: Fanny Fredriksson and Karen Marie Sandø Ambrosen\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom tqdm import tqdm #count ffor loops\nimport math\nfrom sklearn.model_selection import GridSearchCV, StratifiedKFold\nfrom sklearn import preprocessing\nfrom sklearn.utils import shuffle\nfrom sklearn.linear_model import Lasso\nfrom utils_runOnce_classification import getEgillX, getEgillParameters\nfrom utils_runOnce_classification import significant_connected_areasBAitaSigX, getBAitaSigParameters, getBAitaParameters\nimport seaborn as sns\nfrom utils_joint import getNewestFolderDate, get_Xy\n\nimport pdb\n#{}\n#[]\n\n \n##############################################################################\ndef leaveKout_CV(X, y, n_scz_te, rep, perms, classifiers, parameters, count,\n freq_bands, x_size, auc, nz_coef_idx, nz_coef_val, n_BAitaSig = None):\n \"\"\"\n Calculates the leave K out cross validation. \n\n Parameters\n ----------\n X : array of arrays\n Matrix containing a vector with all the features for each subject.\n Dimension (number of subjects)x(number of features).\n y : array\n A vector containing the class-information. \n Remember: 1 = healty controls, 0 = schizophrenic \n n_scz_te : int\n Desired number of schizophrenic patients in each test set.\n rep : integer\n The number of repition that has been used so far.\n perms : range(*)\n Range with desired number (*) of permutations. \n *=1 indicates no permutations.\n classifiers : dictionary\n Dictionary containing classifiers. E.g. {'lasso' : Lasso(max_iter = 10000)}\n parameters : dictionary\n Dictionary containing parameters to the classifiers as in \"classifiers\"\n count : integer\n Used to know how many loops that have been made due to the pre \n allocated space for AUC.\n freq_bands : list of strings\n Either ['all'] or ['detla','theta','alpha','beta1','beta2','gamma'].\n x_size : integer\n The size each X has which changes depending on freq_bands.\n auc : dictionary\n Contains the auc-scores for each loop, either divided into bands or \n with the key \"all\".\n nz_coef_idx : dictionary\n Contains the non-zero coefficient indices for each loop, either \n divided into bands or with the key \"all\".\n nz_coef_val : dictionary\n Contains the non-zero coefficient values (the weights) for each \n loop, either divided into bands or with the key \"all\".\n n_BAitaSig : list of integers, optional\n The number of connections in each band when BAitaSig is used. \n The default is None.\n Returns\n -------\n auc : dictionary\n Contains the updated auc-scores for each loop, either divided into \n bands or with the key \"all\".\n nz_coef_idx : dictionary\n Contains the updated non-zero coefficient indices for each loop, \n either divided into bands or with the key \"all\".\n nz_coef_val : dictionary\n Contains the updated non-zero coefficient values (the weights) for \n each loop, either divided into bands or with the key \"all\".\n count : integer\n Used to know how many loops that have been made due to the pre \n allocated space for AUC.\n\n \"\"\"\n \n skf = StratifiedKFold(n_splits=int(sum(y==0)//n_scz_te),shuffle=True, random_state = rep)\n count_plt = 0\n fig, ax = plt.subplots(2,3 , figsize=(10,6.5))\n for tr_idx, te_idx in skf.split(X,y):\n # Compute test and train targets\n y_tr = np.ravel(y[tr_idx])\n y_te = np.ravel(y[te_idx])\n \n # Make gridsearch function\n clf_name = list(classifiers.keys())[0]\n count += 1\n sns.set(font_scale=1.5)\n for i in range(1): #range(len(freq_bands)):\n if count_plt == 6:\n plt.suptitle('Example of line search for the regularization parameter', fontsize= 18)\n plt.tight_layout()\n plt.subplots_adjust(top = 0.84, bottom = 0.15, hspace = 0.5, wspace = 0.45)\n fig.legend(['Train', 'Validation'], bbox_to_anchor = (0.5, 0.89), \n borderaxespad = 0., loc = 'upper center', ncol = 2)\n \n plt.show()\n fig.savefig('/share/FannyMaster/PythonNew/Figures/LineSearchEx.jpg', bbox_inches = 'tight')\n sns.reset_orig()\n raise NameError('This is just a dumb way of stopping the code after 6 iterations')\n \n i = 1\n clf = GridSearchCV(classifiers[clf_name], {'alpha' :parameters[freq_bands[i]]}, \n cv = StratifiedKFold(n_splits = int(sum(y_tr==0)//n_scz_te)), \n scoring = 'roc_auc', n_jobs = -1, return_train_score=True)\n # Compute test and train sets \n if n_BAitaSig == None:\n X_tr = X[tr_idx, x_size*i:x_size*(i+1)]\n X_te = X[te_idx, x_size*i:x_size*(i+1)]\n else:\n if x_size == sum(n_BAitaSig):\n X_tr = X[tr_idx, :]\n X_te = X[te_idx, :]\n else:\n n_temp = [0]\n n_temp.extend(np.cumsum(n_BAitaSig))\n X_tr = X[tr_idx, n_temp[i]:n_temp[i+1]]\n X_te = X[te_idx, n_temp[i]:n_temp[i+1]]\n \n \n # Standardize\n scaler_out = preprocessing.StandardScaler().fit(X_tr)\n X_tr = scaler_out.transform(X_tr)\n X_te = scaler_out.transform(X_te)\n\n # Fit data and save auc scores\n fit = clf.fit(X_tr, y_tr)\n auc[freq_bands[i]][count] = fit.score(X_te, y_te)\n \n # Make parameter plot\n #plot_grid_search(clf.cv_results_, 'score', parameters[freq_bands[i]], 'log($\\lambda$) ' + freq_bands[i])\n cv_results = clf.cv_results_\n metric = 'score'\n grid_param_1 = parameters[freq_bands[i]]\n \n scores_mean = cv_results[('mean_test_' + metric)]\n # scores_sd = cv_results[('std_test_' + metric)]\n scores_mean_tr = cv_results[('mean_train_' + metric)]\n \n # Set plot style\n #plt.style.use('seaborn')\n \n # Plot Grid search scores\n\n sns.set(font_scale=1.5)\n df1 = pd.DataFrame({'log($\\lambda$)':[math.log(i) for i in grid_param_1], 'CV Average AUC' : scores_mean_tr, 'type' : ['train']*len(scores_mean_tr)})\n df2 = pd.DataFrame({'log($\\lambda$)':[math.log(i) for i in grid_param_1], 'CV Average AUC' : scores_mean, 'type' : ['test']*len(scores_mean_tr)})\n sns.lineplot(x = 'log($\\lambda$)', y = 'CV Average AUC', style='type', legend = False, markers = \"o\", data = df1, ax = ax[count_plt//3][count_plt%3])\n sns.lineplot(x = 'log($\\lambda$)', y = 'CV Average AUC', style='type', legend = False, markers = \"o\", data = df2, ax = ax[count_plt//3][count_plt%3])\n\n ax[count_plt//3][count_plt%3].set_xlabel('log($\\lambda$)', fontsize=14)\n ax[count_plt//3][count_plt%3].set_ylabel('CV Average AUC' , fontsize=14) \n \n #pprint(clf.cv_results_)\n #pdb.set_trace() # Type \"exit\" to get out, type \"c\" to continue\n count_plt += 1\n if len(perms) == 1:\n coef_idx = np.nonzero(fit.best_estimator_.coef_)\n nz_coef_idx[freq_bands[i]].append(coef_idx)\n nz_coef_val[freq_bands[i]].append(fit.best_estimator_.coef_[coef_idx])\n\n return auc, nz_coef_idx, nz_coef_val, count\n\n##############################################################################\ndef CV_classifier(X, y, n_scz_te, reps, separate_bands, perms, dir_save, \n classifiers, parameters, n_BAitaSig = None):\n \"\"\"\n Parameters\n ----------\n X : np.array \n Matrix with dimension (subjects)x(feature vector).\n y : np.array\n Vector with classifications (0: healthy, 1: schizo).\n n_scz_te : int\n Desired number of schizophrenic patients in each test set.\n reps : range(*)\n Range with desired number (*) of extra times the code should run.\n separate_bands : boolean\n True = seperate data into frequency bands. False = don't separate.\n perms : range(*)\n Range with desired number (*) of permutations. \n *=1 indicates no permutations.\n dir_save : string\n Directory path to where the results should be saved.\n classifiers : dictionary\n Dictionary containing classifiers. E.g. {'lasso' : Lasso(max_iter = 10000)}\n parameters : dictionary\n Dictionary containing parameters to the classifiers as in \"classifiers\"\n\n Notes\n -------\n Saves three different values in the dir_save path: \n auc : dictionary\n Contains the auc-scores for each loop, either divided into bands or \n with the key \"all\".\n nz_coef_idx : dictionary\n Contains the non-zero coefficient indices for each loop, either \n divided into bands or with the key \"all\".\n nz_coef_val : dictionary\n Contains the non-zero coefficient values (the weights) for each \n loop, either divided into bands or with the key \"all\".\n \n \"\"\" \n \n # Check if data should be seperated into bands or not:\n if separate_bands:\n freq_bands = ['delta', 'theta', 'alpha', 'beta1', 'beta2', 'gamma']\n else:\n freq_bands = ['all']\n \n if len(perms) > 1:\n y_org = y\n tqdm_perms = tqdm(perms)\n tqdm_reps = reps\n else: \n tqdm_perms = perms\n tqdm_reps = tqdm(reps)\n \n # Initialize space for values \n auc = {}\n nz_coef_idx= {}\n nz_coef_val= {}\n nb_loops = len(reps)*(sum(y==0)//n_scz_te)*len(perms)\n # Define the size of X\n x_size = int(X.shape[1]/len(freq_bands))\n for i in freq_bands:\n auc[i] = np.zeros(nb_loops) # e.g. auc = {'delta':[] , 'theta': [], 'alpha': [], ....}\n nz_coef_idx[i] = []\n nz_coef_val[i] = []\n \n count = -1\n for perm in tqdm_perms:\n if len(perms) > 1:\n y = shuffle(y_org, random_state=perm).reset_index(drop=True)\n \n for rep in tqdm_reps:\n auc, nz_coef_idx, nz_coef_val, count = leaveKout_CV(X, y, n_scz_te, rep, \n perms, classifiers, parameters, count, \n freq_bands, x_size, auc, nz_coef_idx, \n nz_coef_val, n_BAitaSig)\n\n\n\n#%%\ncon_type = 'lps'\nseparate_bands = True # False = All bands together\npartialData = True\n\natlas = 'BAita' # DKEgill, BAita, BAitaSig\n\nsns.set(font_scale=1.5)\nfreq_band_type = 'DiLorenzo'\n# Directories\ndir_folders = r'/share/FannyMaster/PythonNew/' + atlas + '_timeseries_'\nnewest_date = getNewestFolderDate(dir_folders)\ndir_features = dir_folders + newest_date + '/' + freq_band_type + '/Features' \ndir_y_ID = r'/share/FannyMaster/PythonNew/Age_Gender.csv'\nn_scz_te = 2\nreps = range(1)\nclassifiers = {'lasso' : Lasso(max_iter = 10000)} \ndir_save = dir_folders + newest_date + '/' + freq_band_type + '/classificationResults/' + con_type.capitalize() \nX,y = get_Xy(dir_features, dir_y_ID, con_type, partialData)\n\nif atlas == 'DKEgill':\n X = getEgillX(X)\n n_BAitaSig = None\n parameters = getEgillParameters(con_type, separate_bands)\nelif atlas == 'BAitaSig':\n X, n_BAitaSig = significant_connected_areasBAitaSigX(X)\n parameters = getBAitaSigParameters(con_type, separate_bands)\nelif atlas == 'BAita':\n parameters = getBAitaParameters(con_type, separate_bands)\n n_BAitaSig = None\n\nperms = range(1) # 1 = No permutations\nCV_classifier(X, y, n_scz_te, reps, separate_bands, perms, dir_save, \n classifiers, parameters)\n\n\n\n\n", "step-ids": [ 0, 3, 4, 5, 6 ] }
[ 0, 3, 4, 5, 6 ]
<|reserved_special_token_0|> def main(): if len(sys.argv) < 2: print('prosze podac plik') sys.exit() fileName = sys.argv[1] matrix = [] ReadFile(matrix, fileName) Prim(matrix, 0) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def ReadFile(array, fileName): with open(fileName, 'r') as f: if f.readline().rstrip() != 'MS': print('prosze podac macierz sasiedztwa') for i in f: el = list(map(int, i.rstrip().split())) if len(el) > 1: array.append(el) def Prim(matrix, vertex_to_start): heap_map = [(100000) for i in range(len(matrix))] heap_map[vertex_to_start] = 0 length = len(matrix) p = [(0) for i in range(len(matrix))] ready_vertices = [] index = vertex_to_start while len(ready_vertices) != length: for i in range(len(matrix[index])): if i not in ready_vertices and matrix[index][i] != 0: if matrix[index][i] < heap_map[i]: heap_map[i] = matrix[index][i] p[i] = index ready_vertices.append(index) heap_map[index] = 100000 index = heap_map.index(min(heap_map)) p[vertex_to_start] = 'x' print(p) def main(): if len(sys.argv) < 2: print('prosze podac plik') sys.exit() fileName = sys.argv[1] matrix = [] ReadFile(matrix, fileName) Prim(matrix, 0) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def ReadFile(array, fileName): with open(fileName, 'r') as f: if f.readline().rstrip() != 'MS': print('prosze podac macierz sasiedztwa') for i in f: el = list(map(int, i.rstrip().split())) if len(el) > 1: array.append(el) def Prim(matrix, vertex_to_start): heap_map = [(100000) for i in range(len(matrix))] heap_map[vertex_to_start] = 0 length = len(matrix) p = [(0) for i in range(len(matrix))] ready_vertices = [] index = vertex_to_start while len(ready_vertices) != length: for i in range(len(matrix[index])): if i not in ready_vertices and matrix[index][i] != 0: if matrix[index][i] < heap_map[i]: heap_map[i] = matrix[index][i] p[i] = index ready_vertices.append(index) heap_map[index] = 100000 index = heap_map.index(min(heap_map)) p[vertex_to_start] = 'x' print(p) def main(): if len(sys.argv) < 2: print('prosze podac plik') sys.exit() fileName = sys.argv[1] matrix = [] ReadFile(matrix, fileName) Prim(matrix, 0) if __name__ == '__main__': main() <|reserved_special_token_1|> import sys def ReadFile(array, fileName): with open(fileName, 'r') as f: if f.readline().rstrip() != 'MS': print('prosze podac macierz sasiedztwa') for i in f: el = list(map(int, i.rstrip().split())) if len(el) > 1: array.append(el) def Prim(matrix, vertex_to_start): heap_map = [(100000) for i in range(len(matrix))] heap_map[vertex_to_start] = 0 length = len(matrix) p = [(0) for i in range(len(matrix))] ready_vertices = [] index = vertex_to_start while len(ready_vertices) != length: for i in range(len(matrix[index])): if i not in ready_vertices and matrix[index][i] != 0: if matrix[index][i] < heap_map[i]: heap_map[i] = matrix[index][i] p[i] = index ready_vertices.append(index) heap_map[index] = 100000 index = heap_map.index(min(heap_map)) p[vertex_to_start] = 'x' print(p) def main(): if len(sys.argv) < 2: print('prosze podac plik') sys.exit() fileName = sys.argv[1] matrix = [] ReadFile(matrix, fileName) Prim(matrix, 0) if __name__ == '__main__': main() <|reserved_special_token_1|> import sys def ReadFile(array, fileName): with open(fileName, 'r') as f: if f.readline().rstrip() != 'MS': print("prosze podac macierz sasiedztwa") for i in f: el = list(map(int, i.rstrip().split())) if len(el) > 1: array.append(el) def Prim(matrix, vertex_to_start): heap_map = [100000 for i in range(len(matrix))] heap_map[vertex_to_start] = 0 length = len(matrix) # tablica poprzednikow p = [0 for i in range(len(matrix))] # tablica gotowych wierzcholkow ready_vertices = [] # obecny index na ktorym wykonywane sa operacje index = vertex_to_start while len(ready_vertices) != length: for i in range(len(matrix[index])): # sprawdzam czy wierzcholek juz nie jest gotowy i # czy jest polaczenie miedzy wierzcholkami if i not in ready_vertices and matrix[index][i] != 0: # jezeli nowe polaczenie miedzy danym wierzcholkiem i # jakas krawedzia lepsze(krotsze) to zamieniam poprzednika if matrix[index][i] < heap_map[i]: heap_map[i] = matrix[index][i] p[i] = index # dodaje wierzcholek do gotowych ready_vertices.append(index) # sztucznie usuwam z heap_map heap_map[index] = 100000 # wybieram nowy indeks - minimalny index = heap_map.index(min(heap_map)) # wierzcholek poczatkowy p[vertex_to_start] = 'x' print(p) def main(): if len(sys.argv) < 2: print("prosze podac plik") sys.exit() fileName = sys.argv[1] matrix = [] ReadFile(matrix, fileName) #print(matrix[1].index(min(matrix[0]))) Prim(matrix, 0) if __name__ == "__main__": main()
flexible
{ "blob_id": "56b8b9884b8500ff70f59058484c4a351b709311", "index": 3517, "step-1": "<mask token>\n\n\ndef main():\n if len(sys.argv) < 2:\n print('prosze podac plik')\n sys.exit()\n fileName = sys.argv[1]\n matrix = []\n ReadFile(matrix, fileName)\n Prim(matrix, 0)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef ReadFile(array, fileName):\n with open(fileName, 'r') as f:\n if f.readline().rstrip() != 'MS':\n print('prosze podac macierz sasiedztwa')\n for i in f:\n el = list(map(int, i.rstrip().split()))\n if len(el) > 1:\n array.append(el)\n\n\ndef Prim(matrix, vertex_to_start):\n heap_map = [(100000) for i in range(len(matrix))]\n heap_map[vertex_to_start] = 0\n length = len(matrix)\n p = [(0) for i in range(len(matrix))]\n ready_vertices = []\n index = vertex_to_start\n while len(ready_vertices) != length:\n for i in range(len(matrix[index])):\n if i not in ready_vertices and matrix[index][i] != 0:\n if matrix[index][i] < heap_map[i]:\n heap_map[i] = matrix[index][i]\n p[i] = index\n ready_vertices.append(index)\n heap_map[index] = 100000\n index = heap_map.index(min(heap_map))\n p[vertex_to_start] = 'x'\n print(p)\n\n\ndef main():\n if len(sys.argv) < 2:\n print('prosze podac plik')\n sys.exit()\n fileName = sys.argv[1]\n matrix = []\n ReadFile(matrix, fileName)\n Prim(matrix, 0)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef ReadFile(array, fileName):\n with open(fileName, 'r') as f:\n if f.readline().rstrip() != 'MS':\n print('prosze podac macierz sasiedztwa')\n for i in f:\n el = list(map(int, i.rstrip().split()))\n if len(el) > 1:\n array.append(el)\n\n\ndef Prim(matrix, vertex_to_start):\n heap_map = [(100000) for i in range(len(matrix))]\n heap_map[vertex_to_start] = 0\n length = len(matrix)\n p = [(0) for i in range(len(matrix))]\n ready_vertices = []\n index = vertex_to_start\n while len(ready_vertices) != length:\n for i in range(len(matrix[index])):\n if i not in ready_vertices and matrix[index][i] != 0:\n if matrix[index][i] < heap_map[i]:\n heap_map[i] = matrix[index][i]\n p[i] = index\n ready_vertices.append(index)\n heap_map[index] = 100000\n index = heap_map.index(min(heap_map))\n p[vertex_to_start] = 'x'\n print(p)\n\n\ndef main():\n if len(sys.argv) < 2:\n print('prosze podac plik')\n sys.exit()\n fileName = sys.argv[1]\n matrix = []\n ReadFile(matrix, fileName)\n Prim(matrix, 0)\n\n\nif __name__ == '__main__':\n main()\n", "step-4": "import sys\n\n\ndef ReadFile(array, fileName):\n with open(fileName, 'r') as f:\n if f.readline().rstrip() != 'MS':\n print('prosze podac macierz sasiedztwa')\n for i in f:\n el = list(map(int, i.rstrip().split()))\n if len(el) > 1:\n array.append(el)\n\n\ndef Prim(matrix, vertex_to_start):\n heap_map = [(100000) for i in range(len(matrix))]\n heap_map[vertex_to_start] = 0\n length = len(matrix)\n p = [(0) for i in range(len(matrix))]\n ready_vertices = []\n index = vertex_to_start\n while len(ready_vertices) != length:\n for i in range(len(matrix[index])):\n if i not in ready_vertices and matrix[index][i] != 0:\n if matrix[index][i] < heap_map[i]:\n heap_map[i] = matrix[index][i]\n p[i] = index\n ready_vertices.append(index)\n heap_map[index] = 100000\n index = heap_map.index(min(heap_map))\n p[vertex_to_start] = 'x'\n print(p)\n\n\ndef main():\n if len(sys.argv) < 2:\n print('prosze podac plik')\n sys.exit()\n fileName = sys.argv[1]\n matrix = []\n ReadFile(matrix, fileName)\n Prim(matrix, 0)\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "import sys\n\ndef ReadFile(array, fileName):\n with open(fileName, 'r') as f:\n if f.readline().rstrip() != 'MS':\n print(\"prosze podac macierz sasiedztwa\")\n for i in f:\n el = list(map(int, i.rstrip().split()))\n if len(el) > 1:\n array.append(el)\n\n\ndef Prim(matrix, vertex_to_start):\n heap_map = [100000 for i in range(len(matrix))]\n heap_map[vertex_to_start] = 0\n\n length = len(matrix)\n\n # tablica poprzednikow\n p = [0 for i in range(len(matrix))]\n\n # tablica gotowych wierzcholkow\n ready_vertices = []\n\n # obecny index na ktorym wykonywane sa operacje\n index = vertex_to_start\n\n while len(ready_vertices) != length:\n for i in range(len(matrix[index])):\n # sprawdzam czy wierzcholek juz nie jest gotowy i\n # czy jest polaczenie miedzy wierzcholkami\n if i not in ready_vertices and matrix[index][i] != 0:\n # jezeli nowe polaczenie miedzy danym wierzcholkiem i\n # jakas krawedzia lepsze(krotsze) to zamieniam poprzednika\n if matrix[index][i] < heap_map[i]:\n heap_map[i] = matrix[index][i]\n p[i] = index\n # dodaje wierzcholek do gotowych\n ready_vertices.append(index)\n # sztucznie usuwam z heap_map\n heap_map[index] = 100000\n # wybieram nowy indeks - minimalny\n index = heap_map.index(min(heap_map))\n\n # wierzcholek poczatkowy\n p[vertex_to_start] = 'x' \n\n print(p)\n\n\n\n\ndef main():\n if len(sys.argv) < 2:\n print(\"prosze podac plik\")\n sys.exit()\n \n fileName = sys.argv[1]\n matrix = []\n \n ReadFile(matrix, fileName)\n\n #print(matrix[1].index(min(matrix[0])))\n Prim(matrix, 0)\n\n\n\n\nif __name__ == \"__main__\":\n main()", "step-ids": [ 1, 3, 4, 5, 6 ] }
[ 1, 3, 4, 5, 6 ]
#!/usr/bin/python import os import psycopg2 import datetime import time import json import decimal import requests import csv import asyncio from config import get_connection, get_db_sql, get_sql_record_count, CORP_TYPES_IN_SCOPE, corp_num_with_prefix, bare_corp_num from orgbook_data_load import ( get_orgbook_all_corps, get_orgbook_all_corps_csv, get_event_proc_future_corps, get_event_proc_future_corps_csv, get_bc_reg_corps, get_bc_reg_corps_csv, get_agent_wallet_ids, append_agent_wallet_ids ) QUERY_LIMIT = '200000' REPORT_COUNT = 10000 ERROR_THRESHOLD_COUNT = 5 # value for PROD is "https://orgbook.gov.bc.ca/api/v3" ORGBOOK_API_URL = os.environ.get('ORGBOOK_API_URL', 'http://localhost:8081/api/v3') TOPIC_QUERY = "/topic/registration.registries.ca/" TOPIC_NAME_SEARCH = "/search/topic?inactive=false&latest=true&revoked=false&name=" TOPIC_ID_SEARCH = "/search/topic?inactive=false&latest=true&revoked=false&topic_id=" # value for PROD is "https://agent-admin.orgbook.gov.bc.ca/credential/" AGENT_API_URL = os.environ.get("AGENT_API_URL", "http://localhost:8021/credential/") AGENT_API_KEY = os.environ.get("AGENT_API_KEY") # default is to audit active (non-revoked) credentials AUDIT_ALL_CREDENTIALS = (os.environ.get("AUDIT_ALL_CREDENTIALS", "false").lower() == 'true') """ Detail audit report - credential list from orgbook. Reads from the orgbook database: - wallet id for each credential """ async def process_credential_queue(): # preload agent wallet id's print("Get exported wallet id's from agent", datetime.datetime.now()) agent_wallet_ids = get_agent_wallet_ids() print("# wallet id's:", len(agent_wallet_ids)) conn = None try: conn = get_connection('org_book') except (Exception) as error: print(error) raise # get all the corps from orgbook print("Get credential stats from OrgBook DB", datetime.datetime.now()) cred_filter = " and not credential.revoked " if not AUDIT_ALL_CREDENTIALS else "" sql4 = """select credential.credential_id, credential.id, credential.topic_id, credential.update_timestamp, topic.source_id, credential.credential_type_id, credential_type.description, credential.revoked, credential.inactive, credential.latest, credential.effective_date, credential.revoked_date, credential.revoked_by_id from credential, topic, credential_type where topic.id = credential.topic_id""" + cred_filter + """ and credential_type.id = credential.credential_type_id order by id;""" corp_creds = [] try: cur = conn.cursor() cur.execute(sql4) for row in cur: corp_creds.append({ 'credential_id': row[0], 'id': row[1], 'topic_id': row[2], 'timestamp': row[3], 'source_id': row[4], 'credential_type_id': row[5], 'credential_type': row[6], 'revoked': row[7], 'inactive': row[8], 'latest': row[9], 'effective_date': row[10], 'revoked_date': row[11], 'revoked_by': row[12] }) cur.close() except (Exception) as error: print(error) raise print("# orgbook creds:", len(corp_creds), datetime.datetime.now()) i = 0 agent_checks = 0 cache_checks = 0 missing = [] extra_cred = [] not_in_cache = [] print("Checking for valid credentials ...", datetime.datetime.now()) while i < len(corp_creds): # if cached we are good, otherwise check agent via api if not corp_creds[i]['credential_id'] in agent_wallet_ids.keys(): agent_checks = agent_checks + 1 api_key_hdr = {"x-api-key": AGENT_API_KEY} url = AGENT_API_URL + corp_creds[i]['credential_id'] #print(i, url) try: response = requests.get(url, headers=api_key_hdr) response.raise_for_status() if response.status_code == 404: raise Exception("404 not found") else: wallet_credential = response.json() # exists in agent but is not in cache not_in_cache.append(corp_creds[i]) except Exception as e: if (corp_creds[i]['revoked'] and corp_creds[i]['revoked_by'] is not None and corp_creds[i]['effective_date'] == corp_creds[i]['revoked_date']): print("Extra cred in TOB:", i, corp_creds[i]['credential_id']) extra_cred.append(corp_creds[i]) else: print( "Exception:", i, corp_creds[i]['credential_id'], corp_creds[i]['topic_id'], corp_creds[i]['source_id'], corp_creds[i]['credential_type'], corp_creds[i]['revoked'], corp_creds[i]['inactive'], corp_creds[i]['latest'], corp_creds[i]['timestamp'], ) missing.append(corp_creds[i]) else: cache_checks = cache_checks + 1 i = i + 1 if 0 == i % 100000: print(i) append_agent_wallet_ids(not_in_cache) print("Total # missing in wallet:", len(missing), ", Extra:", len(extra_cred), datetime.datetime.now()) print("Cache checks:", cache_checks, ", Agent checks:", agent_checks) try: loop = asyncio.get_event_loop() loop.run_until_complete(process_credential_queue()) except Exception as e: print("Exception", e) raise
normal
{ "blob_id": "cdb49af584ae7befcaebfd9bb303073c8229667e", "index": 3433, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nasync def process_credential_queue():\n print(\"Get exported wallet id's from agent\", datetime.datetime.now())\n agent_wallet_ids = get_agent_wallet_ids()\n print(\"# wallet id's:\", len(agent_wallet_ids))\n conn = None\n try:\n conn = get_connection('org_book')\n except Exception as error:\n print(error)\n raise\n print('Get credential stats from OrgBook DB', datetime.datetime.now())\n cred_filter = (' and not credential.revoked ' if not\n AUDIT_ALL_CREDENTIALS else '')\n sql4 = \"\"\"select \n credential.credential_id, credential.id, credential.topic_id, credential.update_timestamp,\n topic.source_id, credential.credential_type_id, credential_type.description,\n credential.revoked, credential.inactive, credential.latest,\n credential.effective_date, credential.revoked_date, credential.revoked_by_id\n from credential, topic, credential_type\n where topic.id = credential.topic_id\"\"\" + cred_filter + \"\"\"\n and credential_type.id = credential.credential_type_id\n order by id;\"\"\"\n corp_creds = []\n try:\n cur = conn.cursor()\n cur.execute(sql4)\n for row in cur:\n corp_creds.append({'credential_id': row[0], 'id': row[1],\n 'topic_id': row[2], 'timestamp': row[3], 'source_id': row[4\n ], 'credential_type_id': row[5], 'credential_type': row[6],\n 'revoked': row[7], 'inactive': row[8], 'latest': row[9],\n 'effective_date': row[10], 'revoked_date': row[11],\n 'revoked_by': row[12]})\n cur.close()\n except Exception as error:\n print(error)\n raise\n print('# orgbook creds:', len(corp_creds), datetime.datetime.now())\n i = 0\n agent_checks = 0\n cache_checks = 0\n missing = []\n extra_cred = []\n not_in_cache = []\n print('Checking for valid credentials ...', datetime.datetime.now())\n while i < len(corp_creds):\n if not corp_creds[i]['credential_id'] in agent_wallet_ids.keys():\n agent_checks = agent_checks + 1\n api_key_hdr = {'x-api-key': AGENT_API_KEY}\n url = AGENT_API_URL + corp_creds[i]['credential_id']\n try:\n response = requests.get(url, headers=api_key_hdr)\n response.raise_for_status()\n if response.status_code == 404:\n raise Exception('404 not found')\n else:\n wallet_credential = response.json()\n not_in_cache.append(corp_creds[i])\n except Exception as e:\n if corp_creds[i]['revoked'] and corp_creds[i]['revoked_by'\n ] is not None and corp_creds[i]['effective_date'\n ] == corp_creds[i]['revoked_date']:\n print('Extra cred in TOB:', i, corp_creds[i][\n 'credential_id'])\n extra_cred.append(corp_creds[i])\n else:\n print('Exception:', i, corp_creds[i]['credential_id'],\n corp_creds[i]['topic_id'], corp_creds[i][\n 'source_id'], corp_creds[i]['credential_type'],\n corp_creds[i]['revoked'], corp_creds[i]['inactive'],\n corp_creds[i]['latest'], corp_creds[i]['timestamp'])\n missing.append(corp_creds[i])\n else:\n cache_checks = cache_checks + 1\n i = i + 1\n if 0 == i % 100000:\n print(i)\n append_agent_wallet_ids(not_in_cache)\n print('Total # missing in wallet:', len(missing), ', Extra:', len(\n extra_cred), datetime.datetime.now())\n print('Cache checks:', cache_checks, ', Agent checks:', agent_checks)\n\n\ntry:\n loop = asyncio.get_event_loop()\n loop.run_until_complete(process_credential_queue())\nexcept Exception as e:\n print('Exception', e)\n raise\n", "step-3": "<mask token>\nQUERY_LIMIT = '200000'\nREPORT_COUNT = 10000\nERROR_THRESHOLD_COUNT = 5\nORGBOOK_API_URL = os.environ.get('ORGBOOK_API_URL',\n 'http://localhost:8081/api/v3')\nTOPIC_QUERY = '/topic/registration.registries.ca/'\nTOPIC_NAME_SEARCH = (\n '/search/topic?inactive=false&latest=true&revoked=false&name=')\nTOPIC_ID_SEARCH = (\n '/search/topic?inactive=false&latest=true&revoked=false&topic_id=')\nAGENT_API_URL = os.environ.get('AGENT_API_URL',\n 'http://localhost:8021/credential/')\nAGENT_API_KEY = os.environ.get('AGENT_API_KEY')\nAUDIT_ALL_CREDENTIALS = os.environ.get('AUDIT_ALL_CREDENTIALS', 'false').lower(\n ) == 'true'\n<mask token>\n\n\nasync def process_credential_queue():\n print(\"Get exported wallet id's from agent\", datetime.datetime.now())\n agent_wallet_ids = get_agent_wallet_ids()\n print(\"# wallet id's:\", len(agent_wallet_ids))\n conn = None\n try:\n conn = get_connection('org_book')\n except Exception as error:\n print(error)\n raise\n print('Get credential stats from OrgBook DB', datetime.datetime.now())\n cred_filter = (' and not credential.revoked ' if not\n AUDIT_ALL_CREDENTIALS else '')\n sql4 = \"\"\"select \n credential.credential_id, credential.id, credential.topic_id, credential.update_timestamp,\n topic.source_id, credential.credential_type_id, credential_type.description,\n credential.revoked, credential.inactive, credential.latest,\n credential.effective_date, credential.revoked_date, credential.revoked_by_id\n from credential, topic, credential_type\n where topic.id = credential.topic_id\"\"\" + cred_filter + \"\"\"\n and credential_type.id = credential.credential_type_id\n order by id;\"\"\"\n corp_creds = []\n try:\n cur = conn.cursor()\n cur.execute(sql4)\n for row in cur:\n corp_creds.append({'credential_id': row[0], 'id': row[1],\n 'topic_id': row[2], 'timestamp': row[3], 'source_id': row[4\n ], 'credential_type_id': row[5], 'credential_type': row[6],\n 'revoked': row[7], 'inactive': row[8], 'latest': row[9],\n 'effective_date': row[10], 'revoked_date': row[11],\n 'revoked_by': row[12]})\n cur.close()\n except Exception as error:\n print(error)\n raise\n print('# orgbook creds:', len(corp_creds), datetime.datetime.now())\n i = 0\n agent_checks = 0\n cache_checks = 0\n missing = []\n extra_cred = []\n not_in_cache = []\n print('Checking for valid credentials ...', datetime.datetime.now())\n while i < len(corp_creds):\n if not corp_creds[i]['credential_id'] in agent_wallet_ids.keys():\n agent_checks = agent_checks + 1\n api_key_hdr = {'x-api-key': AGENT_API_KEY}\n url = AGENT_API_URL + corp_creds[i]['credential_id']\n try:\n response = requests.get(url, headers=api_key_hdr)\n response.raise_for_status()\n if response.status_code == 404:\n raise Exception('404 not found')\n else:\n wallet_credential = response.json()\n not_in_cache.append(corp_creds[i])\n except Exception as e:\n if corp_creds[i]['revoked'] and corp_creds[i]['revoked_by'\n ] is not None and corp_creds[i]['effective_date'\n ] == corp_creds[i]['revoked_date']:\n print('Extra cred in TOB:', i, corp_creds[i][\n 'credential_id'])\n extra_cred.append(corp_creds[i])\n else:\n print('Exception:', i, corp_creds[i]['credential_id'],\n corp_creds[i]['topic_id'], corp_creds[i][\n 'source_id'], corp_creds[i]['credential_type'],\n corp_creds[i]['revoked'], corp_creds[i]['inactive'],\n corp_creds[i]['latest'], corp_creds[i]['timestamp'])\n missing.append(corp_creds[i])\n else:\n cache_checks = cache_checks + 1\n i = i + 1\n if 0 == i % 100000:\n print(i)\n append_agent_wallet_ids(not_in_cache)\n print('Total # missing in wallet:', len(missing), ', Extra:', len(\n extra_cred), datetime.datetime.now())\n print('Cache checks:', cache_checks, ', Agent checks:', agent_checks)\n\n\ntry:\n loop = asyncio.get_event_loop()\n loop.run_until_complete(process_credential_queue())\nexcept Exception as e:\n print('Exception', e)\n raise\n", "step-4": "import os\nimport psycopg2\nimport datetime\nimport time\nimport json\nimport decimal\nimport requests\nimport csv\nimport asyncio\nfrom config import get_connection, get_db_sql, get_sql_record_count, CORP_TYPES_IN_SCOPE, corp_num_with_prefix, bare_corp_num\nfrom orgbook_data_load import get_orgbook_all_corps, get_orgbook_all_corps_csv, get_event_proc_future_corps, get_event_proc_future_corps_csv, get_bc_reg_corps, get_bc_reg_corps_csv, get_agent_wallet_ids, append_agent_wallet_ids\nQUERY_LIMIT = '200000'\nREPORT_COUNT = 10000\nERROR_THRESHOLD_COUNT = 5\nORGBOOK_API_URL = os.environ.get('ORGBOOK_API_URL',\n 'http://localhost:8081/api/v3')\nTOPIC_QUERY = '/topic/registration.registries.ca/'\nTOPIC_NAME_SEARCH = (\n '/search/topic?inactive=false&latest=true&revoked=false&name=')\nTOPIC_ID_SEARCH = (\n '/search/topic?inactive=false&latest=true&revoked=false&topic_id=')\nAGENT_API_URL = os.environ.get('AGENT_API_URL',\n 'http://localhost:8021/credential/')\nAGENT_API_KEY = os.environ.get('AGENT_API_KEY')\nAUDIT_ALL_CREDENTIALS = os.environ.get('AUDIT_ALL_CREDENTIALS', 'false').lower(\n ) == 'true'\n<mask token>\n\n\nasync def process_credential_queue():\n print(\"Get exported wallet id's from agent\", datetime.datetime.now())\n agent_wallet_ids = get_agent_wallet_ids()\n print(\"# wallet id's:\", len(agent_wallet_ids))\n conn = None\n try:\n conn = get_connection('org_book')\n except Exception as error:\n print(error)\n raise\n print('Get credential stats from OrgBook DB', datetime.datetime.now())\n cred_filter = (' and not credential.revoked ' if not\n AUDIT_ALL_CREDENTIALS else '')\n sql4 = \"\"\"select \n credential.credential_id, credential.id, credential.topic_id, credential.update_timestamp,\n topic.source_id, credential.credential_type_id, credential_type.description,\n credential.revoked, credential.inactive, credential.latest,\n credential.effective_date, credential.revoked_date, credential.revoked_by_id\n from credential, topic, credential_type\n where topic.id = credential.topic_id\"\"\" + cred_filter + \"\"\"\n and credential_type.id = credential.credential_type_id\n order by id;\"\"\"\n corp_creds = []\n try:\n cur = conn.cursor()\n cur.execute(sql4)\n for row in cur:\n corp_creds.append({'credential_id': row[0], 'id': row[1],\n 'topic_id': row[2], 'timestamp': row[3], 'source_id': row[4\n ], 'credential_type_id': row[5], 'credential_type': row[6],\n 'revoked': row[7], 'inactive': row[8], 'latest': row[9],\n 'effective_date': row[10], 'revoked_date': row[11],\n 'revoked_by': row[12]})\n cur.close()\n except Exception as error:\n print(error)\n raise\n print('# orgbook creds:', len(corp_creds), datetime.datetime.now())\n i = 0\n agent_checks = 0\n cache_checks = 0\n missing = []\n extra_cred = []\n not_in_cache = []\n print('Checking for valid credentials ...', datetime.datetime.now())\n while i < len(corp_creds):\n if not corp_creds[i]['credential_id'] in agent_wallet_ids.keys():\n agent_checks = agent_checks + 1\n api_key_hdr = {'x-api-key': AGENT_API_KEY}\n url = AGENT_API_URL + corp_creds[i]['credential_id']\n try:\n response = requests.get(url, headers=api_key_hdr)\n response.raise_for_status()\n if response.status_code == 404:\n raise Exception('404 not found')\n else:\n wallet_credential = response.json()\n not_in_cache.append(corp_creds[i])\n except Exception as e:\n if corp_creds[i]['revoked'] and corp_creds[i]['revoked_by'\n ] is not None and corp_creds[i]['effective_date'\n ] == corp_creds[i]['revoked_date']:\n print('Extra cred in TOB:', i, corp_creds[i][\n 'credential_id'])\n extra_cred.append(corp_creds[i])\n else:\n print('Exception:', i, corp_creds[i]['credential_id'],\n corp_creds[i]['topic_id'], corp_creds[i][\n 'source_id'], corp_creds[i]['credential_type'],\n corp_creds[i]['revoked'], corp_creds[i]['inactive'],\n corp_creds[i]['latest'], corp_creds[i]['timestamp'])\n missing.append(corp_creds[i])\n else:\n cache_checks = cache_checks + 1\n i = i + 1\n if 0 == i % 100000:\n print(i)\n append_agent_wallet_ids(not_in_cache)\n print('Total # missing in wallet:', len(missing), ', Extra:', len(\n extra_cred), datetime.datetime.now())\n print('Cache checks:', cache_checks, ', Agent checks:', agent_checks)\n\n\ntry:\n loop = asyncio.get_event_loop()\n loop.run_until_complete(process_credential_queue())\nexcept Exception as e:\n print('Exception', e)\n raise\n", "step-5": "#!/usr/bin/python\nimport os \nimport psycopg2\nimport datetime\nimport time\nimport json\nimport decimal\nimport requests\nimport csv\nimport asyncio\n\nfrom config import get_connection, get_db_sql, get_sql_record_count, CORP_TYPES_IN_SCOPE, corp_num_with_prefix, bare_corp_num\nfrom orgbook_data_load import (\n get_orgbook_all_corps, get_orgbook_all_corps_csv,\n get_event_proc_future_corps, get_event_proc_future_corps_csv,\n get_bc_reg_corps, get_bc_reg_corps_csv,\n get_agent_wallet_ids, append_agent_wallet_ids\n)\n\n\nQUERY_LIMIT = '200000'\nREPORT_COUNT = 10000\nERROR_THRESHOLD_COUNT = 5\n\n# value for PROD is \"https://orgbook.gov.bc.ca/api/v3\"\nORGBOOK_API_URL = os.environ.get('ORGBOOK_API_URL', 'http://localhost:8081/api/v3')\nTOPIC_QUERY = \"/topic/registration.registries.ca/\"\nTOPIC_NAME_SEARCH = \"/search/topic?inactive=false&latest=true&revoked=false&name=\"\nTOPIC_ID_SEARCH = \"/search/topic?inactive=false&latest=true&revoked=false&topic_id=\"\n\n# value for PROD is \"https://agent-admin.orgbook.gov.bc.ca/credential/\"\nAGENT_API_URL = os.environ.get(\"AGENT_API_URL\", \"http://localhost:8021/credential/\")\nAGENT_API_KEY = os.environ.get(\"AGENT_API_KEY\")\n\n# default is to audit active (non-revoked) credentials\nAUDIT_ALL_CREDENTIALS = (os.environ.get(\"AUDIT_ALL_CREDENTIALS\", \"false\").lower() == 'true')\n\n\n\"\"\"\nDetail audit report - credential list from orgbook.\nReads from the orgbook database:\n- wallet id for each credential\n\"\"\"\n\nasync def process_credential_queue():\n # preload agent wallet id's\n print(\"Get exported wallet id's from agent\", datetime.datetime.now())\n agent_wallet_ids = get_agent_wallet_ids()\n print(\"# wallet id's:\", len(agent_wallet_ids))\n\n conn = None\n try:\n conn = get_connection('org_book')\n except (Exception) as error:\n print(error)\n raise\n\n # get all the corps from orgbook\n print(\"Get credential stats from OrgBook DB\", datetime.datetime.now())\n cred_filter = \" and not credential.revoked \" if not AUDIT_ALL_CREDENTIALS else \"\"\n sql4 = \"\"\"select \n credential.credential_id, credential.id, credential.topic_id, credential.update_timestamp,\n topic.source_id, credential.credential_type_id, credential_type.description,\n credential.revoked, credential.inactive, credential.latest,\n credential.effective_date, credential.revoked_date, credential.revoked_by_id\n from credential, topic, credential_type\n where topic.id = credential.topic_id\"\"\" + cred_filter + \"\"\"\n and credential_type.id = credential.credential_type_id\n order by id;\"\"\"\n corp_creds = []\n try:\n cur = conn.cursor()\n cur.execute(sql4)\n for row in cur:\n corp_creds.append({\n 'credential_id': row[0], 'id': row[1], 'topic_id': row[2], 'timestamp': row[3],\n 'source_id': row[4], 'credential_type_id': row[5], 'credential_type': row[6],\n 'revoked': row[7], 'inactive': row[8], 'latest': row[9],\n 'effective_date': row[10], 'revoked_date': row[11], 'revoked_by': row[12]\n })\n cur.close()\n except (Exception) as error:\n print(error)\n raise\n print(\"# orgbook creds:\", len(corp_creds), datetime.datetime.now())\n\n i = 0\n agent_checks = 0\n cache_checks = 0\n missing = []\n extra_cred = []\n not_in_cache = []\n print(\"Checking for valid credentials ...\", datetime.datetime.now())\n while i < len(corp_creds):\n # if cached we are good, otherwise check agent via api\n if not corp_creds[i]['credential_id'] in agent_wallet_ids.keys():\n agent_checks = agent_checks + 1\n api_key_hdr = {\"x-api-key\": AGENT_API_KEY}\n url = AGENT_API_URL + corp_creds[i]['credential_id']\n #print(i, url)\n try:\n response = requests.get(url, headers=api_key_hdr)\n response.raise_for_status()\n if response.status_code == 404:\n raise Exception(\"404 not found\")\n else:\n wallet_credential = response.json()\n # exists in agent but is not in cache\n not_in_cache.append(corp_creds[i])\n except Exception as e:\n if (corp_creds[i]['revoked'] and corp_creds[i]['revoked_by'] is not None and\n corp_creds[i]['effective_date'] == corp_creds[i]['revoked_date']):\n print(\"Extra cred in TOB:\", i, corp_creds[i]['credential_id'])\n extra_cred.append(corp_creds[i])\n else:\n print(\n \"Exception:\", i, corp_creds[i]['credential_id'],\n corp_creds[i]['topic_id'], corp_creds[i]['source_id'], corp_creds[i]['credential_type'],\n corp_creds[i]['revoked'], corp_creds[i]['inactive'], corp_creds[i]['latest'],\n corp_creds[i]['timestamp'],\n )\n missing.append(corp_creds[i])\n else:\n cache_checks = cache_checks + 1\n i = i + 1\n if 0 == i % 100000:\n print(i)\n\n append_agent_wallet_ids(not_in_cache)\n\n print(\"Total # missing in wallet:\", len(missing), \", Extra:\", len(extra_cred), datetime.datetime.now())\n print(\"Cache checks:\", cache_checks, \", Agent checks:\", agent_checks)\n\n\ntry:\n loop = asyncio.get_event_loop()\n loop.run_until_complete(process_credential_queue())\nexcept Exception as e:\n print(\"Exception\", e)\n raise\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> for l in list1: array = np.array(l) tolist = array.tolist() tolist.insert(0, 'ppp') tolist.append('lll') mysql_data.append(tolist) print(mysql_data) <|reserved_special_token_0|> print(get.text) <|reserved_special_token_1|> list1 = [('北京大洋路', '红蛋', '散框批发', '120-125', '44', '落', '8车'), ('北京回龙观', '红蛋', '散框批发', '124', '44', '落', ''), ('北京石门', '红蛋', '散框批发', '124', '44', '落', '')] mysql_data = [] <|reserved_special_token_0|> for l in list1: array = np.array(l) tolist = array.tolist() tolist.insert(0, 'ppp') tolist.append('lll') mysql_data.append(tolist) print(mysql_data) <|reserved_special_token_0|> headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36' } get = requests.get('http://www.baidu.com', headers=headers) print(get.text) <|reserved_special_token_1|> list1 = [('北京大洋路', '红蛋', '散框批发', '120-125', '44', '落', '8车'), ('北京回龙观', '红蛋', '散框批发', '124', '44', '落', ''), ('北京石门', '红蛋', '散框批发', '124', '44', '落', '')] mysql_data = [] import numpy as np for l in list1: array = np.array(l) tolist = array.tolist() tolist.insert(0, 'ppp') tolist.append('lll') mysql_data.append(tolist) print(mysql_data) import requests headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36' } get = requests.get('http://www.baidu.com', headers=headers) print(get.text)
flexible
{ "blob_id": "896d836ede533bad24f4077e5ba964105d96bf7a", "index": 9485, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor l in list1:\n array = np.array(l)\n tolist = array.tolist()\n tolist.insert(0, 'ppp')\n tolist.append('lll')\n mysql_data.append(tolist)\nprint(mysql_data)\n<mask token>\nprint(get.text)\n", "step-3": "list1 = [('北京大洋路', '红蛋', '散框批发', '120-125', '44', '落', '8车'), ('北京回龙观',\n '红蛋', '散框批发', '124', '44', '落', ''), ('北京石门', '红蛋', '散框批发', '124', '44',\n '落', '')]\nmysql_data = []\n<mask token>\nfor l in list1:\n array = np.array(l)\n tolist = array.tolist()\n tolist.insert(0, 'ppp')\n tolist.append('lll')\n mysql_data.append(tolist)\nprint(mysql_data)\n<mask token>\nheaders = {'User-Agent':\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'\n }\nget = requests.get('http://www.baidu.com', headers=headers)\nprint(get.text)\n", "step-4": "list1 = [('北京大洋路', '红蛋', '散框批发', '120-125', '44', '落', '8车'), ('北京回龙观',\n '红蛋', '散框批发', '124', '44', '落', ''), ('北京石门', '红蛋', '散框批发', '124', '44',\n '落', '')]\nmysql_data = []\nimport numpy as np\nfor l in list1:\n array = np.array(l)\n tolist = array.tolist()\n tolist.insert(0, 'ppp')\n tolist.append('lll')\n mysql_data.append(tolist)\nprint(mysql_data)\nimport requests\nheaders = {'User-Agent':\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'\n }\nget = requests.get('http://www.baidu.com', headers=headers)\nprint(get.text)\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> def LemNormalize(text): return nltk.word_tokenize(text.lower().translate(remove_punct_dict)) <|reserved_special_token_0|> def greeting(sentence): for word in sentence.split(): if word.lower() in GREETING_INPUTS: return random.choice(GREETING_RESPONSE) def responce(user_responce): user_responce = user_responce.lower() robo_responce = '' sent_tokens.append(user_responce) TfidVec = TfidfVectorizer(tokenizer=LemNormalize, stop_words='english') tfidf = TfidVec.fit_transform(sent_tokens) vals = cosine_similarity(tfidf[-1], tfidf) idx = vals.argsort()[0][-2] flat = vals.flatten() flat.sort() score = flat[-2] if score == 0: robo_responce = robo_responce + "i aplogise i didn't understand" else: robo_responce = robo_responce + sent_tokens[idx] sent_tokens.remove(user_responce) return robo_responce <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> warnings.filterwarnings('ignore') nltk.download('punkt', quiet=True) nltk.download('wordnet', quiet=True) <|reserved_special_token_0|> article.download() article.parse() article.nlp() <|reserved_special_token_0|> def LemNormalize(text): return nltk.word_tokenize(text.lower().translate(remove_punct_dict)) <|reserved_special_token_0|> def greeting(sentence): for word in sentence.split(): if word.lower() in GREETING_INPUTS: return random.choice(GREETING_RESPONSE) def responce(user_responce): user_responce = user_responce.lower() robo_responce = '' sent_tokens.append(user_responce) TfidVec = TfidfVectorizer(tokenizer=LemNormalize, stop_words='english') tfidf = TfidVec.fit_transform(sent_tokens) vals = cosine_similarity(tfidf[-1], tfidf) idx = vals.argsort()[0][-2] flat = vals.flatten() flat.sort() score = flat[-2] if score == 0: robo_responce = robo_responce + "i aplogise i didn't understand" else: robo_responce = robo_responce + sent_tokens[idx] sent_tokens.remove(user_responce) return robo_responce <|reserved_special_token_0|> with sr.Microphone() as source: flag = True print('BOT:Iam doctor bot and iam going to answeer your questions') while flag == True: print('speak:') audio = r.listen(source) try: text = r.recognize_google(audio) print('you said:{}'.format(text)) user_responce = text if user_responce != 'bye': if user_responce == 'thanks' or user_responce == 'thank you': flag = False print('BOT:you are welcome') elif greeting(user_responce) != None: print('BOT:' + greeting(user_responce)) else: print('BOT: ' + responce(user_responce)) else: flag = False print('BOT:chat with u later') except: print('could not recognize') <|reserved_special_token_1|> <|reserved_special_token_0|> warnings.filterwarnings('ignore') nltk.download('punkt', quiet=True) nltk.download('wordnet', quiet=True) article = Article( 'https://www.mayoclinic.org/diseases-conditions/chronic-kidney-disease/symptoms-causes/syc-20354521' ) article.download() article.parse() article.nlp() corpus = article.text text = corpus sent_tokens = nltk.sent_tokenize(text) remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation) def LemNormalize(text): return nltk.word_tokenize(text.lower().translate(remove_punct_dict)) GREETING_INPUTS = ['hi', 'hello', 'hola', 'greetings', 'wassup', 'hey'] GREETING_RESPONSE = ['howdy', 'hi', 'hey', "what's good", 'hello'] def greeting(sentence): for word in sentence.split(): if word.lower() in GREETING_INPUTS: return random.choice(GREETING_RESPONSE) def responce(user_responce): user_responce = user_responce.lower() robo_responce = '' sent_tokens.append(user_responce) TfidVec = TfidfVectorizer(tokenizer=LemNormalize, stop_words='english') tfidf = TfidVec.fit_transform(sent_tokens) vals = cosine_similarity(tfidf[-1], tfidf) idx = vals.argsort()[0][-2] flat = vals.flatten() flat.sort() score = flat[-2] if score == 0: robo_responce = robo_responce + "i aplogise i didn't understand" else: robo_responce = robo_responce + sent_tokens[idx] sent_tokens.remove(user_responce) return robo_responce r = sr.Recognizer() with sr.Microphone() as source: flag = True print('BOT:Iam doctor bot and iam going to answeer your questions') while flag == True: print('speak:') audio = r.listen(source) try: text = r.recognize_google(audio) print('you said:{}'.format(text)) user_responce = text if user_responce != 'bye': if user_responce == 'thanks' or user_responce == 'thank you': flag = False print('BOT:you are welcome') elif greeting(user_responce) != None: print('BOT:' + greeting(user_responce)) else: print('BOT: ' + responce(user_responce)) else: flag = False print('BOT:chat with u later') except: print('could not recognize') <|reserved_special_token_1|> from newspaper import Article import random import string from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity import nltk import numpy as np import warnings import speech_recognition as sr warnings.filterwarnings('ignore') nltk.download('punkt', quiet=True) nltk.download('wordnet', quiet=True) article = Article( 'https://www.mayoclinic.org/diseases-conditions/chronic-kidney-disease/symptoms-causes/syc-20354521' ) article.download() article.parse() article.nlp() corpus = article.text text = corpus sent_tokens = nltk.sent_tokenize(text) remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation) def LemNormalize(text): return nltk.word_tokenize(text.lower().translate(remove_punct_dict)) GREETING_INPUTS = ['hi', 'hello', 'hola', 'greetings', 'wassup', 'hey'] GREETING_RESPONSE = ['howdy', 'hi', 'hey', "what's good", 'hello'] def greeting(sentence): for word in sentence.split(): if word.lower() in GREETING_INPUTS: return random.choice(GREETING_RESPONSE) def responce(user_responce): user_responce = user_responce.lower() robo_responce = '' sent_tokens.append(user_responce) TfidVec = TfidfVectorizer(tokenizer=LemNormalize, stop_words='english') tfidf = TfidVec.fit_transform(sent_tokens) vals = cosine_similarity(tfidf[-1], tfidf) idx = vals.argsort()[0][-2] flat = vals.flatten() flat.sort() score = flat[-2] if score == 0: robo_responce = robo_responce + "i aplogise i didn't understand" else: robo_responce = robo_responce + sent_tokens[idx] sent_tokens.remove(user_responce) return robo_responce r = sr.Recognizer() with sr.Microphone() as source: flag = True print('BOT:Iam doctor bot and iam going to answeer your questions') while flag == True: print('speak:') audio = r.listen(source) try: text = r.recognize_google(audio) print('you said:{}'.format(text)) user_responce = text if user_responce != 'bye': if user_responce == 'thanks' or user_responce == 'thank you': flag = False print('BOT:you are welcome') elif greeting(user_responce) != None: print('BOT:' + greeting(user_responce)) else: print('BOT: ' + responce(user_responce)) else: flag = False print('BOT:chat with u later') except: print('could not recognize') <|reserved_special_token_1|> from newspaper import Article import random import string from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity import nltk import numpy as np import warnings import speech_recognition as sr warnings.filterwarnings('ignore') nltk.download('punkt',quiet=True) nltk.download('wordnet',quiet=True) article=Article('https://www.mayoclinic.org/diseases-conditions/chronic-kidney-disease/symptoms-causes/syc-20354521') article.download() article.parse() article.nlp() corpus=article.text #print(corpus) text=corpus sent_tokens=nltk.sent_tokenize(text)#convert the text into a alist of sentences #print(sent_tokens) #creatre a dictionary (key:value) pair to remove punctuations remove_punct_dict=dict( (ord(punct),None) for punct in string.punctuation) #print(string.punctuation) #print(remove_punct_dict) #create ala function to return a list of lenmatized lowercase words after removing puctuatuins.i,e all the sentences in the article are now converted into a list def LemNormalize(text): return nltk.word_tokenize(text.lower().translate(remove_punct_dict)) #prints the tokenozation text by removing the punctuation #print(LemNormalize(text)) #keyword matching #GREETINGS INPUT GREETING_INPUTS=["hi","hello","hola","greetings","wassup","hey"] #greeting response back GREETING_RESPONSE=["howdy","hi","hey","what's good","hello"] #function to return a random greeting response def greeting(sentence): #return a randomly choosen responce for word in sentence.split(): if word.lower() in GREETING_INPUTS: return random.choice(GREETING_RESPONSE) #generate the respnse to the given question def responce(user_responce): #the user's query is taken #user_responce='what is chronic kidney disease' #the user may give his input as capitals so we should convert them into lower() user_responce=user_responce.lower() #set the chat bot respnse to an empt srting i.e declare the roborespnse as a string robo_responce='' #convert the user_responce into a list sent_tokens.append(user_responce) #create a TfidVectorizer object it is used to know how man tomes a word has occured TfidVec=TfidfVectorizer(tokenizer=LemNormalize,stop_words='english') #convert the text into a matrix of TF-IDF features tfidf=TfidVec.fit_transform(sent_tokens) #print(tfidf) #get the measure of similarity(similarit scores) vals=cosine_similarity(tfidf[-1],tfidf) #print(vals) #get the index of the most similar text/sentence to the user response idx=vals.argsort()[0][-2] #reduce the domensionalit of vals flat=vals.flatten() #sort the list in asc flat.sort() #get the most simliar score for the user's responce score=flat[-2] #print the similarit score #print(score) #if the score is 0 then the most similar score to the user resoponce if(score==0): robo_responce=robo_responce+"i aplogise i didn't understand" else: robo_responce=robo_responce+sent_tokens[idx] #pritn the chat bot respnce #print(robo_responce) sent_tokens.remove(user_responce) return robo_responce r=sr.Recognizer() with sr.Microphone() as source: flag=True print("BOT:Iam doctor bot and iam going to answeer your questions") while(flag==True): print("speak:") audio=r.listen(source) try: text=r.recognize_google(audio) print("you said:{}".format(text)) user_responce=text if(user_responce!='bye'): if(user_responce=='thanks' or user_responce=='thank you'): flag=False print("BOT:you are welcome") else: if(greeting(user_responce)!=None): print("BOT:"+greeting(user_responce)) else: print("BOT: "+responce(user_responce)) else: flag=False print("BOT:chat with u later") except: print("could not recognize")
flexible
{ "blob_id": "53b56cf9265a658d999388f0a1e03d7ceb186213", "index": 2836, "step-1": "<mask token>\n\n\ndef LemNormalize(text):\n return nltk.word_tokenize(text.lower().translate(remove_punct_dict))\n\n\n<mask token>\n\n\ndef greeting(sentence):\n for word in sentence.split():\n if word.lower() in GREETING_INPUTS:\n return random.choice(GREETING_RESPONSE)\n\n\ndef responce(user_responce):\n user_responce = user_responce.lower()\n robo_responce = ''\n sent_tokens.append(user_responce)\n TfidVec = TfidfVectorizer(tokenizer=LemNormalize, stop_words='english')\n tfidf = TfidVec.fit_transform(sent_tokens)\n vals = cosine_similarity(tfidf[-1], tfidf)\n idx = vals.argsort()[0][-2]\n flat = vals.flatten()\n flat.sort()\n score = flat[-2]\n if score == 0:\n robo_responce = robo_responce + \"i aplogise i didn't understand\"\n else:\n robo_responce = robo_responce + sent_tokens[idx]\n sent_tokens.remove(user_responce)\n return robo_responce\n\n\n<mask token>\n", "step-2": "<mask token>\nwarnings.filterwarnings('ignore')\nnltk.download('punkt', quiet=True)\nnltk.download('wordnet', quiet=True)\n<mask token>\narticle.download()\narticle.parse()\narticle.nlp()\n<mask token>\n\n\ndef LemNormalize(text):\n return nltk.word_tokenize(text.lower().translate(remove_punct_dict))\n\n\n<mask token>\n\n\ndef greeting(sentence):\n for word in sentence.split():\n if word.lower() in GREETING_INPUTS:\n return random.choice(GREETING_RESPONSE)\n\n\ndef responce(user_responce):\n user_responce = user_responce.lower()\n robo_responce = ''\n sent_tokens.append(user_responce)\n TfidVec = TfidfVectorizer(tokenizer=LemNormalize, stop_words='english')\n tfidf = TfidVec.fit_transform(sent_tokens)\n vals = cosine_similarity(tfidf[-1], tfidf)\n idx = vals.argsort()[0][-2]\n flat = vals.flatten()\n flat.sort()\n score = flat[-2]\n if score == 0:\n robo_responce = robo_responce + \"i aplogise i didn't understand\"\n else:\n robo_responce = robo_responce + sent_tokens[idx]\n sent_tokens.remove(user_responce)\n return robo_responce\n\n\n<mask token>\nwith sr.Microphone() as source:\n flag = True\n print('BOT:Iam doctor bot and iam going to answeer your questions')\n while flag == True:\n print('speak:')\n audio = r.listen(source)\n try:\n text = r.recognize_google(audio)\n print('you said:{}'.format(text))\n user_responce = text\n if user_responce != 'bye':\n if user_responce == 'thanks' or user_responce == 'thank you':\n flag = False\n print('BOT:you are welcome')\n elif greeting(user_responce) != None:\n print('BOT:' + greeting(user_responce))\n else:\n print('BOT: ' + responce(user_responce))\n else:\n flag = False\n print('BOT:chat with u later')\n except:\n print('could not recognize')\n", "step-3": "<mask token>\nwarnings.filterwarnings('ignore')\nnltk.download('punkt', quiet=True)\nnltk.download('wordnet', quiet=True)\narticle = Article(\n 'https://www.mayoclinic.org/diseases-conditions/chronic-kidney-disease/symptoms-causes/syc-20354521'\n )\narticle.download()\narticle.parse()\narticle.nlp()\ncorpus = article.text\ntext = corpus\nsent_tokens = nltk.sent_tokenize(text)\nremove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)\n\n\ndef LemNormalize(text):\n return nltk.word_tokenize(text.lower().translate(remove_punct_dict))\n\n\nGREETING_INPUTS = ['hi', 'hello', 'hola', 'greetings', 'wassup', 'hey']\nGREETING_RESPONSE = ['howdy', 'hi', 'hey', \"what's good\", 'hello']\n\n\ndef greeting(sentence):\n for word in sentence.split():\n if word.lower() in GREETING_INPUTS:\n return random.choice(GREETING_RESPONSE)\n\n\ndef responce(user_responce):\n user_responce = user_responce.lower()\n robo_responce = ''\n sent_tokens.append(user_responce)\n TfidVec = TfidfVectorizer(tokenizer=LemNormalize, stop_words='english')\n tfidf = TfidVec.fit_transform(sent_tokens)\n vals = cosine_similarity(tfidf[-1], tfidf)\n idx = vals.argsort()[0][-2]\n flat = vals.flatten()\n flat.sort()\n score = flat[-2]\n if score == 0:\n robo_responce = robo_responce + \"i aplogise i didn't understand\"\n else:\n robo_responce = robo_responce + sent_tokens[idx]\n sent_tokens.remove(user_responce)\n return robo_responce\n\n\nr = sr.Recognizer()\nwith sr.Microphone() as source:\n flag = True\n print('BOT:Iam doctor bot and iam going to answeer your questions')\n while flag == True:\n print('speak:')\n audio = r.listen(source)\n try:\n text = r.recognize_google(audio)\n print('you said:{}'.format(text))\n user_responce = text\n if user_responce != 'bye':\n if user_responce == 'thanks' or user_responce == 'thank you':\n flag = False\n print('BOT:you are welcome')\n elif greeting(user_responce) != None:\n print('BOT:' + greeting(user_responce))\n else:\n print('BOT: ' + responce(user_responce))\n else:\n flag = False\n print('BOT:chat with u later')\n except:\n print('could not recognize')\n", "step-4": "from newspaper import Article\nimport random\nimport string\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport nltk\nimport numpy as np\nimport warnings\nimport speech_recognition as sr\nwarnings.filterwarnings('ignore')\nnltk.download('punkt', quiet=True)\nnltk.download('wordnet', quiet=True)\narticle = Article(\n 'https://www.mayoclinic.org/diseases-conditions/chronic-kidney-disease/symptoms-causes/syc-20354521'\n )\narticle.download()\narticle.parse()\narticle.nlp()\ncorpus = article.text\ntext = corpus\nsent_tokens = nltk.sent_tokenize(text)\nremove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)\n\n\ndef LemNormalize(text):\n return nltk.word_tokenize(text.lower().translate(remove_punct_dict))\n\n\nGREETING_INPUTS = ['hi', 'hello', 'hola', 'greetings', 'wassup', 'hey']\nGREETING_RESPONSE = ['howdy', 'hi', 'hey', \"what's good\", 'hello']\n\n\ndef greeting(sentence):\n for word in sentence.split():\n if word.lower() in GREETING_INPUTS:\n return random.choice(GREETING_RESPONSE)\n\n\ndef responce(user_responce):\n user_responce = user_responce.lower()\n robo_responce = ''\n sent_tokens.append(user_responce)\n TfidVec = TfidfVectorizer(tokenizer=LemNormalize, stop_words='english')\n tfidf = TfidVec.fit_transform(sent_tokens)\n vals = cosine_similarity(tfidf[-1], tfidf)\n idx = vals.argsort()[0][-2]\n flat = vals.flatten()\n flat.sort()\n score = flat[-2]\n if score == 0:\n robo_responce = robo_responce + \"i aplogise i didn't understand\"\n else:\n robo_responce = robo_responce + sent_tokens[idx]\n sent_tokens.remove(user_responce)\n return robo_responce\n\n\nr = sr.Recognizer()\nwith sr.Microphone() as source:\n flag = True\n print('BOT:Iam doctor bot and iam going to answeer your questions')\n while flag == True:\n print('speak:')\n audio = r.listen(source)\n try:\n text = r.recognize_google(audio)\n print('you said:{}'.format(text))\n user_responce = text\n if user_responce != 'bye':\n if user_responce == 'thanks' or user_responce == 'thank you':\n flag = False\n print('BOT:you are welcome')\n elif greeting(user_responce) != None:\n print('BOT:' + greeting(user_responce))\n else:\n print('BOT: ' + responce(user_responce))\n else:\n flag = False\n print('BOT:chat with u later')\n except:\n print('could not recognize')\n", "step-5": "from newspaper import Article\r\nimport random\r\nimport string\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nfrom sklearn.metrics.pairwise import cosine_similarity\r\nimport nltk\r\nimport numpy as np\r\nimport warnings\r\nimport speech_recognition as sr\r\n\r\n\r\n\r\nwarnings.filterwarnings('ignore')\r\nnltk.download('punkt',quiet=True)\r\nnltk.download('wordnet',quiet=True)\r\narticle=Article('https://www.mayoclinic.org/diseases-conditions/chronic-kidney-disease/symptoms-causes/syc-20354521')\r\narticle.download()\r\narticle.parse()\r\narticle.nlp()\r\ncorpus=article.text\r\n#print(corpus)\r\n \r\ntext=corpus\r\nsent_tokens=nltk.sent_tokenize(text)#convert the text into a alist of sentences\r\n#print(sent_tokens)\r\n\r\n#creatre a dictionary (key:value) pair to remove punctuations\r\nremove_punct_dict=dict( (ord(punct),None) for punct in string.punctuation)\r\n#print(string.punctuation)\r\n#print(remove_punct_dict)\r\n\r\n#create ala function to return a list of lenmatized lowercase words after removing puctuatuins.i,e all the sentences in the article are now converted into a list\r\ndef LemNormalize(text):\r\n return nltk.word_tokenize(text.lower().translate(remove_punct_dict))\r\n#prints the tokenozation text by removing the punctuation\r\n\r\n#print(LemNormalize(text))\r\n\r\n#keyword matching\r\n#GREETINGS INPUT\r\nGREETING_INPUTS=[\"hi\",\"hello\",\"hola\",\"greetings\",\"wassup\",\"hey\"]\r\n#greeting response back\r\nGREETING_RESPONSE=[\"howdy\",\"hi\",\"hey\",\"what's good\",\"hello\"]\r\n#function to return a random greeting response\r\ndef greeting(sentence):\r\n #return a randomly choosen responce\r\n for word in sentence.split():\r\n if word.lower() in GREETING_INPUTS:\r\n return random.choice(GREETING_RESPONSE)\r\n\r\n\r\n\r\n\r\n#generate the respnse to the given question\r\ndef responce(user_responce):\r\n \r\n#the user's query is taken \r\n #user_responce='what is chronic kidney disease'\r\n#the user may give his input as capitals so we should convert them into lower()\r\n user_responce=user_responce.lower()\r\n#set the chat bot respnse to an empt srting i.e declare the roborespnse as a string\r\n robo_responce=''\r\n#convert the user_responce into a list\r\n sent_tokens.append(user_responce)\r\n#create a TfidVectorizer object it is used to know how man tomes a word has occured\r\n TfidVec=TfidfVectorizer(tokenizer=LemNormalize,stop_words='english')\r\n#convert the text into a matrix of TF-IDF features\r\n tfidf=TfidVec.fit_transform(sent_tokens)\r\n#print(tfidf)\r\n\r\n#get the measure of similarity(similarit scores)\r\n vals=cosine_similarity(tfidf[-1],tfidf)\r\n#print(vals)\r\n#get the index of the most similar text/sentence to the user response\r\n idx=vals.argsort()[0][-2]\r\n\r\n #reduce the domensionalit of vals\r\n flat=vals.flatten()\r\n#sort the list in asc\r\n flat.sort()\r\n#get the most simliar score for the user's responce\r\n score=flat[-2]\r\n\r\n\r\n#print the similarit score\r\n#print(score) \r\n#if the score is 0 then the most similar score to the user resoponce\r\n if(score==0):\r\n robo_responce=robo_responce+\"i aplogise i didn't understand\"\r\n else:\r\n robo_responce=robo_responce+sent_tokens[idx]\r\n \r\n#pritn the chat bot respnce\r\n #print(robo_responce)\r\n sent_tokens.remove(user_responce)\r\n return robo_responce\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nr=sr.Recognizer()\r\nwith sr.Microphone() as source:\r\n\r\n\r\n flag=True\r\n print(\"BOT:Iam doctor bot and iam going to answeer your questions\")\r\n while(flag==True):\r\n print(\"speak:\")\r\n audio=r.listen(source)\r\n try:\r\n text=r.recognize_google(audio)\r\n print(\"you said:{}\".format(text))\r\n user_responce=text\r\n if(user_responce!='bye'):\r\n if(user_responce=='thanks' or user_responce=='thank you'):\r\n flag=False\r\n print(\"BOT:you are welcome\")\r\n else:\r\n if(greeting(user_responce)!=None):\r\n print(\"BOT:\"+greeting(user_responce))\r\n else:\r\n print(\"BOT: \"+responce(user_responce))\r\n \r\n else:\r\n flag=False\r\n print(\"BOT:chat with u later\")\r\n except:\r\n print(\"could not recognize\")\r\n ", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
c_horas=int(input("Ingrese la cantidad de horas trabajadas:")) v_horas=int(input("Ingrese el valor de cada hora trabajada:")) sueldo=c_horas*v_horas print("Su sueldo mensual sera") print(sueldo)
normal
{ "blob_id": "2e4b47b8c3ac4f187b32f1013a34c3bea354b519", "index": 6817, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint('Su sueldo mensual sera')\nprint(sueldo)\n", "step-3": "c_horas = int(input('Ingrese la cantidad de horas trabajadas:'))\nv_horas = int(input('Ingrese el valor de cada hora trabajada:'))\nsueldo = c_horas * v_horas\nprint('Su sueldo mensual sera')\nprint(sueldo)\n", "step-4": "c_horas=int(input(\"Ingrese la cantidad de horas trabajadas:\"))\r\nv_horas=int(input(\"Ingrese el valor de cada hora trabajada:\"))\r\nsueldo=c_horas*v_horas\r\nprint(\"Su sueldo mensual sera\")\r\nprint(sueldo)\r\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
''' Created on Nov 1, 2013 @author: hanchensu ''' from numpy import * import numpy as np def smoSimple(dataMatIn, classLabels, C, toler, maxIter): dataMatrix = mat(dataMatIn); labelMat = mat(classLabels).transpose() b = 0; m,n = shape(dataMatrix) matrix = mat([[1,2],[3,4],[5,6]]) m,n= shape(matrix) matA = mat([[1,2],[2,3],[5,6]]) matB = mat([1,2,3]).transpose() print matA print matB print multiply(matA,matB) # x1 = np.arange(9.0).reshape((3, 3)) # x2 = np.arange(3.0) # print x1 # print x2 # print np.multiply(x1, x2)
normal
{ "blob_id": "9bf8834b12bcace0f6daf64adae1babe78bb04fa", "index": 5553, "step-1": "'''\nCreated on Nov 1, 2013\n\n@author: hanchensu\n'''\nfrom numpy import *\nimport numpy as np\n\ndef smoSimple(dataMatIn, classLabels, C, toler, maxIter):\n dataMatrix = mat(dataMatIn); labelMat = mat(classLabels).transpose()\n b = 0; m,n = shape(dataMatrix)\n \nmatrix = mat([[1,2],[3,4],[5,6]])\nm,n= shape(matrix)\n\nmatA = mat([[1,2],[2,3],[5,6]])\nmatB = mat([1,2,3]).transpose()\nprint matA\nprint matB\nprint multiply(matA,matB) \n\n# x1 = np.arange(9.0).reshape((3, 3))\n# x2 = np.arange(3.0)\n# print x1\n# print x2\n# print np.multiply(x1, x2)", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
# encoding = utf-8 import hmac import time from hashlib import sha1 def get_signature(now_): # 签名由clientId,grantType,source,timestamp四个参数生成 h = hmac.new( key='d1b964811afb40118a12068ff74a12f4'.encode('utf-8'), digestmod=sha1) grant_type = 'password' client_id = 'c3cef7c66a1843f8b3a9e6a1e3160e20' source = 'com.zhihu.web' now = now_ h.update((grant_type + client_id + source + now).encode('utf-8')) return h.hexdigest() timestamp = str(int(time.time() * 1000)) signature = get_signature(timestamp) print(signature)
normal
{ "blob_id": "757a69f9ceaa3434c6d9f8b1fcdbadd991190f29", "index": 9315, "step-1": "<mask token>\n\n\ndef get_signature(now_):\n h = hmac.new(key='d1b964811afb40118a12068ff74a12f4'.encode('utf-8'),\n digestmod=sha1)\n grant_type = 'password'\n client_id = 'c3cef7c66a1843f8b3a9e6a1e3160e20'\n source = 'com.zhihu.web'\n now = now_\n h.update((grant_type + client_id + source + now).encode('utf-8'))\n return h.hexdigest()\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef get_signature(now_):\n h = hmac.new(key='d1b964811afb40118a12068ff74a12f4'.encode('utf-8'),\n digestmod=sha1)\n grant_type = 'password'\n client_id = 'c3cef7c66a1843f8b3a9e6a1e3160e20'\n source = 'com.zhihu.web'\n now = now_\n h.update((grant_type + client_id + source + now).encode('utf-8'))\n return h.hexdigest()\n\n\n<mask token>\nprint(signature)\n", "step-3": "<mask token>\n\n\ndef get_signature(now_):\n h = hmac.new(key='d1b964811afb40118a12068ff74a12f4'.encode('utf-8'),\n digestmod=sha1)\n grant_type = 'password'\n client_id = 'c3cef7c66a1843f8b3a9e6a1e3160e20'\n source = 'com.zhihu.web'\n now = now_\n h.update((grant_type + client_id + source + now).encode('utf-8'))\n return h.hexdigest()\n\n\ntimestamp = str(int(time.time() * 1000))\nsignature = get_signature(timestamp)\nprint(signature)\n", "step-4": "import hmac\nimport time\nfrom hashlib import sha1\n\n\ndef get_signature(now_):\n h = hmac.new(key='d1b964811afb40118a12068ff74a12f4'.encode('utf-8'),\n digestmod=sha1)\n grant_type = 'password'\n client_id = 'c3cef7c66a1843f8b3a9e6a1e3160e20'\n source = 'com.zhihu.web'\n now = now_\n h.update((grant_type + client_id + source + now).encode('utf-8'))\n return h.hexdigest()\n\n\ntimestamp = str(int(time.time() * 1000))\nsignature = get_signature(timestamp)\nprint(signature)\n", "step-5": "# encoding = utf-8\nimport hmac\nimport time\nfrom hashlib import sha1\n\n\ndef get_signature(now_):\n # 签名由clientId,grantType,source,timestamp四个参数生成\n h = hmac.new(\n key='d1b964811afb40118a12068ff74a12f4'.encode('utf-8'),\n digestmod=sha1)\n grant_type = 'password'\n client_id = 'c3cef7c66a1843f8b3a9e6a1e3160e20'\n source = 'com.zhihu.web'\n now = now_\n h.update((grant_type + client_id + source + now).encode('utf-8'))\n return h.hexdigest()\n\n\ntimestamp = str(int(time.time() * 1000))\nsignature = get_signature(timestamp)\nprint(signature)\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
<|reserved_special_token_0|> class MemoryCache: def __init__(self, store_key_getter=None, limit=0): self.store_key_getter = store_key_getter self.limit = limit self._cache = {} self.hashing = get_optimized_hashing() @property def store(self): if self.store_key_getter: return self._cache.setdefault(self.store_key_getter(), {}) return self._cache @property def limit_exceeded(self): return len(self.store) >= self.limit def __getitem__(self, key): return self.store.get(key) def __setitem__(self, key, value): if self.limit_exceeded: self.store.popitem() self.store.update({key: value}) <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class MemoryCache: def __init__(self, store_key_getter=None, limit=0): self.store_key_getter = store_key_getter self.limit = limit self._cache = {} self.hashing = get_optimized_hashing() @property def store(self): if self.store_key_getter: return self._cache.setdefault(self.store_key_getter(), {}) return self._cache @property def limit_exceeded(self): return len(self.store) >= self.limit def __getitem__(self, key): return self.store.get(key) def __setitem__(self, key, value): if self.limit_exceeded: self.store.popitem() self.store.update({key: value}) <|reserved_special_token_0|> def clear(self): del self._cache self._cache = {} <|reserved_special_token_1|> <|reserved_special_token_0|> class MemoryCache: def __init__(self, store_key_getter=None, limit=0): self.store_key_getter = store_key_getter self.limit = limit self._cache = {} self.hashing = get_optimized_hashing() @property def store(self): if self.store_key_getter: return self._cache.setdefault(self.store_key_getter(), {}) return self._cache @property def limit_exceeded(self): return len(self.store) >= self.limit def __getitem__(self, key): return self.store.get(key) def __setitem__(self, key, value): if self.limit_exceeded: self.store.popitem() self.store.update({key: value}) def get_or_set(self, key, getter): if self.limit == 0: return getter() hashed_key = self.hashing(key.encode('utf-8')).hexdigest() if not self[hashed_key]: self[hashed_key] = getter() return self[hashed_key] def clear(self): del self._cache self._cache = {} <|reserved_special_token_1|> from flask_minify.utils import get_optimized_hashing class MemoryCache: def __init__(self, store_key_getter=None, limit=0): self.store_key_getter = store_key_getter self.limit = limit self._cache = {} self.hashing = get_optimized_hashing() @property def store(self): if self.store_key_getter: return self._cache.setdefault(self.store_key_getter(), {}) return self._cache @property def limit_exceeded(self): return len(self.store) >= self.limit def __getitem__(self, key): return self.store.get(key) def __setitem__(self, key, value): if self.limit_exceeded: self.store.popitem() self.store.update({key: value}) def get_or_set(self, key, getter): if self.limit == 0: return getter() hashed_key = self.hashing(key.encode('utf-8')).hexdigest() if not self[hashed_key]: self[hashed_key] = getter() return self[hashed_key] def clear(self): del self._cache self._cache = {} <|reserved_special_token_1|> from flask_minify.utils import get_optimized_hashing class MemoryCache: def __init__(self, store_key_getter=None, limit=0): self.store_key_getter = store_key_getter self.limit = limit self._cache = {} self.hashing = get_optimized_hashing() @property def store(self): if self.store_key_getter: return self._cache.setdefault(self.store_key_getter(), {}) return self._cache @property def limit_exceeded(self): return len(self.store) >= self.limit def __getitem__(self, key): return self.store.get(key) def __setitem__(self, key, value): if self.limit_exceeded: self.store.popitem() self.store.update({key: value}) def get_or_set(self, key, getter): if self.limit == 0: return getter() hashed_key = self.hashing(key.encode("utf-8")).hexdigest() if not self[hashed_key]: self[hashed_key] = getter() return self[hashed_key] def clear(self): del self._cache self._cache = {}
flexible
{ "blob_id": "ef5c51a5c706387b62ef3f40c7cadf7dbef6d082", "index": 8671, "step-1": "<mask token>\n\n\nclass MemoryCache:\n\n def __init__(self, store_key_getter=None, limit=0):\n self.store_key_getter = store_key_getter\n self.limit = limit\n self._cache = {}\n self.hashing = get_optimized_hashing()\n\n @property\n def store(self):\n if self.store_key_getter:\n return self._cache.setdefault(self.store_key_getter(), {})\n return self._cache\n\n @property\n def limit_exceeded(self):\n return len(self.store) >= self.limit\n\n def __getitem__(self, key):\n return self.store.get(key)\n\n def __setitem__(self, key, value):\n if self.limit_exceeded:\n self.store.popitem()\n self.store.update({key: value})\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass MemoryCache:\n\n def __init__(self, store_key_getter=None, limit=0):\n self.store_key_getter = store_key_getter\n self.limit = limit\n self._cache = {}\n self.hashing = get_optimized_hashing()\n\n @property\n def store(self):\n if self.store_key_getter:\n return self._cache.setdefault(self.store_key_getter(), {})\n return self._cache\n\n @property\n def limit_exceeded(self):\n return len(self.store) >= self.limit\n\n def __getitem__(self, key):\n return self.store.get(key)\n\n def __setitem__(self, key, value):\n if self.limit_exceeded:\n self.store.popitem()\n self.store.update({key: value})\n <mask token>\n\n def clear(self):\n del self._cache\n self._cache = {}\n", "step-3": "<mask token>\n\n\nclass MemoryCache:\n\n def __init__(self, store_key_getter=None, limit=0):\n self.store_key_getter = store_key_getter\n self.limit = limit\n self._cache = {}\n self.hashing = get_optimized_hashing()\n\n @property\n def store(self):\n if self.store_key_getter:\n return self._cache.setdefault(self.store_key_getter(), {})\n return self._cache\n\n @property\n def limit_exceeded(self):\n return len(self.store) >= self.limit\n\n def __getitem__(self, key):\n return self.store.get(key)\n\n def __setitem__(self, key, value):\n if self.limit_exceeded:\n self.store.popitem()\n self.store.update({key: value})\n\n def get_or_set(self, key, getter):\n if self.limit == 0:\n return getter()\n hashed_key = self.hashing(key.encode('utf-8')).hexdigest()\n if not self[hashed_key]:\n self[hashed_key] = getter()\n return self[hashed_key]\n\n def clear(self):\n del self._cache\n self._cache = {}\n", "step-4": "from flask_minify.utils import get_optimized_hashing\n\n\nclass MemoryCache:\n\n def __init__(self, store_key_getter=None, limit=0):\n self.store_key_getter = store_key_getter\n self.limit = limit\n self._cache = {}\n self.hashing = get_optimized_hashing()\n\n @property\n def store(self):\n if self.store_key_getter:\n return self._cache.setdefault(self.store_key_getter(), {})\n return self._cache\n\n @property\n def limit_exceeded(self):\n return len(self.store) >= self.limit\n\n def __getitem__(self, key):\n return self.store.get(key)\n\n def __setitem__(self, key, value):\n if self.limit_exceeded:\n self.store.popitem()\n self.store.update({key: value})\n\n def get_or_set(self, key, getter):\n if self.limit == 0:\n return getter()\n hashed_key = self.hashing(key.encode('utf-8')).hexdigest()\n if not self[hashed_key]:\n self[hashed_key] = getter()\n return self[hashed_key]\n\n def clear(self):\n del self._cache\n self._cache = {}\n", "step-5": "from flask_minify.utils import get_optimized_hashing\n\n\nclass MemoryCache:\n def __init__(self, store_key_getter=None, limit=0):\n self.store_key_getter = store_key_getter\n self.limit = limit\n self._cache = {}\n self.hashing = get_optimized_hashing()\n\n @property\n def store(self):\n if self.store_key_getter:\n return self._cache.setdefault(self.store_key_getter(), {})\n\n return self._cache\n\n @property\n def limit_exceeded(self):\n return len(self.store) >= self.limit\n\n def __getitem__(self, key):\n return self.store.get(key)\n\n def __setitem__(self, key, value):\n if self.limit_exceeded:\n self.store.popitem()\n\n self.store.update({key: value})\n\n def get_or_set(self, key, getter):\n if self.limit == 0:\n return getter()\n\n hashed_key = self.hashing(key.encode(\"utf-8\")).hexdigest()\n\n if not self[hashed_key]:\n self[hashed_key] = getter()\n\n return self[hashed_key]\n\n def clear(self):\n del self._cache\n self._cache = {}\n", "step-ids": [ 6, 7, 8, 9, 10 ] }
[ 6, 7, 8, 9, 10 ]
''' 多线程更新UI数据(在两个线程中传递数据) ''' from PyQt5.QtCore import QThread , pyqtSignal, QDateTime from PyQt5.QtWidgets import QApplication, QDialog, QLineEdit import time import sys class BackendThread(QThread): update_date = pyqtSignal(str) def run(self): while True: data = QDateTime.currentDateTime() currentTime = data.toString("yyyy-MM-dd hh:mm:ss") self.update_date.emit(str(currentTime)) time.sleep(1) class ThreadUpdateUI(QDialog): def __init__(self): QDialog.__init__(self) self.setWindowTitle('多线程更新UI数据') self.resize(400,100) self.input = QLineEdit(self) self.input.resize(400,100) self.initUI() def initUI(self): self.backend = BackendThread() self.backend.update_date.connect(self.handleDisplay) self.backend.start() def handleDisplay(self,data): self.input.setText(data) if __name__ == '__main__': app = QApplication(sys.argv) example = ThreadUpdateUI() example.show() sys.exit(app.exec_())
normal
{ "blob_id": "ec625bf57388281b3cbd464459fc3ad1c60b7db9", "index": 3305, "step-1": "<mask token>\n\n\nclass BackendThread(QThread):\n <mask token>\n\n def run(self):\n while True:\n data = QDateTime.currentDateTime()\n currentTime = data.toString('yyyy-MM-dd hh:mm:ss')\n self.update_date.emit(str(currentTime))\n time.sleep(1)\n\n\nclass ThreadUpdateUI(QDialog):\n\n def __init__(self):\n QDialog.__init__(self)\n self.setWindowTitle('多线程更新UI数据')\n self.resize(400, 100)\n self.input = QLineEdit(self)\n self.input.resize(400, 100)\n self.initUI()\n\n def initUI(self):\n self.backend = BackendThread()\n self.backend.update_date.connect(self.handleDisplay)\n self.backend.start()\n\n def handleDisplay(self, data):\n self.input.setText(data)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass BackendThread(QThread):\n update_date = pyqtSignal(str)\n\n def run(self):\n while True:\n data = QDateTime.currentDateTime()\n currentTime = data.toString('yyyy-MM-dd hh:mm:ss')\n self.update_date.emit(str(currentTime))\n time.sleep(1)\n\n\nclass ThreadUpdateUI(QDialog):\n\n def __init__(self):\n QDialog.__init__(self)\n self.setWindowTitle('多线程更新UI数据')\n self.resize(400, 100)\n self.input = QLineEdit(self)\n self.input.resize(400, 100)\n self.initUI()\n\n def initUI(self):\n self.backend = BackendThread()\n self.backend.update_date.connect(self.handleDisplay)\n self.backend.start()\n\n def handleDisplay(self, data):\n self.input.setText(data)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass BackendThread(QThread):\n update_date = pyqtSignal(str)\n\n def run(self):\n while True:\n data = QDateTime.currentDateTime()\n currentTime = data.toString('yyyy-MM-dd hh:mm:ss')\n self.update_date.emit(str(currentTime))\n time.sleep(1)\n\n\nclass ThreadUpdateUI(QDialog):\n\n def __init__(self):\n QDialog.__init__(self)\n self.setWindowTitle('多线程更新UI数据')\n self.resize(400, 100)\n self.input = QLineEdit(self)\n self.input.resize(400, 100)\n self.initUI()\n\n def initUI(self):\n self.backend = BackendThread()\n self.backend.update_date.connect(self.handleDisplay)\n self.backend.start()\n\n def handleDisplay(self, data):\n self.input.setText(data)\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n example = ThreadUpdateUI()\n example.show()\n sys.exit(app.exec_())\n", "step-4": "<mask token>\nfrom PyQt5.QtCore import QThread, pyqtSignal, QDateTime\nfrom PyQt5.QtWidgets import QApplication, QDialog, QLineEdit\nimport time\nimport sys\n\n\nclass BackendThread(QThread):\n update_date = pyqtSignal(str)\n\n def run(self):\n while True:\n data = QDateTime.currentDateTime()\n currentTime = data.toString('yyyy-MM-dd hh:mm:ss')\n self.update_date.emit(str(currentTime))\n time.sleep(1)\n\n\nclass ThreadUpdateUI(QDialog):\n\n def __init__(self):\n QDialog.__init__(self)\n self.setWindowTitle('多线程更新UI数据')\n self.resize(400, 100)\n self.input = QLineEdit(self)\n self.input.resize(400, 100)\n self.initUI()\n\n def initUI(self):\n self.backend = BackendThread()\n self.backend.update_date.connect(self.handleDisplay)\n self.backend.start()\n\n def handleDisplay(self, data):\n self.input.setText(data)\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n example = ThreadUpdateUI()\n example.show()\n sys.exit(app.exec_())\n", "step-5": "'''\n\n多线程更新UI数据(在两个线程中传递数据)\n\n'''\n\nfrom PyQt5.QtCore import QThread , pyqtSignal, QDateTime\nfrom PyQt5.QtWidgets import QApplication, QDialog, QLineEdit\nimport time\nimport sys\n\n\nclass BackendThread(QThread):\n update_date = pyqtSignal(str)\n\n def run(self):\n while True:\n data = QDateTime.currentDateTime()\n currentTime = data.toString(\"yyyy-MM-dd hh:mm:ss\")\n self.update_date.emit(str(currentTime))\n time.sleep(1)\nclass ThreadUpdateUI(QDialog):\n def __init__(self):\n QDialog.__init__(self)\n self.setWindowTitle('多线程更新UI数据')\n self.resize(400,100)\n self.input = QLineEdit(self)\n self.input.resize(400,100)\n\n self.initUI()\n def initUI(self):\n self.backend = BackendThread()\n self.backend.update_date.connect(self.handleDisplay)\n\n self.backend.start()\n\n def handleDisplay(self,data):\n self.input.setText(data)\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n example = ThreadUpdateUI()\n example.show()\n sys.exit(app.exec_())", "step-ids": [ 6, 7, 8, 9, 10 ] }
[ 6, 7, 8, 9, 10 ]
#!/usr/bin/python import socket import threading import signal import sys class Proxy: #initialise server socket def __init__(self): self.serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.serverSocket.bind(('', 1700)) self.serverSocket.listen(1) self.__clients = {} #proxy thread to handle requests def proxy_thread(self, conn, client_addr): request = conn.recv(1024) # get the request from browser line = request.split('\n')[0] # parse the first line url = line.split(' ')[1] mName = 'localhost' mPort = 12000 proxySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) proxySocket.connect((mName,mPort)) proxySocket.send(url) #blacklist from proxy side response = proxySocket.recv(1024) if "blacklist" in response: conn.send('403: Forbidden') conn.close() return else: #get the host and port out the url path self.path = url[7:] i = self.path.find('/') host = self.path[:i] i = host.find(':') if i!=-1: port = int(host[i+1:]) host = host[:i] else: port = 80 try: # create a socket to connect to the web server webSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) webSocket.settimeout(5) webSocket.connect((host, port)) webSocket.sendall(request) # send request to webserver while 1: data = webSocket.recv(1024) # receive data from web server if (len(data) > 0): conn.send(data) # send to browser else: break webSocket.close() conn.close() except socket.error as error_msg: if webSocket: webSocket.close() if conn: conn.close() #listen for web client to send request def client(self): while True: (clientSocket, client_address) = self.serverSocket.accept() # Establish the connection p = threading.Thread(name=self._getClientName(client_address), target=self.proxy_thread, args=(clientSocket, client_address)) p.setDaemon(True) p.start() def _getClientName(self, cli_addr): return "Client" if __name__ == '__main__': proxy = Proxy() proxy.client()
normal
{ "blob_id": "2dcf0466c84c952c60dcfce86498f063f43726f3", "index": 2298, "step-1": "#!/usr/bin/python\n\nimport socket\nimport threading\nimport signal\nimport sys\n \nclass Proxy:\n #initialise server socket\n def __init__(self): \n self.serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) \n self.serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) \n self.serverSocket.bind(('', 1700)) \n self.serverSocket.listen(1) \n self.__clients = {}\n \n #proxy thread to handle requests\n def proxy_thread(self, conn, client_addr):\n\n request = conn.recv(1024) # get the request from browser\n \tline = request.split('\\n')[0] # parse the first line\n url = line.split(' ')[1] \n\n \tmName = 'localhost'\n \tmPort = 12000\n \tproxySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n \tproxySocket.connect((mName,mPort))\n \tproxySocket.send(url)\n \n #blacklist from proxy side\n\t\n\tresponse = proxySocket.recv(1024)\n\tif \"blacklist\" in response:\n\t\tconn.send('403: Forbidden')\n\t\tconn.close()\n\t\treturn\n\telse:\t\n\t #get the host and port out the url path\n\t \tself.path = url[7:]\n\t\ti = self.path.find('/')\n\t\thost = self.path[:i]\n\t \ti = host.find(':')\n\t\tif i!=-1:\n\t\t port = int(host[i+1:]) \n\t\t host = host[:i]\n\t\telse:\n\t\t port = 80\n\n\t\ttry:\n\t\t # create a socket to connect to the web server\n\t\t webSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\t webSocket.settimeout(5)\n\t\t webSocket.connect((host, port))\n\t\t webSocket.sendall(request) # send request to webserver\n\n\t\t while 1:\n\t\t data = webSocket.recv(1024) # receive data from web server\n\t\t if (len(data) > 0):\n\t\t conn.send(data) # send to browser\n\t\t else:\n\t\t break\n\t\t webSocket.close()\n\t\t conn.close()\n\n\t\texcept socket.error as error_msg:\n\t\t if webSocket:\n\t\t webSocket.close()\n\t\t if conn:\n\t\t conn.close() \n\n #listen for web client to send request\n def client(self):\n while True:\n (clientSocket, client_address) = self.serverSocket.accept() # Establish the connection\n p = threading.Thread(name=self._getClientName(client_address), target=self.proxy_thread, args=(clientSocket, client_address))\n p.setDaemon(True)\n p.start()\n\n def _getClientName(self, cli_addr):\n return \"Client\"\n\nif __name__ == '__main__':\t\n\tproxy = Proxy()\n\tproxy.client()\n\t\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> from ..translators.translator import Translator
flexible
{ "blob_id": "ab844143ceddf32982682f5092762af0c97db577", "index": 391, "step-1": "<mask token>\n", "step-2": "from ..translators.translator import Translator\n", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ] }
[ 0, 1 ]
#Print table using while loop tablenumber = int(input("Enter a number: ")) upperlimit = int(input("Enter a upper limit: ")) lowerlimit = int(input("Enter a lower limit: ")) i = upperlimit while (i <= lowerlimit): print (i,"*",tablenumber,"=",i*tablenumber) i=i+1 print("=======================================================") #Printing table using for loop tablenumber = int(input("Enter a number: ")) upperlimit = int(input("Enter a upper limit: ")) lowerlimit = int(input("Enter a lower limit: ")) for foreachnumber in range(upperlimit, lowerlimit+1): print (i,"*",tablenumber,"=",i*tablenumber) print("=======================================================")
normal
{ "blob_id": "e2c69191d81724cac44bebba3111a773e408b7c8", "index": 639, "step-1": "<mask token>\n", "step-2": "<mask token>\nwhile i <= lowerlimit:\n print(i, '*', tablenumber, '=', i * tablenumber)\n i = i + 1\nprint('=======================================================')\n<mask token>\nfor foreachnumber in range(upperlimit, lowerlimit + 1):\n print(i, '*', tablenumber, '=', i * tablenumber)\nprint('=======================================================')\n", "step-3": "tablenumber = int(input('Enter a number: '))\nupperlimit = int(input('Enter a upper limit: '))\nlowerlimit = int(input('Enter a lower limit: '))\ni = upperlimit\nwhile i <= lowerlimit:\n print(i, '*', tablenumber, '=', i * tablenumber)\n i = i + 1\nprint('=======================================================')\ntablenumber = int(input('Enter a number: '))\nupperlimit = int(input('Enter a upper limit: '))\nlowerlimit = int(input('Enter a lower limit: '))\nfor foreachnumber in range(upperlimit, lowerlimit + 1):\n print(i, '*', tablenumber, '=', i * tablenumber)\nprint('=======================================================')\n", "step-4": "#Print table using while loop\n\n\ntablenumber = int(input(\"Enter a number: \"))\nupperlimit = int(input(\"Enter a upper limit: \"))\nlowerlimit = int(input(\"Enter a lower limit: \"))\ni = upperlimit\nwhile (i <= lowerlimit):\n print (i,\"*\",tablenumber,\"=\",i*tablenumber)\n i=i+1\nprint(\"=======================================================\")\n#Printing table using for loop\n\ntablenumber = int(input(\"Enter a number: \"))\nupperlimit = int(input(\"Enter a upper limit: \"))\nlowerlimit = int(input(\"Enter a lower limit: \"))\nfor foreachnumber in range(upperlimit, lowerlimit+1):\n print (i,\"*\",tablenumber,\"=\",i*tablenumber)\nprint(\"=======================================================\")\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import streamlit as st import tensorflow.keras from PIL import Image, ImageOps import numpy as np st.set_option('deprecation.showfileUploaderEncoding', False) np.set_printoptions(suppress=True) model = tensorflow.keras.models.load_model('keras_model.h5') data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32) st.title("Leaf Disease Detection Using Machine Learning") uploaded_file = st.file_uploader("Choose an image...", type="JPG") if uploaded_file is not None: image = Image.open(uploaded_file) size = (224, 224) image = ImageOps.fit(image, size, Image.ANTIALIAS) image_array = np.asarray(image) #image.show() st.image(image, caption='Uploaded Image.', width=300) normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1 data[0] = normalized_image_array prediction = model.predict(data) data = np.rint(prediction) print(data) if(data[0][0]==1): st.write("Grape___Black_rot") if(data[0][1]==1): st.write("Grape___Esca_(Black_Measles)") if(data[0][2]==1): st.write("Grape___healthy") if(data[0][3]==1): st.write("Grape___Leaf_blight")
normal
{ "blob_id": "746e0895f0fb971156e778cbff20317cc88441f1", "index": 2059, "step-1": "<mask token>\n", "step-2": "<mask token>\nst.set_option('deprecation.showfileUploaderEncoding', False)\nnp.set_printoptions(suppress=True)\n<mask token>\nst.title('Leaf Disease Detection Using Machine Learning')\n<mask token>\nif uploaded_file is not None:\n image = Image.open(uploaded_file)\n size = 224, 224\n image = ImageOps.fit(image, size, Image.ANTIALIAS)\n image_array = np.asarray(image)\n st.image(image, caption='Uploaded Image.', width=300)\n normalized_image_array = image_array.astype(np.float32) / 127.0 - 1\n data[0] = normalized_image_array\n prediction = model.predict(data)\n data = np.rint(prediction)\n print(data)\n if data[0][0] == 1:\n st.write('Grape___Black_rot')\n if data[0][1] == 1:\n st.write('Grape___Esca_(Black_Measles)')\n if data[0][2] == 1:\n st.write('Grape___healthy')\n if data[0][3] == 1:\n st.write('Grape___Leaf_blight')\n", "step-3": "<mask token>\nst.set_option('deprecation.showfileUploaderEncoding', False)\nnp.set_printoptions(suppress=True)\nmodel = tensorflow.keras.models.load_model('keras_model.h5')\ndata = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)\nst.title('Leaf Disease Detection Using Machine Learning')\nuploaded_file = st.file_uploader('Choose an image...', type='JPG')\nif uploaded_file is not None:\n image = Image.open(uploaded_file)\n size = 224, 224\n image = ImageOps.fit(image, size, Image.ANTIALIAS)\n image_array = np.asarray(image)\n st.image(image, caption='Uploaded Image.', width=300)\n normalized_image_array = image_array.astype(np.float32) / 127.0 - 1\n data[0] = normalized_image_array\n prediction = model.predict(data)\n data = np.rint(prediction)\n print(data)\n if data[0][0] == 1:\n st.write('Grape___Black_rot')\n if data[0][1] == 1:\n st.write('Grape___Esca_(Black_Measles)')\n if data[0][2] == 1:\n st.write('Grape___healthy')\n if data[0][3] == 1:\n st.write('Grape___Leaf_blight')\n", "step-4": "import streamlit as st\nimport tensorflow.keras\nfrom PIL import Image, ImageOps\nimport numpy as np\nst.set_option('deprecation.showfileUploaderEncoding', False)\nnp.set_printoptions(suppress=True)\nmodel = tensorflow.keras.models.load_model('keras_model.h5')\ndata = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)\nst.title('Leaf Disease Detection Using Machine Learning')\nuploaded_file = st.file_uploader('Choose an image...', type='JPG')\nif uploaded_file is not None:\n image = Image.open(uploaded_file)\n size = 224, 224\n image = ImageOps.fit(image, size, Image.ANTIALIAS)\n image_array = np.asarray(image)\n st.image(image, caption='Uploaded Image.', width=300)\n normalized_image_array = image_array.astype(np.float32) / 127.0 - 1\n data[0] = normalized_image_array\n prediction = model.predict(data)\n data = np.rint(prediction)\n print(data)\n if data[0][0] == 1:\n st.write('Grape___Black_rot')\n if data[0][1] == 1:\n st.write('Grape___Esca_(Black_Measles)')\n if data[0][2] == 1:\n st.write('Grape___healthy')\n if data[0][3] == 1:\n st.write('Grape___Leaf_blight')\n", "step-5": "import streamlit as st\nimport tensorflow.keras\nfrom PIL import Image, ImageOps\nimport numpy as np\nst.set_option('deprecation.showfileUploaderEncoding', False)\nnp.set_printoptions(suppress=True)\nmodel = tensorflow.keras.models.load_model('keras_model.h5')\ndata = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)\nst.title(\"Leaf Disease Detection Using Machine Learning\")\n\nuploaded_file = st.file_uploader(\"Choose an image...\", type=\"JPG\")\nif uploaded_file is not None:\n image = Image.open(uploaded_file)\n size = (224, 224)\n image = ImageOps.fit(image, size, Image.ANTIALIAS)\n\n image_array = np.asarray(image)\n #image.show()\n st.image(image, caption='Uploaded Image.', width=300)\n normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1\n data[0] = normalized_image_array\n prediction = model.predict(data)\n data = np.rint(prediction)\n print(data)\n if(data[0][0]==1):\n st.write(\"Grape___Black_rot\")\n if(data[0][1]==1):\n st.write(\"Grape___Esca_(Black_Measles)\")\n if(data[0][2]==1):\n st.write(\"Grape___healthy\")\n if(data[0][3]==1):\n st.write(\"Grape___Leaf_blight\")\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
""" Supreme bot???? """ import os import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait import selenium.webdriver.support.expected_conditions as EC from selenium.common.exceptions import TimeoutException from selenium.webdriver.chrome.options import Options path_to_chromedriver = '/Users/Alan/Desktop/Github/SupremeBot/chromedriver' url = "https://www.supremenewyork.com/shop/new" path_to_log = '/Users/Alan/Desktop/' log_errors = open(path_to_log + 'log_errors.txt', mode = 'w') userProfile = "C:/Users/Alan/AppData/Local/Google/Chrome/User Data" chop = webdriver.ChromeOptions() chop.add_argument("user-data-dir=C:/Users/Alan/AppData/Local/Google/Chrome/User Data") def initDriver(): driver = webdriver.Chrome(executable_path=path_to_chromedriver, chrome_options=chop) driver.get(url) return driver def buyItem(theDriver): try: #Item you're trying to buy item = theDriver.find_element_by_xpath('//*[@id="container"]/article[44]/div/a').click() except TimeoutException: log_errors.write('Couldn\'t locate item' + '\n') def addCart(theDriver): try: print "Adding to Cart..." addCart = WebDriverWait(theDriver, 120).until(EC.element_to_be_clickable((By.NAME, 'commit'))) print addCart.get_attribute("value") addCart.click() except TimeoutException: print "Sold out!" log_errors.write('Sold out' + '\n') def checkout(theDriver): try: print "Checking out..." checkout = WebDriverWait(theDriver, 120).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="cart"]/a[2]'))) time.sleep(.25) checkout.click() except TimeoutException: print "Rip!" log_errors.write('Error' + '\n') def fillInfo(theDriver): try: print "Entering info..." except TimeoutException: print "Error filling info" def readAndAgree(theDriver): try: print "Clicking agree..." #agree = theDriver.find_elements_by_css_selector('.iCheck-helper') #agree[1].click() agree = WebDriverWait(theDriver, 120).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '.iCheck-helper'))) agree[1].click() except TimeoutException: print "Not found" def main(): print "Bot running" driver = initDriver() buyItem(driver) addCart(driver) checkout(driver) readAndAgree(driver) while True: time.sleep(50) if __name__ == '__main__': main() print "Finished"
normal
{ "blob_id": "8fed95cf809afca7b6008d5abcdcf697367a33c2", "index": 2929, "step-1": "\"\"\"\nSupreme bot????\n\n\"\"\"\nimport os\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nimport selenium.webdriver.support.expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.chrome.options import Options\n\npath_to_chromedriver = '/Users/Alan/Desktop/Github/SupremeBot/chromedriver'\nurl = \"https://www.supremenewyork.com/shop/new\"\npath_to_log = '/Users/Alan/Desktop/'\nlog_errors = open(path_to_log + 'log_errors.txt', mode = 'w')\nuserProfile = \"C:/Users/Alan/AppData/Local/Google/Chrome/User Data\"\n\n\nchop = webdriver.ChromeOptions()\nchop.add_argument(\"user-data-dir=C:/Users/Alan/AppData/Local/Google/Chrome/User Data\")\n\n\ndef initDriver():\n driver = webdriver.Chrome(executable_path=path_to_chromedriver, chrome_options=chop)\n driver.get(url)\n \n return driver\n\ndef buyItem(theDriver):\n try:\n #Item you're trying to buy\n item = theDriver.find_element_by_xpath('//*[@id=\"container\"]/article[44]/div/a').click()\n except TimeoutException:\n log_errors.write('Couldn\\'t locate item' + '\\n')\n\ndef addCart(theDriver):\n try:\n print \"Adding to Cart...\"\n addCart = WebDriverWait(theDriver, 120).until(EC.element_to_be_clickable((By.NAME, 'commit')))\n print addCart.get_attribute(\"value\")\n addCart.click()\n except TimeoutException:\n print \"Sold out!\"\n log_errors.write('Sold out' + '\\n')\n\ndef checkout(theDriver):\n try:\n print \"Checking out...\"\n checkout = WebDriverWait(theDriver, 120).until(EC.element_to_be_clickable((By.XPATH, '//*[@id=\"cart\"]/a[2]')))\n time.sleep(.25)\n checkout.click()\n except TimeoutException:\n print \"Rip!\"\n log_errors.write('Error' + '\\n')\n\ndef fillInfo(theDriver):\n try:\n print \"Entering info...\"\n except TimeoutException:\n print \"Error filling info\"\n\ndef readAndAgree(theDriver):\n try:\n print \"Clicking agree...\"\n \n #agree = theDriver.find_elements_by_css_selector('.iCheck-helper')\n #agree[1].click()\n \n agree = WebDriverWait(theDriver, 120).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '.iCheck-helper')))\n agree[1].click()\n except TimeoutException:\n print \"Not found\"\ndef main():\n print \"Bot running\"\n driver = initDriver()\n buyItem(driver)\n addCart(driver)\n checkout(driver)\n readAndAgree(driver)\n while True:\n time.sleep(50)\n\nif __name__ == '__main__':\n main()\n print \"Finished\"\n\n\n\n\n\n \n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
from __future__ import annotations import logging import os import sys from argparse import Namespace from pathlib import Path from uuid import uuid4 import pytest from virtualenv.discovery.builtin import Builtin, get_interpreter from virtualenv.discovery.py_info import PythonInfo from virtualenv.info import fs_supports_symlink @pytest.mark.skipif(not fs_supports_symlink(), reason="symlink not supported") @pytest.mark.parametrize("case", ["mixed", "lower", "upper"]) def test_discovery_via_path(monkeypatch, case, tmp_path, caplog, session_app_data): caplog.set_level(logging.DEBUG) current = PythonInfo.current_system(session_app_data) core = f"somethingVeryCryptic{'.'.join(str(i) for i in current.version_info[0:3])}" name = "somethingVeryCryptic" if case == "lower": name = name.lower() elif case == "upper": name = name.upper() exe_name = f"{name}{current.version_info.major}{'.exe' if sys.platform == 'win32' else ''}" target = tmp_path / current.install_path("scripts") target.mkdir(parents=True) executable = target / exe_name os.symlink(sys.executable, str(executable)) pyvenv_cfg = Path(sys.executable).parents[1] / "pyvenv.cfg" if pyvenv_cfg.exists(): (target / pyvenv_cfg.name).write_bytes(pyvenv_cfg.read_bytes()) new_path = os.pathsep.join([str(target), *os.environ.get("PATH", "").split(os.pathsep)]) monkeypatch.setenv("PATH", new_path) interpreter = get_interpreter(core, []) assert interpreter is not None def test_discovery_via_path_not_found(tmp_path, monkeypatch): monkeypatch.setenv("PATH", str(tmp_path)) interpreter = get_interpreter(uuid4().hex, []) assert interpreter is None def test_relative_path(session_app_data, monkeypatch): sys_executable = Path(PythonInfo.current_system(app_data=session_app_data).system_executable) cwd = sys_executable.parents[1] monkeypatch.chdir(str(cwd)) relative = str(sys_executable.relative_to(cwd)) result = get_interpreter(relative, [], session_app_data) assert result is not None def test_discovery_fallback_fail(session_app_data, caplog): caplog.set_level(logging.DEBUG) builtin = Builtin( Namespace(app_data=session_app_data, try_first_with=[], python=["magic-one", "magic-two"], env=os.environ), ) result = builtin.run() assert result is None assert "accepted" not in caplog.text def test_discovery_fallback_ok(session_app_data, caplog): caplog.set_level(logging.DEBUG) builtin = Builtin( Namespace(app_data=session_app_data, try_first_with=[], python=["magic-one", sys.executable], env=os.environ), ) result = builtin.run() assert result is not None, caplog.text assert result.executable == sys.executable, caplog.text assert "accepted" in caplog.text
normal
{ "blob_id": "55d4f4bba2b72ec93cb883527d2a9c2ebe8ec337", "index": 4910, "step-1": "<mask token>\n\n\ndef test_relative_path(session_app_data, monkeypatch):\n sys_executable = Path(PythonInfo.current_system(app_data=\n session_app_data).system_executable)\n cwd = sys_executable.parents[1]\n monkeypatch.chdir(str(cwd))\n relative = str(sys_executable.relative_to(cwd))\n result = get_interpreter(relative, [], session_app_data)\n assert result is not None\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\[email protected](not fs_supports_symlink(), reason='symlink not supported')\[email protected]('case', ['mixed', 'lower', 'upper'])\ndef test_discovery_via_path(monkeypatch, case, tmp_path, caplog,\n session_app_data):\n caplog.set_level(logging.DEBUG)\n current = PythonInfo.current_system(session_app_data)\n core = (\n f\"somethingVeryCryptic{'.'.join(str(i) for i in current.version_info[0:3])}\"\n )\n name = 'somethingVeryCryptic'\n if case == 'lower':\n name = name.lower()\n elif case == 'upper':\n name = name.upper()\n exe_name = (\n f\"{name}{current.version_info.major}{'.exe' if sys.platform == 'win32' else ''}\"\n )\n target = tmp_path / current.install_path('scripts')\n target.mkdir(parents=True)\n executable = target / exe_name\n os.symlink(sys.executable, str(executable))\n pyvenv_cfg = Path(sys.executable).parents[1] / 'pyvenv.cfg'\n if pyvenv_cfg.exists():\n (target / pyvenv_cfg.name).write_bytes(pyvenv_cfg.read_bytes())\n new_path = os.pathsep.join([str(target), *os.environ.get('PATH', '').\n split(os.pathsep)])\n monkeypatch.setenv('PATH', new_path)\n interpreter = get_interpreter(core, [])\n assert interpreter is not None\n\n\ndef test_discovery_via_path_not_found(tmp_path, monkeypatch):\n monkeypatch.setenv('PATH', str(tmp_path))\n interpreter = get_interpreter(uuid4().hex, [])\n assert interpreter is None\n\n\ndef test_relative_path(session_app_data, monkeypatch):\n sys_executable = Path(PythonInfo.current_system(app_data=\n session_app_data).system_executable)\n cwd = sys_executable.parents[1]\n monkeypatch.chdir(str(cwd))\n relative = str(sys_executable.relative_to(cwd))\n result = get_interpreter(relative, [], session_app_data)\n assert result is not None\n\n\n<mask token>\n\n\ndef test_discovery_fallback_ok(session_app_data, caplog):\n caplog.set_level(logging.DEBUG)\n builtin = Builtin(Namespace(app_data=session_app_data, try_first_with=[\n ], python=['magic-one', sys.executable], env=os.environ))\n result = builtin.run()\n assert result is not None, caplog.text\n assert result.executable == sys.executable, caplog.text\n assert 'accepted' in caplog.text\n", "step-3": "<mask token>\n\n\[email protected](not fs_supports_symlink(), reason='symlink not supported')\[email protected]('case', ['mixed', 'lower', 'upper'])\ndef test_discovery_via_path(monkeypatch, case, tmp_path, caplog,\n session_app_data):\n caplog.set_level(logging.DEBUG)\n current = PythonInfo.current_system(session_app_data)\n core = (\n f\"somethingVeryCryptic{'.'.join(str(i) for i in current.version_info[0:3])}\"\n )\n name = 'somethingVeryCryptic'\n if case == 'lower':\n name = name.lower()\n elif case == 'upper':\n name = name.upper()\n exe_name = (\n f\"{name}{current.version_info.major}{'.exe' if sys.platform == 'win32' else ''}\"\n )\n target = tmp_path / current.install_path('scripts')\n target.mkdir(parents=True)\n executable = target / exe_name\n os.symlink(sys.executable, str(executable))\n pyvenv_cfg = Path(sys.executable).parents[1] / 'pyvenv.cfg'\n if pyvenv_cfg.exists():\n (target / pyvenv_cfg.name).write_bytes(pyvenv_cfg.read_bytes())\n new_path = os.pathsep.join([str(target), *os.environ.get('PATH', '').\n split(os.pathsep)])\n monkeypatch.setenv('PATH', new_path)\n interpreter = get_interpreter(core, [])\n assert interpreter is not None\n\n\ndef test_discovery_via_path_not_found(tmp_path, monkeypatch):\n monkeypatch.setenv('PATH', str(tmp_path))\n interpreter = get_interpreter(uuid4().hex, [])\n assert interpreter is None\n\n\ndef test_relative_path(session_app_data, monkeypatch):\n sys_executable = Path(PythonInfo.current_system(app_data=\n session_app_data).system_executable)\n cwd = sys_executable.parents[1]\n monkeypatch.chdir(str(cwd))\n relative = str(sys_executable.relative_to(cwd))\n result = get_interpreter(relative, [], session_app_data)\n assert result is not None\n\n\ndef test_discovery_fallback_fail(session_app_data, caplog):\n caplog.set_level(logging.DEBUG)\n builtin = Builtin(Namespace(app_data=session_app_data, try_first_with=[\n ], python=['magic-one', 'magic-two'], env=os.environ))\n result = builtin.run()\n assert result is None\n assert 'accepted' not in caplog.text\n\n\ndef test_discovery_fallback_ok(session_app_data, caplog):\n caplog.set_level(logging.DEBUG)\n builtin = Builtin(Namespace(app_data=session_app_data, try_first_with=[\n ], python=['magic-one', sys.executable], env=os.environ))\n result = builtin.run()\n assert result is not None, caplog.text\n assert result.executable == sys.executable, caplog.text\n assert 'accepted' in caplog.text\n", "step-4": "from __future__ import annotations\nimport logging\nimport os\nimport sys\nfrom argparse import Namespace\nfrom pathlib import Path\nfrom uuid import uuid4\nimport pytest\nfrom virtualenv.discovery.builtin import Builtin, get_interpreter\nfrom virtualenv.discovery.py_info import PythonInfo\nfrom virtualenv.info import fs_supports_symlink\n\n\[email protected](not fs_supports_symlink(), reason='symlink not supported')\[email protected]('case', ['mixed', 'lower', 'upper'])\ndef test_discovery_via_path(monkeypatch, case, tmp_path, caplog,\n session_app_data):\n caplog.set_level(logging.DEBUG)\n current = PythonInfo.current_system(session_app_data)\n core = (\n f\"somethingVeryCryptic{'.'.join(str(i) for i in current.version_info[0:3])}\"\n )\n name = 'somethingVeryCryptic'\n if case == 'lower':\n name = name.lower()\n elif case == 'upper':\n name = name.upper()\n exe_name = (\n f\"{name}{current.version_info.major}{'.exe' if sys.platform == 'win32' else ''}\"\n )\n target = tmp_path / current.install_path('scripts')\n target.mkdir(parents=True)\n executable = target / exe_name\n os.symlink(sys.executable, str(executable))\n pyvenv_cfg = Path(sys.executable).parents[1] / 'pyvenv.cfg'\n if pyvenv_cfg.exists():\n (target / pyvenv_cfg.name).write_bytes(pyvenv_cfg.read_bytes())\n new_path = os.pathsep.join([str(target), *os.environ.get('PATH', '').\n split(os.pathsep)])\n monkeypatch.setenv('PATH', new_path)\n interpreter = get_interpreter(core, [])\n assert interpreter is not None\n\n\ndef test_discovery_via_path_not_found(tmp_path, monkeypatch):\n monkeypatch.setenv('PATH', str(tmp_path))\n interpreter = get_interpreter(uuid4().hex, [])\n assert interpreter is None\n\n\ndef test_relative_path(session_app_data, monkeypatch):\n sys_executable = Path(PythonInfo.current_system(app_data=\n session_app_data).system_executable)\n cwd = sys_executable.parents[1]\n monkeypatch.chdir(str(cwd))\n relative = str(sys_executable.relative_to(cwd))\n result = get_interpreter(relative, [], session_app_data)\n assert result is not None\n\n\ndef test_discovery_fallback_fail(session_app_data, caplog):\n caplog.set_level(logging.DEBUG)\n builtin = Builtin(Namespace(app_data=session_app_data, try_first_with=[\n ], python=['magic-one', 'magic-two'], env=os.environ))\n result = builtin.run()\n assert result is None\n assert 'accepted' not in caplog.text\n\n\ndef test_discovery_fallback_ok(session_app_data, caplog):\n caplog.set_level(logging.DEBUG)\n builtin = Builtin(Namespace(app_data=session_app_data, try_first_with=[\n ], python=['magic-one', sys.executable], env=os.environ))\n result = builtin.run()\n assert result is not None, caplog.text\n assert result.executable == sys.executable, caplog.text\n assert 'accepted' in caplog.text\n", "step-5": "from __future__ import annotations\n\nimport logging\nimport os\nimport sys\nfrom argparse import Namespace\nfrom pathlib import Path\nfrom uuid import uuid4\n\nimport pytest\n\nfrom virtualenv.discovery.builtin import Builtin, get_interpreter\nfrom virtualenv.discovery.py_info import PythonInfo\nfrom virtualenv.info import fs_supports_symlink\n\n\[email protected](not fs_supports_symlink(), reason=\"symlink not supported\")\[email protected](\"case\", [\"mixed\", \"lower\", \"upper\"])\ndef test_discovery_via_path(monkeypatch, case, tmp_path, caplog, session_app_data):\n caplog.set_level(logging.DEBUG)\n current = PythonInfo.current_system(session_app_data)\n core = f\"somethingVeryCryptic{'.'.join(str(i) for i in current.version_info[0:3])}\"\n name = \"somethingVeryCryptic\"\n if case == \"lower\":\n name = name.lower()\n elif case == \"upper\":\n name = name.upper()\n exe_name = f\"{name}{current.version_info.major}{'.exe' if sys.platform == 'win32' else ''}\"\n target = tmp_path / current.install_path(\"scripts\")\n target.mkdir(parents=True)\n executable = target / exe_name\n os.symlink(sys.executable, str(executable))\n pyvenv_cfg = Path(sys.executable).parents[1] / \"pyvenv.cfg\"\n if pyvenv_cfg.exists():\n (target / pyvenv_cfg.name).write_bytes(pyvenv_cfg.read_bytes())\n new_path = os.pathsep.join([str(target), *os.environ.get(\"PATH\", \"\").split(os.pathsep)])\n monkeypatch.setenv(\"PATH\", new_path)\n interpreter = get_interpreter(core, [])\n\n assert interpreter is not None\n\n\ndef test_discovery_via_path_not_found(tmp_path, monkeypatch):\n monkeypatch.setenv(\"PATH\", str(tmp_path))\n interpreter = get_interpreter(uuid4().hex, [])\n assert interpreter is None\n\n\ndef test_relative_path(session_app_data, monkeypatch):\n sys_executable = Path(PythonInfo.current_system(app_data=session_app_data).system_executable)\n cwd = sys_executable.parents[1]\n monkeypatch.chdir(str(cwd))\n relative = str(sys_executable.relative_to(cwd))\n result = get_interpreter(relative, [], session_app_data)\n assert result is not None\n\n\ndef test_discovery_fallback_fail(session_app_data, caplog):\n caplog.set_level(logging.DEBUG)\n builtin = Builtin(\n Namespace(app_data=session_app_data, try_first_with=[], python=[\"magic-one\", \"magic-two\"], env=os.environ),\n )\n\n result = builtin.run()\n assert result is None\n\n assert \"accepted\" not in caplog.text\n\n\ndef test_discovery_fallback_ok(session_app_data, caplog):\n caplog.set_level(logging.DEBUG)\n builtin = Builtin(\n Namespace(app_data=session_app_data, try_first_with=[], python=[\"magic-one\", sys.executable], env=os.environ),\n )\n\n result = builtin.run()\n assert result is not None, caplog.text\n assert result.executable == sys.executable, caplog.text\n\n assert \"accepted\" in caplog.text\n", "step-ids": [ 1, 4, 5, 6, 7 ] }
[ 1, 4, 5, 6, 7 ]
<|reserved_special_token_0|> class SaisonCulturelle(Saison): def __unicode__(self): return self.nom class Festival(Saison): saison_culture = models.ForeignKey(SaisonCulturelle) def __unicode__(self): return self.nom class TypeEvenement(models.Model): nom = models.CharField(max_length=255) slug = models.SlugField(unique=True) def __unicode__(self): return self.nom class Meta: ordering = ['nom'] <|reserved_special_token_0|> class Evenement(models.Model): nom = models.CharField(max_length=255) meta_description = models.CharField(max_length=200) description = models.TextField() debut = models.DateTimeField('Date de début') fin = models.DateTimeField('Date de fin') organisateur = models.ManyToManyField(Organisateur) image = FileBrowseField('Image (facultatif)', max_length=255, directory ='evenements', extensions=['.jpg', '.png', '.gif', '.jpeg', '.pdf'], blank=True, null=True) url = models.URLField("Un lien vers plus d'infos: (facultatif)", blank= True, null=True) url_reservation = models.URLField( "Un lien vers la page de reservation: (facultatif, annule le lien vers plus d'infos) " , blank=True, null=True) categorie = models.CharField(max_length=3, choices=EVENEMENT_CATEGORIES, default='aut') public = models.CharField(max_length=3, choices=EVENEMENT_PUBLIC, default='pub') cadre_evenement = models.ForeignKey(Saison) type = models.ForeignKey(TypeEvenement) lieu = models.ForeignKey(Lieu) publish = models.BooleanField('Publié', default=False) page_accueil = models.BooleanField("Page d'accueil", default=False) complet = models.BooleanField('Ce spectacle est complet', default=False) slug = models.SlugField(max_length=255, unique=True) class Meta: ordering = ['-debut'] def Organisateurs(self): return '\n;\n'.join([s.nom for s in self.organisateur.all()]) def __unicode__(self): return self.nom def monthyeardebut(self): return self.debut.strftime('%m') + '-' + self.debut.strftime('%Y') @permalink def get_absolute_url(self): return 'event-details', (), {'slug': self.cadre_evenement.slug, 'evenement_slug': self.slug} class Prix(models.Model): intitule = models.CharField('Intitulé ', max_length=255, blank=False, null=False) prix = models.FloatField('Prix (séparateur point ex : 0.5 )', default= None, blank=False, null=True) evenement = models.ForeignKey(Evenement) class Meta: verbose_name_plural = u'Prix' class DocumentAttache(models.Model): nom = models.CharField(max_length=255, verbose_name='Nom') document = FileBrowseField('Document', max_length=200, directory= 'evenements/docs', extensions=['.pdf', '.doc', '.odt', '.docx', '.txt'] ) reference = models.ForeignKey(Evenement) class EvenementBibManager(models.Manager): def get_queryset(self): return super(EvenementBibManager, self).get_queryset().filter(categorie ='bib') class EvenementBib(Evenement): objects = EvenementBibManager() class Meta: proxy = True verbose_name_plural = u'Événements Bibliothèques' verbose_name = u'Événement Bibliothèque' class EvenementCrdManager(models.Manager): def get_queryset(self): return super(EvenementCrdManager, self).get_queryset().filter(categorie ='crd') class EvenementCrd(Evenement): objects = EvenementCrdManager() class Meta: proxy = True verbose_name_plural = u'Événements Conservatoires' verbose_name = u'Événement Conservatoire' class EvenementDevEcoManager(models.Manager): def get_queryset(self): return super(EvenementDevEcoManager, self).get_queryset().filter( categorie='eco') class EvenementDevEco(Evenement): objects = EvenementDevEcoManager() class Meta: proxy = True verbose_name_plural = u'Événements Dev Eco' verbose_name = u'Événement Dev Eco' <|reserved_special_token_1|> <|reserved_special_token_0|> class Saison(models.Model): nom = models.CharField(max_length=255) debut = models.DateTimeField('Date de début') fin = models.DateTimeField('date de fin') description = models.TextField() slug = models.SlugField(max_length=255, unique=True) objects = InheritanceManager() def __unicode__(self): return self.nom class SaisonCulturelle(Saison): def __unicode__(self): return self.nom class Festival(Saison): saison_culture = models.ForeignKey(SaisonCulturelle) def __unicode__(self): return self.nom class TypeEvenement(models.Model): nom = models.CharField(max_length=255) slug = models.SlugField(unique=True) def __unicode__(self): return self.nom class Meta: ordering = ['nom'] <|reserved_special_token_0|> class Evenement(models.Model): nom = models.CharField(max_length=255) meta_description = models.CharField(max_length=200) description = models.TextField() debut = models.DateTimeField('Date de début') fin = models.DateTimeField('Date de fin') organisateur = models.ManyToManyField(Organisateur) image = FileBrowseField('Image (facultatif)', max_length=255, directory ='evenements', extensions=['.jpg', '.png', '.gif', '.jpeg', '.pdf'], blank=True, null=True) url = models.URLField("Un lien vers plus d'infos: (facultatif)", blank= True, null=True) url_reservation = models.URLField( "Un lien vers la page de reservation: (facultatif, annule le lien vers plus d'infos) " , blank=True, null=True) categorie = models.CharField(max_length=3, choices=EVENEMENT_CATEGORIES, default='aut') public = models.CharField(max_length=3, choices=EVENEMENT_PUBLIC, default='pub') cadre_evenement = models.ForeignKey(Saison) type = models.ForeignKey(TypeEvenement) lieu = models.ForeignKey(Lieu) publish = models.BooleanField('Publié', default=False) page_accueil = models.BooleanField("Page d'accueil", default=False) complet = models.BooleanField('Ce spectacle est complet', default=False) slug = models.SlugField(max_length=255, unique=True) class Meta: ordering = ['-debut'] def Organisateurs(self): return '\n;\n'.join([s.nom for s in self.organisateur.all()]) def __unicode__(self): return self.nom def monthyeardebut(self): return self.debut.strftime('%m') + '-' + self.debut.strftime('%Y') @permalink def get_absolute_url(self): return 'event-details', (), {'slug': self.cadre_evenement.slug, 'evenement_slug': self.slug} class Prix(models.Model): intitule = models.CharField('Intitulé ', max_length=255, blank=False, null=False) prix = models.FloatField('Prix (séparateur point ex : 0.5 )', default= None, blank=False, null=True) evenement = models.ForeignKey(Evenement) class Meta: verbose_name_plural = u'Prix' class DocumentAttache(models.Model): nom = models.CharField(max_length=255, verbose_name='Nom') document = FileBrowseField('Document', max_length=200, directory= 'evenements/docs', extensions=['.pdf', '.doc', '.odt', '.docx', '.txt'] ) reference = models.ForeignKey(Evenement) class EvenementBibManager(models.Manager): def get_queryset(self): return super(EvenementBibManager, self).get_queryset().filter(categorie ='bib') class EvenementBib(Evenement): objects = EvenementBibManager() class Meta: proxy = True verbose_name_plural = u'Événements Bibliothèques' verbose_name = u'Événement Bibliothèque' class EvenementCrdManager(models.Manager): def get_queryset(self): return super(EvenementCrdManager, self).get_queryset().filter(categorie ='crd') class EvenementCrd(Evenement): objects = EvenementCrdManager() class Meta: proxy = True verbose_name_plural = u'Événements Conservatoires' verbose_name = u'Événement Conservatoire' class EvenementDevEcoManager(models.Manager): def get_queryset(self): return super(EvenementDevEcoManager, self).get_queryset().filter( categorie='eco') class EvenementDevEco(Evenement): objects = EvenementDevEcoManager() class Meta: proxy = True verbose_name_plural = u'Événements Dev Eco' verbose_name = u'Événement Dev Eco' <|reserved_special_token_1|> <|reserved_special_token_0|> class Organisateur(models.Model): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> class Meta: verbose_name_plural = 'Organisateurs' ordering = ['ville__nom'] class Saison(models.Model): nom = models.CharField(max_length=255) debut = models.DateTimeField('Date de début') fin = models.DateTimeField('date de fin') description = models.TextField() slug = models.SlugField(max_length=255, unique=True) objects = InheritanceManager() def __unicode__(self): return self.nom class SaisonCulturelle(Saison): def __unicode__(self): return self.nom class Festival(Saison): saison_culture = models.ForeignKey(SaisonCulturelle) def __unicode__(self): return self.nom class TypeEvenement(models.Model): nom = models.CharField(max_length=255) slug = models.SlugField(unique=True) def __unicode__(self): return self.nom class Meta: ordering = ['nom'] <|reserved_special_token_0|> class Evenement(models.Model): nom = models.CharField(max_length=255) meta_description = models.CharField(max_length=200) description = models.TextField() debut = models.DateTimeField('Date de début') fin = models.DateTimeField('Date de fin') organisateur = models.ManyToManyField(Organisateur) image = FileBrowseField('Image (facultatif)', max_length=255, directory ='evenements', extensions=['.jpg', '.png', '.gif', '.jpeg', '.pdf'], blank=True, null=True) url = models.URLField("Un lien vers plus d'infos: (facultatif)", blank= True, null=True) url_reservation = models.URLField( "Un lien vers la page de reservation: (facultatif, annule le lien vers plus d'infos) " , blank=True, null=True) categorie = models.CharField(max_length=3, choices=EVENEMENT_CATEGORIES, default='aut') public = models.CharField(max_length=3, choices=EVENEMENT_PUBLIC, default='pub') cadre_evenement = models.ForeignKey(Saison) type = models.ForeignKey(TypeEvenement) lieu = models.ForeignKey(Lieu) publish = models.BooleanField('Publié', default=False) page_accueil = models.BooleanField("Page d'accueil", default=False) complet = models.BooleanField('Ce spectacle est complet', default=False) slug = models.SlugField(max_length=255, unique=True) class Meta: ordering = ['-debut'] def Organisateurs(self): return '\n;\n'.join([s.nom for s in self.organisateur.all()]) def __unicode__(self): return self.nom def monthyeardebut(self): return self.debut.strftime('%m') + '-' + self.debut.strftime('%Y') @permalink def get_absolute_url(self): return 'event-details', (), {'slug': self.cadre_evenement.slug, 'evenement_slug': self.slug} class Prix(models.Model): intitule = models.CharField('Intitulé ', max_length=255, blank=False, null=False) prix = models.FloatField('Prix (séparateur point ex : 0.5 )', default= None, blank=False, null=True) evenement = models.ForeignKey(Evenement) class Meta: verbose_name_plural = u'Prix' class DocumentAttache(models.Model): nom = models.CharField(max_length=255, verbose_name='Nom') document = FileBrowseField('Document', max_length=200, directory= 'evenements/docs', extensions=['.pdf', '.doc', '.odt', '.docx', '.txt'] ) reference = models.ForeignKey(Evenement) class EvenementBibManager(models.Manager): def get_queryset(self): return super(EvenementBibManager, self).get_queryset().filter(categorie ='bib') class EvenementBib(Evenement): objects = EvenementBibManager() class Meta: proxy = True verbose_name_plural = u'Événements Bibliothèques' verbose_name = u'Événement Bibliothèque' class EvenementCrdManager(models.Manager): def get_queryset(self): return super(EvenementCrdManager, self).get_queryset().filter(categorie ='crd') class EvenementCrd(Evenement): objects = EvenementCrdManager() class Meta: proxy = True verbose_name_plural = u'Événements Conservatoires' verbose_name = u'Événement Conservatoire' class EvenementDevEcoManager(models.Manager): def get_queryset(self): return super(EvenementDevEcoManager, self).get_queryset().filter( categorie='eco') class EvenementDevEco(Evenement): objects = EvenementDevEcoManager() class Meta: proxy = True verbose_name_plural = u'Événements Dev Eco' verbose_name = u'Événement Dev Eco' <|reserved_special_token_1|> <|reserved_special_token_0|> class Organisateur(models.Model): nom = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) meta_description = models.CharField(max_length=200) description = models.TextField() logo = FileBrowseField('Image', max_length=255, directory='evenements', extensions=['.jpg', '.png', '.gif', '.jpeg'], blank=True, null=True) url = models.URLField('Site de cet organisateur: (facultatif) ', blank =True) email = models.EmailField('Mail (facultatif)', max_length=255, blank=True) telephone = models.CharField(max_length=25) fax = models.CharField('Fax (facultatif)', max_length=25, blank=True) rue = models.CharField(max_length=255) ville = models.ForeignKey(Ville) orga_service = models.ForeignKey(Service, blank=True, null=True) orga_equipement = models.ForeignKey(Equipement, blank=True, null=True) orga_ville = models.ForeignKey(Ville, blank=True, null=True, related_name='orga_orga_ville') def __unicode__(self): return self.nom + ' / ' + self.ville.nom class Meta: verbose_name_plural = 'Organisateurs' ordering = ['ville__nom'] class Saison(models.Model): nom = models.CharField(max_length=255) debut = models.DateTimeField('Date de début') fin = models.DateTimeField('date de fin') description = models.TextField() slug = models.SlugField(max_length=255, unique=True) objects = InheritanceManager() def __unicode__(self): return self.nom class SaisonCulturelle(Saison): def __unicode__(self): return self.nom class Festival(Saison): saison_culture = models.ForeignKey(SaisonCulturelle) def __unicode__(self): return self.nom class TypeEvenement(models.Model): nom = models.CharField(max_length=255) slug = models.SlugField(unique=True) def __unicode__(self): return self.nom class Meta: ordering = ['nom'] <|reserved_special_token_0|> class Evenement(models.Model): nom = models.CharField(max_length=255) meta_description = models.CharField(max_length=200) description = models.TextField() debut = models.DateTimeField('Date de début') fin = models.DateTimeField('Date de fin') organisateur = models.ManyToManyField(Organisateur) image = FileBrowseField('Image (facultatif)', max_length=255, directory ='evenements', extensions=['.jpg', '.png', '.gif', '.jpeg', '.pdf'], blank=True, null=True) url = models.URLField("Un lien vers plus d'infos: (facultatif)", blank= True, null=True) url_reservation = models.URLField( "Un lien vers la page de reservation: (facultatif, annule le lien vers plus d'infos) " , blank=True, null=True) categorie = models.CharField(max_length=3, choices=EVENEMENT_CATEGORIES, default='aut') public = models.CharField(max_length=3, choices=EVENEMENT_PUBLIC, default='pub') cadre_evenement = models.ForeignKey(Saison) type = models.ForeignKey(TypeEvenement) lieu = models.ForeignKey(Lieu) publish = models.BooleanField('Publié', default=False) page_accueil = models.BooleanField("Page d'accueil", default=False) complet = models.BooleanField('Ce spectacle est complet', default=False) slug = models.SlugField(max_length=255, unique=True) class Meta: ordering = ['-debut'] def Organisateurs(self): return '\n;\n'.join([s.nom for s in self.organisateur.all()]) def __unicode__(self): return self.nom def monthyeardebut(self): return self.debut.strftime('%m') + '-' + self.debut.strftime('%Y') @permalink def get_absolute_url(self): return 'event-details', (), {'slug': self.cadre_evenement.slug, 'evenement_slug': self.slug} class Prix(models.Model): intitule = models.CharField('Intitulé ', max_length=255, blank=False, null=False) prix = models.FloatField('Prix (séparateur point ex : 0.5 )', default= None, blank=False, null=True) evenement = models.ForeignKey(Evenement) class Meta: verbose_name_plural = u'Prix' class DocumentAttache(models.Model): nom = models.CharField(max_length=255, verbose_name='Nom') document = FileBrowseField('Document', max_length=200, directory= 'evenements/docs', extensions=['.pdf', '.doc', '.odt', '.docx', '.txt'] ) reference = models.ForeignKey(Evenement) class EvenementBibManager(models.Manager): def get_queryset(self): return super(EvenementBibManager, self).get_queryset().filter(categorie ='bib') class EvenementBib(Evenement): objects = EvenementBibManager() class Meta: proxy = True verbose_name_plural = u'Événements Bibliothèques' verbose_name = u'Événement Bibliothèque' class EvenementCrdManager(models.Manager): def get_queryset(self): return super(EvenementCrdManager, self).get_queryset().filter(categorie ='crd') class EvenementCrd(Evenement): objects = EvenementCrdManager() class Meta: proxy = True verbose_name_plural = u'Événements Conservatoires' verbose_name = u'Événement Conservatoire' class EvenementDevEcoManager(models.Manager): def get_queryset(self): return super(EvenementDevEcoManager, self).get_queryset().filter( categorie='eco') class EvenementDevEco(Evenement): objects = EvenementDevEcoManager() class Meta: proxy = True verbose_name_plural = u'Événements Dev Eco' verbose_name = u'Événement Dev Eco' <|reserved_special_token_1|> # -*- coding: utf-8 -*- from django.db import models from filebrowser.fields import FileBrowseField from localisations.models import Ville, Lieu from model_utils.managers import InheritanceManager from services.models import Service from equipements.models import Equipement from localisations.models import Ville from django.db.models import permalink class Organisateur(models.Model): nom = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) meta_description = models.CharField(max_length=200) description = models.TextField() logo = FileBrowseField("Image", max_length=255, directory="evenements", extensions=[".jpg", ".png", ".gif", ".jpeg"], blank=True, null=True) url = models.URLField("Site de cet organisateur: (facultatif) ", blank=True) email = models.EmailField("Mail (facultatif)", max_length=255, blank=True) telephone = models.CharField(max_length=25) fax = models.CharField("Fax (facultatif)", max_length=25, blank=True) rue = models.CharField(max_length=255) ville = models.ForeignKey(Ville) # Un choix de design pas très beau, mais fonctionellement les équipements, services, communes de la # communauté d'agglo peuvent organiser des evènements ainsi que d'autres entités exterieures alors ... orga_service = models.ForeignKey(Service, blank=True, null=True) orga_equipement = models.ForeignKey(Equipement, blank=True, null=True) orga_ville = models.ForeignKey(Ville, blank=True, null=True, related_name='orga_orga_ville') def __unicode__(self): return self.nom + " / " + self.ville.nom class Meta: verbose_name_plural = "Organisateurs" ordering = ['ville__nom'] class Saison(models.Model): nom = models.CharField(max_length=255) debut = models.DateTimeField("Date de début") fin = models.DateTimeField("date de fin") description = models.TextField() slug = models.SlugField(max_length=255, unique=True) objects = InheritanceManager() def __unicode__(self): return self.nom class SaisonCulturelle(Saison): def __unicode__(self): return self.nom class Festival(Saison): saison_culture = models.ForeignKey(SaisonCulturelle) def __unicode__(self): return self.nom class TypeEvenement(models.Model): nom = models.CharField(max_length=255) slug = models.SlugField(unique=True) def __unicode__(self): return self.nom class Meta: ordering = ['nom'] EVENEMENT_CATEGORIES = ( ('bib', u'Bibliothèques/Médiatèques'), ('crd', u'Conservatoires'), ('sty', u'Sothevy'), ('eco', u'Développement Économique'), ('aut', u'Autres'), ) EVENEMENT_PUBLIC = ( ('adt', u'Adulte'), ('enf', u'Enfant'), ('pub', u'Tout public'), ('ent', u'Entreprises'), ) class Evenement(models.Model): nom = models.CharField(max_length=255) meta_description = models.CharField(max_length=200) description = models.TextField() debut = models.DateTimeField("Date de début") fin = models.DateTimeField("Date de fin") organisateur = models.ManyToManyField(Organisateur) image = FileBrowseField("Image (facultatif)", max_length=255, directory="evenements", extensions=[".jpg", ".png", ".gif", ".jpeg", ".pdf"], blank=True, null=True) url = models.URLField("Un lien vers plus d'infos: (facultatif)", blank=True, null=True) url_reservation = models.URLField( "Un lien vers la page de reservation: (facultatif, annule le lien vers plus d'infos) ", blank=True, null=True) categorie = models.CharField(max_length=3, choices=EVENEMENT_CATEGORIES, default='aut') public = models.CharField(max_length=3, choices=EVENEMENT_PUBLIC, default='pub') cadre_evenement = models.ForeignKey(Saison) type = models.ForeignKey(TypeEvenement) lieu = models.ForeignKey(Lieu) publish = models.BooleanField("Publié", default=False) page_accueil = models.BooleanField("Page d'accueil", default=False) complet = models.BooleanField("Ce spectacle est complet", default=False) slug = models.SlugField(max_length=255, unique=True) class Meta: ordering = ['-debut'] def Organisateurs(self): return "\n;\n".join([s.nom for s in self.organisateur.all()]) def __unicode__(self): return self.nom def monthyeardebut(self): return self.debut.strftime("%m") + "-" + self.debut.strftime("%Y") @permalink def get_absolute_url(self): return ('event-details', (), {'slug': self.cadre_evenement.slug, 'evenement_slug': self.slug}) class Prix(models.Model): intitule = models.CharField("Intitulé ", max_length=255, blank=False, null=False) prix = models.FloatField("Prix (séparateur point ex : 0.5 )", default=None, blank=False, null=True) evenement = models.ForeignKey(Evenement) class Meta: verbose_name_plural = u"Prix" class DocumentAttache(models.Model): nom = models.CharField(max_length=255, verbose_name="Nom") document = FileBrowseField("Document", max_length=200, directory="evenements/docs", extensions=[".pdf", ".doc", ".odt", ".docx", ".txt"]) reference = models.ForeignKey(Evenement) class EvenementBibManager(models.Manager): def get_queryset(self): return super(EvenementBibManager, self).get_queryset().filter(categorie='bib') class EvenementBib(Evenement): objects = EvenementBibManager() class Meta: proxy = True verbose_name_plural = u"Événements Bibliothèques" verbose_name = u"Événement Bibliothèque" class EvenementCrdManager(models.Manager): def get_queryset(self): return super(EvenementCrdManager, self).get_queryset().filter(categorie='crd') class EvenementCrd(Evenement): objects = EvenementCrdManager() class Meta: proxy = True verbose_name_plural = u"Événements Conservatoires" verbose_name = u"Événement Conservatoire" class EvenementDevEcoManager(models.Manager): def get_queryset(self): return super(EvenementDevEcoManager, self).get_queryset().filter(categorie='eco') class EvenementDevEco(Evenement): objects = EvenementDevEcoManager() class Meta: proxy = True verbose_name_plural = u"Événements Dev Eco" verbose_name = u"Événement Dev Eco"
flexible
{ "blob_id": "596fe474ae60dd6a06123df6fe246f7e947b3482", "index": 1760, "step-1": "<mask token>\n\n\nclass SaisonCulturelle(Saison):\n\n def __unicode__(self):\n return self.nom\n\n\nclass Festival(Saison):\n saison_culture = models.ForeignKey(SaisonCulturelle)\n\n def __unicode__(self):\n return self.nom\n\n\nclass TypeEvenement(models.Model):\n nom = models.CharField(max_length=255)\n slug = models.SlugField(unique=True)\n\n def __unicode__(self):\n return self.nom\n\n\n class Meta:\n ordering = ['nom']\n\n\n<mask token>\n\n\nclass Evenement(models.Model):\n nom = models.CharField(max_length=255)\n meta_description = models.CharField(max_length=200)\n description = models.TextField()\n debut = models.DateTimeField('Date de début')\n fin = models.DateTimeField('Date de fin')\n organisateur = models.ManyToManyField(Organisateur)\n image = FileBrowseField('Image (facultatif)', max_length=255, directory\n ='evenements', extensions=['.jpg', '.png', '.gif', '.jpeg', '.pdf'],\n blank=True, null=True)\n url = models.URLField(\"Un lien vers plus d'infos: (facultatif)\", blank=\n True, null=True)\n url_reservation = models.URLField(\n \"Un lien vers la page de reservation: (facultatif, annule le lien vers plus d'infos) \"\n , blank=True, null=True)\n categorie = models.CharField(max_length=3, choices=EVENEMENT_CATEGORIES,\n default='aut')\n public = models.CharField(max_length=3, choices=EVENEMENT_PUBLIC,\n default='pub')\n cadre_evenement = models.ForeignKey(Saison)\n type = models.ForeignKey(TypeEvenement)\n lieu = models.ForeignKey(Lieu)\n publish = models.BooleanField('Publié', default=False)\n page_accueil = models.BooleanField(\"Page d'accueil\", default=False)\n complet = models.BooleanField('Ce spectacle est complet', default=False)\n slug = models.SlugField(max_length=255, unique=True)\n\n\n class Meta:\n ordering = ['-debut']\n\n def Organisateurs(self):\n return '\\n;\\n'.join([s.nom for s in self.organisateur.all()])\n\n def __unicode__(self):\n return self.nom\n\n def monthyeardebut(self):\n return self.debut.strftime('%m') + '-' + self.debut.strftime('%Y')\n\n @permalink\n def get_absolute_url(self):\n return 'event-details', (), {'slug': self.cadre_evenement.slug,\n 'evenement_slug': self.slug}\n\n\nclass Prix(models.Model):\n intitule = models.CharField('Intitulé ', max_length=255, blank=False,\n null=False)\n prix = models.FloatField('Prix (séparateur point ex : 0.5 )', default=\n None, blank=False, null=True)\n evenement = models.ForeignKey(Evenement)\n\n\n class Meta:\n verbose_name_plural = u'Prix'\n\n\nclass DocumentAttache(models.Model):\n nom = models.CharField(max_length=255, verbose_name='Nom')\n document = FileBrowseField('Document', max_length=200, directory=\n 'evenements/docs', extensions=['.pdf', '.doc', '.odt', '.docx', '.txt']\n )\n reference = models.ForeignKey(Evenement)\n\n\nclass EvenementBibManager(models.Manager):\n\n def get_queryset(self):\n return super(EvenementBibManager, self).get_queryset().filter(categorie\n ='bib')\n\n\nclass EvenementBib(Evenement):\n objects = EvenementBibManager()\n\n\n class Meta:\n proxy = True\n verbose_name_plural = u'Événements Bibliothèques'\n verbose_name = u'Événement Bibliothèque'\n\n\nclass EvenementCrdManager(models.Manager):\n\n def get_queryset(self):\n return super(EvenementCrdManager, self).get_queryset().filter(categorie\n ='crd')\n\n\nclass EvenementCrd(Evenement):\n objects = EvenementCrdManager()\n\n\n class Meta:\n proxy = True\n verbose_name_plural = u'Événements Conservatoires'\n verbose_name = u'Événement Conservatoire'\n\n\nclass EvenementDevEcoManager(models.Manager):\n\n def get_queryset(self):\n return super(EvenementDevEcoManager, self).get_queryset().filter(\n categorie='eco')\n\n\nclass EvenementDevEco(Evenement):\n objects = EvenementDevEcoManager()\n\n\n class Meta:\n proxy = True\n verbose_name_plural = u'Événements Dev Eco'\n verbose_name = u'Événement Dev Eco'\n", "step-2": "<mask token>\n\n\nclass Saison(models.Model):\n nom = models.CharField(max_length=255)\n debut = models.DateTimeField('Date de début')\n fin = models.DateTimeField('date de fin')\n description = models.TextField()\n slug = models.SlugField(max_length=255, unique=True)\n objects = InheritanceManager()\n\n def __unicode__(self):\n return self.nom\n\n\nclass SaisonCulturelle(Saison):\n\n def __unicode__(self):\n return self.nom\n\n\nclass Festival(Saison):\n saison_culture = models.ForeignKey(SaisonCulturelle)\n\n def __unicode__(self):\n return self.nom\n\n\nclass TypeEvenement(models.Model):\n nom = models.CharField(max_length=255)\n slug = models.SlugField(unique=True)\n\n def __unicode__(self):\n return self.nom\n\n\n class Meta:\n ordering = ['nom']\n\n\n<mask token>\n\n\nclass Evenement(models.Model):\n nom = models.CharField(max_length=255)\n meta_description = models.CharField(max_length=200)\n description = models.TextField()\n debut = models.DateTimeField('Date de début')\n fin = models.DateTimeField('Date de fin')\n organisateur = models.ManyToManyField(Organisateur)\n image = FileBrowseField('Image (facultatif)', max_length=255, directory\n ='evenements', extensions=['.jpg', '.png', '.gif', '.jpeg', '.pdf'],\n blank=True, null=True)\n url = models.URLField(\"Un lien vers plus d'infos: (facultatif)\", blank=\n True, null=True)\n url_reservation = models.URLField(\n \"Un lien vers la page de reservation: (facultatif, annule le lien vers plus d'infos) \"\n , blank=True, null=True)\n categorie = models.CharField(max_length=3, choices=EVENEMENT_CATEGORIES,\n default='aut')\n public = models.CharField(max_length=3, choices=EVENEMENT_PUBLIC,\n default='pub')\n cadre_evenement = models.ForeignKey(Saison)\n type = models.ForeignKey(TypeEvenement)\n lieu = models.ForeignKey(Lieu)\n publish = models.BooleanField('Publié', default=False)\n page_accueil = models.BooleanField(\"Page d'accueil\", default=False)\n complet = models.BooleanField('Ce spectacle est complet', default=False)\n slug = models.SlugField(max_length=255, unique=True)\n\n\n class Meta:\n ordering = ['-debut']\n\n def Organisateurs(self):\n return '\\n;\\n'.join([s.nom for s in self.organisateur.all()])\n\n def __unicode__(self):\n return self.nom\n\n def monthyeardebut(self):\n return self.debut.strftime('%m') + '-' + self.debut.strftime('%Y')\n\n @permalink\n def get_absolute_url(self):\n return 'event-details', (), {'slug': self.cadre_evenement.slug,\n 'evenement_slug': self.slug}\n\n\nclass Prix(models.Model):\n intitule = models.CharField('Intitulé ', max_length=255, blank=False,\n null=False)\n prix = models.FloatField('Prix (séparateur point ex : 0.5 )', default=\n None, blank=False, null=True)\n evenement = models.ForeignKey(Evenement)\n\n\n class Meta:\n verbose_name_plural = u'Prix'\n\n\nclass DocumentAttache(models.Model):\n nom = models.CharField(max_length=255, verbose_name='Nom')\n document = FileBrowseField('Document', max_length=200, directory=\n 'evenements/docs', extensions=['.pdf', '.doc', '.odt', '.docx', '.txt']\n )\n reference = models.ForeignKey(Evenement)\n\n\nclass EvenementBibManager(models.Manager):\n\n def get_queryset(self):\n return super(EvenementBibManager, self).get_queryset().filter(categorie\n ='bib')\n\n\nclass EvenementBib(Evenement):\n objects = EvenementBibManager()\n\n\n class Meta:\n proxy = True\n verbose_name_plural = u'Événements Bibliothèques'\n verbose_name = u'Événement Bibliothèque'\n\n\nclass EvenementCrdManager(models.Manager):\n\n def get_queryset(self):\n return super(EvenementCrdManager, self).get_queryset().filter(categorie\n ='crd')\n\n\nclass EvenementCrd(Evenement):\n objects = EvenementCrdManager()\n\n\n class Meta:\n proxy = True\n verbose_name_plural = u'Événements Conservatoires'\n verbose_name = u'Événement Conservatoire'\n\n\nclass EvenementDevEcoManager(models.Manager):\n\n def get_queryset(self):\n return super(EvenementDevEcoManager, self).get_queryset().filter(\n categorie='eco')\n\n\nclass EvenementDevEco(Evenement):\n objects = EvenementDevEcoManager()\n\n\n class Meta:\n proxy = True\n verbose_name_plural = u'Événements Dev Eco'\n verbose_name = u'Événement Dev Eco'\n", "step-3": "<mask token>\n\n\nclass Organisateur(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\n class Meta:\n verbose_name_plural = 'Organisateurs'\n ordering = ['ville__nom']\n\n\nclass Saison(models.Model):\n nom = models.CharField(max_length=255)\n debut = models.DateTimeField('Date de début')\n fin = models.DateTimeField('date de fin')\n description = models.TextField()\n slug = models.SlugField(max_length=255, unique=True)\n objects = InheritanceManager()\n\n def __unicode__(self):\n return self.nom\n\n\nclass SaisonCulturelle(Saison):\n\n def __unicode__(self):\n return self.nom\n\n\nclass Festival(Saison):\n saison_culture = models.ForeignKey(SaisonCulturelle)\n\n def __unicode__(self):\n return self.nom\n\n\nclass TypeEvenement(models.Model):\n nom = models.CharField(max_length=255)\n slug = models.SlugField(unique=True)\n\n def __unicode__(self):\n return self.nom\n\n\n class Meta:\n ordering = ['nom']\n\n\n<mask token>\n\n\nclass Evenement(models.Model):\n nom = models.CharField(max_length=255)\n meta_description = models.CharField(max_length=200)\n description = models.TextField()\n debut = models.DateTimeField('Date de début')\n fin = models.DateTimeField('Date de fin')\n organisateur = models.ManyToManyField(Organisateur)\n image = FileBrowseField('Image (facultatif)', max_length=255, directory\n ='evenements', extensions=['.jpg', '.png', '.gif', '.jpeg', '.pdf'],\n blank=True, null=True)\n url = models.URLField(\"Un lien vers plus d'infos: (facultatif)\", blank=\n True, null=True)\n url_reservation = models.URLField(\n \"Un lien vers la page de reservation: (facultatif, annule le lien vers plus d'infos) \"\n , blank=True, null=True)\n categorie = models.CharField(max_length=3, choices=EVENEMENT_CATEGORIES,\n default='aut')\n public = models.CharField(max_length=3, choices=EVENEMENT_PUBLIC,\n default='pub')\n cadre_evenement = models.ForeignKey(Saison)\n type = models.ForeignKey(TypeEvenement)\n lieu = models.ForeignKey(Lieu)\n publish = models.BooleanField('Publié', default=False)\n page_accueil = models.BooleanField(\"Page d'accueil\", default=False)\n complet = models.BooleanField('Ce spectacle est complet', default=False)\n slug = models.SlugField(max_length=255, unique=True)\n\n\n class Meta:\n ordering = ['-debut']\n\n def Organisateurs(self):\n return '\\n;\\n'.join([s.nom for s in self.organisateur.all()])\n\n def __unicode__(self):\n return self.nom\n\n def monthyeardebut(self):\n return self.debut.strftime('%m') + '-' + self.debut.strftime('%Y')\n\n @permalink\n def get_absolute_url(self):\n return 'event-details', (), {'slug': self.cadre_evenement.slug,\n 'evenement_slug': self.slug}\n\n\nclass Prix(models.Model):\n intitule = models.CharField('Intitulé ', max_length=255, blank=False,\n null=False)\n prix = models.FloatField('Prix (séparateur point ex : 0.5 )', default=\n None, blank=False, null=True)\n evenement = models.ForeignKey(Evenement)\n\n\n class Meta:\n verbose_name_plural = u'Prix'\n\n\nclass DocumentAttache(models.Model):\n nom = models.CharField(max_length=255, verbose_name='Nom')\n document = FileBrowseField('Document', max_length=200, directory=\n 'evenements/docs', extensions=['.pdf', '.doc', '.odt', '.docx', '.txt']\n )\n reference = models.ForeignKey(Evenement)\n\n\nclass EvenementBibManager(models.Manager):\n\n def get_queryset(self):\n return super(EvenementBibManager, self).get_queryset().filter(categorie\n ='bib')\n\n\nclass EvenementBib(Evenement):\n objects = EvenementBibManager()\n\n\n class Meta:\n proxy = True\n verbose_name_plural = u'Événements Bibliothèques'\n verbose_name = u'Événement Bibliothèque'\n\n\nclass EvenementCrdManager(models.Manager):\n\n def get_queryset(self):\n return super(EvenementCrdManager, self).get_queryset().filter(categorie\n ='crd')\n\n\nclass EvenementCrd(Evenement):\n objects = EvenementCrdManager()\n\n\n class Meta:\n proxy = True\n verbose_name_plural = u'Événements Conservatoires'\n verbose_name = u'Événement Conservatoire'\n\n\nclass EvenementDevEcoManager(models.Manager):\n\n def get_queryset(self):\n return super(EvenementDevEcoManager, self).get_queryset().filter(\n categorie='eco')\n\n\nclass EvenementDevEco(Evenement):\n objects = EvenementDevEcoManager()\n\n\n class Meta:\n proxy = True\n verbose_name_plural = u'Événements Dev Eco'\n verbose_name = u'Événement Dev Eco'\n", "step-4": "<mask token>\n\n\nclass Organisateur(models.Model):\n nom = models.CharField(max_length=255)\n slug = models.SlugField(max_length=255, unique=True)\n meta_description = models.CharField(max_length=200)\n description = models.TextField()\n logo = FileBrowseField('Image', max_length=255, directory='evenements',\n extensions=['.jpg', '.png', '.gif', '.jpeg'], blank=True, null=True)\n url = models.URLField('Site de cet organisateur: (facultatif) ', blank\n =True)\n email = models.EmailField('Mail (facultatif)', max_length=255, blank=True)\n telephone = models.CharField(max_length=25)\n fax = models.CharField('Fax (facultatif)', max_length=25, blank=True)\n rue = models.CharField(max_length=255)\n ville = models.ForeignKey(Ville)\n orga_service = models.ForeignKey(Service, blank=True, null=True)\n orga_equipement = models.ForeignKey(Equipement, blank=True, null=True)\n orga_ville = models.ForeignKey(Ville, blank=True, null=True,\n related_name='orga_orga_ville')\n\n def __unicode__(self):\n return self.nom + ' / ' + self.ville.nom\n\n\n class Meta:\n verbose_name_plural = 'Organisateurs'\n ordering = ['ville__nom']\n\n\nclass Saison(models.Model):\n nom = models.CharField(max_length=255)\n debut = models.DateTimeField('Date de début')\n fin = models.DateTimeField('date de fin')\n description = models.TextField()\n slug = models.SlugField(max_length=255, unique=True)\n objects = InheritanceManager()\n\n def __unicode__(self):\n return self.nom\n\n\nclass SaisonCulturelle(Saison):\n\n def __unicode__(self):\n return self.nom\n\n\nclass Festival(Saison):\n saison_culture = models.ForeignKey(SaisonCulturelle)\n\n def __unicode__(self):\n return self.nom\n\n\nclass TypeEvenement(models.Model):\n nom = models.CharField(max_length=255)\n slug = models.SlugField(unique=True)\n\n def __unicode__(self):\n return self.nom\n\n\n class Meta:\n ordering = ['nom']\n\n\n<mask token>\n\n\nclass Evenement(models.Model):\n nom = models.CharField(max_length=255)\n meta_description = models.CharField(max_length=200)\n description = models.TextField()\n debut = models.DateTimeField('Date de début')\n fin = models.DateTimeField('Date de fin')\n organisateur = models.ManyToManyField(Organisateur)\n image = FileBrowseField('Image (facultatif)', max_length=255, directory\n ='evenements', extensions=['.jpg', '.png', '.gif', '.jpeg', '.pdf'],\n blank=True, null=True)\n url = models.URLField(\"Un lien vers plus d'infos: (facultatif)\", blank=\n True, null=True)\n url_reservation = models.URLField(\n \"Un lien vers la page de reservation: (facultatif, annule le lien vers plus d'infos) \"\n , blank=True, null=True)\n categorie = models.CharField(max_length=3, choices=EVENEMENT_CATEGORIES,\n default='aut')\n public = models.CharField(max_length=3, choices=EVENEMENT_PUBLIC,\n default='pub')\n cadre_evenement = models.ForeignKey(Saison)\n type = models.ForeignKey(TypeEvenement)\n lieu = models.ForeignKey(Lieu)\n publish = models.BooleanField('Publié', default=False)\n page_accueil = models.BooleanField(\"Page d'accueil\", default=False)\n complet = models.BooleanField('Ce spectacle est complet', default=False)\n slug = models.SlugField(max_length=255, unique=True)\n\n\n class Meta:\n ordering = ['-debut']\n\n def Organisateurs(self):\n return '\\n;\\n'.join([s.nom for s in self.organisateur.all()])\n\n def __unicode__(self):\n return self.nom\n\n def monthyeardebut(self):\n return self.debut.strftime('%m') + '-' + self.debut.strftime('%Y')\n\n @permalink\n def get_absolute_url(self):\n return 'event-details', (), {'slug': self.cadre_evenement.slug,\n 'evenement_slug': self.slug}\n\n\nclass Prix(models.Model):\n intitule = models.CharField('Intitulé ', max_length=255, blank=False,\n null=False)\n prix = models.FloatField('Prix (séparateur point ex : 0.5 )', default=\n None, blank=False, null=True)\n evenement = models.ForeignKey(Evenement)\n\n\n class Meta:\n verbose_name_plural = u'Prix'\n\n\nclass DocumentAttache(models.Model):\n nom = models.CharField(max_length=255, verbose_name='Nom')\n document = FileBrowseField('Document', max_length=200, directory=\n 'evenements/docs', extensions=['.pdf', '.doc', '.odt', '.docx', '.txt']\n )\n reference = models.ForeignKey(Evenement)\n\n\nclass EvenementBibManager(models.Manager):\n\n def get_queryset(self):\n return super(EvenementBibManager, self).get_queryset().filter(categorie\n ='bib')\n\n\nclass EvenementBib(Evenement):\n objects = EvenementBibManager()\n\n\n class Meta:\n proxy = True\n verbose_name_plural = u'Événements Bibliothèques'\n verbose_name = u'Événement Bibliothèque'\n\n\nclass EvenementCrdManager(models.Manager):\n\n def get_queryset(self):\n return super(EvenementCrdManager, self).get_queryset().filter(categorie\n ='crd')\n\n\nclass EvenementCrd(Evenement):\n objects = EvenementCrdManager()\n\n\n class Meta:\n proxy = True\n verbose_name_plural = u'Événements Conservatoires'\n verbose_name = u'Événement Conservatoire'\n\n\nclass EvenementDevEcoManager(models.Manager):\n\n def get_queryset(self):\n return super(EvenementDevEcoManager, self).get_queryset().filter(\n categorie='eco')\n\n\nclass EvenementDevEco(Evenement):\n objects = EvenementDevEcoManager()\n\n\n class Meta:\n proxy = True\n verbose_name_plural = u'Événements Dev Eco'\n verbose_name = u'Événement Dev Eco'\n", "step-5": "# -*- coding: utf-8 -*-\nfrom django.db import models\nfrom filebrowser.fields import FileBrowseField\nfrom localisations.models import Ville, Lieu\nfrom model_utils.managers import InheritanceManager\nfrom services.models import Service\nfrom equipements.models import Equipement\nfrom localisations.models import Ville\nfrom django.db.models import permalink\n\n\nclass Organisateur(models.Model):\n nom = models.CharField(max_length=255)\n slug = models.SlugField(max_length=255, unique=True)\n meta_description = models.CharField(max_length=200)\n description = models.TextField()\n logo = FileBrowseField(\"Image\", max_length=255, directory=\"evenements\",\n extensions=[\".jpg\", \".png\", \".gif\", \".jpeg\"], blank=True, null=True)\n url = models.URLField(\"Site de cet organisateur: (facultatif) \", blank=True)\n email = models.EmailField(\"Mail (facultatif)\", max_length=255, blank=True)\n telephone = models.CharField(max_length=25)\n fax = models.CharField(\"Fax (facultatif)\", max_length=25, blank=True)\n rue = models.CharField(max_length=255)\n ville = models.ForeignKey(Ville)\n\n # Un choix de design pas très beau, mais fonctionellement les équipements, services, communes de la\n # communauté d'agglo peuvent organiser des evènements ainsi que d'autres entités exterieures alors ...\n\n orga_service = models.ForeignKey(Service, blank=True, null=True)\n orga_equipement = models.ForeignKey(Equipement, blank=True, null=True)\n orga_ville = models.ForeignKey(Ville, blank=True, null=True, related_name='orga_orga_ville')\n\n def __unicode__(self):\n return self.nom + \" / \" + self.ville.nom\n\n class Meta:\n verbose_name_plural = \"Organisateurs\"\n ordering = ['ville__nom']\n\n\nclass Saison(models.Model):\n nom = models.CharField(max_length=255)\n debut = models.DateTimeField(\"Date de début\")\n fin = models.DateTimeField(\"date de fin\")\n description = models.TextField()\n slug = models.SlugField(max_length=255, unique=True)\n\n objects = InheritanceManager()\n\n def __unicode__(self):\n return self.nom\n\n\nclass SaisonCulturelle(Saison):\n def __unicode__(self):\n return self.nom\n\n\nclass Festival(Saison):\n saison_culture = models.ForeignKey(SaisonCulturelle)\n\n def __unicode__(self):\n return self.nom\n\n\nclass TypeEvenement(models.Model):\n nom = models.CharField(max_length=255)\n slug = models.SlugField(unique=True)\n\n def __unicode__(self):\n return self.nom\n\n class Meta:\n ordering = ['nom']\n\n\nEVENEMENT_CATEGORIES = (\n ('bib', u'Bibliothèques/Médiatèques'),\n ('crd', u'Conservatoires'),\n ('sty', u'Sothevy'),\n ('eco', u'Développement Économique'),\n ('aut', u'Autres'),\n)\n\nEVENEMENT_PUBLIC = (\n ('adt', u'Adulte'),\n ('enf', u'Enfant'),\n ('pub', u'Tout public'),\n ('ent', u'Entreprises'),\n)\n\n\nclass Evenement(models.Model):\n nom = models.CharField(max_length=255)\n meta_description = models.CharField(max_length=200)\n description = models.TextField()\n debut = models.DateTimeField(\"Date de début\")\n fin = models.DateTimeField(\"Date de fin\")\n organisateur = models.ManyToManyField(Organisateur)\n image = FileBrowseField(\"Image (facultatif)\", max_length=255, directory=\"evenements\",\n extensions=[\".jpg\", \".png\", \".gif\", \".jpeg\", \".pdf\"], blank=True, null=True)\n url = models.URLField(\"Un lien vers plus d'infos: (facultatif)\", blank=True, null=True)\n url_reservation = models.URLField(\n \"Un lien vers la page de reservation: (facultatif, annule le lien vers plus d'infos) \", blank=True, null=True)\n categorie = models.CharField(max_length=3, choices=EVENEMENT_CATEGORIES, default='aut')\n public = models.CharField(max_length=3, choices=EVENEMENT_PUBLIC, default='pub')\n cadre_evenement = models.ForeignKey(Saison)\n type = models.ForeignKey(TypeEvenement)\n lieu = models.ForeignKey(Lieu)\n publish = models.BooleanField(\"Publié\", default=False)\n page_accueil = models.BooleanField(\"Page d'accueil\", default=False)\n complet = models.BooleanField(\"Ce spectacle est complet\", default=False)\n slug = models.SlugField(max_length=255, unique=True)\n\n class Meta:\n ordering = ['-debut']\n\n def Organisateurs(self):\n return \"\\n;\\n\".join([s.nom for s in self.organisateur.all()])\n\n def __unicode__(self):\n return self.nom\n\n def monthyeardebut(self):\n return self.debut.strftime(\"%m\") + \"-\" + self.debut.strftime(\"%Y\")\n\n @permalink\n def get_absolute_url(self):\n return ('event-details', (), {'slug': self.cadre_evenement.slug, 'evenement_slug': self.slug})\n\n\nclass Prix(models.Model):\n intitule = models.CharField(\"Intitulé \", max_length=255, blank=False, null=False)\n prix = models.FloatField(\"Prix (séparateur point ex : 0.5 )\", default=None, blank=False, null=True)\n evenement = models.ForeignKey(Evenement)\n\n class Meta:\n verbose_name_plural = u\"Prix\"\n\n\nclass DocumentAttache(models.Model):\n nom = models.CharField(max_length=255, verbose_name=\"Nom\")\n document = FileBrowseField(\"Document\", max_length=200, directory=\"evenements/docs\",\n extensions=[\".pdf\", \".doc\", \".odt\", \".docx\", \".txt\"])\n reference = models.ForeignKey(Evenement)\n\n\nclass EvenementBibManager(models.Manager):\n def get_queryset(self):\n return super(EvenementBibManager, self).get_queryset().filter(categorie='bib')\n\n\nclass EvenementBib(Evenement):\n objects = EvenementBibManager()\n\n class Meta:\n proxy = True\n verbose_name_plural = u\"Événements Bibliothèques\"\n verbose_name = u\"Événement Bibliothèque\"\n\n\nclass EvenementCrdManager(models.Manager):\n def get_queryset(self):\n return super(EvenementCrdManager, self).get_queryset().filter(categorie='crd')\n\n\nclass EvenementCrd(Evenement):\n objects = EvenementCrdManager()\n\n class Meta:\n proxy = True\n verbose_name_plural = u\"Événements Conservatoires\"\n verbose_name = u\"Événement Conservatoire\"\n\n\nclass EvenementDevEcoManager(models.Manager):\n def get_queryset(self):\n return super(EvenementDevEcoManager, self).get_queryset().filter(categorie='eco')\n\n\nclass EvenementDevEco(Evenement):\n objects = EvenementDevEcoManager()\n\n class Meta:\n proxy = True\n verbose_name_plural = u\"Événements Dev Eco\"\n verbose_name = u\"Événement Dev Eco\"", "step-ids": [ 30, 33, 34, 36, 39 ] }
[ 30, 33, 34, 36, 39 ]
<|reserved_special_token_0|> class TestRedisIntervalIADD(object): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class TestRedisIntervalIADD(object): <|reserved_special_token_0|> @classmethod def setup_class(cls): cls.redis = RedisInterval(host='localhost') def test_add_simple_text(self): """ Add simple text inside an interval """ value = self.redis.iadd('test', 0, 10, 'simple text') assert value == 'OK' <|reserved_special_token_1|> <|reserved_special_token_0|> class TestRedisIntervalIADD(object): """ Tests the IADD command """ @classmethod def setup_class(cls): cls.redis = RedisInterval(host='localhost') def test_add_simple_text(self): """ Add simple text inside an interval """ value = self.redis.iadd('test', 0, 10, 'simple text') assert value == 'OK' <|reserved_special_token_1|> from redis_interval.client import RedisInterval class TestRedisIntervalIADD(object): """ Tests the IADD command """ @classmethod def setup_class(cls): cls.redis = RedisInterval(host='localhost') def test_add_simple_text(self): """ Add simple text inside an interval """ value = self.redis.iadd('test', 0, 10, 'simple text') assert value == 'OK' <|reserved_special_token_1|> from redis_interval.client import RedisInterval class TestRedisIntervalIADD(object): """ Tests the IADD command """ @classmethod def setup_class(cls): cls.redis = RedisInterval(host="localhost") def test_add_simple_text(self): """ Add simple text inside an interval """ value = self.redis.iadd("test", 0, 10, "simple text") assert value == 'OK'
flexible
{ "blob_id": "0e7732ffcada864fb83b59625c5b9abb01150aaa", "index": 1702, "step-1": "<mask token>\n\n\nclass TestRedisIntervalIADD(object):\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass TestRedisIntervalIADD(object):\n <mask token>\n\n @classmethod\n def setup_class(cls):\n cls.redis = RedisInterval(host='localhost')\n\n def test_add_simple_text(self):\n \"\"\" Add simple text inside an interval \"\"\"\n value = self.redis.iadd('test', 0, 10, 'simple text')\n assert value == 'OK'\n", "step-3": "<mask token>\n\n\nclass TestRedisIntervalIADD(object):\n \"\"\" Tests the IADD command \"\"\"\n\n @classmethod\n def setup_class(cls):\n cls.redis = RedisInterval(host='localhost')\n\n def test_add_simple_text(self):\n \"\"\" Add simple text inside an interval \"\"\"\n value = self.redis.iadd('test', 0, 10, 'simple text')\n assert value == 'OK'\n", "step-4": "from redis_interval.client import RedisInterval\n\n\nclass TestRedisIntervalIADD(object):\n \"\"\" Tests the IADD command \"\"\"\n\n @classmethod\n def setup_class(cls):\n cls.redis = RedisInterval(host='localhost')\n\n def test_add_simple_text(self):\n \"\"\" Add simple text inside an interval \"\"\"\n value = self.redis.iadd('test', 0, 10, 'simple text')\n assert value == 'OK'\n", "step-5": "from redis_interval.client import RedisInterval\n\n\nclass TestRedisIntervalIADD(object):\n \"\"\" Tests the IADD command \"\"\"\n\n @classmethod\n def setup_class(cls):\n cls.redis = RedisInterval(host=\"localhost\")\n\n def test_add_simple_text(self):\n \"\"\" Add simple text inside an interval \"\"\"\n value = self.redis.iadd(\"test\", 0, 10, \"simple text\")\n assert value == 'OK'\n", "step-ids": [ 1, 3, 4, 5, 6 ] }
[ 1, 3, 4, 5, 6 ]
<|reserved_special_token_0|> def show(a): for i in range(len(a)): for j in range(len(a[i])): print(a[i][j], end=' ') print() def askUserZero(): while True: inputX = input('Введите номер строки нолика') inputY = input('Введите номер столбца нолика') if inputX.isdigit() and inputY.isdigit(): zeroPosX = int(inputX) zeroPosY = int(inputY) if zeroPosX in [1, 2, 3] and zeroPosY in [1, 2, 3]: if field[zeroPosX][zeroPosY] != '-': print('Позиция уже занята :( Попробуйте снова') else: return [zeroPosX, zeroPosY] else: print('Такой позиции не существует, попробуйте снова') else: print( 'Значение должно принимать значения от 1 до 3. Попробуйте снова' ) def askUserCross(): while True: inputX = input('Введите номер строки крестика') inputY = input('Введите номер столбца крестика') if inputX.isdigit() and inputY.isdigit(): crossPosX = int(inputX) crossPosY = int(inputY) if crossPosX in [1, 2, 3] and crossPosY in [1, 2, 3]: if field[crossPosX][crossPosY] != '-': print('Позиция уже занята :(\nПопробуйте снова') else: return [crossPosX, crossPosY] else: print('Такой позиции не существует, попробуйте снова') else: print( 'Значение должно принимать значения от 1 до 3. Попробуйте снова' ) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def show(a): for i in range(len(a)): for j in range(len(a[i])): print(a[i][j], end=' ') print() def askUserZero(): while True: inputX = input('Введите номер строки нолика') inputY = input('Введите номер столбца нолика') if inputX.isdigit() and inputY.isdigit(): zeroPosX = int(inputX) zeroPosY = int(inputY) if zeroPosX in [1, 2, 3] and zeroPosY in [1, 2, 3]: if field[zeroPosX][zeroPosY] != '-': print('Позиция уже занята :( Попробуйте снова') else: return [zeroPosX, zeroPosY] else: print('Такой позиции не существует, попробуйте снова') else: print( 'Значение должно принимать значения от 1 до 3. Попробуйте снова' ) def askUserCross(): while True: inputX = input('Введите номер строки крестика') inputY = input('Введите номер столбца крестика') if inputX.isdigit() and inputY.isdigit(): crossPosX = int(inputX) crossPosY = int(inputY) if crossPosX in [1, 2, 3] and crossPosY in [1, 2, 3]: if field[crossPosX][crossPosY] != '-': print('Позиция уже занята :(\nПопробуйте снова') else: return [crossPosX, crossPosY] else: print('Такой позиции не существует, попробуйте снова') else: print( 'Значение должно принимать значения от 1 до 3. Попробуйте снова' ) def winCombo(a): n = 0 m = 0 t = 0 r = 0 for i in range(1, len(a)): for j in range(1, len(a[i]) - 1): if a[i][j] == a[i][j + 1] and a[i][j] == 'X' or a[i][j] == a[i][ j + 1] and a[i][j] == '0': n += 1 s = a[i][j + 1] if n == len(a[i]) - 2: print('Выйграл', s) return 'Congratulations!' for i in range(1, len(a[1])): for j in range(1, len(a) - 1): if a[j][i] == a[j + 1][i] and a[j][i] == 'X' or a[j][i] == a[j + 1 ][i] and a[j][i] == '0': m += 1 k = a[j][i] if m == len(a) - 2: print('Выйграл', k) return 'Congratulations!' for i in range(1, len(a) - 1): if a[i][i] == a[i + 1][i + 1] and a[i][i] == 'X' or a[i][i] == a[i + 1 ][i + 1] and a[i][i] == '0': t += 1 z = a[i][i] if t == len(a) - 2: print('Выйграл', z) return 'Congratulations!' for i in range(1, len(a) - 1): if a[i][len(a) - i] == a[i + 1][len(a) - i - 1] and a[i][len(a) - i ] == 'X' or a[i][len(a) - i] == a[i + 1][len(a) - i - 1] and a[i][ len(a) - i] == '0': r += 1 b = a[i][len(a) - i] if r == len(a) - 2: print('Выйграл', b) return 'Congratulations!' <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def show(a): for i in range(len(a)): for j in range(len(a[i])): print(a[i][j], end=' ') print() def askUserZero(): while True: inputX = input('Введите номер строки нолика') inputY = input('Введите номер столбца нолика') if inputX.isdigit() and inputY.isdigit(): zeroPosX = int(inputX) zeroPosY = int(inputY) if zeroPosX in [1, 2, 3] and zeroPosY in [1, 2, 3]: if field[zeroPosX][zeroPosY] != '-': print('Позиция уже занята :( Попробуйте снова') else: return [zeroPosX, zeroPosY] else: print('Такой позиции не существует, попробуйте снова') else: print( 'Значение должно принимать значения от 1 до 3. Попробуйте снова' ) def askUserCross(): while True: inputX = input('Введите номер строки крестика') inputY = input('Введите номер столбца крестика') if inputX.isdigit() and inputY.isdigit(): crossPosX = int(inputX) crossPosY = int(inputY) if crossPosX in [1, 2, 3] and crossPosY in [1, 2, 3]: if field[crossPosX][crossPosY] != '-': print('Позиция уже занята :(\nПопробуйте снова') else: return [crossPosX, crossPosY] else: print('Такой позиции не существует, попробуйте снова') else: print( 'Значение должно принимать значения от 1 до 3. Попробуйте снова' ) def winCombo(a): n = 0 m = 0 t = 0 r = 0 for i in range(1, len(a)): for j in range(1, len(a[i]) - 1): if a[i][j] == a[i][j + 1] and a[i][j] == 'X' or a[i][j] == a[i][ j + 1] and a[i][j] == '0': n += 1 s = a[i][j + 1] if n == len(a[i]) - 2: print('Выйграл', s) return 'Congratulations!' for i in range(1, len(a[1])): for j in range(1, len(a) - 1): if a[j][i] == a[j + 1][i] and a[j][i] == 'X' or a[j][i] == a[j + 1 ][i] and a[j][i] == '0': m += 1 k = a[j][i] if m == len(a) - 2: print('Выйграл', k) return 'Congratulations!' for i in range(1, len(a) - 1): if a[i][i] == a[i + 1][i + 1] and a[i][i] == 'X' or a[i][i] == a[i + 1 ][i + 1] and a[i][i] == '0': t += 1 z = a[i][i] if t == len(a) - 2: print('Выйграл', z) return 'Congratulations!' for i in range(1, len(a) - 1): if a[i][len(a) - i] == a[i + 1][len(a) - i - 1] and a[i][len(a) - i ] == 'X' or a[i][len(a) - i] == a[i + 1][len(a) - i - 1] and a[i][ len(a) - i] == '0': r += 1 b = a[i][len(a) - i] if r == len(a) - 2: print('Выйграл', b) return 'Congratulations!' while True: show(field) crossPos = askUserCross() field[crossPos[0]][crossPos[1]] = 'X' show(field) result = winCombo(field) if result: show(field) break zeroPos = askUserZero() field[zeroPos[0]][zeroPos[1]] = '0' result = winCombo(field) if result: show(field) break print(result) <|reserved_special_token_1|> field = [['*', '1', '2', '3'], ['1', '-', '-', '-'], ['2', '-', '-', '-'], ['3', '-', '-', '-']] def show(a): for i in range(len(a)): for j in range(len(a[i])): print(a[i][j], end=' ') print() def askUserZero(): while True: inputX = input('Введите номер строки нолика') inputY = input('Введите номер столбца нолика') if inputX.isdigit() and inputY.isdigit(): zeroPosX = int(inputX) zeroPosY = int(inputY) if zeroPosX in [1, 2, 3] and zeroPosY in [1, 2, 3]: if field[zeroPosX][zeroPosY] != '-': print('Позиция уже занята :( Попробуйте снова') else: return [zeroPosX, zeroPosY] else: print('Такой позиции не существует, попробуйте снова') else: print( 'Значение должно принимать значения от 1 до 3. Попробуйте снова' ) def askUserCross(): while True: inputX = input('Введите номер строки крестика') inputY = input('Введите номер столбца крестика') if inputX.isdigit() and inputY.isdigit(): crossPosX = int(inputX) crossPosY = int(inputY) if crossPosX in [1, 2, 3] and crossPosY in [1, 2, 3]: if field[crossPosX][crossPosY] != '-': print('Позиция уже занята :(\nПопробуйте снова') else: return [crossPosX, crossPosY] else: print('Такой позиции не существует, попробуйте снова') else: print( 'Значение должно принимать значения от 1 до 3. Попробуйте снова' ) def winCombo(a): n = 0 m = 0 t = 0 r = 0 for i in range(1, len(a)): for j in range(1, len(a[i]) - 1): if a[i][j] == a[i][j + 1] and a[i][j] == 'X' or a[i][j] == a[i][ j + 1] and a[i][j] == '0': n += 1 s = a[i][j + 1] if n == len(a[i]) - 2: print('Выйграл', s) return 'Congratulations!' for i in range(1, len(a[1])): for j in range(1, len(a) - 1): if a[j][i] == a[j + 1][i] and a[j][i] == 'X' or a[j][i] == a[j + 1 ][i] and a[j][i] == '0': m += 1 k = a[j][i] if m == len(a) - 2: print('Выйграл', k) return 'Congratulations!' for i in range(1, len(a) - 1): if a[i][i] == a[i + 1][i + 1] and a[i][i] == 'X' or a[i][i] == a[i + 1 ][i + 1] and a[i][i] == '0': t += 1 z = a[i][i] if t == len(a) - 2: print('Выйграл', z) return 'Congratulations!' for i in range(1, len(a) - 1): if a[i][len(a) - i] == a[i + 1][len(a) - i - 1] and a[i][len(a) - i ] == 'X' or a[i][len(a) - i] == a[i + 1][len(a) - i - 1] and a[i][ len(a) - i] == '0': r += 1 b = a[i][len(a) - i] if r == len(a) - 2: print('Выйграл', b) return 'Congratulations!' while True: show(field) crossPos = askUserCross() field[crossPos[0]][crossPos[1]] = 'X' show(field) result = winCombo(field) if result: show(field) break zeroPos = askUserZero() field[zeroPos[0]][zeroPos[1]] = '0' result = winCombo(field) if result: show(field) break print(result) <|reserved_special_token_1|> field = [['*', '1', '2', '3'], ['1', '-', '-', '-'], ['2', '-', '-', '-'], ['3', '-', '-', '-']] def show(a): for i in range(len(a)): for j in range(len(a[i])): print(a[i][j], end=' ') print() def askUserZero(): while True: inputX = input('Введите номер строки нолика') inputY = input('Введите номер столбца нолика') if inputX.isdigit() and inputY.isdigit(): zeroPosX = int(inputX) zeroPosY = int(inputY) if zeroPosX in [1, 2, 3] and zeroPosY in [1, 2, 3]: if field[zeroPosX][zeroPosY] != '-': print("Позиция уже занята :( Попробуйте снова") else: return [zeroPosX, zeroPosY] else: print("Такой позиции не существует, попробуйте снова") else: print("Значение должно принимать значения от 1 до 3. Попробуйте снова") def askUserCross(): while True: inputX = input('Введите номер строки крестика') inputY = input('Введите номер столбца крестика') if inputX.isdigit() and inputY.isdigit(): crossPosX = int(inputX) crossPosY = int(inputY) if crossPosX in [1, 2, 3] and crossPosY in [1, 2, 3]: if field[crossPosX][crossPosY] != '-': print("Позиция уже занята :(\nПопробуйте снова") else: return [crossPosX, crossPosY] else: print("Такой позиции не существует, попробуйте снова") else: print("Значение должно принимать значения от 1 до 3. Попробуйте снова") def winCombo(a): n=0 m=0 t=0 r=0 for i in range(1, len(a)): for j in range(1, len(a[i])-1): if a[i][j] == a[i][j+1] and a[i][j] == 'X' or a[i][j] == a[i][j+1] and a[i][j] == '0': n += 1 s = a[i][j+1] if n == len(a[i])-2: print("Выйграл", s) return "Congratulations!" for i in range(1, len(a[1])): for j in range (1,len(a)-1): if a[j][i] == a[j+1][i] and a[j][i] == 'X' or a[j][i] == a[j+1][i] and a[j][i] == '0': m += 1 k = a[j][i] if m == len(a)-2: print("Выйграл", k) return "Congratulations!" for i in range(1, len(a)-1): if a[i][i] == a[i+1][i+1] and a[i][i] == 'X' or a[i][i] == a[i+1][i+1] and a[i][i] == '0': t += 1 z = a[i][i] if t == len(a)-2: print("Выйграл", z) return "Congratulations!" for i in range(1, len(a)-1): if a[i][len(a)-i] == a[i+1][len(a)-i-1] and a[i][len(a)-i] == 'X' or a[i][len(a)-i] == a[i+1][len(a)-i-1] and a[i][len(a)-i] == '0': r += 1 b = a[i][len(a)-i] if r == len(a)-2: print("Выйграл", b) return "Congratulations!" while True: show(field) crossPos = askUserCross() field[crossPos[0]][crossPos[1]]='X' show(field) result=winCombo(field) if result: show(field) break zeroPos = askUserZero() field[zeroPos[0]][zeroPos[1]]='0' result = winCombo(field) if result: show(field) break print(result)
flexible
{ "blob_id": "3f22bf954a8c4608ec4bd4a28bea3679a664a99a", "index": 2364, "step-1": "<mask token>\n\n\ndef show(a):\n for i in range(len(a)):\n for j in range(len(a[i])):\n print(a[i][j], end=' ')\n print()\n\n\ndef askUserZero():\n while True:\n inputX = input('Введите номер строки нолика')\n inputY = input('Введите номер столбца нолика')\n if inputX.isdigit() and inputY.isdigit():\n zeroPosX = int(inputX)\n zeroPosY = int(inputY)\n if zeroPosX in [1, 2, 3] and zeroPosY in [1, 2, 3]:\n if field[zeroPosX][zeroPosY] != '-':\n print('Позиция уже занята :( Попробуйте снова')\n else:\n return [zeroPosX, zeroPosY]\n else:\n print('Такой позиции не существует, попробуйте снова')\n else:\n print(\n 'Значение должно принимать значения от 1 до 3. Попробуйте снова'\n )\n\n\ndef askUserCross():\n while True:\n inputX = input('Введите номер строки крестика')\n inputY = input('Введите номер столбца крестика')\n if inputX.isdigit() and inputY.isdigit():\n crossPosX = int(inputX)\n crossPosY = int(inputY)\n if crossPosX in [1, 2, 3] and crossPosY in [1, 2, 3]:\n if field[crossPosX][crossPosY] != '-':\n print('Позиция уже занята :(\\nПопробуйте снова')\n else:\n return [crossPosX, crossPosY]\n else:\n print('Такой позиции не существует, попробуйте снова')\n else:\n print(\n 'Значение должно принимать значения от 1 до 3. Попробуйте снова'\n )\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef show(a):\n for i in range(len(a)):\n for j in range(len(a[i])):\n print(a[i][j], end=' ')\n print()\n\n\ndef askUserZero():\n while True:\n inputX = input('Введите номер строки нолика')\n inputY = input('Введите номер столбца нолика')\n if inputX.isdigit() and inputY.isdigit():\n zeroPosX = int(inputX)\n zeroPosY = int(inputY)\n if zeroPosX in [1, 2, 3] and zeroPosY in [1, 2, 3]:\n if field[zeroPosX][zeroPosY] != '-':\n print('Позиция уже занята :( Попробуйте снова')\n else:\n return [zeroPosX, zeroPosY]\n else:\n print('Такой позиции не существует, попробуйте снова')\n else:\n print(\n 'Значение должно принимать значения от 1 до 3. Попробуйте снова'\n )\n\n\ndef askUserCross():\n while True:\n inputX = input('Введите номер строки крестика')\n inputY = input('Введите номер столбца крестика')\n if inputX.isdigit() and inputY.isdigit():\n crossPosX = int(inputX)\n crossPosY = int(inputY)\n if crossPosX in [1, 2, 3] and crossPosY in [1, 2, 3]:\n if field[crossPosX][crossPosY] != '-':\n print('Позиция уже занята :(\\nПопробуйте снова')\n else:\n return [crossPosX, crossPosY]\n else:\n print('Такой позиции не существует, попробуйте снова')\n else:\n print(\n 'Значение должно принимать значения от 1 до 3. Попробуйте снова'\n )\n\n\ndef winCombo(a):\n n = 0\n m = 0\n t = 0\n r = 0\n for i in range(1, len(a)):\n for j in range(1, len(a[i]) - 1):\n if a[i][j] == a[i][j + 1] and a[i][j] == 'X' or a[i][j] == a[i][\n j + 1] and a[i][j] == '0':\n n += 1\n s = a[i][j + 1]\n if n == len(a[i]) - 2:\n print('Выйграл', s)\n return 'Congratulations!'\n for i in range(1, len(a[1])):\n for j in range(1, len(a) - 1):\n if a[j][i] == a[j + 1][i] and a[j][i] == 'X' or a[j][i] == a[j + 1\n ][i] and a[j][i] == '0':\n m += 1\n k = a[j][i]\n if m == len(a) - 2:\n print('Выйграл', k)\n return 'Congratulations!'\n for i in range(1, len(a) - 1):\n if a[i][i] == a[i + 1][i + 1] and a[i][i] == 'X' or a[i][i] == a[i + 1\n ][i + 1] and a[i][i] == '0':\n t += 1\n z = a[i][i]\n if t == len(a) - 2:\n print('Выйграл', z)\n return 'Congratulations!'\n for i in range(1, len(a) - 1):\n if a[i][len(a) - i] == a[i + 1][len(a) - i - 1] and a[i][len(a) - i\n ] == 'X' or a[i][len(a) - i] == a[i + 1][len(a) - i - 1] and a[i][\n len(a) - i] == '0':\n r += 1\n b = a[i][len(a) - i]\n if r == len(a) - 2:\n print('Выйграл', b)\n return 'Congratulations!'\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef show(a):\n for i in range(len(a)):\n for j in range(len(a[i])):\n print(a[i][j], end=' ')\n print()\n\n\ndef askUserZero():\n while True:\n inputX = input('Введите номер строки нолика')\n inputY = input('Введите номер столбца нолика')\n if inputX.isdigit() and inputY.isdigit():\n zeroPosX = int(inputX)\n zeroPosY = int(inputY)\n if zeroPosX in [1, 2, 3] and zeroPosY in [1, 2, 3]:\n if field[zeroPosX][zeroPosY] != '-':\n print('Позиция уже занята :( Попробуйте снова')\n else:\n return [zeroPosX, zeroPosY]\n else:\n print('Такой позиции не существует, попробуйте снова')\n else:\n print(\n 'Значение должно принимать значения от 1 до 3. Попробуйте снова'\n )\n\n\ndef askUserCross():\n while True:\n inputX = input('Введите номер строки крестика')\n inputY = input('Введите номер столбца крестика')\n if inputX.isdigit() and inputY.isdigit():\n crossPosX = int(inputX)\n crossPosY = int(inputY)\n if crossPosX in [1, 2, 3] and crossPosY in [1, 2, 3]:\n if field[crossPosX][crossPosY] != '-':\n print('Позиция уже занята :(\\nПопробуйте снова')\n else:\n return [crossPosX, crossPosY]\n else:\n print('Такой позиции не существует, попробуйте снова')\n else:\n print(\n 'Значение должно принимать значения от 1 до 3. Попробуйте снова'\n )\n\n\ndef winCombo(a):\n n = 0\n m = 0\n t = 0\n r = 0\n for i in range(1, len(a)):\n for j in range(1, len(a[i]) - 1):\n if a[i][j] == a[i][j + 1] and a[i][j] == 'X' or a[i][j] == a[i][\n j + 1] and a[i][j] == '0':\n n += 1\n s = a[i][j + 1]\n if n == len(a[i]) - 2:\n print('Выйграл', s)\n return 'Congratulations!'\n for i in range(1, len(a[1])):\n for j in range(1, len(a) - 1):\n if a[j][i] == a[j + 1][i] and a[j][i] == 'X' or a[j][i] == a[j + 1\n ][i] and a[j][i] == '0':\n m += 1\n k = a[j][i]\n if m == len(a) - 2:\n print('Выйграл', k)\n return 'Congratulations!'\n for i in range(1, len(a) - 1):\n if a[i][i] == a[i + 1][i + 1] and a[i][i] == 'X' or a[i][i] == a[i + 1\n ][i + 1] and a[i][i] == '0':\n t += 1\n z = a[i][i]\n if t == len(a) - 2:\n print('Выйграл', z)\n return 'Congratulations!'\n for i in range(1, len(a) - 1):\n if a[i][len(a) - i] == a[i + 1][len(a) - i - 1] and a[i][len(a) - i\n ] == 'X' or a[i][len(a) - i] == a[i + 1][len(a) - i - 1] and a[i][\n len(a) - i] == '0':\n r += 1\n b = a[i][len(a) - i]\n if r == len(a) - 2:\n print('Выйграл', b)\n return 'Congratulations!'\n\n\nwhile True:\n show(field)\n crossPos = askUserCross()\n field[crossPos[0]][crossPos[1]] = 'X'\n show(field)\n result = winCombo(field)\n if result:\n show(field)\n break\n zeroPos = askUserZero()\n field[zeroPos[0]][zeroPos[1]] = '0'\n result = winCombo(field)\n if result:\n show(field)\n break\n print(result)\n", "step-4": "field = [['*', '1', '2', '3'], ['1', '-', '-', '-'], ['2', '-', '-', '-'],\n ['3', '-', '-', '-']]\n\n\ndef show(a):\n for i in range(len(a)):\n for j in range(len(a[i])):\n print(a[i][j], end=' ')\n print()\n\n\ndef askUserZero():\n while True:\n inputX = input('Введите номер строки нолика')\n inputY = input('Введите номер столбца нолика')\n if inputX.isdigit() and inputY.isdigit():\n zeroPosX = int(inputX)\n zeroPosY = int(inputY)\n if zeroPosX in [1, 2, 3] and zeroPosY in [1, 2, 3]:\n if field[zeroPosX][zeroPosY] != '-':\n print('Позиция уже занята :( Попробуйте снова')\n else:\n return [zeroPosX, zeroPosY]\n else:\n print('Такой позиции не существует, попробуйте снова')\n else:\n print(\n 'Значение должно принимать значения от 1 до 3. Попробуйте снова'\n )\n\n\ndef askUserCross():\n while True:\n inputX = input('Введите номер строки крестика')\n inputY = input('Введите номер столбца крестика')\n if inputX.isdigit() and inputY.isdigit():\n crossPosX = int(inputX)\n crossPosY = int(inputY)\n if crossPosX in [1, 2, 3] and crossPosY in [1, 2, 3]:\n if field[crossPosX][crossPosY] != '-':\n print('Позиция уже занята :(\\nПопробуйте снова')\n else:\n return [crossPosX, crossPosY]\n else:\n print('Такой позиции не существует, попробуйте снова')\n else:\n print(\n 'Значение должно принимать значения от 1 до 3. Попробуйте снова'\n )\n\n\ndef winCombo(a):\n n = 0\n m = 0\n t = 0\n r = 0\n for i in range(1, len(a)):\n for j in range(1, len(a[i]) - 1):\n if a[i][j] == a[i][j + 1] and a[i][j] == 'X' or a[i][j] == a[i][\n j + 1] and a[i][j] == '0':\n n += 1\n s = a[i][j + 1]\n if n == len(a[i]) - 2:\n print('Выйграл', s)\n return 'Congratulations!'\n for i in range(1, len(a[1])):\n for j in range(1, len(a) - 1):\n if a[j][i] == a[j + 1][i] and a[j][i] == 'X' or a[j][i] == a[j + 1\n ][i] and a[j][i] == '0':\n m += 1\n k = a[j][i]\n if m == len(a) - 2:\n print('Выйграл', k)\n return 'Congratulations!'\n for i in range(1, len(a) - 1):\n if a[i][i] == a[i + 1][i + 1] and a[i][i] == 'X' or a[i][i] == a[i + 1\n ][i + 1] and a[i][i] == '0':\n t += 1\n z = a[i][i]\n if t == len(a) - 2:\n print('Выйграл', z)\n return 'Congratulations!'\n for i in range(1, len(a) - 1):\n if a[i][len(a) - i] == a[i + 1][len(a) - i - 1] and a[i][len(a) - i\n ] == 'X' or a[i][len(a) - i] == a[i + 1][len(a) - i - 1] and a[i][\n len(a) - i] == '0':\n r += 1\n b = a[i][len(a) - i]\n if r == len(a) - 2:\n print('Выйграл', b)\n return 'Congratulations!'\n\n\nwhile True:\n show(field)\n crossPos = askUserCross()\n field[crossPos[0]][crossPos[1]] = 'X'\n show(field)\n result = winCombo(field)\n if result:\n show(field)\n break\n zeroPos = askUserZero()\n field[zeroPos[0]][zeroPos[1]] = '0'\n result = winCombo(field)\n if result:\n show(field)\n break\n print(result)\n", "step-5": "field = [['*', '1', '2', '3'], ['1', '-', '-', '-'], ['2', '-', '-', '-'], ['3', '-', '-', '-']]\r\ndef show(a):\r\n for i in range(len(a)):\r\n for j in range(len(a[i])):\r\n print(a[i][j], end=' ')\r\n print()\r\ndef askUserZero():\r\n while True:\r\n inputX = input('Введите номер строки нолика')\r\n inputY = input('Введите номер столбца нолика')\r\n\r\n if inputX.isdigit() and inputY.isdigit():\r\n zeroPosX = int(inputX)\r\n zeroPosY = int(inputY)\r\n if zeroPosX in [1, 2, 3] and zeroPosY in [1, 2, 3]:\r\n if field[zeroPosX][zeroPosY] != '-':\r\n print(\"Позиция уже занята :( Попробуйте снова\")\r\n else:\r\n return [zeroPosX, zeroPosY]\r\n else:\r\n print(\"Такой позиции не существует, попробуйте снова\")\r\n else:\r\n print(\"Значение должно принимать значения от 1 до 3. Попробуйте снова\")\r\n\r\n\r\ndef askUserCross():\r\n while True:\r\n inputX = input('Введите номер строки крестика')\r\n inputY = input('Введите номер столбца крестика')\r\n if inputX.isdigit() and inputY.isdigit():\r\n crossPosX = int(inputX)\r\n crossPosY = int(inputY)\r\n if crossPosX in [1, 2, 3] and crossPosY in [1, 2, 3]:\r\n if field[crossPosX][crossPosY] != '-':\r\n print(\"Позиция уже занята :(\\nПопробуйте снова\")\r\n else:\r\n return [crossPosX, crossPosY]\r\n else:\r\n print(\"Такой позиции не существует, попробуйте снова\")\r\n else:\r\n print(\"Значение должно принимать значения от 1 до 3. Попробуйте снова\")\r\n\r\n\r\n\r\ndef winCombo(a):\r\n n=0\r\n m=0\r\n t=0\r\n r=0\r\n for i in range(1, len(a)):\r\n for j in range(1, len(a[i])-1):\r\n if a[i][j] == a[i][j+1] and a[i][j] == 'X' or a[i][j] == a[i][j+1] and a[i][j] == '0':\r\n n += 1\r\n s = a[i][j+1]\r\n if n == len(a[i])-2:\r\n print(\"Выйграл\", s)\r\n return \"Congratulations!\"\r\n\r\n for i in range(1, len(a[1])):\r\n for j in range (1,len(a)-1):\r\n if a[j][i] == a[j+1][i] and a[j][i] == 'X' or a[j][i] == a[j+1][i] and a[j][i] == '0':\r\n m += 1\r\n k = a[j][i]\r\n if m == len(a)-2:\r\n print(\"Выйграл\", k)\r\n return \"Congratulations!\"\r\n\r\n for i in range(1, len(a)-1):\r\n if a[i][i] == a[i+1][i+1] and a[i][i] == 'X' or a[i][i] == a[i+1][i+1] and a[i][i] == '0':\r\n t += 1\r\n z = a[i][i]\r\n if t == len(a)-2:\r\n print(\"Выйграл\", z)\r\n return \"Congratulations!\"\r\n\r\n for i in range(1, len(a)-1):\r\n\r\n if a[i][len(a)-i] == a[i+1][len(a)-i-1] and a[i][len(a)-i] == 'X' or a[i][len(a)-i] == a[i+1][len(a)-i-1] and a[i][len(a)-i] == '0':\r\n r += 1\r\n b = a[i][len(a)-i]\r\n\r\n if r == len(a)-2:\r\n print(\"Выйграл\", b)\r\n return \"Congratulations!\"\r\n\r\nwhile True:\r\n show(field)\r\n crossPos = askUserCross()\r\n field[crossPos[0]][crossPos[1]]='X'\r\n show(field)\r\n result=winCombo(field)\r\n if result:\r\n show(field)\r\n break\r\n zeroPos = askUserZero()\r\n field[zeroPos[0]][zeroPos[1]]='0'\r\n result = winCombo(field)\r\n if result:\r\n show(field)\r\n break\r\n print(result)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
import wx from six import print_ import os FONTSIZE = 10 class TextDocPrintout(wx.Printout): """ A printout class that is able to print simple text documents. Does not handle page numbers or titles, and it assumes that no lines are longer than what will fit within the page width. Those features are left as an exercise for the reader. ;-) """ def __init__(self, text, title, margins): wx.Printout.__init__(self, title) self.lines = text.split('\n') self.margins = margins def HasPage(self, page): return page <= self.numPages def GetPageInfo(self): return (1, self.numPages, 1, self.numPages) def CalculateScale(self, dc): # Scale the DC such that the printout is roughly the same as # the screen scaling. ppiPrinterX, ppiPrinterY = self.GetPPIPrinter() ppiScreenX, ppiScreenY = self.GetPPIScreen() logScale = float(ppiPrinterX)/float(ppiScreenX) # Now adjust if the real page size is reduced (such as when # drawing on a scaled wx.MemoryDC in the Print Preview.) If # page width == DC width then nothing changes, otherwise we # scale down for the DC. pw, ph = self.GetPageSizePixels() dw, dh = dc.GetSize() scale = logScale * float(dw)/float(pw) # Set the DC's scale. dc.SetUserScale(scale, scale) # Find the logical units per millimeter (for calculating the # margins) self.logUnitsMM = float(ppiPrinterX)/(logScale*25.4) def CalculateLayout(self, dc): # Determine the position of the margins and the # page/line height topLeft, bottomRight = self.margins dw, dh = dc.GetSize() self.x1 = topLeft.x * self.logUnitsMM self.y1 = topLeft.y * self.logUnitsMM self.x2 = dc.DeviceToLogicalXRel(dw) - bottomRight.x * self.logUnitsMM self.y2 = dc.DeviceToLogicalYRel(dh) - bottomRight.y * self.logUnitsMM # use a 1mm buffer around the inside of the box, and a few # pixels between each line self.pageHeight = self.y2 - self.y1 - 2*self.logUnitsMM font = wx.Font(FONTSIZE, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) dc.SetFont(font) self.lineHeight = dc.GetCharHeight() self.linesPerPage = int(self.pageHeight/self.lineHeight) def OnPreparePrinting(self): # calculate the number of pages dc = self.GetDC() self.CalculateScale(dc) self.CalculateLayout(dc) self.numPages = len(self.lines) / self.linesPerPage if len(self.lines) % self.linesPerPage != 0: self.numPages += 1 def OnPrintPage(self, page): dc = self.GetDC() self.CalculateScale(dc) self.CalculateLayout(dc) # draw a page outline at the margin points dc.SetPen(wx.Pen("black", 0)) dc.SetBrush(wx.TRANSPARENT_BRUSH) r = wx.Rect(wx.Point(self.x1, self.y1), wx.Point(self.x2, self.y2)) dc.DrawRectangle(r) dc.SetClippingRegion(r) # Draw the text lines for this page line = (page-1) * self.linesPerPage x = self.x1 + self.logUnitsMM y = self.y1 + self.logUnitsMM while line < (page * self.linesPerPage): dc.DrawText(self.lines[line], x, y) y += self.lineHeight line += 1 if line >= len(self.lines): break return True class PrintFrameworkSample(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, size=(640, 480), title="Print Framework Sample") self.CreateStatusBar() # A text widget to display the doc and let it be edited self.tc = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE|wx.TE_DONTWRAP) self.tc.SetFont(wx.Font(FONTSIZE, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) filename = os.path.join(os.path.dirname(__file__), "sample-text.txt") with open(filename) as fid: self.tc.SetValue(fid.read()) self.tc.Bind(wx.EVT_SET_FOCUS, self.OnClearSelection) wx.CallAfter(self.tc.SetInsertionPoint, 0) # Create the menu and menubar menu = wx.Menu() item = menu.Append(-1, "Page Setup...\tF5", "Set up page margins and etc.") self.Bind(wx.EVT_MENU, self.OnPageSetup, item) item = menu.Append(-1, "Print Preview...\tF6", "View the printout on-screen") self.Bind(wx.EVT_MENU, self.OnPrintPreview, item) item = menu.Append(-1, "Print...\tF7", "Print the document") self.Bind(wx.EVT_MENU, self.OnPrint, item) menu.AppendSeparator() ## item = menu.Append(-1, "Test other stuff...\tF9", "") ## self.Bind(wx.EVT_MENU, self.OnPrintTest, item) ## menu.AppendSeparator() item = menu.Append(wx.ID_ABOUT, "About", "About this application") self.Bind(wx.EVT_MENU, self.OnAbout, item) item = menu.Append(wx.ID_EXIT, "E&xit\tCtrl-Q", "Close this application") self.Bind(wx.EVT_MENU, self.OnExit, item) menubar = wx.MenuBar() menubar.Append(menu, "&File") self.SetMenuBar(menubar) # initialize the print data and set some default values self.pdata = wx.PrintData() self.pdata.SetPaperId(wx.PAPER_LETTER) self.pdata.SetOrientation(wx.PORTRAIT) self.margins = (wx.Point(15,15), wx.Point(15,15)) def OnExit(self, evt): self.Close() def OnAbout(self, evt): wx.MessageBox('Print framework sample application\n' '\n' 'Using wxPython %s' % wx.version(), 'About') def OnClearSelection(self, evt): evt.Skip() wx.CallAfter(self.tc.SetInsertionPoint, self.tc.GetInsertionPoint()) def OnPageSetup(self, evt): data = wx.PageSetupDialogData() data.SetPrintData(self.pdata) data.SetDefaultMinMargins(True) data.SetMarginTopLeft(self.margins[0]) data.SetMarginBottomRight(self.margins[1]) dlg = wx.PageSetupDialog(self, data) if dlg.ShowModal() == wx.ID_OK: data = dlg.GetPageSetupData() self.pdata = wx.PrintData(data.GetPrintData()) # force a copy self.pdata.SetPaperId(data.GetPaperId()) #print_("paperID %r, paperSize %r" % (self.pdata.GetPaperId(), self.pdata.GetPaperSize())) self.margins = (data.GetMarginTopLeft(), data.GetMarginBottomRight()) dlg.Destroy() def OnPrintPreview(self, evt): data = wx.PrintDialogData(self.pdata) text = self.tc.GetValue() printout1 = TextDocPrintout(text, "title", self.margins) printout2 = TextDocPrintout(text, "title", self.margins) preview = wx.PrintPreview(printout1, printout2, data) if not preview: wx.MessageBox("Unable to create PrintPreview!", "Error") else: # create the preview frame such that it overlays the app frame frame = wx.PreviewFrame(preview, self, "Print Preview", pos=self.GetPosition(), size=self.GetSize()) frame.Initialize() frame.Show() def OnPrint(self, evt): data = wx.PrintDialogData(self.pdata) printer = wx.Printer(data) text = self.tc.GetValue() printout = TextDocPrintout(text, "title", self.margins) useSetupDialog = True if not printer.Print(self, printout, useSetupDialog) \ and printer.GetLastError() == wx.PRINTER_ERROR: wx.MessageBox( "There was a problem printing.\n" "Perhaps your current printer is not set correctly?", "Printing Error", wx.OK) else: data = printer.GetPrintDialogData() self.pdata = wx.PrintData(data.GetPrintData()) # force a copy printout.Destroy() def OnPrintTest(self, evt): data = wx.PrintDialogData(self.pdata) dlg = wx.PrintDialog(self, data) if dlg.ShowModal() == wx.ID_OK: data = dlg.GetPrintDialogData() print_() print_("GetFromPage:", data.GetFromPage()) print_("GetToPage:", data.GetToPage()) print_("GetMinPage:", data.GetMinPage()) print_("GetMaxPage:", data.GetMaxPage()) print_("GetNoCopies:", data.GetNoCopies()) print_("GetAllPages:", data.GetAllPages()) print_("GetSelection:", data.GetSelection()) print_("GetCollate:", data.GetCollate()) print_("GetPrintToFile:", data.GetPrintToFile()) self.pdata = wx.PrintData(data.GetPrintData()) print_() print_("GetPrinterName:", self.pdata.GetPrinterName()) dlg.Destroy() app = wx.App() frm = PrintFrameworkSample() frm.Show() app.MainLoop()
normal
{ "blob_id": "2790bd80949bafe4e98ab9aca9cf80a6a0f31490", "index": 6200, "step-1": "<mask token>\n\n\nclass TextDocPrintout(wx.Printout):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass PrintFrameworkSample(wx.Frame):\n\n def __init__(self):\n wx.Frame.__init__(self, None, size=(640, 480), title=\n 'Print Framework Sample')\n self.CreateStatusBar()\n self.tc = wx.TextCtrl(self, -1, '', style=wx.TE_MULTILINE | wx.\n TE_DONTWRAP)\n self.tc.SetFont(wx.Font(FONTSIZE, wx.FONTFAMILY_TELETYPE, wx.\n FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL))\n filename = os.path.join(os.path.dirname(__file__), 'sample-text.txt')\n with open(filename) as fid:\n self.tc.SetValue(fid.read())\n self.tc.Bind(wx.EVT_SET_FOCUS, self.OnClearSelection)\n wx.CallAfter(self.tc.SetInsertionPoint, 0)\n menu = wx.Menu()\n item = menu.Append(-1, 'Page Setup...\\tF5',\n 'Set up page margins and etc.')\n self.Bind(wx.EVT_MENU, self.OnPageSetup, item)\n item = menu.Append(-1, 'Print Preview...\\tF6',\n 'View the printout on-screen')\n self.Bind(wx.EVT_MENU, self.OnPrintPreview, item)\n item = menu.Append(-1, 'Print...\\tF7', 'Print the document')\n self.Bind(wx.EVT_MENU, self.OnPrint, item)\n menu.AppendSeparator()\n item = menu.Append(wx.ID_ABOUT, 'About', 'About this application')\n self.Bind(wx.EVT_MENU, self.OnAbout, item)\n item = menu.Append(wx.ID_EXIT, 'E&xit\\tCtrl-Q',\n 'Close this application')\n self.Bind(wx.EVT_MENU, self.OnExit, item)\n menubar = wx.MenuBar()\n menubar.Append(menu, '&File')\n self.SetMenuBar(menubar)\n self.pdata = wx.PrintData()\n self.pdata.SetPaperId(wx.PAPER_LETTER)\n self.pdata.SetOrientation(wx.PORTRAIT)\n self.margins = wx.Point(15, 15), wx.Point(15, 15)\n\n def OnExit(self, evt):\n self.Close()\n\n def OnAbout(self, evt):\n wx.MessageBox(\n 'Print framework sample application\\n\\nUsing wxPython %s' % wx.\n version(), 'About')\n\n def OnClearSelection(self, evt):\n evt.Skip()\n wx.CallAfter(self.tc.SetInsertionPoint, self.tc.GetInsertionPoint())\n\n def OnPageSetup(self, evt):\n data = wx.PageSetupDialogData()\n data.SetPrintData(self.pdata)\n data.SetDefaultMinMargins(True)\n data.SetMarginTopLeft(self.margins[0])\n data.SetMarginBottomRight(self.margins[1])\n dlg = wx.PageSetupDialog(self, data)\n if dlg.ShowModal() == wx.ID_OK:\n data = dlg.GetPageSetupData()\n self.pdata = wx.PrintData(data.GetPrintData())\n self.pdata.SetPaperId(data.GetPaperId())\n self.margins = data.GetMarginTopLeft(), data.GetMarginBottomRight()\n dlg.Destroy()\n\n def OnPrintPreview(self, evt):\n data = wx.PrintDialogData(self.pdata)\n text = self.tc.GetValue()\n printout1 = TextDocPrintout(text, 'title', self.margins)\n printout2 = TextDocPrintout(text, 'title', self.margins)\n preview = wx.PrintPreview(printout1, printout2, data)\n if not preview:\n wx.MessageBox('Unable to create PrintPreview!', 'Error')\n else:\n frame = wx.PreviewFrame(preview, self, 'Print Preview', pos=\n self.GetPosition(), size=self.GetSize())\n frame.Initialize()\n frame.Show()\n\n def OnPrint(self, evt):\n data = wx.PrintDialogData(self.pdata)\n printer = wx.Printer(data)\n text = self.tc.GetValue()\n printout = TextDocPrintout(text, 'title', self.margins)\n useSetupDialog = True\n if not printer.Print(self, printout, useSetupDialog\n ) and printer.GetLastError() == wx.PRINTER_ERROR:\n wx.MessageBox(\n \"\"\"There was a problem printing.\nPerhaps your current printer is not set correctly?\"\"\"\n , 'Printing Error', wx.OK)\n else:\n data = printer.GetPrintDialogData()\n self.pdata = wx.PrintData(data.GetPrintData())\n printout.Destroy()\n\n def OnPrintTest(self, evt):\n data = wx.PrintDialogData(self.pdata)\n dlg = wx.PrintDialog(self, data)\n if dlg.ShowModal() == wx.ID_OK:\n data = dlg.GetPrintDialogData()\n print_()\n print_('GetFromPage:', data.GetFromPage())\n print_('GetToPage:', data.GetToPage())\n print_('GetMinPage:', data.GetMinPage())\n print_('GetMaxPage:', data.GetMaxPage())\n print_('GetNoCopies:', data.GetNoCopies())\n print_('GetAllPages:', data.GetAllPages())\n print_('GetSelection:', data.GetSelection())\n print_('GetCollate:', data.GetCollate())\n print_('GetPrintToFile:', data.GetPrintToFile())\n self.pdata = wx.PrintData(data.GetPrintData())\n print_()\n print_('GetPrinterName:', self.pdata.GetPrinterName())\n dlg.Destroy()\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass TextDocPrintout(wx.Printout):\n <mask token>\n <mask token>\n <mask token>\n\n def GetPageInfo(self):\n return 1, self.numPages, 1, self.numPages\n\n def CalculateScale(self, dc):\n ppiPrinterX, ppiPrinterY = self.GetPPIPrinter()\n ppiScreenX, ppiScreenY = self.GetPPIScreen()\n logScale = float(ppiPrinterX) / float(ppiScreenX)\n pw, ph = self.GetPageSizePixels()\n dw, dh = dc.GetSize()\n scale = logScale * float(dw) / float(pw)\n dc.SetUserScale(scale, scale)\n self.logUnitsMM = float(ppiPrinterX) / (logScale * 25.4)\n\n def CalculateLayout(self, dc):\n topLeft, bottomRight = self.margins\n dw, dh = dc.GetSize()\n self.x1 = topLeft.x * self.logUnitsMM\n self.y1 = topLeft.y * self.logUnitsMM\n self.x2 = dc.DeviceToLogicalXRel(dw) - bottomRight.x * self.logUnitsMM\n self.y2 = dc.DeviceToLogicalYRel(dh) - bottomRight.y * self.logUnitsMM\n self.pageHeight = self.y2 - self.y1 - 2 * self.logUnitsMM\n font = wx.Font(FONTSIZE, wx.FONTFAMILY_TELETYPE, wx.\n FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)\n dc.SetFont(font)\n self.lineHeight = dc.GetCharHeight()\n self.linesPerPage = int(self.pageHeight / self.lineHeight)\n <mask token>\n\n def OnPrintPage(self, page):\n dc = self.GetDC()\n self.CalculateScale(dc)\n self.CalculateLayout(dc)\n dc.SetPen(wx.Pen('black', 0))\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n r = wx.Rect(wx.Point(self.x1, self.y1), wx.Point(self.x2, self.y2))\n dc.DrawRectangle(r)\n dc.SetClippingRegion(r)\n line = (page - 1) * self.linesPerPage\n x = self.x1 + self.logUnitsMM\n y = self.y1 + self.logUnitsMM\n while line < page * self.linesPerPage:\n dc.DrawText(self.lines[line], x, y)\n y += self.lineHeight\n line += 1\n if line >= len(self.lines):\n break\n return True\n\n\nclass PrintFrameworkSample(wx.Frame):\n\n def __init__(self):\n wx.Frame.__init__(self, None, size=(640, 480), title=\n 'Print Framework Sample')\n self.CreateStatusBar()\n self.tc = wx.TextCtrl(self, -1, '', style=wx.TE_MULTILINE | wx.\n TE_DONTWRAP)\n self.tc.SetFont(wx.Font(FONTSIZE, wx.FONTFAMILY_TELETYPE, wx.\n FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL))\n filename = os.path.join(os.path.dirname(__file__), 'sample-text.txt')\n with open(filename) as fid:\n self.tc.SetValue(fid.read())\n self.tc.Bind(wx.EVT_SET_FOCUS, self.OnClearSelection)\n wx.CallAfter(self.tc.SetInsertionPoint, 0)\n menu = wx.Menu()\n item = menu.Append(-1, 'Page Setup...\\tF5',\n 'Set up page margins and etc.')\n self.Bind(wx.EVT_MENU, self.OnPageSetup, item)\n item = menu.Append(-1, 'Print Preview...\\tF6',\n 'View the printout on-screen')\n self.Bind(wx.EVT_MENU, self.OnPrintPreview, item)\n item = menu.Append(-1, 'Print...\\tF7', 'Print the document')\n self.Bind(wx.EVT_MENU, self.OnPrint, item)\n menu.AppendSeparator()\n item = menu.Append(wx.ID_ABOUT, 'About', 'About this application')\n self.Bind(wx.EVT_MENU, self.OnAbout, item)\n item = menu.Append(wx.ID_EXIT, 'E&xit\\tCtrl-Q',\n 'Close this application')\n self.Bind(wx.EVT_MENU, self.OnExit, item)\n menubar = wx.MenuBar()\n menubar.Append(menu, '&File')\n self.SetMenuBar(menubar)\n self.pdata = wx.PrintData()\n self.pdata.SetPaperId(wx.PAPER_LETTER)\n self.pdata.SetOrientation(wx.PORTRAIT)\n self.margins = wx.Point(15, 15), wx.Point(15, 15)\n\n def OnExit(self, evt):\n self.Close()\n\n def OnAbout(self, evt):\n wx.MessageBox(\n 'Print framework sample application\\n\\nUsing wxPython %s' % wx.\n version(), 'About')\n\n def OnClearSelection(self, evt):\n evt.Skip()\n wx.CallAfter(self.tc.SetInsertionPoint, self.tc.GetInsertionPoint())\n\n def OnPageSetup(self, evt):\n data = wx.PageSetupDialogData()\n data.SetPrintData(self.pdata)\n data.SetDefaultMinMargins(True)\n data.SetMarginTopLeft(self.margins[0])\n data.SetMarginBottomRight(self.margins[1])\n dlg = wx.PageSetupDialog(self, data)\n if dlg.ShowModal() == wx.ID_OK:\n data = dlg.GetPageSetupData()\n self.pdata = wx.PrintData(data.GetPrintData())\n self.pdata.SetPaperId(data.GetPaperId())\n self.margins = data.GetMarginTopLeft(), data.GetMarginBottomRight()\n dlg.Destroy()\n\n def OnPrintPreview(self, evt):\n data = wx.PrintDialogData(self.pdata)\n text = self.tc.GetValue()\n printout1 = TextDocPrintout(text, 'title', self.margins)\n printout2 = TextDocPrintout(text, 'title', self.margins)\n preview = wx.PrintPreview(printout1, printout2, data)\n if not preview:\n wx.MessageBox('Unable to create PrintPreview!', 'Error')\n else:\n frame = wx.PreviewFrame(preview, self, 'Print Preview', pos=\n self.GetPosition(), size=self.GetSize())\n frame.Initialize()\n frame.Show()\n\n def OnPrint(self, evt):\n data = wx.PrintDialogData(self.pdata)\n printer = wx.Printer(data)\n text = self.tc.GetValue()\n printout = TextDocPrintout(text, 'title', self.margins)\n useSetupDialog = True\n if not printer.Print(self, printout, useSetupDialog\n ) and printer.GetLastError() == wx.PRINTER_ERROR:\n wx.MessageBox(\n \"\"\"There was a problem printing.\nPerhaps your current printer is not set correctly?\"\"\"\n , 'Printing Error', wx.OK)\n else:\n data = printer.GetPrintDialogData()\n self.pdata = wx.PrintData(data.GetPrintData())\n printout.Destroy()\n\n def OnPrintTest(self, evt):\n data = wx.PrintDialogData(self.pdata)\n dlg = wx.PrintDialog(self, data)\n if dlg.ShowModal() == wx.ID_OK:\n data = dlg.GetPrintDialogData()\n print_()\n print_('GetFromPage:', data.GetFromPage())\n print_('GetToPage:', data.GetToPage())\n print_('GetMinPage:', data.GetMinPage())\n print_('GetMaxPage:', data.GetMaxPage())\n print_('GetNoCopies:', data.GetNoCopies())\n print_('GetAllPages:', data.GetAllPages())\n print_('GetSelection:', data.GetSelection())\n print_('GetCollate:', data.GetCollate())\n print_('GetPrintToFile:', data.GetPrintToFile())\n self.pdata = wx.PrintData(data.GetPrintData())\n print_()\n print_('GetPrinterName:', self.pdata.GetPrinterName())\n dlg.Destroy()\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass TextDocPrintout(wx.Printout):\n <mask token>\n\n def __init__(self, text, title, margins):\n wx.Printout.__init__(self, title)\n self.lines = text.split('\\n')\n self.margins = margins\n\n def HasPage(self, page):\n return page <= self.numPages\n\n def GetPageInfo(self):\n return 1, self.numPages, 1, self.numPages\n\n def CalculateScale(self, dc):\n ppiPrinterX, ppiPrinterY = self.GetPPIPrinter()\n ppiScreenX, ppiScreenY = self.GetPPIScreen()\n logScale = float(ppiPrinterX) / float(ppiScreenX)\n pw, ph = self.GetPageSizePixels()\n dw, dh = dc.GetSize()\n scale = logScale * float(dw) / float(pw)\n dc.SetUserScale(scale, scale)\n self.logUnitsMM = float(ppiPrinterX) / (logScale * 25.4)\n\n def CalculateLayout(self, dc):\n topLeft, bottomRight = self.margins\n dw, dh = dc.GetSize()\n self.x1 = topLeft.x * self.logUnitsMM\n self.y1 = topLeft.y * self.logUnitsMM\n self.x2 = dc.DeviceToLogicalXRel(dw) - bottomRight.x * self.logUnitsMM\n self.y2 = dc.DeviceToLogicalYRel(dh) - bottomRight.y * self.logUnitsMM\n self.pageHeight = self.y2 - self.y1 - 2 * self.logUnitsMM\n font = wx.Font(FONTSIZE, wx.FONTFAMILY_TELETYPE, wx.\n FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)\n dc.SetFont(font)\n self.lineHeight = dc.GetCharHeight()\n self.linesPerPage = int(self.pageHeight / self.lineHeight)\n <mask token>\n\n def OnPrintPage(self, page):\n dc = self.GetDC()\n self.CalculateScale(dc)\n self.CalculateLayout(dc)\n dc.SetPen(wx.Pen('black', 0))\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n r = wx.Rect(wx.Point(self.x1, self.y1), wx.Point(self.x2, self.y2))\n dc.DrawRectangle(r)\n dc.SetClippingRegion(r)\n line = (page - 1) * self.linesPerPage\n x = self.x1 + self.logUnitsMM\n y = self.y1 + self.logUnitsMM\n while line < page * self.linesPerPage:\n dc.DrawText(self.lines[line], x, y)\n y += self.lineHeight\n line += 1\n if line >= len(self.lines):\n break\n return True\n\n\nclass PrintFrameworkSample(wx.Frame):\n\n def __init__(self):\n wx.Frame.__init__(self, None, size=(640, 480), title=\n 'Print Framework Sample')\n self.CreateStatusBar()\n self.tc = wx.TextCtrl(self, -1, '', style=wx.TE_MULTILINE | wx.\n TE_DONTWRAP)\n self.tc.SetFont(wx.Font(FONTSIZE, wx.FONTFAMILY_TELETYPE, wx.\n FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL))\n filename = os.path.join(os.path.dirname(__file__), 'sample-text.txt')\n with open(filename) as fid:\n self.tc.SetValue(fid.read())\n self.tc.Bind(wx.EVT_SET_FOCUS, self.OnClearSelection)\n wx.CallAfter(self.tc.SetInsertionPoint, 0)\n menu = wx.Menu()\n item = menu.Append(-1, 'Page Setup...\\tF5',\n 'Set up page margins and etc.')\n self.Bind(wx.EVT_MENU, self.OnPageSetup, item)\n item = menu.Append(-1, 'Print Preview...\\tF6',\n 'View the printout on-screen')\n self.Bind(wx.EVT_MENU, self.OnPrintPreview, item)\n item = menu.Append(-1, 'Print...\\tF7', 'Print the document')\n self.Bind(wx.EVT_MENU, self.OnPrint, item)\n menu.AppendSeparator()\n item = menu.Append(wx.ID_ABOUT, 'About', 'About this application')\n self.Bind(wx.EVT_MENU, self.OnAbout, item)\n item = menu.Append(wx.ID_EXIT, 'E&xit\\tCtrl-Q',\n 'Close this application')\n self.Bind(wx.EVT_MENU, self.OnExit, item)\n menubar = wx.MenuBar()\n menubar.Append(menu, '&File')\n self.SetMenuBar(menubar)\n self.pdata = wx.PrintData()\n self.pdata.SetPaperId(wx.PAPER_LETTER)\n self.pdata.SetOrientation(wx.PORTRAIT)\n self.margins = wx.Point(15, 15), wx.Point(15, 15)\n\n def OnExit(self, evt):\n self.Close()\n\n def OnAbout(self, evt):\n wx.MessageBox(\n 'Print framework sample application\\n\\nUsing wxPython %s' % wx.\n version(), 'About')\n\n def OnClearSelection(self, evt):\n evt.Skip()\n wx.CallAfter(self.tc.SetInsertionPoint, self.tc.GetInsertionPoint())\n\n def OnPageSetup(self, evt):\n data = wx.PageSetupDialogData()\n data.SetPrintData(self.pdata)\n data.SetDefaultMinMargins(True)\n data.SetMarginTopLeft(self.margins[0])\n data.SetMarginBottomRight(self.margins[1])\n dlg = wx.PageSetupDialog(self, data)\n if dlg.ShowModal() == wx.ID_OK:\n data = dlg.GetPageSetupData()\n self.pdata = wx.PrintData(data.GetPrintData())\n self.pdata.SetPaperId(data.GetPaperId())\n self.margins = data.GetMarginTopLeft(), data.GetMarginBottomRight()\n dlg.Destroy()\n\n def OnPrintPreview(self, evt):\n data = wx.PrintDialogData(self.pdata)\n text = self.tc.GetValue()\n printout1 = TextDocPrintout(text, 'title', self.margins)\n printout2 = TextDocPrintout(text, 'title', self.margins)\n preview = wx.PrintPreview(printout1, printout2, data)\n if not preview:\n wx.MessageBox('Unable to create PrintPreview!', 'Error')\n else:\n frame = wx.PreviewFrame(preview, self, 'Print Preview', pos=\n self.GetPosition(), size=self.GetSize())\n frame.Initialize()\n frame.Show()\n\n def OnPrint(self, evt):\n data = wx.PrintDialogData(self.pdata)\n printer = wx.Printer(data)\n text = self.tc.GetValue()\n printout = TextDocPrintout(text, 'title', self.margins)\n useSetupDialog = True\n if not printer.Print(self, printout, useSetupDialog\n ) and printer.GetLastError() == wx.PRINTER_ERROR:\n wx.MessageBox(\n \"\"\"There was a problem printing.\nPerhaps your current printer is not set correctly?\"\"\"\n , 'Printing Error', wx.OK)\n else:\n data = printer.GetPrintDialogData()\n self.pdata = wx.PrintData(data.GetPrintData())\n printout.Destroy()\n\n def OnPrintTest(self, evt):\n data = wx.PrintDialogData(self.pdata)\n dlg = wx.PrintDialog(self, data)\n if dlg.ShowModal() == wx.ID_OK:\n data = dlg.GetPrintDialogData()\n print_()\n print_('GetFromPage:', data.GetFromPage())\n print_('GetToPage:', data.GetToPage())\n print_('GetMinPage:', data.GetMinPage())\n print_('GetMaxPage:', data.GetMaxPage())\n print_('GetNoCopies:', data.GetNoCopies())\n print_('GetAllPages:', data.GetAllPages())\n print_('GetSelection:', data.GetSelection())\n print_('GetCollate:', data.GetCollate())\n print_('GetPrintToFile:', data.GetPrintToFile())\n self.pdata = wx.PrintData(data.GetPrintData())\n print_()\n print_('GetPrinterName:', self.pdata.GetPrinterName())\n dlg.Destroy()\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\nclass TextDocPrintout(wx.Printout):\n \"\"\"\n A printout class that is able to print simple text documents.\n Does not handle page numbers or titles, and it assumes that no\n lines are longer than what will fit within the page width. Those\n features are left as an exercise for the reader. ;-)\n \"\"\"\n\n def __init__(self, text, title, margins):\n wx.Printout.__init__(self, title)\n self.lines = text.split('\\n')\n self.margins = margins\n\n def HasPage(self, page):\n return page <= self.numPages\n\n def GetPageInfo(self):\n return 1, self.numPages, 1, self.numPages\n\n def CalculateScale(self, dc):\n ppiPrinterX, ppiPrinterY = self.GetPPIPrinter()\n ppiScreenX, ppiScreenY = self.GetPPIScreen()\n logScale = float(ppiPrinterX) / float(ppiScreenX)\n pw, ph = self.GetPageSizePixels()\n dw, dh = dc.GetSize()\n scale = logScale * float(dw) / float(pw)\n dc.SetUserScale(scale, scale)\n self.logUnitsMM = float(ppiPrinterX) / (logScale * 25.4)\n\n def CalculateLayout(self, dc):\n topLeft, bottomRight = self.margins\n dw, dh = dc.GetSize()\n self.x1 = topLeft.x * self.logUnitsMM\n self.y1 = topLeft.y * self.logUnitsMM\n self.x2 = dc.DeviceToLogicalXRel(dw) - bottomRight.x * self.logUnitsMM\n self.y2 = dc.DeviceToLogicalYRel(dh) - bottomRight.y * self.logUnitsMM\n self.pageHeight = self.y2 - self.y1 - 2 * self.logUnitsMM\n font = wx.Font(FONTSIZE, wx.FONTFAMILY_TELETYPE, wx.\n FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)\n dc.SetFont(font)\n self.lineHeight = dc.GetCharHeight()\n self.linesPerPage = int(self.pageHeight / self.lineHeight)\n\n def OnPreparePrinting(self):\n dc = self.GetDC()\n self.CalculateScale(dc)\n self.CalculateLayout(dc)\n self.numPages = len(self.lines) / self.linesPerPage\n if len(self.lines) % self.linesPerPage != 0:\n self.numPages += 1\n\n def OnPrintPage(self, page):\n dc = self.GetDC()\n self.CalculateScale(dc)\n self.CalculateLayout(dc)\n dc.SetPen(wx.Pen('black', 0))\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n r = wx.Rect(wx.Point(self.x1, self.y1), wx.Point(self.x2, self.y2))\n dc.DrawRectangle(r)\n dc.SetClippingRegion(r)\n line = (page - 1) * self.linesPerPage\n x = self.x1 + self.logUnitsMM\n y = self.y1 + self.logUnitsMM\n while line < page * self.linesPerPage:\n dc.DrawText(self.lines[line], x, y)\n y += self.lineHeight\n line += 1\n if line >= len(self.lines):\n break\n return True\n\n\nclass PrintFrameworkSample(wx.Frame):\n\n def __init__(self):\n wx.Frame.__init__(self, None, size=(640, 480), title=\n 'Print Framework Sample')\n self.CreateStatusBar()\n self.tc = wx.TextCtrl(self, -1, '', style=wx.TE_MULTILINE | wx.\n TE_DONTWRAP)\n self.tc.SetFont(wx.Font(FONTSIZE, wx.FONTFAMILY_TELETYPE, wx.\n FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL))\n filename = os.path.join(os.path.dirname(__file__), 'sample-text.txt')\n with open(filename) as fid:\n self.tc.SetValue(fid.read())\n self.tc.Bind(wx.EVT_SET_FOCUS, self.OnClearSelection)\n wx.CallAfter(self.tc.SetInsertionPoint, 0)\n menu = wx.Menu()\n item = menu.Append(-1, 'Page Setup...\\tF5',\n 'Set up page margins and etc.')\n self.Bind(wx.EVT_MENU, self.OnPageSetup, item)\n item = menu.Append(-1, 'Print Preview...\\tF6',\n 'View the printout on-screen')\n self.Bind(wx.EVT_MENU, self.OnPrintPreview, item)\n item = menu.Append(-1, 'Print...\\tF7', 'Print the document')\n self.Bind(wx.EVT_MENU, self.OnPrint, item)\n menu.AppendSeparator()\n item = menu.Append(wx.ID_ABOUT, 'About', 'About this application')\n self.Bind(wx.EVT_MENU, self.OnAbout, item)\n item = menu.Append(wx.ID_EXIT, 'E&xit\\tCtrl-Q',\n 'Close this application')\n self.Bind(wx.EVT_MENU, self.OnExit, item)\n menubar = wx.MenuBar()\n menubar.Append(menu, '&File')\n self.SetMenuBar(menubar)\n self.pdata = wx.PrintData()\n self.pdata.SetPaperId(wx.PAPER_LETTER)\n self.pdata.SetOrientation(wx.PORTRAIT)\n self.margins = wx.Point(15, 15), wx.Point(15, 15)\n\n def OnExit(self, evt):\n self.Close()\n\n def OnAbout(self, evt):\n wx.MessageBox(\n 'Print framework sample application\\n\\nUsing wxPython %s' % wx.\n version(), 'About')\n\n def OnClearSelection(self, evt):\n evt.Skip()\n wx.CallAfter(self.tc.SetInsertionPoint, self.tc.GetInsertionPoint())\n\n def OnPageSetup(self, evt):\n data = wx.PageSetupDialogData()\n data.SetPrintData(self.pdata)\n data.SetDefaultMinMargins(True)\n data.SetMarginTopLeft(self.margins[0])\n data.SetMarginBottomRight(self.margins[1])\n dlg = wx.PageSetupDialog(self, data)\n if dlg.ShowModal() == wx.ID_OK:\n data = dlg.GetPageSetupData()\n self.pdata = wx.PrintData(data.GetPrintData())\n self.pdata.SetPaperId(data.GetPaperId())\n self.margins = data.GetMarginTopLeft(), data.GetMarginBottomRight()\n dlg.Destroy()\n\n def OnPrintPreview(self, evt):\n data = wx.PrintDialogData(self.pdata)\n text = self.tc.GetValue()\n printout1 = TextDocPrintout(text, 'title', self.margins)\n printout2 = TextDocPrintout(text, 'title', self.margins)\n preview = wx.PrintPreview(printout1, printout2, data)\n if not preview:\n wx.MessageBox('Unable to create PrintPreview!', 'Error')\n else:\n frame = wx.PreviewFrame(preview, self, 'Print Preview', pos=\n self.GetPosition(), size=self.GetSize())\n frame.Initialize()\n frame.Show()\n\n def OnPrint(self, evt):\n data = wx.PrintDialogData(self.pdata)\n printer = wx.Printer(data)\n text = self.tc.GetValue()\n printout = TextDocPrintout(text, 'title', self.margins)\n useSetupDialog = True\n if not printer.Print(self, printout, useSetupDialog\n ) and printer.GetLastError() == wx.PRINTER_ERROR:\n wx.MessageBox(\n \"\"\"There was a problem printing.\nPerhaps your current printer is not set correctly?\"\"\"\n , 'Printing Error', wx.OK)\n else:\n data = printer.GetPrintDialogData()\n self.pdata = wx.PrintData(data.GetPrintData())\n printout.Destroy()\n\n def OnPrintTest(self, evt):\n data = wx.PrintDialogData(self.pdata)\n dlg = wx.PrintDialog(self, data)\n if dlg.ShowModal() == wx.ID_OK:\n data = dlg.GetPrintDialogData()\n print_()\n print_('GetFromPage:', data.GetFromPage())\n print_('GetToPage:', data.GetToPage())\n print_('GetMinPage:', data.GetMinPage())\n print_('GetMaxPage:', data.GetMaxPage())\n print_('GetNoCopies:', data.GetNoCopies())\n print_('GetAllPages:', data.GetAllPages())\n print_('GetSelection:', data.GetSelection())\n print_('GetCollate:', data.GetCollate())\n print_('GetPrintToFile:', data.GetPrintToFile())\n self.pdata = wx.PrintData(data.GetPrintData())\n print_()\n print_('GetPrinterName:', self.pdata.GetPrinterName())\n dlg.Destroy()\n\n\n<mask token>\nfrm.Show()\napp.MainLoop()\n", "step-5": "import wx\nfrom six import print_\nimport os\n\nFONTSIZE = 10\n\nclass TextDocPrintout(wx.Printout):\n \"\"\"\n A printout class that is able to print simple text documents.\n Does not handle page numbers or titles, and it assumes that no\n lines are longer than what will fit within the page width. Those\n features are left as an exercise for the reader. ;-)\n \"\"\"\n def __init__(self, text, title, margins):\n wx.Printout.__init__(self, title)\n self.lines = text.split('\\n')\n self.margins = margins\n\n\n def HasPage(self, page):\n return page <= self.numPages\n\n def GetPageInfo(self):\n return (1, self.numPages, 1, self.numPages)\n\n\n def CalculateScale(self, dc):\n # Scale the DC such that the printout is roughly the same as\n # the screen scaling.\n ppiPrinterX, ppiPrinterY = self.GetPPIPrinter()\n ppiScreenX, ppiScreenY = self.GetPPIScreen()\n logScale = float(ppiPrinterX)/float(ppiScreenX)\n\n # Now adjust if the real page size is reduced (such as when\n # drawing on a scaled wx.MemoryDC in the Print Preview.) If\n # page width == DC width then nothing changes, otherwise we\n # scale down for the DC.\n pw, ph = self.GetPageSizePixels()\n dw, dh = dc.GetSize()\n scale = logScale * float(dw)/float(pw)\n\n # Set the DC's scale.\n dc.SetUserScale(scale, scale)\n\n # Find the logical units per millimeter (for calculating the\n # margins)\n self.logUnitsMM = float(ppiPrinterX)/(logScale*25.4)\n\n\n def CalculateLayout(self, dc):\n # Determine the position of the margins and the\n # page/line height\n topLeft, bottomRight = self.margins\n dw, dh = dc.GetSize()\n self.x1 = topLeft.x * self.logUnitsMM\n self.y1 = topLeft.y * self.logUnitsMM\n self.x2 = dc.DeviceToLogicalXRel(dw) - bottomRight.x * self.logUnitsMM\n self.y2 = dc.DeviceToLogicalYRel(dh) - bottomRight.y * self.logUnitsMM\n\n # use a 1mm buffer around the inside of the box, and a few\n # pixels between each line\n self.pageHeight = self.y2 - self.y1 - 2*self.logUnitsMM\n font = wx.Font(FONTSIZE, wx.FONTFAMILY_TELETYPE,\n wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)\n dc.SetFont(font)\n self.lineHeight = dc.GetCharHeight()\n self.linesPerPage = int(self.pageHeight/self.lineHeight)\n\n\n def OnPreparePrinting(self):\n # calculate the number of pages\n dc = self.GetDC()\n self.CalculateScale(dc)\n self.CalculateLayout(dc)\n self.numPages = len(self.lines) / self.linesPerPage\n if len(self.lines) % self.linesPerPage != 0:\n self.numPages += 1\n\n\n def OnPrintPage(self, page):\n dc = self.GetDC()\n self.CalculateScale(dc)\n self.CalculateLayout(dc)\n\n # draw a page outline at the margin points\n dc.SetPen(wx.Pen(\"black\", 0))\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n r = wx.Rect(wx.Point(self.x1, self.y1), wx.Point(self.x2, self.y2))\n dc.DrawRectangle(r)\n dc.SetClippingRegion(r)\n\n # Draw the text lines for this page\n line = (page-1) * self.linesPerPage\n x = self.x1 + self.logUnitsMM\n y = self.y1 + self.logUnitsMM\n while line < (page * self.linesPerPage):\n dc.DrawText(self.lines[line], x, y)\n y += self.lineHeight\n line += 1\n if line >= len(self.lines):\n break\n return True\n\n\n\nclass PrintFrameworkSample(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None, size=(640, 480),\n title=\"Print Framework Sample\")\n self.CreateStatusBar()\n\n # A text widget to display the doc and let it be edited\n self.tc = wx.TextCtrl(self, -1, \"\",\n style=wx.TE_MULTILINE|wx.TE_DONTWRAP)\n self.tc.SetFont(wx.Font(FONTSIZE, wx.FONTFAMILY_TELETYPE,\n wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL))\n filename = os.path.join(os.path.dirname(__file__), \"sample-text.txt\")\n with open(filename) as fid:\n self.tc.SetValue(fid.read())\n self.tc.Bind(wx.EVT_SET_FOCUS, self.OnClearSelection)\n wx.CallAfter(self.tc.SetInsertionPoint, 0)\n\n # Create the menu and menubar\n menu = wx.Menu()\n item = menu.Append(-1, \"Page Setup...\\tF5\",\n \"Set up page margins and etc.\")\n self.Bind(wx.EVT_MENU, self.OnPageSetup, item)\n item = menu.Append(-1, \"Print Preview...\\tF6\",\n \"View the printout on-screen\")\n self.Bind(wx.EVT_MENU, self.OnPrintPreview, item)\n item = menu.Append(-1, \"Print...\\tF7\", \"Print the document\")\n self.Bind(wx.EVT_MENU, self.OnPrint, item)\n menu.AppendSeparator()\n## item = menu.Append(-1, \"Test other stuff...\\tF9\", \"\")\n## self.Bind(wx.EVT_MENU, self.OnPrintTest, item)\n## menu.AppendSeparator()\n\n item = menu.Append(wx.ID_ABOUT, \"About\", \"About this application\")\n self.Bind(wx.EVT_MENU, self.OnAbout, item)\n item = menu.Append(wx.ID_EXIT, \"E&xit\\tCtrl-Q\", \"Close this application\")\n self.Bind(wx.EVT_MENU, self.OnExit, item)\n\n menubar = wx.MenuBar()\n menubar.Append(menu, \"&File\")\n self.SetMenuBar(menubar)\n\n # initialize the print data and set some default values\n self.pdata = wx.PrintData()\n self.pdata.SetPaperId(wx.PAPER_LETTER)\n self.pdata.SetOrientation(wx.PORTRAIT)\n self.margins = (wx.Point(15,15), wx.Point(15,15))\n\n\n def OnExit(self, evt):\n self.Close()\n\n\n def OnAbout(self, evt):\n wx.MessageBox('Print framework sample application\\n'\n '\\n'\n 'Using wxPython %s' % wx.version(),\n 'About')\n\n def OnClearSelection(self, evt):\n evt.Skip()\n wx.CallAfter(self.tc.SetInsertionPoint,\n self.tc.GetInsertionPoint())\n\n\n def OnPageSetup(self, evt):\n data = wx.PageSetupDialogData()\n data.SetPrintData(self.pdata)\n\n data.SetDefaultMinMargins(True)\n data.SetMarginTopLeft(self.margins[0])\n data.SetMarginBottomRight(self.margins[1])\n\n dlg = wx.PageSetupDialog(self, data)\n if dlg.ShowModal() == wx.ID_OK:\n data = dlg.GetPageSetupData()\n self.pdata = wx.PrintData(data.GetPrintData()) # force a copy\n self.pdata.SetPaperId(data.GetPaperId())\n #print_(\"paperID %r, paperSize %r\" % (self.pdata.GetPaperId(), self.pdata.GetPaperSize()))\n self.margins = (data.GetMarginTopLeft(),\n data.GetMarginBottomRight())\n dlg.Destroy()\n\n\n def OnPrintPreview(self, evt):\n data = wx.PrintDialogData(self.pdata)\n text = self.tc.GetValue()\n printout1 = TextDocPrintout(text, \"title\", self.margins)\n printout2 = TextDocPrintout(text, \"title\", self.margins)\n preview = wx.PrintPreview(printout1, printout2, data)\n if not preview:\n wx.MessageBox(\"Unable to create PrintPreview!\", \"Error\")\n else:\n # create the preview frame such that it overlays the app frame\n frame = wx.PreviewFrame(preview, self, \"Print Preview\",\n pos=self.GetPosition(),\n size=self.GetSize())\n frame.Initialize()\n frame.Show()\n\n\n def OnPrint(self, evt):\n data = wx.PrintDialogData(self.pdata)\n printer = wx.Printer(data)\n text = self.tc.GetValue()\n printout = TextDocPrintout(text, \"title\", self.margins)\n useSetupDialog = True\n if not printer.Print(self, printout, useSetupDialog) \\\n and printer.GetLastError() == wx.PRINTER_ERROR:\n wx.MessageBox(\n \"There was a problem printing.\\n\"\n \"Perhaps your current printer is not set correctly?\",\n \"Printing Error\", wx.OK)\n else:\n data = printer.GetPrintDialogData()\n self.pdata = wx.PrintData(data.GetPrintData()) # force a copy\n printout.Destroy()\n\n\n def OnPrintTest(self, evt):\n data = wx.PrintDialogData(self.pdata)\n dlg = wx.PrintDialog(self, data)\n if dlg.ShowModal() == wx.ID_OK:\n data = dlg.GetPrintDialogData()\n print_()\n print_(\"GetFromPage:\", data.GetFromPage())\n print_(\"GetToPage:\", data.GetToPage())\n print_(\"GetMinPage:\", data.GetMinPage())\n print_(\"GetMaxPage:\", data.GetMaxPage())\n print_(\"GetNoCopies:\", data.GetNoCopies())\n print_(\"GetAllPages:\", data.GetAllPages())\n print_(\"GetSelection:\", data.GetSelection())\n print_(\"GetCollate:\", data.GetCollate())\n print_(\"GetPrintToFile:\", data.GetPrintToFile())\n\n self.pdata = wx.PrintData(data.GetPrintData())\n print_()\n print_(\"GetPrinterName:\", self.pdata.GetPrinterName())\n\n dlg.Destroy()\n\n\napp = wx.App()\nfrm = PrintFrameworkSample()\nfrm.Show()\napp.MainLoop()\n", "step-ids": [ 10, 14, 16, 19, 22 ] }
[ 10, 14, 16, 19, 22 ]
from flask import ( Flask, render_template, request ) import requests app = Flask(__name__) base_url = "https://api.github.com/users/" @app.route("/", methods = ["GET", "POST"]) def index(): if request.method == "POST": githubName = request.form.get("githubname") responseUser = requests.get("{}{}".format(base_url, githubName)) responseRepos = requests.get("{}{}/repos".format(base_url, githubName)) userInfo = responseUser.json() userRepos = responseRepos.json() if "message" in userInfo: return render_template("index.html", error = "Kullanıcı Bulunamadı") return render_template("index.html", profile = userInfo , repos = userRepos) return render_template("index.html") if __name__ == "__main__": app.run(debug = True)
normal
{ "blob_id": "62094d036596f39e7cf936fe7a91e67d53ee055e", "index": 9557, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\[email protected]('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n githubName = request.form.get('githubname')\n responseUser = requests.get('{}{}'.format(base_url, githubName))\n responseRepos = requests.get('{}{}/repos'.format(base_url, githubName))\n userInfo = responseUser.json()\n userRepos = responseRepos.json()\n if 'message' in userInfo:\n return render_template('index.html', error='Kullanıcı Bulunamadı')\n return render_template('index.html', profile=userInfo, repos=userRepos)\n return render_template('index.html')\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n", "step-3": "<mask token>\napp = Flask(__name__)\nbase_url = 'https://api.github.com/users/'\n\n\[email protected]('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n githubName = request.form.get('githubname')\n responseUser = requests.get('{}{}'.format(base_url, githubName))\n responseRepos = requests.get('{}{}/repos'.format(base_url, githubName))\n userInfo = responseUser.json()\n userRepos = responseRepos.json()\n if 'message' in userInfo:\n return render_template('index.html', error='Kullanıcı Bulunamadı')\n return render_template('index.html', profile=userInfo, repos=userRepos)\n return render_template('index.html')\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n", "step-4": "from flask import Flask, render_template, request\nimport requests\napp = Flask(__name__)\nbase_url = 'https://api.github.com/users/'\n\n\[email protected]('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n githubName = request.form.get('githubname')\n responseUser = requests.get('{}{}'.format(base_url, githubName))\n responseRepos = requests.get('{}{}/repos'.format(base_url, githubName))\n userInfo = responseUser.json()\n userRepos = responseRepos.json()\n if 'message' in userInfo:\n return render_template('index.html', error='Kullanıcı Bulunamadı')\n return render_template('index.html', profile=userInfo, repos=userRepos)\n return render_template('index.html')\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n", "step-5": "from flask import (\n Flask,\n render_template,\n request\n)\nimport requests\n\napp = Flask(__name__)\nbase_url = \"https://api.github.com/users/\"\n\[email protected](\"/\", methods = [\"GET\", \"POST\"])\ndef index():\n if request.method == \"POST\":\n githubName = request.form.get(\"githubname\")\n responseUser = requests.get(\"{}{}\".format(base_url, githubName))\n responseRepos = requests.get(\"{}{}/repos\".format(base_url, githubName))\n\n userInfo = responseUser.json()\n userRepos = responseRepos.json()\n\n if \"message\" in userInfo:\n return render_template(\"index.html\", error = \"Kullanıcı Bulunamadı\")\n return render_template(\"index.html\", profile = userInfo , repos = userRepos)\n return render_template(\"index.html\")\n\nif __name__ == \"__main__\":\n app.run(debug = True)", "step-ids": [ 0, 2, 3, 4, 5 ] }
[ 0, 2, 3, 4, 5 ]
<|reserved_special_token_0|> class TestAccountsViews(TestCase): <|reserved_special_token_0|> <|reserved_special_token_0|> def test_logout_view(self): response = self.client.get(reverse('accounts:logout')) self.assertEqual(response.status_code, 302) <|reserved_special_token_0|> def test_register_view(self): url = reverse('accounts:register') response = self.client.get(url) self.assertTemplateUsed(response, 'accounts/register.html') self.assertEqual(response.status_code, 200) def test_userfollow_view(self): url = reverse('accounts:follow', kwargs={'user_slug': self.user.slug}) response = self.client.get(url) self.assertEqual(response.status_code, 302) self.client.login(email=self.email, password=self.password) self.assertEqual(response.status_code, 302) def test_follow_manager_view(self): url = reverse('accounts:follow_manage', kwargs={'user_slug': self. user.slug}) response = self.client.get(url) self.assertEqual(response.status_code, 302) self.client.login(email=self.email, password=self.password) self.assertEqual(response.status_code, 302) def test_profile_update_view(self): url = reverse('accounts:profile_update', kwargs={'pk': self.user.id}) response = self.client.get(url) self.assertEqual(response.status_code, 302) def test_followers_view(self): url = reverse('accounts:followers', kwargs={'user_slug': self.user. slug}) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'accounts/followers.html') def test_following_view(self): url = reverse('accounts:following', kwargs={'user_slug': self.user. slug}) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'accounts/following.html') def test_user_like_view(self): url = reverse('accounts:user-like', kwargs={'slug': self.user.slug, 'pk': self.tweet.id}) response = self.client.get(url) self.assertEqual(response.status_code, 403) self.client.login(email=self.email, password=self.password) response = self.client.get(url) self.assertEqual(response.status_code, 200) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class TestAccountsViews(TestCase): <|reserved_special_token_0|> <|reserved_special_token_0|> def test_logout_view(self): response = self.client.get(reverse('accounts:logout')) self.assertEqual(response.status_code, 302) <|reserved_special_token_0|> def test_register_view(self): url = reverse('accounts:register') response = self.client.get(url) self.assertTemplateUsed(response, 'accounts/register.html') self.assertEqual(response.status_code, 200) def test_userfollow_view(self): url = reverse('accounts:follow', kwargs={'user_slug': self.user.slug}) response = self.client.get(url) self.assertEqual(response.status_code, 302) self.client.login(email=self.email, password=self.password) self.assertEqual(response.status_code, 302) def test_follow_manager_view(self): url = reverse('accounts:follow_manage', kwargs={'user_slug': self. user.slug}) response = self.client.get(url) self.assertEqual(response.status_code, 302) self.client.login(email=self.email, password=self.password) self.assertEqual(response.status_code, 302) def test_profile_update_view(self): url = reverse('accounts:profile_update', kwargs={'pk': self.user.id}) response = self.client.get(url) self.assertEqual(response.status_code, 302) def test_followers_view(self): url = reverse('accounts:followers', kwargs={'user_slug': self.user. slug}) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'accounts/followers.html') def test_following_view(self): url = reverse('accounts:following', kwargs={'user_slug': self.user. slug}) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'accounts/following.html') def test_user_like_view(self): url = reverse('accounts:user-like', kwargs={'slug': self.user.slug, 'pk': self.tweet.id}) response = self.client.get(url) self.assertEqual(response.status_code, 403) self.client.login(email=self.email, password=self.password) response = self.client.get(url) self.assertEqual(response.status_code, 200) def test_theme_view(self): url = reverse('accounts:theme') response = self.client.post(url) self.assertEqual(response.status_code, 302) self.client.login(email=self.email, password=self.password) response = self.client.post(url) self.assertEqual(response.status_code, 302) <|reserved_special_token_1|> <|reserved_special_token_0|> class TestAccountsViews(TestCase): <|reserved_special_token_0|> def test_login_view(self): response = self.client.get(reverse('accounts:login')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'accounts/login.html') def test_logout_view(self): response = self.client.get(reverse('accounts:logout')) self.assertEqual(response.status_code, 302) <|reserved_special_token_0|> def test_register_view(self): url = reverse('accounts:register') response = self.client.get(url) self.assertTemplateUsed(response, 'accounts/register.html') self.assertEqual(response.status_code, 200) def test_userfollow_view(self): url = reverse('accounts:follow', kwargs={'user_slug': self.user.slug}) response = self.client.get(url) self.assertEqual(response.status_code, 302) self.client.login(email=self.email, password=self.password) self.assertEqual(response.status_code, 302) def test_follow_manager_view(self): url = reverse('accounts:follow_manage', kwargs={'user_slug': self. user.slug}) response = self.client.get(url) self.assertEqual(response.status_code, 302) self.client.login(email=self.email, password=self.password) self.assertEqual(response.status_code, 302) def test_profile_update_view(self): url = reverse('accounts:profile_update', kwargs={'pk': self.user.id}) response = self.client.get(url) self.assertEqual(response.status_code, 302) def test_followers_view(self): url = reverse('accounts:followers', kwargs={'user_slug': self.user. slug}) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'accounts/followers.html') def test_following_view(self): url = reverse('accounts:following', kwargs={'user_slug': self.user. slug}) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'accounts/following.html') def test_user_like_view(self): url = reverse('accounts:user-like', kwargs={'slug': self.user.slug, 'pk': self.tweet.id}) response = self.client.get(url) self.assertEqual(response.status_code, 403) self.client.login(email=self.email, password=self.password) response = self.client.get(url) self.assertEqual(response.status_code, 200) def test_theme_view(self): url = reverse('accounts:theme') response = self.client.post(url) self.assertEqual(response.status_code, 302) self.client.login(email=self.email, password=self.password) response = self.client.post(url) self.assertEqual(response.status_code, 302) <|reserved_special_token_1|> <|reserved_special_token_0|> class TestAccountsViews(TestCase): def setUp(self): self.username = 'masterbdx' self.email = '[email protected]' self.password = '123456789' self.user = User.objects.create_superuser(email=self.email, username=self.username, password=self.password, subscribed=True) self.tweet = Tweet.objects.create(user=self.user, content='hello world' ) self.client = Client() def test_login_view(self): response = self.client.get(reverse('accounts:login')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'accounts/login.html') def test_logout_view(self): response = self.client.get(reverse('accounts:logout')) self.assertEqual(response.status_code, 302) <|reserved_special_token_0|> def test_register_view(self): url = reverse('accounts:register') response = self.client.get(url) self.assertTemplateUsed(response, 'accounts/register.html') self.assertEqual(response.status_code, 200) def test_userfollow_view(self): url = reverse('accounts:follow', kwargs={'user_slug': self.user.slug}) response = self.client.get(url) self.assertEqual(response.status_code, 302) self.client.login(email=self.email, password=self.password) self.assertEqual(response.status_code, 302) def test_follow_manager_view(self): url = reverse('accounts:follow_manage', kwargs={'user_slug': self. user.slug}) response = self.client.get(url) self.assertEqual(response.status_code, 302) self.client.login(email=self.email, password=self.password) self.assertEqual(response.status_code, 302) def test_profile_update_view(self): url = reverse('accounts:profile_update', kwargs={'pk': self.user.id}) response = self.client.get(url) self.assertEqual(response.status_code, 302) def test_followers_view(self): url = reverse('accounts:followers', kwargs={'user_slug': self.user. slug}) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'accounts/followers.html') def test_following_view(self): url = reverse('accounts:following', kwargs={'user_slug': self.user. slug}) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'accounts/following.html') def test_user_like_view(self): url = reverse('accounts:user-like', kwargs={'slug': self.user.slug, 'pk': self.tweet.id}) response = self.client.get(url) self.assertEqual(response.status_code, 403) self.client.login(email=self.email, password=self.password) response = self.client.get(url) self.assertEqual(response.status_code, 200) def test_theme_view(self): url = reverse('accounts:theme') response = self.client.post(url) self.assertEqual(response.status_code, 302) self.client.login(email=self.email, password=self.password) response = self.client.post(url) self.assertEqual(response.status_code, 302) <|reserved_special_token_1|> from django.test import TestCase, Client from django.urls import reverse from django.contrib.auth import get_user_model from tweets.models import Tweet from ..models import UserProfile User = get_user_model() class TestAccountsViews(TestCase): def setUp(self): self.username = 'masterbdx' self.email = '[email protected]' self.password = '123456789' self.user = User.objects.create_superuser(email=self.email, username=self.username, password=self.password, subscribed=True ) self.tweet = Tweet.objects.create( user=self.user, content='hello world',) self.client = Client() def test_login_view(self): response = self.client.get(reverse('accounts:login')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'accounts/login.html') def test_logout_view(self): response = self.client.get(reverse('accounts:logout')) self.assertEqual(response.status_code, 302) def test_profile_view(self): url = reverse('accounts:profile', kwargs={'user_slug': self.user.slug}) response = self.client.get(url) self.assertTemplateUsed(response, 'accounts/profile.html') self.assertEqual(response.status_code, 200) def test_register_view(self): url = reverse('accounts:register') response = self.client.get(url) self.assertTemplateUsed(response, 'accounts/register.html') self.assertEqual(response.status_code, 200) def test_userfollow_view(self): url = reverse('accounts:follow', kwargs={'user_slug': self.user.slug}) response = self.client.get(url) self.assertEqual(response.status_code, 302) self.client.login( email=self.email, password=self.password) self.assertEqual(response.status_code, 302) def test_follow_manager_view(self): url = reverse('accounts:follow_manage', kwargs={ 'user_slug': self.user.slug}) response = self.client.get(url) self.assertEqual(response.status_code, 302) self.client.login( email=self.email, password=self.password) self.assertEqual(response.status_code, 302) def test_profile_update_view(self): url = reverse('accounts:profile_update', kwargs={ 'pk': self.user.id}) response = self.client.get(url) self.assertEqual(response.status_code, 302) def test_followers_view(self): url = reverse('accounts:followers', kwargs={ 'user_slug': self.user.slug}) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'accounts/followers.html') def test_following_view(self): url = reverse('accounts:following', kwargs={ 'user_slug': self.user.slug}) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'accounts/following.html') def test_user_like_view(self): url = reverse('accounts:user-like', kwargs={ 'slug': self.user.slug, 'pk': self.tweet.id}) response = self.client.get(url) self.assertEqual(response.status_code, 403) self.client.login( email=self.email, password=self.password) response = self.client.get(url) self.assertEqual(response.status_code, 200) def test_theme_view(self): url = reverse('accounts:theme') response = self.client.post(url) self.assertEqual(response.status_code, 302) self.client.login( email=self.email, password=self.password) response = self.client.post(url) self.assertEqual(response.status_code, 302)
flexible
{ "blob_id": "888a5847beca2470f4063da474da1f05079abca9", "index": 5579, "step-1": "<mask token>\n\n\nclass TestAccountsViews(TestCase):\n <mask token>\n <mask token>\n\n def test_logout_view(self):\n response = self.client.get(reverse('accounts:logout'))\n self.assertEqual(response.status_code, 302)\n <mask token>\n\n def test_register_view(self):\n url = reverse('accounts:register')\n response = self.client.get(url)\n self.assertTemplateUsed(response, 'accounts/register.html')\n self.assertEqual(response.status_code, 200)\n\n def test_userfollow_view(self):\n url = reverse('accounts:follow', kwargs={'user_slug': self.user.slug})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 302)\n self.client.login(email=self.email, password=self.password)\n self.assertEqual(response.status_code, 302)\n\n def test_follow_manager_view(self):\n url = reverse('accounts:follow_manage', kwargs={'user_slug': self.\n user.slug})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 302)\n self.client.login(email=self.email, password=self.password)\n self.assertEqual(response.status_code, 302)\n\n def test_profile_update_view(self):\n url = reverse('accounts:profile_update', kwargs={'pk': self.user.id})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 302)\n\n def test_followers_view(self):\n url = reverse('accounts:followers', kwargs={'user_slug': self.user.\n slug})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'accounts/followers.html')\n\n def test_following_view(self):\n url = reverse('accounts:following', kwargs={'user_slug': self.user.\n slug})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'accounts/following.html')\n\n def test_user_like_view(self):\n url = reverse('accounts:user-like', kwargs={'slug': self.user.slug,\n 'pk': self.tweet.id})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 403)\n self.client.login(email=self.email, password=self.password)\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n <mask token>\n", "step-2": "<mask token>\n\n\nclass TestAccountsViews(TestCase):\n <mask token>\n <mask token>\n\n def test_logout_view(self):\n response = self.client.get(reverse('accounts:logout'))\n self.assertEqual(response.status_code, 302)\n <mask token>\n\n def test_register_view(self):\n url = reverse('accounts:register')\n response = self.client.get(url)\n self.assertTemplateUsed(response, 'accounts/register.html')\n self.assertEqual(response.status_code, 200)\n\n def test_userfollow_view(self):\n url = reverse('accounts:follow', kwargs={'user_slug': self.user.slug})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 302)\n self.client.login(email=self.email, password=self.password)\n self.assertEqual(response.status_code, 302)\n\n def test_follow_manager_view(self):\n url = reverse('accounts:follow_manage', kwargs={'user_slug': self.\n user.slug})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 302)\n self.client.login(email=self.email, password=self.password)\n self.assertEqual(response.status_code, 302)\n\n def test_profile_update_view(self):\n url = reverse('accounts:profile_update', kwargs={'pk': self.user.id})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 302)\n\n def test_followers_view(self):\n url = reverse('accounts:followers', kwargs={'user_slug': self.user.\n slug})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'accounts/followers.html')\n\n def test_following_view(self):\n url = reverse('accounts:following', kwargs={'user_slug': self.user.\n slug})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'accounts/following.html')\n\n def test_user_like_view(self):\n url = reverse('accounts:user-like', kwargs={'slug': self.user.slug,\n 'pk': self.tweet.id})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 403)\n self.client.login(email=self.email, password=self.password)\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n\n def test_theme_view(self):\n url = reverse('accounts:theme')\n response = self.client.post(url)\n self.assertEqual(response.status_code, 302)\n self.client.login(email=self.email, password=self.password)\n response = self.client.post(url)\n self.assertEqual(response.status_code, 302)\n", "step-3": "<mask token>\n\n\nclass TestAccountsViews(TestCase):\n <mask token>\n\n def test_login_view(self):\n response = self.client.get(reverse('accounts:login'))\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'accounts/login.html')\n\n def test_logout_view(self):\n response = self.client.get(reverse('accounts:logout'))\n self.assertEqual(response.status_code, 302)\n <mask token>\n\n def test_register_view(self):\n url = reverse('accounts:register')\n response = self.client.get(url)\n self.assertTemplateUsed(response, 'accounts/register.html')\n self.assertEqual(response.status_code, 200)\n\n def test_userfollow_view(self):\n url = reverse('accounts:follow', kwargs={'user_slug': self.user.slug})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 302)\n self.client.login(email=self.email, password=self.password)\n self.assertEqual(response.status_code, 302)\n\n def test_follow_manager_view(self):\n url = reverse('accounts:follow_manage', kwargs={'user_slug': self.\n user.slug})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 302)\n self.client.login(email=self.email, password=self.password)\n self.assertEqual(response.status_code, 302)\n\n def test_profile_update_view(self):\n url = reverse('accounts:profile_update', kwargs={'pk': self.user.id})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 302)\n\n def test_followers_view(self):\n url = reverse('accounts:followers', kwargs={'user_slug': self.user.\n slug})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'accounts/followers.html')\n\n def test_following_view(self):\n url = reverse('accounts:following', kwargs={'user_slug': self.user.\n slug})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'accounts/following.html')\n\n def test_user_like_view(self):\n url = reverse('accounts:user-like', kwargs={'slug': self.user.slug,\n 'pk': self.tweet.id})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 403)\n self.client.login(email=self.email, password=self.password)\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n\n def test_theme_view(self):\n url = reverse('accounts:theme')\n response = self.client.post(url)\n self.assertEqual(response.status_code, 302)\n self.client.login(email=self.email, password=self.password)\n response = self.client.post(url)\n self.assertEqual(response.status_code, 302)\n", "step-4": "<mask token>\n\n\nclass TestAccountsViews(TestCase):\n\n def setUp(self):\n self.username = 'masterbdx'\n self.email = '[email protected]'\n self.password = '123456789'\n self.user = User.objects.create_superuser(email=self.email,\n username=self.username, password=self.password, subscribed=True)\n self.tweet = Tweet.objects.create(user=self.user, content='hello world'\n )\n self.client = Client()\n\n def test_login_view(self):\n response = self.client.get(reverse('accounts:login'))\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'accounts/login.html')\n\n def test_logout_view(self):\n response = self.client.get(reverse('accounts:logout'))\n self.assertEqual(response.status_code, 302)\n <mask token>\n\n def test_register_view(self):\n url = reverse('accounts:register')\n response = self.client.get(url)\n self.assertTemplateUsed(response, 'accounts/register.html')\n self.assertEqual(response.status_code, 200)\n\n def test_userfollow_view(self):\n url = reverse('accounts:follow', kwargs={'user_slug': self.user.slug})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 302)\n self.client.login(email=self.email, password=self.password)\n self.assertEqual(response.status_code, 302)\n\n def test_follow_manager_view(self):\n url = reverse('accounts:follow_manage', kwargs={'user_slug': self.\n user.slug})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 302)\n self.client.login(email=self.email, password=self.password)\n self.assertEqual(response.status_code, 302)\n\n def test_profile_update_view(self):\n url = reverse('accounts:profile_update', kwargs={'pk': self.user.id})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 302)\n\n def test_followers_view(self):\n url = reverse('accounts:followers', kwargs={'user_slug': self.user.\n slug})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'accounts/followers.html')\n\n def test_following_view(self):\n url = reverse('accounts:following', kwargs={'user_slug': self.user.\n slug})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'accounts/following.html')\n\n def test_user_like_view(self):\n url = reverse('accounts:user-like', kwargs={'slug': self.user.slug,\n 'pk': self.tweet.id})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 403)\n self.client.login(email=self.email, password=self.password)\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n\n def test_theme_view(self):\n url = reverse('accounts:theme')\n response = self.client.post(url)\n self.assertEqual(response.status_code, 302)\n self.client.login(email=self.email, password=self.password)\n response = self.client.post(url)\n self.assertEqual(response.status_code, 302)\n", "step-5": "from django.test import TestCase, Client\nfrom django.urls import reverse\nfrom django.contrib.auth import get_user_model\n\nfrom tweets.models import Tweet\nfrom ..models import UserProfile\nUser = get_user_model()\n\n\nclass TestAccountsViews(TestCase):\n def setUp(self):\n self.username = 'masterbdx'\n self.email = '[email protected]'\n self.password = '123456789'\n self.user = User.objects.create_superuser(email=self.email,\n username=self.username,\n password=self.password,\n subscribed=True\n )\n\n self.tweet = Tweet.objects.create(\n user=self.user,\n content='hello world',)\n\n self.client = Client()\n\n def test_login_view(self):\n response = self.client.get(reverse('accounts:login'))\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'accounts/login.html')\n\n def test_logout_view(self):\n response = self.client.get(reverse('accounts:logout'))\n self.assertEqual(response.status_code, 302)\n\n def test_profile_view(self):\n url = reverse('accounts:profile', kwargs={'user_slug': self.user.slug})\n response = self.client.get(url)\n self.assertTemplateUsed(response, 'accounts/profile.html')\n self.assertEqual(response.status_code, 200)\n\n def test_register_view(self):\n url = reverse('accounts:register')\n response = self.client.get(url)\n self.assertTemplateUsed(response, 'accounts/register.html')\n self.assertEqual(response.status_code, 200)\n\n def test_userfollow_view(self):\n url = reverse('accounts:follow', kwargs={'user_slug': self.user.slug})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 302)\n self.client.login(\n email=self.email, password=self.password)\n self.assertEqual(response.status_code, 302)\n\n def test_follow_manager_view(self):\n url = reverse('accounts:follow_manage', kwargs={\n 'user_slug': self.user.slug})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 302)\n self.client.login(\n email=self.email, password=self.password)\n self.assertEqual(response.status_code, 302)\n\n def test_profile_update_view(self):\n url = reverse('accounts:profile_update', kwargs={\n 'pk': self.user.id})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 302)\n\n def test_followers_view(self):\n url = reverse('accounts:followers', kwargs={\n 'user_slug': self.user.slug})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'accounts/followers.html')\n\n def test_following_view(self):\n url = reverse('accounts:following', kwargs={\n 'user_slug': self.user.slug})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'accounts/following.html')\n\n def test_user_like_view(self):\n url = reverse('accounts:user-like', kwargs={\n 'slug': self.user.slug, 'pk': self.tweet.id})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 403)\n self.client.login(\n email=self.email, password=self.password)\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n\n def test_theme_view(self):\n url = reverse('accounts:theme')\n response = self.client.post(url)\n self.assertEqual(response.status_code, 302)\n self.client.login(\n email=self.email, password=self.password)\n response = self.client.post(url)\n self.assertEqual(response.status_code, 302)\n", "step-ids": [ 9, 10, 11, 12, 16 ] }
[ 9, 10, 11, 12, 16 ]
import sys def is_huge(A, B): return (A[0] > B[0]) and (A[1] > B[1]) if __name__ == '__main__': bulks = [] num = int(sys.stdin.readline()) for i in range(num): bulks.append(list(map(int, sys.stdin.readline().split()))) for i in range(len(bulks)): count = 0 for j in range(len(bulks)): if bulks[i] != bulks[j] and is_huge(bulks[j], bulks[i]): count += 1 if count == 0: print(1, end=" ") else: print(count+1, end=" ")
normal
{ "blob_id": "5dc8f420e16ee14ecfdc61413f10a783e819ec32", "index": 506, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef is_huge(A, B):\n return A[0] > B[0] and A[1] > B[1]\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef is_huge(A, B):\n return A[0] > B[0] and A[1] > B[1]\n\n\nif __name__ == '__main__':\n bulks = []\n num = int(sys.stdin.readline())\n for i in range(num):\n bulks.append(list(map(int, sys.stdin.readline().split())))\n for i in range(len(bulks)):\n count = 0\n for j in range(len(bulks)):\n if bulks[i] != bulks[j] and is_huge(bulks[j], bulks[i]):\n count += 1\n if count == 0:\n print(1, end=' ')\n else:\n print(count + 1, end=' ')\n", "step-4": "import sys\n\n\ndef is_huge(A, B):\n return A[0] > B[0] and A[1] > B[1]\n\n\nif __name__ == '__main__':\n bulks = []\n num = int(sys.stdin.readline())\n for i in range(num):\n bulks.append(list(map(int, sys.stdin.readline().split())))\n for i in range(len(bulks)):\n count = 0\n for j in range(len(bulks)):\n if bulks[i] != bulks[j] and is_huge(bulks[j], bulks[i]):\n count += 1\n if count == 0:\n print(1, end=' ')\n else:\n print(count + 1, end=' ')\n", "step-5": "import sys\n\n\ndef is_huge(A, B):\n return (A[0] > B[0]) and (A[1] > B[1])\n\n\nif __name__ == '__main__':\n bulks = []\n num = int(sys.stdin.readline())\n for i in range(num):\n bulks.append(list(map(int, sys.stdin.readline().split())))\n\n for i in range(len(bulks)):\n count = 0\n for j in range(len(bulks)):\n if bulks[i] != bulks[j] and is_huge(bulks[j], bulks[i]):\n count += 1\n\n if count == 0:\n print(1, end=\" \")\n else:\n print(count+1, end=\" \")\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
from django.db import models from django.utils.text import slugify import misaka from django.urls import reverse from django.contrib.auth import get_user_model from django import template register=template.Library() User=get_user_model() #call things out of users current session # Create your models here. class Group(models.Model): name = models.CharField(max_length=128,unique=True) slug = models.SlugField(allow_unicode=True,unique=True) #to avoid overlappping of the group names description= models.TextField(blank=True,default='') description_html=models.TextField(editable=False,default='',blank=True) member= models.ManyToManyField(User,through='GroupMember') def __str__(self): return self.name def save(self,*args,**kwargs): self.slug=slugify(self.name) #whatever the name is we can put spaces in it self.description_html=misaka.html(self.description) super().save(*args,**kwargs) def get_absolute_url(self): return reverse("groups:single", kwargs={"slug": self.slug}) class GroupMember(models.Model): group = models.ForeignKey(Group, related_name='memberships',on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='user_groups',on_delete=models.CASCADE) def __str__(self): return self.user.username class Meta: unique_together=('group','user')
normal
{ "blob_id": "51563f52e700a286451663a6e837d56e104c2c72", "index": 2849, "step-1": "<mask token>\n\n\nclass Group(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __str__(self):\n return self.name\n <mask token>\n <mask token>\n\n\nclass GroupMember(models.Model):\n group = models.ForeignKey(Group, related_name='memberships', on_delete=\n models.CASCADE)\n user = models.ForeignKey(User, related_name='user_groups', on_delete=\n models.CASCADE)\n\n def __str__(self):\n return self.user.username\n\n\n class Meta:\n unique_together = 'group', 'user'\n", "step-2": "<mask token>\n\n\nclass Group(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __str__(self):\n return self.name\n\n def save(self, *args, **kwargs):\n self.slug = slugify(self.name)\n self.description_html = misaka.html(self.description)\n super().save(*args, **kwargs)\n\n def get_absolute_url(self):\n return reverse('groups:single', kwargs={'slug': self.slug})\n\n\nclass GroupMember(models.Model):\n group = models.ForeignKey(Group, related_name='memberships', on_delete=\n models.CASCADE)\n user = models.ForeignKey(User, related_name='user_groups', on_delete=\n models.CASCADE)\n\n def __str__(self):\n return self.user.username\n\n\n class Meta:\n unique_together = 'group', 'user'\n", "step-3": "<mask token>\n\n\nclass Group(models.Model):\n name = models.CharField(max_length=128, unique=True)\n slug = models.SlugField(allow_unicode=True, unique=True)\n description = models.TextField(blank=True, default='')\n description_html = models.TextField(editable=False, default='', blank=True)\n member = models.ManyToManyField(User, through='GroupMember')\n\n def __str__(self):\n return self.name\n\n def save(self, *args, **kwargs):\n self.slug = slugify(self.name)\n self.description_html = misaka.html(self.description)\n super().save(*args, **kwargs)\n\n def get_absolute_url(self):\n return reverse('groups:single', kwargs={'slug': self.slug})\n\n\nclass GroupMember(models.Model):\n group = models.ForeignKey(Group, related_name='memberships', on_delete=\n models.CASCADE)\n user = models.ForeignKey(User, related_name='user_groups', on_delete=\n models.CASCADE)\n\n def __str__(self):\n return self.user.username\n\n\n class Meta:\n unique_together = 'group', 'user'\n", "step-4": "<mask token>\nregister = template.Library()\nUser = get_user_model()\n\n\nclass Group(models.Model):\n name = models.CharField(max_length=128, unique=True)\n slug = models.SlugField(allow_unicode=True, unique=True)\n description = models.TextField(blank=True, default='')\n description_html = models.TextField(editable=False, default='', blank=True)\n member = models.ManyToManyField(User, through='GroupMember')\n\n def __str__(self):\n return self.name\n\n def save(self, *args, **kwargs):\n self.slug = slugify(self.name)\n self.description_html = misaka.html(self.description)\n super().save(*args, **kwargs)\n\n def get_absolute_url(self):\n return reverse('groups:single', kwargs={'slug': self.slug})\n\n\nclass GroupMember(models.Model):\n group = models.ForeignKey(Group, related_name='memberships', on_delete=\n models.CASCADE)\n user = models.ForeignKey(User, related_name='user_groups', on_delete=\n models.CASCADE)\n\n def __str__(self):\n return self.user.username\n\n\n class Meta:\n unique_together = 'group', 'user'\n", "step-5": "from django.db import models\nfrom django.utils.text import slugify\nimport misaka\nfrom django.urls import reverse \nfrom django.contrib.auth import get_user_model\nfrom django import template\nregister=template.Library()\n\n\nUser=get_user_model() #call things out of users current session\n\n# Create your models here.\n\n\nclass Group(models.Model):\n name = models.CharField(max_length=128,unique=True)\n slug = models.SlugField(allow_unicode=True,unique=True) #to avoid overlappping of the group names\n description= models.TextField(blank=True,default='')\n description_html=models.TextField(editable=False,default='',blank=True)\n member= models.ManyToManyField(User,through='GroupMember')\n \n def __str__(self):\n return self.name\n \n def save(self,*args,**kwargs):\n self.slug=slugify(self.name) #whatever the name is we can put spaces in it\n self.description_html=misaka.html(self.description)\n super().save(*args,**kwargs)\n \n def get_absolute_url(self):\n return reverse(\"groups:single\", kwargs={\"slug\": self.slug})\n \n\nclass GroupMember(models.Model):\n group = models.ForeignKey(Group, related_name='memberships',on_delete=models.CASCADE)\n user = models.ForeignKey(User, related_name='user_groups',on_delete=models.CASCADE)\n \n def __str__(self):\n return self.user.username\n \n class Meta:\n unique_together=('group','user')", "step-ids": [ 5, 7, 8, 9, 11 ] }
[ 5, 7, 8, 9, 11 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> settings.configure(DEBUG=True, SECRET_KEY= 'ki==706e99f0ps9w5s*!kx%1^=5jq_k1c&4r@#e&ng9=xlm5_', ROOT_URLCONF= 'sitebuilder.urls', MIDDLEWARE_CLASSES=(), INSTALLED_APPS=( 'django.contrib.staticfiles', 'django.contrib.webdesign', 'sitebuilder', 'compressor'), STATIC_URL='/static/', SITE_PAGES_DIRECTORY=os.path.join (BASE_DIR, 'pages'), SITE_OUTPUT_DIRECTORY=os.path.join(BASE_DIR, '_build'), STATIC_ROOT=os.path.join(BASE_DIR, '_build', 'static'), STATICFILES_FINDERS=( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder')) if __name__ == '__main__': from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) <|reserved_special_token_1|> <|reserved_special_token_0|> BASE_DIR = os.path.dirname(__file__) settings.configure(DEBUG=True, SECRET_KEY= 'ki==706e99f0ps9w5s*!kx%1^=5jq_k1c&4r@#e&ng9=xlm5_', ROOT_URLCONF= 'sitebuilder.urls', MIDDLEWARE_CLASSES=(), INSTALLED_APPS=( 'django.contrib.staticfiles', 'django.contrib.webdesign', 'sitebuilder', 'compressor'), STATIC_URL='/static/', SITE_PAGES_DIRECTORY=os.path.join (BASE_DIR, 'pages'), SITE_OUTPUT_DIRECTORY=os.path.join(BASE_DIR, '_build'), STATIC_ROOT=os.path.join(BASE_DIR, '_build', 'static'), STATICFILES_FINDERS=( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder')) if __name__ == '__main__': from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) <|reserved_special_token_1|> import sys import os from django.conf import settings BASE_DIR = os.path.dirname(__file__) settings.configure(DEBUG=True, SECRET_KEY= 'ki==706e99f0ps9w5s*!kx%1^=5jq_k1c&4r@#e&ng9=xlm5_', ROOT_URLCONF= 'sitebuilder.urls', MIDDLEWARE_CLASSES=(), INSTALLED_APPS=( 'django.contrib.staticfiles', 'django.contrib.webdesign', 'sitebuilder', 'compressor'), STATIC_URL='/static/', SITE_PAGES_DIRECTORY=os.path.join (BASE_DIR, 'pages'), SITE_OUTPUT_DIRECTORY=os.path.join(BASE_DIR, '_build'), STATIC_ROOT=os.path.join(BASE_DIR, '_build', 'static'), STATICFILES_FINDERS=( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder')) if __name__ == '__main__': from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) <|reserved_special_token_1|> import sys import os from django.conf import settings BASE_DIR=os.path.dirname(__file__) settings.configure( DEBUG=True, SECRET_KEY='ki==706e99f0ps9w5s*!kx%1^=5jq_k1c&4r@#e&ng9=xlm5_', ROOT_URLCONF='sitebuilder.urls', MIDDLEWARE_CLASSES=(), INSTALLED_APPS=( 'django.contrib.staticfiles', 'django.contrib.webdesign', 'sitebuilder', 'compressor', ), STATIC_URL='/static/', SITE_PAGES_DIRECTORY=os.path.join(BASE_DIR,'pages'), SITE_OUTPUT_DIRECTORY=os.path.join(BASE_DIR,'_build'), STATIC_ROOT=os.path.join(BASE_DIR,'_build','static'), #STATICFILES_STORAGE='django.contrib.staticfiles.storage.CachedStaticFilesStorage', STATICFILES_FINDERS=( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder', ) ) if __name__ =="__main__": from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
flexible
{ "blob_id": "d30e5e24dd06a4846fdde3c9fcac0a5dac55ad0d", "index": 5916, "step-1": "<mask token>\n", "step-2": "<mask token>\nsettings.configure(DEBUG=True, SECRET_KEY=\n 'ki==706e99f0ps9w5s*!kx%1^=5jq_k1c&4r@#e&ng9=xlm5_', ROOT_URLCONF=\n 'sitebuilder.urls', MIDDLEWARE_CLASSES=(), INSTALLED_APPS=(\n 'django.contrib.staticfiles', 'django.contrib.webdesign', 'sitebuilder',\n 'compressor'), STATIC_URL='/static/', SITE_PAGES_DIRECTORY=os.path.join\n (BASE_DIR, 'pages'), SITE_OUTPUT_DIRECTORY=os.path.join(BASE_DIR,\n '_build'), STATIC_ROOT=os.path.join(BASE_DIR, '_build', 'static'),\n STATICFILES_FINDERS=(\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n 'compressor.finders.CompressorFinder'))\nif __name__ == '__main__':\n from django.core.management import execute_from_command_line\n execute_from_command_line(sys.argv)\n", "step-3": "<mask token>\nBASE_DIR = os.path.dirname(__file__)\nsettings.configure(DEBUG=True, SECRET_KEY=\n 'ki==706e99f0ps9w5s*!kx%1^=5jq_k1c&4r@#e&ng9=xlm5_', ROOT_URLCONF=\n 'sitebuilder.urls', MIDDLEWARE_CLASSES=(), INSTALLED_APPS=(\n 'django.contrib.staticfiles', 'django.contrib.webdesign', 'sitebuilder',\n 'compressor'), STATIC_URL='/static/', SITE_PAGES_DIRECTORY=os.path.join\n (BASE_DIR, 'pages'), SITE_OUTPUT_DIRECTORY=os.path.join(BASE_DIR,\n '_build'), STATIC_ROOT=os.path.join(BASE_DIR, '_build', 'static'),\n STATICFILES_FINDERS=(\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n 'compressor.finders.CompressorFinder'))\nif __name__ == '__main__':\n from django.core.management import execute_from_command_line\n execute_from_command_line(sys.argv)\n", "step-4": "import sys\nimport os\nfrom django.conf import settings\nBASE_DIR = os.path.dirname(__file__)\nsettings.configure(DEBUG=True, SECRET_KEY=\n 'ki==706e99f0ps9w5s*!kx%1^=5jq_k1c&4r@#e&ng9=xlm5_', ROOT_URLCONF=\n 'sitebuilder.urls', MIDDLEWARE_CLASSES=(), INSTALLED_APPS=(\n 'django.contrib.staticfiles', 'django.contrib.webdesign', 'sitebuilder',\n 'compressor'), STATIC_URL='/static/', SITE_PAGES_DIRECTORY=os.path.join\n (BASE_DIR, 'pages'), SITE_OUTPUT_DIRECTORY=os.path.join(BASE_DIR,\n '_build'), STATIC_ROOT=os.path.join(BASE_DIR, '_build', 'static'),\n STATICFILES_FINDERS=(\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n 'compressor.finders.CompressorFinder'))\nif __name__ == '__main__':\n from django.core.management import execute_from_command_line\n execute_from_command_line(sys.argv)\n", "step-5": "import sys\nimport os\n\nfrom django.conf import settings\n\nBASE_DIR=os.path.dirname(__file__)\n\nsettings.configure(\n\tDEBUG=True,\n\tSECRET_KEY='ki==706e99f0ps9w5s*!kx%1^=5jq_k1c&4r@#e&ng9=xlm5_',\n\tROOT_URLCONF='sitebuilder.urls',\n\tMIDDLEWARE_CLASSES=(),\n\tINSTALLED_APPS=(\n\t\t'django.contrib.staticfiles',\n\t\t'django.contrib.webdesign',\n\t\t'sitebuilder',\n\t\t'compressor',\n\n\t\t),\n\tSTATIC_URL='/static/',\n\tSITE_PAGES_DIRECTORY=os.path.join(BASE_DIR,'pages'),\n\tSITE_OUTPUT_DIRECTORY=os.path.join(BASE_DIR,'_build'),\n\tSTATIC_ROOT=os.path.join(BASE_DIR,'_build','static'),\n\t#STATICFILES_STORAGE='django.contrib.staticfiles.storage.CachedStaticFilesStorage',\n\tSTATICFILES_FINDERS=(\n\t\t'django.contrib.staticfiles.finders.FileSystemFinder',\n\t\t'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n\t\t'compressor.finders.CompressorFinder',\n\n\t\t)\n\n)\n\nif __name__ ==\"__main__\":\n\tfrom django.core.management import execute_from_command_line\n\n\texecute_from_command_line(sys.argv)", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# -*- coding: utf-8 -*- import io import urllib.request from pymarc import MARCReader class Item: """ Represents an item from our Library catalogue (https://www-lib.soton.ac.uk) Usage: #>>> import findbooks #>>> item = findbooks.Item('12345678') #>>> item.getMarcFields() #>>> print(item.title) """ webcat = "http://lms.soton.ac.uk/cgi-bin/goobi_marc.cgi?itemid=" def __init__(self, barcode): self.barcode = barcode self.marc = None self.record = None self.title = None self.author = None self.year = None def _get_marc(self): with urllib.request.urlopen(Item.webcat + self.barcode) as response: html = response.read().decode("utf-8") marc = html[html.find(">")+1:html.rfind("<")].strip(''' ''') if "Barcode not found" not in marc: self.marc = marc def _get_title(self): if self.record['245']: title = self.record['245']['a'].strip(' /:,.') return title def _get_long_title(self): title = self.record.title().strip(' /:,.') return title def _get_author(self): if self.record['100']: return self.record['100']['a'] elif self.record['110']: return self.record['110']['a'] elif self.record['111']: return self.record['111']['a'] else: return None def _get_year(self): date = self.record.pubyear() if date: # dates should only have numbers nums = '1234567890' new_date = '' for ch in date: if ch in nums: new_date += ch # dates should have '1' as the first char if not new_date[0] == "1": return None # dates should eb 4 chars long if not len(new_date) == 4: return None return new_date else: return None def get_marc_fields(self, len_title): self._get_marc() if self.marc: with io.BytesIO(self.marc.encode('utf-8')) as fh: reader = MARCReader(fh) for record in reader: self.record = record self.title = self._get_title() if len_title == "short" else self._get_long_title() self.author = self._get_author() self.year = self._get_year() # item = Item('59571478') # item.get_marc_fields() # print(item.title)
normal
{ "blob_id": "abfff0901e5f825a473119c93f53cba206609428", "index": 7482, "step-1": "<mask token>\n\n\nclass Item:\n <mask token>\n <mask token>\n\n def __init__(self, barcode):\n self.barcode = barcode\n self.marc = None\n self.record = None\n self.title = None\n self.author = None\n self.year = None\n\n def _get_marc(self):\n with urllib.request.urlopen(Item.webcat + self.barcode) as response:\n html = response.read().decode('utf-8')\n marc = html[html.find('>') + 1:html.rfind('<')].strip('\\n\\n ')\n if 'Barcode not found' not in marc:\n self.marc = marc\n\n def _get_title(self):\n if self.record['245']:\n title = self.record['245']['a'].strip(' /:,.')\n return title\n <mask token>\n <mask token>\n\n def _get_year(self):\n date = self.record.pubyear()\n if date:\n nums = '1234567890'\n new_date = ''\n for ch in date:\n if ch in nums:\n new_date += ch\n if not new_date[0] == '1':\n return None\n if not len(new_date) == 4:\n return None\n return new_date\n else:\n return None\n\n def get_marc_fields(self, len_title):\n self._get_marc()\n if self.marc:\n with io.BytesIO(self.marc.encode('utf-8')) as fh:\n reader = MARCReader(fh)\n for record in reader:\n self.record = record\n self.title = self._get_title(\n ) if len_title == 'short' else self._get_long_title()\n self.author = self._get_author()\n self.year = self._get_year()\n", "step-2": "<mask token>\n\n\nclass Item:\n <mask token>\n <mask token>\n\n def __init__(self, barcode):\n self.barcode = barcode\n self.marc = None\n self.record = None\n self.title = None\n self.author = None\n self.year = None\n\n def _get_marc(self):\n with urllib.request.urlopen(Item.webcat + self.barcode) as response:\n html = response.read().decode('utf-8')\n marc = html[html.find('>') + 1:html.rfind('<')].strip('\\n\\n ')\n if 'Barcode not found' not in marc:\n self.marc = marc\n\n def _get_title(self):\n if self.record['245']:\n title = self.record['245']['a'].strip(' /:,.')\n return title\n <mask token>\n\n def _get_author(self):\n if self.record['100']:\n return self.record['100']['a']\n elif self.record['110']:\n return self.record['110']['a']\n elif self.record['111']:\n return self.record['111']['a']\n else:\n return None\n\n def _get_year(self):\n date = self.record.pubyear()\n if date:\n nums = '1234567890'\n new_date = ''\n for ch in date:\n if ch in nums:\n new_date += ch\n if not new_date[0] == '1':\n return None\n if not len(new_date) == 4:\n return None\n return new_date\n else:\n return None\n\n def get_marc_fields(self, len_title):\n self._get_marc()\n if self.marc:\n with io.BytesIO(self.marc.encode('utf-8')) as fh:\n reader = MARCReader(fh)\n for record in reader:\n self.record = record\n self.title = self._get_title(\n ) if len_title == 'short' else self._get_long_title()\n self.author = self._get_author()\n self.year = self._get_year()\n", "step-3": "<mask token>\n\n\nclass Item:\n <mask token>\n <mask token>\n\n def __init__(self, barcode):\n self.barcode = barcode\n self.marc = None\n self.record = None\n self.title = None\n self.author = None\n self.year = None\n\n def _get_marc(self):\n with urllib.request.urlopen(Item.webcat + self.barcode) as response:\n html = response.read().decode('utf-8')\n marc = html[html.find('>') + 1:html.rfind('<')].strip('\\n\\n ')\n if 'Barcode not found' not in marc:\n self.marc = marc\n\n def _get_title(self):\n if self.record['245']:\n title = self.record['245']['a'].strip(' /:,.')\n return title\n\n def _get_long_title(self):\n title = self.record.title().strip(' /:,.')\n return title\n\n def _get_author(self):\n if self.record['100']:\n return self.record['100']['a']\n elif self.record['110']:\n return self.record['110']['a']\n elif self.record['111']:\n return self.record['111']['a']\n else:\n return None\n\n def _get_year(self):\n date = self.record.pubyear()\n if date:\n nums = '1234567890'\n new_date = ''\n for ch in date:\n if ch in nums:\n new_date += ch\n if not new_date[0] == '1':\n return None\n if not len(new_date) == 4:\n return None\n return new_date\n else:\n return None\n\n def get_marc_fields(self, len_title):\n self._get_marc()\n if self.marc:\n with io.BytesIO(self.marc.encode('utf-8')) as fh:\n reader = MARCReader(fh)\n for record in reader:\n self.record = record\n self.title = self._get_title(\n ) if len_title == 'short' else self._get_long_title()\n self.author = self._get_author()\n self.year = self._get_year()\n", "step-4": "import io\nimport urllib.request\nfrom pymarc import MARCReader\n\n\nclass Item:\n \"\"\"\n Represents an item from our\n Library catalogue (https://www-lib.soton.ac.uk)\n Usage:\n\n #>>> import findbooks\n #>>> item = findbooks.Item('12345678')\n #>>> item.getMarcFields()\n #>>> print(item.title)\n\n \"\"\"\n webcat = 'http://lms.soton.ac.uk/cgi-bin/goobi_marc.cgi?itemid='\n\n def __init__(self, barcode):\n self.barcode = barcode\n self.marc = None\n self.record = None\n self.title = None\n self.author = None\n self.year = None\n\n def _get_marc(self):\n with urllib.request.urlopen(Item.webcat + self.barcode) as response:\n html = response.read().decode('utf-8')\n marc = html[html.find('>') + 1:html.rfind('<')].strip('\\n\\n ')\n if 'Barcode not found' not in marc:\n self.marc = marc\n\n def _get_title(self):\n if self.record['245']:\n title = self.record['245']['a'].strip(' /:,.')\n return title\n\n def _get_long_title(self):\n title = self.record.title().strip(' /:,.')\n return title\n\n def _get_author(self):\n if self.record['100']:\n return self.record['100']['a']\n elif self.record['110']:\n return self.record['110']['a']\n elif self.record['111']:\n return self.record['111']['a']\n else:\n return None\n\n def _get_year(self):\n date = self.record.pubyear()\n if date:\n nums = '1234567890'\n new_date = ''\n for ch in date:\n if ch in nums:\n new_date += ch\n if not new_date[0] == '1':\n return None\n if not len(new_date) == 4:\n return None\n return new_date\n else:\n return None\n\n def get_marc_fields(self, len_title):\n self._get_marc()\n if self.marc:\n with io.BytesIO(self.marc.encode('utf-8')) as fh:\n reader = MARCReader(fh)\n for record in reader:\n self.record = record\n self.title = self._get_title(\n ) if len_title == 'short' else self._get_long_title()\n self.author = self._get_author()\n self.year = self._get_year()\n", "step-5": "# -*- coding: utf-8 -*-\nimport io\nimport urllib.request\nfrom pymarc import MARCReader\n\n\nclass Item:\n \"\"\"\n Represents an item from our\n Library catalogue (https://www-lib.soton.ac.uk)\n Usage:\n\n #>>> import findbooks\n #>>> item = findbooks.Item('12345678')\n #>>> item.getMarcFields()\n #>>> print(item.title)\n\n \"\"\"\n webcat = \"http://lms.soton.ac.uk/cgi-bin/goobi_marc.cgi?itemid=\"\n\n def __init__(self, barcode):\n self.barcode = barcode\n self.marc = None\n self.record = None\n self.title = None\n self.author = None\n self.year = None\n\n def _get_marc(self):\n with urllib.request.urlopen(Item.webcat + self.barcode) as response:\n html = response.read().decode(\"utf-8\")\n marc = html[html.find(\">\")+1:html.rfind(\"<\")].strip('''\n\n ''')\n if \"Barcode not found\" not in marc:\n self.marc = marc\n\n def _get_title(self):\n if self.record['245']:\n title = self.record['245']['a'].strip(' /:,.')\n return title\n\n def _get_long_title(self):\n title = self.record.title().strip(' /:,.')\n return title\n\n def _get_author(self):\n if self.record['100']:\n return self.record['100']['a']\n elif self.record['110']:\n return self.record['110']['a']\n elif self.record['111']:\n return self.record['111']['a']\n else:\n return None\n\n def _get_year(self):\n date = self.record.pubyear()\n if date:\n # dates should only have numbers\n nums = '1234567890'\n new_date = ''\n for ch in date:\n if ch in nums:\n new_date += ch\n # dates should have '1' as the first char\n if not new_date[0] == \"1\":\n return None\n # dates should eb 4 chars long\n if not len(new_date) == 4:\n return None\n return new_date\n else:\n return None\n\n def get_marc_fields(self, len_title):\n self._get_marc()\n if self.marc:\n with io.BytesIO(self.marc.encode('utf-8')) as fh:\n reader = MARCReader(fh)\n for record in reader:\n self.record = record\n self.title = self._get_title() if len_title == \"short\" else self._get_long_title()\n self.author = self._get_author()\n self.year = self._get_year()\n\n# item = Item('59571478')\n# item.get_marc_fields()\n# print(item.title)\n", "step-ids": [ 6, 7, 8, 11, 12 ] }
[ 6, 7, 8, 11, 12 ]
# -*- coding: utf-8 -*- import re import argparse import utils # Les arguments à fournir en ligne de commande parser = argparse.ArgumentParser(description="""Génère le graph des articles""") parser.add_argument('corpus', type=str, help="Le nom du corpus (sans l'extension .tsv')") parser.add_argument('-v', '--verbose', action='store_true', help="Afficher les messages d'information") args = parser.parse_args() corpus_file = args.corpus + '.tsv' with open(corpus_file) as f: o = open(args.corpus + '_graph.adj', 'w') f.readline() for i, raw_line in enumerate(f): doc = utils.Document(raw_line) renvois = re.findall("\[([^][]*?([[]\w*[]][^][]*)*)->(>?)([^]]*)\]", doc.text) for ref in renvois: if re.match("(?:art)?(\d+)", ref[3]): o.write(doc.id + ' ' + re.match("(?:art)?(\d+)", ref[3]).group(1) + '\n') if re.match("http://(www\.)?monde-diplomatique\.fr/\d{4}/\d{2}/\w*/(\d+)", ref[3]): o.write(doc.id + ' ' + re.match("http://(www\.)?monde-diplomatique\.fr/\d{4}/\d{2}/\w*/(\d+)", ref[3]).group(2 ) + '\n') if args.verbose: print "Article n°%d traité" % (i) o.close()
normal
{ "blob_id": "a2593d5b89b9a35d91b0e1011f5b2a23a5a2062e", "index": 2792, "step-1": "# -*- coding: utf-8 -*-\n\nimport re\nimport argparse\n\nimport utils\n\n# Les arguments à fournir en ligne de commande\nparser = argparse.ArgumentParser(description=\"\"\"Génère le graph des articles\"\"\")\nparser.add_argument('corpus', type=str, help=\"Le nom du corpus (sans l'extension .tsv')\")\nparser.add_argument('-v', '--verbose', action='store_true',\n help=\"Afficher les messages d'information\")\nargs = parser.parse_args()\n\ncorpus_file = args.corpus + '.tsv'\n\nwith open(corpus_file) as f:\n o = open(args.corpus + '_graph.adj', 'w')\n \n f.readline()\n for i, raw_line in enumerate(f):\n doc = utils.Document(raw_line)\n \n renvois = re.findall(\"\\[([^][]*?([[]\\w*[]][^][]*)*)->(>?)([^]]*)\\]\", doc.text)\n \n for ref in renvois:\n if re.match(\"(?:art)?(\\d+)\", ref[3]):\n o.write(doc.id + ' ' + re.match(\"(?:art)?(\\d+)\", ref[3]).group(1) + '\\n')\n \n if re.match(\"http://(www\\.)?monde-diplomatique\\.fr/\\d{4}/\\d{2}/\\w*/(\\d+)\", ref[3]):\n o.write(doc.id + ' ' + re.match(\"http://(www\\.)?monde-diplomatique\\.fr/\\d{4}/\\d{2}/\\w*/(\\d+)\", ref[3]).group(2 ) + '\\n')\n \n if args.verbose:\n print \"Article n°%d traité\" % (i)\n \n o.close()\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> f.close() print(cl.classify('Where to travel in bangalore ?')) print(cl.classify('Name a golf course in Myrtle beach .')) print(cl.classify('What body of water does the Danube River flow into ?')) print(time.time() - start) <|reserved_special_token_1|> <|reserved_special_token_0|> start = time.time() f = open('my_classifier.pickle', 'rb') cl = pickle.load(f) f.close() print(cl.classify('Where to travel in bangalore ?')) print(cl.classify('Name a golf course in Myrtle beach .')) print(cl.classify('What body of water does the Danube River flow into ?')) print(time.time() - start) <|reserved_special_token_1|> import pickle import time start = time.time() f = open('my_classifier.pickle', 'rb') cl = pickle.load(f) f.close() print(cl.classify('Where to travel in bangalore ?')) print(cl.classify('Name a golf course in Myrtle beach .')) print(cl.classify('What body of water does the Danube River flow into ?')) print(time.time() - start) <|reserved_special_token_1|> import pickle import time start = time.time() f = open('my_classifier.pickle', 'rb') cl = pickle.load(f) f.close() print(cl.classify("Where to travel in bangalore ?")) print(cl.classify("Name a golf course in Myrtle beach .")) print(cl.classify("What body of water does the Danube River flow into ?")) #print("Accuracy: {0}".format(cl.accuracy(test))) print(time.time()-start)
flexible
{ "blob_id": "82a3fca0261b4bde43f7bf258bb22e5b2ea8c28d", "index": 5370, "step-1": "<mask token>\n", "step-2": "<mask token>\nf.close()\nprint(cl.classify('Where to travel in bangalore ?'))\nprint(cl.classify('Name a golf course in Myrtle beach .'))\nprint(cl.classify('What body of water does the Danube River flow into ?'))\nprint(time.time() - start)\n", "step-3": "<mask token>\nstart = time.time()\nf = open('my_classifier.pickle', 'rb')\ncl = pickle.load(f)\nf.close()\nprint(cl.classify('Where to travel in bangalore ?'))\nprint(cl.classify('Name a golf course in Myrtle beach .'))\nprint(cl.classify('What body of water does the Danube River flow into ?'))\nprint(time.time() - start)\n", "step-4": "import pickle\nimport time\nstart = time.time()\nf = open('my_classifier.pickle', 'rb')\ncl = pickle.load(f)\nf.close()\nprint(cl.classify('Where to travel in bangalore ?'))\nprint(cl.classify('Name a golf course in Myrtle beach .'))\nprint(cl.classify('What body of water does the Danube River flow into ?'))\nprint(time.time() - start)\n", "step-5": "import pickle\nimport time\n\nstart = time.time()\nf = open('my_classifier.pickle', 'rb')\ncl = pickle.load(f)\nf.close()\n\nprint(cl.classify(\"Where to travel in bangalore ?\"))\nprint(cl.classify(\"Name a golf course in Myrtle beach .\"))\nprint(cl.classify(\"What body of water does the Danube River flow into ?\"))\n#print(\"Accuracy: {0}\".format(cl.accuracy(test)))\nprint(time.time()-start)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> def getLinks(url): links = [] document = BeautifulSoup(response, 'html.parser') for element in document.findAll('a', href=re.compile('.pdf$')): links.append(element.get('href')) return links <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def getLinks(url): links = [] document = BeautifulSoup(response, 'html.parser') for element in document.findAll('a', href=re.compile('.pdf$')): links.append(element.get('href')) return links <|reserved_special_token_0|> for link in pdf_links: pdf_file = requests.get(url) files.append(pdf_file) with Printer(linegap=1) as printer: for pdf_file in files: printer.text(pdf_file) <|reserved_special_token_1|> <|reserved_special_token_0|> def getLinks(url): links = [] document = BeautifulSoup(response, 'html.parser') for element in document.findAll('a', href=re.compile('.pdf$')): links.append(element.get('href')) return links site = 'https://greenteapress.com/wp/think-python/' http = httplib2.Http() status, response = http.request(site) pdf_links = getLinks(response) files = [] for link in pdf_links: pdf_file = requests.get(url) files.append(pdf_file) with Printer(linegap=1) as printer: for pdf_file in files: printer.text(pdf_file) <|reserved_special_token_1|> from requests import get from bs4 import BeautifulSoup, SoupStrainer import httplib2 import re from win32printing import Printer def getLinks(url): links = [] document = BeautifulSoup(response, 'html.parser') for element in document.findAll('a', href=re.compile('.pdf$')): links.append(element.get('href')) return links site = 'https://greenteapress.com/wp/think-python/' http = httplib2.Http() status, response = http.request(site) pdf_links = getLinks(response) files = [] for link in pdf_links: pdf_file = requests.get(url) files.append(pdf_file) with Printer(linegap=1) as printer: for pdf_file in files: printer.text(pdf_file) <|reserved_special_token_1|> from requests import get from bs4 import BeautifulSoup, SoupStrainer import httplib2 import re from win32printing import Printer def getLinks(url): links = [] document = BeautifulSoup(response, "html.parser") for element in document.findAll('a', href=re.compile(".pdf$")): links.append(element.get('href')) return links site = 'https://greenteapress.com/wp/think-python/' http = httplib2.Http() status, response = http.request(site) pdf_links = getLinks(response) files = [] for link in pdf_links: pdf_file = requests.get(url) files.append(pdf_file) with Printer(linegap=1) as printer: for pdf_file in files: printer.text(pdf_file)
flexible
{ "blob_id": "dbb007af79b2da2b5474281759c2bcce2a836fb5", "index": 1254, "step-1": "<mask token>\n\n\ndef getLinks(url):\n links = []\n document = BeautifulSoup(response, 'html.parser')\n for element in document.findAll('a', href=re.compile('.pdf$')):\n links.append(element.get('href'))\n return links\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef getLinks(url):\n links = []\n document = BeautifulSoup(response, 'html.parser')\n for element in document.findAll('a', href=re.compile('.pdf$')):\n links.append(element.get('href'))\n return links\n\n\n<mask token>\nfor link in pdf_links:\n pdf_file = requests.get(url)\n files.append(pdf_file)\nwith Printer(linegap=1) as printer:\n for pdf_file in files:\n printer.text(pdf_file)\n", "step-3": "<mask token>\n\n\ndef getLinks(url):\n links = []\n document = BeautifulSoup(response, 'html.parser')\n for element in document.findAll('a', href=re.compile('.pdf$')):\n links.append(element.get('href'))\n return links\n\n\nsite = 'https://greenteapress.com/wp/think-python/'\nhttp = httplib2.Http()\nstatus, response = http.request(site)\npdf_links = getLinks(response)\nfiles = []\nfor link in pdf_links:\n pdf_file = requests.get(url)\n files.append(pdf_file)\nwith Printer(linegap=1) as printer:\n for pdf_file in files:\n printer.text(pdf_file)\n", "step-4": "from requests import get\nfrom bs4 import BeautifulSoup, SoupStrainer\nimport httplib2\nimport re\nfrom win32printing import Printer\n\n\ndef getLinks(url):\n links = []\n document = BeautifulSoup(response, 'html.parser')\n for element in document.findAll('a', href=re.compile('.pdf$')):\n links.append(element.get('href'))\n return links\n\n\nsite = 'https://greenteapress.com/wp/think-python/'\nhttp = httplib2.Http()\nstatus, response = http.request(site)\npdf_links = getLinks(response)\nfiles = []\nfor link in pdf_links:\n pdf_file = requests.get(url)\n files.append(pdf_file)\nwith Printer(linegap=1) as printer:\n for pdf_file in files:\n printer.text(pdf_file)\n", "step-5": "from requests import get\nfrom bs4 import BeautifulSoup, SoupStrainer\nimport httplib2\nimport re\nfrom win32printing import Printer\n\ndef getLinks(url):\n links = []\n document = BeautifulSoup(response, \"html.parser\")\n\n for element in document.findAll('a', href=re.compile(\".pdf$\")):\n links.append(element.get('href'))\n\n return links\n\nsite = 'https://greenteapress.com/wp/think-python/'\n\nhttp = httplib2.Http()\nstatus, response = http.request(site)\npdf_links = getLinks(response) \n\nfiles = []\n\nfor link in pdf_links:\n pdf_file = requests.get(url)\n files.append(pdf_file)\n\nwith Printer(linegap=1) as printer:\n for pdf_file in files:\n printer.text(pdf_file)", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
""" r - reading fike w - writing to file a - append to file / add to the end of the file - always at the end r+ - read and write to file (writing based on python cursor position) -> by default at the beginning of file -> won't insert and shift things over, will overwrite the contents. -> r+ can only be used with already existing files. """ with open("haiku.txt", "w") as file: file.write("This is the line 1 of the haiku\n") file.write("Following the line 2 of the haiku\n") file.write("Finishing off with the line 3 of the haiku\n") with open("haiku.txt", "a") as file: file.write("This is the line 1 of the haiku\n") file.write("Following the line 2 of the haiku\n") file.write("Finishing off with the line 3 of the haiku\n") with open("existing_file.txt", "r+") as file: file.write("This is the line 1 of the haiku\n") file.write("Following the line 2 of the haiku\n") file.write("Finishing off with the line 3 of the haiku\n")
normal
{ "blob_id": "cde2454c68a0d6a0c86b7d647e41a86d3aa97a0d", "index": 8267, "step-1": "<mask token>\n", "step-2": "<mask token>\nwith open('haiku.txt', 'w') as file:\n file.write('This is the line 1 of the haiku\\n')\n file.write('Following the line 2 of the haiku\\n')\n file.write('Finishing off with the line 3 of the haiku\\n')\nwith open('haiku.txt', 'a') as file:\n file.write('This is the line 1 of the haiku\\n')\n file.write('Following the line 2 of the haiku\\n')\n file.write('Finishing off with the line 3 of the haiku\\n')\nwith open('existing_file.txt', 'r+') as file:\n file.write('This is the line 1 of the haiku\\n')\n file.write('Following the line 2 of the haiku\\n')\n file.write('Finishing off with the line 3 of the haiku\\n')\n", "step-3": "\"\"\"\nr - reading fike\nw - writing to file\na - append to file / add to the end of the file - always at the end\nr+ - read and write to file (writing based on python cursor position) -> by default at the beginning of file -> won't insert and shift things over,\nwill overwrite the contents. -> r+ can only be used with already existing files.\n\n\"\"\"\n\nwith open(\"haiku.txt\", \"w\") as file:\n file.write(\"This is the line 1 of the haiku\\n\")\n file.write(\"Following the line 2 of the haiku\\n\")\n file.write(\"Finishing off with the line 3 of the haiku\\n\")\n\nwith open(\"haiku.txt\", \"a\") as file:\n file.write(\"This is the line 1 of the haiku\\n\")\n file.write(\"Following the line 2 of the haiku\\n\")\n file.write(\"Finishing off with the line 3 of the haiku\\n\")\n\nwith open(\"existing_file.txt\", \"r+\") as file:\n file.write(\"This is the line 1 of the haiku\\n\")\n file.write(\"Following the line 2 of the haiku\\n\")\n file.write(\"Finishing off with the line 3 of the haiku\\n\")", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
""" SteinNS: BayesianLogisticRegression_KSD.py Created on 10/9/18 6:25 PM @author: Hanxi Sun """ import tensorflow as tf import numpy as np import scipy.io from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt ######################################################################################################################## # Data data = scipy.io.loadmat("data/covertype.mat") X_input = data['covtype'][:, 1:] y_input = data['covtype'][:, 0] y_input[y_input == 2] = -1 N_all = X_input.shape[0] X_input = np.hstack([X_input, np.ones([N_all, 1])]) d = X_input.shape[1] X_dim = d + 1 # dimension of the target distribution # split the data set into training and testing X_train, X_test, y_train, y_test = train_test_split(X_input, y_input, test_size=0.2, random_state=21) X_train_tf = tf.convert_to_tensor(X_train, dtype=tf.float64) X_test_tf = tf.convert_to_tensor(X_test, dtype=tf.float64) y_train_tf = tf.convert_to_tensor(y_train, dtype=tf.float64) y_test_tf = tf.convert_to_tensor(y_test, dtype=tf.float64) N = X_train.shape[0] ######################################################################################################################## # model parameters lr = 4e-4 # learning rate kernel = "rbf" # "rbf" or "imq" kernel z_dim = 100 h_dim_g = 200 mb_size_x = 100 # date mini-batch size mb_size = 100 # sample mini-batch size n_iter = 200000 iter_eval = 1000 optimizer = tf.train.RMSPropOptimizer ######################################################################################################################## # network tf.reset_default_graph() initializer = tf.contrib.layers.xavier_initializer() Xs = tf.placeholder(tf.float64, shape=[None, d]) ys = tf.placeholder(tf.float64, shape=[None]) z = tf.placeholder(tf.float64, shape=[None, z_dim]) G_W1 = tf.get_variable('g_w1', [z_dim, h_dim_g], dtype=tf.float64, initializer=initializer) G_b1 = tf.get_variable('g_b1', [h_dim_g], dtype=tf.float64, initializer=initializer) G_W2 = tf.get_variable('g_w2', [h_dim_g, h_dim_g], dtype=tf.float64, initializer=initializer) G_b2 = tf.get_variable('g_b2', [h_dim_g], dtype=tf.float64, initializer=initializer) G_W3 = tf.get_variable('g_w3', [h_dim_g, X_dim], dtype=tf.float64, initializer=initializer) G_b3 = tf.get_variable('g_b3', [X_dim], dtype=tf.float64, initializer=initializer) theta_G = [G_W1, G_b1, G_W2, G_b2, G_W3, G_b3] ######################################################################################################################## # functions & structures def sample_z(m, n, sd=10.): return np.random.normal(0, sd, size=[m, n]) def S_q(theta, a0=1, b0=0.01): # Reference: # https://github.com/DartML/Stein-Variational-Gradient-Descent/blob/master/python/bayesian_logistic_regression.py w = theta[:, :-1] # (m, d) s = tf.reshape(theta[:, -1], shape=[-1, 1]) # (m, 1); alpha = s**2 y_hat = 1. / (1. + tf.exp(- tf.matmul(Xs, tf.transpose(w)))) # (mx, m); shape(Xs) = (mx, d) y = tf.reshape((ys + 1.) / 2., shape=[-1, 1]) # (mx, 1) dw_data = tf.matmul(tf.transpose(y - y_hat), Xs) # (m, d) dw_prior = - s**2 * w # (m, d) dw = dw_data * N / mb_size_x + dw_prior # (m, d) w2 = tf.reshape(tf.reduce_sum(tf.square(w), axis=1), shape=[-1, 1]) # (m, 1); = wtw ds = (2. * a0 - 2 + d) / s - tf.multiply(w2 + 2. * b0, s) # (m, 1) return tf.concat([dw, ds], axis=1) def rbf_kernel(x, dim=X_dim, h=1.): # Reference 1: https://github.com/ChunyuanLI/SVGD/blob/master/demo_svgd.ipynb # Reference 2: https://github.com/yc14600/svgd/blob/master/svgd.py XY = tf.matmul(x, tf.transpose(x)) X2_ = tf.reshape(tf.reduce_sum(tf.square(x), axis=1), shape=[tf.shape(x)[0], 1]) X2 = tf.tile(X2_, [1, tf.shape(x)[0]]) pdist = tf.subtract(tf.add(X2, tf.transpose(X2)), 2 * XY) # pairwise distance matrix kxy = tf.exp(- pdist / h ** 2 / 2.0) # kernel matrix sum_kxy = tf.expand_dims(tf.reduce_sum(kxy, axis=1), 1) dxkxy = tf.add(-tf.matmul(kxy, x), tf.multiply(x, sum_kxy)) / (h ** 2) # sum_y dk(x, y)/dx dxykxy_tr = tf.multiply((dim * (h**2) - pdist), kxy) / (h**4) # tr( dk(x, y)/dxdy ) return kxy, dxkxy, dxykxy_tr def imq_kernel(x, dim=X_dim, beta=-.5, c=1.): XY = tf.matmul(x, tf.transpose(x)) X2_ = tf.reshape(tf.reduce_sum(tf.square(x), axis=1), shape=[tf.shape(x)[0], 1]) X2 = tf.tile(X2_, [1, tf.shape(x)[0]]) pdist = tf.subtract(tf.add(X2, tf.transpose(X2)), 2 * XY) # pairwise distance matrix kxy = (c + pdist) ** beta coeff = 2 * beta * ((c + pdist) ** (beta-1)) dxkxy = tf.matmul(coeff, x) - tf.multiply(x, tf.expand_dims(tf.reduce_sum(coeff, axis=1), 1)) dxykxy_tr = tf.multiply((c + pdist) ** (beta - 2), - 2 * dim * c * beta + (- 4 * beta ** 2 + (4 - 2 * dim) * beta) * pdist) return kxy, dxkxy, dxykxy_tr kernels = {"rbf": rbf_kernel, "imq": imq_kernel} Kernel = kernels[kernel] def ksd_emp(x, ap=1, dim=X_dim): sq = S_q(x, ap) kxy, dxkxy, dxykxy_tr = Kernel(x, dim) t13 = tf.multiply(tf.matmul(sq, tf.transpose(sq)), kxy) + dxykxy_tr t2 = 2 * tf.trace(tf.matmul(sq, tf.transpose(dxkxy))) n = tf.cast(tf.shape(x)[0], tf.float64) # ksd = (tf.reduce_sum(t13) - tf.trace(t13) + t2) / (n * (n-1)) ksd = (tf.reduce_sum(t13) + t2) / (n ** 2) return ksd def generator(z): G_h1 = tf.nn.tanh(tf.matmul(z, G_W1) + G_b1) G_h2 = tf.nn.tanh(tf.matmul(G_h1, G_W2) + G_b2) out = 10. * tf.matmul(G_h2, G_W3) + G_b3 return out def evaluation(theta, X_t=X_test, y_t=y_test): w = theta[:, :-1] y = y_t.reshape([-1, 1]) coff = - np.matmul(y * X_t, w.T) prob = np.mean(1. / (1 + np.exp(coff)), axis=1) acc = np.mean(prob > .5) llh = np.mean(np.log(prob)) return acc, llh G_sample = generator(z) ksd = ksd_emp(G_sample) solver_KSD = optimizer(learning_rate=lr).minimize(ksd, var_list=theta_G) ####################################################################################################################### sess = tf.Session() sess.run(tf.global_variables_initializer()) ksd_loss = np.zeros(n_iter) acc = np.zeros(1 + (n_iter // iter_eval)) loglik = np.zeros(1 + (n_iter // iter_eval)) for it in range(n_iter): batch = [i % N for i in range(it * mb_size_x, (it + 1) * mb_size_x)] X_b = X_train[batch, :] y_b = y_train[batch] _, loss_curr = sess.run([solver_KSD, ksd], feed_dict={Xs: X_b, ys: y_b, z: sample_z(mb_size, z_dim)}) ksd_loss[it] = loss_curr if it % iter_eval == 0: post = sess.run(G_sample, feed_dict={z: sample_z(mb_size, z_dim)}) post_eval = evaluation(post) acc[it // iter_eval] = post_eval[0] loglik[it // iter_eval] = post_eval[1] plt.plot(ksd) plt.axvline(np.argmin(ksd_loss), color="r") plt.title("KSD loss (min={:.04f} at iter {})".format(np.min(ksd_loss), np.argmin(ksd_loss))) plt.show() plt.close() plt.plot(np.arange(len(acc)) * iter_eval, acc) plt.ylim(top=0.8) plt.axhline(0.75, color="g") plt.title("Accuracy (max={:0.4f} at iter {})".format(np.max(acc), np.argmax(acc)*iter_eval)) plt.show() plt.close()
normal
{ "blob_id": "a0a9527268fb5f8ea24de700f7700b874fbf4a6b", "index": 4838, "step-1": "<mask token>\n\n\ndef S_q(theta, a0=1, b0=0.01):\n w = theta[:, :-1]\n s = tf.reshape(theta[:, -1], shape=[-1, 1])\n y_hat = 1.0 / (1.0 + tf.exp(-tf.matmul(Xs, tf.transpose(w))))\n y = tf.reshape((ys + 1.0) / 2.0, shape=[-1, 1])\n dw_data = tf.matmul(tf.transpose(y - y_hat), Xs)\n dw_prior = -s ** 2 * w\n dw = dw_data * N / mb_size_x + dw_prior\n w2 = tf.reshape(tf.reduce_sum(tf.square(w), axis=1), shape=[-1, 1])\n ds = (2.0 * a0 - 2 + d) / s - tf.multiply(w2 + 2.0 * b0, s)\n return tf.concat([dw, ds], axis=1)\n\n\ndef rbf_kernel(x, dim=X_dim, h=1.0):\n XY = tf.matmul(x, tf.transpose(x))\n X2_ = tf.reshape(tf.reduce_sum(tf.square(x), axis=1), shape=[tf.shape(x\n )[0], 1])\n X2 = tf.tile(X2_, [1, tf.shape(x)[0]])\n pdist = tf.subtract(tf.add(X2, tf.transpose(X2)), 2 * XY)\n kxy = tf.exp(-pdist / h ** 2 / 2.0)\n sum_kxy = tf.expand_dims(tf.reduce_sum(kxy, axis=1), 1)\n dxkxy = tf.add(-tf.matmul(kxy, x), tf.multiply(x, sum_kxy)) / h ** 2\n dxykxy_tr = tf.multiply(dim * h ** 2 - pdist, kxy) / h ** 4\n return kxy, dxkxy, dxykxy_tr\n\n\ndef imq_kernel(x, dim=X_dim, beta=-0.5, c=1.0):\n XY = tf.matmul(x, tf.transpose(x))\n X2_ = tf.reshape(tf.reduce_sum(tf.square(x), axis=1), shape=[tf.shape(x\n )[0], 1])\n X2 = tf.tile(X2_, [1, tf.shape(x)[0]])\n pdist = tf.subtract(tf.add(X2, tf.transpose(X2)), 2 * XY)\n kxy = (c + pdist) ** beta\n coeff = 2 * beta * (c + pdist) ** (beta - 1)\n dxkxy = tf.matmul(coeff, x) - tf.multiply(x, tf.expand_dims(tf.\n reduce_sum(coeff, axis=1), 1))\n dxykxy_tr = tf.multiply((c + pdist) ** (beta - 2), -2 * dim * c * beta +\n (-4 * beta ** 2 + (4 - 2 * dim) * beta) * pdist)\n return kxy, dxkxy, dxykxy_tr\n\n\n<mask token>\n\n\ndef ksd_emp(x, ap=1, dim=X_dim):\n sq = S_q(x, ap)\n kxy, dxkxy, dxykxy_tr = Kernel(x, dim)\n t13 = tf.multiply(tf.matmul(sq, tf.transpose(sq)), kxy) + dxykxy_tr\n t2 = 2 * tf.trace(tf.matmul(sq, tf.transpose(dxkxy)))\n n = tf.cast(tf.shape(x)[0], tf.float64)\n ksd = (tf.reduce_sum(t13) + t2) / n ** 2\n return ksd\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef sample_z(m, n, sd=10.0):\n return np.random.normal(0, sd, size=[m, n])\n\n\ndef S_q(theta, a0=1, b0=0.01):\n w = theta[:, :-1]\n s = tf.reshape(theta[:, -1], shape=[-1, 1])\n y_hat = 1.0 / (1.0 + tf.exp(-tf.matmul(Xs, tf.transpose(w))))\n y = tf.reshape((ys + 1.0) / 2.0, shape=[-1, 1])\n dw_data = tf.matmul(tf.transpose(y - y_hat), Xs)\n dw_prior = -s ** 2 * w\n dw = dw_data * N / mb_size_x + dw_prior\n w2 = tf.reshape(tf.reduce_sum(tf.square(w), axis=1), shape=[-1, 1])\n ds = (2.0 * a0 - 2 + d) / s - tf.multiply(w2 + 2.0 * b0, s)\n return tf.concat([dw, ds], axis=1)\n\n\ndef rbf_kernel(x, dim=X_dim, h=1.0):\n XY = tf.matmul(x, tf.transpose(x))\n X2_ = tf.reshape(tf.reduce_sum(tf.square(x), axis=1), shape=[tf.shape(x\n )[0], 1])\n X2 = tf.tile(X2_, [1, tf.shape(x)[0]])\n pdist = tf.subtract(tf.add(X2, tf.transpose(X2)), 2 * XY)\n kxy = tf.exp(-pdist / h ** 2 / 2.0)\n sum_kxy = tf.expand_dims(tf.reduce_sum(kxy, axis=1), 1)\n dxkxy = tf.add(-tf.matmul(kxy, x), tf.multiply(x, sum_kxy)) / h ** 2\n dxykxy_tr = tf.multiply(dim * h ** 2 - pdist, kxy) / h ** 4\n return kxy, dxkxy, dxykxy_tr\n\n\ndef imq_kernel(x, dim=X_dim, beta=-0.5, c=1.0):\n XY = tf.matmul(x, tf.transpose(x))\n X2_ = tf.reshape(tf.reduce_sum(tf.square(x), axis=1), shape=[tf.shape(x\n )[0], 1])\n X2 = tf.tile(X2_, [1, tf.shape(x)[0]])\n pdist = tf.subtract(tf.add(X2, tf.transpose(X2)), 2 * XY)\n kxy = (c + pdist) ** beta\n coeff = 2 * beta * (c + pdist) ** (beta - 1)\n dxkxy = tf.matmul(coeff, x) - tf.multiply(x, tf.expand_dims(tf.\n reduce_sum(coeff, axis=1), 1))\n dxykxy_tr = tf.multiply((c + pdist) ** (beta - 2), -2 * dim * c * beta +\n (-4 * beta ** 2 + (4 - 2 * dim) * beta) * pdist)\n return kxy, dxkxy, dxykxy_tr\n\n\n<mask token>\n\n\ndef ksd_emp(x, ap=1, dim=X_dim):\n sq = S_q(x, ap)\n kxy, dxkxy, dxykxy_tr = Kernel(x, dim)\n t13 = tf.multiply(tf.matmul(sq, tf.transpose(sq)), kxy) + dxykxy_tr\n t2 = 2 * tf.trace(tf.matmul(sq, tf.transpose(dxkxy)))\n n = tf.cast(tf.shape(x)[0], tf.float64)\n ksd = (tf.reduce_sum(t13) + t2) / n ** 2\n return ksd\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef sample_z(m, n, sd=10.0):\n return np.random.normal(0, sd, size=[m, n])\n\n\ndef S_q(theta, a0=1, b0=0.01):\n w = theta[:, :-1]\n s = tf.reshape(theta[:, -1], shape=[-1, 1])\n y_hat = 1.0 / (1.0 + tf.exp(-tf.matmul(Xs, tf.transpose(w))))\n y = tf.reshape((ys + 1.0) / 2.0, shape=[-1, 1])\n dw_data = tf.matmul(tf.transpose(y - y_hat), Xs)\n dw_prior = -s ** 2 * w\n dw = dw_data * N / mb_size_x + dw_prior\n w2 = tf.reshape(tf.reduce_sum(tf.square(w), axis=1), shape=[-1, 1])\n ds = (2.0 * a0 - 2 + d) / s - tf.multiply(w2 + 2.0 * b0, s)\n return tf.concat([dw, ds], axis=1)\n\n\ndef rbf_kernel(x, dim=X_dim, h=1.0):\n XY = tf.matmul(x, tf.transpose(x))\n X2_ = tf.reshape(tf.reduce_sum(tf.square(x), axis=1), shape=[tf.shape(x\n )[0], 1])\n X2 = tf.tile(X2_, [1, tf.shape(x)[0]])\n pdist = tf.subtract(tf.add(X2, tf.transpose(X2)), 2 * XY)\n kxy = tf.exp(-pdist / h ** 2 / 2.0)\n sum_kxy = tf.expand_dims(tf.reduce_sum(kxy, axis=1), 1)\n dxkxy = tf.add(-tf.matmul(kxy, x), tf.multiply(x, sum_kxy)) / h ** 2\n dxykxy_tr = tf.multiply(dim * h ** 2 - pdist, kxy) / h ** 4\n return kxy, dxkxy, dxykxy_tr\n\n\ndef imq_kernel(x, dim=X_dim, beta=-0.5, c=1.0):\n XY = tf.matmul(x, tf.transpose(x))\n X2_ = tf.reshape(tf.reduce_sum(tf.square(x), axis=1), shape=[tf.shape(x\n )[0], 1])\n X2 = tf.tile(X2_, [1, tf.shape(x)[0]])\n pdist = tf.subtract(tf.add(X2, tf.transpose(X2)), 2 * XY)\n kxy = (c + pdist) ** beta\n coeff = 2 * beta * (c + pdist) ** (beta - 1)\n dxkxy = tf.matmul(coeff, x) - tf.multiply(x, tf.expand_dims(tf.\n reduce_sum(coeff, axis=1), 1))\n dxykxy_tr = tf.multiply((c + pdist) ** (beta - 2), -2 * dim * c * beta +\n (-4 * beta ** 2 + (4 - 2 * dim) * beta) * pdist)\n return kxy, dxkxy, dxykxy_tr\n\n\n<mask token>\n\n\ndef ksd_emp(x, ap=1, dim=X_dim):\n sq = S_q(x, ap)\n kxy, dxkxy, dxykxy_tr = Kernel(x, dim)\n t13 = tf.multiply(tf.matmul(sq, tf.transpose(sq)), kxy) + dxykxy_tr\n t2 = 2 * tf.trace(tf.matmul(sq, tf.transpose(dxkxy)))\n n = tf.cast(tf.shape(x)[0], tf.float64)\n ksd = (tf.reduce_sum(t13) + t2) / n ** 2\n return ksd\n\n\ndef generator(z):\n G_h1 = tf.nn.tanh(tf.matmul(z, G_W1) + G_b1)\n G_h2 = tf.nn.tanh(tf.matmul(G_h1, G_W2) + G_b2)\n out = 10.0 * tf.matmul(G_h2, G_W3) + G_b3\n return out\n\n\ndef evaluation(theta, X_t=X_test, y_t=y_test):\n w = theta[:, :-1]\n y = y_t.reshape([-1, 1])\n coff = -np.matmul(y * X_t, w.T)\n prob = np.mean(1.0 / (1 + np.exp(coff)), axis=1)\n acc = np.mean(prob > 0.5)\n llh = np.mean(np.log(prob))\n return acc, llh\n\n\n<mask token>\n", "step-4": "<mask token>\ntf.reset_default_graph()\n<mask token>\n\n\ndef sample_z(m, n, sd=10.0):\n return np.random.normal(0, sd, size=[m, n])\n\n\ndef S_q(theta, a0=1, b0=0.01):\n w = theta[:, :-1]\n s = tf.reshape(theta[:, -1], shape=[-1, 1])\n y_hat = 1.0 / (1.0 + tf.exp(-tf.matmul(Xs, tf.transpose(w))))\n y = tf.reshape((ys + 1.0) / 2.0, shape=[-1, 1])\n dw_data = tf.matmul(tf.transpose(y - y_hat), Xs)\n dw_prior = -s ** 2 * w\n dw = dw_data * N / mb_size_x + dw_prior\n w2 = tf.reshape(tf.reduce_sum(tf.square(w), axis=1), shape=[-1, 1])\n ds = (2.0 * a0 - 2 + d) / s - tf.multiply(w2 + 2.0 * b0, s)\n return tf.concat([dw, ds], axis=1)\n\n\ndef rbf_kernel(x, dim=X_dim, h=1.0):\n XY = tf.matmul(x, tf.transpose(x))\n X2_ = tf.reshape(tf.reduce_sum(tf.square(x), axis=1), shape=[tf.shape(x\n )[0], 1])\n X2 = tf.tile(X2_, [1, tf.shape(x)[0]])\n pdist = tf.subtract(tf.add(X2, tf.transpose(X2)), 2 * XY)\n kxy = tf.exp(-pdist / h ** 2 / 2.0)\n sum_kxy = tf.expand_dims(tf.reduce_sum(kxy, axis=1), 1)\n dxkxy = tf.add(-tf.matmul(kxy, x), tf.multiply(x, sum_kxy)) / h ** 2\n dxykxy_tr = tf.multiply(dim * h ** 2 - pdist, kxy) / h ** 4\n return kxy, dxkxy, dxykxy_tr\n\n\ndef imq_kernel(x, dim=X_dim, beta=-0.5, c=1.0):\n XY = tf.matmul(x, tf.transpose(x))\n X2_ = tf.reshape(tf.reduce_sum(tf.square(x), axis=1), shape=[tf.shape(x\n )[0], 1])\n X2 = tf.tile(X2_, [1, tf.shape(x)[0]])\n pdist = tf.subtract(tf.add(X2, tf.transpose(X2)), 2 * XY)\n kxy = (c + pdist) ** beta\n coeff = 2 * beta * (c + pdist) ** (beta - 1)\n dxkxy = tf.matmul(coeff, x) - tf.multiply(x, tf.expand_dims(tf.\n reduce_sum(coeff, axis=1), 1))\n dxykxy_tr = tf.multiply((c + pdist) ** (beta - 2), -2 * dim * c * beta +\n (-4 * beta ** 2 + (4 - 2 * dim) * beta) * pdist)\n return kxy, dxkxy, dxykxy_tr\n\n\n<mask token>\n\n\ndef ksd_emp(x, ap=1, dim=X_dim):\n sq = S_q(x, ap)\n kxy, dxkxy, dxykxy_tr = Kernel(x, dim)\n t13 = tf.multiply(tf.matmul(sq, tf.transpose(sq)), kxy) + dxykxy_tr\n t2 = 2 * tf.trace(tf.matmul(sq, tf.transpose(dxkxy)))\n n = tf.cast(tf.shape(x)[0], tf.float64)\n ksd = (tf.reduce_sum(t13) + t2) / n ** 2\n return ksd\n\n\ndef generator(z):\n G_h1 = tf.nn.tanh(tf.matmul(z, G_W1) + G_b1)\n G_h2 = tf.nn.tanh(tf.matmul(G_h1, G_W2) + G_b2)\n out = 10.0 * tf.matmul(G_h2, G_W3) + G_b3\n return out\n\n\ndef evaluation(theta, X_t=X_test, y_t=y_test):\n w = theta[:, :-1]\n y = y_t.reshape([-1, 1])\n coff = -np.matmul(y * X_t, w.T)\n prob = np.mean(1.0 / (1 + np.exp(coff)), axis=1)\n acc = np.mean(prob > 0.5)\n llh = np.mean(np.log(prob))\n return acc, llh\n\n\n<mask token>\nsess.run(tf.global_variables_initializer())\n<mask token>\nfor it in range(n_iter):\n batch = [(i % N) for i in range(it * mb_size_x, (it + 1) * mb_size_x)]\n X_b = X_train[batch, :]\n y_b = y_train[batch]\n _, loss_curr = sess.run([solver_KSD, ksd], feed_dict={Xs: X_b, ys: y_b,\n z: sample_z(mb_size, z_dim)})\n ksd_loss[it] = loss_curr\n if it % iter_eval == 0:\n post = sess.run(G_sample, feed_dict={z: sample_z(mb_size, z_dim)})\n post_eval = evaluation(post)\n acc[it // iter_eval] = post_eval[0]\n loglik[it // iter_eval] = post_eval[1]\nplt.plot(ksd)\nplt.axvline(np.argmin(ksd_loss), color='r')\nplt.title('KSD loss (min={:.04f} at iter {})'.format(np.min(ksd_loss), np.\n argmin(ksd_loss)))\nplt.show()\nplt.close()\nplt.plot(np.arange(len(acc)) * iter_eval, acc)\nplt.ylim(top=0.8)\nplt.axhline(0.75, color='g')\nplt.title('Accuracy (max={:0.4f} at iter {})'.format(np.max(acc), np.argmax\n (acc) * iter_eval))\nplt.show()\nplt.close()\n", "step-5": "\"\"\"\n\nSteinNS: BayesianLogisticRegression_KSD.py\n\nCreated on 10/9/18 6:25 PM\n\n@author: Hanxi Sun\n\n\"\"\"\n\nimport tensorflow as tf\nimport numpy as np\nimport scipy.io\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\n\n\n########################################################################################################################\n# Data\n\ndata = scipy.io.loadmat(\"data/covertype.mat\")\nX_input = data['covtype'][:, 1:]\ny_input = data['covtype'][:, 0]\ny_input[y_input == 2] = -1\n\nN_all = X_input.shape[0]\nX_input = np.hstack([X_input, np.ones([N_all, 1])])\nd = X_input.shape[1]\nX_dim = d + 1 # dimension of the target distribution\n\n# split the data set into training and testing\nX_train, X_test, y_train, y_test = train_test_split(X_input, y_input, test_size=0.2, random_state=21)\nX_train_tf = tf.convert_to_tensor(X_train, dtype=tf.float64)\nX_test_tf = tf.convert_to_tensor(X_test, dtype=tf.float64)\ny_train_tf = tf.convert_to_tensor(y_train, dtype=tf.float64)\ny_test_tf = tf.convert_to_tensor(y_test, dtype=tf.float64)\n\nN = X_train.shape[0]\n\n\n########################################################################################################################\n# model parameters\n\nlr = 4e-4 # learning rate\nkernel = \"rbf\" # \"rbf\" or \"imq\" kernel\n\nz_dim = 100\nh_dim_g = 200\n\nmb_size_x = 100 # date mini-batch size\nmb_size = 100 # sample mini-batch size\nn_iter = 200000\niter_eval = 1000\n\noptimizer = tf.train.RMSPropOptimizer\n\n\n########################################################################################################################\n# network\ntf.reset_default_graph()\n\ninitializer = tf.contrib.layers.xavier_initializer()\n\nXs = tf.placeholder(tf.float64, shape=[None, d])\nys = tf.placeholder(tf.float64, shape=[None])\nz = tf.placeholder(tf.float64, shape=[None, z_dim])\n\nG_W1 = tf.get_variable('g_w1', [z_dim, h_dim_g], dtype=tf.float64, initializer=initializer)\nG_b1 = tf.get_variable('g_b1', [h_dim_g], dtype=tf.float64, initializer=initializer)\nG_W2 = tf.get_variable('g_w2', [h_dim_g, h_dim_g], dtype=tf.float64, initializer=initializer)\nG_b2 = tf.get_variable('g_b2', [h_dim_g], dtype=tf.float64, initializer=initializer)\nG_W3 = tf.get_variable('g_w3', [h_dim_g, X_dim], dtype=tf.float64, initializer=initializer)\nG_b3 = tf.get_variable('g_b3', [X_dim], dtype=tf.float64, initializer=initializer)\n\ntheta_G = [G_W1, G_b1, G_W2, G_b2, G_W3, G_b3]\n\n\n########################################################################################################################\n# functions & structures\n\ndef sample_z(m, n, sd=10.):\n return np.random.normal(0, sd, size=[m, n])\n\n\ndef S_q(theta, a0=1, b0=0.01):\n # Reference:\n # https://github.com/DartML/Stein-Variational-Gradient-Descent/blob/master/python/bayesian_logistic_regression.py\n\n w = theta[:, :-1] # (m, d)\n s = tf.reshape(theta[:, -1], shape=[-1, 1]) # (m, 1); alpha = s**2\n\n y_hat = 1. / (1. + tf.exp(- tf.matmul(Xs, tf.transpose(w)))) # (mx, m); shape(Xs) = (mx, d)\n y = tf.reshape((ys + 1.) / 2., shape=[-1, 1]) # (mx, 1)\n\n dw_data = tf.matmul(tf.transpose(y - y_hat), Xs) # (m, d)\n dw_prior = - s**2 * w # (m, d)\n dw = dw_data * N / mb_size_x + dw_prior # (m, d)\n\n w2 = tf.reshape(tf.reduce_sum(tf.square(w), axis=1), shape=[-1, 1]) # (m, 1); = wtw\n ds = (2. * a0 - 2 + d) / s - tf.multiply(w2 + 2. * b0, s) # (m, 1)\n\n return tf.concat([dw, ds], axis=1)\n\n\ndef rbf_kernel(x, dim=X_dim, h=1.):\n # Reference 1: https://github.com/ChunyuanLI/SVGD/blob/master/demo_svgd.ipynb\n # Reference 2: https://github.com/yc14600/svgd/blob/master/svgd.py\n XY = tf.matmul(x, tf.transpose(x))\n X2_ = tf.reshape(tf.reduce_sum(tf.square(x), axis=1), shape=[tf.shape(x)[0], 1])\n X2 = tf.tile(X2_, [1, tf.shape(x)[0]])\n pdist = tf.subtract(tf.add(X2, tf.transpose(X2)), 2 * XY) # pairwise distance matrix\n\n kxy = tf.exp(- pdist / h ** 2 / 2.0) # kernel matrix\n\n sum_kxy = tf.expand_dims(tf.reduce_sum(kxy, axis=1), 1)\n dxkxy = tf.add(-tf.matmul(kxy, x), tf.multiply(x, sum_kxy)) / (h ** 2) # sum_y dk(x, y)/dx\n\n dxykxy_tr = tf.multiply((dim * (h**2) - pdist), kxy) / (h**4) # tr( dk(x, y)/dxdy )\n\n return kxy, dxkxy, dxykxy_tr\n\n\ndef imq_kernel(x, dim=X_dim, beta=-.5, c=1.):\n XY = tf.matmul(x, tf.transpose(x))\n X2_ = tf.reshape(tf.reduce_sum(tf.square(x), axis=1), shape=[tf.shape(x)[0], 1])\n X2 = tf.tile(X2_, [1, tf.shape(x)[0]])\n pdist = tf.subtract(tf.add(X2, tf.transpose(X2)), 2 * XY) # pairwise distance matrix\n\n kxy = (c + pdist) ** beta\n\n coeff = 2 * beta * ((c + pdist) ** (beta-1))\n dxkxy = tf.matmul(coeff, x) - tf.multiply(x, tf.expand_dims(tf.reduce_sum(coeff, axis=1), 1))\n\n dxykxy_tr = tf.multiply((c + pdist) ** (beta - 2),\n - 2 * dim * c * beta + (- 4 * beta ** 2 + (4 - 2 * dim) * beta) * pdist)\n\n return kxy, dxkxy, dxykxy_tr\n\n\nkernels = {\"rbf\": rbf_kernel,\n \"imq\": imq_kernel}\n\nKernel = kernels[kernel]\n\n\ndef ksd_emp(x, ap=1, dim=X_dim):\n sq = S_q(x, ap)\n kxy, dxkxy, dxykxy_tr = Kernel(x, dim)\n t13 = tf.multiply(tf.matmul(sq, tf.transpose(sq)), kxy) + dxykxy_tr\n t2 = 2 * tf.trace(tf.matmul(sq, tf.transpose(dxkxy)))\n n = tf.cast(tf.shape(x)[0], tf.float64)\n\n # ksd = (tf.reduce_sum(t13) - tf.trace(t13) + t2) / (n * (n-1))\n ksd = (tf.reduce_sum(t13) + t2) / (n ** 2)\n\n return ksd\n\n\ndef generator(z):\n G_h1 = tf.nn.tanh(tf.matmul(z, G_W1) + G_b1)\n G_h2 = tf.nn.tanh(tf.matmul(G_h1, G_W2) + G_b2)\n out = 10. * tf.matmul(G_h2, G_W3) + G_b3\n return out\n\n\ndef evaluation(theta, X_t=X_test, y_t=y_test):\n w = theta[:, :-1]\n y = y_t.reshape([-1, 1])\n coff = - np.matmul(y * X_t, w.T)\n prob = np.mean(1. / (1 + np.exp(coff)), axis=1)\n acc = np.mean(prob > .5)\n llh = np.mean(np.log(prob))\n return acc, llh\n\n\nG_sample = generator(z)\n\nksd = ksd_emp(G_sample)\nsolver_KSD = optimizer(learning_rate=lr).minimize(ksd, var_list=theta_G)\n\n\n#######################################################################################################################\n\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\n\nksd_loss = np.zeros(n_iter)\nacc = np.zeros(1 + (n_iter // iter_eval))\nloglik = np.zeros(1 + (n_iter // iter_eval))\n\nfor it in range(n_iter):\n batch = [i % N for i in range(it * mb_size_x, (it + 1) * mb_size_x)]\n\n X_b = X_train[batch, :]\n y_b = y_train[batch]\n\n _, loss_curr = sess.run([solver_KSD, ksd], feed_dict={Xs: X_b, ys: y_b, z: sample_z(mb_size, z_dim)})\n\n ksd_loss[it] = loss_curr\n\n if it % iter_eval == 0:\n post = sess.run(G_sample, feed_dict={z: sample_z(mb_size, z_dim)})\n post_eval = evaluation(post)\n acc[it // iter_eval] = post_eval[0]\n loglik[it // iter_eval] = post_eval[1]\n\nplt.plot(ksd)\nplt.axvline(np.argmin(ksd_loss), color=\"r\")\nplt.title(\"KSD loss (min={:.04f} at iter {})\".format(np.min(ksd_loss), np.argmin(ksd_loss)))\nplt.show()\nplt.close()\n\n\nplt.plot(np.arange(len(acc)) * iter_eval, acc)\nplt.ylim(top=0.8)\nplt.axhline(0.75, color=\"g\")\nplt.title(\"Accuracy (max={:0.4f} at iter {})\".format(np.max(acc), np.argmax(acc)*iter_eval))\nplt.show()\nplt.close()\n\n\n\n", "step-ids": [ 4, 5, 7, 8, 11 ] }
[ 4, 5, 7, 8, 11 ]
<|reserved_special_token_0|> def leerNumero(): numer = int(input('Escribe un numero ==> ')) primo(numer) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def leerNumero(): numer = int(input('Escribe un numero ==> ')) primo(numer) def main(): leerNumero() <|reserved_special_token_0|> <|reserved_special_token_1|> def primo(num): if num < 1: print(f'El numero {num} no es primo') return None elif num == 2: print(f'El numero {num} es primo') return None else: for i in range(2, num): if num % i == 0: print(f'El numero {num} no es primo') return None print(f'El numero {num} es primo') def leerNumero(): numer = int(input('Escribe un numero ==> ')) primo(numer) def main(): leerNumero() <|reserved_special_token_0|> <|reserved_special_token_1|> def primo(num): if num < 1: print(f'El numero {num} no es primo') return None elif num == 2: print(f'El numero {num} es primo') return None else: for i in range(2, num): if num % i == 0: print(f'El numero {num} no es primo') return None print(f'El numero {num} es primo') def leerNumero(): numer = int(input('Escribe un numero ==> ')) primo(numer) def main(): leerNumero() if __name__ == '__main__': main() <|reserved_special_token_1|> def primo(num): if num < 1: print(f"El numero {num} no es primo") return None else: if num == 2: print(f"El numero {num} es primo") return None else: for i in range(2, num): if num % i == 0: print(f"El numero {num} no es primo") return None print(f"El numero {num} es primo") def leerNumero(): numer = int(input("Escribe un numero ==> ")) primo(numer) def main(): leerNumero() if __name__ =="__main__": main()
flexible
{ "blob_id": "29eb1a1642d38160c138733e269bb3ba0c5d4bba", "index": 9834, "step-1": "<mask token>\n\n\ndef leerNumero():\n numer = int(input('Escribe un numero ==> '))\n primo(numer)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef leerNumero():\n numer = int(input('Escribe un numero ==> '))\n primo(numer)\n\n\ndef main():\n leerNumero()\n\n\n<mask token>\n", "step-3": "def primo(num):\n if num < 1:\n print(f'El numero {num} no es primo')\n return None\n elif num == 2:\n print(f'El numero {num} es primo')\n return None\n else:\n for i in range(2, num):\n if num % i == 0:\n print(f'El numero {num} no es primo')\n return None\n print(f'El numero {num} es primo')\n\n\ndef leerNumero():\n numer = int(input('Escribe un numero ==> '))\n primo(numer)\n\n\ndef main():\n leerNumero()\n\n\n<mask token>\n", "step-4": "def primo(num):\n if num < 1:\n print(f'El numero {num} no es primo')\n return None\n elif num == 2:\n print(f'El numero {num} es primo')\n return None\n else:\n for i in range(2, num):\n if num % i == 0:\n print(f'El numero {num} no es primo')\n return None\n print(f'El numero {num} es primo')\n\n\ndef leerNumero():\n numer = int(input('Escribe un numero ==> '))\n primo(numer)\n\n\ndef main():\n leerNumero()\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "\ndef primo(num):\n if num < 1:\n print(f\"El numero {num} no es primo\")\n return None\n else:\n if num == 2:\n print(f\"El numero {num} es primo\")\n return None\n else:\n for i in range(2, num):\n if num % i == 0:\n print(f\"El numero {num} no es primo\")\n return None\n print(f\"El numero {num} es primo\") \n\n\ndef leerNumero():\n numer = int(input(\"Escribe un numero ==> \"))\n primo(numer)\n\n\ndef main():\n leerNumero()\n\n\nif __name__ ==\"__main__\":\n main() ", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
"""" articulo cliente venta ventadet """ class Articulo: def __init__(self,cod,des,pre,stoc): self.codigo=cod self.descripcion = des self.precio=pre self.stock=stoc class ventaDetalle: def __init__(self,pro,pre,cant): self.producto=pro self.precio=pre self.cantidad=cant
normal
{ "blob_id": "f70f66926b9e2bf8b387d481263493d7f4c65397", "index": 516, "step-1": "<mask token>\n\n\nclass ventaDetalle:\n <mask token>\n", "step-2": "<mask token>\n\n\nclass ventaDetalle:\n\n def __init__(self, pro, pre, cant):\n self.producto = pro\n self.precio = pre\n self.cantidad = cant\n", "step-3": "<mask token>\n\n\nclass Articulo:\n <mask token>\n\n\nclass ventaDetalle:\n\n def __init__(self, pro, pre, cant):\n self.producto = pro\n self.precio = pre\n self.cantidad = cant\n", "step-4": "<mask token>\n\n\nclass Articulo:\n\n def __init__(self, cod, des, pre, stoc):\n self.codigo = cod\n self.descripcion = des\n self.precio = pre\n self.stock = stoc\n\n\nclass ventaDetalle:\n\n def __init__(self, pro, pre, cant):\n self.producto = pro\n self.precio = pre\n self.cantidad = cant\n", "step-5": "\"\"\"\"\r\narticulo\r\ncliente\r\nventa\r\nventadet\r\n\"\"\"\r\nclass Articulo:\r\n def __init__(self,cod,des,pre,stoc):\r\n self.codigo=cod\r\n self.descripcion = des\r\n self.precio=pre\r\n self.stock=stoc\r\n\r\n\r\n\r\n\r\n\r\nclass ventaDetalle:\r\n def __init__(self,pro,pre,cant):\r\n self.producto=pro\r\n self.precio=pre\r\n self.cantidad=cant\r\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
<|reserved_special_token_0|> class invites(models.Model): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def __init__(self, *args, **kwargs): super(invites, self).__init__(*args, **kwargs) if not self.code and self.alumni_id: code = [self.PREFIX, str(self.alumni.year) + translit(self. alumni.letter).lower()] full_name = re.sub('\\([^)]*\\)\\s+', '', self.alumni.full_name) surname, name = full_name.split(' ', 1) code.append(translit(surname[:3]).lower() + translit(name[0]). lower()) csprng = SystemRandom() code.append(''.join(csprng.choice(string.digits) for _ in range (self.STRENGTH))) self.code = '-'.join(code) class Meta: verbose_name = 'Invite' verbose_name_plural = 'Invites' def __unicode__(self): return unicode(self.code) + ' (' + unicode(self.alumni) + ')' def safe_form(self): code = self.code[:-self.STRENGTH] + 'x' * (self.STRENGTH - 4 ) + self.code[-4:] return unicode(code) def is_enabled(self): return self.status == self.STATUS_OK def is_temporary(self): return self.application_id is not None def disable(self, at=None): if at is None: at = timezone.now() self.status = self.STATUS_DISABLED if at > timezone.now(): at = timezone.now() if self.disabled_at is None or self.disabled_at > at: self.disabled_at = at def merge_to(self, other_code, session): link = invite_links(code_from=self, code_to=other_code, is_merged_to=True, session=session) link.save() def verbose_status(self): if self.status == self.STATUS_OK: return 'ok' if self.status == self.STATUS_DISABLED: return 'disabled' if self.status == self.STATUS_BANNED: return 'banned' return None <|reserved_special_token_0|> def ensure_expires_after(self, valid_for): expires_at = datetime.datetime.now() + datetime.timedelta(seconds= valid_for) if expires_at > self.expires_at: self.expires_at = expires_at self.save() class invite_links(models.Model): code_to = models.ForeignKey(invites, related_name='invite_links_to') code_from = models.ForeignKey(invites, related_name='invite_links_from') is_issued_by = models.BooleanField(default=False) is_merged_to = models.BooleanField(default=False) is_temporary_for = models.BooleanField(default=False) add_time = models.DateTimeField(auto_now_add=True) session = models.CharField(max_length=100, null=True, blank=True) class Meta: verbose_name = 'Invite link' verbose_name_plural = 'Invite links' def __unicode__(self): return unicode(self.code_from) + ' -> ' + unicode(self.code_to) <|reserved_special_token_1|> <|reserved_special_token_0|> class invites(models.Model): PREFIX = '57' STRENGTH = 16 STATUS_OK = 1 STATUS_DISABLED = 2 STATUS_BANNED = 3 STATUSES = (1, 'OK'), (2, 'DISABLED'), (3, 'BANNED') code = models.CharField(max_length=255) alumni = models.ForeignKey(alumni) application = models.ForeignKey(Application, null=True, blank=True) add_time = models.DateTimeField(auto_now_add=True) status = models.SmallIntegerField(choices=STATUSES, default=STATUS_OK) disabled_at = models.DateTimeField(null=True, blank=True) expires_at = models.DateTimeField(null=True, blank=True) used_at = models.DateTimeField(null=True, blank=True) @classmethod def temporary_for(cls, invite, application, valid_for, session): try: new_code = invite_links.objects.get(code_from_id=invite.id, is_temporary_for=True, code_to__application_id=application.id ).code_to if valid_for is not None: new_code.ensure_expires_after(valid_for) return new_code except invite_links.DoesNotExist: pass if valid_for is None: valid_for = application.valid_for expires_at = datetime.datetime.now() + datetime.timedelta(seconds= valid_for) new_code = invites(application=application, alumni_id=invite. alumni_id, expires_at=expires_at, used_at=datetime.datetime.now()) new_code.code += '-' + application.slug new_code.save() link = invite_links(code_from=invite, code_to=new_code, session= session, is_temporary_for=True) link.save() return new_code def __init__(self, *args, **kwargs): super(invites, self).__init__(*args, **kwargs) if not self.code and self.alumni_id: code = [self.PREFIX, str(self.alumni.year) + translit(self. alumni.letter).lower()] full_name = re.sub('\\([^)]*\\)\\s+', '', self.alumni.full_name) surname, name = full_name.split(' ', 1) code.append(translit(surname[:3]).lower() + translit(name[0]). lower()) csprng = SystemRandom() code.append(''.join(csprng.choice(string.digits) for _ in range (self.STRENGTH))) self.code = '-'.join(code) class Meta: verbose_name = 'Invite' verbose_name_plural = 'Invites' def __unicode__(self): return unicode(self.code) + ' (' + unicode(self.alumni) + ')' def safe_form(self): code = self.code[:-self.STRENGTH] + 'x' * (self.STRENGTH - 4 ) + self.code[-4:] return unicode(code) def is_enabled(self): return self.status == self.STATUS_OK def is_temporary(self): return self.application_id is not None def disable(self, at=None): if at is None: at = timezone.now() self.status = self.STATUS_DISABLED if at > timezone.now(): at = timezone.now() if self.disabled_at is None or self.disabled_at > at: self.disabled_at = at def merge_to(self, other_code, session): link = invite_links(code_from=self, code_to=other_code, is_merged_to=True, session=session) link.save() def verbose_status(self): if self.status == self.STATUS_OK: return 'ok' if self.status == self.STATUS_DISABLED: return 'disabled' if self.status == self.STATUS_BANNED: return 'banned' return None def expires_at_timestamp(self): if self.expires_at is not None: return time.mktime(self.expires_at.timetuple()) return None def ensure_expires_after(self, valid_for): expires_at = datetime.datetime.now() + datetime.timedelta(seconds= valid_for) if expires_at > self.expires_at: self.expires_at = expires_at self.save() class invite_links(models.Model): code_to = models.ForeignKey(invites, related_name='invite_links_to') code_from = models.ForeignKey(invites, related_name='invite_links_from') is_issued_by = models.BooleanField(default=False) is_merged_to = models.BooleanField(default=False) is_temporary_for = models.BooleanField(default=False) add_time = models.DateTimeField(auto_now_add=True) session = models.CharField(max_length=100, null=True, blank=True) class Meta: verbose_name = 'Invite link' verbose_name_plural = 'Invite links' def __unicode__(self): return unicode(self.code_from) + ' -> ' + unicode(self.code_to) <|reserved_special_token_1|> <|reserved_special_token_0|> class Application(models.Model): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def __unicode__(self): return self.slug class invites(models.Model): PREFIX = '57' STRENGTH = 16 STATUS_OK = 1 STATUS_DISABLED = 2 STATUS_BANNED = 3 STATUSES = (1, 'OK'), (2, 'DISABLED'), (3, 'BANNED') code = models.CharField(max_length=255) alumni = models.ForeignKey(alumni) application = models.ForeignKey(Application, null=True, blank=True) add_time = models.DateTimeField(auto_now_add=True) status = models.SmallIntegerField(choices=STATUSES, default=STATUS_OK) disabled_at = models.DateTimeField(null=True, blank=True) expires_at = models.DateTimeField(null=True, blank=True) used_at = models.DateTimeField(null=True, blank=True) @classmethod def temporary_for(cls, invite, application, valid_for, session): try: new_code = invite_links.objects.get(code_from_id=invite.id, is_temporary_for=True, code_to__application_id=application.id ).code_to if valid_for is not None: new_code.ensure_expires_after(valid_for) return new_code except invite_links.DoesNotExist: pass if valid_for is None: valid_for = application.valid_for expires_at = datetime.datetime.now() + datetime.timedelta(seconds= valid_for) new_code = invites(application=application, alumni_id=invite. alumni_id, expires_at=expires_at, used_at=datetime.datetime.now()) new_code.code += '-' + application.slug new_code.save() link = invite_links(code_from=invite, code_to=new_code, session= session, is_temporary_for=True) link.save() return new_code def __init__(self, *args, **kwargs): super(invites, self).__init__(*args, **kwargs) if not self.code and self.alumni_id: code = [self.PREFIX, str(self.alumni.year) + translit(self. alumni.letter).lower()] full_name = re.sub('\\([^)]*\\)\\s+', '', self.alumni.full_name) surname, name = full_name.split(' ', 1) code.append(translit(surname[:3]).lower() + translit(name[0]). lower()) csprng = SystemRandom() code.append(''.join(csprng.choice(string.digits) for _ in range (self.STRENGTH))) self.code = '-'.join(code) class Meta: verbose_name = 'Invite' verbose_name_plural = 'Invites' def __unicode__(self): return unicode(self.code) + ' (' + unicode(self.alumni) + ')' def safe_form(self): code = self.code[:-self.STRENGTH] + 'x' * (self.STRENGTH - 4 ) + self.code[-4:] return unicode(code) def is_enabled(self): return self.status == self.STATUS_OK def is_temporary(self): return self.application_id is not None def disable(self, at=None): if at is None: at = timezone.now() self.status = self.STATUS_DISABLED if at > timezone.now(): at = timezone.now() if self.disabled_at is None or self.disabled_at > at: self.disabled_at = at def merge_to(self, other_code, session): link = invite_links(code_from=self, code_to=other_code, is_merged_to=True, session=session) link.save() def verbose_status(self): if self.status == self.STATUS_OK: return 'ok' if self.status == self.STATUS_DISABLED: return 'disabled' if self.status == self.STATUS_BANNED: return 'banned' return None def expires_at_timestamp(self): if self.expires_at is not None: return time.mktime(self.expires_at.timetuple()) return None def ensure_expires_after(self, valid_for): expires_at = datetime.datetime.now() + datetime.timedelta(seconds= valid_for) if expires_at > self.expires_at: self.expires_at = expires_at self.save() class invite_links(models.Model): code_to = models.ForeignKey(invites, related_name='invite_links_to') code_from = models.ForeignKey(invites, related_name='invite_links_from') is_issued_by = models.BooleanField(default=False) is_merged_to = models.BooleanField(default=False) is_temporary_for = models.BooleanField(default=False) add_time = models.DateTimeField(auto_now_add=True) session = models.CharField(max_length=100, null=True, blank=True) class Meta: verbose_name = 'Invite link' verbose_name_plural = 'Invite links' def __unicode__(self): return unicode(self.code_from) + ' -> ' + unicode(self.code_to) <|reserved_special_token_1|> <|reserved_special_token_0|> class alumni(models.Model): alumnus_id = models.AutoField(primary_key=True) full_name = models.CharField(max_length=150) year = models.IntegerField() letter = models.CharField(max_length=2) add_time = models.DateTimeField(auto_now_add=True) added_by = models.CharField(max_length=50) class Meta: verbose_name = 'Alumnus' verbose_name_plural = 'Alumni' def __unicode__(self): return self.full_name + ', ' + unicode(self.year) + self.letter class Application(models.Model): slug = models.SlugField() name = models.CharField(max_length=200) url = models.URLField() disabled = models.BooleanField(default=False) valid_for = models.PositiveIntegerField() def __unicode__(self): return self.slug class invites(models.Model): PREFIX = '57' STRENGTH = 16 STATUS_OK = 1 STATUS_DISABLED = 2 STATUS_BANNED = 3 STATUSES = (1, 'OK'), (2, 'DISABLED'), (3, 'BANNED') code = models.CharField(max_length=255) alumni = models.ForeignKey(alumni) application = models.ForeignKey(Application, null=True, blank=True) add_time = models.DateTimeField(auto_now_add=True) status = models.SmallIntegerField(choices=STATUSES, default=STATUS_OK) disabled_at = models.DateTimeField(null=True, blank=True) expires_at = models.DateTimeField(null=True, blank=True) used_at = models.DateTimeField(null=True, blank=True) @classmethod def temporary_for(cls, invite, application, valid_for, session): try: new_code = invite_links.objects.get(code_from_id=invite.id, is_temporary_for=True, code_to__application_id=application.id ).code_to if valid_for is not None: new_code.ensure_expires_after(valid_for) return new_code except invite_links.DoesNotExist: pass if valid_for is None: valid_for = application.valid_for expires_at = datetime.datetime.now() + datetime.timedelta(seconds= valid_for) new_code = invites(application=application, alumni_id=invite. alumni_id, expires_at=expires_at, used_at=datetime.datetime.now()) new_code.code += '-' + application.slug new_code.save() link = invite_links(code_from=invite, code_to=new_code, session= session, is_temporary_for=True) link.save() return new_code def __init__(self, *args, **kwargs): super(invites, self).__init__(*args, **kwargs) if not self.code and self.alumni_id: code = [self.PREFIX, str(self.alumni.year) + translit(self. alumni.letter).lower()] full_name = re.sub('\\([^)]*\\)\\s+', '', self.alumni.full_name) surname, name = full_name.split(' ', 1) code.append(translit(surname[:3]).lower() + translit(name[0]). lower()) csprng = SystemRandom() code.append(''.join(csprng.choice(string.digits) for _ in range (self.STRENGTH))) self.code = '-'.join(code) class Meta: verbose_name = 'Invite' verbose_name_plural = 'Invites' def __unicode__(self): return unicode(self.code) + ' (' + unicode(self.alumni) + ')' def safe_form(self): code = self.code[:-self.STRENGTH] + 'x' * (self.STRENGTH - 4 ) + self.code[-4:] return unicode(code) def is_enabled(self): return self.status == self.STATUS_OK def is_temporary(self): return self.application_id is not None def disable(self, at=None): if at is None: at = timezone.now() self.status = self.STATUS_DISABLED if at > timezone.now(): at = timezone.now() if self.disabled_at is None or self.disabled_at > at: self.disabled_at = at def merge_to(self, other_code, session): link = invite_links(code_from=self, code_to=other_code, is_merged_to=True, session=session) link.save() def verbose_status(self): if self.status == self.STATUS_OK: return 'ok' if self.status == self.STATUS_DISABLED: return 'disabled' if self.status == self.STATUS_BANNED: return 'banned' return None def expires_at_timestamp(self): if self.expires_at is not None: return time.mktime(self.expires_at.timetuple()) return None def ensure_expires_after(self, valid_for): expires_at = datetime.datetime.now() + datetime.timedelta(seconds= valid_for) if expires_at > self.expires_at: self.expires_at = expires_at self.save() class invite_links(models.Model): code_to = models.ForeignKey(invites, related_name='invite_links_to') code_from = models.ForeignKey(invites, related_name='invite_links_from') is_issued_by = models.BooleanField(default=False) is_merged_to = models.BooleanField(default=False) is_temporary_for = models.BooleanField(default=False) add_time = models.DateTimeField(auto_now_add=True) session = models.CharField(max_length=100, null=True, blank=True) class Meta: verbose_name = 'Invite link' verbose_name_plural = 'Invite links' def __unicode__(self): return unicode(self.code_from) + ' -> ' + unicode(self.code_to) <|reserved_special_token_1|> import datetime from random import SystemRandom import re import string import time from django.db import models from django.utils import timezone from app.translit import translit # Each model extends models.Model class alumni(models.Model): alumnus_id = models.AutoField(primary_key=True) full_name = models.CharField(max_length=150) year = models.IntegerField() letter = models.CharField(max_length=2) add_time = models.DateTimeField(auto_now_add=True) added_by = models.CharField(max_length=50) class Meta: verbose_name = 'Alumnus' verbose_name_plural = 'Alumni' def __unicode__(self): return self.full_name + ", " + unicode(self.year) + self.letter class Application(models.Model): slug = models.SlugField() name = models.CharField(max_length=200) url = models.URLField() disabled = models.BooleanField(default=False) valid_for = models.PositiveIntegerField() def __unicode__(self): return self.slug class invites(models.Model): PREFIX = '57' STRENGTH = 16 STATUS_OK = 1 STATUS_DISABLED = 2 STATUS_BANNED = 3 STATUSES = ( (1, 'OK'), (2, 'DISABLED'), (3, 'BANNED'), ) code = models.CharField(max_length=255) alumni = models.ForeignKey(alumni) application = models.ForeignKey(Application, null=True, blank=True) add_time = models.DateTimeField(auto_now_add=True) status = models.SmallIntegerField(choices=STATUSES, default=STATUS_OK) disabled_at = models.DateTimeField(null=True, blank=True) expires_at = models.DateTimeField(null=True, blank=True) used_at = models.DateTimeField(null=True, blank=True) @classmethod def temporary_for(cls, invite, application, valid_for, session): try: new_code = invite_links.objects.get( code_from_id=invite.id, is_temporary_for=True, code_to__application_id=application.id ).code_to if valid_for is not None: new_code.ensure_expires_after(valid_for) return new_code except invite_links.DoesNotExist: pass if valid_for is None: valid_for = application.valid_for expires_at = datetime.datetime.now() + datetime.timedelta(seconds=valid_for) new_code = invites(application=application, alumni_id=invite.alumni_id, expires_at=expires_at, used_at=datetime.datetime.now()) new_code.code += '-' + application.slug new_code.save() link = invite_links(code_from=invite, code_to=new_code, session=session, is_temporary_for=True) link.save() return new_code def __init__(self, *args, **kwargs): super(invites, self).__init__(*args, **kwargs) if not self.code and self.alumni_id: code = [self.PREFIX, str(self.alumni.year) + translit(self.alumni.letter).lower()] full_name = re.sub(r'\([^)]*\)\s+', '', self.alumni.full_name) surname, name = full_name.split(' ', 1) code.append(translit(surname[:3]).lower() + translit(name[0]).lower()) csprng = SystemRandom() code.append(''.join(csprng.choice(string.digits) for _ in range(self.STRENGTH))) self.code = "-".join(code) class Meta: verbose_name = 'Invite' verbose_name_plural = 'Invites' def __unicode__(self): return unicode(self.code) + " (" + unicode(self.alumni) + ")" def safe_form(self): code = self.code[:-self.STRENGTH] + 'x' * (self.STRENGTH-4) + self.code[-4:] return unicode(code) def is_enabled(self): return self.status == self.STATUS_OK def is_temporary(self): return self.application_id is not None def disable(self, at=None): if at is None: at = timezone.now() self.status = self.STATUS_DISABLED if at > timezone.now(): at = timezone.now() if self.disabled_at is None or self.disabled_at > at: self.disabled_at = at def merge_to(self, other_code, session): link = invite_links(code_from=self, code_to=other_code, is_merged_to=True, session=session) link.save() def verbose_status(self): if self.status == self.STATUS_OK: return 'ok' if self.status == self.STATUS_DISABLED: return 'disabled' if self.status == self.STATUS_BANNED: return 'banned' return None def expires_at_timestamp(self): if self.expires_at is not None: return time.mktime(self.expires_at.timetuple()) return None def ensure_expires_after(self, valid_for): expires_at = datetime.datetime.now() + datetime.timedelta(seconds=valid_for) if expires_at > self.expires_at: self.expires_at = expires_at self.save() class invite_links(models.Model): code_to = models.ForeignKey(invites, related_name="invite_links_to") code_from = models.ForeignKey(invites, related_name="invite_links_from") is_issued_by = models.BooleanField(default=False) is_merged_to = models.BooleanField(default=False) is_temporary_for = models.BooleanField(default=False) add_time = models.DateTimeField(auto_now_add=True) session = models.CharField(max_length=100, null=True, blank=True) class Meta: verbose_name = 'Invite link' verbose_name_plural = 'Invite links' def __unicode__(self): return unicode(self.code_from) + " -> " + unicode(self.code_to) # class Usage(models.Model): # code = models.ForeignKey(invites)
flexible
{ "blob_id": "192e789129a51aa646a925fc4f8c3f8f4e14d478", "index": 7988, "step-1": "<mask token>\n\n\nclass invites(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, *args, **kwargs):\n super(invites, self).__init__(*args, **kwargs)\n if not self.code and self.alumni_id:\n code = [self.PREFIX, str(self.alumni.year) + translit(self.\n alumni.letter).lower()]\n full_name = re.sub('\\\\([^)]*\\\\)\\\\s+', '', self.alumni.full_name)\n surname, name = full_name.split(' ', 1)\n code.append(translit(surname[:3]).lower() + translit(name[0]).\n lower())\n csprng = SystemRandom()\n code.append(''.join(csprng.choice(string.digits) for _ in range\n (self.STRENGTH)))\n self.code = '-'.join(code)\n\n\n class Meta:\n verbose_name = 'Invite'\n verbose_name_plural = 'Invites'\n\n def __unicode__(self):\n return unicode(self.code) + ' (' + unicode(self.alumni) + ')'\n\n def safe_form(self):\n code = self.code[:-self.STRENGTH] + 'x' * (self.STRENGTH - 4\n ) + self.code[-4:]\n return unicode(code)\n\n def is_enabled(self):\n return self.status == self.STATUS_OK\n\n def is_temporary(self):\n return self.application_id is not None\n\n def disable(self, at=None):\n if at is None:\n at = timezone.now()\n self.status = self.STATUS_DISABLED\n if at > timezone.now():\n at = timezone.now()\n if self.disabled_at is None or self.disabled_at > at:\n self.disabled_at = at\n\n def merge_to(self, other_code, session):\n link = invite_links(code_from=self, code_to=other_code,\n is_merged_to=True, session=session)\n link.save()\n\n def verbose_status(self):\n if self.status == self.STATUS_OK:\n return 'ok'\n if self.status == self.STATUS_DISABLED:\n return 'disabled'\n if self.status == self.STATUS_BANNED:\n return 'banned'\n return None\n <mask token>\n\n def ensure_expires_after(self, valid_for):\n expires_at = datetime.datetime.now() + datetime.timedelta(seconds=\n valid_for)\n if expires_at > self.expires_at:\n self.expires_at = expires_at\n self.save()\n\n\nclass invite_links(models.Model):\n code_to = models.ForeignKey(invites, related_name='invite_links_to')\n code_from = models.ForeignKey(invites, related_name='invite_links_from')\n is_issued_by = models.BooleanField(default=False)\n is_merged_to = models.BooleanField(default=False)\n is_temporary_for = models.BooleanField(default=False)\n add_time = models.DateTimeField(auto_now_add=True)\n session = models.CharField(max_length=100, null=True, blank=True)\n\n\n class Meta:\n verbose_name = 'Invite link'\n verbose_name_plural = 'Invite links'\n\n def __unicode__(self):\n return unicode(self.code_from) + ' -> ' + unicode(self.code_to)\n", "step-2": "<mask token>\n\n\nclass invites(models.Model):\n PREFIX = '57'\n STRENGTH = 16\n STATUS_OK = 1\n STATUS_DISABLED = 2\n STATUS_BANNED = 3\n STATUSES = (1, 'OK'), (2, 'DISABLED'), (3, 'BANNED')\n code = models.CharField(max_length=255)\n alumni = models.ForeignKey(alumni)\n application = models.ForeignKey(Application, null=True, blank=True)\n add_time = models.DateTimeField(auto_now_add=True)\n status = models.SmallIntegerField(choices=STATUSES, default=STATUS_OK)\n disabled_at = models.DateTimeField(null=True, blank=True)\n expires_at = models.DateTimeField(null=True, blank=True)\n used_at = models.DateTimeField(null=True, blank=True)\n\n @classmethod\n def temporary_for(cls, invite, application, valid_for, session):\n try:\n new_code = invite_links.objects.get(code_from_id=invite.id,\n is_temporary_for=True, code_to__application_id=application.id\n ).code_to\n if valid_for is not None:\n new_code.ensure_expires_after(valid_for)\n return new_code\n except invite_links.DoesNotExist:\n pass\n if valid_for is None:\n valid_for = application.valid_for\n expires_at = datetime.datetime.now() + datetime.timedelta(seconds=\n valid_for)\n new_code = invites(application=application, alumni_id=invite.\n alumni_id, expires_at=expires_at, used_at=datetime.datetime.now())\n new_code.code += '-' + application.slug\n new_code.save()\n link = invite_links(code_from=invite, code_to=new_code, session=\n session, is_temporary_for=True)\n link.save()\n return new_code\n\n def __init__(self, *args, **kwargs):\n super(invites, self).__init__(*args, **kwargs)\n if not self.code and self.alumni_id:\n code = [self.PREFIX, str(self.alumni.year) + translit(self.\n alumni.letter).lower()]\n full_name = re.sub('\\\\([^)]*\\\\)\\\\s+', '', self.alumni.full_name)\n surname, name = full_name.split(' ', 1)\n code.append(translit(surname[:3]).lower() + translit(name[0]).\n lower())\n csprng = SystemRandom()\n code.append(''.join(csprng.choice(string.digits) for _ in range\n (self.STRENGTH)))\n self.code = '-'.join(code)\n\n\n class Meta:\n verbose_name = 'Invite'\n verbose_name_plural = 'Invites'\n\n def __unicode__(self):\n return unicode(self.code) + ' (' + unicode(self.alumni) + ')'\n\n def safe_form(self):\n code = self.code[:-self.STRENGTH] + 'x' * (self.STRENGTH - 4\n ) + self.code[-4:]\n return unicode(code)\n\n def is_enabled(self):\n return self.status == self.STATUS_OK\n\n def is_temporary(self):\n return self.application_id is not None\n\n def disable(self, at=None):\n if at is None:\n at = timezone.now()\n self.status = self.STATUS_DISABLED\n if at > timezone.now():\n at = timezone.now()\n if self.disabled_at is None or self.disabled_at > at:\n self.disabled_at = at\n\n def merge_to(self, other_code, session):\n link = invite_links(code_from=self, code_to=other_code,\n is_merged_to=True, session=session)\n link.save()\n\n def verbose_status(self):\n if self.status == self.STATUS_OK:\n return 'ok'\n if self.status == self.STATUS_DISABLED:\n return 'disabled'\n if self.status == self.STATUS_BANNED:\n return 'banned'\n return None\n\n def expires_at_timestamp(self):\n if self.expires_at is not None:\n return time.mktime(self.expires_at.timetuple())\n return None\n\n def ensure_expires_after(self, valid_for):\n expires_at = datetime.datetime.now() + datetime.timedelta(seconds=\n valid_for)\n if expires_at > self.expires_at:\n self.expires_at = expires_at\n self.save()\n\n\nclass invite_links(models.Model):\n code_to = models.ForeignKey(invites, related_name='invite_links_to')\n code_from = models.ForeignKey(invites, related_name='invite_links_from')\n is_issued_by = models.BooleanField(default=False)\n is_merged_to = models.BooleanField(default=False)\n is_temporary_for = models.BooleanField(default=False)\n add_time = models.DateTimeField(auto_now_add=True)\n session = models.CharField(max_length=100, null=True, blank=True)\n\n\n class Meta:\n verbose_name = 'Invite link'\n verbose_name_plural = 'Invite links'\n\n def __unicode__(self):\n return unicode(self.code_from) + ' -> ' + unicode(self.code_to)\n", "step-3": "<mask token>\n\n\nclass Application(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __unicode__(self):\n return self.slug\n\n\nclass invites(models.Model):\n PREFIX = '57'\n STRENGTH = 16\n STATUS_OK = 1\n STATUS_DISABLED = 2\n STATUS_BANNED = 3\n STATUSES = (1, 'OK'), (2, 'DISABLED'), (3, 'BANNED')\n code = models.CharField(max_length=255)\n alumni = models.ForeignKey(alumni)\n application = models.ForeignKey(Application, null=True, blank=True)\n add_time = models.DateTimeField(auto_now_add=True)\n status = models.SmallIntegerField(choices=STATUSES, default=STATUS_OK)\n disabled_at = models.DateTimeField(null=True, blank=True)\n expires_at = models.DateTimeField(null=True, blank=True)\n used_at = models.DateTimeField(null=True, blank=True)\n\n @classmethod\n def temporary_for(cls, invite, application, valid_for, session):\n try:\n new_code = invite_links.objects.get(code_from_id=invite.id,\n is_temporary_for=True, code_to__application_id=application.id\n ).code_to\n if valid_for is not None:\n new_code.ensure_expires_after(valid_for)\n return new_code\n except invite_links.DoesNotExist:\n pass\n if valid_for is None:\n valid_for = application.valid_for\n expires_at = datetime.datetime.now() + datetime.timedelta(seconds=\n valid_for)\n new_code = invites(application=application, alumni_id=invite.\n alumni_id, expires_at=expires_at, used_at=datetime.datetime.now())\n new_code.code += '-' + application.slug\n new_code.save()\n link = invite_links(code_from=invite, code_to=new_code, session=\n session, is_temporary_for=True)\n link.save()\n return new_code\n\n def __init__(self, *args, **kwargs):\n super(invites, self).__init__(*args, **kwargs)\n if not self.code and self.alumni_id:\n code = [self.PREFIX, str(self.alumni.year) + translit(self.\n alumni.letter).lower()]\n full_name = re.sub('\\\\([^)]*\\\\)\\\\s+', '', self.alumni.full_name)\n surname, name = full_name.split(' ', 1)\n code.append(translit(surname[:3]).lower() + translit(name[0]).\n lower())\n csprng = SystemRandom()\n code.append(''.join(csprng.choice(string.digits) for _ in range\n (self.STRENGTH)))\n self.code = '-'.join(code)\n\n\n class Meta:\n verbose_name = 'Invite'\n verbose_name_plural = 'Invites'\n\n def __unicode__(self):\n return unicode(self.code) + ' (' + unicode(self.alumni) + ')'\n\n def safe_form(self):\n code = self.code[:-self.STRENGTH] + 'x' * (self.STRENGTH - 4\n ) + self.code[-4:]\n return unicode(code)\n\n def is_enabled(self):\n return self.status == self.STATUS_OK\n\n def is_temporary(self):\n return self.application_id is not None\n\n def disable(self, at=None):\n if at is None:\n at = timezone.now()\n self.status = self.STATUS_DISABLED\n if at > timezone.now():\n at = timezone.now()\n if self.disabled_at is None or self.disabled_at > at:\n self.disabled_at = at\n\n def merge_to(self, other_code, session):\n link = invite_links(code_from=self, code_to=other_code,\n is_merged_to=True, session=session)\n link.save()\n\n def verbose_status(self):\n if self.status == self.STATUS_OK:\n return 'ok'\n if self.status == self.STATUS_DISABLED:\n return 'disabled'\n if self.status == self.STATUS_BANNED:\n return 'banned'\n return None\n\n def expires_at_timestamp(self):\n if self.expires_at is not None:\n return time.mktime(self.expires_at.timetuple())\n return None\n\n def ensure_expires_after(self, valid_for):\n expires_at = datetime.datetime.now() + datetime.timedelta(seconds=\n valid_for)\n if expires_at > self.expires_at:\n self.expires_at = expires_at\n self.save()\n\n\nclass invite_links(models.Model):\n code_to = models.ForeignKey(invites, related_name='invite_links_to')\n code_from = models.ForeignKey(invites, related_name='invite_links_from')\n is_issued_by = models.BooleanField(default=False)\n is_merged_to = models.BooleanField(default=False)\n is_temporary_for = models.BooleanField(default=False)\n add_time = models.DateTimeField(auto_now_add=True)\n session = models.CharField(max_length=100, null=True, blank=True)\n\n\n class Meta:\n verbose_name = 'Invite link'\n verbose_name_plural = 'Invite links'\n\n def __unicode__(self):\n return unicode(self.code_from) + ' -> ' + unicode(self.code_to)\n", "step-4": "<mask token>\n\n\nclass alumni(models.Model):\n alumnus_id = models.AutoField(primary_key=True)\n full_name = models.CharField(max_length=150)\n year = models.IntegerField()\n letter = models.CharField(max_length=2)\n add_time = models.DateTimeField(auto_now_add=True)\n added_by = models.CharField(max_length=50)\n\n\n class Meta:\n verbose_name = 'Alumnus'\n verbose_name_plural = 'Alumni'\n\n def __unicode__(self):\n return self.full_name + ', ' + unicode(self.year) + self.letter\n\n\nclass Application(models.Model):\n slug = models.SlugField()\n name = models.CharField(max_length=200)\n url = models.URLField()\n disabled = models.BooleanField(default=False)\n valid_for = models.PositiveIntegerField()\n\n def __unicode__(self):\n return self.slug\n\n\nclass invites(models.Model):\n PREFIX = '57'\n STRENGTH = 16\n STATUS_OK = 1\n STATUS_DISABLED = 2\n STATUS_BANNED = 3\n STATUSES = (1, 'OK'), (2, 'DISABLED'), (3, 'BANNED')\n code = models.CharField(max_length=255)\n alumni = models.ForeignKey(alumni)\n application = models.ForeignKey(Application, null=True, blank=True)\n add_time = models.DateTimeField(auto_now_add=True)\n status = models.SmallIntegerField(choices=STATUSES, default=STATUS_OK)\n disabled_at = models.DateTimeField(null=True, blank=True)\n expires_at = models.DateTimeField(null=True, blank=True)\n used_at = models.DateTimeField(null=True, blank=True)\n\n @classmethod\n def temporary_for(cls, invite, application, valid_for, session):\n try:\n new_code = invite_links.objects.get(code_from_id=invite.id,\n is_temporary_for=True, code_to__application_id=application.id\n ).code_to\n if valid_for is not None:\n new_code.ensure_expires_after(valid_for)\n return new_code\n except invite_links.DoesNotExist:\n pass\n if valid_for is None:\n valid_for = application.valid_for\n expires_at = datetime.datetime.now() + datetime.timedelta(seconds=\n valid_for)\n new_code = invites(application=application, alumni_id=invite.\n alumni_id, expires_at=expires_at, used_at=datetime.datetime.now())\n new_code.code += '-' + application.slug\n new_code.save()\n link = invite_links(code_from=invite, code_to=new_code, session=\n session, is_temporary_for=True)\n link.save()\n return new_code\n\n def __init__(self, *args, **kwargs):\n super(invites, self).__init__(*args, **kwargs)\n if not self.code and self.alumni_id:\n code = [self.PREFIX, str(self.alumni.year) + translit(self.\n alumni.letter).lower()]\n full_name = re.sub('\\\\([^)]*\\\\)\\\\s+', '', self.alumni.full_name)\n surname, name = full_name.split(' ', 1)\n code.append(translit(surname[:3]).lower() + translit(name[0]).\n lower())\n csprng = SystemRandom()\n code.append(''.join(csprng.choice(string.digits) for _ in range\n (self.STRENGTH)))\n self.code = '-'.join(code)\n\n\n class Meta:\n verbose_name = 'Invite'\n verbose_name_plural = 'Invites'\n\n def __unicode__(self):\n return unicode(self.code) + ' (' + unicode(self.alumni) + ')'\n\n def safe_form(self):\n code = self.code[:-self.STRENGTH] + 'x' * (self.STRENGTH - 4\n ) + self.code[-4:]\n return unicode(code)\n\n def is_enabled(self):\n return self.status == self.STATUS_OK\n\n def is_temporary(self):\n return self.application_id is not None\n\n def disable(self, at=None):\n if at is None:\n at = timezone.now()\n self.status = self.STATUS_DISABLED\n if at > timezone.now():\n at = timezone.now()\n if self.disabled_at is None or self.disabled_at > at:\n self.disabled_at = at\n\n def merge_to(self, other_code, session):\n link = invite_links(code_from=self, code_to=other_code,\n is_merged_to=True, session=session)\n link.save()\n\n def verbose_status(self):\n if self.status == self.STATUS_OK:\n return 'ok'\n if self.status == self.STATUS_DISABLED:\n return 'disabled'\n if self.status == self.STATUS_BANNED:\n return 'banned'\n return None\n\n def expires_at_timestamp(self):\n if self.expires_at is not None:\n return time.mktime(self.expires_at.timetuple())\n return None\n\n def ensure_expires_after(self, valid_for):\n expires_at = datetime.datetime.now() + datetime.timedelta(seconds=\n valid_for)\n if expires_at > self.expires_at:\n self.expires_at = expires_at\n self.save()\n\n\nclass invite_links(models.Model):\n code_to = models.ForeignKey(invites, related_name='invite_links_to')\n code_from = models.ForeignKey(invites, related_name='invite_links_from')\n is_issued_by = models.BooleanField(default=False)\n is_merged_to = models.BooleanField(default=False)\n is_temporary_for = models.BooleanField(default=False)\n add_time = models.DateTimeField(auto_now_add=True)\n session = models.CharField(max_length=100, null=True, blank=True)\n\n\n class Meta:\n verbose_name = 'Invite link'\n verbose_name_plural = 'Invite links'\n\n def __unicode__(self):\n return unicode(self.code_from) + ' -> ' + unicode(self.code_to)\n", "step-5": "import datetime\nfrom random import SystemRandom\nimport re\nimport string\nimport time\n\nfrom django.db import models\nfrom django.utils import timezone\n\nfrom app.translit import translit\n\n\n# Each model extends models.Model\nclass alumni(models.Model):\n alumnus_id = models.AutoField(primary_key=True)\n full_name = models.CharField(max_length=150)\n year = models.IntegerField()\n letter = models.CharField(max_length=2)\n add_time = models.DateTimeField(auto_now_add=True)\n added_by = models.CharField(max_length=50)\n\n class Meta:\n verbose_name = 'Alumnus'\n verbose_name_plural = 'Alumni'\n\n def __unicode__(self):\n return self.full_name + \", \" + unicode(self.year) + self.letter\n\n\nclass Application(models.Model):\n slug = models.SlugField()\n name = models.CharField(max_length=200)\n url = models.URLField()\n disabled = models.BooleanField(default=False)\n valid_for = models.PositiveIntegerField()\n\n def __unicode__(self):\n return self.slug\n\n\nclass invites(models.Model):\n PREFIX = '57'\n STRENGTH = 16\n STATUS_OK = 1\n STATUS_DISABLED = 2\n STATUS_BANNED = 3\n STATUSES = (\n (1, 'OK'),\n (2, 'DISABLED'),\n (3, 'BANNED'),\n )\n\n code = models.CharField(max_length=255)\n alumni = models.ForeignKey(alumni)\n application = models.ForeignKey(Application, null=True, blank=True)\n add_time = models.DateTimeField(auto_now_add=True)\n status = models.SmallIntegerField(choices=STATUSES, default=STATUS_OK)\n disabled_at = models.DateTimeField(null=True, blank=True)\n expires_at = models.DateTimeField(null=True, blank=True)\n used_at = models.DateTimeField(null=True, blank=True)\n\n @classmethod\n def temporary_for(cls, invite, application, valid_for, session):\n try:\n new_code = invite_links.objects.get(\n code_from_id=invite.id,\n is_temporary_for=True,\n code_to__application_id=application.id\n ).code_to\n if valid_for is not None:\n new_code.ensure_expires_after(valid_for)\n return new_code\n except invite_links.DoesNotExist:\n pass\n\n if valid_for is None:\n valid_for = application.valid_for\n\n expires_at = datetime.datetime.now() + datetime.timedelta(seconds=valid_for)\n new_code = invites(application=application, alumni_id=invite.alumni_id, expires_at=expires_at, used_at=datetime.datetime.now())\n new_code.code += '-' + application.slug\n new_code.save()\n link = invite_links(code_from=invite, code_to=new_code, session=session, is_temporary_for=True)\n link.save()\n return new_code\n\n def __init__(self, *args, **kwargs):\n super(invites, self).__init__(*args, **kwargs)\n if not self.code and self.alumni_id:\n code = [self.PREFIX, str(self.alumni.year) + translit(self.alumni.letter).lower()]\n full_name = re.sub(r'\\([^)]*\\)\\s+', '', self.alumni.full_name)\n surname, name = full_name.split(' ', 1)\n code.append(translit(surname[:3]).lower() + translit(name[0]).lower())\n csprng = SystemRandom()\n code.append(''.join(csprng.choice(string.digits) for _ in range(self.STRENGTH)))\n self.code = \"-\".join(code)\n\n class Meta:\n verbose_name = 'Invite'\n verbose_name_plural = 'Invites'\n\n def __unicode__(self):\n return unicode(self.code) + \" (\" + unicode(self.alumni) + \")\"\n\n def safe_form(self):\n code = self.code[:-self.STRENGTH] + 'x' * (self.STRENGTH-4) + self.code[-4:]\n return unicode(code)\n\n def is_enabled(self):\n return self.status == self.STATUS_OK\n\n def is_temporary(self):\n return self.application_id is not None\n\n def disable(self, at=None):\n if at is None:\n at = timezone.now()\n\n self.status = self.STATUS_DISABLED\n if at > timezone.now():\n at = timezone.now()\n if self.disabled_at is None or self.disabled_at > at:\n self.disabled_at = at\n\n def merge_to(self, other_code, session):\n link = invite_links(code_from=self, code_to=other_code, is_merged_to=True, session=session)\n link.save()\n\n def verbose_status(self):\n if self.status == self.STATUS_OK:\n return 'ok'\n if self.status == self.STATUS_DISABLED:\n return 'disabled'\n if self.status == self.STATUS_BANNED:\n return 'banned'\n return None\n\n def expires_at_timestamp(self):\n if self.expires_at is not None:\n return time.mktime(self.expires_at.timetuple())\n return None\n\n def ensure_expires_after(self, valid_for):\n expires_at = datetime.datetime.now() + datetime.timedelta(seconds=valid_for)\n if expires_at > self.expires_at:\n self.expires_at = expires_at\n self.save()\n\n\nclass invite_links(models.Model):\n code_to = models.ForeignKey(invites, related_name=\"invite_links_to\")\n code_from = models.ForeignKey(invites, related_name=\"invite_links_from\")\n is_issued_by = models.BooleanField(default=False)\n is_merged_to = models.BooleanField(default=False)\n is_temporary_for = models.BooleanField(default=False)\n add_time = models.DateTimeField(auto_now_add=True)\n session = models.CharField(max_length=100, null=True, blank=True)\n\n class Meta:\n verbose_name = 'Invite link'\n verbose_name_plural = 'Invite links'\n\n def __unicode__(self):\n return unicode(self.code_from) + \" -> \" + unicode(self.code_to)\n\n\n# class Usage(models.Model):\n# code = models.ForeignKey(invites)\n", "step-ids": [ 13, 16, 18, 22, 24 ] }
[ 13, 16, 18, 22, 24 ]
#!/usr/bin/env python # coding:utf-8 import time from SocketServer import (TCPServer as TCP, StreamRequestHandler as SRH) HOST = '127.0.0.1' PORT = 8888 BUFSIZE = 1024 ADDR = (HOST, PORT) class MyRequestHandler(SRH): def handle(self): print '...connected from :', self.client_address self.wfile.write('[%s] %s' % (time.ctime(), self.rfile.readline())) tcpServ = TCP(ADDR, MyRequestHandler) print 'waiting for connection...' tcpServ.serve_forever( )
normal
{ "blob_id": "377143635939cf113e4188b5c4f55cec068a17b1", "index": 4171, "step-1": "#!/usr/bin/env python\n# coding:utf-8\nimport time\nfrom SocketServer import (TCPServer as TCP,\n StreamRequestHandler as SRH)\n\nHOST = '127.0.0.1'\nPORT = 8888\nBUFSIZE = 1024\nADDR = (HOST, PORT)\n\nclass MyRequestHandler(SRH):\n def handle(self):\n print '...connected from :', self.client_address\n self.wfile.write('[%s] %s' % (time.ctime(), \n self.rfile.readline()))\n \ntcpServ = TCP(ADDR, MyRequestHandler)\nprint 'waiting for connection...'\ntcpServ.serve_forever( )", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 11 14:55:12 2019 @author: Furankyyy """ import numpy as np import matplotlib.pyplot as plt import timeit ###worst sort function### #define the function that checks whether the list is in ascending order def right_permutation(arr): if len(arr)==1: #if there's only one element, then the order is always correct return True for i in range(len(arr)-1): #check every elements from the first to the second to the last if arr[i+1]<arr[i]: #if the i+1th element is smaller than ith, the order is wrong, break the loop and return false break else: if i == len(arr)-2: #if the i+1th element is greater than/equal to ith, check if we have already checked all the elements return True #if we've already checked all the elements (i.e. i==len(arr)-2), return true; if not, continue the loop return False #define the worst sort function def worstsort(arr): sort_arr=[] #initialize output check = False #initialize the result of right_permutation() while check == False: #while the order is wrong, generate a new permyutation and check if its order is correct sort_arr = np.random.permutation(arr) check = right_permutation(sort_arr) return sort_arr #test cases test1=[5,4,3,2,1] test2=[1,2,3,4,5] #best case test3=[2,2,2,2,2] #best case as well! test4=[2] #only one element print(worstsort(test1)) print(worstsort(test2)) print(worstsort(test3)) print(worstsort(test4)) #the best case is when the input list is already sorted, in this case, we only need to run the right_permutation once #we have a for loop in right_permutation, so the best case complexity is O(n) #given a random input of size n, the chance that the input x_k is correctly sorted is Pr(x_k) = 1/P_n = 1/n! #since in this worst algorithm, we do not "remember" the permutations that we've already checked #so each time, the Pr(sorted) remains the same 1/n! #Then we would expect to have n! times to have the corrected sorted list #the reason is that we have E[Pr(x1)+Pr(x2)+...+Pr(x_k)]=1, since Pr(x_k)=1/n!, we would expect k = n! #this reasoning is the same as the random indicator variable in the book, where we have the pr(I) for each choice (permutation) and we sum them to find the expected value #so the averaage case complexity is O(n!) #to calculate what n is best for this function def factorial(n): result=1 for i in range(n): result=result*(i+1) return result x=np.arange(0,7,1) y_factorial=list(map(factorial,x)) y_compare=x*x plt.plot(x,y_factorial,label="Factorial of n") plt.plot(x,y_compare,label="n square") plt.title("Complexity comparison") plt.legend() #from the plot we can see that for algorithms with comlexity of O(n^2) and O(n!), the difference comes when n=5 #when n=4, the two algorithms do not vary that much, but when n=5, they have a >100 times difference #therefore, this method is feasible when n<=4 #p.s. constants are discounted (they are relatively unimportant) ###median finder### #the worst case for the median finder is that the elements in the input list are unique #the best case is that all elements are the same --> no matter which we choose, it is the median #to consider the times we try before stopping, we need to consider the worst case --> all elements are different #then the chance to find the exact median is 1/n #the number of elements lying in the input deviation range x is x//(100/n)+1 for this worst case #explanation: divide the 100% to n parts, if all elements are different then each element takes the 1 part, the x//(range for 1 part)+1 is the num of elements lying in the range #therefore, the probability of choosing the element in the range given by x is (x//(100/n)+1)/n #I want to try the expected times of choosing the correct element(s) for the worst case #Pr(failure) for 1 try is 1-(x//(100/n)+1)/n #Pr(failure) for the first k try is (1-(x//(100/n)+1)/n)^k, which scales with x and n. #so the Pr(at least one success) for the first k try is 1-Pr(failure)=1-(1-(x//(100/n)+1)/n)^k #we want to find a k taht makes this Pr large enough #so we want to find a small k minimizing Pr(failure) for the first k try #to simplify the problem, we regard x as constant and assume the "//" is "/" #(1-(x//(100/n)+1)/n)^k = ((n-xn/100-1)/n)^k =(1-x/100-1/n)^k #x/100 is a constant #-->(1-1/n)^k #when n is sufficiently large, (1-1/n) is nearly 1 #it is extremely hard to succeed if n is very large, I set the limit of k at 10000, simply because my laptop's computational ability def median_finder(arr,x): tried = 0 #record the number of times of choosing the random element if abs(x) <= 0.5: #when x is valid lower=np.percentile(arr,50-x/2) upper=np.percentile(arr,50+x/2) while tried <10000: find = np.random.randint(0,len(arr)) #find a new element if lower<=arr[find] and arr[find]<=upper: #if the chosen element is in the range, return it return arr[find] else: tried += 1 return "Tried enough times, still cannot find the value" else: return "x not in the domain" #test cases test1=list(np.random.permutation(200)) test2=[4]*100 test3=[5]*1000 test4=test2+test3 print(median_finder(test1,0.5)) #worst case, exactly 2 elements in the range print(median_finder(test2,0.5)) #best case print(median_finder(test2,0)) #best case print(median_finder(test3,0.5)) #best case print(median_finder(test4,0)) #1000/1100 probability print(median_finder(test4,0.5)) #same as above. #time complexity #best case running time is O(1) #the time complexity of the worst case running time is E[k]=Sum(E[ki]) #E[ki]=Pr(correct)=(x//(100/n)+1)/n #sum is from 1 to the limit tried k #since x is between 0 and 0.5, we simply regard it as constant #we also assume the "//" is "/" #then the expression becomes: E[k]= k*(xn/100+1)/n #as n goes to infinity, we can solve this by trying to use L'Hopital's rule #the result is kx/100, which is a constant #O(1) data=np.empty((1,2)) for i in range(200,1200,50): testlist=list(np.random.permutation(i)) time=timeit.timeit(stmt="median_finder(testlist,0.5)",setup="from __main__ import median_finder,testlist",number=100) time=time/100 stack=np.array((time,i)) data=np.vstack((data,stack)) data=data[1:] plt.figure() plt.ylim(0,0.01) plt.scatter(x=data[:,1],y=data[:,0]) plt.xlabel("Inputsize") plt.ylabel("Running time") plt.title("Median finder running time") #from the plot we can see that the running time is almost constant --> O(1) #space complexity is O(n), because each time we just store the (sorted) list of length n
normal
{ "blob_id": "7c82565a4184b2e779e2bb6ba70b497cc287af35", "index": 5285, "step-1": "<mask token>\n\n\ndef right_permutation(arr):\n if len(arr) == 1:\n return True\n for i in range(len(arr) - 1):\n if arr[i + 1] < arr[i]:\n break\n elif i == len(arr) - 2:\n return True\n return False\n\n\ndef worstsort(arr):\n sort_arr = []\n check = False\n while check == False:\n sort_arr = np.random.permutation(arr)\n check = right_permutation(sort_arr)\n return sort_arr\n\n\n<mask token>\n\n\ndef factorial(n):\n result = 1\n for i in range(n):\n result = result * (i + 1)\n return result\n\n\n<mask token>\n\n\ndef median_finder(arr, x):\n tried = 0\n if abs(x) <= 0.5:\n lower = np.percentile(arr, 50 - x / 2)\n upper = np.percentile(arr, 50 + x / 2)\n while tried < 10000:\n find = np.random.randint(0, len(arr))\n if lower <= arr[find] and arr[find] <= upper:\n return arr[find]\n else:\n tried += 1\n return 'Tried enough times, still cannot find the value'\n else:\n return 'x not in the domain'\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef right_permutation(arr):\n if len(arr) == 1:\n return True\n for i in range(len(arr) - 1):\n if arr[i + 1] < arr[i]:\n break\n elif i == len(arr) - 2:\n return True\n return False\n\n\ndef worstsort(arr):\n sort_arr = []\n check = False\n while check == False:\n sort_arr = np.random.permutation(arr)\n check = right_permutation(sort_arr)\n return sort_arr\n\n\n<mask token>\nprint(worstsort(test1))\nprint(worstsort(test2))\nprint(worstsort(test3))\nprint(worstsort(test4))\n\n\ndef factorial(n):\n result = 1\n for i in range(n):\n result = result * (i + 1)\n return result\n\n\n<mask token>\nplt.plot(x, y_factorial, label='Factorial of n')\nplt.plot(x, y_compare, label='n square')\nplt.title('Complexity comparison')\nplt.legend()\n\n\ndef median_finder(arr, x):\n tried = 0\n if abs(x) <= 0.5:\n lower = np.percentile(arr, 50 - x / 2)\n upper = np.percentile(arr, 50 + x / 2)\n while tried < 10000:\n find = np.random.randint(0, len(arr))\n if lower <= arr[find] and arr[find] <= upper:\n return arr[find]\n else:\n tried += 1\n return 'Tried enough times, still cannot find the value'\n else:\n return 'x not in the domain'\n\n\n<mask token>\nprint(median_finder(test1, 0.5))\nprint(median_finder(test2, 0.5))\nprint(median_finder(test2, 0))\nprint(median_finder(test3, 0.5))\nprint(median_finder(test4, 0))\nprint(median_finder(test4, 0.5))\n<mask token>\nfor i in range(200, 1200, 50):\n testlist = list(np.random.permutation(i))\n time = timeit.timeit(stmt='median_finder(testlist,0.5)', setup=\n 'from __main__ import median_finder,testlist', number=100)\n time = time / 100\n stack = np.array((time, i))\n data = np.vstack((data, stack))\n<mask token>\nplt.figure()\nplt.ylim(0, 0.01)\nplt.scatter(x=data[:, 1], y=data[:, 0])\nplt.xlabel('Inputsize')\nplt.ylabel('Running time')\nplt.title('Median finder running time')\n", "step-3": "<mask token>\n\n\ndef right_permutation(arr):\n if len(arr) == 1:\n return True\n for i in range(len(arr) - 1):\n if arr[i + 1] < arr[i]:\n break\n elif i == len(arr) - 2:\n return True\n return False\n\n\ndef worstsort(arr):\n sort_arr = []\n check = False\n while check == False:\n sort_arr = np.random.permutation(arr)\n check = right_permutation(sort_arr)\n return sort_arr\n\n\ntest1 = [5, 4, 3, 2, 1]\ntest2 = [1, 2, 3, 4, 5]\ntest3 = [2, 2, 2, 2, 2]\ntest4 = [2]\nprint(worstsort(test1))\nprint(worstsort(test2))\nprint(worstsort(test3))\nprint(worstsort(test4))\n\n\ndef factorial(n):\n result = 1\n for i in range(n):\n result = result * (i + 1)\n return result\n\n\nx = np.arange(0, 7, 1)\ny_factorial = list(map(factorial, x))\ny_compare = x * x\nplt.plot(x, y_factorial, label='Factorial of n')\nplt.plot(x, y_compare, label='n square')\nplt.title('Complexity comparison')\nplt.legend()\n\n\ndef median_finder(arr, x):\n tried = 0\n if abs(x) <= 0.5:\n lower = np.percentile(arr, 50 - x / 2)\n upper = np.percentile(arr, 50 + x / 2)\n while tried < 10000:\n find = np.random.randint(0, len(arr))\n if lower <= arr[find] and arr[find] <= upper:\n return arr[find]\n else:\n tried += 1\n return 'Tried enough times, still cannot find the value'\n else:\n return 'x not in the domain'\n\n\ntest1 = list(np.random.permutation(200))\ntest2 = [4] * 100\ntest3 = [5] * 1000\ntest4 = test2 + test3\nprint(median_finder(test1, 0.5))\nprint(median_finder(test2, 0.5))\nprint(median_finder(test2, 0))\nprint(median_finder(test3, 0.5))\nprint(median_finder(test4, 0))\nprint(median_finder(test4, 0.5))\ndata = np.empty((1, 2))\nfor i in range(200, 1200, 50):\n testlist = list(np.random.permutation(i))\n time = timeit.timeit(stmt='median_finder(testlist,0.5)', setup=\n 'from __main__ import median_finder,testlist', number=100)\n time = time / 100\n stack = np.array((time, i))\n data = np.vstack((data, stack))\ndata = data[1:]\nplt.figure()\nplt.ylim(0, 0.01)\nplt.scatter(x=data[:, 1], y=data[:, 0])\nplt.xlabel('Inputsize')\nplt.ylabel('Running time')\nplt.title('Median finder running time')\n", "step-4": "<mask token>\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport timeit\n\n\ndef right_permutation(arr):\n if len(arr) == 1:\n return True\n for i in range(len(arr) - 1):\n if arr[i + 1] < arr[i]:\n break\n elif i == len(arr) - 2:\n return True\n return False\n\n\ndef worstsort(arr):\n sort_arr = []\n check = False\n while check == False:\n sort_arr = np.random.permutation(arr)\n check = right_permutation(sort_arr)\n return sort_arr\n\n\ntest1 = [5, 4, 3, 2, 1]\ntest2 = [1, 2, 3, 4, 5]\ntest3 = [2, 2, 2, 2, 2]\ntest4 = [2]\nprint(worstsort(test1))\nprint(worstsort(test2))\nprint(worstsort(test3))\nprint(worstsort(test4))\n\n\ndef factorial(n):\n result = 1\n for i in range(n):\n result = result * (i + 1)\n return result\n\n\nx = np.arange(0, 7, 1)\ny_factorial = list(map(factorial, x))\ny_compare = x * x\nplt.plot(x, y_factorial, label='Factorial of n')\nplt.plot(x, y_compare, label='n square')\nplt.title('Complexity comparison')\nplt.legend()\n\n\ndef median_finder(arr, x):\n tried = 0\n if abs(x) <= 0.5:\n lower = np.percentile(arr, 50 - x / 2)\n upper = np.percentile(arr, 50 + x / 2)\n while tried < 10000:\n find = np.random.randint(0, len(arr))\n if lower <= arr[find] and arr[find] <= upper:\n return arr[find]\n else:\n tried += 1\n return 'Tried enough times, still cannot find the value'\n else:\n return 'x not in the domain'\n\n\ntest1 = list(np.random.permutation(200))\ntest2 = [4] * 100\ntest3 = [5] * 1000\ntest4 = test2 + test3\nprint(median_finder(test1, 0.5))\nprint(median_finder(test2, 0.5))\nprint(median_finder(test2, 0))\nprint(median_finder(test3, 0.5))\nprint(median_finder(test4, 0))\nprint(median_finder(test4, 0.5))\ndata = np.empty((1, 2))\nfor i in range(200, 1200, 50):\n testlist = list(np.random.permutation(i))\n time = timeit.timeit(stmt='median_finder(testlist,0.5)', setup=\n 'from __main__ import median_finder,testlist', number=100)\n time = time / 100\n stack = np.array((time, i))\n data = np.vstack((data, stack))\ndata = data[1:]\nplt.figure()\nplt.ylim(0, 0.01)\nplt.scatter(x=data[:, 1], y=data[:, 0])\nplt.xlabel('Inputsize')\nplt.ylabel('Running time')\nplt.title('Median finder running time')\n", "step-5": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 11 14:55:12 2019\n\n@author: Furankyyy\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport timeit\n\n###worst sort function###\n\n#define the function that checks whether the list is in ascending order\ndef right_permutation(arr):\n if len(arr)==1: #if there's only one element, then the order is always correct\n return True\n for i in range(len(arr)-1): #check every elements from the first to the second to the last\n if arr[i+1]<arr[i]: #if the i+1th element is smaller than ith, the order is wrong, break the loop and return false\n break\n else:\n if i == len(arr)-2: #if the i+1th element is greater than/equal to ith, check if we have already checked all the elements\n return True #if we've already checked all the elements (i.e. i==len(arr)-2), return true; if not, continue the loop\n return False\n \n \n#define the worst sort function\ndef worstsort(arr):\n sort_arr=[] #initialize output\n check = False #initialize the result of right_permutation()\n while check == False: #while the order is wrong, generate a new permyutation and check if its order is correct\n sort_arr = np.random.permutation(arr)\n check = right_permutation(sort_arr)\n return sort_arr\n\n#test cases\ntest1=[5,4,3,2,1]\ntest2=[1,2,3,4,5] #best case\ntest3=[2,2,2,2,2] #best case as well!\ntest4=[2] #only one element\nprint(worstsort(test1))\nprint(worstsort(test2))\nprint(worstsort(test3))\nprint(worstsort(test4))\n\n\n#the best case is when the input list is already sorted, in this case, we only need to run the right_permutation once\n#we have a for loop in right_permutation, so the best case complexity is O(n)\n\n\n#given a random input of size n, the chance that the input x_k is correctly sorted is Pr(x_k) = 1/P_n = 1/n! \n#since in this worst algorithm, we do not \"remember\" the permutations that we've already checked\n#so each time, the Pr(sorted) remains the same 1/n!\n#Then we would expect to have n! times to have the corrected sorted list \n#the reason is that we have E[Pr(x1)+Pr(x2)+...+Pr(x_k)]=1, since Pr(x_k)=1/n!, we would expect k = n!\n#this reasoning is the same as the random indicator variable in the book, where we have the pr(I) for each choice (permutation) and we sum them to find the expected value\n#so the averaage case complexity is O(n!)\n\n\n#to calculate what n is best for this function\n\ndef factorial(n):\n result=1\n for i in range(n):\n result=result*(i+1)\n return result\n\nx=np.arange(0,7,1)\ny_factorial=list(map(factorial,x))\ny_compare=x*x\n\nplt.plot(x,y_factorial,label=\"Factorial of n\")\nplt.plot(x,y_compare,label=\"n square\")\nplt.title(\"Complexity comparison\")\nplt.legend()\n\n#from the plot we can see that for algorithms with comlexity of O(n^2) and O(n!), the difference comes when n=5\n#when n=4, the two algorithms do not vary that much, but when n=5, they have a >100 times difference\n#therefore, this method is feasible when n<=4\n#p.s. constants are discounted (they are relatively unimportant)\n\n\n\n\n###median finder###\n\n#the worst case for the median finder is that the elements in the input list are unique\n#the best case is that all elements are the same --> no matter which we choose, it is the median\n\n#to consider the times we try before stopping, we need to consider the worst case --> all elements are different\n#then the chance to find the exact median is 1/n\n#the number of elements lying in the input deviation range x is x//(100/n)+1 for this worst case\n#explanation: divide the 100% to n parts, if all elements are different then each element takes the 1 part, the x//(range for 1 part)+1 is the num of elements lying in the range\n#therefore, the probability of choosing the element in the range given by x is (x//(100/n)+1)/n\n#I want to try the expected times of choosing the correct element(s) for the worst case\n\n#Pr(failure) for 1 try is 1-(x//(100/n)+1)/n\n#Pr(failure) for the first k try is (1-(x//(100/n)+1)/n)^k, which scales with x and n.\n\n#so the Pr(at least one success) for the first k try is 1-Pr(failure)=1-(1-(x//(100/n)+1)/n)^k\n#we want to find a k taht makes this Pr large enough\n#so we want to find a small k minimizing Pr(failure) for the first k try\n#to simplify the problem, we regard x as constant and assume the \"//\" is \"/\"\n#(1-(x//(100/n)+1)/n)^k = ((n-xn/100-1)/n)^k =(1-x/100-1/n)^k\n#x/100 is a constant\n#-->(1-1/n)^k\n#when n is sufficiently large, (1-1/n) is nearly 1\n#it is extremely hard to succeed if n is very large, I set the limit of k at 10000, simply because my laptop's computational ability\n\ndef median_finder(arr,x):\n tried = 0 #record the number of times of choosing the random element\n if abs(x) <= 0.5: #when x is valid\n lower=np.percentile(arr,50-x/2)\n upper=np.percentile(arr,50+x/2)\n while tried <10000:\n find = np.random.randint(0,len(arr)) #find a new element\n if lower<=arr[find] and arr[find]<=upper: #if the chosen element is in the range, return it\n return arr[find]\n else: \n tried += 1 \n return \"Tried enough times, still cannot find the value\"\n else:\n return \"x not in the domain\"\n\n#test cases\ntest1=list(np.random.permutation(200))\ntest2=[4]*100\ntest3=[5]*1000\ntest4=test2+test3\n\nprint(median_finder(test1,0.5)) #worst case, exactly 2 elements in the range\nprint(median_finder(test2,0.5)) #best case\nprint(median_finder(test2,0)) #best case\nprint(median_finder(test3,0.5)) #best case\nprint(median_finder(test4,0)) #1000/1100 probability \nprint(median_finder(test4,0.5)) #same as above.\n\n\n#time complexity\n\n#best case running time is O(1)\n\n#the time complexity of the worst case running time is E[k]=Sum(E[ki])\n#E[ki]=Pr(correct)=(x//(100/n)+1)/n\n#sum is from 1 to the limit tried k\n#since x is between 0 and 0.5, we simply regard it as constant\n#we also assume the \"//\" is \"/\"\n#then the expression becomes: E[k]= k*(xn/100+1)/n\n#as n goes to infinity, we can solve this by trying to use L'Hopital's rule\n#the result is kx/100, which is a constant\n#O(1)\n\n\ndata=np.empty((1,2))\n\nfor i in range(200,1200,50): \n testlist=list(np.random.permutation(i))\n time=timeit.timeit(stmt=\"median_finder(testlist,0.5)\",setup=\"from __main__ import median_finder,testlist\",number=100)\n time=time/100\n stack=np.array((time,i))\n\n data=np.vstack((data,stack))\n\ndata=data[1:]\n\nplt.figure()\nplt.ylim(0,0.01)\nplt.scatter(x=data[:,1],y=data[:,0])\nplt.xlabel(\"Inputsize\")\nplt.ylabel(\"Running time\")\nplt.title(\"Median finder running time\")\n\n#from the plot we can see that the running time is almost constant --> O(1)\n\n\n#space complexity is O(n), because each time we just store the (sorted) list of length n", "step-ids": [ 4, 5, 6, 7, 8 ] }
[ 4, 5, 6, 7, 8 ]
<|reserved_special_token_0|> class WeatherToMusicConverter: <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class WeatherToMusicConverter: <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def weather_to_music(self, api_key, city) ->MidiFile: api_handling = WeatherApi() converter = Converter() weather_forecast = api_handling.get_weather_forecast_from_api(city, api_key) average_temperature = converter.average_temperature(weather_forecast .weather_timestamps) ticks_per_beat = converter.average_temperature_to_ticks_per_beat( average_temperature) outfile = MidiFile() outfile.ticks_per_beat = ticks_per_beat melody_builder = MelodyBuilder(outfile, self.PHRASE_LENGTH) temperature = TemperatureTrack(1, Instruments.BrightAcousticPiano) rain = RainTrack(2, Instruments.Celesta) clouds = CloudsTrack(3, Instruments.TremoloStrings) humidity = HumidityTrack(4, Instruments.ElectricGuitar_clean) wind = WindTrack(5, Instruments.Seashore) for track in [temperature, rain, clouds, humidity, wind]: melody_builder.set_instrument(track.get_track(), track. get_channel(), track.get_instrument()) for entry in weather_forecast.weather_timestamps: base_note = converter.temperature_to_base_note(entry. temperature.feels_like) music_scale = self.music_scales.melodic_minor(base_note) temperature_sequence = TemperatureSequence(entry.temperature, self.PHRASE_LENGTH, base_note, temperature.get_track()) temperature_appender = TemperatureAppender() temperature_appender.append(melody_builder, temperature_sequence, temperature) rain_sequence = RainSequence(entry.weather.rain, self. PHRASE_LENGTH, base_note, rain.get_track(), music_scale) rain_appender = RainAppender() rain_appender.append(melody_builder, rain_sequence, rain) clouds_sequence = CloudsSequence(entry.weather.clouds, self. PHRASE_LENGTH, base_note, clouds.get_track()) clouds_appender = CloudsAppender() clouds_appender.append(melody_builder, clouds_sequence, clouds) humidity_sequence = HumiditySequence(entry.weather.humidity, self.PHRASE_LENGTH, base_note, humidity.get_track()) humidity_appender = HumidityAppender() humidity_appender.append(melody_builder, humidity_sequence, humidity) wind_sequence = WindSequence(entry.weather.wind_speed, self. PHRASE_LENGTH, base_note, wind.get_track()) wind_appender = WindAppender() wind_appender.append(melody_builder, wind_sequence, wind) for track in [temperature.get_track(), rain.get_track(), clouds. get_track(), humidity.get_track(), wind.get_track()]: outfile.tracks.append(track) file_name = ('weather_song_' + weather_forecast.city + '_' + weather_forecast.country + '_' + str(weather_forecast. weather_timestamps[0].timestamp)) self.save_file(outfile, self.OUTPUT_FILE_DIR, file_name) return outfile def save_file(self, outfile: MidiFile, file_dir: str, file_name: str ) ->MidiFile: Path(file_dir).mkdir(exist_ok=True) file_path = file_dir + '/' + file_name + '.mid' outfile.save(file_path) print('file saved at ' + file_path) return outfile def get_midi_track_time(self, midi_track: MidiTrack): sum = 0 for message in midi_track: sum += message.time return sum <|reserved_special_token_1|> <|reserved_special_token_0|> class WeatherToMusicConverter: PHRASE_LENGTH = 1200 OUTPUT_FILE_DIR = 'midi_out' music_scales = MusicScale() def weather_to_music(self, api_key, city) ->MidiFile: api_handling = WeatherApi() converter = Converter() weather_forecast = api_handling.get_weather_forecast_from_api(city, api_key) average_temperature = converter.average_temperature(weather_forecast .weather_timestamps) ticks_per_beat = converter.average_temperature_to_ticks_per_beat( average_temperature) outfile = MidiFile() outfile.ticks_per_beat = ticks_per_beat melody_builder = MelodyBuilder(outfile, self.PHRASE_LENGTH) temperature = TemperatureTrack(1, Instruments.BrightAcousticPiano) rain = RainTrack(2, Instruments.Celesta) clouds = CloudsTrack(3, Instruments.TremoloStrings) humidity = HumidityTrack(4, Instruments.ElectricGuitar_clean) wind = WindTrack(5, Instruments.Seashore) for track in [temperature, rain, clouds, humidity, wind]: melody_builder.set_instrument(track.get_track(), track. get_channel(), track.get_instrument()) for entry in weather_forecast.weather_timestamps: base_note = converter.temperature_to_base_note(entry. temperature.feels_like) music_scale = self.music_scales.melodic_minor(base_note) temperature_sequence = TemperatureSequence(entry.temperature, self.PHRASE_LENGTH, base_note, temperature.get_track()) temperature_appender = TemperatureAppender() temperature_appender.append(melody_builder, temperature_sequence, temperature) rain_sequence = RainSequence(entry.weather.rain, self. PHRASE_LENGTH, base_note, rain.get_track(), music_scale) rain_appender = RainAppender() rain_appender.append(melody_builder, rain_sequence, rain) clouds_sequence = CloudsSequence(entry.weather.clouds, self. PHRASE_LENGTH, base_note, clouds.get_track()) clouds_appender = CloudsAppender() clouds_appender.append(melody_builder, clouds_sequence, clouds) humidity_sequence = HumiditySequence(entry.weather.humidity, self.PHRASE_LENGTH, base_note, humidity.get_track()) humidity_appender = HumidityAppender() humidity_appender.append(melody_builder, humidity_sequence, humidity) wind_sequence = WindSequence(entry.weather.wind_speed, self. PHRASE_LENGTH, base_note, wind.get_track()) wind_appender = WindAppender() wind_appender.append(melody_builder, wind_sequence, wind) for track in [temperature.get_track(), rain.get_track(), clouds. get_track(), humidity.get_track(), wind.get_track()]: outfile.tracks.append(track) file_name = ('weather_song_' + weather_forecast.city + '_' + weather_forecast.country + '_' + str(weather_forecast. weather_timestamps[0].timestamp)) self.save_file(outfile, self.OUTPUT_FILE_DIR, file_name) return outfile def save_file(self, outfile: MidiFile, file_dir: str, file_name: str ) ->MidiFile: Path(file_dir).mkdir(exist_ok=True) file_path = file_dir + '/' + file_name + '.mid' outfile.save(file_path) print('file saved at ' + file_path) return outfile def get_midi_track_time(self, midi_track: MidiTrack): sum = 0 for message in midi_track: sum += message.time return sum <|reserved_special_token_1|> from pathlib import Path from build_midi.appenders import * from build_midi.converters import Converter from build_midi.melody_builder import MelodyBuilder from build_midi.sequences import * from build_midi.tracks import * from music_rules.instruments import Instruments from music_rules.music_scale import MusicScale from weather.weather_api import WeatherApi class WeatherToMusicConverter: PHRASE_LENGTH = 1200 OUTPUT_FILE_DIR = 'midi_out' music_scales = MusicScale() def weather_to_music(self, api_key, city) ->MidiFile: api_handling = WeatherApi() converter = Converter() weather_forecast = api_handling.get_weather_forecast_from_api(city, api_key) average_temperature = converter.average_temperature(weather_forecast .weather_timestamps) ticks_per_beat = converter.average_temperature_to_ticks_per_beat( average_temperature) outfile = MidiFile() outfile.ticks_per_beat = ticks_per_beat melody_builder = MelodyBuilder(outfile, self.PHRASE_LENGTH) temperature = TemperatureTrack(1, Instruments.BrightAcousticPiano) rain = RainTrack(2, Instruments.Celesta) clouds = CloudsTrack(3, Instruments.TremoloStrings) humidity = HumidityTrack(4, Instruments.ElectricGuitar_clean) wind = WindTrack(5, Instruments.Seashore) for track in [temperature, rain, clouds, humidity, wind]: melody_builder.set_instrument(track.get_track(), track. get_channel(), track.get_instrument()) for entry in weather_forecast.weather_timestamps: base_note = converter.temperature_to_base_note(entry. temperature.feels_like) music_scale = self.music_scales.melodic_minor(base_note) temperature_sequence = TemperatureSequence(entry.temperature, self.PHRASE_LENGTH, base_note, temperature.get_track()) temperature_appender = TemperatureAppender() temperature_appender.append(melody_builder, temperature_sequence, temperature) rain_sequence = RainSequence(entry.weather.rain, self. PHRASE_LENGTH, base_note, rain.get_track(), music_scale) rain_appender = RainAppender() rain_appender.append(melody_builder, rain_sequence, rain) clouds_sequence = CloudsSequence(entry.weather.clouds, self. PHRASE_LENGTH, base_note, clouds.get_track()) clouds_appender = CloudsAppender() clouds_appender.append(melody_builder, clouds_sequence, clouds) humidity_sequence = HumiditySequence(entry.weather.humidity, self.PHRASE_LENGTH, base_note, humidity.get_track()) humidity_appender = HumidityAppender() humidity_appender.append(melody_builder, humidity_sequence, humidity) wind_sequence = WindSequence(entry.weather.wind_speed, self. PHRASE_LENGTH, base_note, wind.get_track()) wind_appender = WindAppender() wind_appender.append(melody_builder, wind_sequence, wind) for track in [temperature.get_track(), rain.get_track(), clouds. get_track(), humidity.get_track(), wind.get_track()]: outfile.tracks.append(track) file_name = ('weather_song_' + weather_forecast.city + '_' + weather_forecast.country + '_' + str(weather_forecast. weather_timestamps[0].timestamp)) self.save_file(outfile, self.OUTPUT_FILE_DIR, file_name) return outfile def save_file(self, outfile: MidiFile, file_dir: str, file_name: str ) ->MidiFile: Path(file_dir).mkdir(exist_ok=True) file_path = file_dir + '/' + file_name + '.mid' outfile.save(file_path) print('file saved at ' + file_path) return outfile def get_midi_track_time(self, midi_track: MidiTrack): sum = 0 for message in midi_track: sum += message.time return sum <|reserved_special_token_1|> from pathlib import Path from build_midi.appenders import * from build_midi.converters import Converter from build_midi.melody_builder import MelodyBuilder from build_midi.sequences import * from build_midi.tracks import * from music_rules.instruments import Instruments from music_rules.music_scale import MusicScale from weather.weather_api import WeatherApi class WeatherToMusicConverter: PHRASE_LENGTH = 1200 OUTPUT_FILE_DIR = 'midi_out' music_scales = MusicScale() def weather_to_music(self, api_key, city) -> MidiFile: api_handling = WeatherApi() converter = Converter() weather_forecast = api_handling.get_weather_forecast_from_api(city, api_key) average_temperature = converter.average_temperature(weather_forecast.weather_timestamps) ticks_per_beat = converter.average_temperature_to_ticks_per_beat(average_temperature) outfile = MidiFile() outfile.ticks_per_beat = ticks_per_beat melody_builder = MelodyBuilder(outfile, self.PHRASE_LENGTH) temperature = TemperatureTrack(1, Instruments.BrightAcousticPiano) rain = RainTrack(2, Instruments.Celesta) clouds = CloudsTrack(3, Instruments.TremoloStrings) humidity = HumidityTrack(4, Instruments.ElectricGuitar_clean) wind = WindTrack(5, Instruments.Seashore) for track in [temperature, rain, clouds, humidity, wind]: melody_builder.set_instrument(track.get_track(), track.get_channel(), track.get_instrument()) for entry in weather_forecast.weather_timestamps: base_note = converter.temperature_to_base_note(entry.temperature.feels_like) music_scale = self.music_scales.melodic_minor(base_note) temperature_sequence = TemperatureSequence(entry.temperature, self.PHRASE_LENGTH, base_note, temperature.get_track()) temperature_appender = TemperatureAppender() temperature_appender.append(melody_builder, temperature_sequence, temperature) rain_sequence = RainSequence(entry.weather.rain, self.PHRASE_LENGTH, base_note, rain.get_track(), music_scale) rain_appender = RainAppender() rain_appender.append(melody_builder, rain_sequence, rain) clouds_sequence = CloudsSequence(entry.weather.clouds, self.PHRASE_LENGTH, base_note, clouds.get_track()) clouds_appender = CloudsAppender() clouds_appender.append(melody_builder, clouds_sequence, clouds) humidity_sequence = HumiditySequence(entry.weather.humidity, self.PHRASE_LENGTH, base_note, humidity.get_track()) humidity_appender = HumidityAppender() humidity_appender.append(melody_builder, humidity_sequence, humidity) wind_sequence = WindSequence(entry.weather.wind_speed, self.PHRASE_LENGTH, base_note, wind.get_track()) wind_appender = WindAppender() wind_appender.append(melody_builder, wind_sequence, wind) for track in [temperature.get_track(), rain.get_track(), clouds.get_track(), humidity.get_track(), wind.get_track()]: outfile.tracks.append(track) file_name = 'weather_song_' + weather_forecast.city + '_' + weather_forecast.country + '_' + str(weather_forecast.weather_timestamps[0].timestamp) self.save_file(outfile, self.OUTPUT_FILE_DIR, file_name) return outfile def save_file(self, outfile: MidiFile, file_dir: str, file_name: str) -> MidiFile: Path(file_dir).mkdir(exist_ok=True) file_path = file_dir + '/' + file_name + '.mid' outfile.save(file_path) print('file saved at ' + file_path) return outfile def get_midi_track_time(self, midi_track: MidiTrack): sum = 0 for message in midi_track: sum += message.time return sum
flexible
{ "blob_id": "c846c33ef13795d51c6d23ffa5a6b564b66e6a3c", "index": 3438, "step-1": "<mask token>\n\n\nclass WeatherToMusicConverter:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass WeatherToMusicConverter:\n <mask token>\n <mask token>\n <mask token>\n\n def weather_to_music(self, api_key, city) ->MidiFile:\n api_handling = WeatherApi()\n converter = Converter()\n weather_forecast = api_handling.get_weather_forecast_from_api(city,\n api_key)\n average_temperature = converter.average_temperature(weather_forecast\n .weather_timestamps)\n ticks_per_beat = converter.average_temperature_to_ticks_per_beat(\n average_temperature)\n outfile = MidiFile()\n outfile.ticks_per_beat = ticks_per_beat\n melody_builder = MelodyBuilder(outfile, self.PHRASE_LENGTH)\n temperature = TemperatureTrack(1, Instruments.BrightAcousticPiano)\n rain = RainTrack(2, Instruments.Celesta)\n clouds = CloudsTrack(3, Instruments.TremoloStrings)\n humidity = HumidityTrack(4, Instruments.ElectricGuitar_clean)\n wind = WindTrack(5, Instruments.Seashore)\n for track in [temperature, rain, clouds, humidity, wind]:\n melody_builder.set_instrument(track.get_track(), track.\n get_channel(), track.get_instrument())\n for entry in weather_forecast.weather_timestamps:\n base_note = converter.temperature_to_base_note(entry.\n temperature.feels_like)\n music_scale = self.music_scales.melodic_minor(base_note)\n temperature_sequence = TemperatureSequence(entry.temperature,\n self.PHRASE_LENGTH, base_note, temperature.get_track())\n temperature_appender = TemperatureAppender()\n temperature_appender.append(melody_builder,\n temperature_sequence, temperature)\n rain_sequence = RainSequence(entry.weather.rain, self.\n PHRASE_LENGTH, base_note, rain.get_track(), music_scale)\n rain_appender = RainAppender()\n rain_appender.append(melody_builder, rain_sequence, rain)\n clouds_sequence = CloudsSequence(entry.weather.clouds, self.\n PHRASE_LENGTH, base_note, clouds.get_track())\n clouds_appender = CloudsAppender()\n clouds_appender.append(melody_builder, clouds_sequence, clouds)\n humidity_sequence = HumiditySequence(entry.weather.humidity,\n self.PHRASE_LENGTH, base_note, humidity.get_track())\n humidity_appender = HumidityAppender()\n humidity_appender.append(melody_builder, humidity_sequence,\n humidity)\n wind_sequence = WindSequence(entry.weather.wind_speed, self.\n PHRASE_LENGTH, base_note, wind.get_track())\n wind_appender = WindAppender()\n wind_appender.append(melody_builder, wind_sequence, wind)\n for track in [temperature.get_track(), rain.get_track(), clouds.\n get_track(), humidity.get_track(), wind.get_track()]:\n outfile.tracks.append(track)\n file_name = ('weather_song_' + weather_forecast.city + '_' +\n weather_forecast.country + '_' + str(weather_forecast.\n weather_timestamps[0].timestamp))\n self.save_file(outfile, self.OUTPUT_FILE_DIR, file_name)\n return outfile\n\n def save_file(self, outfile: MidiFile, file_dir: str, file_name: str\n ) ->MidiFile:\n Path(file_dir).mkdir(exist_ok=True)\n file_path = file_dir + '/' + file_name + '.mid'\n outfile.save(file_path)\n print('file saved at ' + file_path)\n return outfile\n\n def get_midi_track_time(self, midi_track: MidiTrack):\n sum = 0\n for message in midi_track:\n sum += message.time\n return sum\n", "step-3": "<mask token>\n\n\nclass WeatherToMusicConverter:\n PHRASE_LENGTH = 1200\n OUTPUT_FILE_DIR = 'midi_out'\n music_scales = MusicScale()\n\n def weather_to_music(self, api_key, city) ->MidiFile:\n api_handling = WeatherApi()\n converter = Converter()\n weather_forecast = api_handling.get_weather_forecast_from_api(city,\n api_key)\n average_temperature = converter.average_temperature(weather_forecast\n .weather_timestamps)\n ticks_per_beat = converter.average_temperature_to_ticks_per_beat(\n average_temperature)\n outfile = MidiFile()\n outfile.ticks_per_beat = ticks_per_beat\n melody_builder = MelodyBuilder(outfile, self.PHRASE_LENGTH)\n temperature = TemperatureTrack(1, Instruments.BrightAcousticPiano)\n rain = RainTrack(2, Instruments.Celesta)\n clouds = CloudsTrack(3, Instruments.TremoloStrings)\n humidity = HumidityTrack(4, Instruments.ElectricGuitar_clean)\n wind = WindTrack(5, Instruments.Seashore)\n for track in [temperature, rain, clouds, humidity, wind]:\n melody_builder.set_instrument(track.get_track(), track.\n get_channel(), track.get_instrument())\n for entry in weather_forecast.weather_timestamps:\n base_note = converter.temperature_to_base_note(entry.\n temperature.feels_like)\n music_scale = self.music_scales.melodic_minor(base_note)\n temperature_sequence = TemperatureSequence(entry.temperature,\n self.PHRASE_LENGTH, base_note, temperature.get_track())\n temperature_appender = TemperatureAppender()\n temperature_appender.append(melody_builder,\n temperature_sequence, temperature)\n rain_sequence = RainSequence(entry.weather.rain, self.\n PHRASE_LENGTH, base_note, rain.get_track(), music_scale)\n rain_appender = RainAppender()\n rain_appender.append(melody_builder, rain_sequence, rain)\n clouds_sequence = CloudsSequence(entry.weather.clouds, self.\n PHRASE_LENGTH, base_note, clouds.get_track())\n clouds_appender = CloudsAppender()\n clouds_appender.append(melody_builder, clouds_sequence, clouds)\n humidity_sequence = HumiditySequence(entry.weather.humidity,\n self.PHRASE_LENGTH, base_note, humidity.get_track())\n humidity_appender = HumidityAppender()\n humidity_appender.append(melody_builder, humidity_sequence,\n humidity)\n wind_sequence = WindSequence(entry.weather.wind_speed, self.\n PHRASE_LENGTH, base_note, wind.get_track())\n wind_appender = WindAppender()\n wind_appender.append(melody_builder, wind_sequence, wind)\n for track in [temperature.get_track(), rain.get_track(), clouds.\n get_track(), humidity.get_track(), wind.get_track()]:\n outfile.tracks.append(track)\n file_name = ('weather_song_' + weather_forecast.city + '_' +\n weather_forecast.country + '_' + str(weather_forecast.\n weather_timestamps[0].timestamp))\n self.save_file(outfile, self.OUTPUT_FILE_DIR, file_name)\n return outfile\n\n def save_file(self, outfile: MidiFile, file_dir: str, file_name: str\n ) ->MidiFile:\n Path(file_dir).mkdir(exist_ok=True)\n file_path = file_dir + '/' + file_name + '.mid'\n outfile.save(file_path)\n print('file saved at ' + file_path)\n return outfile\n\n def get_midi_track_time(self, midi_track: MidiTrack):\n sum = 0\n for message in midi_track:\n sum += message.time\n return sum\n", "step-4": "from pathlib import Path\nfrom build_midi.appenders import *\nfrom build_midi.converters import Converter\nfrom build_midi.melody_builder import MelodyBuilder\nfrom build_midi.sequences import *\nfrom build_midi.tracks import *\nfrom music_rules.instruments import Instruments\nfrom music_rules.music_scale import MusicScale\nfrom weather.weather_api import WeatherApi\n\n\nclass WeatherToMusicConverter:\n PHRASE_LENGTH = 1200\n OUTPUT_FILE_DIR = 'midi_out'\n music_scales = MusicScale()\n\n def weather_to_music(self, api_key, city) ->MidiFile:\n api_handling = WeatherApi()\n converter = Converter()\n weather_forecast = api_handling.get_weather_forecast_from_api(city,\n api_key)\n average_temperature = converter.average_temperature(weather_forecast\n .weather_timestamps)\n ticks_per_beat = converter.average_temperature_to_ticks_per_beat(\n average_temperature)\n outfile = MidiFile()\n outfile.ticks_per_beat = ticks_per_beat\n melody_builder = MelodyBuilder(outfile, self.PHRASE_LENGTH)\n temperature = TemperatureTrack(1, Instruments.BrightAcousticPiano)\n rain = RainTrack(2, Instruments.Celesta)\n clouds = CloudsTrack(3, Instruments.TremoloStrings)\n humidity = HumidityTrack(4, Instruments.ElectricGuitar_clean)\n wind = WindTrack(5, Instruments.Seashore)\n for track in [temperature, rain, clouds, humidity, wind]:\n melody_builder.set_instrument(track.get_track(), track.\n get_channel(), track.get_instrument())\n for entry in weather_forecast.weather_timestamps:\n base_note = converter.temperature_to_base_note(entry.\n temperature.feels_like)\n music_scale = self.music_scales.melodic_minor(base_note)\n temperature_sequence = TemperatureSequence(entry.temperature,\n self.PHRASE_LENGTH, base_note, temperature.get_track())\n temperature_appender = TemperatureAppender()\n temperature_appender.append(melody_builder,\n temperature_sequence, temperature)\n rain_sequence = RainSequence(entry.weather.rain, self.\n PHRASE_LENGTH, base_note, rain.get_track(), music_scale)\n rain_appender = RainAppender()\n rain_appender.append(melody_builder, rain_sequence, rain)\n clouds_sequence = CloudsSequence(entry.weather.clouds, self.\n PHRASE_LENGTH, base_note, clouds.get_track())\n clouds_appender = CloudsAppender()\n clouds_appender.append(melody_builder, clouds_sequence, clouds)\n humidity_sequence = HumiditySequence(entry.weather.humidity,\n self.PHRASE_LENGTH, base_note, humidity.get_track())\n humidity_appender = HumidityAppender()\n humidity_appender.append(melody_builder, humidity_sequence,\n humidity)\n wind_sequence = WindSequence(entry.weather.wind_speed, self.\n PHRASE_LENGTH, base_note, wind.get_track())\n wind_appender = WindAppender()\n wind_appender.append(melody_builder, wind_sequence, wind)\n for track in [temperature.get_track(), rain.get_track(), clouds.\n get_track(), humidity.get_track(), wind.get_track()]:\n outfile.tracks.append(track)\n file_name = ('weather_song_' + weather_forecast.city + '_' +\n weather_forecast.country + '_' + str(weather_forecast.\n weather_timestamps[0].timestamp))\n self.save_file(outfile, self.OUTPUT_FILE_DIR, file_name)\n return outfile\n\n def save_file(self, outfile: MidiFile, file_dir: str, file_name: str\n ) ->MidiFile:\n Path(file_dir).mkdir(exist_ok=True)\n file_path = file_dir + '/' + file_name + '.mid'\n outfile.save(file_path)\n print('file saved at ' + file_path)\n return outfile\n\n def get_midi_track_time(self, midi_track: MidiTrack):\n sum = 0\n for message in midi_track:\n sum += message.time\n return sum\n", "step-5": "from pathlib import Path\n\nfrom build_midi.appenders import *\nfrom build_midi.converters import Converter\nfrom build_midi.melody_builder import MelodyBuilder\nfrom build_midi.sequences import *\nfrom build_midi.tracks import *\nfrom music_rules.instruments import Instruments\nfrom music_rules.music_scale import MusicScale\nfrom weather.weather_api import WeatherApi\n\n\nclass WeatherToMusicConverter:\n\n\tPHRASE_LENGTH = 1200\n\tOUTPUT_FILE_DIR = 'midi_out'\n\n\tmusic_scales = MusicScale()\n\n\tdef weather_to_music(self, api_key, city) -> MidiFile:\n\t\tapi_handling = WeatherApi()\n\t\tconverter = Converter()\n\n\t\tweather_forecast = api_handling.get_weather_forecast_from_api(city, api_key)\n\n\t\taverage_temperature = converter.average_temperature(weather_forecast.weather_timestamps)\n\t\tticks_per_beat = converter.average_temperature_to_ticks_per_beat(average_temperature)\n\n\t\toutfile = MidiFile()\n\t\toutfile.ticks_per_beat = ticks_per_beat\n\n\t\tmelody_builder = MelodyBuilder(outfile, self.PHRASE_LENGTH)\n\n\t\ttemperature = TemperatureTrack(1, Instruments.BrightAcousticPiano)\n\t\train = RainTrack(2, Instruments.Celesta)\n\t\tclouds = CloudsTrack(3, Instruments.TremoloStrings)\n\t\thumidity = HumidityTrack(4, Instruments.ElectricGuitar_clean)\n\t\twind = WindTrack(5, Instruments.Seashore)\n\n\t\tfor track in [temperature, rain, clouds, humidity, wind]:\n\t\t\tmelody_builder.set_instrument(track.get_track(), track.get_channel(), track.get_instrument())\n\n\t\tfor entry in weather_forecast.weather_timestamps:\n\n\t\t\tbase_note = converter.temperature_to_base_note(entry.temperature.feels_like)\n\t\t\tmusic_scale = self.music_scales.melodic_minor(base_note)\n\n\t\t\ttemperature_sequence = TemperatureSequence(entry.temperature, self.PHRASE_LENGTH, base_note, temperature.get_track())\n\t\t\ttemperature_appender = TemperatureAppender()\n\t\t\ttemperature_appender.append(melody_builder, temperature_sequence, temperature)\n\n\t\t\train_sequence = RainSequence(entry.weather.rain, self.PHRASE_LENGTH, base_note, rain.get_track(), music_scale)\n\t\t\train_appender = RainAppender()\n\t\t\train_appender.append(melody_builder, rain_sequence, rain)\n\n\t\t\tclouds_sequence = CloudsSequence(entry.weather.clouds, self.PHRASE_LENGTH, base_note, clouds.get_track())\n\t\t\tclouds_appender = CloudsAppender()\n\t\t\tclouds_appender.append(melody_builder, clouds_sequence, clouds)\n\n\t\t\thumidity_sequence = HumiditySequence(entry.weather.humidity, self.PHRASE_LENGTH, base_note, humidity.get_track())\n\t\t\thumidity_appender = HumidityAppender()\n\t\t\thumidity_appender.append(melody_builder, humidity_sequence, humidity)\n\n\t\t\twind_sequence = WindSequence(entry.weather.wind_speed, self.PHRASE_LENGTH, base_note, wind.get_track())\n\t\t\twind_appender = WindAppender()\n\t\t\twind_appender.append(melody_builder, wind_sequence, wind)\n\n\t\tfor track in [temperature.get_track(), rain.get_track(), clouds.get_track(), humidity.get_track(), wind.get_track()]:\n\t\t\toutfile.tracks.append(track)\n\n\t\tfile_name = 'weather_song_' + weather_forecast.city + '_' + weather_forecast.country + '_' + str(weather_forecast.weather_timestamps[0].timestamp)\n\t\tself.save_file(outfile, self.OUTPUT_FILE_DIR, file_name)\n\n\t\treturn outfile\n\n\tdef save_file(self, outfile: MidiFile, file_dir: str, file_name: str) -> MidiFile:\n\t\tPath(file_dir).mkdir(exist_ok=True)\n\t\tfile_path = file_dir + '/' + file_name + '.mid'\n\t\toutfile.save(file_path)\n\t\tprint('file saved at ' + file_path)\n\t\treturn outfile\n\n\tdef get_midi_track_time(self, midi_track: MidiTrack):\n\t\tsum = 0\n\t\tfor message in midi_track:\n\t\t\tsum += message.time\n\t\treturn sum\n\n", "step-ids": [ 1, 4, 5, 6, 7 ] }
[ 1, 4, 5, 6, 7 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): dependencies = [('products', '0003_auto_20200615_1225')] operations = [migrations.AlterField(model_name='product', name= 'harmonizacao', field=models.TextField(null=True)), migrations. AlterField(model_name='product', name='history', field=models. TextField(null=True)), migrations.AlterField(model_name='product', name='premios', field=models.TextField(null=True))] <|reserved_special_token_1|> from django.db import migrations, models class Migration(migrations.Migration): dependencies = [('products', '0003_auto_20200615_1225')] operations = [migrations.AlterField(model_name='product', name= 'harmonizacao', field=models.TextField(null=True)), migrations. AlterField(model_name='product', name='history', field=models. TextField(null=True)), migrations.AlterField(model_name='product', name='premios', field=models.TextField(null=True))] <|reserved_special_token_1|> # Generated by Django 3.0.7 on 2020-06-15 15:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('products', '0003_auto_20200615_1225'), ] operations = [ migrations.AlterField( model_name='product', name='harmonizacao', field=models.TextField(null=True), ), migrations.AlterField( model_name='product', name='history', field=models.TextField(null=True), ), migrations.AlterField( model_name='product', name='premios', field=models.TextField(null=True), ), ]
flexible
{ "blob_id": "c382b298cce8d7045d6ce8a84f90b3800dba7717", "index": 297, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('products', '0003_auto_20200615_1225')]\n operations = [migrations.AlterField(model_name='product', name=\n 'harmonizacao', field=models.TextField(null=True)), migrations.\n AlterField(model_name='product', name='history', field=models.\n TextField(null=True)), migrations.AlterField(model_name='product',\n name='premios', field=models.TextField(null=True))]\n", "step-4": "from django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('products', '0003_auto_20200615_1225')]\n operations = [migrations.AlterField(model_name='product', name=\n 'harmonizacao', field=models.TextField(null=True)), migrations.\n AlterField(model_name='product', name='history', field=models.\n TextField(null=True)), migrations.AlterField(model_name='product',\n name='premios', field=models.TextField(null=True))]\n", "step-5": "# Generated by Django 3.0.7 on 2020-06-15 15:26\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('products', '0003_auto_20200615_1225'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='product',\n name='harmonizacao',\n field=models.TextField(null=True),\n ),\n migrations.AlterField(\n model_name='product',\n name='history',\n field=models.TextField(null=True),\n ),\n migrations.AlterField(\n model_name='product',\n name='premios',\n field=models.TextField(null=True),\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): dependencies = [('django_otp', '0001_initial')] operations = [migrations.AddField(model_name='otpsecrets', name= 'issuer_name', field=models.CharField(blank=True, db_index=True, max_length=40))] <|reserved_special_token_1|> from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [('django_otp', '0001_initial')] operations = [migrations.AddField(model_name='otpsecrets', name= 'issuer_name', field=models.CharField(blank=True, db_index=True, max_length=40))] <|reserved_special_token_1|> # -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2016-12-29 03:38 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('django_otp', '0001_initial'), ] operations = [ migrations.AddField( model_name='otpsecrets', name='issuer_name', field=models.CharField(blank=True, db_index=True, max_length=40), ), ]
flexible
{ "blob_id": "d45ca839a24093266c48e5f97164b160190b154d", "index": 2133, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('django_otp', '0001_initial')]\n operations = [migrations.AddField(model_name='otpsecrets', name=\n 'issuer_name', field=models.CharField(blank=True, db_index=True,\n max_length=40))]\n", "step-4": "from __future__ import unicode_literals\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('django_otp', '0001_initial')]\n operations = [migrations.AddField(model_name='otpsecrets', name=\n 'issuer_name', field=models.CharField(blank=True, db_index=True,\n max_length=40))]\n", "step-5": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10.4 on 2016-12-29 03:38\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('django_otp', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='otpsecrets',\n name='issuer_name',\n field=models.CharField(blank=True, db_index=True, max_length=40),\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
def ex7(*siruri, x=1, flag=True): res = () for sir in siruri: chars = [] for char in sir: if ord(char) % x == (not flag): chars.append(char) res += (chars,) return res print(ex7("test", "hello", "lab002", x=2, flag=False))
normal
{ "blob_id": "90a402cccf383ed6a12b70ecdc3de623e6e223f9", "index": 8365, "step-1": "<mask token>\n", "step-2": "def ex7(*siruri, x=1, flag=True):\n res = ()\n for sir in siruri:\n chars = []\n for char in sir:\n if ord(char) % x == (not flag):\n chars.append(char)\n res += chars,\n return res\n\n\n<mask token>\n", "step-3": "def ex7(*siruri, x=1, flag=True):\n res = ()\n for sir in siruri:\n chars = []\n for char in sir:\n if ord(char) % x == (not flag):\n chars.append(char)\n res += chars,\n return res\n\n\nprint(ex7('test', 'hello', 'lab002', x=2, flag=False))\n", "step-4": "def ex7(*siruri, x=1, flag=True):\n res = ()\n for sir in siruri:\n chars = []\n for char in sir:\n if ord(char) % x == (not flag):\n chars.append(char)\n res += (chars,)\n\n return res\n\n\nprint(ex7(\"test\", \"hello\", \"lab002\", x=2, flag=False))\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class TaobaoSpider(Spider): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class TaobaoSpider(Spider): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def parse(self, response, **kwargs): pass <|reserved_special_token_1|> <|reserved_special_token_0|> class TaobaoSpider(Spider): name = 'taobao' allowed_domains = ['www.taobao.com'] start_urls = ['http://www.taobao.com/'] def parse(self, response, **kwargs): pass <|reserved_special_token_1|> from scrapy import Spider, Request from urllib.parse import quote from Product.items import ProductItem class TaobaoSpider(Spider): name = 'taobao' allowed_domains = ['www.taobao.com'] start_urls = ['http://www.taobao.com/'] def parse(self, response, **kwargs): pass
flexible
{ "blob_id": "8f709af924820c77290f97731d9f96258c3db095", "index": 2533, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass TaobaoSpider(Spider):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass TaobaoSpider(Spider):\n <mask token>\n <mask token>\n <mask token>\n\n def parse(self, response, **kwargs):\n pass\n", "step-4": "<mask token>\n\n\nclass TaobaoSpider(Spider):\n name = 'taobao'\n allowed_domains = ['www.taobao.com']\n start_urls = ['http://www.taobao.com/']\n\n def parse(self, response, **kwargs):\n pass\n", "step-5": "from scrapy import Spider, Request\nfrom urllib.parse import quote\nfrom Product.items import ProductItem\n\n\nclass TaobaoSpider(Spider):\n name = 'taobao'\n allowed_domains = ['www.taobao.com']\n start_urls = ['http://www.taobao.com/']\n\n def parse(self, response, **kwargs):\n pass\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
"""Usage: sharedprint.py INPUT [--output=out.mrc] sharedprint.py INPUT [--csv=greenglass.csv] Process Koha MARC export for SCELC Shared Print. The two uses above either 1) create a subset of the MARC input that's limited to circulating items only or 2) performs a comparison between what's in the catalog and what's in GreenGlass i.e. how many records were added and weeded. Arguments: INPUT MARC records (.mrc file) Options: -h --help show this usage information --debug show debug information as the script runs --output=FILE output records to this file [default: out.mrc] --csv=CSV GreenGlass CSV to compare input MARC file against """ import csv from docopt import docopt from pymarc import MARCReader, MARCWriter # https://library-staff.cca.edu/cgi-bin/koha/admin/authorised_values.pl?searchfield=LOST lost_codes = { "0": "", "1": "Lost", "2": "Long Overdue (Lost)", "3": "Lost and Paid For", "4": "Missing", "5": "Lost (On Search)", "6": "Claims Returned", } # https://library-staff.cca.edu/cgi-bin/koha/admin/authorised_values.pl?searchfield=NOT_LOAN notforloan_codes = { "-3": "Repair", "-2": "In Processing", "-1": "Ordered", "0": "", "1": "Library Use Only", "2": "Staff Collection", "3": "Bindery", "4": "By Appointment", "5": "On display", } # https://library-staff.cca.edu/cgi-bin/koha/admin/authorised_values.pl?searchfield=LOC valid_locations = [ "CART", "FACDEV", "MAIN", "NEWBOOK", "DISPLAY", ] # https://library-staff.cca.edu/cgi-bin/koha/admin/itemtypes.pl valid_types = [ "BOOK", "SUPPL", ] # name of column in the GreenGlass spreadsheet that contains the bib record ID GG_ID_COLUMN = 'Bib Record Number' # field and subfield in MARC record that contains the bib record ID # Koha appears to store it in both 999$c & $d MARC_ID_FIELD = '999' MARC_ID_SUBFIELD = 'c' def validate_item(item): # "item status" is an agglomeration of several things status = [] # whether the _item_ we're looking at should be included valid = True # checked out, will be a date if item is checked out if item['q'] and item['q'] != "0": status.append('checked out') # "not for loan", variety of reasons why an item might not circ if item['7'] and item['7'] != "0": status.append(notforloan_codes[item['7']]) valid = False # 1 is an item is damanged if item['4'] and item['4'] != "0": status.append('damaged') valid = False # lost, variety of codes if item['1'] and item['1'] != "0": status.append(lost_codes[item['1']]) valid = False # 1 if an item has been withdrawn if item['0'] and item['0'] != "0": status.append('withdrawn') valid = False # filter items based on location & type if item['c'] not in valid_locations: valid = False if item['y'] not in valid_types: valid = False if len(status) > 0 and options.get('--debug'): print('"' + record.title() + '" item status: ' + ', '.join(status)) return valid def main(): total_count = 0 valid_count = 0 with open(options['INPUT'], 'rb') as fh: reader = MARCReader(fh, to_unicode=True, force_utf8=True) # 1) first mode: write a MARC output file if not options['--csv']: writer = MARCWriter(open('out.mrc' or options['--output'], 'wb')) for record in reader: # whether we'll include the _bib_ record in export file include_record = False # Koha stores item data in 952 fields, one per item for item in record.get_fields('952'): valid = validate_item(item) total_count += 1 if valid is True: valid_count += 1 # if there's any valid item then the bib should be included include_record = True if include_record is True: writer.write(record) print('Total items: %i | Items included: %i' % (total_count, valid_count)) elif options['--csv']: koha_record_ids = set() for record in reader: total_count += 1 for item in record.get_fields('952'): valid = validate_item(item) if valid: id = record.get_fields(MARC_ID_FIELD)[0].get_subfields(MARC_ID_SUBFIELD)[0] koha_record_ids.add(id) # stop looking at items after we find the first valid one break csvreader = csv.DictReader(open(options['--csv'], 'r')) gg_record_ids = set() for row in csvreader: gg_record_ids.add(row[GG_ID_COLUMN]) print('Total Koha Bibs: %i' % total_count) print('Koha Bibs with circulating items: %i ' % len(koha_record_ids)) print('Total GreenGlass Bibs: %i' % len(gg_record_ids)) print('Weeded Items (I in GG & not in Koha): %i' % len(gg_record_ids - koha_record_ids)) print('Added Items (I in Koha & not in GG): %i' % len(koha_record_ids - gg_record_ids)) if __name__ == '__main__': options = docopt(__doc__) # print(options) main()
normal
{ "blob_id": "c6cce2edafd7683af766b932d90ca170359e648a", "index": 679, "step-1": "<mask token>\n\n\ndef main():\n total_count = 0\n valid_count = 0\n with open(options['INPUT'], 'rb') as fh:\n reader = MARCReader(fh, to_unicode=True, force_utf8=True)\n if not options['--csv']:\n writer = MARCWriter(open('out.mrc' or options['--output'], 'wb'))\n for record in reader:\n include_record = False\n for item in record.get_fields('952'):\n valid = validate_item(item)\n total_count += 1\n if valid is True:\n valid_count += 1\n include_record = True\n if include_record is True:\n writer.write(record)\n print('Total items: %i | Items included: %i' % (total_count,\n valid_count))\n elif options['--csv']:\n koha_record_ids = set()\n for record in reader:\n total_count += 1\n for item in record.get_fields('952'):\n valid = validate_item(item)\n if valid:\n id = record.get_fields(MARC_ID_FIELD)[0].get_subfields(\n MARC_ID_SUBFIELD)[0]\n koha_record_ids.add(id)\n break\n csvreader = csv.DictReader(open(options['--csv'], 'r'))\n gg_record_ids = set()\n for row in csvreader:\n gg_record_ids.add(row[GG_ID_COLUMN])\n print('Total Koha Bibs: %i' % total_count)\n print('Koha Bibs with circulating items: %i ' % len(\n koha_record_ids))\n print('Total GreenGlass Bibs: %i' % len(gg_record_ids))\n print('Weeded Items (I in GG & not in Koha): %i' % len(\n gg_record_ids - koha_record_ids))\n print('Added Items (I in Koha & not in GG): %i' % len(\n koha_record_ids - gg_record_ids))\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef validate_item(item):\n status = []\n valid = True\n if item['q'] and item['q'] != '0':\n status.append('checked out')\n if item['7'] and item['7'] != '0':\n status.append(notforloan_codes[item['7']])\n valid = False\n if item['4'] and item['4'] != '0':\n status.append('damaged')\n valid = False\n if item['1'] and item['1'] != '0':\n status.append(lost_codes[item['1']])\n valid = False\n if item['0'] and item['0'] != '0':\n status.append('withdrawn')\n valid = False\n if item['c'] not in valid_locations:\n valid = False\n if item['y'] not in valid_types:\n valid = False\n if len(status) > 0 and options.get('--debug'):\n print('\"' + record.title() + '\" item status: ' + ', '.join(status))\n return valid\n\n\ndef main():\n total_count = 0\n valid_count = 0\n with open(options['INPUT'], 'rb') as fh:\n reader = MARCReader(fh, to_unicode=True, force_utf8=True)\n if not options['--csv']:\n writer = MARCWriter(open('out.mrc' or options['--output'], 'wb'))\n for record in reader:\n include_record = False\n for item in record.get_fields('952'):\n valid = validate_item(item)\n total_count += 1\n if valid is True:\n valid_count += 1\n include_record = True\n if include_record is True:\n writer.write(record)\n print('Total items: %i | Items included: %i' % (total_count,\n valid_count))\n elif options['--csv']:\n koha_record_ids = set()\n for record in reader:\n total_count += 1\n for item in record.get_fields('952'):\n valid = validate_item(item)\n if valid:\n id = record.get_fields(MARC_ID_FIELD)[0].get_subfields(\n MARC_ID_SUBFIELD)[0]\n koha_record_ids.add(id)\n break\n csvreader = csv.DictReader(open(options['--csv'], 'r'))\n gg_record_ids = set()\n for row in csvreader:\n gg_record_ids.add(row[GG_ID_COLUMN])\n print('Total Koha Bibs: %i' % total_count)\n print('Koha Bibs with circulating items: %i ' % len(\n koha_record_ids))\n print('Total GreenGlass Bibs: %i' % len(gg_record_ids))\n print('Weeded Items (I in GG & not in Koha): %i' % len(\n gg_record_ids - koha_record_ids))\n print('Added Items (I in Koha & not in GG): %i' % len(\n koha_record_ids - gg_record_ids))\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef validate_item(item):\n status = []\n valid = True\n if item['q'] and item['q'] != '0':\n status.append('checked out')\n if item['7'] and item['7'] != '0':\n status.append(notforloan_codes[item['7']])\n valid = False\n if item['4'] and item['4'] != '0':\n status.append('damaged')\n valid = False\n if item['1'] and item['1'] != '0':\n status.append(lost_codes[item['1']])\n valid = False\n if item['0'] and item['0'] != '0':\n status.append('withdrawn')\n valid = False\n if item['c'] not in valid_locations:\n valid = False\n if item['y'] not in valid_types:\n valid = False\n if len(status) > 0 and options.get('--debug'):\n print('\"' + record.title() + '\" item status: ' + ', '.join(status))\n return valid\n\n\ndef main():\n total_count = 0\n valid_count = 0\n with open(options['INPUT'], 'rb') as fh:\n reader = MARCReader(fh, to_unicode=True, force_utf8=True)\n if not options['--csv']:\n writer = MARCWriter(open('out.mrc' or options['--output'], 'wb'))\n for record in reader:\n include_record = False\n for item in record.get_fields('952'):\n valid = validate_item(item)\n total_count += 1\n if valid is True:\n valid_count += 1\n include_record = True\n if include_record is True:\n writer.write(record)\n print('Total items: %i | Items included: %i' % (total_count,\n valid_count))\n elif options['--csv']:\n koha_record_ids = set()\n for record in reader:\n total_count += 1\n for item in record.get_fields('952'):\n valid = validate_item(item)\n if valid:\n id = record.get_fields(MARC_ID_FIELD)[0].get_subfields(\n MARC_ID_SUBFIELD)[0]\n koha_record_ids.add(id)\n break\n csvreader = csv.DictReader(open(options['--csv'], 'r'))\n gg_record_ids = set()\n for row in csvreader:\n gg_record_ids.add(row[GG_ID_COLUMN])\n print('Total Koha Bibs: %i' % total_count)\n print('Koha Bibs with circulating items: %i ' % len(\n koha_record_ids))\n print('Total GreenGlass Bibs: %i' % len(gg_record_ids))\n print('Weeded Items (I in GG & not in Koha): %i' % len(\n gg_record_ids - koha_record_ids))\n print('Added Items (I in Koha & not in GG): %i' % len(\n koha_record_ids - gg_record_ids))\n\n\nif __name__ == '__main__':\n options = docopt(__doc__)\n main()\n", "step-4": "<mask token>\nimport csv\nfrom docopt import docopt\nfrom pymarc import MARCReader, MARCWriter\nlost_codes = {'0': '', '1': 'Lost', '2': 'Long Overdue (Lost)', '3':\n 'Lost and Paid For', '4': 'Missing', '5': 'Lost (On Search)', '6':\n 'Claims Returned'}\nnotforloan_codes = {'-3': 'Repair', '-2': 'In Processing', '-1': 'Ordered',\n '0': '', '1': 'Library Use Only', '2': 'Staff Collection', '3':\n 'Bindery', '4': 'By Appointment', '5': 'On display'}\nvalid_locations = ['CART', 'FACDEV', 'MAIN', 'NEWBOOK', 'DISPLAY']\nvalid_types = ['BOOK', 'SUPPL']\nGG_ID_COLUMN = 'Bib Record Number'\nMARC_ID_FIELD = '999'\nMARC_ID_SUBFIELD = 'c'\n\n\ndef validate_item(item):\n status = []\n valid = True\n if item['q'] and item['q'] != '0':\n status.append('checked out')\n if item['7'] and item['7'] != '0':\n status.append(notforloan_codes[item['7']])\n valid = False\n if item['4'] and item['4'] != '0':\n status.append('damaged')\n valid = False\n if item['1'] and item['1'] != '0':\n status.append(lost_codes[item['1']])\n valid = False\n if item['0'] and item['0'] != '0':\n status.append('withdrawn')\n valid = False\n if item['c'] not in valid_locations:\n valid = False\n if item['y'] not in valid_types:\n valid = False\n if len(status) > 0 and options.get('--debug'):\n print('\"' + record.title() + '\" item status: ' + ', '.join(status))\n return valid\n\n\ndef main():\n total_count = 0\n valid_count = 0\n with open(options['INPUT'], 'rb') as fh:\n reader = MARCReader(fh, to_unicode=True, force_utf8=True)\n if not options['--csv']:\n writer = MARCWriter(open('out.mrc' or options['--output'], 'wb'))\n for record in reader:\n include_record = False\n for item in record.get_fields('952'):\n valid = validate_item(item)\n total_count += 1\n if valid is True:\n valid_count += 1\n include_record = True\n if include_record is True:\n writer.write(record)\n print('Total items: %i | Items included: %i' % (total_count,\n valid_count))\n elif options['--csv']:\n koha_record_ids = set()\n for record in reader:\n total_count += 1\n for item in record.get_fields('952'):\n valid = validate_item(item)\n if valid:\n id = record.get_fields(MARC_ID_FIELD)[0].get_subfields(\n MARC_ID_SUBFIELD)[0]\n koha_record_ids.add(id)\n break\n csvreader = csv.DictReader(open(options['--csv'], 'r'))\n gg_record_ids = set()\n for row in csvreader:\n gg_record_ids.add(row[GG_ID_COLUMN])\n print('Total Koha Bibs: %i' % total_count)\n print('Koha Bibs with circulating items: %i ' % len(\n koha_record_ids))\n print('Total GreenGlass Bibs: %i' % len(gg_record_ids))\n print('Weeded Items (I in GG & not in Koha): %i' % len(\n gg_record_ids - koha_record_ids))\n print('Added Items (I in Koha & not in GG): %i' % len(\n koha_record_ids - gg_record_ids))\n\n\nif __name__ == '__main__':\n options = docopt(__doc__)\n main()\n", "step-5": "\"\"\"Usage:\n sharedprint.py INPUT [--output=out.mrc]\n sharedprint.py INPUT [--csv=greenglass.csv]\n\nProcess Koha MARC export for SCELC Shared Print.\n\nThe two uses above either 1) create a subset of the MARC input that's limited to\ncirculating items only or 2) performs a comparison between what's in the catalog\nand what's in GreenGlass i.e. how many records were added and weeded.\n\nArguments:\n INPUT MARC records (.mrc file)\n\nOptions:\n -h --help show this usage information\n --debug show debug information as the script runs\n --output=FILE output records to this file [default: out.mrc]\n --csv=CSV GreenGlass CSV to compare input MARC file against\n\"\"\"\nimport csv\n\nfrom docopt import docopt\nfrom pymarc import MARCReader, MARCWriter\n\n# https://library-staff.cca.edu/cgi-bin/koha/admin/authorised_values.pl?searchfield=LOST\nlost_codes = {\n \"0\": \"\",\n \"1\": \"Lost\",\n \"2\": \"Long Overdue (Lost)\",\n \"3\": \"Lost and Paid For\",\n \"4\": \"Missing\",\n \"5\": \"Lost (On Search)\",\n \"6\": \"Claims Returned\",\n}\n\n# https://library-staff.cca.edu/cgi-bin/koha/admin/authorised_values.pl?searchfield=NOT_LOAN\nnotforloan_codes = {\n \"-3\":\t\"Repair\",\n \"-2\":\t\"In Processing\",\n \"-1\":\t\"Ordered\",\n \"0\":\t\"\",\n \"1\":\t\"Library Use Only\",\n \"2\":\t\"Staff Collection\",\n \"3\":\t\"Bindery\",\n \"4\":\t\"By Appointment\",\n \"5\":\t\"On display\",\n}\n\n# https://library-staff.cca.edu/cgi-bin/koha/admin/authorised_values.pl?searchfield=LOC\nvalid_locations = [\n \"CART\",\n \"FACDEV\",\n \"MAIN\",\n \"NEWBOOK\",\n \"DISPLAY\",\n]\n\n# https://library-staff.cca.edu/cgi-bin/koha/admin/itemtypes.pl\nvalid_types = [\n \"BOOK\",\n \"SUPPL\",\n]\n\n# name of column in the GreenGlass spreadsheet that contains the bib record ID\nGG_ID_COLUMN = 'Bib Record Number'\n# field and subfield in MARC record that contains the bib record ID\n# Koha appears to store it in both 999$c & $d\nMARC_ID_FIELD = '999'\nMARC_ID_SUBFIELD = 'c'\n\ndef validate_item(item):\n # \"item status\" is an agglomeration of several things\n status = []\n # whether the _item_ we're looking at should be included\n valid = True\n\n # checked out, will be a date if item is checked out\n if item['q'] and item['q'] != \"0\":\n status.append('checked out')\n\n # \"not for loan\", variety of reasons why an item might not circ\n if item['7'] and item['7'] != \"0\":\n status.append(notforloan_codes[item['7']])\n valid = False\n\n # 1 is an item is damanged\n if item['4'] and item['4'] != \"0\":\n status.append('damaged')\n valid = False\n\n # lost, variety of codes\n if item['1'] and item['1'] != \"0\":\n status.append(lost_codes[item['1']])\n valid = False\n\n # 1 if an item has been withdrawn\n if item['0'] and item['0'] != \"0\":\n status.append('withdrawn')\n valid = False\n\n # filter items based on location & type\n if item['c'] not in valid_locations:\n valid = False\n\n if item['y'] not in valid_types:\n valid = False\n\n if len(status) > 0 and options.get('--debug'):\n print('\"' + record.title() + '\" item status: ' + ', '.join(status))\n\n return valid\n\n\ndef main():\n total_count = 0\n valid_count = 0\n with open(options['INPUT'], 'rb') as fh:\n reader = MARCReader(fh, to_unicode=True, force_utf8=True)\n # 1) first mode: write a MARC output file\n if not options['--csv']:\n writer = MARCWriter(open('out.mrc' or options['--output'], 'wb'))\n for record in reader:\n # whether we'll include the _bib_ record in export file\n include_record = False\n # Koha stores item data in 952 fields, one per item\n for item in record.get_fields('952'):\n valid = validate_item(item)\n\n total_count += 1\n if valid is True:\n valid_count += 1\n # if there's any valid item then the bib should be included\n include_record = True\n\n if include_record is True:\n writer.write(record)\n\n print('Total items: %i | Items included: %i' % (total_count, valid_count))\n elif options['--csv']:\n koha_record_ids = set()\n for record in reader:\n total_count += 1\n for item in record.get_fields('952'):\n valid = validate_item(item)\n if valid:\n id = record.get_fields(MARC_ID_FIELD)[0].get_subfields(MARC_ID_SUBFIELD)[0]\n koha_record_ids.add(id)\n # stop looking at items after we find the first valid one\n break\n\n csvreader = csv.DictReader(open(options['--csv'], 'r'))\n gg_record_ids = set()\n for row in csvreader:\n gg_record_ids.add(row[GG_ID_COLUMN])\n\n print('Total Koha Bibs: %i' % total_count)\n print('Koha Bibs with circulating items: %i ' % len(koha_record_ids))\n print('Total GreenGlass Bibs: %i' % len(gg_record_ids))\n print('Weeded Items (I in GG & not in Koha): %i' % len(gg_record_ids - koha_record_ids))\n print('Added Items (I in Koha & not in GG): %i' % len(koha_record_ids - gg_record_ids))\n\n\nif __name__ == '__main__':\n options = docopt(__doc__)\n # print(options)\n main()\n", "step-ids": [ 1, 2, 3, 5, 6 ] }
[ 1, 2, 3, 5, 6 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> if __name__ == '__main__': sentence_url = 'http://www.manythings.org/anki/deu-eng.zip' r = requests.get(sentence_url) z = ZipFile(io.BytesIO(r.content)) file = z.read('deu.txt') eng_ger_data = file.decode() eng_ger_data = eng_ger_data.encode('ascii', errors='ignore') eng_ger_data = eng_ger_data.decode().split('\n') eng_ger_data = [x.split('\t') for x in eng_ger_data if len(x) >= 1] [english_sentence, german_sentence] = [list(x) for x in zip(*eng_ger_data)] print(len(english_sentence)) print(len(german_sentence)) print(eng_ger_data[9]) print(eng_ger_data[10]) print(german_sentence) <|reserved_special_token_1|> import requests import io from zipfile import ZipFile if __name__ == '__main__': sentence_url = 'http://www.manythings.org/anki/deu-eng.zip' r = requests.get(sentence_url) z = ZipFile(io.BytesIO(r.content)) file = z.read('deu.txt') eng_ger_data = file.decode() eng_ger_data = eng_ger_data.encode('ascii', errors='ignore') eng_ger_data = eng_ger_data.decode().split('\n') eng_ger_data = [x.split('\t') for x in eng_ger_data if len(x) >= 1] [english_sentence, german_sentence] = [list(x) for x in zip(*eng_ger_data)] print(len(english_sentence)) print(len(german_sentence)) print(eng_ger_data[9]) print(eng_ger_data[10]) print(german_sentence) <|reserved_special_token_1|> # coding:utf-8 import requests import io from zipfile import ZipFile if __name__ == '__main__': sentence_url = "http://www.manythings.org/anki/deu-eng.zip" r = requests.get(sentence_url) z = ZipFile(io.BytesIO(r.content)) file = z.read('deu.txt') eng_ger_data = file.decode() eng_ger_data = eng_ger_data.encode('ascii', errors='ignore') eng_ger_data = eng_ger_data.decode().split('\n') eng_ger_data = [x.split('\t') for x in eng_ger_data if len(x) >= 1] [english_sentence, german_sentence] = [list(x) for x in zip(*eng_ger_data)] print(len(english_sentence)) print(len(german_sentence)) print(eng_ger_data[9]) print(eng_ger_data[10]) print(german_sentence)
flexible
{ "blob_id": "559c665e5544dd864d2f020c967ac8a8665af134", "index": 6805, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n sentence_url = 'http://www.manythings.org/anki/deu-eng.zip'\n r = requests.get(sentence_url)\n z = ZipFile(io.BytesIO(r.content))\n file = z.read('deu.txt')\n eng_ger_data = file.decode()\n eng_ger_data = eng_ger_data.encode('ascii', errors='ignore')\n eng_ger_data = eng_ger_data.decode().split('\\n')\n eng_ger_data = [x.split('\\t') for x in eng_ger_data if len(x) >= 1]\n [english_sentence, german_sentence] = [list(x) for x in zip(*eng_ger_data)]\n print(len(english_sentence))\n print(len(german_sentence))\n print(eng_ger_data[9])\n print(eng_ger_data[10])\n print(german_sentence)\n", "step-3": "import requests\nimport io\nfrom zipfile import ZipFile\nif __name__ == '__main__':\n sentence_url = 'http://www.manythings.org/anki/deu-eng.zip'\n r = requests.get(sentence_url)\n z = ZipFile(io.BytesIO(r.content))\n file = z.read('deu.txt')\n eng_ger_data = file.decode()\n eng_ger_data = eng_ger_data.encode('ascii', errors='ignore')\n eng_ger_data = eng_ger_data.decode().split('\\n')\n eng_ger_data = [x.split('\\t') for x in eng_ger_data if len(x) >= 1]\n [english_sentence, german_sentence] = [list(x) for x in zip(*eng_ger_data)]\n print(len(english_sentence))\n print(len(german_sentence))\n print(eng_ger_data[9])\n print(eng_ger_data[10])\n print(german_sentence)\n", "step-4": "# coding:utf-8\nimport requests\nimport io\nfrom zipfile import ZipFile\n\nif __name__ == '__main__':\n sentence_url = \"http://www.manythings.org/anki/deu-eng.zip\"\n r = requests.get(sentence_url)\n z = ZipFile(io.BytesIO(r.content))\n file = z.read('deu.txt')\n eng_ger_data = file.decode()\n eng_ger_data = eng_ger_data.encode('ascii', errors='ignore')\n eng_ger_data = eng_ger_data.decode().split('\\n')\n eng_ger_data = [x.split('\\t') for x in eng_ger_data if len(x) >= 1]\n [english_sentence, german_sentence] = [list(x) for x in zip(*eng_ger_data)]\n print(len(english_sentence))\n print(len(german_sentence))\n print(eng_ger_data[9])\n print(eng_ger_data[10])\n print(german_sentence)\n\n\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> ID = '113' TITLE = 'Path Sum II' DIFFICULTY = 'Medium' URL = 'https://oj.leetcode.com/problems/path-sum-ii/' BOOK = False PROBLEM = """Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example: Given the below binary tree and `sum = 22`, 5 / \\ 4 8 / / \\ 11 13 4 / \\ / \\ 7 2 5 1 return [ [5,4,11,2], [5,8,4,5] ] """ <|reserved_special_token_1|> ID = '113' TITLE = 'Path Sum II' DIFFICULTY = 'Medium' URL = 'https://oj.leetcode.com/problems/path-sum-ii/' BOOK = False PROBLEM = r"""Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example: Given the below binary tree and `sum = 22`, 5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1 return [ [5,4,11,2], [5,8,4,5] ] """
flexible
{ "blob_id": "9a62a57f6d9af7ef09c8ed6e78a100df7978da6e", "index": 8631, "step-1": "<mask token>\n", "step-2": "ID = '113'\nTITLE = 'Path Sum II'\nDIFFICULTY = 'Medium'\nURL = 'https://oj.leetcode.com/problems/path-sum-ii/'\nBOOK = False\nPROBLEM = \"\"\"Given a binary tree and a sum, find all root-to-leaf paths where each path's\nsum equals the given sum.\n\nFor example: \nGiven the below binary tree and `sum = 22`,\n\n \n \n \n 5\n / \\\\\n 4 8\n / / \\\\\n 11 13 4\n / \\\\ / \\\\\n 7 2 5 1\n \n\nreturn \n\n \n \n \n [\n [5,4,11,2],\n [5,8,4,5]\n ]\n \n\n\n\"\"\"\n", "step-3": "ID = '113'\nTITLE = 'Path Sum II'\nDIFFICULTY = 'Medium'\nURL = 'https://oj.leetcode.com/problems/path-sum-ii/'\nBOOK = False\nPROBLEM = r\"\"\"Given a binary tree and a sum, find all root-to-leaf paths where each path's\nsum equals the given sum.\n\nFor example: \nGiven the below binary tree and `sum = 22`,\n\n \n \n \n 5\n / \\\n 4 8\n / / \\\n 11 13 4\n / \\ / \\\n 7 2 5 1\n \n\nreturn \n\n \n \n \n [\n [5,4,11,2],\n [5,8,4,5]\n ]\n \n\n\n\"\"\"\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
import numpy as np import cv2 print("read imafe from file" ) img = cv2.imread("panda.jpg") print("create a window holder for the image") cv2.namedWindow("Image",cv2.WINDOW_NORMAL) print ('display the image ') cv2.imshow("Image",img) print ('press a key inside the image to make a copy') cv2.waitKey(0)
normal
{ "blob_id": "7cf6a4b8057280b38572dd92693013724751c47f", "index": 9502, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint('read imafe from file')\n<mask token>\nprint('create a window holder for the image')\ncv2.namedWindow('Image', cv2.WINDOW_NORMAL)\nprint('display the image ')\ncv2.imshow('Image', img)\nprint('press a key inside the image to make a copy')\ncv2.waitKey(0)\n", "step-3": "<mask token>\nprint('read imafe from file')\nimg = cv2.imread('panda.jpg')\nprint('create a window holder for the image')\ncv2.namedWindow('Image', cv2.WINDOW_NORMAL)\nprint('display the image ')\ncv2.imshow('Image', img)\nprint('press a key inside the image to make a copy')\ncv2.waitKey(0)\n", "step-4": "import numpy as np\nimport cv2\nprint('read imafe from file')\nimg = cv2.imread('panda.jpg')\nprint('create a window holder for the image')\ncv2.namedWindow('Image', cv2.WINDOW_NORMAL)\nprint('display the image ')\ncv2.imshow('Image', img)\nprint('press a key inside the image to make a copy')\ncv2.waitKey(0)\n", "step-5": "import numpy as np \nimport cv2\n\n\nprint(\"read imafe from file\" )\nimg = cv2.imread(\"panda.jpg\")\n\nprint(\"create a window holder for the image\")\ncv2.namedWindow(\"Image\",cv2.WINDOW_NORMAL)\n\nprint ('display the image ')\ncv2.imshow(\"Image\",img)\n\nprint ('press a key inside the image to make a copy')\ncv2.waitKey(0)\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> @app.route('/') def hello(): return render_template('index.html') @app.route('/', methods=['POST']) def func(): st = request.form['review'] if st == '': return render_template('index.html') english = spacy.load('en_core_web_sm') result = english(st) sentences = [str(s) for s in result.sents] analyzer = vaderSentiment.SentimentIntensityAnalyzer() sentiment = [analyzer.polarity_scores(str(s)) for s in sentences] if sentiment[0]['compound'] >= 0.05: sent = 'Positive ' emoji = 128512 address = ( ' https://st.depositphotos.com/1016482/2236/i/950/depositphotos_22362437-stock-photo-background-with-heap-of-yellow.jpg' ) elif sentiment[0]['compound'] <= -0.05: sent = 'Negative ' emoji = 128577 address = ( 'https://www.ecopetit.cat/wpic/mpic/270-2706765_sad-emoji-cover-photo-for-fb.jpg ' ) else: sent = 'Neutral ' emoji = 128528 address = ( 'https://atlas-content-cdn.pixelsquid.com/stock-images/neutral-face-facial-expression-L63Mrq1-600.jpg ' ) return render_template('output.html', sentence=st, sent=sent, emoji= emoji, address=address) @app.route('/fu.html') def result(): return render_template('fu.html') @app.route('/new.html') def new(): return render_template('new.html') <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> @app.route('/') def hello(): return render_template('index.html') @app.route('/', methods=['POST']) def func(): st = request.form['review'] if st == '': return render_template('index.html') english = spacy.load('en_core_web_sm') result = english(st) sentences = [str(s) for s in result.sents] analyzer = vaderSentiment.SentimentIntensityAnalyzer() sentiment = [analyzer.polarity_scores(str(s)) for s in sentences] if sentiment[0]['compound'] >= 0.05: sent = 'Positive ' emoji = 128512 address = ( ' https://st.depositphotos.com/1016482/2236/i/950/depositphotos_22362437-stock-photo-background-with-heap-of-yellow.jpg' ) elif sentiment[0]['compound'] <= -0.05: sent = 'Negative ' emoji = 128577 address = ( 'https://www.ecopetit.cat/wpic/mpic/270-2706765_sad-emoji-cover-photo-for-fb.jpg ' ) else: sent = 'Neutral ' emoji = 128528 address = ( 'https://atlas-content-cdn.pixelsquid.com/stock-images/neutral-face-facial-expression-L63Mrq1-600.jpg ' ) return render_template('output.html', sentence=st, sent=sent, emoji= emoji, address=address) @app.route('/fu.html') def result(): return render_template('fu.html') @app.route('/new.html') def new(): return render_template('new.html') if __name__ == '__main__': app.run(debug=True) <|reserved_special_token_1|> <|reserved_special_token_0|> app = Flask(__name__) @app.route('/') def hello(): return render_template('index.html') @app.route('/', methods=['POST']) def func(): st = request.form['review'] if st == '': return render_template('index.html') english = spacy.load('en_core_web_sm') result = english(st) sentences = [str(s) for s in result.sents] analyzer = vaderSentiment.SentimentIntensityAnalyzer() sentiment = [analyzer.polarity_scores(str(s)) for s in sentences] if sentiment[0]['compound'] >= 0.05: sent = 'Positive ' emoji = 128512 address = ( ' https://st.depositphotos.com/1016482/2236/i/950/depositphotos_22362437-stock-photo-background-with-heap-of-yellow.jpg' ) elif sentiment[0]['compound'] <= -0.05: sent = 'Negative ' emoji = 128577 address = ( 'https://www.ecopetit.cat/wpic/mpic/270-2706765_sad-emoji-cover-photo-for-fb.jpg ' ) else: sent = 'Neutral ' emoji = 128528 address = ( 'https://atlas-content-cdn.pixelsquid.com/stock-images/neutral-face-facial-expression-L63Mrq1-600.jpg ' ) return render_template('output.html', sentence=st, sent=sent, emoji= emoji, address=address) @app.route('/fu.html') def result(): return render_template('fu.html') @app.route('/new.html') def new(): return render_template('new.html') if __name__ == '__main__': app.run(debug=True) <|reserved_special_token_1|> import spacy from vaderSentiment import vaderSentiment from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def hello(): return render_template('index.html') @app.route('/', methods=['POST']) def func(): st = request.form['review'] if st == '': return render_template('index.html') english = spacy.load('en_core_web_sm') result = english(st) sentences = [str(s) for s in result.sents] analyzer = vaderSentiment.SentimentIntensityAnalyzer() sentiment = [analyzer.polarity_scores(str(s)) for s in sentences] if sentiment[0]['compound'] >= 0.05: sent = 'Positive ' emoji = 128512 address = ( ' https://st.depositphotos.com/1016482/2236/i/950/depositphotos_22362437-stock-photo-background-with-heap-of-yellow.jpg' ) elif sentiment[0]['compound'] <= -0.05: sent = 'Negative ' emoji = 128577 address = ( 'https://www.ecopetit.cat/wpic/mpic/270-2706765_sad-emoji-cover-photo-for-fb.jpg ' ) else: sent = 'Neutral ' emoji = 128528 address = ( 'https://atlas-content-cdn.pixelsquid.com/stock-images/neutral-face-facial-expression-L63Mrq1-600.jpg ' ) return render_template('output.html', sentence=st, sent=sent, emoji= emoji, address=address) @app.route('/fu.html') def result(): return render_template('fu.html') @app.route('/new.html') def new(): return render_template('new.html') if __name__ == '__main__': app.run(debug=True) <|reserved_special_token_1|> import spacy from vaderSentiment import vaderSentiment from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def hello(): return render_template('index.html') @app.route('/',methods=['POST']) def func(): st=request.form["review"] if(st==''): return render_template('index.html') english = spacy.load("en_core_web_sm") result = english(st) sentences = [str(s) for s in result.sents] analyzer = vaderSentiment.SentimentIntensityAnalyzer() sentiment = [analyzer.polarity_scores(str(s)) for s in sentences] if(sentiment[0]['compound'] >= 0.05) : sent="Positive " emoji=128512 address=' https://st.depositphotos.com/1016482/2236/i/950/depositphotos_22362437-stock-photo-background-with-heap-of-yellow.jpg' elif(sentiment[0]['compound'] <= - 0.05) : sent="Negative " emoji=128577 address='https://www.ecopetit.cat/wpic/mpic/270-2706765_sad-emoji-cover-photo-for-fb.jpg ' else : sent="Neutral " emoji=128528 address='https://atlas-content-cdn.pixelsquid.com/stock-images/neutral-face-facial-expression-L63Mrq1-600.jpg ' return render_template('output.html', sentence=st, sent=sent, emoji=emoji, address=address) @app.route('/fu.html') def result(): return render_template('fu.html') @app.route('/new.html') def new(): return render_template('new.html') if __name__ == '__main__': app.run(debug=True)
flexible
{ "blob_id": "2d7f7cb66480ecb8335949687854554679026959", "index": 9988, "step-1": "<mask token>\n\n\[email protected]('/')\ndef hello():\n return render_template('index.html')\n\n\[email protected]('/', methods=['POST'])\ndef func():\n st = request.form['review']\n if st == '':\n return render_template('index.html')\n english = spacy.load('en_core_web_sm')\n result = english(st)\n sentences = [str(s) for s in result.sents]\n analyzer = vaderSentiment.SentimentIntensityAnalyzer()\n sentiment = [analyzer.polarity_scores(str(s)) for s in sentences]\n if sentiment[0]['compound'] >= 0.05:\n sent = 'Positive '\n emoji = 128512\n address = (\n ' https://st.depositphotos.com/1016482/2236/i/950/depositphotos_22362437-stock-photo-background-with-heap-of-yellow.jpg'\n )\n elif sentiment[0]['compound'] <= -0.05:\n sent = 'Negative '\n emoji = 128577\n address = (\n 'https://www.ecopetit.cat/wpic/mpic/270-2706765_sad-emoji-cover-photo-for-fb.jpg '\n )\n else:\n sent = 'Neutral '\n emoji = 128528\n address = (\n 'https://atlas-content-cdn.pixelsquid.com/stock-images/neutral-face-facial-expression-L63Mrq1-600.jpg '\n )\n return render_template('output.html', sentence=st, sent=sent, emoji=\n emoji, address=address)\n\n\[email protected]('/fu.html')\ndef result():\n return render_template('fu.html')\n\n\[email protected]('/new.html')\ndef new():\n return render_template('new.html')\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\[email protected]('/')\ndef hello():\n return render_template('index.html')\n\n\[email protected]('/', methods=['POST'])\ndef func():\n st = request.form['review']\n if st == '':\n return render_template('index.html')\n english = spacy.load('en_core_web_sm')\n result = english(st)\n sentences = [str(s) for s in result.sents]\n analyzer = vaderSentiment.SentimentIntensityAnalyzer()\n sentiment = [analyzer.polarity_scores(str(s)) for s in sentences]\n if sentiment[0]['compound'] >= 0.05:\n sent = 'Positive '\n emoji = 128512\n address = (\n ' https://st.depositphotos.com/1016482/2236/i/950/depositphotos_22362437-stock-photo-background-with-heap-of-yellow.jpg'\n )\n elif sentiment[0]['compound'] <= -0.05:\n sent = 'Negative '\n emoji = 128577\n address = (\n 'https://www.ecopetit.cat/wpic/mpic/270-2706765_sad-emoji-cover-photo-for-fb.jpg '\n )\n else:\n sent = 'Neutral '\n emoji = 128528\n address = (\n 'https://atlas-content-cdn.pixelsquid.com/stock-images/neutral-face-facial-expression-L63Mrq1-600.jpg '\n )\n return render_template('output.html', sentence=st, sent=sent, emoji=\n emoji, address=address)\n\n\[email protected]('/fu.html')\ndef result():\n return render_template('fu.html')\n\n\[email protected]('/new.html')\ndef new():\n return render_template('new.html')\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n", "step-3": "<mask token>\napp = Flask(__name__)\n\n\[email protected]('/')\ndef hello():\n return render_template('index.html')\n\n\[email protected]('/', methods=['POST'])\ndef func():\n st = request.form['review']\n if st == '':\n return render_template('index.html')\n english = spacy.load('en_core_web_sm')\n result = english(st)\n sentences = [str(s) for s in result.sents]\n analyzer = vaderSentiment.SentimentIntensityAnalyzer()\n sentiment = [analyzer.polarity_scores(str(s)) for s in sentences]\n if sentiment[0]['compound'] >= 0.05:\n sent = 'Positive '\n emoji = 128512\n address = (\n ' https://st.depositphotos.com/1016482/2236/i/950/depositphotos_22362437-stock-photo-background-with-heap-of-yellow.jpg'\n )\n elif sentiment[0]['compound'] <= -0.05:\n sent = 'Negative '\n emoji = 128577\n address = (\n 'https://www.ecopetit.cat/wpic/mpic/270-2706765_sad-emoji-cover-photo-for-fb.jpg '\n )\n else:\n sent = 'Neutral '\n emoji = 128528\n address = (\n 'https://atlas-content-cdn.pixelsquid.com/stock-images/neutral-face-facial-expression-L63Mrq1-600.jpg '\n )\n return render_template('output.html', sentence=st, sent=sent, emoji=\n emoji, address=address)\n\n\[email protected]('/fu.html')\ndef result():\n return render_template('fu.html')\n\n\[email protected]('/new.html')\ndef new():\n return render_template('new.html')\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n", "step-4": "import spacy\nfrom vaderSentiment import vaderSentiment\nfrom flask import Flask, render_template, request\napp = Flask(__name__)\n\n\[email protected]('/')\ndef hello():\n return render_template('index.html')\n\n\[email protected]('/', methods=['POST'])\ndef func():\n st = request.form['review']\n if st == '':\n return render_template('index.html')\n english = spacy.load('en_core_web_sm')\n result = english(st)\n sentences = [str(s) for s in result.sents]\n analyzer = vaderSentiment.SentimentIntensityAnalyzer()\n sentiment = [analyzer.polarity_scores(str(s)) for s in sentences]\n if sentiment[0]['compound'] >= 0.05:\n sent = 'Positive '\n emoji = 128512\n address = (\n ' https://st.depositphotos.com/1016482/2236/i/950/depositphotos_22362437-stock-photo-background-with-heap-of-yellow.jpg'\n )\n elif sentiment[0]['compound'] <= -0.05:\n sent = 'Negative '\n emoji = 128577\n address = (\n 'https://www.ecopetit.cat/wpic/mpic/270-2706765_sad-emoji-cover-photo-for-fb.jpg '\n )\n else:\n sent = 'Neutral '\n emoji = 128528\n address = (\n 'https://atlas-content-cdn.pixelsquid.com/stock-images/neutral-face-facial-expression-L63Mrq1-600.jpg '\n )\n return render_template('output.html', sentence=st, sent=sent, emoji=\n emoji, address=address)\n\n\[email protected]('/fu.html')\ndef result():\n return render_template('fu.html')\n\n\[email protected]('/new.html')\ndef new():\n return render_template('new.html')\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n", "step-5": "import spacy\nfrom vaderSentiment import vaderSentiment\nfrom flask import Flask, render_template, request\napp = Flask(__name__)\n\[email protected]('/')\ndef hello():\n return render_template('index.html')\n \[email protected]('/',methods=['POST'])\ndef func():\n st=request.form[\"review\"]\n if(st==''):\n return render_template('index.html')\n english = spacy.load(\"en_core_web_sm\")\n result = english(st)\n sentences = [str(s) for s in result.sents]\n analyzer = vaderSentiment.SentimentIntensityAnalyzer()\n sentiment = [analyzer.polarity_scores(str(s)) for s in sentences]\n \n \n if(sentiment[0]['compound'] >= 0.05) : \n sent=\"Positive \" \n emoji=128512\n address=' https://st.depositphotos.com/1016482/2236/i/950/depositphotos_22362437-stock-photo-background-with-heap-of-yellow.jpg'\n \n elif(sentiment[0]['compound'] <= - 0.05) : \n sent=\"Negative \"\n emoji=128577\n address='https://www.ecopetit.cat/wpic/mpic/270-2706765_sad-emoji-cover-photo-for-fb.jpg '\n \n else :\n sent=\"Neutral \"\n emoji=128528\n address='https://atlas-content-cdn.pixelsquid.com/stock-images/neutral-face-facial-expression-L63Mrq1-600.jpg '\n \n \n return render_template('output.html', sentence=st, sent=sent, emoji=emoji, address=address)\n \n\[email protected]('/fu.html')\ndef result():\n return render_template('fu.html')\n\[email protected]('/new.html')\ndef new():\n return render_template('new.html')\n\nif __name__ == '__main__':\n app.run(debug=True)\n", "step-ids": [ 4, 5, 6, 7, 8 ] }
[ 4, 5, 6, 7, 8 ]
import json import os from flask import Flask, request, url_for from flask_cors import CORS from werkzeug.utils import secure_filename from service.Binarizacion import Binarizacion UPLOAD_FOLDER = './public/files' app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER CORS(app) @app.route('/') def hello(): return 'Hello word' @app.route('/analyze', methods=['POST']) def analyze(): if request.method == 'POST': image_file = request.files['image'] file_name = secure_filename(image_file.filename) # image_file.save('./public/files/' + secure_filename(image_file.filename)) image_file.save(os.path.join(app.config['UPLOAD_FOLDER'], file_name)) print(f'{UPLOAD_FOLDER}/{file_name}', os.path.join(app.config['UPLOAD_FOLDER'])) binarization = Binarizacion(f'./public/files/{file_name}') binarization.binaryImage() binarization.otsuImage() binarization.adatativeImage() binarization.fondoMorfologico() m, color, diametro, pre = binarization.analize() return json.dumps({'ok': True, 'url': f'./public/files/{file_name}', 'm': m, 'color': color, 'diametro': diametro, 'pre': pre}) return json.dumps({'ok': False})
normal
{ "blob_id": "b9c8689dbdf451e6a981f1abdae55771266fe231", "index": 9129, "step-1": "<mask token>\n\n\[email protected]('/')\ndef hello():\n return 'Hello word'\n\n\[email protected]('/analyze', methods=['POST'])\ndef analyze():\n if request.method == 'POST':\n image_file = request.files['image']\n file_name = secure_filename(image_file.filename)\n image_file.save(os.path.join(app.config['UPLOAD_FOLDER'], file_name))\n print(f'{UPLOAD_FOLDER}/{file_name}', os.path.join(app.config[\n 'UPLOAD_FOLDER']))\n binarization = Binarizacion(f'./public/files/{file_name}')\n binarization.binaryImage()\n binarization.otsuImage()\n binarization.adatativeImage()\n binarization.fondoMorfologico()\n m, color, diametro, pre = binarization.analize()\n return json.dumps({'ok': True, 'url': f'./public/files/{file_name}',\n 'm': m, 'color': color, 'diametro': diametro, 'pre': pre})\n return json.dumps({'ok': False})\n", "step-2": "<mask token>\nCORS(app)\n\n\[email protected]('/')\ndef hello():\n return 'Hello word'\n\n\[email protected]('/analyze', methods=['POST'])\ndef analyze():\n if request.method == 'POST':\n image_file = request.files['image']\n file_name = secure_filename(image_file.filename)\n image_file.save(os.path.join(app.config['UPLOAD_FOLDER'], file_name))\n print(f'{UPLOAD_FOLDER}/{file_name}', os.path.join(app.config[\n 'UPLOAD_FOLDER']))\n binarization = Binarizacion(f'./public/files/{file_name}')\n binarization.binaryImage()\n binarization.otsuImage()\n binarization.adatativeImage()\n binarization.fondoMorfologico()\n m, color, diametro, pre = binarization.analize()\n return json.dumps({'ok': True, 'url': f'./public/files/{file_name}',\n 'm': m, 'color': color, 'diametro': diametro, 'pre': pre})\n return json.dumps({'ok': False})\n", "step-3": "<mask token>\nUPLOAD_FOLDER = './public/files'\napp = Flask(__name__)\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\nCORS(app)\n\n\[email protected]('/')\ndef hello():\n return 'Hello word'\n\n\[email protected]('/analyze', methods=['POST'])\ndef analyze():\n if request.method == 'POST':\n image_file = request.files['image']\n file_name = secure_filename(image_file.filename)\n image_file.save(os.path.join(app.config['UPLOAD_FOLDER'], file_name))\n print(f'{UPLOAD_FOLDER}/{file_name}', os.path.join(app.config[\n 'UPLOAD_FOLDER']))\n binarization = Binarizacion(f'./public/files/{file_name}')\n binarization.binaryImage()\n binarization.otsuImage()\n binarization.adatativeImage()\n binarization.fondoMorfologico()\n m, color, diametro, pre = binarization.analize()\n return json.dumps({'ok': True, 'url': f'./public/files/{file_name}',\n 'm': m, 'color': color, 'diametro': diametro, 'pre': pre})\n return json.dumps({'ok': False})\n", "step-4": "import json\nimport os\nfrom flask import Flask, request, url_for\nfrom flask_cors import CORS\nfrom werkzeug.utils import secure_filename\nfrom service.Binarizacion import Binarizacion\nUPLOAD_FOLDER = './public/files'\napp = Flask(__name__)\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\nCORS(app)\n\n\[email protected]('/')\ndef hello():\n return 'Hello word'\n\n\[email protected]('/analyze', methods=['POST'])\ndef analyze():\n if request.method == 'POST':\n image_file = request.files['image']\n file_name = secure_filename(image_file.filename)\n image_file.save(os.path.join(app.config['UPLOAD_FOLDER'], file_name))\n print(f'{UPLOAD_FOLDER}/{file_name}', os.path.join(app.config[\n 'UPLOAD_FOLDER']))\n binarization = Binarizacion(f'./public/files/{file_name}')\n binarization.binaryImage()\n binarization.otsuImage()\n binarization.adatativeImage()\n binarization.fondoMorfologico()\n m, color, diametro, pre = binarization.analize()\n return json.dumps({'ok': True, 'url': f'./public/files/{file_name}',\n 'm': m, 'color': color, 'diametro': diametro, 'pre': pre})\n return json.dumps({'ok': False})\n", "step-5": "import json\nimport os\n\nfrom flask import Flask, request, url_for\nfrom flask_cors import CORS\nfrom werkzeug.utils import secure_filename\n\nfrom service.Binarizacion import Binarizacion\n\nUPLOAD_FOLDER = './public/files'\n\napp = Flask(__name__)\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\nCORS(app)\n\[email protected]('/')\ndef hello():\n return 'Hello word'\n\[email protected]('/analyze', methods=['POST'])\ndef analyze():\n if request.method == 'POST':\n image_file = request.files['image']\n file_name = secure_filename(image_file.filename)\n # image_file.save('./public/files/' + secure_filename(image_file.filename))\n image_file.save(os.path.join(app.config['UPLOAD_FOLDER'], file_name))\n \n print(f'{UPLOAD_FOLDER}/{file_name}', os.path.join(app.config['UPLOAD_FOLDER']))\n binarization = Binarizacion(f'./public/files/{file_name}')\n binarization.binaryImage()\n binarization.otsuImage()\n binarization.adatativeImage()\n binarization.fondoMorfologico()\n \n m, color, diametro, pre = binarization.analize()\n \n return json.dumps({'ok': True, 'url': f'./public/files/{file_name}',\n 'm': m,\n 'color': color,\n 'diametro': diametro,\n 'pre': pre})\n \n return json.dumps({'ok': False})\n", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
# -*- coding: utf-8 -*- import numpy as np import pickle import os import feature_extraction #import topic file1 = open('vecdict_all.p', 'r') file2 = open('classif_all.p','r') vec = pickle.load(file1) classifier = pickle.load(file2) file1.close() file2.close() #sentence = "I never miss the lecture of Dan Moldovan" #sentence = "Donald trump will make america great again" #sentence = "Messi is the best footballer in the world" #sentence = "Oh how I love being ignored" #sentence = "Absolutely adore it when my bus is late" #sentence = "I work 40 hours a week to be this poor" #sentence = "I love working at 3 AM" #sentence ="I love talking to myself" #sentence =" I like it when my boss is shouting at me" #sentence =" Monday mornings are so awesome" def getSarcasmScore(sentence): sentence = sentence.encode('ascii', 'ignore') features = feature_extraction.getallfeatureset(sentence) features_vec = vec.transform(features) score = classifier.decision_function(features_vec)[0] percentage = int(round(2.0*(1.0/(1.0+np.exp(-score))-0.5)*100.0)) return percentage while True: print "enter the sentence to get sarcastic score or type exit to quit" data = str(raw_input()) if data == "exit": break; else: print getSarcasmScore(data)
normal
{ "blob_id": "1d1576825f80c3b65ce1b7f8d1daccbbf8543d7d", "index": 8294, "step-1": "# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport pickle\nimport os\nimport feature_extraction\n#import topic\n\n\nfile1 = open('vecdict_all.p', 'r')\nfile2 = open('classif_all.p','r')\n\nvec = pickle.load(file1)\nclassifier = pickle.load(file2)\n\nfile1.close()\nfile2.close()\n\n#sentence = \"I never miss the lecture of Dan Moldovan\"\n#sentence = \"Donald trump will make america great again\"\n#sentence = \"Messi is the best footballer in the world\"\n#sentence = \"Oh how I love being ignored\"\n#sentence = \"Absolutely adore it when my bus is late\"\n#sentence = \"I work 40 hours a week to be this poor\"\n#sentence = \"I love working at 3 AM\"\n#sentence =\"I love talking to myself\"\n#sentence =\" I like it when my boss is shouting at me\"\n#sentence =\" Monday mornings are so awesome\"\n\ndef getSarcasmScore(sentence):\n sentence = sentence.encode('ascii', 'ignore')\n features = feature_extraction.getallfeatureset(sentence)\n \n features_vec = vec.transform(features)\n score = classifier.decision_function(features_vec)[0]\n percentage = int(round(2.0*(1.0/(1.0+np.exp(-score))-0.5)*100.0))\n \n return percentage\n\nwhile True:\n print \"enter the sentence to get sarcastic score or type exit to quit\"\n data = str(raw_input())\n if data == \"exit\":\n break;\n else:\n print getSarcasmScore(data)\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
<|reserved_special_token_0|> class SGD(BasicOptimizer): <|reserved_special_token_0|> def __init__(self, iterations: int, circuit: BasicCircuit, learning_rate: float): """The constructor of the SGD class Args: iterations (int): Number of iterations circuit (BasicCircuit): Circuit whose parameters are to be optimized learning_rate (float): Learning rate """ super().__init__(iterations, circuit) self._learning_rate = learning_rate <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class SGD(BasicOptimizer): <|reserved_special_token_0|> def __init__(self, iterations: int, circuit: BasicCircuit, learning_rate: float): """The constructor of the SGD class Args: iterations (int): Number of iterations circuit (BasicCircuit): Circuit whose parameters are to be optimized learning_rate (float): Learning rate """ super().__init__(iterations, circuit) self._learning_rate = learning_rate def minimize(self, shots: int, loss_func: Callable[[np.ndarray, int], float], grad_func: Callable[[np.ndarray, int], np.ndarray]) ->None: """Minimizes the given loss function Args: shots (int): Number of measurement shots loss_func (Callable[[np.ndarray, int], float]): Loss function to be minimized grad_func (Callable[[np.ndarray, int], np.ndarray]): Function for calculating gradients """ self._loss_history = [] for _ in tqdm(range(self._iterations)): curr_param = self._circuit.parameters gradient = grad_func(curr_param, shots) new_param = curr_param - self._learning_rate * gradient loss = loss_func(new_param, shots) self._loss_history.append(loss) <|reserved_special_token_1|> <|reserved_special_token_0|> class SGD(BasicOptimizer): """SGD Optimizer class """ def __init__(self, iterations: int, circuit: BasicCircuit, learning_rate: float): """The constructor of the SGD class Args: iterations (int): Number of iterations circuit (BasicCircuit): Circuit whose parameters are to be optimized learning_rate (float): Learning rate """ super().__init__(iterations, circuit) self._learning_rate = learning_rate def minimize(self, shots: int, loss_func: Callable[[np.ndarray, int], float], grad_func: Callable[[np.ndarray, int], np.ndarray]) ->None: """Minimizes the given loss function Args: shots (int): Number of measurement shots loss_func (Callable[[np.ndarray, int], float]): Loss function to be minimized grad_func (Callable[[np.ndarray, int], np.ndarray]): Function for calculating gradients """ self._loss_history = [] for _ in tqdm(range(self._iterations)): curr_param = self._circuit.parameters gradient = grad_func(curr_param, shots) new_param = curr_param - self._learning_rate * gradient loss = loss_func(new_param, shots) self._loss_history.append(loss) <|reserved_special_token_1|> <|reserved_special_token_0|> from typing import Callable import numpy as np from tqdm import tqdm from ..circuit import BasicCircuit from .basic_optimizer import BasicOptimizer class SGD(BasicOptimizer): """SGD Optimizer class """ def __init__(self, iterations: int, circuit: BasicCircuit, learning_rate: float): """The constructor of the SGD class Args: iterations (int): Number of iterations circuit (BasicCircuit): Circuit whose parameters are to be optimized learning_rate (float): Learning rate """ super().__init__(iterations, circuit) self._learning_rate = learning_rate def minimize(self, shots: int, loss_func: Callable[[np.ndarray, int], float], grad_func: Callable[[np.ndarray, int], np.ndarray]) ->None: """Minimizes the given loss function Args: shots (int): Number of measurement shots loss_func (Callable[[np.ndarray, int], float]): Loss function to be minimized grad_func (Callable[[np.ndarray, int], np.ndarray]): Function for calculating gradients """ self._loss_history = [] for _ in tqdm(range(self._iterations)): curr_param = self._circuit.parameters gradient = grad_func(curr_param, shots) new_param = curr_param - self._learning_rate * gradient loss = loss_func(new_param, shots) self._loss_history.append(loss) <|reserved_special_token_1|> # !/usr/bin/env python3 # -*- coding: UTF-8 -*- # Copyright (c) 2021 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Stochastic Gradient Descent """ from typing import Callable import numpy as np from tqdm import tqdm from ..circuit import BasicCircuit from .basic_optimizer import BasicOptimizer class SGD(BasicOptimizer): r"""SGD Optimizer class """ def __init__(self, iterations: int, circuit: BasicCircuit, learning_rate: float): r"""The constructor of the SGD class Args: iterations (int): Number of iterations circuit (BasicCircuit): Circuit whose parameters are to be optimized learning_rate (float): Learning rate """ super().__init__(iterations, circuit) self._learning_rate = learning_rate def minimize( self, shots: int, loss_func: Callable[[np.ndarray, int], float], grad_func: Callable[[np.ndarray, int], np.ndarray] ) -> None: r"""Minimizes the given loss function Args: shots (int): Number of measurement shots loss_func (Callable[[np.ndarray, int], float]): Loss function to be minimized grad_func (Callable[[np.ndarray, int], np.ndarray]): Function for calculating gradients """ self._loss_history = [] for _ in tqdm(range(self._iterations)): curr_param = self._circuit.parameters gradient = grad_func(curr_param, shots) new_param = curr_param - self._learning_rate * gradient loss = loss_func(new_param, shots) self._loss_history.append(loss)
flexible
{ "blob_id": "129df937d7d295bae2009cfb65b2f85228206698", "index": 8657, "step-1": "<mask token>\n\n\nclass SGD(BasicOptimizer):\n <mask token>\n\n def __init__(self, iterations: int, circuit: BasicCircuit,\n learning_rate: float):\n \"\"\"The constructor of the SGD class\n\n Args:\n iterations (int): Number of iterations\n circuit (BasicCircuit): Circuit whose parameters are to be optimized\n learning_rate (float): Learning rate\n\n \"\"\"\n super().__init__(iterations, circuit)\n self._learning_rate = learning_rate\n <mask token>\n", "step-2": "<mask token>\n\n\nclass SGD(BasicOptimizer):\n <mask token>\n\n def __init__(self, iterations: int, circuit: BasicCircuit,\n learning_rate: float):\n \"\"\"The constructor of the SGD class\n\n Args:\n iterations (int): Number of iterations\n circuit (BasicCircuit): Circuit whose parameters are to be optimized\n learning_rate (float): Learning rate\n\n \"\"\"\n super().__init__(iterations, circuit)\n self._learning_rate = learning_rate\n\n def minimize(self, shots: int, loss_func: Callable[[np.ndarray, int],\n float], grad_func: Callable[[np.ndarray, int], np.ndarray]) ->None:\n \"\"\"Minimizes the given loss function\n\n Args:\n shots (int): Number of measurement shots\n loss_func (Callable[[np.ndarray, int], float]): Loss function to be minimized\n grad_func (Callable[[np.ndarray, int], np.ndarray]): Function for calculating gradients\n\n \"\"\"\n self._loss_history = []\n for _ in tqdm(range(self._iterations)):\n curr_param = self._circuit.parameters\n gradient = grad_func(curr_param, shots)\n new_param = curr_param - self._learning_rate * gradient\n loss = loss_func(new_param, shots)\n self._loss_history.append(loss)\n", "step-3": "<mask token>\n\n\nclass SGD(BasicOptimizer):\n \"\"\"SGD Optimizer class\n \"\"\"\n\n def __init__(self, iterations: int, circuit: BasicCircuit,\n learning_rate: float):\n \"\"\"The constructor of the SGD class\n\n Args:\n iterations (int): Number of iterations\n circuit (BasicCircuit): Circuit whose parameters are to be optimized\n learning_rate (float): Learning rate\n\n \"\"\"\n super().__init__(iterations, circuit)\n self._learning_rate = learning_rate\n\n def minimize(self, shots: int, loss_func: Callable[[np.ndarray, int],\n float], grad_func: Callable[[np.ndarray, int], np.ndarray]) ->None:\n \"\"\"Minimizes the given loss function\n\n Args:\n shots (int): Number of measurement shots\n loss_func (Callable[[np.ndarray, int], float]): Loss function to be minimized\n grad_func (Callable[[np.ndarray, int], np.ndarray]): Function for calculating gradients\n\n \"\"\"\n self._loss_history = []\n for _ in tqdm(range(self._iterations)):\n curr_param = self._circuit.parameters\n gradient = grad_func(curr_param, shots)\n new_param = curr_param - self._learning_rate * gradient\n loss = loss_func(new_param, shots)\n self._loss_history.append(loss)\n", "step-4": "<mask token>\nfrom typing import Callable\nimport numpy as np\nfrom tqdm import tqdm\nfrom ..circuit import BasicCircuit\nfrom .basic_optimizer import BasicOptimizer\n\n\nclass SGD(BasicOptimizer):\n \"\"\"SGD Optimizer class\n \"\"\"\n\n def __init__(self, iterations: int, circuit: BasicCircuit,\n learning_rate: float):\n \"\"\"The constructor of the SGD class\n\n Args:\n iterations (int): Number of iterations\n circuit (BasicCircuit): Circuit whose parameters are to be optimized\n learning_rate (float): Learning rate\n\n \"\"\"\n super().__init__(iterations, circuit)\n self._learning_rate = learning_rate\n\n def minimize(self, shots: int, loss_func: Callable[[np.ndarray, int],\n float], grad_func: Callable[[np.ndarray, int], np.ndarray]) ->None:\n \"\"\"Minimizes the given loss function\n\n Args:\n shots (int): Number of measurement shots\n loss_func (Callable[[np.ndarray, int], float]): Loss function to be minimized\n grad_func (Callable[[np.ndarray, int], np.ndarray]): Function for calculating gradients\n\n \"\"\"\n self._loss_history = []\n for _ in tqdm(range(self._iterations)):\n curr_param = self._circuit.parameters\n gradient = grad_func(curr_param, shots)\n new_param = curr_param - self._learning_rate * gradient\n loss = loss_func(new_param, shots)\n self._loss_history.append(loss)\n", "step-5": "# !/usr/bin/env python3\n# -*- coding: UTF-8 -*-\n# Copyright (c) 2021 Baidu, Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nStochastic Gradient Descent\n\"\"\"\n\nfrom typing import Callable\nimport numpy as np\nfrom tqdm import tqdm\nfrom ..circuit import BasicCircuit\nfrom .basic_optimizer import BasicOptimizer\n\n\nclass SGD(BasicOptimizer):\n r\"\"\"SGD Optimizer class\n \"\"\"\n def __init__(self, iterations: int, circuit: BasicCircuit, learning_rate: float):\n r\"\"\"The constructor of the SGD class\n\n Args:\n iterations (int): Number of iterations\n circuit (BasicCircuit): Circuit whose parameters are to be optimized\n learning_rate (float): Learning rate\n\n \"\"\"\n super().__init__(iterations, circuit)\n self._learning_rate = learning_rate\n\n def minimize(\n self, shots: int,\n loss_func: Callable[[np.ndarray, int], float],\n grad_func: Callable[[np.ndarray, int], np.ndarray]\n ) -> None:\n r\"\"\"Minimizes the given loss function\n\n Args:\n shots (int): Number of measurement shots\n loss_func (Callable[[np.ndarray, int], float]): Loss function to be minimized\n grad_func (Callable[[np.ndarray, int], np.ndarray]): Function for calculating gradients\n\n \"\"\"\n self._loss_history = []\n for _ in tqdm(range(self._iterations)):\n curr_param = self._circuit.parameters\n gradient = grad_func(curr_param, shots)\n new_param = curr_param - self._learning_rate * gradient\n loss = loss_func(new_param, shots)\n self._loss_history.append(loss)\n", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def cut_frames(data): pass <|reserved_special_token_1|> <|reserved_special_token_0|> def mfcc(data): pass def cut_frames(data): pass <|reserved_special_token_1|> import numpy as np import tensorflow as tf def mfcc(data): pass def cut_frames(data): pass
flexible
{ "blob_id": "8411acf6b27425357d212f5e220314daa019e023", "index": 9669, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef cut_frames(data):\n pass\n", "step-3": "<mask token>\n\n\ndef mfcc(data):\n pass\n\n\ndef cut_frames(data):\n pass\n", "step-4": "import numpy as np\nimport tensorflow as tf\n\n\ndef mfcc(data):\n pass\n\n\ndef cut_frames(data):\n pass\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
from numpy import* a=int(input('numero: ')) b='*' c='o' for i in range(a): d=(b*(a-i))+(c*(a-(a-i)))+(c*(a-(a-i)))+(b*(a-i)) print(d)
normal
{ "blob_id": "155b243ad7d93bcf2b74cd5b2bd3409ab7ec7473", "index": 8488, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in range(a):\n d = b * (a - i) + c * (a - (a - i)) + c * (a - (a - i)) + b * (a - i)\n print(d)\n", "step-3": "<mask token>\na = int(input('numero: '))\nb = '*'\nc = 'o'\nfor i in range(a):\n d = b * (a - i) + c * (a - (a - i)) + c * (a - (a - i)) + b * (a - i)\n print(d)\n", "step-4": "from numpy import *\na = int(input('numero: '))\nb = '*'\nc = 'o'\nfor i in range(a):\n d = b * (a - i) + c * (a - (a - i)) + c * (a - (a - i)) + b * (a - i)\n print(d)\n", "step-5": "from numpy import*\n\na=int(input('numero: '))\nb='*'\nc='o'\nfor i in range(a):\n\td=(b*(a-i))+(c*(a-(a-i)))+(c*(a-(a-i)))+(b*(a-i))\n\tprint(d)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> if 1 in string: string.remove(1) <|reserved_special_token_0|> string.remove(string[0]) <|reserved_special_token_0|> while string != []: tar = 0 length = len(string) i = 0 while i < len(string): cout = 0 count = 0 for j in mid: for k in range(2, min(string[i], j) + 1): if (string[i] % k == 0) & (j % k == 0): mid.append(string[i]) string.remove(string[i]) count = 1 break if count == 0: cout += 1 else: break if count == 0: i += 1 if cout == len(mid): tar += 1 if (tar == length) | (string == []): if len(mid) > result: result = len(mid) if string != []: mid = [string[0]] string.remove(string[0]) if len(mid) > result: reuslt = len(mid) print(result) <|reserved_special_token_1|> string = input() string = string.replace('(', '') string = string.replace(')', '') string = list(map(int, string.split(','))) if 1 in string: string.remove(1) mid = [string[0]] string.remove(string[0]) result = 0 tar = 0 while string != []: tar = 0 length = len(string) i = 0 while i < len(string): cout = 0 count = 0 for j in mid: for k in range(2, min(string[i], j) + 1): if (string[i] % k == 0) & (j % k == 0): mid.append(string[i]) string.remove(string[i]) count = 1 break if count == 0: cout += 1 else: break if count == 0: i += 1 if cout == len(mid): tar += 1 if (tar == length) | (string == []): if len(mid) > result: result = len(mid) if string != []: mid = [string[0]] string.remove(string[0]) if len(mid) > result: reuslt = len(mid) print(result) <|reserved_special_token_1|> string=input(); string=string.replace("(",""); string=string.replace(")",""); string=list(map(int,string.split(","))); if(1 in string): string.remove(1); mid=[string[0]]; string.remove(string[0]); result=0; tar=0; while(string!=[]): tar=0; length=len(string); i=0 while(i<len(string)): cout=0; count=0 for j in mid: for k in range(2,min(string[i],j)+1): if(string[i]%k==0)&(j%k==0): mid.append(string[i]); string.remove(string[i]); count=1; break; if(count==0): cout+=1; else: break; if(count==0): i+=1; if(cout==len(mid)): tar+=1; if (tar == length)|(string==[]): if (len(mid) > result): result = len(mid); if(string!=[]): mid = [string[0]]; string.remove((string[0])); if(len(mid)>result): reuslt=len(mid); print(result)
flexible
{ "blob_id": "6a8cab1fceffa0d70441cc600137417a8b81d7b1", "index": 6897, "step-1": "<mask token>\n", "step-2": "<mask token>\nif 1 in string:\n string.remove(1)\n<mask token>\nstring.remove(string[0])\n<mask token>\nwhile string != []:\n tar = 0\n length = len(string)\n i = 0\n while i < len(string):\n cout = 0\n count = 0\n for j in mid:\n for k in range(2, min(string[i], j) + 1):\n if (string[i] % k == 0) & (j % k == 0):\n mid.append(string[i])\n string.remove(string[i])\n count = 1\n break\n if count == 0:\n cout += 1\n else:\n break\n if count == 0:\n i += 1\n if cout == len(mid):\n tar += 1\n if (tar == length) | (string == []):\n if len(mid) > result:\n result = len(mid)\n if string != []:\n mid = [string[0]]\n string.remove(string[0])\nif len(mid) > result:\n reuslt = len(mid)\nprint(result)\n", "step-3": "string = input()\nstring = string.replace('(', '')\nstring = string.replace(')', '')\nstring = list(map(int, string.split(',')))\nif 1 in string:\n string.remove(1)\nmid = [string[0]]\nstring.remove(string[0])\nresult = 0\ntar = 0\nwhile string != []:\n tar = 0\n length = len(string)\n i = 0\n while i < len(string):\n cout = 0\n count = 0\n for j in mid:\n for k in range(2, min(string[i], j) + 1):\n if (string[i] % k == 0) & (j % k == 0):\n mid.append(string[i])\n string.remove(string[i])\n count = 1\n break\n if count == 0:\n cout += 1\n else:\n break\n if count == 0:\n i += 1\n if cout == len(mid):\n tar += 1\n if (tar == length) | (string == []):\n if len(mid) > result:\n result = len(mid)\n if string != []:\n mid = [string[0]]\n string.remove(string[0])\nif len(mid) > result:\n reuslt = len(mid)\nprint(result)\n", "step-4": "string=input();\nstring=string.replace(\"(\",\"\");\nstring=string.replace(\")\",\"\");\nstring=list(map(int,string.split(\",\")));\nif(1 in string):\n string.remove(1);\nmid=[string[0]];\nstring.remove(string[0]);\nresult=0;\ntar=0;\nwhile(string!=[]):\n tar=0;\n length=len(string);\n i=0\n while(i<len(string)):\n cout=0;\n count=0\n for j in mid:\n for k in range(2,min(string[i],j)+1):\n if(string[i]%k==0)&(j%k==0):\n mid.append(string[i]);\n string.remove(string[i]);\n count=1;\n break;\n if(count==0):\n cout+=1;\n else:\n break;\n if(count==0):\n i+=1;\n if(cout==len(mid)):\n tar+=1;\n if (tar == length)|(string==[]):\n if (len(mid) > result):\n result = len(mid);\n if(string!=[]):\n mid = [string[0]];\n string.remove((string[0]));\nif(len(mid)>result):\n reuslt=len(mid);\nprint(result)\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import random import string import datetime from app import db from dateutil.parser import parse as date_parse from flask_security import UserMixin, RoleMixin roles_users = db.Table('roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('users.id')), db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))) class Role(db.Model, RoleMixin): id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(80), unique=True) description = db.Column(db.String(255)) class StudyUsers(db.Model): __tablename__ = 'study_users' id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True) study_id = db.Column(db.Integer, db.ForeignKey('studies.id'), index=True) role = db.Column(db.Enum('labeller', 'owner', name='user_role')) def __init__(self, user_id, study_id, role): self.study_id = study_id self.user_id = user_id self.study_id = study_id self.role = role class Users(db.Model, UserMixin): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.Unicode) password = db.Column(db.String(255)) active = db.Column(db.Boolean()) confirmed_at = db.Column(db.DateTime()) study_roles = db.relationship('StudyUsers', backref=db.backref('users'), lazy='dynamic') labels = db.relationship('UserLabels', backref='users', lazy='dynamic') roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic')) def studies(self): return db.session.query(Studies, StudyUsers).\ join(StudyUsers).filter_by(user_id=self.id) def study_labels(self, study_id): return db.session.query(LabelledDatasets).\ filter_by(user_id=self.id).\ join(Datasets).filter_by(study_id=study_id).count() class StudyUploads(db.Model): __tablename__ = 'study_uploads' id = db.Column(db.Integer, primary_key=True) created_at = db.Column(db.DateTime, default=datetime.datetime.now) filename = db.Column(db.Unicode) data = db.Column(db.LargeBinary) study_id = db.Column(db.Integer, db.ForeignKey('studies.id'), index=True) state = db.Column(db.String(64), default='submitted', nullable=True) error_message = db.Column(db.Text, nullable=True) def __init__(self, filename, data, study_id): self.filename = filename self.data = data self.study_id = study_id class Studies(db.Model): __tablename__ = 'studies' id = db.Column(db.Integer, primary_key=True) created_at = db.Column(db.DateTime, default=datetime.datetime.now) title = db.Column(db.Unicode) y_min = db.Column(db.Float, default=0) y_max = db.Column(db.Float, default=200) token = db.Column(db.String, nullable=True) datasets = db.relationship('Datasets', lazy="dynamic", cascade="all, delete-orphan", backref="study") uploads = db.relationship('StudyUploads', lazy="dynamic", cascade="all, delete-orphan", backref="study") users = db.relationship('StudyUsers', backref=db.backref('studies'), lazy='dynamic') def __init__(self, title): self.title = title def most_recent_successful_job(self): return SZJob.query.filter(SZJob.study == self, SZJob.state == 'success').order_by(SZJob.created_at.desc()).first() def add_user(self, user, role): study_user = StudyUsers(user.id, self.id, role) for existing_user in self.users: if existing_user.user_id == user.id: return self.users.append(study_user) db.session.commit() def get_roles(self, user): roles = [study_user.role for study_user in self.users.filter_by(user_id=user.id).all()] return roles def is_labeller(self, user): return ("labeller" in self.get_roles(user)) or ("owner" in self.get_roles(user)) def is_owner(self, user): return "owner" in self.get_roles(user) def delete(self): for dataset in self.datasets: dataset.delete() self.uploads.delete() db.session.delete(self) db.session.commit() def labellers(self): return Users.query.join(StudyUsers).\ filter(StudyUsers.role == "labeller").\ filter(StudyUsers.study_id == self.id) def update_range(self): maxmin = db.session.query(db.func.max(DataPoints.value), db.func.min(DataPoints.value)).\ join(Datasets).filter(Datasets.study_id == self.id).first() self.y_max = maxmin[0] self.y_min = maxmin[1] db.session.commit() def has_jobs(self): resp = SZJob.query.filter(SZJob.study == self, ~SZJob.archived) return resp.count() > 0 def has_archived_jobs(self): resp = SZJob.query.filter(SZJob.study == self, SZJob.archived) return resp.count() > 0 def generate_token(self): self.token = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8)) return self.token def user_labels_as_csv(self): resp = db.session.execute("""SELECT user_labels.datapoint_id, user_labels.dataset_id, user_labels.user_id, label, users.email, datapoints.timestamp, datasets.title FROM user_labels JOIN datapoints ON user_labels.datapoint_id = datapoints.id JOIN users ON user_labels.user_id = users.id JOIN datasets ON user_labels.dataset_id = datasets.id WHERE study_id = :study_id""", {'study_id': self.id}) import StringIO import csv output = StringIO.StringIO() writer = csv.writer(output) writer.writerow(['datapoint_id', 'dataset_id', 'user_id', 'label', 'email', 'timestamp', 'title']) for row in resp: writer.writerow(row) return output.getvalue() class Datasets(db.Model): __tablename__ = 'datasets' id = db.Column(db.Integer, primary_key=True) created_at = db.Column(db.DateTime, default=datetime.datetime.now) title = db.Column(db.Unicode) study_id = db.Column(db.Integer, db.ForeignKey('studies.id'), index=True) notes = db.relationship('Notes', cascade="all, delete-orphan", backref="dataset", lazy="dynamic") user_labels = db.relationship('UserLabels', cascade="all, delete-orphan", backref="dataset", lazy="dynamic") data_points = db.relationship('DataPoints', cascade="all, delete-orphan", backref="dataset", lazy="dynamic") labelled = db.relationship('LabelledDatasets', cascade="all, delete-orphan", backref="dataset", lazy="dynamic") def __init__(self, title, study_id, notes=[], data_points=[]): self.title = title self.study_id = study_id self.notes = notes self.data_points = data_points def next(self): return Datasets.query.\ filter(Datasets.study_id == self.study_id).\ filter(Datasets.created_at < self.created_at).\ order_by(Datasets.created_at.desc()).\ first() def prev(self): return Datasets.query.\ filter(Datasets.study_id == self.study_id).\ filter(Datasets.created_at > self.created_at).\ order_by(Datasets.created_at).\ first() def items(self): return Datasets.query.\ filter(Datasets.study_id == self.study_id).\ order_by(Datasets.created_at.desc()).\ all() def labels_for_user(self, user): return db.session.query(Datasets, DataPoints, UserLabels).\ filter_by(id=self.id).\ join(UserLabels).filter_by(user_id=user.id).\ join(DataPoints).\ order_by(DataPoints.timestamp) def delete(self): self.user_labels.delete() self.notes.delete() self.data_points.delete() self.labelled.delete() db.session.delete(self) db.session.commit() def user_has_labelled(self, user): return self.labelled.filter_by(user_id=user.id).count() > 0 class LabelledDatasets(db.Model): __tablename__ = 'labelled_datasets' id = db.Column(db.Integer, primary_key=True) dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True) user_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True) def __init__(self, dataset_id, user_id): self.dataset_id = dataset_id self.user_id = user_id class Notes(db.Model): __tablename__ = 'notes' id = db.Column(db.Integer, primary_key=True) created_at = db.Column(db.DateTime, default=datetime.datetime.now) text = db.Column(db.Unicode) dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True) def __init__(self, text): self.text = text @classmethod def dict_from_parsed(cls, text, dataset_id): return dict( created_at=datetime.datetime.now(), text=text, dataset_id=dataset_id ) class DataPoints(db.Model): __tablename__ = 'datapoints' id = db.Column(db.Integer, primary_key=True) created_at = db.Column(db.DateTime, default=datetime.datetime.now) timestamp = db.Column(db.DateTime, index=True) unit = db.Column(db.String(16)) value = db.Column(db.Float) training = db.Column(db.Boolean) dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True) user_labels = db.relationship('UserLabels', backref="datapoint", lazy="dynamic", passive_deletes=True) result_data_points = db.relationship('ResultDataPoints', cascade="all, delete-orphan", backref="dataset", lazy="dynamic") def __init__(self, timestamp, unit, value): self.timestamp = timestamp self.unit = unit self.value = value @classmethod def dict_from_parsed(cls, parsed_point, dataset_id, training_selector): timestamp = date_parse(parsed_point[0]) return dict( created_at=datetime.datetime.now(), timestamp=timestamp, unit=parsed_point[1], value=float(parsed_point[2]), dataset_id=dataset_id, training=training_selector(timestamp) ) class ResultDataPoints(db.Model): __tablename__ = 'resultdatapoints' id = db.Column(db.Integer, primary_key=True) created_at = db.Column(db.DateTime, default=datetime.datetime.now) timestamp = db.Column(db.DateTime, index=True) value = db.Column(db.Float) prediction = db.Column(db.Float) job_id = db.Column(db.Integer, db.ForeignKey('sz_job.id')) datapoint_id = db.Column(db.Integer, db.ForeignKey('datapoints.id'), index=True) dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True) def __init__(self): pass @classmethod def dict_from_parsed(cls, parsed_point, dataset_id, training_selector): timestamp = date_parse(parsed_point[0]) return dict( created_at=datetime.datetime.now(), timestamp=timestamp, unit=parsed_point[1], value=float(parsed_point[2]), dataset_id=dataset_id, training=training_selector(timestamp) ) class UserLabels(db.Model): __tablename__ = 'user_labels' id = db.Column(db.Integer, primary_key=True) datapoint_id = db.Column(db.Integer, db.ForeignKey('datapoints.id'), index=True) dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True) user_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True) label = db.Column(db.Boolean) def __init__(self, datapoint_id, dataset_id, user_id, label=False): self.datapoint_id = datapoint_id self.dataset_id = dataset_id self.user_id = user_id self.label = False @classmethod def dicts_from_datapoints(cls, data_points, dataset_id, user_id): dicts = [dict(datapoint_id=data_point.id, dataset_id=dataset_id, user_id=user_id, label=False) for data_point in data_points] return dicts class SZJob(db.Model): id = db.Column(db.Integer, primary_key=True) study_id = db.Column(db.Integer, db.ForeignKey('studies.id'), index=True) created_at = db.Column(db.DateTime, default=datetime.datetime.now) state = db.Column(db.String(64), default='submitted') message = db.Column(db.Unicode, nullable=True) csv_blob = db.Column(db.Unicode, nullable=True) csv_binary_blob = db.Column(db.LargeBinary, nullable=True) archived = db.Column(db.Boolean, nullable=True, default=False) study = db.relationship('Studies', backref='szjobs')
normal
{ "blob_id": "06b07045fcfafd174bb78ff5c3a36bed11e36e54", "index": 9616, "step-1": "<mask token>\n\n\nclass Studies(db.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, title):\n self.title = title\n\n def most_recent_successful_job(self):\n return SZJob.query.filter(SZJob.study == self, SZJob.state == 'success'\n ).order_by(SZJob.created_at.desc()).first()\n\n def add_user(self, user, role):\n study_user = StudyUsers(user.id, self.id, role)\n for existing_user in self.users:\n if existing_user.user_id == user.id:\n return\n self.users.append(study_user)\n db.session.commit()\n <mask token>\n\n def is_labeller(self, user):\n return 'labeller' in self.get_roles(user) or 'owner' in self.get_roles(\n user)\n\n def is_owner(self, user):\n return 'owner' in self.get_roles(user)\n\n def delete(self):\n for dataset in self.datasets:\n dataset.delete()\n self.uploads.delete()\n db.session.delete(self)\n db.session.commit()\n\n def labellers(self):\n return Users.query.join(StudyUsers).filter(StudyUsers.role ==\n 'labeller').filter(StudyUsers.study_id == self.id)\n\n def update_range(self):\n maxmin = db.session.query(db.func.max(DataPoints.value), db.func.\n min(DataPoints.value)).join(Datasets).filter(Datasets.study_id ==\n self.id).first()\n self.y_max = maxmin[0]\n self.y_min = maxmin[1]\n db.session.commit()\n\n def has_jobs(self):\n resp = SZJob.query.filter(SZJob.study == self, ~SZJob.archived)\n return resp.count() > 0\n\n def has_archived_jobs(self):\n resp = SZJob.query.filter(SZJob.study == self, SZJob.archived)\n return resp.count() > 0\n\n def generate_token(self):\n self.token = ''.join(random.choice(string.ascii_uppercase + string.\n digits) for _ in range(8))\n return self.token\n <mask token>\n\n\nclass Datasets(db.Model):\n __tablename__ = 'datasets'\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n title = db.Column(db.Unicode)\n study_id = db.Column(db.Integer, db.ForeignKey('studies.id'), index=True)\n notes = db.relationship('Notes', cascade='all, delete-orphan', backref=\n 'dataset', lazy='dynamic')\n user_labels = db.relationship('UserLabels', cascade=\n 'all, delete-orphan', backref='dataset', lazy='dynamic')\n data_points = db.relationship('DataPoints', cascade=\n 'all, delete-orphan', backref='dataset', lazy='dynamic')\n labelled = db.relationship('LabelledDatasets', cascade=\n 'all, delete-orphan', backref='dataset', lazy='dynamic')\n\n def __init__(self, title, study_id, notes=[], data_points=[]):\n self.title = title\n self.study_id = study_id\n self.notes = notes\n self.data_points = data_points\n\n def next(self):\n return Datasets.query.filter(Datasets.study_id == self.study_id\n ).filter(Datasets.created_at < self.created_at).order_by(Datasets\n .created_at.desc()).first()\n\n def prev(self):\n return Datasets.query.filter(Datasets.study_id == self.study_id\n ).filter(Datasets.created_at > self.created_at).order_by(Datasets\n .created_at).first()\n\n def items(self):\n return Datasets.query.filter(Datasets.study_id == self.study_id\n ).order_by(Datasets.created_at.desc()).all()\n\n def labels_for_user(self, user):\n return db.session.query(Datasets, DataPoints, UserLabels).filter_by(id\n =self.id).join(UserLabels).filter_by(user_id=user.id).join(\n DataPoints).order_by(DataPoints.timestamp)\n\n def delete(self):\n self.user_labels.delete()\n self.notes.delete()\n self.data_points.delete()\n self.labelled.delete()\n db.session.delete(self)\n db.session.commit()\n\n def user_has_labelled(self, user):\n return self.labelled.filter_by(user_id=user.id).count() > 0\n\n\nclass LabelledDatasets(db.Model):\n __tablename__ = 'labelled_datasets'\n id = db.Column(db.Integer, primary_key=True)\n dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True\n )\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True)\n\n def __init__(self, dataset_id, user_id):\n self.dataset_id = dataset_id\n self.user_id = user_id\n\n\nclass Notes(db.Model):\n __tablename__ = 'notes'\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n text = db.Column(db.Unicode)\n dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True\n )\n\n def __init__(self, text):\n self.text = text\n\n @classmethod\n def dict_from_parsed(cls, text, dataset_id):\n return dict(created_at=datetime.datetime.now(), text=text,\n dataset_id=dataset_id)\n\n\nclass DataPoints(db.Model):\n __tablename__ = 'datapoints'\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n timestamp = db.Column(db.DateTime, index=True)\n unit = db.Column(db.String(16))\n value = db.Column(db.Float)\n training = db.Column(db.Boolean)\n dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True\n )\n user_labels = db.relationship('UserLabels', backref='datapoint', lazy=\n 'dynamic', passive_deletes=True)\n result_data_points = db.relationship('ResultDataPoints', cascade=\n 'all, delete-orphan', backref='dataset', lazy='dynamic')\n\n def __init__(self, timestamp, unit, value):\n self.timestamp = timestamp\n self.unit = unit\n self.value = value\n\n @classmethod\n def dict_from_parsed(cls, parsed_point, dataset_id, training_selector):\n timestamp = date_parse(parsed_point[0])\n return dict(created_at=datetime.datetime.now(), timestamp=timestamp,\n unit=parsed_point[1], value=float(parsed_point[2]), dataset_id=\n dataset_id, training=training_selector(timestamp))\n\n\nclass ResultDataPoints(db.Model):\n __tablename__ = 'resultdatapoints'\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n timestamp = db.Column(db.DateTime, index=True)\n value = db.Column(db.Float)\n prediction = db.Column(db.Float)\n job_id = db.Column(db.Integer, db.ForeignKey('sz_job.id'))\n datapoint_id = db.Column(db.Integer, db.ForeignKey('datapoints.id'),\n index=True)\n dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True\n )\n\n def __init__(self):\n pass\n\n @classmethod\n def dict_from_parsed(cls, parsed_point, dataset_id, training_selector):\n timestamp = date_parse(parsed_point[0])\n return dict(created_at=datetime.datetime.now(), timestamp=timestamp,\n unit=parsed_point[1], value=float(parsed_point[2]), dataset_id=\n dataset_id, training=training_selector(timestamp))\n\n\nclass UserLabels(db.Model):\n __tablename__ = 'user_labels'\n id = db.Column(db.Integer, primary_key=True)\n datapoint_id = db.Column(db.Integer, db.ForeignKey('datapoints.id'),\n index=True)\n dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True\n )\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True)\n label = db.Column(db.Boolean)\n\n def __init__(self, datapoint_id, dataset_id, user_id, label=False):\n self.datapoint_id = datapoint_id\n self.dataset_id = dataset_id\n self.user_id = user_id\n self.label = False\n\n @classmethod\n def dicts_from_datapoints(cls, data_points, dataset_id, user_id):\n dicts = [dict(datapoint_id=data_point.id, dataset_id=dataset_id,\n user_id=user_id, label=False) for data_point in data_points]\n return dicts\n\n\nclass SZJob(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n study_id = db.Column(db.Integer, db.ForeignKey('studies.id'), index=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n state = db.Column(db.String(64), default='submitted')\n message = db.Column(db.Unicode, nullable=True)\n csv_blob = db.Column(db.Unicode, nullable=True)\n csv_binary_blob = db.Column(db.LargeBinary, nullable=True)\n archived = db.Column(db.Boolean, nullable=True, default=False)\n study = db.relationship('Studies', backref='szjobs')\n", "step-2": "<mask token>\n\n\nclass Studies(db.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, title):\n self.title = title\n\n def most_recent_successful_job(self):\n return SZJob.query.filter(SZJob.study == self, SZJob.state == 'success'\n ).order_by(SZJob.created_at.desc()).first()\n\n def add_user(self, user, role):\n study_user = StudyUsers(user.id, self.id, role)\n for existing_user in self.users:\n if existing_user.user_id == user.id:\n return\n self.users.append(study_user)\n db.session.commit()\n\n def get_roles(self, user):\n roles = [study_user.role for study_user in self.users.filter_by(\n user_id=user.id).all()]\n return roles\n\n def is_labeller(self, user):\n return 'labeller' in self.get_roles(user) or 'owner' in self.get_roles(\n user)\n\n def is_owner(self, user):\n return 'owner' in self.get_roles(user)\n\n def delete(self):\n for dataset in self.datasets:\n dataset.delete()\n self.uploads.delete()\n db.session.delete(self)\n db.session.commit()\n\n def labellers(self):\n return Users.query.join(StudyUsers).filter(StudyUsers.role ==\n 'labeller').filter(StudyUsers.study_id == self.id)\n\n def update_range(self):\n maxmin = db.session.query(db.func.max(DataPoints.value), db.func.\n min(DataPoints.value)).join(Datasets).filter(Datasets.study_id ==\n self.id).first()\n self.y_max = maxmin[0]\n self.y_min = maxmin[1]\n db.session.commit()\n\n def has_jobs(self):\n resp = SZJob.query.filter(SZJob.study == self, ~SZJob.archived)\n return resp.count() > 0\n\n def has_archived_jobs(self):\n resp = SZJob.query.filter(SZJob.study == self, SZJob.archived)\n return resp.count() > 0\n\n def generate_token(self):\n self.token = ''.join(random.choice(string.ascii_uppercase + string.\n digits) for _ in range(8))\n return self.token\n\n def user_labels_as_csv(self):\n resp = db.session.execute(\n \"\"\"SELECT\n user_labels.datapoint_id,\n user_labels.dataset_id,\n user_labels.user_id,\n label,\n users.email,\n datapoints.timestamp,\n datasets.title\n FROM user_labels\n JOIN datapoints ON user_labels.datapoint_id = datapoints.id\n JOIN users ON user_labels.user_id = users.id\n JOIN datasets ON user_labels.dataset_id = datasets.id\n WHERE study_id = :study_id\"\"\"\n , {'study_id': self.id})\n import StringIO\n import csv\n output = StringIO.StringIO()\n writer = csv.writer(output)\n writer.writerow(['datapoint_id', 'dataset_id', 'user_id', 'label',\n 'email', 'timestamp', 'title'])\n for row in resp:\n writer.writerow(row)\n return output.getvalue()\n\n\nclass Datasets(db.Model):\n __tablename__ = 'datasets'\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n title = db.Column(db.Unicode)\n study_id = db.Column(db.Integer, db.ForeignKey('studies.id'), index=True)\n notes = db.relationship('Notes', cascade='all, delete-orphan', backref=\n 'dataset', lazy='dynamic')\n user_labels = db.relationship('UserLabels', cascade=\n 'all, delete-orphan', backref='dataset', lazy='dynamic')\n data_points = db.relationship('DataPoints', cascade=\n 'all, delete-orphan', backref='dataset', lazy='dynamic')\n labelled = db.relationship('LabelledDatasets', cascade=\n 'all, delete-orphan', backref='dataset', lazy='dynamic')\n\n def __init__(self, title, study_id, notes=[], data_points=[]):\n self.title = title\n self.study_id = study_id\n self.notes = notes\n self.data_points = data_points\n\n def next(self):\n return Datasets.query.filter(Datasets.study_id == self.study_id\n ).filter(Datasets.created_at < self.created_at).order_by(Datasets\n .created_at.desc()).first()\n\n def prev(self):\n return Datasets.query.filter(Datasets.study_id == self.study_id\n ).filter(Datasets.created_at > self.created_at).order_by(Datasets\n .created_at).first()\n\n def items(self):\n return Datasets.query.filter(Datasets.study_id == self.study_id\n ).order_by(Datasets.created_at.desc()).all()\n\n def labels_for_user(self, user):\n return db.session.query(Datasets, DataPoints, UserLabels).filter_by(id\n =self.id).join(UserLabels).filter_by(user_id=user.id).join(\n DataPoints).order_by(DataPoints.timestamp)\n\n def delete(self):\n self.user_labels.delete()\n self.notes.delete()\n self.data_points.delete()\n self.labelled.delete()\n db.session.delete(self)\n db.session.commit()\n\n def user_has_labelled(self, user):\n return self.labelled.filter_by(user_id=user.id).count() > 0\n\n\nclass LabelledDatasets(db.Model):\n __tablename__ = 'labelled_datasets'\n id = db.Column(db.Integer, primary_key=True)\n dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True\n )\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True)\n\n def __init__(self, dataset_id, user_id):\n self.dataset_id = dataset_id\n self.user_id = user_id\n\n\nclass Notes(db.Model):\n __tablename__ = 'notes'\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n text = db.Column(db.Unicode)\n dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True\n )\n\n def __init__(self, text):\n self.text = text\n\n @classmethod\n def dict_from_parsed(cls, text, dataset_id):\n return dict(created_at=datetime.datetime.now(), text=text,\n dataset_id=dataset_id)\n\n\nclass DataPoints(db.Model):\n __tablename__ = 'datapoints'\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n timestamp = db.Column(db.DateTime, index=True)\n unit = db.Column(db.String(16))\n value = db.Column(db.Float)\n training = db.Column(db.Boolean)\n dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True\n )\n user_labels = db.relationship('UserLabels', backref='datapoint', lazy=\n 'dynamic', passive_deletes=True)\n result_data_points = db.relationship('ResultDataPoints', cascade=\n 'all, delete-orphan', backref='dataset', lazy='dynamic')\n\n def __init__(self, timestamp, unit, value):\n self.timestamp = timestamp\n self.unit = unit\n self.value = value\n\n @classmethod\n def dict_from_parsed(cls, parsed_point, dataset_id, training_selector):\n timestamp = date_parse(parsed_point[0])\n return dict(created_at=datetime.datetime.now(), timestamp=timestamp,\n unit=parsed_point[1], value=float(parsed_point[2]), dataset_id=\n dataset_id, training=training_selector(timestamp))\n\n\nclass ResultDataPoints(db.Model):\n __tablename__ = 'resultdatapoints'\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n timestamp = db.Column(db.DateTime, index=True)\n value = db.Column(db.Float)\n prediction = db.Column(db.Float)\n job_id = db.Column(db.Integer, db.ForeignKey('sz_job.id'))\n datapoint_id = db.Column(db.Integer, db.ForeignKey('datapoints.id'),\n index=True)\n dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True\n )\n\n def __init__(self):\n pass\n\n @classmethod\n def dict_from_parsed(cls, parsed_point, dataset_id, training_selector):\n timestamp = date_parse(parsed_point[0])\n return dict(created_at=datetime.datetime.now(), timestamp=timestamp,\n unit=parsed_point[1], value=float(parsed_point[2]), dataset_id=\n dataset_id, training=training_selector(timestamp))\n\n\nclass UserLabels(db.Model):\n __tablename__ = 'user_labels'\n id = db.Column(db.Integer, primary_key=True)\n datapoint_id = db.Column(db.Integer, db.ForeignKey('datapoints.id'),\n index=True)\n dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True\n )\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True)\n label = db.Column(db.Boolean)\n\n def __init__(self, datapoint_id, dataset_id, user_id, label=False):\n self.datapoint_id = datapoint_id\n self.dataset_id = dataset_id\n self.user_id = user_id\n self.label = False\n\n @classmethod\n def dicts_from_datapoints(cls, data_points, dataset_id, user_id):\n dicts = [dict(datapoint_id=data_point.id, dataset_id=dataset_id,\n user_id=user_id, label=False) for data_point in data_points]\n return dicts\n\n\nclass SZJob(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n study_id = db.Column(db.Integer, db.ForeignKey('studies.id'), index=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n state = db.Column(db.String(64), default='submitted')\n message = db.Column(db.Unicode, nullable=True)\n csv_blob = db.Column(db.Unicode, nullable=True)\n csv_binary_blob = db.Column(db.LargeBinary, nullable=True)\n archived = db.Column(db.Boolean, nullable=True, default=False)\n study = db.relationship('Studies', backref='szjobs')\n", "step-3": "<mask token>\n\n\nclass StudyUsers(db.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Users(db.Model, UserMixin):\n __tablename__ = 'users'\n id = db.Column(db.Integer, primary_key=True)\n email = db.Column(db.Unicode)\n password = db.Column(db.String(255))\n active = db.Column(db.Boolean())\n confirmed_at = db.Column(db.DateTime())\n study_roles = db.relationship('StudyUsers', backref=db.backref('users'),\n lazy='dynamic')\n labels = db.relationship('UserLabels', backref='users', lazy='dynamic')\n roles = db.relationship('Role', secondary=roles_users, backref=db.\n backref('users', lazy='dynamic'))\n\n def studies(self):\n return db.session.query(Studies, StudyUsers).join(StudyUsers\n ).filter_by(user_id=self.id)\n\n def study_labels(self, study_id):\n return db.session.query(LabelledDatasets).filter_by(user_id=self.id\n ).join(Datasets).filter_by(study_id=study_id).count()\n\n\nclass StudyUploads(db.Model):\n __tablename__ = 'study_uploads'\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n filename = db.Column(db.Unicode)\n data = db.Column(db.LargeBinary)\n study_id = db.Column(db.Integer, db.ForeignKey('studies.id'), index=True)\n state = db.Column(db.String(64), default='submitted', nullable=True)\n error_message = db.Column(db.Text, nullable=True)\n\n def __init__(self, filename, data, study_id):\n self.filename = filename\n self.data = data\n self.study_id = study_id\n\n\nclass Studies(db.Model):\n __tablename__ = 'studies'\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n title = db.Column(db.Unicode)\n y_min = db.Column(db.Float, default=0)\n y_max = db.Column(db.Float, default=200)\n token = db.Column(db.String, nullable=True)\n datasets = db.relationship('Datasets', lazy='dynamic', cascade=\n 'all, delete-orphan', backref='study')\n uploads = db.relationship('StudyUploads', lazy='dynamic', cascade=\n 'all, delete-orphan', backref='study')\n users = db.relationship('StudyUsers', backref=db.backref('studies'),\n lazy='dynamic')\n\n def __init__(self, title):\n self.title = title\n\n def most_recent_successful_job(self):\n return SZJob.query.filter(SZJob.study == self, SZJob.state == 'success'\n ).order_by(SZJob.created_at.desc()).first()\n\n def add_user(self, user, role):\n study_user = StudyUsers(user.id, self.id, role)\n for existing_user in self.users:\n if existing_user.user_id == user.id:\n return\n self.users.append(study_user)\n db.session.commit()\n\n def get_roles(self, user):\n roles = [study_user.role for study_user in self.users.filter_by(\n user_id=user.id).all()]\n return roles\n\n def is_labeller(self, user):\n return 'labeller' in self.get_roles(user) or 'owner' in self.get_roles(\n user)\n\n def is_owner(self, user):\n return 'owner' in self.get_roles(user)\n\n def delete(self):\n for dataset in self.datasets:\n dataset.delete()\n self.uploads.delete()\n db.session.delete(self)\n db.session.commit()\n\n def labellers(self):\n return Users.query.join(StudyUsers).filter(StudyUsers.role ==\n 'labeller').filter(StudyUsers.study_id == self.id)\n\n def update_range(self):\n maxmin = db.session.query(db.func.max(DataPoints.value), db.func.\n min(DataPoints.value)).join(Datasets).filter(Datasets.study_id ==\n self.id).first()\n self.y_max = maxmin[0]\n self.y_min = maxmin[1]\n db.session.commit()\n\n def has_jobs(self):\n resp = SZJob.query.filter(SZJob.study == self, ~SZJob.archived)\n return resp.count() > 0\n\n def has_archived_jobs(self):\n resp = SZJob.query.filter(SZJob.study == self, SZJob.archived)\n return resp.count() > 0\n\n def generate_token(self):\n self.token = ''.join(random.choice(string.ascii_uppercase + string.\n digits) for _ in range(8))\n return self.token\n\n def user_labels_as_csv(self):\n resp = db.session.execute(\n \"\"\"SELECT\n user_labels.datapoint_id,\n user_labels.dataset_id,\n user_labels.user_id,\n label,\n users.email,\n datapoints.timestamp,\n datasets.title\n FROM user_labels\n JOIN datapoints ON user_labels.datapoint_id = datapoints.id\n JOIN users ON user_labels.user_id = users.id\n JOIN datasets ON user_labels.dataset_id = datasets.id\n WHERE study_id = :study_id\"\"\"\n , {'study_id': self.id})\n import StringIO\n import csv\n output = StringIO.StringIO()\n writer = csv.writer(output)\n writer.writerow(['datapoint_id', 'dataset_id', 'user_id', 'label',\n 'email', 'timestamp', 'title'])\n for row in resp:\n writer.writerow(row)\n return output.getvalue()\n\n\nclass Datasets(db.Model):\n __tablename__ = 'datasets'\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n title = db.Column(db.Unicode)\n study_id = db.Column(db.Integer, db.ForeignKey('studies.id'), index=True)\n notes = db.relationship('Notes', cascade='all, delete-orphan', backref=\n 'dataset', lazy='dynamic')\n user_labels = db.relationship('UserLabels', cascade=\n 'all, delete-orphan', backref='dataset', lazy='dynamic')\n data_points = db.relationship('DataPoints', cascade=\n 'all, delete-orphan', backref='dataset', lazy='dynamic')\n labelled = db.relationship('LabelledDatasets', cascade=\n 'all, delete-orphan', backref='dataset', lazy='dynamic')\n\n def __init__(self, title, study_id, notes=[], data_points=[]):\n self.title = title\n self.study_id = study_id\n self.notes = notes\n self.data_points = data_points\n\n def next(self):\n return Datasets.query.filter(Datasets.study_id == self.study_id\n ).filter(Datasets.created_at < self.created_at).order_by(Datasets\n .created_at.desc()).first()\n\n def prev(self):\n return Datasets.query.filter(Datasets.study_id == self.study_id\n ).filter(Datasets.created_at > self.created_at).order_by(Datasets\n .created_at).first()\n\n def items(self):\n return Datasets.query.filter(Datasets.study_id == self.study_id\n ).order_by(Datasets.created_at.desc()).all()\n\n def labels_for_user(self, user):\n return db.session.query(Datasets, DataPoints, UserLabels).filter_by(id\n =self.id).join(UserLabels).filter_by(user_id=user.id).join(\n DataPoints).order_by(DataPoints.timestamp)\n\n def delete(self):\n self.user_labels.delete()\n self.notes.delete()\n self.data_points.delete()\n self.labelled.delete()\n db.session.delete(self)\n db.session.commit()\n\n def user_has_labelled(self, user):\n return self.labelled.filter_by(user_id=user.id).count() > 0\n\n\nclass LabelledDatasets(db.Model):\n __tablename__ = 'labelled_datasets'\n id = db.Column(db.Integer, primary_key=True)\n dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True\n )\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True)\n\n def __init__(self, dataset_id, user_id):\n self.dataset_id = dataset_id\n self.user_id = user_id\n\n\nclass Notes(db.Model):\n __tablename__ = 'notes'\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n text = db.Column(db.Unicode)\n dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True\n )\n\n def __init__(self, text):\n self.text = text\n\n @classmethod\n def dict_from_parsed(cls, text, dataset_id):\n return dict(created_at=datetime.datetime.now(), text=text,\n dataset_id=dataset_id)\n\n\nclass DataPoints(db.Model):\n __tablename__ = 'datapoints'\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n timestamp = db.Column(db.DateTime, index=True)\n unit = db.Column(db.String(16))\n value = db.Column(db.Float)\n training = db.Column(db.Boolean)\n dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True\n )\n user_labels = db.relationship('UserLabels', backref='datapoint', lazy=\n 'dynamic', passive_deletes=True)\n result_data_points = db.relationship('ResultDataPoints', cascade=\n 'all, delete-orphan', backref='dataset', lazy='dynamic')\n\n def __init__(self, timestamp, unit, value):\n self.timestamp = timestamp\n self.unit = unit\n self.value = value\n\n @classmethod\n def dict_from_parsed(cls, parsed_point, dataset_id, training_selector):\n timestamp = date_parse(parsed_point[0])\n return dict(created_at=datetime.datetime.now(), timestamp=timestamp,\n unit=parsed_point[1], value=float(parsed_point[2]), dataset_id=\n dataset_id, training=training_selector(timestamp))\n\n\nclass ResultDataPoints(db.Model):\n __tablename__ = 'resultdatapoints'\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n timestamp = db.Column(db.DateTime, index=True)\n value = db.Column(db.Float)\n prediction = db.Column(db.Float)\n job_id = db.Column(db.Integer, db.ForeignKey('sz_job.id'))\n datapoint_id = db.Column(db.Integer, db.ForeignKey('datapoints.id'),\n index=True)\n dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True\n )\n\n def __init__(self):\n pass\n\n @classmethod\n def dict_from_parsed(cls, parsed_point, dataset_id, training_selector):\n timestamp = date_parse(parsed_point[0])\n return dict(created_at=datetime.datetime.now(), timestamp=timestamp,\n unit=parsed_point[1], value=float(parsed_point[2]), dataset_id=\n dataset_id, training=training_selector(timestamp))\n\n\nclass UserLabels(db.Model):\n __tablename__ = 'user_labels'\n id = db.Column(db.Integer, primary_key=True)\n datapoint_id = db.Column(db.Integer, db.ForeignKey('datapoints.id'),\n index=True)\n dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True\n )\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True)\n label = db.Column(db.Boolean)\n\n def __init__(self, datapoint_id, dataset_id, user_id, label=False):\n self.datapoint_id = datapoint_id\n self.dataset_id = dataset_id\n self.user_id = user_id\n self.label = False\n\n @classmethod\n def dicts_from_datapoints(cls, data_points, dataset_id, user_id):\n dicts = [dict(datapoint_id=data_point.id, dataset_id=dataset_id,\n user_id=user_id, label=False) for data_point in data_points]\n return dicts\n\n\nclass SZJob(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n study_id = db.Column(db.Integer, db.ForeignKey('studies.id'), index=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n state = db.Column(db.String(64), default='submitted')\n message = db.Column(db.Unicode, nullable=True)\n csv_blob = db.Column(db.Unicode, nullable=True)\n csv_binary_blob = db.Column(db.LargeBinary, nullable=True)\n archived = db.Column(db.Boolean, nullable=True, default=False)\n study = db.relationship('Studies', backref='szjobs')\n", "step-4": "<mask token>\n\n\nclass StudyUsers(db.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, user_id, study_id, role):\n self.study_id = study_id\n self.user_id = user_id\n self.study_id = study_id\n self.role = role\n\n\nclass Users(db.Model, UserMixin):\n __tablename__ = 'users'\n id = db.Column(db.Integer, primary_key=True)\n email = db.Column(db.Unicode)\n password = db.Column(db.String(255))\n active = db.Column(db.Boolean())\n confirmed_at = db.Column(db.DateTime())\n study_roles = db.relationship('StudyUsers', backref=db.backref('users'),\n lazy='dynamic')\n labels = db.relationship('UserLabels', backref='users', lazy='dynamic')\n roles = db.relationship('Role', secondary=roles_users, backref=db.\n backref('users', lazy='dynamic'))\n\n def studies(self):\n return db.session.query(Studies, StudyUsers).join(StudyUsers\n ).filter_by(user_id=self.id)\n\n def study_labels(self, study_id):\n return db.session.query(LabelledDatasets).filter_by(user_id=self.id\n ).join(Datasets).filter_by(study_id=study_id).count()\n\n\nclass StudyUploads(db.Model):\n __tablename__ = 'study_uploads'\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n filename = db.Column(db.Unicode)\n data = db.Column(db.LargeBinary)\n study_id = db.Column(db.Integer, db.ForeignKey('studies.id'), index=True)\n state = db.Column(db.String(64), default='submitted', nullable=True)\n error_message = db.Column(db.Text, nullable=True)\n\n def __init__(self, filename, data, study_id):\n self.filename = filename\n self.data = data\n self.study_id = study_id\n\n\nclass Studies(db.Model):\n __tablename__ = 'studies'\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n title = db.Column(db.Unicode)\n y_min = db.Column(db.Float, default=0)\n y_max = db.Column(db.Float, default=200)\n token = db.Column(db.String, nullable=True)\n datasets = db.relationship('Datasets', lazy='dynamic', cascade=\n 'all, delete-orphan', backref='study')\n uploads = db.relationship('StudyUploads', lazy='dynamic', cascade=\n 'all, delete-orphan', backref='study')\n users = db.relationship('StudyUsers', backref=db.backref('studies'),\n lazy='dynamic')\n\n def __init__(self, title):\n self.title = title\n\n def most_recent_successful_job(self):\n return SZJob.query.filter(SZJob.study == self, SZJob.state == 'success'\n ).order_by(SZJob.created_at.desc()).first()\n\n def add_user(self, user, role):\n study_user = StudyUsers(user.id, self.id, role)\n for existing_user in self.users:\n if existing_user.user_id == user.id:\n return\n self.users.append(study_user)\n db.session.commit()\n\n def get_roles(self, user):\n roles = [study_user.role for study_user in self.users.filter_by(\n user_id=user.id).all()]\n return roles\n\n def is_labeller(self, user):\n return 'labeller' in self.get_roles(user) or 'owner' in self.get_roles(\n user)\n\n def is_owner(self, user):\n return 'owner' in self.get_roles(user)\n\n def delete(self):\n for dataset in self.datasets:\n dataset.delete()\n self.uploads.delete()\n db.session.delete(self)\n db.session.commit()\n\n def labellers(self):\n return Users.query.join(StudyUsers).filter(StudyUsers.role ==\n 'labeller').filter(StudyUsers.study_id == self.id)\n\n def update_range(self):\n maxmin = db.session.query(db.func.max(DataPoints.value), db.func.\n min(DataPoints.value)).join(Datasets).filter(Datasets.study_id ==\n self.id).first()\n self.y_max = maxmin[0]\n self.y_min = maxmin[1]\n db.session.commit()\n\n def has_jobs(self):\n resp = SZJob.query.filter(SZJob.study == self, ~SZJob.archived)\n return resp.count() > 0\n\n def has_archived_jobs(self):\n resp = SZJob.query.filter(SZJob.study == self, SZJob.archived)\n return resp.count() > 0\n\n def generate_token(self):\n self.token = ''.join(random.choice(string.ascii_uppercase + string.\n digits) for _ in range(8))\n return self.token\n\n def user_labels_as_csv(self):\n resp = db.session.execute(\n \"\"\"SELECT\n user_labels.datapoint_id,\n user_labels.dataset_id,\n user_labels.user_id,\n label,\n users.email,\n datapoints.timestamp,\n datasets.title\n FROM user_labels\n JOIN datapoints ON user_labels.datapoint_id = datapoints.id\n JOIN users ON user_labels.user_id = users.id\n JOIN datasets ON user_labels.dataset_id = datasets.id\n WHERE study_id = :study_id\"\"\"\n , {'study_id': self.id})\n import StringIO\n import csv\n output = StringIO.StringIO()\n writer = csv.writer(output)\n writer.writerow(['datapoint_id', 'dataset_id', 'user_id', 'label',\n 'email', 'timestamp', 'title'])\n for row in resp:\n writer.writerow(row)\n return output.getvalue()\n\n\nclass Datasets(db.Model):\n __tablename__ = 'datasets'\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n title = db.Column(db.Unicode)\n study_id = db.Column(db.Integer, db.ForeignKey('studies.id'), index=True)\n notes = db.relationship('Notes', cascade='all, delete-orphan', backref=\n 'dataset', lazy='dynamic')\n user_labels = db.relationship('UserLabels', cascade=\n 'all, delete-orphan', backref='dataset', lazy='dynamic')\n data_points = db.relationship('DataPoints', cascade=\n 'all, delete-orphan', backref='dataset', lazy='dynamic')\n labelled = db.relationship('LabelledDatasets', cascade=\n 'all, delete-orphan', backref='dataset', lazy='dynamic')\n\n def __init__(self, title, study_id, notes=[], data_points=[]):\n self.title = title\n self.study_id = study_id\n self.notes = notes\n self.data_points = data_points\n\n def next(self):\n return Datasets.query.filter(Datasets.study_id == self.study_id\n ).filter(Datasets.created_at < self.created_at).order_by(Datasets\n .created_at.desc()).first()\n\n def prev(self):\n return Datasets.query.filter(Datasets.study_id == self.study_id\n ).filter(Datasets.created_at > self.created_at).order_by(Datasets\n .created_at).first()\n\n def items(self):\n return Datasets.query.filter(Datasets.study_id == self.study_id\n ).order_by(Datasets.created_at.desc()).all()\n\n def labels_for_user(self, user):\n return db.session.query(Datasets, DataPoints, UserLabels).filter_by(id\n =self.id).join(UserLabels).filter_by(user_id=user.id).join(\n DataPoints).order_by(DataPoints.timestamp)\n\n def delete(self):\n self.user_labels.delete()\n self.notes.delete()\n self.data_points.delete()\n self.labelled.delete()\n db.session.delete(self)\n db.session.commit()\n\n def user_has_labelled(self, user):\n return self.labelled.filter_by(user_id=user.id).count() > 0\n\n\nclass LabelledDatasets(db.Model):\n __tablename__ = 'labelled_datasets'\n id = db.Column(db.Integer, primary_key=True)\n dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True\n )\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True)\n\n def __init__(self, dataset_id, user_id):\n self.dataset_id = dataset_id\n self.user_id = user_id\n\n\nclass Notes(db.Model):\n __tablename__ = 'notes'\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n text = db.Column(db.Unicode)\n dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True\n )\n\n def __init__(self, text):\n self.text = text\n\n @classmethod\n def dict_from_parsed(cls, text, dataset_id):\n return dict(created_at=datetime.datetime.now(), text=text,\n dataset_id=dataset_id)\n\n\nclass DataPoints(db.Model):\n __tablename__ = 'datapoints'\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n timestamp = db.Column(db.DateTime, index=True)\n unit = db.Column(db.String(16))\n value = db.Column(db.Float)\n training = db.Column(db.Boolean)\n dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True\n )\n user_labels = db.relationship('UserLabels', backref='datapoint', lazy=\n 'dynamic', passive_deletes=True)\n result_data_points = db.relationship('ResultDataPoints', cascade=\n 'all, delete-orphan', backref='dataset', lazy='dynamic')\n\n def __init__(self, timestamp, unit, value):\n self.timestamp = timestamp\n self.unit = unit\n self.value = value\n\n @classmethod\n def dict_from_parsed(cls, parsed_point, dataset_id, training_selector):\n timestamp = date_parse(parsed_point[0])\n return dict(created_at=datetime.datetime.now(), timestamp=timestamp,\n unit=parsed_point[1], value=float(parsed_point[2]), dataset_id=\n dataset_id, training=training_selector(timestamp))\n\n\nclass ResultDataPoints(db.Model):\n __tablename__ = 'resultdatapoints'\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n timestamp = db.Column(db.DateTime, index=True)\n value = db.Column(db.Float)\n prediction = db.Column(db.Float)\n job_id = db.Column(db.Integer, db.ForeignKey('sz_job.id'))\n datapoint_id = db.Column(db.Integer, db.ForeignKey('datapoints.id'),\n index=True)\n dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True\n )\n\n def __init__(self):\n pass\n\n @classmethod\n def dict_from_parsed(cls, parsed_point, dataset_id, training_selector):\n timestamp = date_parse(parsed_point[0])\n return dict(created_at=datetime.datetime.now(), timestamp=timestamp,\n unit=parsed_point[1], value=float(parsed_point[2]), dataset_id=\n dataset_id, training=training_selector(timestamp))\n\n\nclass UserLabels(db.Model):\n __tablename__ = 'user_labels'\n id = db.Column(db.Integer, primary_key=True)\n datapoint_id = db.Column(db.Integer, db.ForeignKey('datapoints.id'),\n index=True)\n dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True\n )\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True)\n label = db.Column(db.Boolean)\n\n def __init__(self, datapoint_id, dataset_id, user_id, label=False):\n self.datapoint_id = datapoint_id\n self.dataset_id = dataset_id\n self.user_id = user_id\n self.label = False\n\n @classmethod\n def dicts_from_datapoints(cls, data_points, dataset_id, user_id):\n dicts = [dict(datapoint_id=data_point.id, dataset_id=dataset_id,\n user_id=user_id, label=False) for data_point in data_points]\n return dicts\n\n\nclass SZJob(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n study_id = db.Column(db.Integer, db.ForeignKey('studies.id'), index=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n state = db.Column(db.String(64), default='submitted')\n message = db.Column(db.Unicode, nullable=True)\n csv_blob = db.Column(db.Unicode, nullable=True)\n csv_binary_blob = db.Column(db.LargeBinary, nullable=True)\n archived = db.Column(db.Boolean, nullable=True, default=False)\n study = db.relationship('Studies', backref='szjobs')\n", "step-5": "import random\nimport string\nimport datetime\nfrom app import db\nfrom dateutil.parser import parse as date_parse\nfrom flask_security import UserMixin, RoleMixin\n\nroles_users = db.Table('roles_users',\n db.Column('user_id', db.Integer(), db.ForeignKey('users.id')),\n db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))\n\n\nclass Role(db.Model, RoleMixin):\n id = db.Column(db.Integer(), primary_key=True)\n name = db.Column(db.String(80), unique=True)\n description = db.Column(db.String(255))\n\n\nclass StudyUsers(db.Model):\n __tablename__ = 'study_users'\n\n id = db.Column(db.Integer, primary_key=True)\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True)\n study_id = db.Column(db.Integer, db.ForeignKey('studies.id'), index=True)\n role = db.Column(db.Enum('labeller', 'owner', name='user_role'))\n\n def __init__(self, user_id, study_id, role):\n self.study_id = study_id\n self.user_id = user_id\n self.study_id = study_id\n self.role = role\n\n\nclass Users(db.Model, UserMixin):\n __tablename__ = 'users'\n\n id = db.Column(db.Integer, primary_key=True)\n email = db.Column(db.Unicode)\n password = db.Column(db.String(255))\n active = db.Column(db.Boolean())\n confirmed_at = db.Column(db.DateTime())\n\n study_roles = db.relationship('StudyUsers',\n backref=db.backref('users'), lazy='dynamic')\n labels = db.relationship('UserLabels',\n backref='users', lazy='dynamic')\n roles = db.relationship('Role', secondary=roles_users,\n backref=db.backref('users', lazy='dynamic'))\n\n def studies(self):\n return db.session.query(Studies, StudyUsers).\\\n join(StudyUsers).filter_by(user_id=self.id)\n\n def study_labels(self, study_id):\n return db.session.query(LabelledDatasets).\\\n filter_by(user_id=self.id).\\\n join(Datasets).filter_by(study_id=study_id).count()\n\n\nclass StudyUploads(db.Model):\n __tablename__ = 'study_uploads'\n\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n filename = db.Column(db.Unicode)\n data = db.Column(db.LargeBinary)\n study_id = db.Column(db.Integer, db.ForeignKey('studies.id'), index=True)\n state = db.Column(db.String(64), default='submitted', nullable=True)\n error_message = db.Column(db.Text, nullable=True)\n\n def __init__(self, filename, data, study_id):\n self.filename = filename\n self.data = data\n self.study_id = study_id\n\n\nclass Studies(db.Model):\n __tablename__ = 'studies'\n\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n title = db.Column(db.Unicode)\n y_min = db.Column(db.Float, default=0)\n y_max = db.Column(db.Float, default=200)\n token = db.Column(db.String, nullable=True)\n\n datasets = db.relationship('Datasets', lazy=\"dynamic\", cascade=\"all, delete-orphan\", backref=\"study\")\n uploads = db.relationship('StudyUploads', lazy=\"dynamic\", cascade=\"all, delete-orphan\", backref=\"study\")\n\n users = db.relationship('StudyUsers',\n backref=db.backref('studies'), lazy='dynamic')\n\n def __init__(self, title):\n self.title = title\n\n def most_recent_successful_job(self):\n return SZJob.query.filter(SZJob.study == self, SZJob.state == 'success').order_by(SZJob.created_at.desc()).first()\n\n def add_user(self, user, role):\n study_user = StudyUsers(user.id, self.id, role)\n for existing_user in self.users:\n if existing_user.user_id == user.id:\n return\n self.users.append(study_user)\n db.session.commit()\n\n def get_roles(self, user):\n roles = [study_user.role for study_user in self.users.filter_by(user_id=user.id).all()]\n return roles\n\n def is_labeller(self, user):\n return (\"labeller\" in self.get_roles(user)) or (\"owner\" in self.get_roles(user))\n\n def is_owner(self, user):\n return \"owner\" in self.get_roles(user)\n\n def delete(self):\n for dataset in self.datasets:\n dataset.delete()\n self.uploads.delete()\n db.session.delete(self)\n db.session.commit()\n\n def labellers(self):\n return Users.query.join(StudyUsers).\\\n filter(StudyUsers.role == \"labeller\").\\\n filter(StudyUsers.study_id == self.id)\n\n def update_range(self):\n maxmin = db.session.query(db.func.max(DataPoints.value), db.func.min(DataPoints.value)).\\\n join(Datasets).filter(Datasets.study_id == self.id).first()\n self.y_max = maxmin[0]\n self.y_min = maxmin[1]\n db.session.commit()\n\n def has_jobs(self):\n resp = SZJob.query.filter(SZJob.study == self, ~SZJob.archived)\n return resp.count() > 0\n\n def has_archived_jobs(self):\n resp = SZJob.query.filter(SZJob.study == self, SZJob.archived)\n return resp.count() > 0\n\n def generate_token(self):\n self.token = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))\n return self.token\n\n def user_labels_as_csv(self):\n\n resp = db.session.execute(\"\"\"SELECT\n user_labels.datapoint_id,\n user_labels.dataset_id,\n user_labels.user_id,\n label,\n users.email,\n datapoints.timestamp,\n datasets.title\n FROM user_labels\n JOIN datapoints ON user_labels.datapoint_id = datapoints.id\n JOIN users ON user_labels.user_id = users.id\n JOIN datasets ON user_labels.dataset_id = datasets.id\n WHERE study_id = :study_id\"\"\", {'study_id': self.id})\n\n import StringIO\n import csv\n output = StringIO.StringIO()\n writer = csv.writer(output)\n writer.writerow(['datapoint_id', 'dataset_id', 'user_id', 'label', 'email', 'timestamp', 'title'])\n for row in resp:\n writer.writerow(row)\n return output.getvalue()\n\n\nclass Datasets(db.Model):\n __tablename__ = 'datasets'\n\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n title = db.Column(db.Unicode)\n study_id = db.Column(db.Integer, db.ForeignKey('studies.id'), index=True)\n\n notes = db.relationship('Notes', cascade=\"all, delete-orphan\", backref=\"dataset\", lazy=\"dynamic\")\n user_labels = db.relationship('UserLabels', cascade=\"all, delete-orphan\", backref=\"dataset\", lazy=\"dynamic\")\n data_points = db.relationship('DataPoints', cascade=\"all, delete-orphan\", backref=\"dataset\", lazy=\"dynamic\")\n labelled = db.relationship('LabelledDatasets', cascade=\"all, delete-orphan\", backref=\"dataset\", lazy=\"dynamic\")\n\n def __init__(self, title, study_id, notes=[], data_points=[]):\n self.title = title\n self.study_id = study_id\n self.notes = notes\n self.data_points = data_points\n\n def next(self):\n return Datasets.query.\\\n filter(Datasets.study_id == self.study_id).\\\n filter(Datasets.created_at < self.created_at).\\\n order_by(Datasets.created_at.desc()).\\\n first()\n\n def prev(self):\n return Datasets.query.\\\n filter(Datasets.study_id == self.study_id).\\\n filter(Datasets.created_at > self.created_at).\\\n order_by(Datasets.created_at).\\\n first()\n\n def items(self):\n return Datasets.query.\\\n filter(Datasets.study_id == self.study_id).\\\n order_by(Datasets.created_at.desc()).\\\n all()\n\n def labels_for_user(self, user):\n return db.session.query(Datasets, DataPoints, UserLabels).\\\n filter_by(id=self.id).\\\n join(UserLabels).filter_by(user_id=user.id).\\\n join(DataPoints).\\\n order_by(DataPoints.timestamp)\n\n def delete(self):\n self.user_labels.delete()\n self.notes.delete()\n self.data_points.delete()\n self.labelled.delete()\n db.session.delete(self)\n db.session.commit()\n\n def user_has_labelled(self, user):\n return self.labelled.filter_by(user_id=user.id).count() > 0\n\n\nclass LabelledDatasets(db.Model):\n __tablename__ = 'labelled_datasets'\n\n id = db.Column(db.Integer, primary_key=True)\n dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True)\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True)\n\n def __init__(self, dataset_id, user_id):\n self.dataset_id = dataset_id\n self.user_id = user_id\n\n\nclass Notes(db.Model):\n __tablename__ = 'notes'\n\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n text = db.Column(db.Unicode)\n\n dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True)\n\n def __init__(self, text):\n self.text = text\n\n @classmethod\n def dict_from_parsed(cls, text, dataset_id):\n return dict(\n created_at=datetime.datetime.now(),\n text=text,\n dataset_id=dataset_id\n )\n\n\nclass DataPoints(db.Model):\n __tablename__ = 'datapoints'\n\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n timestamp = db.Column(db.DateTime, index=True)\n unit = db.Column(db.String(16))\n value = db.Column(db.Float)\n training = db.Column(db.Boolean)\n\n dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True)\n user_labels = db.relationship('UserLabels', backref=\"datapoint\", lazy=\"dynamic\", passive_deletes=True)\n result_data_points = db.relationship('ResultDataPoints', cascade=\"all, delete-orphan\", backref=\"dataset\", lazy=\"dynamic\")\n\n\n def __init__(self, timestamp, unit, value):\n self.timestamp = timestamp\n self.unit = unit\n self.value = value\n\n @classmethod\n def dict_from_parsed(cls, parsed_point, dataset_id, training_selector):\n timestamp = date_parse(parsed_point[0])\n return dict(\n created_at=datetime.datetime.now(),\n timestamp=timestamp,\n unit=parsed_point[1],\n value=float(parsed_point[2]),\n dataset_id=dataset_id,\n training=training_selector(timestamp)\n )\n\nclass ResultDataPoints(db.Model):\n __tablename__ = 'resultdatapoints'\n\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n timestamp = db.Column(db.DateTime, index=True)\n value = db.Column(db.Float)\n prediction = db.Column(db.Float)\n\n job_id = db.Column(db.Integer, db.ForeignKey('sz_job.id'))\n datapoint_id = db.Column(db.Integer, db.ForeignKey('datapoints.id'), index=True)\n dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True)\n\n def __init__(self):\n pass\n\n @classmethod\n def dict_from_parsed(cls, parsed_point, dataset_id, training_selector):\n timestamp = date_parse(parsed_point[0])\n return dict(\n created_at=datetime.datetime.now(),\n timestamp=timestamp,\n unit=parsed_point[1],\n value=float(parsed_point[2]),\n dataset_id=dataset_id,\n training=training_selector(timestamp)\n )\n\n\nclass UserLabels(db.Model):\n __tablename__ = 'user_labels'\n\n id = db.Column(db.Integer, primary_key=True)\n datapoint_id = db.Column(db.Integer, db.ForeignKey('datapoints.id'), index=True)\n dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), index=True)\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True)\n label = db.Column(db.Boolean)\n\n def __init__(self, datapoint_id, dataset_id, user_id, label=False):\n self.datapoint_id = datapoint_id\n self.dataset_id = dataset_id\n self.user_id = user_id\n self.label = False\n\n @classmethod\n def dicts_from_datapoints(cls, data_points, dataset_id, user_id):\n dicts = [dict(datapoint_id=data_point.id,\n dataset_id=dataset_id,\n user_id=user_id,\n label=False) for data_point in data_points]\n return dicts\n\n\n\nclass SZJob(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n study_id = db.Column(db.Integer, db.ForeignKey('studies.id'), index=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n state = db.Column(db.String(64), default='submitted')\n message = db.Column(db.Unicode, nullable=True)\n csv_blob = db.Column(db.Unicode, nullable=True)\n csv_binary_blob = db.Column(db.LargeBinary, nullable=True)\n archived = db.Column(db.Boolean, nullable=True, default=False)\n\n study = db.relationship('Studies', backref='szjobs')\n\n\n\n\n", "step-ids": [ 42, 44, 53, 54, 60 ] }
[ 42, 44, 53, 54, 60 ]
# -*- coding: utf-8 -*- import json import re import scrapy from scrapy import Request class PageInfoAjaxSpider(scrapy.Spider): name = 'page_info_ajax' allowed_domains = ['bilibili.com'] # start_urls = ['http://bilibili.com/'] headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36', } def start_requests(self): url = 'https://s.search.bilibili.com/cate/search?callback=jqueryCallback_bili_8995260575257822&main_ver=v3&search_type=video&view_type=hot_rank&order=click&copy_right=-1&cate_id=130&page=1&pagesize=20&jsonp=jsonp&time_from=20190426&time_to=20190625&_=1561516363499' yield Request(url, headers=self.headers) def parse(self, response): req_body = response.body json_data = req_body.decode('utf-8') pure_json_data = re.sub(r'jqueryCallback_bili_([0-9])*', '', json_data, count=1) pure_json_data = json.loads(pure_json_data[1:-1]) print(pure_json_data['numPages'])
normal
{ "blob_id": "cdcb2710291e9897b874f63840193470ed58be49", "index": 825, "step-1": "<mask token>\n\n\nclass PageInfoAjaxSpider(scrapy.Spider):\n <mask token>\n <mask token>\n <mask token>\n\n def start_requests(self):\n url = (\n 'https://s.search.bilibili.com/cate/search?callback=jqueryCallback_bili_8995260575257822&main_ver=v3&search_type=video&view_type=hot_rank&order=click&copy_right=-1&cate_id=130&page=1&pagesize=20&jsonp=jsonp&time_from=20190426&time_to=20190625&_=1561516363499'\n )\n yield Request(url, headers=self.headers)\n <mask token>\n", "step-2": "<mask token>\n\n\nclass PageInfoAjaxSpider(scrapy.Spider):\n <mask token>\n <mask token>\n <mask token>\n\n def start_requests(self):\n url = (\n 'https://s.search.bilibili.com/cate/search?callback=jqueryCallback_bili_8995260575257822&main_ver=v3&search_type=video&view_type=hot_rank&order=click&copy_right=-1&cate_id=130&page=1&pagesize=20&jsonp=jsonp&time_from=20190426&time_to=20190625&_=1561516363499'\n )\n yield Request(url, headers=self.headers)\n\n def parse(self, response):\n req_body = response.body\n json_data = req_body.decode('utf-8')\n pure_json_data = re.sub('jqueryCallback_bili_([0-9])*', '',\n json_data, count=1)\n pure_json_data = json.loads(pure_json_data[1:-1])\n print(pure_json_data['numPages'])\n", "step-3": "<mask token>\n\n\nclass PageInfoAjaxSpider(scrapy.Spider):\n name = 'page_info_ajax'\n allowed_domains = ['bilibili.com']\n headers = {'User-Agent':\n 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'\n }\n\n def start_requests(self):\n url = (\n 'https://s.search.bilibili.com/cate/search?callback=jqueryCallback_bili_8995260575257822&main_ver=v3&search_type=video&view_type=hot_rank&order=click&copy_right=-1&cate_id=130&page=1&pagesize=20&jsonp=jsonp&time_from=20190426&time_to=20190625&_=1561516363499'\n )\n yield Request(url, headers=self.headers)\n\n def parse(self, response):\n req_body = response.body\n json_data = req_body.decode('utf-8')\n pure_json_data = re.sub('jqueryCallback_bili_([0-9])*', '',\n json_data, count=1)\n pure_json_data = json.loads(pure_json_data[1:-1])\n print(pure_json_data['numPages'])\n", "step-4": "import json\nimport re\nimport scrapy\nfrom scrapy import Request\n\n\nclass PageInfoAjaxSpider(scrapy.Spider):\n name = 'page_info_ajax'\n allowed_domains = ['bilibili.com']\n headers = {'User-Agent':\n 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'\n }\n\n def start_requests(self):\n url = (\n 'https://s.search.bilibili.com/cate/search?callback=jqueryCallback_bili_8995260575257822&main_ver=v3&search_type=video&view_type=hot_rank&order=click&copy_right=-1&cate_id=130&page=1&pagesize=20&jsonp=jsonp&time_from=20190426&time_to=20190625&_=1561516363499'\n )\n yield Request(url, headers=self.headers)\n\n def parse(self, response):\n req_body = response.body\n json_data = req_body.decode('utf-8')\n pure_json_data = re.sub('jqueryCallback_bili_([0-9])*', '',\n json_data, count=1)\n pure_json_data = json.loads(pure_json_data[1:-1])\n print(pure_json_data['numPages'])\n", "step-5": "# -*- coding: utf-8 -*-\nimport json\nimport re\n\nimport scrapy\nfrom scrapy import Request\n\n\nclass PageInfoAjaxSpider(scrapy.Spider):\n name = 'page_info_ajax'\n allowed_domains = ['bilibili.com']\n # start_urls = ['http://bilibili.com/']\n\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36',\n }\n\n def start_requests(self):\n url = 'https://s.search.bilibili.com/cate/search?callback=jqueryCallback_bili_8995260575257822&main_ver=v3&search_type=video&view_type=hot_rank&order=click&copy_right=-1&cate_id=130&page=1&pagesize=20&jsonp=jsonp&time_from=20190426&time_to=20190625&_=1561516363499'\n yield Request(url, headers=self.headers)\n\n def parse(self, response):\n req_body = response.body\n json_data = req_body.decode('utf-8')\n pure_json_data = re.sub(r'jqueryCallback_bili_([0-9])*', '', json_data, count=1)\n pure_json_data = json.loads(pure_json_data[1:-1])\n print(pure_json_data['numPages'])\n", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
<|reserved_special_token_0|> @pytest.fixture def client(): os.environ['FLASK_ENV'] = 'testing' yield get_client() <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def get_client(): from apiserver import app, is_caching_enabled app.config['TESTING'] = True app.enable_cache(is_caching_enabled()) return app.test_client() @pytest.fixture def client(): os.environ['FLASK_ENV'] = 'testing' yield get_client() <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def get_client(): from apiserver import app, is_caching_enabled app.config['TESTING'] = True app.enable_cache(is_caching_enabled()) return app.test_client() @pytest.fixture def client(): os.environ['FLASK_ENV'] = 'testing' yield get_client() @pytest.fixture def client_with_caching(): os.environ['FLASK_ENV'] = 'production' yield get_client() <|reserved_special_token_1|> import os import pytest def get_client(): from apiserver import app, is_caching_enabled app.config['TESTING'] = True app.enable_cache(is_caching_enabled()) return app.test_client() @pytest.fixture def client(): os.environ['FLASK_ENV'] = 'testing' yield get_client() @pytest.fixture def client_with_caching(): os.environ['FLASK_ENV'] = 'production' yield get_client()
flexible
{ "blob_id": "c0b5a0605bdfcb7cb84211d3ad0d24f78f838cdf", "index": 5421, "step-1": "<mask token>\n\n\[email protected]\ndef client():\n os.environ['FLASK_ENV'] = 'testing'\n yield get_client()\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef get_client():\n from apiserver import app, is_caching_enabled\n app.config['TESTING'] = True\n app.enable_cache(is_caching_enabled())\n return app.test_client()\n\n\[email protected]\ndef client():\n os.environ['FLASK_ENV'] = 'testing'\n yield get_client()\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef get_client():\n from apiserver import app, is_caching_enabled\n app.config['TESTING'] = True\n app.enable_cache(is_caching_enabled())\n return app.test_client()\n\n\[email protected]\ndef client():\n os.environ['FLASK_ENV'] = 'testing'\n yield get_client()\n\n\[email protected]\ndef client_with_caching():\n os.environ['FLASK_ENV'] = 'production'\n yield get_client()\n", "step-4": "import os\nimport pytest\n\n\ndef get_client():\n from apiserver import app, is_caching_enabled\n app.config['TESTING'] = True\n app.enable_cache(is_caching_enabled())\n return app.test_client()\n\n\[email protected]\ndef client():\n os.environ['FLASK_ENV'] = 'testing'\n yield get_client()\n\n\[email protected]\ndef client_with_caching():\n os.environ['FLASK_ENV'] = 'production'\n yield get_client()\n", "step-5": null, "step-ids": [ 1, 2, 3, 4 ] }
[ 1, 2, 3, 4 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> with open('python.jpg', 'rb') as f: data = f.read() <|reserved_special_token_0|> print(r.data.decode()) <|reserved_special_token_1|> <|reserved_special_token_0|> with open('python.jpg', 'rb') as f: data = f.read() http = urllib3.PoolManager() r = http.request('POST', 'http://httpbin.org/post', body=data, headers={ 'Content-Type': 'image/jpeg'}) print(r.data.decode()) <|reserved_special_token_1|> import urllib3 with open('python.jpg', 'rb') as f: data = f.read() http = urllib3.PoolManager() r = http.request('POST', 'http://httpbin.org/post', body=data, headers={ 'Content-Type': 'image/jpeg'}) print(r.data.decode())
flexible
{ "blob_id": "98dbc6c3bdc3efb4310a2dbb7b1cc1c89eb4582b", "index": 7354, "step-1": "<mask token>\n", "step-2": "<mask token>\nwith open('python.jpg', 'rb') as f:\n data = f.read()\n<mask token>\nprint(r.data.decode())\n", "step-3": "<mask token>\nwith open('python.jpg', 'rb') as f:\n data = f.read()\nhttp = urllib3.PoolManager()\nr = http.request('POST', 'http://httpbin.org/post', body=data, headers={\n 'Content-Type': 'image/jpeg'})\nprint(r.data.decode())\n", "step-4": "import urllib3\nwith open('python.jpg', 'rb') as f:\n data = f.read()\nhttp = urllib3.PoolManager()\nr = http.request('POST', 'http://httpbin.org/post', body=data, headers={\n 'Content-Type': 'image/jpeg'})\nprint(r.data.decode())\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
''' Module for handling configurable portions of tools ''' from json import load default_file_loc = 'config.json' config = None def loadConfiguration(fileloc): '''Loads configuration from file location''' global config with open(fileloc, 'r') as file_: conf = load(file_) if config is None: config = conf else: config.update(conf) def get(key): '''Gets the configuration value for key ''' return config[key] loadConfiguration(default_file_loc)
normal
{ "blob_id": "5261ae90a67e2df8dd1c679a8046ee3e0cbc6221", "index": 3264, "step-1": "<mask token>\n\n\ndef loadConfiguration(fileloc):\n \"\"\"Loads configuration from file location\"\"\"\n global config\n with open(fileloc, 'r') as file_:\n conf = load(file_)\n if config is None:\n config = conf\n else:\n config.update(conf)\n\n\ndef get(key):\n \"\"\"Gets the configuration value for key \"\"\"\n return config[key]\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef loadConfiguration(fileloc):\n \"\"\"Loads configuration from file location\"\"\"\n global config\n with open(fileloc, 'r') as file_:\n conf = load(file_)\n if config is None:\n config = conf\n else:\n config.update(conf)\n\n\ndef get(key):\n \"\"\"Gets the configuration value for key \"\"\"\n return config[key]\n\n\nloadConfiguration(default_file_loc)\n", "step-3": "<mask token>\ndefault_file_loc = 'config.json'\nconfig = None\n\n\ndef loadConfiguration(fileloc):\n \"\"\"Loads configuration from file location\"\"\"\n global config\n with open(fileloc, 'r') as file_:\n conf = load(file_)\n if config is None:\n config = conf\n else:\n config.update(conf)\n\n\ndef get(key):\n \"\"\"Gets the configuration value for key \"\"\"\n return config[key]\n\n\nloadConfiguration(default_file_loc)\n", "step-4": "<mask token>\nfrom json import load\ndefault_file_loc = 'config.json'\nconfig = None\n\n\ndef loadConfiguration(fileloc):\n \"\"\"Loads configuration from file location\"\"\"\n global config\n with open(fileloc, 'r') as file_:\n conf = load(file_)\n if config is None:\n config = conf\n else:\n config.update(conf)\n\n\ndef get(key):\n \"\"\"Gets the configuration value for key \"\"\"\n return config[key]\n\n\nloadConfiguration(default_file_loc)\n", "step-5": "'''\nModule for handling configurable portions of tools\n'''\n\nfrom json import load\n\ndefault_file_loc = 'config.json'\nconfig = None\n\ndef loadConfiguration(fileloc):\n '''Loads configuration from file location'''\n global config\n with open(fileloc, 'r') as file_:\n conf = load(file_)\n if config is None:\n config = conf\n else:\n config.update(conf)\n\ndef get(key):\n '''Gets the configuration value for key '''\n return config[key]\n\nloadConfiguration(default_file_loc)\n", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> if __name__ == '__main__': idf = Identifier() while raw_input('Hello!, to start listening press enter, to exit press q\n' ) != 'q': idf.guess() <|reserved_special_token_1|> from application.identifier import Identifier if __name__ == '__main__': idf = Identifier() while raw_input('Hello!, to start listening press enter, to exit press q\n' ) != 'q': idf.guess()
flexible
{ "blob_id": "d8da01433b2e6adb403fdadc713d4ee30e92c787", "index": 4829, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n idf = Identifier()\n while raw_input('Hello!, to start listening press enter, to exit press q\\n'\n ) != 'q':\n idf.guess()\n", "step-3": "from application.identifier import Identifier\nif __name__ == '__main__':\n idf = Identifier()\n while raw_input('Hello!, to start listening press enter, to exit press q\\n'\n ) != 'q':\n idf.guess()\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
<|reserved_special_token_0|> @admin.route('/', methods=['GET']) @login_required def index(): headers = {'Content-Type': 'text/html'} return make_response(render_template('index.html'), headers) <|reserved_special_token_0|> @admin.route('/roles/<role_id>', methods=['GET']) @admin.route('/roles/new', methods=['GET']) @admin.route('/roles', methods=['GET']) @login_required def roles(role_id=None, operation_type=None): headers = {'Content-Type': 'text/html'} if request.path[-4:] == '/new': roles = [Role()] operation_type = 'new' if not operation_type: roles = list_roles(role_id) operation_type = 'list' if not role_id else 'edit' return make_response(render_template('roles.html', roles=roles, operation_type=operation_type)) <|reserved_special_token_1|> <|reserved_special_token_0|> @admin.route('/', methods=['GET']) @login_required def index(): headers = {'Content-Type': 'text/html'} return make_response(render_template('index.html'), headers) @admin.route('/clients/<client_id>', methods=['GET']) @admin.route('/clients/new', methods=['GET']) @admin.route('/clients', methods=['GET']) @login_required def clients(client_id=None): headers = {'Content-Type': 'text/html'} if request.path[-4:] == '/new': clients = [Client()] operation_type = 'new' else: clients = list_clients(client_id) operation_type = 'list' if not client_id else 'edit' return make_response(render_template('clients.html', clients=clients, operation_type=operation_type)) @admin.route('/roles/<role_id>', methods=['GET']) @admin.route('/roles/new', methods=['GET']) @admin.route('/roles', methods=['GET']) @login_required def roles(role_id=None, operation_type=None): headers = {'Content-Type': 'text/html'} if request.path[-4:] == '/new': roles = [Role()] operation_type = 'new' if not operation_type: roles = list_roles(role_id) operation_type = 'list' if not role_id else 'edit' return make_response(render_template('roles.html', roles=roles, operation_type=operation_type)) <|reserved_special_token_1|> <|reserved_special_token_0|> admin = Blueprint('admin', __name__, url_prefix='/passport/admin') @admin.route('/', methods=['GET']) @login_required def index(): headers = {'Content-Type': 'text/html'} return make_response(render_template('index.html'), headers) @admin.route('/clients/<client_id>', methods=['GET']) @admin.route('/clients/new', methods=['GET']) @admin.route('/clients', methods=['GET']) @login_required def clients(client_id=None): headers = {'Content-Type': 'text/html'} if request.path[-4:] == '/new': clients = [Client()] operation_type = 'new' else: clients = list_clients(client_id) operation_type = 'list' if not client_id else 'edit' return make_response(render_template('clients.html', clients=clients, operation_type=operation_type)) @admin.route('/roles/<role_id>', methods=['GET']) @admin.route('/roles/new', methods=['GET']) @admin.route('/roles', methods=['GET']) @login_required def roles(role_id=None, operation_type=None): headers = {'Content-Type': 'text/html'} if request.path[-4:] == '/new': roles = [Role()] operation_type = 'new' if not operation_type: roles = list_roles(role_id) operation_type = 'list' if not role_id else 'edit' return make_response(render_template('roles.html', roles=roles, operation_type=operation_type)) <|reserved_special_token_1|> from flask import Blueprint, make_response, render_template, request from flask_restful import Resource from flask_security import login_required from ..clients.service import list_clients from ..roles.service import list_roles from ...models import Client, Role admin = Blueprint('admin', __name__, url_prefix='/passport/admin') @admin.route('/', methods=['GET']) @login_required def index(): headers = {'Content-Type': 'text/html'} return make_response(render_template('index.html'), headers) @admin.route('/clients/<client_id>', methods=['GET']) @admin.route('/clients/new', methods=['GET']) @admin.route('/clients', methods=['GET']) @login_required def clients(client_id=None): headers = {'Content-Type': 'text/html'} if request.path[-4:] == '/new': clients = [Client()] operation_type = 'new' else: clients = list_clients(client_id) operation_type = 'list' if not client_id else 'edit' return make_response(render_template('clients.html', clients=clients, operation_type=operation_type)) @admin.route('/roles/<role_id>', methods=['GET']) @admin.route('/roles/new', methods=['GET']) @admin.route('/roles', methods=['GET']) @login_required def roles(role_id=None, operation_type=None): headers = {'Content-Type': 'text/html'} if request.path[-4:] == '/new': roles = [Role()] operation_type = 'new' if not operation_type: roles = list_roles(role_id) operation_type = 'list' if not role_id else 'edit' return make_response(render_template('roles.html', roles=roles, operation_type=operation_type)) <|reserved_special_token_1|> # coding: utf-8 from flask import Blueprint, make_response, render_template, request from flask_restful import Resource from flask_security import login_required from ..clients.service import list_clients from ..roles.service import list_roles from ...models import Client, Role admin = Blueprint('admin', __name__, url_prefix='/passport/admin') @admin.route('/', methods=['GET']) @login_required def index(): headers = {'Content-Type': 'text/html'} return make_response(render_template( 'index.html'), headers) @admin.route('/clients/<client_id>', methods=['GET']) @admin.route('/clients/new', methods=['GET']) @admin.route('/clients', methods=['GET']) @login_required def clients(client_id=None): headers = {'Content-Type': 'text/html'} if request.path[-4:] == '/new': clients = [Client()] operation_type = 'new' else: clients = list_clients(client_id) operation_type = 'list' if not client_id else 'edit' return make_response(render_template( 'clients.html', clients=clients, operation_type=operation_type)) @admin.route('/roles/<role_id>', methods=['GET']) @admin.route('/roles/new', methods=['GET']) @admin.route('/roles', methods=['GET']) @login_required def roles(role_id=None, operation_type=None): headers = {'Content-Type': 'text/html'} if request.path[-4:] == '/new': roles = [Role()] operation_type = 'new' if not operation_type: roles = list_roles(role_id) operation_type = 'list' if not role_id else 'edit' return make_response(render_template( 'roles.html', roles=roles, operation_type=operation_type))
flexible
{ "blob_id": "f5f1a4db33cea8421cb4236606dfb288efee7621", "index": 2142, "step-1": "<mask token>\n\n\[email protected]('/', methods=['GET'])\n@login_required\ndef index():\n headers = {'Content-Type': 'text/html'}\n return make_response(render_template('index.html'), headers)\n\n\n<mask token>\n\n\[email protected]('/roles/<role_id>', methods=['GET'])\[email protected]('/roles/new', methods=['GET'])\[email protected]('/roles', methods=['GET'])\n@login_required\ndef roles(role_id=None, operation_type=None):\n headers = {'Content-Type': 'text/html'}\n if request.path[-4:] == '/new':\n roles = [Role()]\n operation_type = 'new'\n if not operation_type:\n roles = list_roles(role_id)\n operation_type = 'list' if not role_id else 'edit'\n return make_response(render_template('roles.html', roles=roles,\n operation_type=operation_type))\n", "step-2": "<mask token>\n\n\[email protected]('/', methods=['GET'])\n@login_required\ndef index():\n headers = {'Content-Type': 'text/html'}\n return make_response(render_template('index.html'), headers)\n\n\[email protected]('/clients/<client_id>', methods=['GET'])\[email protected]('/clients/new', methods=['GET'])\[email protected]('/clients', methods=['GET'])\n@login_required\ndef clients(client_id=None):\n headers = {'Content-Type': 'text/html'}\n if request.path[-4:] == '/new':\n clients = [Client()]\n operation_type = 'new'\n else:\n clients = list_clients(client_id)\n operation_type = 'list' if not client_id else 'edit'\n return make_response(render_template('clients.html', clients=clients,\n operation_type=operation_type))\n\n\[email protected]('/roles/<role_id>', methods=['GET'])\[email protected]('/roles/new', methods=['GET'])\[email protected]('/roles', methods=['GET'])\n@login_required\ndef roles(role_id=None, operation_type=None):\n headers = {'Content-Type': 'text/html'}\n if request.path[-4:] == '/new':\n roles = [Role()]\n operation_type = 'new'\n if not operation_type:\n roles = list_roles(role_id)\n operation_type = 'list' if not role_id else 'edit'\n return make_response(render_template('roles.html', roles=roles,\n operation_type=operation_type))\n", "step-3": "<mask token>\nadmin = Blueprint('admin', __name__, url_prefix='/passport/admin')\n\n\[email protected]('/', methods=['GET'])\n@login_required\ndef index():\n headers = {'Content-Type': 'text/html'}\n return make_response(render_template('index.html'), headers)\n\n\[email protected]('/clients/<client_id>', methods=['GET'])\[email protected]('/clients/new', methods=['GET'])\[email protected]('/clients', methods=['GET'])\n@login_required\ndef clients(client_id=None):\n headers = {'Content-Type': 'text/html'}\n if request.path[-4:] == '/new':\n clients = [Client()]\n operation_type = 'new'\n else:\n clients = list_clients(client_id)\n operation_type = 'list' if not client_id else 'edit'\n return make_response(render_template('clients.html', clients=clients,\n operation_type=operation_type))\n\n\[email protected]('/roles/<role_id>', methods=['GET'])\[email protected]('/roles/new', methods=['GET'])\[email protected]('/roles', methods=['GET'])\n@login_required\ndef roles(role_id=None, operation_type=None):\n headers = {'Content-Type': 'text/html'}\n if request.path[-4:] == '/new':\n roles = [Role()]\n operation_type = 'new'\n if not operation_type:\n roles = list_roles(role_id)\n operation_type = 'list' if not role_id else 'edit'\n return make_response(render_template('roles.html', roles=roles,\n operation_type=operation_type))\n", "step-4": "from flask import Blueprint, make_response, render_template, request\nfrom flask_restful import Resource\nfrom flask_security import login_required\nfrom ..clients.service import list_clients\nfrom ..roles.service import list_roles\nfrom ...models import Client, Role\nadmin = Blueprint('admin', __name__, url_prefix='/passport/admin')\n\n\[email protected]('/', methods=['GET'])\n@login_required\ndef index():\n headers = {'Content-Type': 'text/html'}\n return make_response(render_template('index.html'), headers)\n\n\[email protected]('/clients/<client_id>', methods=['GET'])\[email protected]('/clients/new', methods=['GET'])\[email protected]('/clients', methods=['GET'])\n@login_required\ndef clients(client_id=None):\n headers = {'Content-Type': 'text/html'}\n if request.path[-4:] == '/new':\n clients = [Client()]\n operation_type = 'new'\n else:\n clients = list_clients(client_id)\n operation_type = 'list' if not client_id else 'edit'\n return make_response(render_template('clients.html', clients=clients,\n operation_type=operation_type))\n\n\[email protected]('/roles/<role_id>', methods=['GET'])\[email protected]('/roles/new', methods=['GET'])\[email protected]('/roles', methods=['GET'])\n@login_required\ndef roles(role_id=None, operation_type=None):\n headers = {'Content-Type': 'text/html'}\n if request.path[-4:] == '/new':\n roles = [Role()]\n operation_type = 'new'\n if not operation_type:\n roles = list_roles(role_id)\n operation_type = 'list' if not role_id else 'edit'\n return make_response(render_template('roles.html', roles=roles,\n operation_type=operation_type))\n", "step-5": "# coding: utf-8\nfrom flask import Blueprint, make_response, render_template, request\nfrom flask_restful import Resource\nfrom flask_security import login_required\n\nfrom ..clients.service import list_clients\nfrom ..roles.service import list_roles\nfrom ...models import Client, Role\n\n\nadmin = Blueprint('admin', __name__, url_prefix='/passport/admin')\n\n\[email protected]('/', methods=['GET'])\n@login_required\ndef index():\n headers = {'Content-Type': 'text/html'}\n return make_response(render_template(\n 'index.html'), headers)\n\n\[email protected]('/clients/<client_id>', methods=['GET'])\[email protected]('/clients/new', methods=['GET'])\[email protected]('/clients', methods=['GET'])\n@login_required\ndef clients(client_id=None):\n headers = {'Content-Type': 'text/html'}\n if request.path[-4:] == '/new':\n clients = [Client()]\n operation_type = 'new'\n else:\n clients = list_clients(client_id)\n operation_type = 'list' if not client_id else 'edit'\n\n return make_response(render_template(\n 'clients.html', clients=clients, operation_type=operation_type))\n\n\[email protected]('/roles/<role_id>', methods=['GET'])\[email protected]('/roles/new', methods=['GET'])\[email protected]('/roles', methods=['GET'])\n@login_required\ndef roles(role_id=None, operation_type=None):\n headers = {'Content-Type': 'text/html'}\n if request.path[-4:] == '/new':\n roles = [Role()]\n operation_type = 'new'\n if not operation_type:\n roles = list_roles(role_id)\n operation_type = 'list' if not role_id else 'edit'\n\n return make_response(render_template(\n 'roles.html', roles=roles, operation_type=operation_type))\n", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
#!/home/porosya/.local/share/virtualenvs/checkio-VEsvC6M1/bin/checkio --domain=py run inside-block # https://py.checkio.org/mission/inside-block/ # When it comes to city planning it's import to understand the borders of various city structures. Parks, lakes or living blocks can be represented as closed polygon and can be described using cartesian coordinates on a map . We need functionality to determine is a point (a building or a tree) lies inside the structure. # # For the purpose of this mission, a city structure may be considered a polygon represented as a sequence of vertex coordinates on a plane or map. The vertices are connected sequentially with the last vertex in the list connecting to the first. We are given the coordinates of the point which we need to check. If the point of impact lies on the edge of the polygon then it should be considered inside it. For this mission, you need to determine whether the given point lies inside the polygon. # # # END_DESC def is_inside(polygon, point): return True or False if __name__ == '__main__': assert is_inside(((1, 1), (1, 3), (3, 3), (3, 1)), (2, 2)) == True, "First" assert is_inside(((1, 1), (1, 3), (3, 3), (3, 1)), (4, 2)) == False, "Second" assert is_inside(((1, 1), (4, 1), (2, 3)), (3, 2)) == True, "Third" assert is_inside(((1, 1), (4, 1), (1, 3)), (3, 3)) == False, "Fourth" assert is_inside(((2, 1), (4, 1), (5, 3), (3, 4), (1, 3)), (4, 3)) == True, "Fifth" assert is_inside(((2, 1), (4, 1), (3, 2), (3, 4), (1, 3)), (4, 3)) == False, "Sixth" assert is_inside(((1, 1), (3, 2), (5, 1), (4, 3), (5, 5), (3, 4), (1, 5), (2, 3)), (3, 3)) == True, "Seventh" assert is_inside(((1, 1), (1, 5), (5, 5), (5, 4), (2, 4), (2, 2), (5, 2), (5, 1)), (4, 3)) == False, "Eighth"
normal
{ "blob_id": "548c4dbfc1456fead75c22927ae7c6224fafeace", "index": 7893, "step-1": "<mask token>\n", "step-2": "def is_inside(polygon, point):\n return True or False\n\n\n<mask token>\n", "step-3": "def is_inside(polygon, point):\n return True or False\n\n\nif __name__ == '__main__':\n assert is_inside(((1, 1), (1, 3), (3, 3), (3, 1)), (2, 2)) == True, 'First'\n assert is_inside(((1, 1), (1, 3), (3, 3), (3, 1)), (4, 2)\n ) == False, 'Second'\n assert is_inside(((1, 1), (4, 1), (2, 3)), (3, 2)) == True, 'Third'\n assert is_inside(((1, 1), (4, 1), (1, 3)), (3, 3)) == False, 'Fourth'\n assert is_inside(((2, 1), (4, 1), (5, 3), (3, 4), (1, 3)), (4, 3)\n ) == True, 'Fifth'\n assert is_inside(((2, 1), (4, 1), (3, 2), (3, 4), (1, 3)), (4, 3)\n ) == False, 'Sixth'\n assert is_inside(((1, 1), (3, 2), (5, 1), (4, 3), (5, 5), (3, 4), (1, 5\n ), (2, 3)), (3, 3)) == True, 'Seventh'\n assert is_inside(((1, 1), (1, 5), (5, 5), (5, 4), (2, 4), (2, 2), (5, 2\n ), (5, 1)), (4, 3)) == False, 'Eighth'\n", "step-4": "#!/home/porosya/.local/share/virtualenvs/checkio-VEsvC6M1/bin/checkio --domain=py run inside-block\n\n# https://py.checkio.org/mission/inside-block/\n\n# When it comes to city planning it's import to understand the borders of various city structures. Parks, lakes or living blocks can be represented as closed polygon and can be described using cartesian coordinates on a map . We need functionality to determine is a point (a building or a tree) lies inside the structure.\n# \n# For the purpose of this mission, a city structure may be considered a polygon represented as a sequence of vertex coordinates on a plane or map. The vertices are connected sequentially with the last vertex in the list connecting to the first. We are given the coordinates of the point which we need to check. If the point of impact lies on the edge of the polygon then it should be considered inside it. For this mission, you need to determine whether the given point lies inside the polygon.\n# \n# \n# END_DESC\n\ndef is_inside(polygon, point):\n return True or False\n\n\nif __name__ == '__main__':\n assert is_inside(((1, 1), (1, 3), (3, 3), (3, 1)),\n (2, 2)) == True, \"First\"\n assert is_inside(((1, 1), (1, 3), (3, 3), (3, 1)),\n (4, 2)) == False, \"Second\"\n assert is_inside(((1, 1), (4, 1), (2, 3)),\n (3, 2)) == True, \"Third\"\n assert is_inside(((1, 1), (4, 1), (1, 3)),\n (3, 3)) == False, \"Fourth\"\n assert is_inside(((2, 1), (4, 1), (5, 3), (3, 4), (1, 3)),\n (4, 3)) == True, \"Fifth\"\n assert is_inside(((2, 1), (4, 1), (3, 2), (3, 4), (1, 3)),\n (4, 3)) == False, \"Sixth\"\n assert is_inside(((1, 1), (3, 2), (5, 1), (4, 3), (5, 5), (3, 4), (1, 5), (2, 3)),\n (3, 3)) == True, \"Seventh\"\n assert is_inside(((1, 1), (1, 5), (5, 5), (5, 4), (2, 4), (2, 2), (5, 2), (5, 1)),\n (4, 3)) == False, \"Eighth\"", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> class Window(tk.Tk): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def Get_Current_Player(self) ->str: return self.Handler.Get_Current_Player() <|reserved_special_token_0|> class Pregame(tk.Frame): FrameName = 'Pregame' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.set_vals = [] self.__GUI_Reset__() def __GUI_Reset__(self): for widget in self.winfo_children(): widget.destroy() tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack( side='top') Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10 ) rule_set_frame = tk.Frame(self, bg='white') rule_set_frame.pack(pady=10) self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font= FONTS['medium'], bg='white') self.rs_label.pack(side='top') self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[ 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set( 'full')) self.full_btn.pack() self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font= FONTS['medium'], bg='#bbbbbb', command=lambda : self. Select_Rule_Set('simple')) self.simple_btn.pack() row_frame = tk.Frame(self, bg='white') row_frame.pack(pady=10) self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[ 'medium'], bg='white') self.row_label.grid(row=0, column=0, columnspan=7) self.Rows_Buttons = [] place = 0 for rows in [4, 6, 8, 10, 12, 14, 16]: x = tk.Button(row_frame, text=str(rows), font=FONTS['small'], bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows)) x.grid(row=1, column=place) self.Rows_Buttons.append(x) place += 1 col_frame = tk.Frame(self, bg='white') col_frame.pack(pady=10) self.col_label = tk.Label(col_frame, text='Board Columns', font= FONTS['medium'], bg='white') self.col_label.grid(row=0, column=0, columnspan=7) self.Cols_Buttons = [] place = 0 for cols in [4, 6, 8, 10, 12, 14, 16]: x = tk.Button(col_frame, text=str(cols), font=FONTS['small'], bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols)) x.grid(row=1, column=place) self.Cols_Buttons.append(x) place += 1 first_move_frame = tk.Frame(self, bg='white') first_move_frame.pack(pady=10) self.first_move_label = tk.Label(first_move_frame, text= 'First to move', bg='white', font=FONTS['medium']) self.first_move_label.grid(row=0, column=0, columnspan=2) self.black_btn = tk.Button(first_move_frame, text='Black', bg= '#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_First_Move('black')) self.black_btn.grid(row=1, column=0) self.white_btn = tk.Button(first_move_frame, text='White', bg= '#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_First_Move('white')) self.white_btn.grid(row=1, column=1) condition_frame = tk.Frame(self, bg='white') condition_frame.pack(pady=10) self.condition_label = tk.Label(condition_frame, text= 'The winner is, the player with..', bg='white', font=FONTS[ 'medium']) self.condition_label.grid(row=0, column=0, columnspan=2) self.greater_score = tk.Button(condition_frame, text='more discs.', bg='#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_Condition('>')) self.greater_score.grid(row=1, column=0) self.lesser_score = tk.Button(condition_frame, text='less discs.', bg='#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_Condition('<')) self.lesser_score.grid(row=1, column=1) self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222', activebackground='#992222', font=FONTS['medium']) self.Start_Game_Btn.pack(side='bottom') def Select_Rule_Set(self, _set: str): if _set == 'simple': self.controller.Handler.GameParams['game_type'] = 1 else: self.controller.Handler.GameParams['game_type'] = 2 self.full_btn.destroy() self.simple_btn.destroy() self.rs_label.configure(text='Rule Set: ' + _set.upper()) self.set_vals.append('rules') self.Check_Can_Start() def Select_Rows(self, rows: int): self.controller.Handler.GameParams['y_size'] = rows for button in self.Rows_Buttons: button.destroy() self.row_label.configure(text='Board Rows: ' + str(rows)) self.set_vals.append('rows') self.Check_Can_Start() def Select_Cols(self, cols: int): self.controller.Handler.GameParams['x_size'] = cols for button in self.Cols_Buttons: button.destroy() self.col_label.configure(text='Board Columns: ' + str(cols)) self.set_vals.append('cols') self.Check_Can_Start() def Select_First_Move(self, mover: str): if mover == 'black': self.controller.Handler.GameParams['first_move'] = 'B' else: self.controller.Handler.GameParams['first_move'] = 'W' self.black_btn.destroy() self.white_btn.destroy() self.first_move_label.configure(text='First to move: ' + mover) self.set_vals.append('move') self.Check_Can_Start() def Select_Condition(self, condition: str): self.controller.Handler.GameParams['game_winner'] = condition if condition == '>': self.condition_label.configure(text= 'The winner is, the player with more discs.') else: self.condition_label.configure(text= 'The winner is, the player with less discs.') self.lesser_score.destroy() self.greater_score.destroy() self.set_vals.append('win') self.Check_Can_Start() def Check_Can_Start(self): if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in self.set_vals and 'move' in self.set_vals and 'win' in self. set_vals): self.Start_Game_Btn.configure(bg='#22ff22', activebackground= '#229922', command=lambda : self.Start_Custom_Board()) def Start_Custom_Board(self): self.controller.Pages['Setup_Board'].Setup_Board() self.controller.showPage('Setup_Board') self.controller.Pages['Setup_Board'].Instructions_Display() class Custom_Board(tk.Frame): FrameName = 'Setup_Board' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.Title_Frame = tk.Frame(self, bg='white') self.Title_Frame.pack(side='top', fill='x') tk.Label(self.Title_Frame, text='Create Custom Board', bg='white', font=FONTS['medium']).pack(side='left') start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22', activebackground='#229922', font=FONTS['medium'], command=lambda : self.Start()) start.pack(side='right') self.Use_Board = tk.IntVar() Use_Board = tk.Checkbutton(self.Title_Frame, text= 'Use custom board', font=FONTS['medium'], bg='white', activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0 ) Use_Board.pack(side='right', padx=10) self.Board_Area = tk.Frame(self, bg='#009900') self.Board_Area.pack(side='top', fill='both', expand=True) self.Board = [] def Setup_Board(self): for widget in self.Board_Area.winfo_children(): widget.destroy() self.Board = [] for y in range(self.controller.Handler.GameParams['y_size']): row = [] for x in range(self.controller.Handler.GameParams['x_size']): height = self.Board_Area.winfo_height() width = self.Board_Area.winfo_width() if height > width: diameter = width / self.controller.Handler.GameParams[ 'x_size'] else: diameter = height / self.controller.Handler.GameParams[ 'y_size'] self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) disc = wg.Disc(self.Board_Area, self.controller, diameter= diameter, mode='setup') disc.grid(row=y, column=x, sticky='nsew') row.append(disc) self.Board.append(row) def Parse_Board(self) ->list: new_board = [] for row in self.Board: new_row = [] for disc in row: if disc.Current_Color == 'white': new_row.append('W') elif disc.Current_Color == 'black': new_row.append('B') else: new_row.append(None) new_board.append(new_row) return new_board def Instructions_Display(self): showinfo('How to use', 'Click on a tile to cycle between white, black or empty. Check the "Use Custom Board" box to use this board!' ) def Start(self): if self.Use_Board.get(): self.controller.Handler.GameParams['board'] = self.Parse_Board() self.controller.Begin_Game() self.controller.Pages['Game'].__GUI_init__() self.controller.Pages['Game'].Update_Board() self.controller.showPage('Game') class Game(tk.Frame): FrameName = 'Game' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.Status_Bar = tk.Frame(self, bg='white') self.Status_Bar.pack(side='top', fill='x') self.Status_Bar.grid_columnconfigure(0, weight=1) self.Status_Bar.grid_columnconfigure(1, weight=1) self.Status_Bar.grid_columnconfigure(2, weight=1) self.Status_Bar.grid_rowconfigure(0, weight=1) self.Current_Player = tk.Label(self.Status_Bar, text='None', bg= 'white', font=FONTS['medium']) self.Current_Player.grid(row=0, column=0) self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white', font=FONTS['medium']) self.Game_Type.grid(row=0, column=1) self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White', bg='white', font=FONTS['medium']) self.Score.grid(row=0, column=2) self.Board_Area = tk.Frame(self, bg='#009900') self.Board_Area.pack(side='top', fill='both', expand=True) self.Board = [] def __GUI_init__(self): for y in range(self.controller.Handler.GameParams['y_size']): row = [] for x in range(self.controller.Handler.GameParams['x_size']): height = self.Board_Area.winfo_height() width = self.Board_Area.winfo_width() if height > width: diameter = width / self.controller.Handler.GameParams[ 'x_size'] else: diameter = height / self.controller.Handler.GameParams[ 'y_size'] self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) disc = wg.Disc(self.Board_Area, self.controller, diameter= diameter, command=lambda x=x, y=y: self.Disc_Function(x, y) ) disc.grid(row=y, column=x, sticky='nsew') row.append(disc) self.Board.append(row) self.Update_Board() def Reset_Game(self): self.Board = [] for widget in self.Board_Area.winfo_children(): widget.destroy() def Disc_Function(self, x: int, y: int): if not self.controller.Handler.Move(x + 1, y + 1): self.Invalid_Move() def Invalid_Move(self): showerror('Invalid Move', 'You cannot move there!') def Update_Board(self): for y in range(len(self.Board)): for x in range(len(self.Board[y])): game_piece = self.controller.Handler.Game.Board[y][x] if game_piece == None: pass elif game_piece == 'B': if self.Board[y][x].Current_Color != 'black': self.Board[y][x].Set_Piece_Color('black') elif game_piece == 'W': if self.Board[y][x].Current_Color != 'white': self.Board[y][x].Set_Piece_Color('white') def Update_Current_Player(self): self.Current_Player.config(text='Turn: ' + self.controller. Get_Current_Player()) def Update_Game_Type(self): g_type = self.controller.Handler.Get_Game_Type() self.Game_Type.configure(text='Rules: ' + g_type) def Update_Score(self): b, w = self.controller.Handler.Get_Score() self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w)) def Full_Update(self): self.Update_Score() self.Update_Current_Player() self.Update_Board() class Postgame(tk.Frame): FrameName = 'Postgame' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.Title = tk.Label(self, text='Game Over!', bg='white', font= FONTS['large']) self.Title.pack(side='top') Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10 ) self.Winner = tk.Label(self, text='The winner is black-discs.', bg= 'white', font=FONTS['medium']) self.Winner.pack(side='top') self.Buttons = tk.Frame(self, bg='white') self.Buttons.pack() Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font= FONTS['medium'], command=lambda : self.Replay()) Replay.grid(row=0, column=0) Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font= FONTS['medium'], command=lambda : self.Quit()) Quit.grid(row=0, column=1) self.Board_Area = tk.Frame(self, bg='white') self.Board_Area.pack(side='bottom') self.Score = tk.Label(self.Board_Area, text='', bg='white', font= FONTS['medium']) self.Score.pack() self.Board_Display = tk.Frame(self.Board_Area, bg='green') self.Board_Display.pack() self.Board = [] def Replay(self): self.controller.Replay() def Quit(self): self.controller.destroy() exit() def Update_Board(self): for widget in self.Board_Display.winfo_children(): widget.destroy() for y in range(self.controller.Handler.GameParams['y_size']): row = [] for x in range(self.controller.Handler.GameParams['x_size']): self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) col = None place_col = self.controller.Handler.Game.Board[y][x] if place_col == 'B': col = 'black' elif place_col == 'W': col = 'white' disc = wg.Disc(self.Board_Display, self.controller, col=col, diameter=50) disc.grid(row=y, column=x, sticky='nsew') row.append(disc) self.Board.append(row) def Update(self): winner, scores = self.controller.Handler.Get_Winner() if winner.lower() == 'b': winner = 'black-discs' elif winner.lower() == 'w': winner = 'white-discs' else: winner == 'no one' self.Winner.configure(text='The winner is ' + winner) self.Score.configure(text='Black: {0!s} | {1!s}:White'.format( scores[0], scores[1])) self.Update_Board() <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Window(tk.Tk): <|reserved_special_token_0|> def showPage(self, pagename: str): page = self.Pages[pagename] page.tkraise() <|reserved_special_token_0|> def Get_Current_Player(self) ->str: return self.Handler.Get_Current_Player() <|reserved_special_token_0|> class Pregame(tk.Frame): FrameName = 'Pregame' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.set_vals = [] self.__GUI_Reset__() def __GUI_Reset__(self): for widget in self.winfo_children(): widget.destroy() tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack( side='top') Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10 ) rule_set_frame = tk.Frame(self, bg='white') rule_set_frame.pack(pady=10) self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font= FONTS['medium'], bg='white') self.rs_label.pack(side='top') self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[ 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set( 'full')) self.full_btn.pack() self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font= FONTS['medium'], bg='#bbbbbb', command=lambda : self. Select_Rule_Set('simple')) self.simple_btn.pack() row_frame = tk.Frame(self, bg='white') row_frame.pack(pady=10) self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[ 'medium'], bg='white') self.row_label.grid(row=0, column=0, columnspan=7) self.Rows_Buttons = [] place = 0 for rows in [4, 6, 8, 10, 12, 14, 16]: x = tk.Button(row_frame, text=str(rows), font=FONTS['small'], bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows)) x.grid(row=1, column=place) self.Rows_Buttons.append(x) place += 1 col_frame = tk.Frame(self, bg='white') col_frame.pack(pady=10) self.col_label = tk.Label(col_frame, text='Board Columns', font= FONTS['medium'], bg='white') self.col_label.grid(row=0, column=0, columnspan=7) self.Cols_Buttons = [] place = 0 for cols in [4, 6, 8, 10, 12, 14, 16]: x = tk.Button(col_frame, text=str(cols), font=FONTS['small'], bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols)) x.grid(row=1, column=place) self.Cols_Buttons.append(x) place += 1 first_move_frame = tk.Frame(self, bg='white') first_move_frame.pack(pady=10) self.first_move_label = tk.Label(first_move_frame, text= 'First to move', bg='white', font=FONTS['medium']) self.first_move_label.grid(row=0, column=0, columnspan=2) self.black_btn = tk.Button(first_move_frame, text='Black', bg= '#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_First_Move('black')) self.black_btn.grid(row=1, column=0) self.white_btn = tk.Button(first_move_frame, text='White', bg= '#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_First_Move('white')) self.white_btn.grid(row=1, column=1) condition_frame = tk.Frame(self, bg='white') condition_frame.pack(pady=10) self.condition_label = tk.Label(condition_frame, text= 'The winner is, the player with..', bg='white', font=FONTS[ 'medium']) self.condition_label.grid(row=0, column=0, columnspan=2) self.greater_score = tk.Button(condition_frame, text='more discs.', bg='#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_Condition('>')) self.greater_score.grid(row=1, column=0) self.lesser_score = tk.Button(condition_frame, text='less discs.', bg='#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_Condition('<')) self.lesser_score.grid(row=1, column=1) self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222', activebackground='#992222', font=FONTS['medium']) self.Start_Game_Btn.pack(side='bottom') def Select_Rule_Set(self, _set: str): if _set == 'simple': self.controller.Handler.GameParams['game_type'] = 1 else: self.controller.Handler.GameParams['game_type'] = 2 self.full_btn.destroy() self.simple_btn.destroy() self.rs_label.configure(text='Rule Set: ' + _set.upper()) self.set_vals.append('rules') self.Check_Can_Start() def Select_Rows(self, rows: int): self.controller.Handler.GameParams['y_size'] = rows for button in self.Rows_Buttons: button.destroy() self.row_label.configure(text='Board Rows: ' + str(rows)) self.set_vals.append('rows') self.Check_Can_Start() def Select_Cols(self, cols: int): self.controller.Handler.GameParams['x_size'] = cols for button in self.Cols_Buttons: button.destroy() self.col_label.configure(text='Board Columns: ' + str(cols)) self.set_vals.append('cols') self.Check_Can_Start() def Select_First_Move(self, mover: str): if mover == 'black': self.controller.Handler.GameParams['first_move'] = 'B' else: self.controller.Handler.GameParams['first_move'] = 'W' self.black_btn.destroy() self.white_btn.destroy() self.first_move_label.configure(text='First to move: ' + mover) self.set_vals.append('move') self.Check_Can_Start() def Select_Condition(self, condition: str): self.controller.Handler.GameParams['game_winner'] = condition if condition == '>': self.condition_label.configure(text= 'The winner is, the player with more discs.') else: self.condition_label.configure(text= 'The winner is, the player with less discs.') self.lesser_score.destroy() self.greater_score.destroy() self.set_vals.append('win') self.Check_Can_Start() def Check_Can_Start(self): if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in self.set_vals and 'move' in self.set_vals and 'win' in self. set_vals): self.Start_Game_Btn.configure(bg='#22ff22', activebackground= '#229922', command=lambda : self.Start_Custom_Board()) def Start_Custom_Board(self): self.controller.Pages['Setup_Board'].Setup_Board() self.controller.showPage('Setup_Board') self.controller.Pages['Setup_Board'].Instructions_Display() class Custom_Board(tk.Frame): FrameName = 'Setup_Board' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.Title_Frame = tk.Frame(self, bg='white') self.Title_Frame.pack(side='top', fill='x') tk.Label(self.Title_Frame, text='Create Custom Board', bg='white', font=FONTS['medium']).pack(side='left') start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22', activebackground='#229922', font=FONTS['medium'], command=lambda : self.Start()) start.pack(side='right') self.Use_Board = tk.IntVar() Use_Board = tk.Checkbutton(self.Title_Frame, text= 'Use custom board', font=FONTS['medium'], bg='white', activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0 ) Use_Board.pack(side='right', padx=10) self.Board_Area = tk.Frame(self, bg='#009900') self.Board_Area.pack(side='top', fill='both', expand=True) self.Board = [] def Setup_Board(self): for widget in self.Board_Area.winfo_children(): widget.destroy() self.Board = [] for y in range(self.controller.Handler.GameParams['y_size']): row = [] for x in range(self.controller.Handler.GameParams['x_size']): height = self.Board_Area.winfo_height() width = self.Board_Area.winfo_width() if height > width: diameter = width / self.controller.Handler.GameParams[ 'x_size'] else: diameter = height / self.controller.Handler.GameParams[ 'y_size'] self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) disc = wg.Disc(self.Board_Area, self.controller, diameter= diameter, mode='setup') disc.grid(row=y, column=x, sticky='nsew') row.append(disc) self.Board.append(row) def Parse_Board(self) ->list: new_board = [] for row in self.Board: new_row = [] for disc in row: if disc.Current_Color == 'white': new_row.append('W') elif disc.Current_Color == 'black': new_row.append('B') else: new_row.append(None) new_board.append(new_row) return new_board def Instructions_Display(self): showinfo('How to use', 'Click on a tile to cycle between white, black or empty. Check the "Use Custom Board" box to use this board!' ) def Start(self): if self.Use_Board.get(): self.controller.Handler.GameParams['board'] = self.Parse_Board() self.controller.Begin_Game() self.controller.Pages['Game'].__GUI_init__() self.controller.Pages['Game'].Update_Board() self.controller.showPage('Game') class Game(tk.Frame): FrameName = 'Game' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.Status_Bar = tk.Frame(self, bg='white') self.Status_Bar.pack(side='top', fill='x') self.Status_Bar.grid_columnconfigure(0, weight=1) self.Status_Bar.grid_columnconfigure(1, weight=1) self.Status_Bar.grid_columnconfigure(2, weight=1) self.Status_Bar.grid_rowconfigure(0, weight=1) self.Current_Player = tk.Label(self.Status_Bar, text='None', bg= 'white', font=FONTS['medium']) self.Current_Player.grid(row=0, column=0) self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white', font=FONTS['medium']) self.Game_Type.grid(row=0, column=1) self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White', bg='white', font=FONTS['medium']) self.Score.grid(row=0, column=2) self.Board_Area = tk.Frame(self, bg='#009900') self.Board_Area.pack(side='top', fill='both', expand=True) self.Board = [] def __GUI_init__(self): for y in range(self.controller.Handler.GameParams['y_size']): row = [] for x in range(self.controller.Handler.GameParams['x_size']): height = self.Board_Area.winfo_height() width = self.Board_Area.winfo_width() if height > width: diameter = width / self.controller.Handler.GameParams[ 'x_size'] else: diameter = height / self.controller.Handler.GameParams[ 'y_size'] self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) disc = wg.Disc(self.Board_Area, self.controller, diameter= diameter, command=lambda x=x, y=y: self.Disc_Function(x, y) ) disc.grid(row=y, column=x, sticky='nsew') row.append(disc) self.Board.append(row) self.Update_Board() def Reset_Game(self): self.Board = [] for widget in self.Board_Area.winfo_children(): widget.destroy() def Disc_Function(self, x: int, y: int): if not self.controller.Handler.Move(x + 1, y + 1): self.Invalid_Move() def Invalid_Move(self): showerror('Invalid Move', 'You cannot move there!') def Update_Board(self): for y in range(len(self.Board)): for x in range(len(self.Board[y])): game_piece = self.controller.Handler.Game.Board[y][x] if game_piece == None: pass elif game_piece == 'B': if self.Board[y][x].Current_Color != 'black': self.Board[y][x].Set_Piece_Color('black') elif game_piece == 'W': if self.Board[y][x].Current_Color != 'white': self.Board[y][x].Set_Piece_Color('white') def Update_Current_Player(self): self.Current_Player.config(text='Turn: ' + self.controller. Get_Current_Player()) def Update_Game_Type(self): g_type = self.controller.Handler.Get_Game_Type() self.Game_Type.configure(text='Rules: ' + g_type) def Update_Score(self): b, w = self.controller.Handler.Get_Score() self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w)) def Full_Update(self): self.Update_Score() self.Update_Current_Player() self.Update_Board() class Postgame(tk.Frame): FrameName = 'Postgame' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.Title = tk.Label(self, text='Game Over!', bg='white', font= FONTS['large']) self.Title.pack(side='top') Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10 ) self.Winner = tk.Label(self, text='The winner is black-discs.', bg= 'white', font=FONTS['medium']) self.Winner.pack(side='top') self.Buttons = tk.Frame(self, bg='white') self.Buttons.pack() Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font= FONTS['medium'], command=lambda : self.Replay()) Replay.grid(row=0, column=0) Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font= FONTS['medium'], command=lambda : self.Quit()) Quit.grid(row=0, column=1) self.Board_Area = tk.Frame(self, bg='white') self.Board_Area.pack(side='bottom') self.Score = tk.Label(self.Board_Area, text='', bg='white', font= FONTS['medium']) self.Score.pack() self.Board_Display = tk.Frame(self.Board_Area, bg='green') self.Board_Display.pack() self.Board = [] def Replay(self): self.controller.Replay() def Quit(self): self.controller.destroy() exit() def Update_Board(self): for widget in self.Board_Display.winfo_children(): widget.destroy() for y in range(self.controller.Handler.GameParams['y_size']): row = [] for x in range(self.controller.Handler.GameParams['x_size']): self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) col = None place_col = self.controller.Handler.Game.Board[y][x] if place_col == 'B': col = 'black' elif place_col == 'W': col = 'white' disc = wg.Disc(self.Board_Display, self.controller, col=col, diameter=50) disc.grid(row=y, column=x, sticky='nsew') row.append(disc) self.Board.append(row) def Update(self): winner, scores = self.controller.Handler.Get_Winner() if winner.lower() == 'b': winner = 'black-discs' elif winner.lower() == 'w': winner = 'white-discs' else: winner == 'no one' self.Winner.configure(text='The winner is ' + winner) self.Score.configure(text='Black: {0!s} | {1!s}:White'.format( scores[0], scores[1])) self.Update_Board() <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Window(tk.Tk): def __init__(self, controller, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.Handler = controller self.title('Othello') try: self.iconbitmap('Icon.ico') except: pass self.minsize(600, 600) self.container = tk.Frame(self) self.container.pack(side='top', fill='both', expand=True) self.container.grid_rowconfigure(0, weight=1) self.container.grid_columnconfigure(0, weight=1) self.Pages = {} for page in (Pregame, Custom_Board, Game, Postgame): new = page(self.container, self) self.Pages[page.FrameName] = new new.grid(row=0, column=0, sticky='nsew') self.showPage('Pregame') def showPage(self, pagename: str): page = self.Pages[pagename] page.tkraise() <|reserved_special_token_0|> def Get_Current_Player(self) ->str: return self.Handler.Get_Current_Player() <|reserved_special_token_0|> class Pregame(tk.Frame): FrameName = 'Pregame' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.set_vals = [] self.__GUI_Reset__() def __GUI_Reset__(self): for widget in self.winfo_children(): widget.destroy() tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack( side='top') Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10 ) rule_set_frame = tk.Frame(self, bg='white') rule_set_frame.pack(pady=10) self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font= FONTS['medium'], bg='white') self.rs_label.pack(side='top') self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[ 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set( 'full')) self.full_btn.pack() self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font= FONTS['medium'], bg='#bbbbbb', command=lambda : self. Select_Rule_Set('simple')) self.simple_btn.pack() row_frame = tk.Frame(self, bg='white') row_frame.pack(pady=10) self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[ 'medium'], bg='white') self.row_label.grid(row=0, column=0, columnspan=7) self.Rows_Buttons = [] place = 0 for rows in [4, 6, 8, 10, 12, 14, 16]: x = tk.Button(row_frame, text=str(rows), font=FONTS['small'], bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows)) x.grid(row=1, column=place) self.Rows_Buttons.append(x) place += 1 col_frame = tk.Frame(self, bg='white') col_frame.pack(pady=10) self.col_label = tk.Label(col_frame, text='Board Columns', font= FONTS['medium'], bg='white') self.col_label.grid(row=0, column=0, columnspan=7) self.Cols_Buttons = [] place = 0 for cols in [4, 6, 8, 10, 12, 14, 16]: x = tk.Button(col_frame, text=str(cols), font=FONTS['small'], bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols)) x.grid(row=1, column=place) self.Cols_Buttons.append(x) place += 1 first_move_frame = tk.Frame(self, bg='white') first_move_frame.pack(pady=10) self.first_move_label = tk.Label(first_move_frame, text= 'First to move', bg='white', font=FONTS['medium']) self.first_move_label.grid(row=0, column=0, columnspan=2) self.black_btn = tk.Button(first_move_frame, text='Black', bg= '#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_First_Move('black')) self.black_btn.grid(row=1, column=0) self.white_btn = tk.Button(first_move_frame, text='White', bg= '#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_First_Move('white')) self.white_btn.grid(row=1, column=1) condition_frame = tk.Frame(self, bg='white') condition_frame.pack(pady=10) self.condition_label = tk.Label(condition_frame, text= 'The winner is, the player with..', bg='white', font=FONTS[ 'medium']) self.condition_label.grid(row=0, column=0, columnspan=2) self.greater_score = tk.Button(condition_frame, text='more discs.', bg='#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_Condition('>')) self.greater_score.grid(row=1, column=0) self.lesser_score = tk.Button(condition_frame, text='less discs.', bg='#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_Condition('<')) self.lesser_score.grid(row=1, column=1) self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222', activebackground='#992222', font=FONTS['medium']) self.Start_Game_Btn.pack(side='bottom') def Select_Rule_Set(self, _set: str): if _set == 'simple': self.controller.Handler.GameParams['game_type'] = 1 else: self.controller.Handler.GameParams['game_type'] = 2 self.full_btn.destroy() self.simple_btn.destroy() self.rs_label.configure(text='Rule Set: ' + _set.upper()) self.set_vals.append('rules') self.Check_Can_Start() def Select_Rows(self, rows: int): self.controller.Handler.GameParams['y_size'] = rows for button in self.Rows_Buttons: button.destroy() self.row_label.configure(text='Board Rows: ' + str(rows)) self.set_vals.append('rows') self.Check_Can_Start() def Select_Cols(self, cols: int): self.controller.Handler.GameParams['x_size'] = cols for button in self.Cols_Buttons: button.destroy() self.col_label.configure(text='Board Columns: ' + str(cols)) self.set_vals.append('cols') self.Check_Can_Start() def Select_First_Move(self, mover: str): if mover == 'black': self.controller.Handler.GameParams['first_move'] = 'B' else: self.controller.Handler.GameParams['first_move'] = 'W' self.black_btn.destroy() self.white_btn.destroy() self.first_move_label.configure(text='First to move: ' + mover) self.set_vals.append('move') self.Check_Can_Start() def Select_Condition(self, condition: str): self.controller.Handler.GameParams['game_winner'] = condition if condition == '>': self.condition_label.configure(text= 'The winner is, the player with more discs.') else: self.condition_label.configure(text= 'The winner is, the player with less discs.') self.lesser_score.destroy() self.greater_score.destroy() self.set_vals.append('win') self.Check_Can_Start() def Check_Can_Start(self): if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in self.set_vals and 'move' in self.set_vals and 'win' in self. set_vals): self.Start_Game_Btn.configure(bg='#22ff22', activebackground= '#229922', command=lambda : self.Start_Custom_Board()) def Start_Custom_Board(self): self.controller.Pages['Setup_Board'].Setup_Board() self.controller.showPage('Setup_Board') self.controller.Pages['Setup_Board'].Instructions_Display() class Custom_Board(tk.Frame): FrameName = 'Setup_Board' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.Title_Frame = tk.Frame(self, bg='white') self.Title_Frame.pack(side='top', fill='x') tk.Label(self.Title_Frame, text='Create Custom Board', bg='white', font=FONTS['medium']).pack(side='left') start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22', activebackground='#229922', font=FONTS['medium'], command=lambda : self.Start()) start.pack(side='right') self.Use_Board = tk.IntVar() Use_Board = tk.Checkbutton(self.Title_Frame, text= 'Use custom board', font=FONTS['medium'], bg='white', activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0 ) Use_Board.pack(side='right', padx=10) self.Board_Area = tk.Frame(self, bg='#009900') self.Board_Area.pack(side='top', fill='both', expand=True) self.Board = [] def Setup_Board(self): for widget in self.Board_Area.winfo_children(): widget.destroy() self.Board = [] for y in range(self.controller.Handler.GameParams['y_size']): row = [] for x in range(self.controller.Handler.GameParams['x_size']): height = self.Board_Area.winfo_height() width = self.Board_Area.winfo_width() if height > width: diameter = width / self.controller.Handler.GameParams[ 'x_size'] else: diameter = height / self.controller.Handler.GameParams[ 'y_size'] self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) disc = wg.Disc(self.Board_Area, self.controller, diameter= diameter, mode='setup') disc.grid(row=y, column=x, sticky='nsew') row.append(disc) self.Board.append(row) def Parse_Board(self) ->list: new_board = [] for row in self.Board: new_row = [] for disc in row: if disc.Current_Color == 'white': new_row.append('W') elif disc.Current_Color == 'black': new_row.append('B') else: new_row.append(None) new_board.append(new_row) return new_board def Instructions_Display(self): showinfo('How to use', 'Click on a tile to cycle between white, black or empty. Check the "Use Custom Board" box to use this board!' ) def Start(self): if self.Use_Board.get(): self.controller.Handler.GameParams['board'] = self.Parse_Board() self.controller.Begin_Game() self.controller.Pages['Game'].__GUI_init__() self.controller.Pages['Game'].Update_Board() self.controller.showPage('Game') class Game(tk.Frame): FrameName = 'Game' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.Status_Bar = tk.Frame(self, bg='white') self.Status_Bar.pack(side='top', fill='x') self.Status_Bar.grid_columnconfigure(0, weight=1) self.Status_Bar.grid_columnconfigure(1, weight=1) self.Status_Bar.grid_columnconfigure(2, weight=1) self.Status_Bar.grid_rowconfigure(0, weight=1) self.Current_Player = tk.Label(self.Status_Bar, text='None', bg= 'white', font=FONTS['medium']) self.Current_Player.grid(row=0, column=0) self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white', font=FONTS['medium']) self.Game_Type.grid(row=0, column=1) self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White', bg='white', font=FONTS['medium']) self.Score.grid(row=0, column=2) self.Board_Area = tk.Frame(self, bg='#009900') self.Board_Area.pack(side='top', fill='both', expand=True) self.Board = [] def __GUI_init__(self): for y in range(self.controller.Handler.GameParams['y_size']): row = [] for x in range(self.controller.Handler.GameParams['x_size']): height = self.Board_Area.winfo_height() width = self.Board_Area.winfo_width() if height > width: diameter = width / self.controller.Handler.GameParams[ 'x_size'] else: diameter = height / self.controller.Handler.GameParams[ 'y_size'] self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) disc = wg.Disc(self.Board_Area, self.controller, diameter= diameter, command=lambda x=x, y=y: self.Disc_Function(x, y) ) disc.grid(row=y, column=x, sticky='nsew') row.append(disc) self.Board.append(row) self.Update_Board() def Reset_Game(self): self.Board = [] for widget in self.Board_Area.winfo_children(): widget.destroy() def Disc_Function(self, x: int, y: int): if not self.controller.Handler.Move(x + 1, y + 1): self.Invalid_Move() def Invalid_Move(self): showerror('Invalid Move', 'You cannot move there!') def Update_Board(self): for y in range(len(self.Board)): for x in range(len(self.Board[y])): game_piece = self.controller.Handler.Game.Board[y][x] if game_piece == None: pass elif game_piece == 'B': if self.Board[y][x].Current_Color != 'black': self.Board[y][x].Set_Piece_Color('black') elif game_piece == 'W': if self.Board[y][x].Current_Color != 'white': self.Board[y][x].Set_Piece_Color('white') def Update_Current_Player(self): self.Current_Player.config(text='Turn: ' + self.controller. Get_Current_Player()) def Update_Game_Type(self): g_type = self.controller.Handler.Get_Game_Type() self.Game_Type.configure(text='Rules: ' + g_type) def Update_Score(self): b, w = self.controller.Handler.Get_Score() self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w)) def Full_Update(self): self.Update_Score() self.Update_Current_Player() self.Update_Board() class Postgame(tk.Frame): FrameName = 'Postgame' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.Title = tk.Label(self, text='Game Over!', bg='white', font= FONTS['large']) self.Title.pack(side='top') Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10 ) self.Winner = tk.Label(self, text='The winner is black-discs.', bg= 'white', font=FONTS['medium']) self.Winner.pack(side='top') self.Buttons = tk.Frame(self, bg='white') self.Buttons.pack() Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font= FONTS['medium'], command=lambda : self.Replay()) Replay.grid(row=0, column=0) Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font= FONTS['medium'], command=lambda : self.Quit()) Quit.grid(row=0, column=1) self.Board_Area = tk.Frame(self, bg='white') self.Board_Area.pack(side='bottom') self.Score = tk.Label(self.Board_Area, text='', bg='white', font= FONTS['medium']) self.Score.pack() self.Board_Display = tk.Frame(self.Board_Area, bg='green') self.Board_Display.pack() self.Board = [] def Replay(self): self.controller.Replay() def Quit(self): self.controller.destroy() exit() def Update_Board(self): for widget in self.Board_Display.winfo_children(): widget.destroy() for y in range(self.controller.Handler.GameParams['y_size']): row = [] for x in range(self.controller.Handler.GameParams['x_size']): self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) col = None place_col = self.controller.Handler.Game.Board[y][x] if place_col == 'B': col = 'black' elif place_col == 'W': col = 'white' disc = wg.Disc(self.Board_Display, self.controller, col=col, diameter=50) disc.grid(row=y, column=x, sticky='nsew') row.append(disc) self.Board.append(row) def Update(self): winner, scores = self.controller.Handler.Get_Winner() if winner.lower() == 'b': winner = 'black-discs' elif winner.lower() == 'w': winner = 'white-discs' else: winner == 'no one' self.Winner.configure(text='The winner is ' + winner) self.Score.configure(text='Black: {0!s} | {1!s}:White'.format( scores[0], scores[1])) self.Update_Board() <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Handler: def __init__(self): self.Game = None self.GameParams = {} self.Window = Window(self) self.Window.mainloop() <|reserved_special_token_0|> def Is_Running(self): return self.Game.Running def Start_Game(self): self.Game = lgc.Game(**self.GameParams) self.Game.Start_Game() self.Update_Game() self.Window.Pages['Game'].Update_Game_Type() def Get_Current_Player(self) ->str: if self.Game.Running: if self.Game.Current_Player == 'B': return 'black' else: return 'white' else: return 'None' def Get_Game_Type(self) ->str: g = self.Game.Game_Type if g == 1: return 'SIMPLE' else: return 'FULL' <|reserved_special_token_0|> def Move(self, x: int, y: int) ->bool: complete = self.Game.Next_Move(x, y) if complete: self.Update_Game() self.Game_Complete_Check() return True self.Update_Game() self.Game_Complete_Check() return False def Get_Winner(self) ->tuple: return self.Game.Check_Winner() def Game_Complete_Check(self): if self.Is_Running() == False: self.Window.showPage('Postgame') self.Window.Pages['Postgame'].Update() <|reserved_special_token_0|> class Window(tk.Tk): def __init__(self, controller, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.Handler = controller self.title('Othello') try: self.iconbitmap('Icon.ico') except: pass self.minsize(600, 600) self.container = tk.Frame(self) self.container.pack(side='top', fill='both', expand=True) self.container.grid_rowconfigure(0, weight=1) self.container.grid_columnconfigure(0, weight=1) self.Pages = {} for page in (Pregame, Custom_Board, Game, Postgame): new = page(self.container, self) self.Pages[page.FrameName] = new new.grid(row=0, column=0, sticky='nsew') self.showPage('Pregame') def showPage(self, pagename: str): page = self.Pages[pagename] page.tkraise() def Begin_Game(self): self.Handler.Start_Game() def Get_Current_Player(self) ->str: return self.Handler.Get_Current_Player() def Replay(self): self.Pages['Pregame'].__GUI_Reset__() self.Pages['Game'].Reset_Game() self.Handler.Replay() self.showPage('Pregame') class Pregame(tk.Frame): FrameName = 'Pregame' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.set_vals = [] self.__GUI_Reset__() def __GUI_Reset__(self): for widget in self.winfo_children(): widget.destroy() tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack( side='top') Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10 ) rule_set_frame = tk.Frame(self, bg='white') rule_set_frame.pack(pady=10) self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font= FONTS['medium'], bg='white') self.rs_label.pack(side='top') self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[ 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set( 'full')) self.full_btn.pack() self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font= FONTS['medium'], bg='#bbbbbb', command=lambda : self. Select_Rule_Set('simple')) self.simple_btn.pack() row_frame = tk.Frame(self, bg='white') row_frame.pack(pady=10) self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[ 'medium'], bg='white') self.row_label.grid(row=0, column=0, columnspan=7) self.Rows_Buttons = [] place = 0 for rows in [4, 6, 8, 10, 12, 14, 16]: x = tk.Button(row_frame, text=str(rows), font=FONTS['small'], bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows)) x.grid(row=1, column=place) self.Rows_Buttons.append(x) place += 1 col_frame = tk.Frame(self, bg='white') col_frame.pack(pady=10) self.col_label = tk.Label(col_frame, text='Board Columns', font= FONTS['medium'], bg='white') self.col_label.grid(row=0, column=0, columnspan=7) self.Cols_Buttons = [] place = 0 for cols in [4, 6, 8, 10, 12, 14, 16]: x = tk.Button(col_frame, text=str(cols), font=FONTS['small'], bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols)) x.grid(row=1, column=place) self.Cols_Buttons.append(x) place += 1 first_move_frame = tk.Frame(self, bg='white') first_move_frame.pack(pady=10) self.first_move_label = tk.Label(first_move_frame, text= 'First to move', bg='white', font=FONTS['medium']) self.first_move_label.grid(row=0, column=0, columnspan=2) self.black_btn = tk.Button(first_move_frame, text='Black', bg= '#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_First_Move('black')) self.black_btn.grid(row=1, column=0) self.white_btn = tk.Button(first_move_frame, text='White', bg= '#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_First_Move('white')) self.white_btn.grid(row=1, column=1) condition_frame = tk.Frame(self, bg='white') condition_frame.pack(pady=10) self.condition_label = tk.Label(condition_frame, text= 'The winner is, the player with..', bg='white', font=FONTS[ 'medium']) self.condition_label.grid(row=0, column=0, columnspan=2) self.greater_score = tk.Button(condition_frame, text='more discs.', bg='#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_Condition('>')) self.greater_score.grid(row=1, column=0) self.lesser_score = tk.Button(condition_frame, text='less discs.', bg='#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_Condition('<')) self.lesser_score.grid(row=1, column=1) self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222', activebackground='#992222', font=FONTS['medium']) self.Start_Game_Btn.pack(side='bottom') def Select_Rule_Set(self, _set: str): if _set == 'simple': self.controller.Handler.GameParams['game_type'] = 1 else: self.controller.Handler.GameParams['game_type'] = 2 self.full_btn.destroy() self.simple_btn.destroy() self.rs_label.configure(text='Rule Set: ' + _set.upper()) self.set_vals.append('rules') self.Check_Can_Start() def Select_Rows(self, rows: int): self.controller.Handler.GameParams['y_size'] = rows for button in self.Rows_Buttons: button.destroy() self.row_label.configure(text='Board Rows: ' + str(rows)) self.set_vals.append('rows') self.Check_Can_Start() def Select_Cols(self, cols: int): self.controller.Handler.GameParams['x_size'] = cols for button in self.Cols_Buttons: button.destroy() self.col_label.configure(text='Board Columns: ' + str(cols)) self.set_vals.append('cols') self.Check_Can_Start() def Select_First_Move(self, mover: str): if mover == 'black': self.controller.Handler.GameParams['first_move'] = 'B' else: self.controller.Handler.GameParams['first_move'] = 'W' self.black_btn.destroy() self.white_btn.destroy() self.first_move_label.configure(text='First to move: ' + mover) self.set_vals.append('move') self.Check_Can_Start() def Select_Condition(self, condition: str): self.controller.Handler.GameParams['game_winner'] = condition if condition == '>': self.condition_label.configure(text= 'The winner is, the player with more discs.') else: self.condition_label.configure(text= 'The winner is, the player with less discs.') self.lesser_score.destroy() self.greater_score.destroy() self.set_vals.append('win') self.Check_Can_Start() def Check_Can_Start(self): if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in self.set_vals and 'move' in self.set_vals and 'win' in self. set_vals): self.Start_Game_Btn.configure(bg='#22ff22', activebackground= '#229922', command=lambda : self.Start_Custom_Board()) def Start_Custom_Board(self): self.controller.Pages['Setup_Board'].Setup_Board() self.controller.showPage('Setup_Board') self.controller.Pages['Setup_Board'].Instructions_Display() class Custom_Board(tk.Frame): FrameName = 'Setup_Board' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.Title_Frame = tk.Frame(self, bg='white') self.Title_Frame.pack(side='top', fill='x') tk.Label(self.Title_Frame, text='Create Custom Board', bg='white', font=FONTS['medium']).pack(side='left') start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22', activebackground='#229922', font=FONTS['medium'], command=lambda : self.Start()) start.pack(side='right') self.Use_Board = tk.IntVar() Use_Board = tk.Checkbutton(self.Title_Frame, text= 'Use custom board', font=FONTS['medium'], bg='white', activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0 ) Use_Board.pack(side='right', padx=10) self.Board_Area = tk.Frame(self, bg='#009900') self.Board_Area.pack(side='top', fill='both', expand=True) self.Board = [] def Setup_Board(self): for widget in self.Board_Area.winfo_children(): widget.destroy() self.Board = [] for y in range(self.controller.Handler.GameParams['y_size']): row = [] for x in range(self.controller.Handler.GameParams['x_size']): height = self.Board_Area.winfo_height() width = self.Board_Area.winfo_width() if height > width: diameter = width / self.controller.Handler.GameParams[ 'x_size'] else: diameter = height / self.controller.Handler.GameParams[ 'y_size'] self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) disc = wg.Disc(self.Board_Area, self.controller, diameter= diameter, mode='setup') disc.grid(row=y, column=x, sticky='nsew') row.append(disc) self.Board.append(row) def Parse_Board(self) ->list: new_board = [] for row in self.Board: new_row = [] for disc in row: if disc.Current_Color == 'white': new_row.append('W') elif disc.Current_Color == 'black': new_row.append('B') else: new_row.append(None) new_board.append(new_row) return new_board def Instructions_Display(self): showinfo('How to use', 'Click on a tile to cycle between white, black or empty. Check the "Use Custom Board" box to use this board!' ) def Start(self): if self.Use_Board.get(): self.controller.Handler.GameParams['board'] = self.Parse_Board() self.controller.Begin_Game() self.controller.Pages['Game'].__GUI_init__() self.controller.Pages['Game'].Update_Board() self.controller.showPage('Game') class Game(tk.Frame): FrameName = 'Game' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.Status_Bar = tk.Frame(self, bg='white') self.Status_Bar.pack(side='top', fill='x') self.Status_Bar.grid_columnconfigure(0, weight=1) self.Status_Bar.grid_columnconfigure(1, weight=1) self.Status_Bar.grid_columnconfigure(2, weight=1) self.Status_Bar.grid_rowconfigure(0, weight=1) self.Current_Player = tk.Label(self.Status_Bar, text='None', bg= 'white', font=FONTS['medium']) self.Current_Player.grid(row=0, column=0) self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white', font=FONTS['medium']) self.Game_Type.grid(row=0, column=1) self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White', bg='white', font=FONTS['medium']) self.Score.grid(row=0, column=2) self.Board_Area = tk.Frame(self, bg='#009900') self.Board_Area.pack(side='top', fill='both', expand=True) self.Board = [] def __GUI_init__(self): for y in range(self.controller.Handler.GameParams['y_size']): row = [] for x in range(self.controller.Handler.GameParams['x_size']): height = self.Board_Area.winfo_height() width = self.Board_Area.winfo_width() if height > width: diameter = width / self.controller.Handler.GameParams[ 'x_size'] else: diameter = height / self.controller.Handler.GameParams[ 'y_size'] self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) disc = wg.Disc(self.Board_Area, self.controller, diameter= diameter, command=lambda x=x, y=y: self.Disc_Function(x, y) ) disc.grid(row=y, column=x, sticky='nsew') row.append(disc) self.Board.append(row) self.Update_Board() def Reset_Game(self): self.Board = [] for widget in self.Board_Area.winfo_children(): widget.destroy() def Disc_Function(self, x: int, y: int): if not self.controller.Handler.Move(x + 1, y + 1): self.Invalid_Move() def Invalid_Move(self): showerror('Invalid Move', 'You cannot move there!') def Update_Board(self): for y in range(len(self.Board)): for x in range(len(self.Board[y])): game_piece = self.controller.Handler.Game.Board[y][x] if game_piece == None: pass elif game_piece == 'B': if self.Board[y][x].Current_Color != 'black': self.Board[y][x].Set_Piece_Color('black') elif game_piece == 'W': if self.Board[y][x].Current_Color != 'white': self.Board[y][x].Set_Piece_Color('white') def Update_Current_Player(self): self.Current_Player.config(text='Turn: ' + self.controller. Get_Current_Player()) def Update_Game_Type(self): g_type = self.controller.Handler.Get_Game_Type() self.Game_Type.configure(text='Rules: ' + g_type) def Update_Score(self): b, w = self.controller.Handler.Get_Score() self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w)) def Full_Update(self): self.Update_Score() self.Update_Current_Player() self.Update_Board() class Postgame(tk.Frame): FrameName = 'Postgame' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.Title = tk.Label(self, text='Game Over!', bg='white', font= FONTS['large']) self.Title.pack(side='top') Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10 ) self.Winner = tk.Label(self, text='The winner is black-discs.', bg= 'white', font=FONTS['medium']) self.Winner.pack(side='top') self.Buttons = tk.Frame(self, bg='white') self.Buttons.pack() Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font= FONTS['medium'], command=lambda : self.Replay()) Replay.grid(row=0, column=0) Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font= FONTS['medium'], command=lambda : self.Quit()) Quit.grid(row=0, column=1) self.Board_Area = tk.Frame(self, bg='white') self.Board_Area.pack(side='bottom') self.Score = tk.Label(self.Board_Area, text='', bg='white', font= FONTS['medium']) self.Score.pack() self.Board_Display = tk.Frame(self.Board_Area, bg='green') self.Board_Display.pack() self.Board = [] def Replay(self): self.controller.Replay() def Quit(self): self.controller.destroy() exit() def Update_Board(self): for widget in self.Board_Display.winfo_children(): widget.destroy() for y in range(self.controller.Handler.GameParams['y_size']): row = [] for x in range(self.controller.Handler.GameParams['x_size']): self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) col = None place_col = self.controller.Handler.Game.Board[y][x] if place_col == 'B': col = 'black' elif place_col == 'W': col = 'white' disc = wg.Disc(self.Board_Display, self.controller, col=col, diameter=50) disc.grid(row=y, column=x, sticky='nsew') row.append(disc) self.Board.append(row) def Update(self): winner, scores = self.controller.Handler.Get_Winner() if winner.lower() == 'b': winner = 'black-discs' elif winner.lower() == 'w': winner = 'white-discs' else: winner == 'no one' self.Winner.configure(text='The winner is ' + winner) self.Score.configure(text='Black: {0!s} | {1!s}:White'.format( scores[0], scores[1])) self.Update_Board() <|reserved_special_token_0|> <|reserved_special_token_1|> import tkinter as tk import Widgets as wg import Logic as lgc from tkinter.ttk import Separator from tkinter.messagebox import showerror, showinfo # Fonts that we can utilise FONTS = {"large":("Helvetica", 20), "medium":("Helvetica", 16), "small":("Helvetica", 12)} class Handler: # Handles the window and the Game interaction def __init__(self): # Game Handle self.Game = None self.GameParams = {} # Window Handle self.Window = Window(self) self.Window.mainloop() def Replay (self): # Reset attributes and classes self.GameParams = {} del self.Game self.Game = None def Is_Running (self): return self.Game.Running def Start_Game(self): # Begin the game, run the updates needed. self.Game = lgc.Game(**self.GameParams) self.Game.Start_Game() # Update Game page self.Update_Game() self.Window.Pages["Game"].Update_Game_Type() def Get_Current_Player(self) -> str: # get the current player whose turn it is if self.Game.Running: if self.Game.Current_Player == "B": return "black" else: return "white" else: return "None" def Get_Game_Type(self) -> str: # Get the game rule type g = self.Game.Game_Type if g == 1: return "SIMPLE" else: return "FULL" def Get_Score(self) -> tuple: # Get the current score s = self.Game.Get_Discs() return s[0], s[1] # b, w def Move(self, x: int, y: int) -> bool: # Make a move on a given place complete = self.Game.Next_Move(x, y) if complete: self.Update_Game() self.Game_Complete_Check() return True self.Update_Game() self.Game_Complete_Check() return False def Get_Winner(self) -> tuple: # Gets the winner of the game return self.Game.Check_Winner() def Game_Complete_Check(self): # Check if the game is over and act accordingly if self.Is_Running() == False: # Run Game Over feature here self.Window.showPage("Postgame") # Update the post page self.Window.Pages["Postgame"].Update() def Update_Game(self): # Run a full update on the game self.Window.Pages["Game"].Full_Update() class Window (tk.Tk): # This will be the main window of the GUI def __init__ (self, controller, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.Handler = controller # This is handler between the game and window # Root attributes self.title("Othello") try: self.iconbitmap("Icon.ico") except: pass self.minsize(600, 600) #self.maxsize(1000,1000) # Master frame self.container = tk.Frame(self) self.container.pack(side="top", fill="both", expand=True) self.container.grid_rowconfigure(0, weight=1) self.container.grid_columnconfigure(0, weight=1) # Set up the pages self.Pages = {} for page in (Pregame, Custom_Board, Game, Postgame): # Initiate each page and add them to the dictionary # Dictionary will use the name of the class so that it can be accessed # without the knowledge of the clas name new = page(self.container, self) self.Pages[page.FrameName] = new new.grid(row=0, column=0, sticky="nsew") # Show the initial page self.showPage("Pregame") # Window def showPage(self, pagename: str): # Show a chosen page page = self.Pages[pagename] page.tkraise() # Game def Begin_Game(self): # Start the game self.Handler.Start_Game() def Get_Current_Player (self) -> str: # Get the current player return self.Handler.Get_Current_Player() def Replay(self): # Clean up the old game, start an new one self.Pages["Pregame"].__GUI_Reset__() self.Pages["Game"].Reset_Game() self.Handler.Replay() self.showPage("Pregame") class Pregame (tk.Frame): # The 'home' screen FrameName = "Pregame" def __init__ (self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg="white") self.set_vals = [] self.__GUI_Reset__() def __GUI_Reset__(self): # This will clean the screen and then recreate it, this is essential for replaying the game for widget in self.winfo_children(): widget.destroy() # Title Banner tk.Label(self, text="Otello", font=FONTS["large"], bg="white").pack(side="top") Separator(self, orient="horizontal").pack(side="top", fill="x", padx=10) # Rule Set rule_set_frame = tk.Frame(self, bg="white") rule_set_frame.pack(pady=10) # Subheading self.rs_label = tk.Label(rule_set_frame, text="Rule Set", font=FONTS["medium"], bg="white") self.rs_label.pack(side="top") self.full_btn = tk.Button(rule_set_frame, text="FULL", font=FONTS["medium"], bg="#bbbbbb", command=lambda:self.Select_Rule_Set("full")) self.full_btn.pack() self.simple_btn = tk.Button(rule_set_frame, text="SIMPLE", font=FONTS["medium"], bg="#bbbbbb", command=lambda:self.Select_Rule_Set("simple")) self.simple_btn.pack() # Row Size row_frame = tk.Frame(self, bg="white") row_frame.pack(pady=10) self.row_label = tk.Label(row_frame, text="Board Rows", font=FONTS["medium"], bg="white") self.row_label.grid(row=0, column=0, columnspan=7) self.Rows_Buttons = [] place = 0 for rows in [4, 6, 8, 10, 12, 14, 16]: x = tk.Button(row_frame, text=str(rows), font=FONTS["small"], bg="#bbbbbb", command=lambda rows=rows: self.Select_Rows(rows)) x.grid(row=1, column=place) self.Rows_Buttons.append(x) place += 1 # Column Size col_frame = tk.Frame(self, bg="white") col_frame.pack(pady=10) self.col_label = tk.Label(col_frame, text="Board Columns", font=FONTS["medium"], bg="white") self.col_label.grid(row=0, column=0, columnspan=7) self.Cols_Buttons = [] place = 0 for cols in [4, 6, 8, 10, 12, 14, 16]: x = tk.Button(col_frame, text=str(cols), font=FONTS["small"], bg="#bbbbbb", command=lambda cols=cols: self.Select_Cols(cols)) x.grid(row=1, column=place) self.Cols_Buttons.append(x) place += 1 # First to Move first_move_frame = tk.Frame(self, bg="white") first_move_frame.pack(pady=10) self.first_move_label = tk.Label(first_move_frame, text="First to move", bg="white", font=FONTS["medium"]) self.first_move_label.grid(row=0, column=0, columnspan=2) self.black_btn = tk.Button(first_move_frame, text="Black", bg="#bbbbbb", font=FONTS["medium"], command=lambda:self.Select_First_Move("black")) self.black_btn.grid(row=1, column=0) self.white_btn = tk.Button(first_move_frame, text="White", bg="#bbbbbb", font=FONTS["medium"], command=lambda:self.Select_First_Move("white")) self.white_btn.grid(row=1, column=1) # How to win condition_frame = tk.Frame(self, bg="white") condition_frame.pack(pady=10) self.condition_label = tk.Label(condition_frame, text="The winner is, the player with..", bg="white", font=FONTS["medium"]) self.condition_label.grid(row=0, column=0, columnspan=2) self.greater_score = tk.Button(condition_frame, text="more discs.", bg="#bbbbbb", font=FONTS["medium"], command=lambda: self.Select_Condition(">")) self.greater_score.grid(row=1, column=0) self.lesser_score = tk.Button(condition_frame, text="less discs.", bg="#bbbbbb", font=FONTS["medium"], command=lambda: self.Select_Condition("<")) self.lesser_score.grid(row=1, column=1) # Start the game button self.Start_Game_Btn = tk.Button(self, text="Start", bg="#ff2222", activebackground="#992222", font=FONTS["medium"]) self.Start_Game_Btn.pack(side="bottom") def Select_Rule_Set(self, _set: str): # sets the rule set of the game if _set == "simple": self.controller.Handler.GameParams["game_type"] = 1 # Corresponds to the game logic else: self.controller.Handler.GameParams["game_type"] = 2 self.full_btn.destroy() self.simple_btn.destroy() self.rs_label.configure(text="Rule Set: " + _set.upper()) self.set_vals.append("rules") self.Check_Can_Start() def Select_Rows(self, rows: int): # Sets the rows of the board self.controller.Handler.GameParams["y_size"] = rows for button in self.Rows_Buttons: button.destroy() self.row_label.configure(text="Board Rows: " + str(rows)) self.set_vals.append("rows") self.Check_Can_Start() def Select_Cols(self, cols: int): # sets the columns of the board self.controller.Handler.GameParams["x_size"] = cols for button in self.Cols_Buttons: button.destroy() self.col_label.configure(text="Board Columns: " + str(cols)) self.set_vals.append("cols") self.Check_Can_Start() def Select_First_Move (self, mover: str): # Sets the first player to make a move if mover == "black": self.controller.Handler.GameParams["first_move"] = "B" else: self.controller.Handler.GameParams["first_move"] = "W" self.black_btn.destroy() self.white_btn.destroy() self.first_move_label.configure(text="First to move: " + mover) self.set_vals.append("move") self.Check_Can_Start() def Select_Condition(self, condition: str):# This will set the game win condition self.controller.Handler.GameParams["game_winner"] = condition if condition == ">": self.condition_label.configure(text="The winner is, the player with more discs.") else: self.condition_label.configure(text="The winner is, the player with less discs.") self.lesser_score.destroy() self.greater_score.destroy() self.set_vals.append("win") self.Check_Can_Start() def Check_Can_Start (self): # This will start the game if the game can be started if "rules" in self.set_vals and\ "rows" in self.set_vals and\ "cols" in self.set_vals and\ "move" in self.set_vals and\ "win" in self.set_vals: self.Start_Game_Btn.configure(bg="#22ff22", activebackground="#229922", command=lambda: self.Start_Custom_Board()) def Start_Custom_Board (self): self.controller.Pages["Setup_Board"].Setup_Board() self.controller.showPage("Setup_Board") self.controller.Pages["Setup_Board"].Instructions_Display() class Custom_Board (tk.Frame): FrameName = "Setup_Board" def __init__ (self, parent, controller): tk.Frame.__init__ (self, parent) self.controller = controller self.configure(bg="white") # Title bar self.Title_Frame = tk.Frame(self, bg="white") self.Title_Frame.pack(side="top", fill="x") # Title tk.Label(self.Title_Frame, text="Create Custom Board", bg="white", font=FONTS["medium"]).pack(side="left") # Start Button start = tk.Button(self.Title_Frame, text="Play", bg="#22ff22", activebackground="#229922", font=FONTS["medium"], command=lambda: self.Start()) start.pack(side="right") # Use custom Board check button self.Use_Board = tk.IntVar() Use_Board = tk.Checkbutton(self.Title_Frame, text="Use custom board", font=FONTS["medium"], bg="white", activebackground="white", var=self.Use_Board, onvalue=1, offvalue=0) Use_Board.pack(side="right", padx=10) # Board self.Board_Area = tk.Frame(self, bg="#009900") self.Board_Area.pack(side="top", fill="both", expand=True) self.Board = [] def Setup_Board (self): for widget in self.Board_Area.winfo_children(): widget.destroy() self.Board = [] for y in range(self.controller.Handler.GameParams["y_size"]): row = [] for x in range(self.controller.Handler.GameParams["x_size"]): # Diameter with respond to the length of the shortest side of the board height = self.Board_Area.winfo_height() width = self.Board_Area.winfo_width() if height > width: diameter = width/self.controller.Handler.GameParams["x_size"] else: diameter = height/self.controller.Handler.GameParams["y_size"] self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) disc = wg.Disc(self.Board_Area, self.controller, diameter=diameter, mode="setup") disc.grid(row=y, column=x, sticky="nsew") row.append(disc) self.Board.append(row) def Parse_Board (self) -> list: # This will parse the GUI board and create a board that will work for the Game() new_board = [] for row in self.Board: new_row = [] for disc in row: if disc.Current_Color == "white": new_row.append("W") elif disc.Current_Color == "black": new_row.append("B") else: new_row.append(None) new_board.append(new_row) return new_board def Instructions_Display(self): showinfo("How to use", "Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!") def Start (self): # This will check if the user wants to use a custom board and then will set Game board to be the users selection if self.Use_Board.get(): self.controller.Handler.GameParams["board"] = self.Parse_Board() self.controller.Begin_Game() self.controller.Pages["Game"].__GUI_init__() self.controller.Pages["Game"].Update_Board() self.controller.showPage("Game") class Game (tk.Frame): # This is the 'stage' where the game will be played. FrameName = "Game" def __init__ (self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg="white") # Status Bar self.Status_Bar = tk.Frame(self, bg="white") self.Status_Bar.pack(side="top", fill="x") self.Status_Bar.grid_columnconfigure(0, weight=1) self.Status_Bar.grid_columnconfigure(1, weight=1) self.Status_Bar.grid_columnconfigure(2, weight=1) self.Status_Bar.grid_rowconfigure(0, weight=1) self.Current_Player = tk.Label(self.Status_Bar, text="None", bg="white", font=FONTS["medium"]) self.Current_Player.grid(row=0, column=0) self.Game_Type = tk.Label(self.Status_Bar, text="FULL", bg="white", font=FONTS["medium"]) self.Game_Type.grid(row=0, column=1) self.Score = tk.Label(self.Status_Bar, text="Black: 2 | 2:White", bg="white", font=FONTS["medium"]) self.Score.grid(row=0, column=2) # Board self.Board_Area = tk.Frame(self, bg="#009900") self.Board_Area.pack(side="top", fill="both", expand=True) self.Board = [] def __GUI_init__ (self): # This will initiate the game board once all the datya is provided. for y in range(self.controller.Handler.GameParams["y_size"]): row = [] for x in range(self.controller.Handler.GameParams["x_size"]): # Diameter with respond to the length of the shortest side of the board height = self.Board_Area.winfo_height() width = self.Board_Area.winfo_width() if height > width: diameter = width/self.controller.Handler.GameParams["x_size"] else: diameter = height/self.controller.Handler.GameParams["y_size"] self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) disc = wg.Disc(self.Board_Area, self.controller, diameter=diameter, command= lambda x=x, y=y: self.Disc_Function(x, y)) disc.grid(row=y, column=x, sticky="nsew") row.append(disc) self.Board.append(row) self.Update_Board() def Reset_Game(self): #This will reset the game board to its initial state self.Board = [] for widget in self.Board_Area.winfo_children(): widget.destroy() def Disc_Function (self, x: int, y: int): # This is the function run when the player clicks a disc slot/disc if not self.controller.Handler.Move(x+1, y+1): # Try run the Move function on the Handler self.Invalid_Move() def Invalid_Move(self): # This command will run when a player tries to make a move thats not possible showerror("Invalid Move", "You cannot move there!") def Update_Board (self): # Update the board to mathe the Game() board for y in range(len(self.Board)): for x in range(len(self.Board[y])): game_piece = self.controller.Handler.Game.Board[y][x] if game_piece == None: pass elif game_piece == "B": if self.Board[y][x].Current_Color != "black": self.Board[y][x].Set_Piece_Color("black") elif game_piece == "W": if self.Board[y][x].Current_Color != "white": self.Board[y][x].Set_Piece_Color("white") def Update_Current_Player (self): # Update the current player identifier self.Current_Player.config(text="Turn: " + self.controller.Get_Current_Player()) def Update_Game_Type(self): # Update the game type identifier g_type = self.controller.Handler.Get_Game_Type() self.Game_Type.configure(text="Rules: " + g_type) def Update_Score (self): # Update the score identifier b, w = self.controller.Handler.Get_Score() self.Score.configure(text="Black: {0!s} | {1!s} :White".format(b, w)) def Full_Update(self): # Run a full update on the graphics self.Update_Score() self.Update_Current_Player() self.Update_Board() class Postgame (tk.Frame): # The 'end game' screen FrameName = "Postgame" def __init__ (self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg="white") # Set a page title self.Title = tk.Label(self, text="Game Over!", bg="white", font=FONTS["large"]) self.Title.pack(side="top") Separator(self, orient="horizontal").pack(side="top", fill="x", padx=10) # Set the winner text object self.Winner = tk.Label(self, text="The winner is black-discs.", bg="white", font=FONTS["medium"]) self.Winner.pack(side="top") # Create the replay and exit buttons self.Buttons = tk.Frame(self, bg="white") self.Buttons.pack() Replay = tk.Button(self.Buttons, text="Replay", bg="#bbbbbb", font=FONTS["medium"], command=lambda: self.Replay()) Replay.grid(row=0, column=0) Quit = tk.Button(self.Buttons, text="Quit", bg="#bbbbbb", font=FONTS["medium"], command=lambda: self.Quit()) Quit.grid(row=0, column=1) # the area for the board output self.Board_Area = tk.Frame(self, bg="white") self.Board_Area.pack(side="bottom") # Score text self.Score = tk.Label(self.Board_Area, text="", bg="white", font=FONTS["medium"]) self.Score.pack() # The display for the board self.Board_Display = tk.Frame(self.Board_Area, bg="green") self.Board_Display.pack() self.Board = [] def Replay(self): # Initiate the Replay self.controller.Replay() def Quit(self): # Kill the game self.controller.destroy() exit() def Update_Board (self): # Update the game board display, kill old, create new for widget in self.Board_Display.winfo_children(): widget.destroy() for y in range(self.controller.Handler.GameParams["y_size"]): row = [] for x in range(self.controller.Handler.GameParams["x_size"]): self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) col = None place_col = self.controller.Handler.Game.Board[y][x] if place_col == "B": col = "black" elif place_col == "W": col = "white" disc = wg.Disc(self.Board_Display, self.controller, col=col, diameter=50) disc.grid(row=y, column=x, sticky="nsew") row.append(disc) self.Board.append(row) def Update(self): # Update the whole page winner, scores = self.controller.Handler.Get_Winner() if winner.lower() == "b": winner = "black-discs" elif winner.lower() == "w": winner = "white-discs" else: winner == "no one" self.Winner.configure(text="The winner is " + winner) self.Score.configure(text="Black: {0!s} | {1!s}:White".format(scores[0], scores[1])) self.Update_Board() if __name__ == "__main__": Window = Handler()
flexible
{ "blob_id": "9b8f3962172d4a867a3a070b6139bb302fd7e2f5", "index": 9934, "step-1": "<mask token>\n\n\nclass Window(tk.Tk):\n <mask token>\n <mask token>\n <mask token>\n\n def Get_Current_Player(self) ->str:\n return self.Handler.Get_Current_Player()\n <mask token>\n\n\nclass Pregame(tk.Frame):\n FrameName = 'Pregame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n\n def Start_Custom_Board(self):\n self.controller.Pages['Setup_Board'].Setup_Board()\n self.controller.showPage('Setup_Board')\n self.controller.Pages['Setup_Board'].Instructions_Display()\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Window(tk.Tk):\n <mask token>\n\n def showPage(self, pagename: str):\n page = self.Pages[pagename]\n page.tkraise()\n <mask token>\n\n def Get_Current_Player(self) ->str:\n return self.Handler.Get_Current_Player()\n <mask token>\n\n\nclass Pregame(tk.Frame):\n FrameName = 'Pregame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n\n def Start_Custom_Board(self):\n self.controller.Pages['Setup_Board'].Setup_Board()\n self.controller.showPage('Setup_Board')\n self.controller.Pages['Setup_Board'].Instructions_Display()\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass Window(tk.Tk):\n\n def __init__(self, controller, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.Handler = controller\n self.title('Othello')\n try:\n self.iconbitmap('Icon.ico')\n except:\n pass\n self.minsize(600, 600)\n self.container = tk.Frame(self)\n self.container.pack(side='top', fill='both', expand=True)\n self.container.grid_rowconfigure(0, weight=1)\n self.container.grid_columnconfigure(0, weight=1)\n self.Pages = {}\n for page in (Pregame, Custom_Board, Game, Postgame):\n new = page(self.container, self)\n self.Pages[page.FrameName] = new\n new.grid(row=0, column=0, sticky='nsew')\n self.showPage('Pregame')\n\n def showPage(self, pagename: str):\n page = self.Pages[pagename]\n page.tkraise()\n <mask token>\n\n def Get_Current_Player(self) ->str:\n return self.Handler.Get_Current_Player()\n <mask token>\n\n\nclass Pregame(tk.Frame):\n FrameName = 'Pregame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n\n def Start_Custom_Board(self):\n self.controller.Pages['Setup_Board'].Setup_Board()\n self.controller.showPage('Setup_Board')\n self.controller.Pages['Setup_Board'].Instructions_Display()\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\nclass Handler:\n\n def __init__(self):\n self.Game = None\n self.GameParams = {}\n self.Window = Window(self)\n self.Window.mainloop()\n <mask token>\n\n def Is_Running(self):\n return self.Game.Running\n\n def Start_Game(self):\n self.Game = lgc.Game(**self.GameParams)\n self.Game.Start_Game()\n self.Update_Game()\n self.Window.Pages['Game'].Update_Game_Type()\n\n def Get_Current_Player(self) ->str:\n if self.Game.Running:\n if self.Game.Current_Player == 'B':\n return 'black'\n else:\n return 'white'\n else:\n return 'None'\n\n def Get_Game_Type(self) ->str:\n g = self.Game.Game_Type\n if g == 1:\n return 'SIMPLE'\n else:\n return 'FULL'\n <mask token>\n\n def Move(self, x: int, y: int) ->bool:\n complete = self.Game.Next_Move(x, y)\n if complete:\n self.Update_Game()\n self.Game_Complete_Check()\n return True\n self.Update_Game()\n self.Game_Complete_Check()\n return False\n\n def Get_Winner(self) ->tuple:\n return self.Game.Check_Winner()\n\n def Game_Complete_Check(self):\n if self.Is_Running() == False:\n self.Window.showPage('Postgame')\n self.Window.Pages['Postgame'].Update()\n <mask token>\n\n\nclass Window(tk.Tk):\n\n def __init__(self, controller, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.Handler = controller\n self.title('Othello')\n try:\n self.iconbitmap('Icon.ico')\n except:\n pass\n self.minsize(600, 600)\n self.container = tk.Frame(self)\n self.container.pack(side='top', fill='both', expand=True)\n self.container.grid_rowconfigure(0, weight=1)\n self.container.grid_columnconfigure(0, weight=1)\n self.Pages = {}\n for page in (Pregame, Custom_Board, Game, Postgame):\n new = page(self.container, self)\n self.Pages[page.FrameName] = new\n new.grid(row=0, column=0, sticky='nsew')\n self.showPage('Pregame')\n\n def showPage(self, pagename: str):\n page = self.Pages[pagename]\n page.tkraise()\n\n def Begin_Game(self):\n self.Handler.Start_Game()\n\n def Get_Current_Player(self) ->str:\n return self.Handler.Get_Current_Player()\n\n def Replay(self):\n self.Pages['Pregame'].__GUI_Reset__()\n self.Pages['Game'].Reset_Game()\n self.Handler.Replay()\n self.showPage('Pregame')\n\n\nclass Pregame(tk.Frame):\n FrameName = 'Pregame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n\n def Start_Custom_Board(self):\n self.controller.Pages['Setup_Board'].Setup_Board()\n self.controller.showPage('Setup_Board')\n self.controller.Pages['Setup_Board'].Instructions_Display()\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<mask token>\n", "step-5": "import tkinter \t\tas tk\nimport Widgets \t\tas wg\nimport Logic \t\tas lgc\nfrom tkinter.ttk \timport Separator\nfrom tkinter.messagebox import showerror, showinfo\n\n# Fonts that we can utilise\nFONTS = {\"large\":(\"Helvetica\", 20), \"medium\":(\"Helvetica\", 16), \"small\":(\"Helvetica\", 12)}\n\nclass Handler: # Handles the window and the Game interaction\n\tdef __init__(self):\n\n\t\t# Game Handle\n\t\tself.Game = None\n\t\tself.GameParams = {}\n\n\t\t# Window Handle\n\t\tself.Window = Window(self)\n\t\tself.Window.mainloop()\n\n\tdef Replay (self): # Reset attributes and classes\n\t\tself.GameParams = {}\n\t\tdel self.Game\n\t\tself.Game = None\n\t\t\n\tdef Is_Running (self):\n\t\treturn self.Game.Running\n\n\tdef Start_Game(self): # Begin the game, run the updates needed.\n\t\tself.Game = lgc.Game(**self.GameParams)\n\t\tself.Game.Start_Game()\n\n\t\t# Update Game page\n\t\tself.Update_Game()\n\t\tself.Window.Pages[\"Game\"].Update_Game_Type()\n\n\tdef Get_Current_Player(self) -> str: # get the current player whose turn it is\n\t\tif self.Game.Running:\n\t\t\tif self.Game.Current_Player == \"B\":\n\t\t\t\treturn \"black\"\n\t\t\telse:\n\t\t\t\treturn \"white\"\n\t\telse:\n\t\t\treturn \"None\"\n\n\tdef Get_Game_Type(self) -> str: # Get the game rule type\n\t\tg = self.Game.Game_Type\n\t\tif g == 1:\n\t\t\treturn \"SIMPLE\"\n\t\telse:\n\t\t\treturn \"FULL\"\n\n\tdef Get_Score(self) -> tuple: # Get the current score\n\t\ts = self.Game.Get_Discs()\n\t\treturn s[0], s[1] # b, w\n\n\tdef Move(self, x: int, y: int) -> bool: # Make a move on a given place\n\t\tcomplete = self.Game.Next_Move(x, y)\n\t\tif complete:\n\t\t\tself.Update_Game()\n\t\t\tself.Game_Complete_Check()\n\t\t\treturn True\n\t\tself.Update_Game()\n\t\tself.Game_Complete_Check()\n\t\treturn False\n\n\tdef Get_Winner(self) -> tuple: # Gets the winner of the game\n\t\treturn self.Game.Check_Winner()\n\n\tdef Game_Complete_Check(self): # Check if the game is over and act accordingly\n\t\tif self.Is_Running() == False:\n\t\t\t# Run Game Over feature here\n\t\t\tself.Window.showPage(\"Postgame\")\n\t\t\t# Update the post page\n\t\t\tself.Window.Pages[\"Postgame\"].Update()\n\n\tdef Update_Game(self): # Run a full update on the game\n\t\tself.Window.Pages[\"Game\"].Full_Update()\n\nclass Window (tk.Tk): # This will be the main window of the GUI\n\tdef __init__ (self, controller, *args, **kwargs):\n\t\ttk.Tk.__init__(self, *args, **kwargs)\n\n\t\tself.Handler = controller # This is handler between the game and window\n\n\t\t# Root attributes\n\t\tself.title(\"Othello\")\n\t\t\n\t\ttry:\n\t\t\tself.iconbitmap(\"Icon.ico\")\n\t\texcept:\n\t\t\tpass\n\n\t\tself.minsize(600, 600)\n\t\t#self.maxsize(1000,1000)\n\n\t\t# Master frame\n\t\tself.container = tk.Frame(self)\n\t\tself.container.pack(side=\"top\", fill=\"both\", expand=True)\n\t\tself.container.grid_rowconfigure(0, weight=1)\n\t\tself.container.grid_columnconfigure(0, weight=1)\n\n\t\t# Set up the pages\n\t\tself.Pages = {}\n\t\tfor page in (Pregame, Custom_Board, Game, Postgame):\n\t\t\t# Initiate each page and add them to the dictionary\n\t\t\t# Dictionary will use the name of the class so that it can be accessed\n\t\t\t# without the knowledge of the clas name\n\t\t\tnew = page(self.container, self)\n\t\t\tself.Pages[page.FrameName] = new\n\t\t\tnew.grid(row=0, column=0, sticky=\"nsew\")\n\n\t\t# Show the initial page\n\t\tself.showPage(\"Pregame\")\n\n\t# Window\n\n\tdef showPage(self, pagename: str): # Show a chosen page\n\t\tpage = self.Pages[pagename]\n\t\tpage.tkraise()\n\n\t# Game\n\tdef Begin_Game(self): # Start the game\n\t\tself.Handler.Start_Game()\n\n\tdef Get_Current_Player (self) -> str: # Get the current player\n\t\treturn self.Handler.Get_Current_Player()\n\n\tdef Replay(self): # Clean up the old game, start an new one\n\t\tself.Pages[\"Pregame\"].__GUI_Reset__()\n\t\tself.Pages[\"Game\"].Reset_Game()\n\t\tself.Handler.Replay()\n\t\tself.showPage(\"Pregame\")\n\nclass Pregame (tk.Frame): # The 'home' screen\n\tFrameName = \"Pregame\"\n\tdef __init__ (self, parent, controller):\n\t\ttk.Frame.__init__(self, parent)\t\n\n\t\tself.controller = controller\n\t\tself.configure(bg=\"white\")\n\n\t\tself.set_vals = []\n\n\t\tself.__GUI_Reset__()\n\n\tdef __GUI_Reset__(self): # This will clean the screen and then recreate it, this is essential for replaying the game\n\t\tfor widget in self.winfo_children():\n\t\t\twidget.destroy()\n\n\t\t# Title Banner\n\t\ttk.Label(self, text=\"Otello\", font=FONTS[\"large\"], bg=\"white\").pack(side=\"top\")\n\t\tSeparator(self, orient=\"horizontal\").pack(side=\"top\", fill=\"x\", padx=10)\n\n\t\t# Rule Set\n\t\trule_set_frame = tk.Frame(self, bg=\"white\")\n\t\trule_set_frame.pack(pady=10)\n\t\t# Subheading\n\t\tself.rs_label = tk.Label(rule_set_frame, text=\"Rule Set\", font=FONTS[\"medium\"], bg=\"white\")\n\t\tself.rs_label.pack(side=\"top\")\n\n\t\tself.full_btn = tk.Button(rule_set_frame, text=\"FULL\", font=FONTS[\"medium\"], bg=\"#bbbbbb\",\n\t\t\tcommand=lambda:self.Select_Rule_Set(\"full\"))\n\t\tself.full_btn.pack()\n\n\t\tself.simple_btn = tk.Button(rule_set_frame, text=\"SIMPLE\", font=FONTS[\"medium\"], bg=\"#bbbbbb\",\n\t\t\tcommand=lambda:self.Select_Rule_Set(\"simple\"))\n\t\tself.simple_btn.pack()\n\n\t\t# Row Size\n\t\trow_frame = tk.Frame(self, bg=\"white\")\n\t\trow_frame.pack(pady=10)\n\n\t\tself.row_label = tk.Label(row_frame, text=\"Board Rows\", font=FONTS[\"medium\"], bg=\"white\")\n\t\tself.row_label.grid(row=0, column=0, columnspan=7)\n\n\t\tself.Rows_Buttons = []\n\n\t\tplace = 0\n\t\tfor rows in [4, 6, 8, 10, 12, 14, 16]:\n\t\t\tx = tk.Button(row_frame, text=str(rows), font=FONTS[\"small\"], bg=\"#bbbbbb\",\n\t\t\t\tcommand=lambda rows=rows: self.Select_Rows(rows))\n\t\t\tx.grid(row=1, column=place)\n\t\t\tself.Rows_Buttons.append(x)\n\t\t\tplace += 1\n\n\t\t# Column Size\n\t\tcol_frame = tk.Frame(self, bg=\"white\")\n\t\tcol_frame.pack(pady=10)\n\n\t\tself.col_label = tk.Label(col_frame, text=\"Board Columns\", font=FONTS[\"medium\"], bg=\"white\")\n\t\tself.col_label.grid(row=0, column=0, columnspan=7)\n\n\t\tself.Cols_Buttons = []\n\n\t\tplace = 0\n\t\tfor cols in [4, 6, 8, 10, 12, 14, 16]:\n\t\t\tx = tk.Button(col_frame, text=str(cols), font=FONTS[\"small\"], bg=\"#bbbbbb\",\n\t\t\t\tcommand=lambda cols=cols: self.Select_Cols(cols))\n\t\t\tx.grid(row=1, column=place)\n\t\t\tself.Cols_Buttons.append(x)\n\t\t\tplace += 1\n\n\t\t# First to Move\n\t\tfirst_move_frame = tk.Frame(self, bg=\"white\")\n\t\tfirst_move_frame.pack(pady=10)\n\n\t\tself.first_move_label = tk.Label(first_move_frame, text=\"First to move\", bg=\"white\", font=FONTS[\"medium\"])\n\t\tself.first_move_label.grid(row=0, column=0, columnspan=2)\n\n\t\tself.black_btn = tk.Button(first_move_frame, text=\"Black\", bg=\"#bbbbbb\", font=FONTS[\"medium\"],\n\t\t\tcommand=lambda:self.Select_First_Move(\"black\"))\n\t\tself.black_btn.grid(row=1, column=0)\n\n\t\tself.white_btn = tk.Button(first_move_frame, text=\"White\", bg=\"#bbbbbb\", font=FONTS[\"medium\"],\n\t\t\tcommand=lambda:self.Select_First_Move(\"white\"))\n\t\tself.white_btn.grid(row=1, column=1)\n\n\t\t# How to win\n\t\tcondition_frame = tk.Frame(self, bg=\"white\")\n\t\tcondition_frame.pack(pady=10)\n\n\t\tself.condition_label = tk.Label(condition_frame, text=\"The winner is, the player with..\",\n\t\t\tbg=\"white\", font=FONTS[\"medium\"])\n\t\tself.condition_label.grid(row=0, column=0, columnspan=2)\n\n\t\tself.greater_score = tk.Button(condition_frame, text=\"more discs.\", bg=\"#bbbbbb\", font=FONTS[\"medium\"],\n\t\t\tcommand=lambda: self.Select_Condition(\">\"))\n\t\tself.greater_score.grid(row=1, column=0)\n\n\t\tself.lesser_score = tk.Button(condition_frame, text=\"less discs.\", bg=\"#bbbbbb\", font=FONTS[\"medium\"],\n\t\t\tcommand=lambda: self.Select_Condition(\"<\"))\n\t\tself.lesser_score.grid(row=1, column=1)\n\n\n\t\t# Start the game button\n\t\tself.Start_Game_Btn = tk.Button(self, text=\"Start\", bg=\"#ff2222\", activebackground=\"#992222\",\n\t\t\t\t\t\t\t\t\tfont=FONTS[\"medium\"])\n\t\tself.Start_Game_Btn.pack(side=\"bottom\")\n\n\tdef Select_Rule_Set(self, _set: str): # sets the rule set of the game\n\t\tif _set == \"simple\":\n\t\t\tself.controller.Handler.GameParams[\"game_type\"] = 1 # Corresponds to the game logic\n\t\telse:\n\t\t\tself.controller.Handler.GameParams[\"game_type\"] = 2\n\n\t\tself.full_btn.destroy()\n\t\tself.simple_btn.destroy()\n\t\tself.rs_label.configure(text=\"Rule Set: \" + _set.upper())\n\n\t\tself.set_vals.append(\"rules\")\n\t\tself.Check_Can_Start()\n\n\tdef Select_Rows(self, rows: int): # Sets the rows of the board\n\t\tself.controller.Handler.GameParams[\"y_size\"] = rows\n\n\t\tfor button in self.Rows_Buttons:\n\t\t\tbutton.destroy()\n\n\t\tself.row_label.configure(text=\"Board Rows: \" + str(rows))\n\n\t\tself.set_vals.append(\"rows\")\n\t\tself.Check_Can_Start()\n\n\tdef Select_Cols(self, cols: int): # sets the columns of the board\n\t\tself.controller.Handler.GameParams[\"x_size\"] = cols\n\n\t\tfor button in self.Cols_Buttons:\n\t\t\tbutton.destroy()\n\n\t\tself.col_label.configure(text=\"Board Columns: \" + str(cols))\n\t\t\n\t\tself.set_vals.append(\"cols\")\n\t\tself.Check_Can_Start()\n\n\tdef Select_First_Move (self, mover: str): # Sets the first player to make a move\n\t\tif mover == \"black\":\n\t\t\tself.controller.Handler.GameParams[\"first_move\"] = \"B\"\n\t\telse:\n\t\t\tself.controller.Handler.GameParams[\"first_move\"] = \"W\"\n\n\t\tself.black_btn.destroy()\n\t\tself.white_btn.destroy()\n\n\t\tself.first_move_label.configure(text=\"First to move: \" + mover)\n\n\t\tself.set_vals.append(\"move\")\n\t\tself.Check_Can_Start()\n\n\tdef Select_Condition(self, condition: str):# This will set the game win condition\n\t\tself.controller.Handler.GameParams[\"game_winner\"] = condition\n\n\t\tif condition == \">\":\n\t\t\tself.condition_label.configure(text=\"The winner is, the player with more discs.\")\n\t\telse:\n\t\t\tself.condition_label.configure(text=\"The winner is, the player with less discs.\")\n\n\t\tself.lesser_score.destroy()\n\t\tself.greater_score.destroy()\n\n\t\tself.set_vals.append(\"win\")\n\t\tself.Check_Can_Start()\n\n\tdef Check_Can_Start (self): # This will start the game if the game can be started\n\t\tif \"rules\" in self.set_vals and\\\n\t\t \"rows\" in self.set_vals and\\\n\t\t \"cols\" in self.set_vals and\\\n\t\t \"move\" in self.set_vals and\\\n\t\t \"win\" in self.set_vals:\n\t\t self.Start_Game_Btn.configure(bg=\"#22ff22\", activebackground=\"#229922\",\n\t\t \tcommand=lambda: self.Start_Custom_Board())\n\n\tdef Start_Custom_Board (self):\n\t\tself.controller.Pages[\"Setup_Board\"].Setup_Board()\n\t\tself.controller.showPage(\"Setup_Board\")\n\t\tself.controller.Pages[\"Setup_Board\"].Instructions_Display()\n\nclass Custom_Board (tk.Frame):\n\tFrameName = \"Setup_Board\"\n\tdef __init__ (self, parent, controller):\n\t\ttk.Frame.__init__ (self, parent)\n\n\t\tself.controller = controller\n\t\tself.configure(bg=\"white\")\n\n\t\t# Title bar\n\t\tself.Title_Frame = tk.Frame(self, bg=\"white\")\n\t\tself.Title_Frame.pack(side=\"top\", fill=\"x\")\n\n\t\t# Title\n\t\ttk.Label(self.Title_Frame, text=\"Create Custom Board\", bg=\"white\", font=FONTS[\"medium\"]).pack(side=\"left\")\n\n\t\t# Start Button\n\t\tstart = tk.Button(self.Title_Frame, text=\"Play\", bg=\"#22ff22\", activebackground=\"#229922\", font=FONTS[\"medium\"],\n\t\t\tcommand=lambda: self.Start())\n\t\tstart.pack(side=\"right\")\t\t\n\n\n\t\t# Use custom Board check button\n\t\tself.Use_Board = tk.IntVar()\n\n\t\tUse_Board = tk.Checkbutton(self.Title_Frame, text=\"Use custom board\", font=FONTS[\"medium\"],\n\t\t\tbg=\"white\", activebackground=\"white\",\n\t\t\tvar=self.Use_Board, onvalue=1, offvalue=0)\n\t\tUse_Board.pack(side=\"right\", padx=10)\n\n\t\t\n\t\t# Board\n\t\tself.Board_Area = tk.Frame(self, bg=\"#009900\")\n\t\tself.Board_Area.pack(side=\"top\", fill=\"both\", expand=True)\n\n\t\tself.Board = []\n\n\tdef Setup_Board (self):\n\t\tfor widget in self.Board_Area.winfo_children():\n\t\t\twidget.destroy()\n\t\tself.Board = []\n\n\t\t\n\t\tfor y in range(self.controller.Handler.GameParams[\"y_size\"]):\n\t\t\trow = []\n\t\t\tfor x in range(self.controller.Handler.GameParams[\"x_size\"]):\n\t\t\t\t# Diameter with respond to the length of the shortest side of the board\n\t\t\t\theight = self.Board_Area.winfo_height()\n\t\t\t\twidth = self.Board_Area.winfo_width()\n\n\t\t\t\tif height > width:\n\t\t\t\t\tdiameter = width/self.controller.Handler.GameParams[\"x_size\"]\n\t\t\t\telse:\n\t\t\t\t\tdiameter = height/self.controller.Handler.GameParams[\"y_size\"]\n\n\t\t\t\tself.Board_Area.grid_columnconfigure(x, weight=1)\n\t\t\t\tself.Board_Area.grid_rowconfigure(y, weight=1)\n\n\t\t\t\tdisc = wg.Disc(self.Board_Area, self.controller, diameter=diameter, mode=\"setup\")\n\t\t\t\tdisc.grid(row=y, column=x, sticky=\"nsew\")\n\t\t\t\trow.append(disc)\n\n\t\t\tself.Board.append(row)\n\n\tdef Parse_Board (self) -> list: # This will parse the GUI board and create a board that will work for the Game()\n\t\tnew_board = []\n\t\tfor row in self.Board:\n\t\t\tnew_row = []\n\t\t\tfor disc in row:\n\t\t\t\tif disc.Current_Color == \"white\":\n\t\t\t\t\tnew_row.append(\"W\")\n\t\t\t\telif disc.Current_Color == \"black\":\n\t\t\t\t\tnew_row.append(\"B\")\n\t\t\t\telse:\n\t\t\t\t\tnew_row.append(None)\n\t\t\tnew_board.append(new_row)\n\n\t\treturn new_board\n\n\tdef Instructions_Display(self):\n\t\tshowinfo(\"How to use\", \"Click on a tile to cycle between white, black or empty. Check the \\\"Use Custom Board\\\" box to use this board!\")\n\n\tdef Start (self): # This will check if the user wants to use a custom board and then will set Game board to be the users selection\n\t\tif self.Use_Board.get():\n\t\t\tself.controller.Handler.GameParams[\"board\"] = self.Parse_Board()\n\t\tself.controller.Begin_Game()\n\t\tself.controller.Pages[\"Game\"].__GUI_init__()\n\t\tself.controller.Pages[\"Game\"].Update_Board()\n\t\tself.controller.showPage(\"Game\")\n\nclass Game (tk.Frame): # This is the 'stage' where the game will be played.\n\tFrameName = \"Game\"\n\tdef __init__ (self, parent, controller):\n\t\ttk.Frame.__init__(self, parent)\n\n\t\tself.controller = controller\n\t\tself.configure(bg=\"white\")\n\n\t\t# Status Bar\n\t\tself.Status_Bar = tk.Frame(self, bg=\"white\")\n\t\tself.Status_Bar.pack(side=\"top\", fill=\"x\")\n\n\t\tself.Status_Bar.grid_columnconfigure(0, weight=1)\n\t\tself.Status_Bar.grid_columnconfigure(1, weight=1)\n\t\tself.Status_Bar.grid_columnconfigure(2, weight=1)\n\t\tself.Status_Bar.grid_rowconfigure(0, weight=1)\n\n\t\tself.Current_Player = tk.Label(self.Status_Bar, text=\"None\", bg=\"white\", font=FONTS[\"medium\"])\n\t\tself.Current_Player.grid(row=0, column=0)\n\n\t\tself.Game_Type = tk.Label(self.Status_Bar, text=\"FULL\", bg=\"white\", font=FONTS[\"medium\"])\n\t\tself.Game_Type.grid(row=0, column=1)\n\n\t\tself.Score = tk.Label(self.Status_Bar, text=\"Black: 2 | 2:White\", bg=\"white\", font=FONTS[\"medium\"])\n\t\tself.Score.grid(row=0, column=2)\n\n\t\t# Board\n\t\tself.Board_Area = tk.Frame(self, bg=\"#009900\")\n\t\tself.Board_Area.pack(side=\"top\", fill=\"both\", expand=True)\n\n\t\tself.Board = []\n\n\tdef __GUI_init__ (self): # This will initiate the game board once all the datya is provided.\n\t\tfor y in range(self.controller.Handler.GameParams[\"y_size\"]):\n\t\t\trow = []\n\t\t\tfor x in range(self.controller.Handler.GameParams[\"x_size\"]):\n\t\t\t\t# Diameter with respond to the length of the shortest side of the board\n\t\t\t\theight = self.Board_Area.winfo_height()\n\t\t\t\twidth = self.Board_Area.winfo_width()\n\n\t\t\t\tif height > width:\n\t\t\t\t\tdiameter = width/self.controller.Handler.GameParams[\"x_size\"]\n\t\t\t\telse:\n\t\t\t\t\tdiameter = height/self.controller.Handler.GameParams[\"y_size\"]\n\n\t\t\t\tself.Board_Area.grid_columnconfigure(x, weight=1)\n\t\t\t\tself.Board_Area.grid_rowconfigure(y, weight=1)\n\n\t\t\t\tdisc = wg.Disc(self.Board_Area, self.controller, diameter=diameter,\n\t\t\t\t\tcommand= lambda x=x, y=y: self.Disc_Function(x, y))\n\t\t\t\tdisc.grid(row=y, column=x, sticky=\"nsew\")\n\t\t\t\trow.append(disc)\n\n\t\t\tself.Board.append(row)\n\n\t\tself.Update_Board()\n\n\tdef Reset_Game(self): #This will reset the game board to its initial state\n\t\tself.Board = []\n\t\tfor widget in self.Board_Area.winfo_children():\n\t\t\twidget.destroy()\n\n\tdef Disc_Function (self, x: int, y: int): # This is the function run when the player clicks a disc slot/disc\n\t\tif not self.controller.Handler.Move(x+1, y+1): # Try run the Move function on the Handler\n\t\t\tself.Invalid_Move()\n\n\tdef Invalid_Move(self): # This command will run when a player tries to make a move thats not possible\n\t\tshowerror(\"Invalid Move\", \"You cannot move there!\")\n\n\tdef Update_Board (self): # Update the board to mathe the Game() board\n\t\tfor y in range(len(self.Board)):\n\t\t\tfor x in range(len(self.Board[y])):\n\t\t\t\tgame_piece = self.controller.Handler.Game.Board[y][x]\n\t\t\t\tif game_piece == None:\n\t\t\t\t\tpass\n\t\t\t\telif game_piece == \"B\":\n\t\t\t\t\tif self.Board[y][x].Current_Color != \"black\":\n\t\t\t\t\t\tself.Board[y][x].Set_Piece_Color(\"black\")\n\t\t\t\telif game_piece == \"W\":\n\t\t\t\t\tif self.Board[y][x].Current_Color != \"white\":\n\t\t\t\t\t\tself.Board[y][x].Set_Piece_Color(\"white\")\n\n\tdef Update_Current_Player (self): # Update the current player identifier\n\t\tself.Current_Player.config(text=\"Turn: \" + self.controller.Get_Current_Player())\n\n\tdef Update_Game_Type(self): # Update the game type identifier\n\t\tg_type = self.controller.Handler.Get_Game_Type()\n\t\tself.Game_Type.configure(text=\"Rules: \" + g_type)\n\n\tdef Update_Score (self): # Update the score identifier\n\t\tb, w = self.controller.Handler.Get_Score()\n\t\tself.Score.configure(text=\"Black: {0!s} | {1!s} :White\".format(b, w))\n\n\tdef Full_Update(self): # Run a full update on the graphics\n\t\tself.Update_Score()\n\t\tself.Update_Current_Player()\n\t\tself.Update_Board()\n\nclass Postgame (tk.Frame): # The 'end game' screen\n\tFrameName = \"Postgame\"\n\tdef __init__ (self, parent, controller):\n\t\ttk.Frame.__init__(self, parent)\n\n\t\tself.controller = controller\n\t\tself.configure(bg=\"white\")\n\n\t\t# Set a page title\n\t\tself.Title = tk.Label(self, text=\"Game Over!\", bg=\"white\", font=FONTS[\"large\"])\n\t\tself.Title.pack(side=\"top\")\n\n\t\tSeparator(self, orient=\"horizontal\").pack(side=\"top\", fill=\"x\", padx=10)\n\n\t\t# Set the winner text object\n\t\tself.Winner = tk.Label(self, text=\"The winner is black-discs.\", bg=\"white\", font=FONTS[\"medium\"])\n\t\tself.Winner.pack(side=\"top\")\n\n\t\t# Create the replay and exit buttons\n\t\tself.Buttons = tk.Frame(self, bg=\"white\")\n\t\tself.Buttons.pack()\n\n\t\tReplay = tk.Button(self.Buttons, text=\"Replay\", bg=\"#bbbbbb\", font=FONTS[\"medium\"],\n\t\t\tcommand=lambda: self.Replay())\n\t\tReplay.grid(row=0, column=0)\n\n\t\tQuit = tk.Button(self.Buttons, text=\"Quit\", bg=\"#bbbbbb\", font=FONTS[\"medium\"],\n\t\t\tcommand=lambda: self.Quit())\n\t\tQuit.grid(row=0, column=1)\n\n\t\t# the area for the board output\n\t\tself.Board_Area = tk.Frame(self, bg=\"white\")\n\t\tself.Board_Area.pack(side=\"bottom\")\n\n\t\t# Score text\n\t\tself.Score = tk.Label(self.Board_Area, text=\"\", bg=\"white\", font=FONTS[\"medium\"])\n\t\tself.Score.pack()\n\n\t\t# The display for the board\n\t\tself.Board_Display = tk.Frame(self.Board_Area, bg=\"green\")\n\t\tself.Board_Display.pack()\n\n\t\tself.Board = []\n\n\tdef Replay(self): # Initiate the Replay\n\t\tself.controller.Replay()\n\n\tdef Quit(self): # Kill the game\n\t\tself.controller.destroy()\n\t\texit()\n\n\tdef Update_Board (self): # Update the game board display, kill old, create new\n\t\tfor widget in self.Board_Display.winfo_children():\n\t\t\twidget.destroy()\n\n\t\tfor y in range(self.controller.Handler.GameParams[\"y_size\"]):\n\t\t\trow = []\n\t\t\tfor x in range(self.controller.Handler.GameParams[\"x_size\"]):\n\t\t\t\tself.Board_Area.grid_columnconfigure(x, weight=1)\n\t\t\t\tself.Board_Area.grid_rowconfigure(y, weight=1)\n\n\t\t\t\tcol = None\n\t\t\t\tplace_col = self.controller.Handler.Game.Board[y][x]\n\t\t\t\tif place_col == \"B\":\n\t\t\t\t\tcol = \"black\"\n\t\t\t\telif place_col == \"W\":\n\t\t\t\t\tcol = \"white\"\n\n\t\t\t\tdisc = wg.Disc(self.Board_Display, self.controller, col=col, diameter=50)\n\t\t\t\tdisc.grid(row=y, column=x, sticky=\"nsew\")\n\t\t\t\trow.append(disc)\n\n\t\t\tself.Board.append(row)\n\n\tdef Update(self): # Update the whole page\n\t\twinner, scores = self.controller.Handler.Get_Winner() \n\t\tif winner.lower() == \"b\":\n\t\t\twinner = \"black-discs\"\n\t\telif winner.lower() == \"w\":\n\t\t\twinner = \"white-discs\"\n\t\telse:\n\t\t\twinner == \"no one\"\n\t\tself.Winner.configure(text=\"The winner is \" + winner)\n\t\tself.Score.configure(text=\"Black: {0!s} | {1!s}:White\".format(scores[0], scores[1]))\n\t\tself.Update_Board()\n\nif __name__ == \"__main__\":\n\tWindow = Handler()\n", "step-ids": [ 39, 40, 41, 52, 59 ] }
[ 39, 40, 41, 52, 59 ]
<|reserved_special_token_0|> class FunctionPygameCircle(FunctionExample): def __init__(self, data_len, width=500, height=500, dot_size=5): self.angle = 2 * math.pi / data_len self.width = width self.height = height self.dot_size = dot_size <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def reset(self): pygame.display.flip() self.screen.fill([0, 0, 0]) def close(self): pygame.quit() <|reserved_special_token_1|> <|reserved_special_token_0|> class FunctionPygameCircle(FunctionExample): def __init__(self, data_len, width=500, height=500, dot_size=5): self.angle = 2 * math.pi / data_len self.width = width self.height = height self.dot_size = dot_size <|reserved_special_token_0|> def run(self, data): return pygame.draw.circle(self.screen, [150, 0, 150], [int(self. width / 2 - math.cos(self.angle * data) * (self.width / 2 - self.dot_size)), int(self.height / 2 - math.sin(self.angle * data) * (self.height / 2 - self.dot_size))], self.dot_size) def run_no_return(self, data): pygame.draw.circle(self.screen, [150, 0, 150], [int(self.width / 2 - math.cos(self.angle * data) * (self.width / 2 - self.dot_size)), int(self.height / 2 - math.sin(self.angle * data) * (self. height / 2 - self.dot_size))], self.dot_size) def reset(self): pygame.display.flip() self.screen.fill([0, 0, 0]) def close(self): pygame.quit() <|reserved_special_token_1|> <|reserved_special_token_0|> class FunctionPygameCircle(FunctionExample): def __init__(self, data_len, width=500, height=500, dot_size=5): self.angle = 2 * math.pi / data_len self.width = width self.height = height self.dot_size = dot_size def setup(self): pygame.init() self.screen = pygame.display.set_mode([self.width, self.height]) pygame.key.set_repeat(100, 50) self.screen.fill([0, 0, 0]) def run(self, data): return pygame.draw.circle(self.screen, [150, 0, 150], [int(self. width / 2 - math.cos(self.angle * data) * (self.width / 2 - self.dot_size)), int(self.height / 2 - math.sin(self.angle * data) * (self.height / 2 - self.dot_size))], self.dot_size) def run_no_return(self, data): pygame.draw.circle(self.screen, [150, 0, 150], [int(self.width / 2 - math.cos(self.angle * data) * (self.width / 2 - self.dot_size)), int(self.height / 2 - math.sin(self.angle * data) * (self. height / 2 - self.dot_size))], self.dot_size) def reset(self): pygame.display.flip() self.screen.fill([0, 0, 0]) def close(self): pygame.quit() <|reserved_special_token_1|> import math import pygame from TestingFunctions.FunctionExample import FunctionExample class FunctionPygameCircle(FunctionExample): def __init__(self, data_len, width=500, height=500, dot_size=5): self.angle = 2 * math.pi / data_len self.width = width self.height = height self.dot_size = dot_size def setup(self): pygame.init() self.screen = pygame.display.set_mode([self.width, self.height]) pygame.key.set_repeat(100, 50) self.screen.fill([0, 0, 0]) def run(self, data): return pygame.draw.circle(self.screen, [150, 0, 150], [int(self. width / 2 - math.cos(self.angle * data) * (self.width / 2 - self.dot_size)), int(self.height / 2 - math.sin(self.angle * data) * (self.height / 2 - self.dot_size))], self.dot_size) def run_no_return(self, data): pygame.draw.circle(self.screen, [150, 0, 150], [int(self.width / 2 - math.cos(self.angle * data) * (self.width / 2 - self.dot_size)), int(self.height / 2 - math.sin(self.angle * data) * (self. height / 2 - self.dot_size))], self.dot_size) def reset(self): pygame.display.flip() self.screen.fill([0, 0, 0]) def close(self): pygame.quit() <|reserved_special_token_1|> import math import pygame from TestingFunctions.FunctionExample import FunctionExample class FunctionPygameCircle(FunctionExample): def __init__(self, data_len, width=500, height=500, dot_size=5): self.angle = (2 * math.pi) / (data_len) self.width = width self.height = height self.dot_size = dot_size def setup(self): pygame.init() self.screen = pygame.display.set_mode([self.width, self.height]) pygame.key.set_repeat(100, 50) self.screen.fill([0, 0, 0]) def run(self, data): return pygame.draw.circle(self.screen, [150, 0, 150], [int(self.width / 2 - math.cos(self.angle * data) * (self.width / 2 - self.dot_size)), int(self.height / 2 - math.sin(self.angle * data) * ( self.height / 2 - self.dot_size))], self.dot_size) def run_no_return(self, data): pygame.draw.circle(self.screen, [150, 0, 150], [int(self.width / 2 - math.cos(self.angle * data) * (self.width / 2 - self.dot_size)), int(self.height / 2 - math.sin(self.angle * data) * (self.height / 2 - self.dot_size))], self.dot_size) def reset(self): pygame.display.flip() self.screen.fill([0, 0, 0]) def close(self): pygame.quit()
flexible
{ "blob_id": "2faf39f8d12197e20948b2bf4288b7ee406f5b86", "index": 2025, "step-1": "<mask token>\n\n\nclass FunctionPygameCircle(FunctionExample):\n\n def __init__(self, data_len, width=500, height=500, dot_size=5):\n self.angle = 2 * math.pi / data_len\n self.width = width\n self.height = height\n self.dot_size = dot_size\n <mask token>\n <mask token>\n <mask token>\n\n def reset(self):\n pygame.display.flip()\n self.screen.fill([0, 0, 0])\n\n def close(self):\n pygame.quit()\n", "step-2": "<mask token>\n\n\nclass FunctionPygameCircle(FunctionExample):\n\n def __init__(self, data_len, width=500, height=500, dot_size=5):\n self.angle = 2 * math.pi / data_len\n self.width = width\n self.height = height\n self.dot_size = dot_size\n <mask token>\n\n def run(self, data):\n return pygame.draw.circle(self.screen, [150, 0, 150], [int(self.\n width / 2 - math.cos(self.angle * data) * (self.width / 2 -\n self.dot_size)), int(self.height / 2 - math.sin(self.angle *\n data) * (self.height / 2 - self.dot_size))], self.dot_size)\n\n def run_no_return(self, data):\n pygame.draw.circle(self.screen, [150, 0, 150], [int(self.width / 2 -\n math.cos(self.angle * data) * (self.width / 2 - self.dot_size)),\n int(self.height / 2 - math.sin(self.angle * data) * (self.\n height / 2 - self.dot_size))], self.dot_size)\n\n def reset(self):\n pygame.display.flip()\n self.screen.fill([0, 0, 0])\n\n def close(self):\n pygame.quit()\n", "step-3": "<mask token>\n\n\nclass FunctionPygameCircle(FunctionExample):\n\n def __init__(self, data_len, width=500, height=500, dot_size=5):\n self.angle = 2 * math.pi / data_len\n self.width = width\n self.height = height\n self.dot_size = dot_size\n\n def setup(self):\n pygame.init()\n self.screen = pygame.display.set_mode([self.width, self.height])\n pygame.key.set_repeat(100, 50)\n self.screen.fill([0, 0, 0])\n\n def run(self, data):\n return pygame.draw.circle(self.screen, [150, 0, 150], [int(self.\n width / 2 - math.cos(self.angle * data) * (self.width / 2 -\n self.dot_size)), int(self.height / 2 - math.sin(self.angle *\n data) * (self.height / 2 - self.dot_size))], self.dot_size)\n\n def run_no_return(self, data):\n pygame.draw.circle(self.screen, [150, 0, 150], [int(self.width / 2 -\n math.cos(self.angle * data) * (self.width / 2 - self.dot_size)),\n int(self.height / 2 - math.sin(self.angle * data) * (self.\n height / 2 - self.dot_size))], self.dot_size)\n\n def reset(self):\n pygame.display.flip()\n self.screen.fill([0, 0, 0])\n\n def close(self):\n pygame.quit()\n", "step-4": "import math\nimport pygame\nfrom TestingFunctions.FunctionExample import FunctionExample\n\n\nclass FunctionPygameCircle(FunctionExample):\n\n def __init__(self, data_len, width=500, height=500, dot_size=5):\n self.angle = 2 * math.pi / data_len\n self.width = width\n self.height = height\n self.dot_size = dot_size\n\n def setup(self):\n pygame.init()\n self.screen = pygame.display.set_mode([self.width, self.height])\n pygame.key.set_repeat(100, 50)\n self.screen.fill([0, 0, 0])\n\n def run(self, data):\n return pygame.draw.circle(self.screen, [150, 0, 150], [int(self.\n width / 2 - math.cos(self.angle * data) * (self.width / 2 -\n self.dot_size)), int(self.height / 2 - math.sin(self.angle *\n data) * (self.height / 2 - self.dot_size))], self.dot_size)\n\n def run_no_return(self, data):\n pygame.draw.circle(self.screen, [150, 0, 150], [int(self.width / 2 -\n math.cos(self.angle * data) * (self.width / 2 - self.dot_size)),\n int(self.height / 2 - math.sin(self.angle * data) * (self.\n height / 2 - self.dot_size))], self.dot_size)\n\n def reset(self):\n pygame.display.flip()\n self.screen.fill([0, 0, 0])\n\n def close(self):\n pygame.quit()\n", "step-5": "import math\nimport pygame\n\nfrom TestingFunctions.FunctionExample import FunctionExample\n\n\nclass FunctionPygameCircle(FunctionExample):\n def __init__(self, data_len, width=500, height=500, dot_size=5):\n self.angle = (2 * math.pi) / (data_len)\n self.width = width\n self.height = height\n self.dot_size = dot_size\n\n def setup(self):\n pygame.init()\n self.screen = pygame.display.set_mode([self.width, self.height])\n pygame.key.set_repeat(100, 50)\n self.screen.fill([0, 0, 0])\n\n def run(self, data):\n return pygame.draw.circle(self.screen, [150, 0, 150],\n [int(self.width / 2 - math.cos(self.angle * data) * (self.width / 2 - self.dot_size)),\n int(self.height / 2 - math.sin(self.angle * data) * (\n self.height / 2 - self.dot_size))],\n self.dot_size)\n\n def run_no_return(self, data):\n pygame.draw.circle(self.screen, [150, 0, 150],\n [int(self.width / 2 - math.cos(self.angle * data) * (self.width / 2 - self.dot_size)),\n int(self.height / 2 - math.sin(self.angle * data) * (self.height / 2 - self.dot_size))],\n self.dot_size)\n\n def reset(self):\n pygame.display.flip()\n self.screen.fill([0, 0, 0])\n\n def close(self):\n pygame.quit()\n", "step-ids": [ 4, 6, 7, 8, 9 ] }
[ 4, 6, 7, 8, 9 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def chang_name(name): global school school = 'Mage Linux' print('Before change:', name, school) name = 'Stack Cong' age = 33 print('After change:', name) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def chang_name(name): global school school = 'Mage Linux' print('Before change:', name, school) name = 'Stack Cong' age = 33 print('After change:', name) print('School:', school) <|reserved_special_token_0|> chang_name(name) print(name) <|reserved_special_token_1|> school = 'Old boy' def chang_name(name): global school school = 'Mage Linux' print('Before change:', name, school) name = 'Stack Cong' age = 33 print('After change:', name) print('School:', school) name = 'Stack' chang_name(name) print(name) <|reserved_special_token_1|> #!/usr/bin/env python # -*- coding:utf-8 -*- school = "Old boy" def chang_name(name): global school #声明全局变量 school = "Mage Linux" print("Before change:", name, school) name = 'Stack Cong' age = 33 print("After change:", name) print("School:", school) name = "Stack" chang_name(name) print(name)
flexible
{ "blob_id": "a9531fb020428e573d189c377652692e301ea4d3", "index": 3026, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef chang_name(name):\n global school\n school = 'Mage Linux'\n print('Before change:', name, school)\n name = 'Stack Cong'\n age = 33\n print('After change:', name)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef chang_name(name):\n global school\n school = 'Mage Linux'\n print('Before change:', name, school)\n name = 'Stack Cong'\n age = 33\n print('After change:', name)\n\n\nprint('School:', school)\n<mask token>\nchang_name(name)\nprint(name)\n", "step-4": "school = 'Old boy'\n\n\ndef chang_name(name):\n global school\n school = 'Mage Linux'\n print('Before change:', name, school)\n name = 'Stack Cong'\n age = 33\n print('After change:', name)\n\n\nprint('School:', school)\nname = 'Stack'\nchang_name(name)\nprint(name)\n", "step-5": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nschool = \"Old boy\"\n\ndef chang_name(name):\n global school #声明全局变量\n school = \"Mage Linux\"\n print(\"Before change:\", name, school)\n name = 'Stack Cong'\n age = 33\n print(\"After change:\", name)\n\nprint(\"School:\", school)\nname = \"Stack\"\nchang_name(name)\nprint(name)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> with open(os.path.join(os.path.dirname(__file__), 'storage/robot_list.csv'), 'w') as file: writer = csv.writer(file, delimiter=',') headers = [cell.value for cell in sheet.row(0)] writer.writerow(headers) for i in range(1, sheet.nrows): rowvalue_list = [(str(cell.value).strip() if cell.value else None) for cell in sheet.row(i)] writer.writerow(rowvalue_list) <|reserved_special_token_1|> <|reserved_special_token_0|> xlsfile = glob.glob(os.path.join(os.path.dirname(__file__), 'storage/robot*.xls'))[0] wb = open_workbook(xlsfile) sheet = wb.sheet_by_name('robot_list') with open(os.path.join(os.path.dirname(__file__), 'storage/robot_list.csv'), 'w') as file: writer = csv.writer(file, delimiter=',') headers = [cell.value for cell in sheet.row(0)] writer.writerow(headers) for i in range(1, sheet.nrows): rowvalue_list = [(str(cell.value).strip() if cell.value else None) for cell in sheet.row(i)] writer.writerow(rowvalue_list) <|reserved_special_token_1|> import requests, shutil, os, glob from zipfile import ZipFile import pandas as pd from xlrd import open_workbook import csv xlsfile = glob.glob(os.path.join(os.path.dirname(__file__), 'storage/robot*.xls'))[0] wb = open_workbook(xlsfile) sheet = wb.sheet_by_name('robot_list') with open(os.path.join(os.path.dirname(__file__), 'storage/robot_list.csv'), 'w') as file: writer = csv.writer(file, delimiter=',') headers = [cell.value for cell in sheet.row(0)] writer.writerow(headers) for i in range(1, sheet.nrows): rowvalue_list = [(str(cell.value).strip() if cell.value else None) for cell in sheet.row(i)] writer.writerow(rowvalue_list) <|reserved_special_token_1|> import requests, shutil, os, glob from zipfile import ZipFile import pandas as pd from xlrd import open_workbook import csv # zipfilename = 'desiya_hotels' # try: # # downloading zip file # r = requests.get('http://staticstore.travelguru.com/testdump/1300001176/Excel.zip', auth=('testdump', 'testdump'), verify=False,stream=True) #Note web_link is https:// # r.raw.decode_content = True # with open(os.path.join(os.path.dirname(__file__), 'storage/{}.zip'.format(zipfilename)), 'wb') as f: # shutil.copyfileobj(r.raw, f) # # #extracting zip file as xls file # with ZipFile(glob.glob(os.path.join(os.path.dirname(__file__), 'storage/desiya*.zip'))[0], 'r') as zip: # zip.extractall(os.path.join(os.path.dirname(__file__), 'storage/')) # #Rename xls file name as "desiya_hotels" # if glob.glob(os.path.join(os.path.dirname(__file__), 'storage/*[0-9].xls')): # for filename in glob.glob(os.path.join(os.path.dirname(__file__), 'storage/*[a-zA-z].xls')): # os.remove(filename) # os.rename(glob.glob(os.path.join(os.path.dirname(__file__), 'storage/*[0-9].xls'))[0], os.path.join(os.path.dirname(__file__),'storage/{}.xls'.format(zipfilename))) # else: # print('unzipped xls file is not found in storare folder') # except Exception as e: # print("Error while downloading zip file") #read xls file # xls = pd.ExcelFile(glob.glob(os.path.join(os.path.dirname(__file__), 'storage/desiya*.xls'))[0]) # df = pd.read_excel(xls, sheet_name=0, index_col=None) # print(df['Name']) # print(df.head(5)) # for index, row in df.iterrows(): # print(index, row[3]) #convert xls to csvc # df.to_csv(os.path.join(os.path.dirname(__file__),'storage/{}'.format('robot.csv')), encoding='utf-8', index=False) #convert xls file to csv using xlrd module xlsfile = glob.glob(os.path.join(os.path.dirname(__file__), 'storage/robot*.xls'))[0] wb = open_workbook(xlsfile) sheet = wb.sheet_by_name('robot_list') with open(os.path.join(os.path.dirname(__file__), 'storage/robot_list.csv'), "w") as file: writer = csv.writer(file, delimiter=",") headers = [cell.value for cell in sheet.row(0)] writer.writerow(headers) for i in range(1, sheet.nrows): rowvalue_list = [str(cell.value).strip() if cell.value else None for cell in sheet.row(i)] writer.writerow(rowvalue_list)
flexible
{ "blob_id": "1ef9df43725196904ec6c0c881f4a1204174b176", "index": 375, "step-1": "<mask token>\n", "step-2": "<mask token>\nwith open(os.path.join(os.path.dirname(__file__), 'storage/robot_list.csv'),\n 'w') as file:\n writer = csv.writer(file, delimiter=',')\n headers = [cell.value for cell in sheet.row(0)]\n writer.writerow(headers)\n for i in range(1, sheet.nrows):\n rowvalue_list = [(str(cell.value).strip() if cell.value else None) for\n cell in sheet.row(i)]\n writer.writerow(rowvalue_list)\n", "step-3": "<mask token>\nxlsfile = glob.glob(os.path.join(os.path.dirname(__file__),\n 'storage/robot*.xls'))[0]\nwb = open_workbook(xlsfile)\nsheet = wb.sheet_by_name('robot_list')\nwith open(os.path.join(os.path.dirname(__file__), 'storage/robot_list.csv'),\n 'w') as file:\n writer = csv.writer(file, delimiter=',')\n headers = [cell.value for cell in sheet.row(0)]\n writer.writerow(headers)\n for i in range(1, sheet.nrows):\n rowvalue_list = [(str(cell.value).strip() if cell.value else None) for\n cell in sheet.row(i)]\n writer.writerow(rowvalue_list)\n", "step-4": "import requests, shutil, os, glob\nfrom zipfile import ZipFile\nimport pandas as pd\nfrom xlrd import open_workbook\nimport csv\nxlsfile = glob.glob(os.path.join(os.path.dirname(__file__),\n 'storage/robot*.xls'))[0]\nwb = open_workbook(xlsfile)\nsheet = wb.sheet_by_name('robot_list')\nwith open(os.path.join(os.path.dirname(__file__), 'storage/robot_list.csv'),\n 'w') as file:\n writer = csv.writer(file, delimiter=',')\n headers = [cell.value for cell in sheet.row(0)]\n writer.writerow(headers)\n for i in range(1, sheet.nrows):\n rowvalue_list = [(str(cell.value).strip() if cell.value else None) for\n cell in sheet.row(i)]\n writer.writerow(rowvalue_list)\n", "step-5": "\n\nimport requests, shutil, os, glob\nfrom zipfile import ZipFile\nimport pandas as pd\nfrom xlrd import open_workbook\nimport csv\n\n# zipfilename = 'desiya_hotels'\n# try:\n# # downloading zip file\n# r = requests.get('http://staticstore.travelguru.com/testdump/1300001176/Excel.zip', auth=('testdump', 'testdump'), verify=False,stream=True) #Note web_link is https://\n# r.raw.decode_content = True\n# with open(os.path.join(os.path.dirname(__file__), 'storage/{}.zip'.format(zipfilename)), 'wb') as f:\n# shutil.copyfileobj(r.raw, f)\n#\n# #extracting zip file as xls file\n# with ZipFile(glob.glob(os.path.join(os.path.dirname(__file__), 'storage/desiya*.zip'))[0], 'r') as zip:\n# zip.extractall(os.path.join(os.path.dirname(__file__), 'storage/'))\n# #Rename xls file name as \"desiya_hotels\"\n# if glob.glob(os.path.join(os.path.dirname(__file__), 'storage/*[0-9].xls')):\n# for filename in glob.glob(os.path.join(os.path.dirname(__file__), 'storage/*[a-zA-z].xls')):\n# os.remove(filename)\n# os.rename(glob.glob(os.path.join(os.path.dirname(__file__), 'storage/*[0-9].xls'))[0], os.path.join(os.path.dirname(__file__),'storage/{}.xls'.format(zipfilename)))\n# else:\n# print('unzipped xls file is not found in storare folder')\n# except Exception as e:\n# print(\"Error while downloading zip file\")\n\n#read xls file\n# xls = pd.ExcelFile(glob.glob(os.path.join(os.path.dirname(__file__), 'storage/desiya*.xls'))[0])\n# df = pd.read_excel(xls, sheet_name=0, index_col=None)\n# print(df['Name'])\n# print(df.head(5))\n# for index, row in df.iterrows():\n# print(index, row[3])\n\n#convert xls to csvc\n# df.to_csv(os.path.join(os.path.dirname(__file__),'storage/{}'.format('robot.csv')), encoding='utf-8', index=False)\n\n\n#convert xls file to csv using xlrd module\nxlsfile = glob.glob(os.path.join(os.path.dirname(__file__), 'storage/robot*.xls'))[0]\nwb = open_workbook(xlsfile)\nsheet = wb.sheet_by_name('robot_list')\nwith open(os.path.join(os.path.dirname(__file__), 'storage/robot_list.csv'), \"w\") as file:\n writer = csv.writer(file, delimiter=\",\")\n headers = [cell.value for cell in sheet.row(0)]\n writer.writerow(headers)\n for i in range(1, sheet.nrows):\n rowvalue_list = [str(cell.value).strip() if cell.value else None for cell in sheet.row(i)]\n writer.writerow(rowvalue_list)\n\n\n\n\n\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
#-*- coding: utf8 -*- #credits to https://github.com/pytorch/examples/blob/master/imagenet/main.py import shutil, time, logging import torch import torch.optim import numpy as np import visdom, copy from datetime import datetime from collections import defaultdict from generic_models.yellowfin import YFOptimizer logger = logging.getLogger('app') logger.setLevel(logging.DEBUG) class VisdomMonitor(object): def __init__(self, prefix=None, server='http://localhost', port=8097): self.__prefix = prefix or datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S') self.__vis = visdom.Visdom(server=server, port=port) self.__metrics = defaultdict(lambda :defaultdict(list)) self.__win_dict = {} self.__opts = self._init_opts() def _init_opts(self): opts = dict(legend=['Train', 'Validate']) return opts def __add(self, name, value, type): self.__metrics[type][name].append(value) def _add_val_performance(self, name, value): self.__add(name, value, type='val') def _add_train_performance(self, name, value): self.__add(name, value, type='train') def add_performance(self, metric_name, train_value, val_value): self._add_train_performance(metric_name, train_value ) self._add_val_performance(metric_name, val_value) self.plot(metric_name) def plot(self, metric_name): current_win = self.__win_dict.get(metric_name, None) train_values = self.__metrics['train'][metric_name] val_values = self.__metrics['val'][metric_name] epochs = max(len(train_values), len(val_values)) values_for_plot = np.column_stack((np.array(train_values), np.array(val_values))) opts = copy.deepcopy(self.__opts) opts.update(dict(title='%s\ntrain/val %s' % (self.__prefix, metric_name))) win = self.__vis.line(Y=values_for_plot, X=np.arange(epochs), opts=opts, win=current_win) if current_win is None: self.__win_dict[metric_name] = win class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def adjust_learning_rate_by_schedule(config, optimizer, epoch, decrease_rate=0.1): """Sets the learning rate to the initial LR decayed by 1/decrease_rate every 10 epochs""" if not isinstance(optimizer, torch.optim.SGD): return #lr = config.lr * (0.1 ** (epoch // 10)) if epoch and epoch % 10 == 0: for i, param_group in enumerate(optimizer.param_groups): param_group['lr'] *= decrease_rate logger.info('Setting learning layer=i, rate=%.6f', i, param_group['lr']) class PlateauScheduler(object): """Sets the lr to the initial LR decayed by 1/decrease_rate, when not improving for max_stops epochs""" def __init__(self, optimizer, patience, early_stop_n, decrease_rate=0.1, eps=1e-5, warm_up_epochs=None, best_score=None): self.optimizer = optimizer if not isinstance(optimizer, (torch.optim.SGD, YFOptimizer)): raise TypeError self.patience = patience self.early_stop_n = early_stop_n self.decrease_rate = decrease_rate self.eps = eps self.warm_up_epochs = warm_up_epochs self.__lr_changed = 0 self.__early_stop_counter = 0 self.__best_score = best_score self.__descrease_times = 0 self.__warm_up = self.__has_warm_up(optimizer) def __has_warm_up(self, optimizer): for param_group in self.optimizer.param_groups: if param_group['lr'] != param_group['after_warmup_lr']: logger.info('Optimizer has warm-up stage') return True def step(self, epoch, score): adjusted, to_break = False, False prev_best_score = self.__best_score or -1 is_best = self.__best_score is None or score < self.__best_score - self.eps self.__best_score = self.__best_score is not None and min(score, self.__best_score) or score if is_best: logger.info('Current model is best by val score %.5f < %.5f' % (self.__best_score, prev_best_score)) self.__early_stop_counter = 0 else: self.__early_stop_counter += 1 if self.__early_stop_counter >= self.early_stop_n: logger.info('Early stopping, regress for %d iterations', self.__early_stop_counter) to_break = True logger.info('early_stop_counter: %d', self.__early_stop_counter) if (self.warm_up_epochs and self.__descrease_times == 0 and self.__warm_up and epoch >= self.warm_up_epochs - 1 ) or \ (self.__lr_changed <= epoch - self.patience and \ (self.__early_stop_counter is not None and self.patience and self.__early_stop_counter >= self.patience)): self.__lr_changed = epoch for param_group in self.optimizer.param_groups: if self.__descrease_times == 0 and self.__warm_up: param_group['lr'] = param_group['after_warmup_lr'] else: param_group['lr'] = param_group['lr'] * self.decrease_rate logger.info('Setting for group learning rate=%.8f, epoch=%d', param_group['lr'], self.__lr_changed) adjusted = True self.__descrease_times += 1 return adjusted, to_break, is_best def init_optimizer(model, config, exact_layers=None): """param 'exact_layers' specifies which parameters of the model to train, None - all, else - list of layers with a multiplier (optional) for LR schedule""" opt_type = config.optimizer if exact_layers: logger.info('Learning exact layers, number=%d', len(exact_layers)) parameters = [] for i, layer in enumerate(exact_layers): if isinstance(layer, tuple) and len(layer) == 2: layer, multiplier = layer init_multiplier = 1 elif isinstance(layer, tuple) and len(layer) == 3: layer, init_multiplier, multiplier = layer else: multiplier = 1 init_multiplier = 1 lr = config.lr * multiplier init_lr = config.lr * multiplier * init_multiplier logger.info('Layer=%d, lr=%.5f', i, init_lr) parameters.append({'params': layer.parameters(), 'lr': init_lr, 'after_warmup_lr': lr}) else: logger.info('Optimizing all parameters, lr=%.5f', config.lr) parameters = model.parameters() if opt_type == 'sgd': optimizer = torch.optim.SGD(parameters, config.lr, momentum=config.momentum, weight_decay=config.weight_decay) elif opt_type == 'adam': optimizer = torch.optim.Adam(parameters, lr=config.lr, weight_decay=config.weight_decay) elif opt_type == 'yf': optimizer = YFOptimizer(parameters, config.lr, mu=config.momentum, weight_decay=config.weight_decay, clip_thresh=0.1) else: raise TypeError, 'Unknown optimizer type=%s' % (opt_type, ) return optimizer def save_checkpoint(state, epoch, is_best, filename, best_filename): torch.save(state, filename) if is_best: shutil.copyfile(filename, best_filename) shutil.copyfile(filename, best_filename + '-%d' % epoch) def load_checkpoint(filename): checkpoint = torch.load(filename) return checkpoint def train(train_loader, model, criterion, optimizer, epoch, is_multi_fc=False): batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() predictions = AverageMeter() # switch to train mode model.train() end = time.time() for i, (input, target) in enumerate(train_loader): # measure data loading time data_time.update(time.time() - end) target = target.cuda(async=True) input_var = torch.autograd.Variable(input) target_var = torch.autograd.Variable(target) # compute output if is_multi_fc==False: # this is original loss function output = model(input_var) loss = criterion(output, target_var) else: # this is for inception_v3 with 2 output channels # https://github.com/pytorch/vision/issues/302 output, output_aux = model(input_var) loss = criterion(output, target_var) loss+= criterion(output_aux, target_var) # measure accuracy and record loss losses.update(loss.data[0], input.size(0)) # compute gradient and do SGD step optimizer.zero_grad() loss.backward() optimizer.step() # measure elapsed time batch_time.update(time.time() - end) end = time.time() if (i and i % 50 == 0) or i == len(train_loader) - 1: logger.info('Epoch: [{0}][{1}/{2}]\t' 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 'Data {data_time.val:.3f} ({data_time.avg:.3f})\t' 'Accuracy {acc.val:.4f} ({acc.avg:.4f})\t' 'Loss {loss.val:.4f} ({loss.avg:.4f})\t'.format( epoch, i, len(train_loader), batch_time=batch_time, data_time=data_time, loss=losses, acc=predictions)) return losses.avg def compute_f2(output, target): true_and_pred = target * output ttp_sum = torch.sum(true_and_pred, 1) tpred_sum = torch.sum(output, 1) ttrue_sum = torch.sum(target, 1) tprecision = ttp_sum / tpred_sum trecall = ttp_sum / ttrue_sum f2 = ((1 + 4) * tprecision * trecall) / (4 * tprecision + trecall) return f2 def validate(val_loader, model, criterion, activation=torch.sigmoid): logger.info('Validating model') batch_time = AverageMeter() losses = AverageMeter() f2s = AverageMeter() # switch to evaluate mode model.eval() end = time.time() for i, (input, target) in enumerate(val_loader): target = target.cuda(async=True) input_var = torch.autograd.Variable(input, volatile=True) target_var = torch.autograd.Variable(target, volatile=True) # compute output output = model(input_var) loss = criterion(output, target_var) # compute f2 f2 = compute_f2(activation(output), target_var).mean() f2s.update(f2.data[0], input.size(0)) # measure accuracy and record loss losses.update(loss.data[0], input.size(0)) # measure elapsed time batch_time.update(time.time() - end) end = time.time() logger.info('Test: [{0}/{0}]\t' 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 'Loss {loss.avg:.5f}\t' 'F2: {f2s.avg}\t'.format( len(val_loader), batch_time=batch_time, loss=losses, f2s=f2s)) return losses.avg def get_outputs(loader, model, activation): model.eval() outputs, targets = [], [] for i, (input, target) in enumerate(loader): input_var = torch.autograd.Variable(input, volatile=True) output = model(input_var) if activation is not None: output = activation(output) outputs.extend(output.cpu().data) targets.extend(target) return outputs, targets def test_model(test_loader, model, activation=None): logger.info('Testing') model.eval() names, results = [], [] for i, (input, name_batch) in enumerate(test_loader): input_var = torch.autograd.Variable(input, volatile=True) output = model(input_var) if activation is not None: output = activation(output) names.extend(name_batch) results.extend(output.cpu()) if i and i % 20 == 0: logger.info('Batch %d',i) return names, results
normal
{ "blob_id": "be90dcb4bbb69053e9451479990e030cd4841e4a", "index": 1620, "step-1": "#-*- coding: utf8 -*-\n#credits to https://github.com/pytorch/examples/blob/master/imagenet/main.py\nimport shutil, time, logging\nimport torch\nimport torch.optim\nimport numpy as np\nimport visdom, copy\nfrom datetime import datetime\nfrom collections import defaultdict\nfrom generic_models.yellowfin import YFOptimizer\n\n\nlogger = logging.getLogger('app')\nlogger.setLevel(logging.DEBUG)\n\n\nclass VisdomMonitor(object):\n def __init__(self, prefix=None, server='http://localhost', port=8097):\n self.__prefix = prefix or datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')\n self.__vis = visdom.Visdom(server=server, port=port)\n self.__metrics = defaultdict(lambda :defaultdict(list))\n self.__win_dict = {}\n self.__opts = self._init_opts()\n\n def _init_opts(self):\n opts = dict(legend=['Train', 'Validate'])\n return opts\n\n def __add(self, name, value, type):\n self.__metrics[type][name].append(value)\n\n def _add_val_performance(self, name, value):\n self.__add(name, value, type='val')\n\n def _add_train_performance(self, name, value):\n self.__add(name, value, type='train')\n\n def add_performance(self, metric_name, train_value, val_value):\n self._add_train_performance(metric_name, train_value )\n self._add_val_performance(metric_name, val_value)\n self.plot(metric_name)\n\n def plot(self, metric_name):\n current_win = self.__win_dict.get(metric_name, None)\n train_values = self.__metrics['train'][metric_name]\n val_values = self.__metrics['val'][metric_name]\n epochs = max(len(train_values), len(val_values))\n values_for_plot = np.column_stack((np.array(train_values), np.array(val_values)))\n opts = copy.deepcopy(self.__opts)\n opts.update(dict(title='%s\\ntrain/val %s' % (self.__prefix, metric_name)))\n win = self.__vis.line(Y=values_for_plot, X=np.arange(epochs), opts=opts, win=current_win)\n\n if current_win is None:\n self.__win_dict[metric_name] = win\n\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n\ndef adjust_learning_rate_by_schedule(config, optimizer, epoch, decrease_rate=0.1):\n \"\"\"Sets the learning rate to the initial LR decayed by 1/decrease_rate every 10 epochs\"\"\"\n if not isinstance(optimizer, torch.optim.SGD):\n return\n #lr = config.lr * (0.1 ** (epoch // 10))\n if epoch and epoch % 10 == 0:\n for i, param_group in enumerate(optimizer.param_groups):\n param_group['lr'] *= decrease_rate\n logger.info('Setting learning layer=i, rate=%.6f', i, param_group['lr'])\n\n\nclass PlateauScheduler(object):\n \"\"\"Sets the lr to the initial LR decayed by 1/decrease_rate, when not improving for max_stops epochs\"\"\"\n def __init__(self, optimizer, patience, early_stop_n, decrease_rate=0.1, eps=1e-5,\n warm_up_epochs=None, best_score=None):\n self.optimizer = optimizer\n if not isinstance(optimizer, (torch.optim.SGD, YFOptimizer)):\n raise TypeError\n self.patience = patience\n self.early_stop_n = early_stop_n\n self.decrease_rate = decrease_rate\n self.eps = eps\n self.warm_up_epochs = warm_up_epochs\n self.__lr_changed = 0\n self.__early_stop_counter = 0\n self.__best_score = best_score\n self.__descrease_times = 0\n self.__warm_up = self.__has_warm_up(optimizer)\n\n def __has_warm_up(self, optimizer):\n for param_group in self.optimizer.param_groups:\n if param_group['lr'] != param_group['after_warmup_lr']:\n logger.info('Optimizer has warm-up stage')\n return True\n\n def step(self, epoch, score):\n adjusted, to_break = False, False\n\n prev_best_score = self.__best_score or -1\n is_best = self.__best_score is None or score < self.__best_score - self.eps\n self.__best_score = self.__best_score is not None and min(score, self.__best_score) or score\n if is_best:\n logger.info('Current model is best by val score %.5f < %.5f' % (self.__best_score, prev_best_score))\n self.__early_stop_counter = 0\n else:\n self.__early_stop_counter += 1\n if self.__early_stop_counter >= self.early_stop_n:\n logger.info('Early stopping, regress for %d iterations', self.__early_stop_counter)\n to_break = True\n logger.info('early_stop_counter: %d', self.__early_stop_counter)\n\n if (self.warm_up_epochs and self.__descrease_times == 0 and self.__warm_up and epoch >= self.warm_up_epochs - 1 ) or \\\n (self.__lr_changed <= epoch - self.patience and \\\n (self.__early_stop_counter is not None and self.patience and self.__early_stop_counter >= self.patience)):\n self.__lr_changed = epoch\n for param_group in self.optimizer.param_groups:\n if self.__descrease_times == 0 and self.__warm_up:\n param_group['lr'] = param_group['after_warmup_lr']\n else:\n param_group['lr'] = param_group['lr'] * self.decrease_rate\n logger.info('Setting for group learning rate=%.8f, epoch=%d', param_group['lr'], self.__lr_changed)\n adjusted = True\n self.__descrease_times += 1\n\n return adjusted, to_break, is_best\n\n\ndef init_optimizer(model, config, exact_layers=None):\n \"\"\"param 'exact_layers' specifies which parameters of the model to train, None - all,\n else - list of layers with a multiplier (optional) for LR schedule\"\"\"\n opt_type = config.optimizer\n if exact_layers:\n logger.info('Learning exact layers, number=%d', len(exact_layers))\n parameters = []\n for i, layer in enumerate(exact_layers):\n if isinstance(layer, tuple) and len(layer) == 2:\n layer, multiplier = layer\n init_multiplier = 1\n elif isinstance(layer, tuple) and len(layer) == 3:\n layer, init_multiplier, multiplier = layer\n else:\n multiplier = 1\n init_multiplier = 1\n lr = config.lr * multiplier\n init_lr = config.lr * multiplier * init_multiplier\n logger.info('Layer=%d, lr=%.5f', i, init_lr)\n parameters.append({'params': layer.parameters(), 'lr': init_lr, 'after_warmup_lr': lr})\n else:\n logger.info('Optimizing all parameters, lr=%.5f', config.lr)\n parameters = model.parameters()\n\n if opt_type == 'sgd':\n optimizer = torch.optim.SGD(parameters, config.lr, momentum=config.momentum, weight_decay=config.weight_decay)\n elif opt_type == 'adam':\n optimizer = torch.optim.Adam(parameters, lr=config.lr, weight_decay=config.weight_decay)\n elif opt_type == 'yf':\n optimizer = YFOptimizer(parameters, config.lr, mu=config.momentum, weight_decay=config.weight_decay,\n clip_thresh=0.1)\n else:\n raise TypeError, 'Unknown optimizer type=%s' % (opt_type, )\n return optimizer\n\n\ndef save_checkpoint(state, epoch, is_best, filename, best_filename):\n torch.save(state, filename)\n if is_best:\n shutil.copyfile(filename, best_filename)\n shutil.copyfile(filename, best_filename + '-%d' % epoch)\n\n\ndef load_checkpoint(filename):\n checkpoint = torch.load(filename)\n return checkpoint\n\n\ndef train(train_loader, model, criterion, optimizer, epoch, is_multi_fc=False):\n batch_time = AverageMeter()\n data_time = AverageMeter()\n losses = AverageMeter()\n predictions = AverageMeter()\n\n # switch to train mode\n model.train()\n\n end = time.time()\n for i, (input, target) in enumerate(train_loader):\n # measure data loading time\n data_time.update(time.time() - end)\n target = target.cuda(async=True)\n input_var = torch.autograd.Variable(input)\n target_var = torch.autograd.Variable(target)\n # compute output\n if is_multi_fc==False:\n # this is original loss function\n output = model(input_var)\n loss = criterion(output, target_var)\n else:\n # this is for inception_v3 with 2 output channels\n # https://github.com/pytorch/vision/issues/302\n output, output_aux = model(input_var)\n loss = criterion(output, target_var)\n loss+= criterion(output_aux, target_var)\n \n # measure accuracy and record loss\n losses.update(loss.data[0], input.size(0))\n\n # compute gradient and do SGD step\n optimizer.zero_grad()\n\n loss.backward()\n optimizer.step()\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n if (i and i % 50 == 0) or i == len(train_loader) - 1:\n logger.info('Epoch: [{0}][{1}/{2}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Data {data_time.val:.3f} ({data_time.avg:.3f})\\t'\n 'Accuracy {acc.val:.4f} ({acc.avg:.4f})\\t'\n 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'.format(\n epoch, i, len(train_loader), batch_time=batch_time,\n data_time=data_time, loss=losses, acc=predictions))\n\n return losses.avg\n\n\ndef compute_f2(output, target):\n true_and_pred = target * output\n\n ttp_sum = torch.sum(true_and_pred, 1)\n tpred_sum = torch.sum(output, 1)\n ttrue_sum = torch.sum(target, 1)\n\n tprecision = ttp_sum / tpred_sum\n trecall = ttp_sum / ttrue_sum\n f2 = ((1 + 4) * tprecision * trecall) / (4 * tprecision + trecall)\n\n return f2\n\n\ndef validate(val_loader, model, criterion, activation=torch.sigmoid):\n logger.info('Validating model')\n batch_time = AverageMeter()\n losses = AverageMeter()\n f2s = AverageMeter()\n\n # switch to evaluate mode\n model.eval()\n\n end = time.time()\n for i, (input, target) in enumerate(val_loader):\n target = target.cuda(async=True)\n input_var = torch.autograd.Variable(input, volatile=True)\n target_var = torch.autograd.Variable(target, volatile=True)\n\n # compute output\n output = model(input_var)\n\n loss = criterion(output, target_var)\n\n # compute f2\n f2 = compute_f2(activation(output), target_var).mean()\n f2s.update(f2.data[0], input.size(0))\n\n # measure accuracy and record loss\n losses.update(loss.data[0], input.size(0))\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n logger.info('Test: [{0}/{0}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Loss {loss.avg:.5f}\\t'\n 'F2: {f2s.avg}\\t'.format(\n len(val_loader), batch_time=batch_time, loss=losses, f2s=f2s))\n\n return losses.avg\n\n\ndef get_outputs(loader, model, activation):\n model.eval()\n outputs, targets = [], []\n for i, (input, target) in enumerate(loader):\n input_var = torch.autograd.Variable(input, volatile=True)\n output = model(input_var)\n if activation is not None:\n output = activation(output)\n outputs.extend(output.cpu().data)\n targets.extend(target)\n return outputs, targets\n\n\ndef test_model(test_loader, model, activation=None):\n logger.info('Testing')\n model.eval()\n\n names, results = [], []\n for i, (input, name_batch) in enumerate(test_loader):\n input_var = torch.autograd.Variable(input, volatile=True)\n\n output = model(input_var)\n if activation is not None:\n output = activation(output)\n\n names.extend(name_batch)\n results.extend(output.cpu())\n if i and i % 20 == 0:\n logger.info('Batch %d',i)\n\n return names, results\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
from selenium import webdriver from selenium.webdriver.chrome.options import Options from webdriver_manager.chrome import ChromeDriverManager import time import csv options = Options() # options.add_argument('--headless') options.add_argument('--disable-gpu') driver = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=options) from selenium.common.exceptions import NoSuchElementException try: driver.get("http://localhost:1667/") #Cookie accept: button_accept = driver.find_element_by_xpath('//*[@id="cookie-policy-panel"]/div/div[2]/button[2]').click() from selenium.webdriver.common.action_chains import ActionChains # Activate Sign in input field login = driver.find_element_by_xpath('//*[@id="app"]/nav/div/ul/li[2]/a') mousehover = driver.find_element_by_xpath('//*[@id="app"]/nav/div/ul/li[2]/a') ActionChains(driver).move_to_element(mousehover).perform() time.sleep(3) actions = ActionChains(driver) actions.click(login) actions.perform() # Fill input fields: def fill_login(mail, pw): email = driver.find_element_by_xpath('//*[@id="app"]//fieldset[1]/input') password = driver.find_element_by_xpath('//*[@id="app"]//fieldset[2]/input') button = driver.find_element_by_xpath('//*[@id="app"]//form/button') email.send_keys(mail) password.send_keys(pw) button.click() username="kiskacsa3" fill_login("[email protected]", "Kiskacsa3$") # Activate Log out: time.sleep(3) logout = driver.find_element_by_xpath('//*[@id="app"]/nav/div/ul/li[5]') mousehover = driver.find_element_by_xpath('//*[@id="app"]/nav/div/ul/li[5]/a') ActionChains(driver).move_to_element(mousehover).perform() time.sleep(3) actions = ActionChains(driver) actions.click(logout) actions.perform() # Checking the disappered username: if logout: def test_element_does_not_exist(self): with self.assertRaises(NoSuchElementException): driver.find_element_by_xpath("log_out") return("User panel disappered.") finally: pass # driver.close()
normal
{ "blob_id": "8c5815c1dd71b2ae887b1c9b1968176dfceea4f9", "index": 6182, "step-1": "from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom webdriver_manager.chrome import ChromeDriverManager\nimport time\nimport csv\n\noptions = Options()\n# options.add_argument('--headless')\noptions.add_argument('--disable-gpu')\ndriver = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=options)\nfrom selenium.common.exceptions import NoSuchElementException\n\ntry:\n driver.get(\"http://localhost:1667/\")\n\n #Cookie accept:\n button_accept = driver.find_element_by_xpath('//*[@id=\"cookie-policy-panel\"]/div/div[2]/button[2]').click()\n from selenium.webdriver.common.action_chains import ActionChains\n\n # Activate Sign in input field\n login = driver.find_element_by_xpath('//*[@id=\"app\"]/nav/div/ul/li[2]/a')\n mousehover = driver.find_element_by_xpath('//*[@id=\"app\"]/nav/div/ul/li[2]/a')\n ActionChains(driver).move_to_element(mousehover).perform()\n time.sleep(3)\n actions = ActionChains(driver)\n actions.click(login)\n actions.perform()\n\n\n # Fill input fields:\n def fill_login(mail, pw):\n email = driver.find_element_by_xpath('//*[@id=\"app\"]//fieldset[1]/input')\n password = driver.find_element_by_xpath('//*[@id=\"app\"]//fieldset[2]/input')\n button = driver.find_element_by_xpath('//*[@id=\"app\"]//form/button')\n\n email.send_keys(mail)\n password.send_keys(pw)\n button.click()\n\n username=\"kiskacsa3\"\n fill_login(\"[email protected]\", \"Kiskacsa3$\")\n\n # Activate Log out:\n time.sleep(3)\n logout = driver.find_element_by_xpath('//*[@id=\"app\"]/nav/div/ul/li[5]')\n mousehover = driver.find_element_by_xpath('//*[@id=\"app\"]/nav/div/ul/li[5]/a')\n ActionChains(driver).move_to_element(mousehover).perform()\n time.sleep(3)\n actions = ActionChains(driver)\n actions.click(logout)\n actions.perform()\n\n # Checking the disappered username:\n if logout:\n\n def test_element_does_not_exist(self):\n with self.assertRaises(NoSuchElementException):\n driver.find_element_by_xpath(\"log_out\")\n return(\"User panel disappered.\")\n\nfinally:\n pass\n # driver.close()", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
import media import fresh_tomatoes toy_story = media.Movie("Toy Story", "A story of a boy and his toys that come to life", '<p><a href="https://en.wikipedia.org/wiki/File:Toy_Story.jpg#/media/File:Toy_Story.jpg"><img src="https://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg" alt="The poster features Woody anxiously holding onto Buzz Lightyear as he flies in Andy\'s room. Below them sitting on the bed are Bo Peep, Mr. Potato Head, Troll, Hamm, Slinky, Sarge and Rex. In the lower right center of the image is the film\'s title. The background shows the cloud wallpaper featured in the bedroom."></a><br>By From <a rel="nofollow" class="external text" href="http://www.impawards.com/1995/toy_story_ver1.html">impawards</a>., <a href="https://en.wikipedia.org/w/index.php?curid=26009601">Link</a></p>', "https://youtu.be/KYz2wyBy3kc") avatar = media.Movie("Avatar", "A marine on an alien planet", '<p><a href="https://en.wikipedia.org/wiki/File:Avatar-Teaser-Poster.jpg#/media/File:Avatar-Teaser-Poster.jpg"><img src="https://upload.wikimedia.org/wikipedia/en/b/b0/Avatar-Teaser-Poster.jpg" alt="Avatar-Teaser-Poster.jpg"></a><br>By Source, <a href="//en.wikipedia.org/wiki/File:Avatar-Teaser-Poster.jpg" title="Fair use of copyrighted material in the context of Avatar (2009 film)">Fair use</a>, <a href="https://en.wikipedia.org/w/index.php?curid=23732044">Link</a></p>', "https://youtu.be/5PSNL1qE6VY") # print(avatar.storyline) # avatar.show_trailer() movies = [toy_story, avatar] fresh_tomatoes.open_movies_page(movies) # print(media.Movie.__doc__) # print(media.Movie.__name__) # print(media.Movie.__module__)
normal
{ "blob_id": "e2f6e6e872f95471ebbc8b25bde08247fe8f7e61", "index": 8829, "step-1": "<mask token>\n", "step-2": "<mask token>\nfresh_tomatoes.open_movies_page(movies)\n", "step-3": "<mask token>\ntoy_story = media.Movie('Toy Story',\n 'A story of a boy and his toys that come to life',\n '<p><a href=\"https://en.wikipedia.org/wiki/File:Toy_Story.jpg#/media/File:Toy_Story.jpg\"><img src=\"https://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg\" alt=\"The poster features Woody anxiously holding onto Buzz Lightyear as he flies in Andy\\'s room. Below them sitting on the bed are Bo Peep, Mr. Potato Head, Troll, Hamm, Slinky, Sarge and Rex. In the lower right center of the image is the film\\'s title. The background shows the cloud wallpaper featured in the bedroom.\"></a><br>By From <a rel=\"nofollow\" class=\"external text\" href=\"http://www.impawards.com/1995/toy_story_ver1.html\">impawards</a>., <a href=\"https://en.wikipedia.org/w/index.php?curid=26009601\">Link</a></p>'\n , 'https://youtu.be/KYz2wyBy3kc')\navatar = media.Movie('Avatar', 'A marine on an alien planet',\n '<p><a href=\"https://en.wikipedia.org/wiki/File:Avatar-Teaser-Poster.jpg#/media/File:Avatar-Teaser-Poster.jpg\"><img src=\"https://upload.wikimedia.org/wikipedia/en/b/b0/Avatar-Teaser-Poster.jpg\" alt=\"Avatar-Teaser-Poster.jpg\"></a><br>By Source, <a href=\"//en.wikipedia.org/wiki/File:Avatar-Teaser-Poster.jpg\" title=\"Fair use of copyrighted material in the context of Avatar (2009 film)\">Fair use</a>, <a href=\"https://en.wikipedia.org/w/index.php?curid=23732044\">Link</a></p>'\n , 'https://youtu.be/5PSNL1qE6VY')\nmovies = [toy_story, avatar]\nfresh_tomatoes.open_movies_page(movies)\n", "step-4": "import media\nimport fresh_tomatoes\ntoy_story = media.Movie('Toy Story',\n 'A story of a boy and his toys that come to life',\n '<p><a href=\"https://en.wikipedia.org/wiki/File:Toy_Story.jpg#/media/File:Toy_Story.jpg\"><img src=\"https://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg\" alt=\"The poster features Woody anxiously holding onto Buzz Lightyear as he flies in Andy\\'s room. Below them sitting on the bed are Bo Peep, Mr. Potato Head, Troll, Hamm, Slinky, Sarge and Rex. In the lower right center of the image is the film\\'s title. The background shows the cloud wallpaper featured in the bedroom.\"></a><br>By From <a rel=\"nofollow\" class=\"external text\" href=\"http://www.impawards.com/1995/toy_story_ver1.html\">impawards</a>., <a href=\"https://en.wikipedia.org/w/index.php?curid=26009601\">Link</a></p>'\n , 'https://youtu.be/KYz2wyBy3kc')\navatar = media.Movie('Avatar', 'A marine on an alien planet',\n '<p><a href=\"https://en.wikipedia.org/wiki/File:Avatar-Teaser-Poster.jpg#/media/File:Avatar-Teaser-Poster.jpg\"><img src=\"https://upload.wikimedia.org/wikipedia/en/b/b0/Avatar-Teaser-Poster.jpg\" alt=\"Avatar-Teaser-Poster.jpg\"></a><br>By Source, <a href=\"//en.wikipedia.org/wiki/File:Avatar-Teaser-Poster.jpg\" title=\"Fair use of copyrighted material in the context of Avatar (2009 film)\">Fair use</a>, <a href=\"https://en.wikipedia.org/w/index.php?curid=23732044\">Link</a></p>'\n , 'https://youtu.be/5PSNL1qE6VY')\nmovies = [toy_story, avatar]\nfresh_tomatoes.open_movies_page(movies)\n", "step-5": "import media\nimport fresh_tomatoes\n\ntoy_story = media.Movie(\"Toy Story\",\n \"A story of a boy and his toys that come to life\",\n '<p><a href=\"https://en.wikipedia.org/wiki/File:Toy_Story.jpg#/media/File:Toy_Story.jpg\"><img src=\"https://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg\" alt=\"The poster features Woody anxiously holding onto Buzz Lightyear as he flies in Andy\\'s room. Below them sitting on the bed are Bo Peep, Mr. Potato Head, Troll, Hamm, Slinky, Sarge and Rex. In the lower right center of the image is the film\\'s title. The background shows the cloud wallpaper featured in the bedroom.\"></a><br>By From <a rel=\"nofollow\" class=\"external text\" href=\"http://www.impawards.com/1995/toy_story_ver1.html\">impawards</a>., <a href=\"https://en.wikipedia.org/w/index.php?curid=26009601\">Link</a></p>',\n \"https://youtu.be/KYz2wyBy3kc\")\n\navatar = media.Movie(\"Avatar\",\n \"A marine on an alien planet\",\n '<p><a href=\"https://en.wikipedia.org/wiki/File:Avatar-Teaser-Poster.jpg#/media/File:Avatar-Teaser-Poster.jpg\"><img src=\"https://upload.wikimedia.org/wikipedia/en/b/b0/Avatar-Teaser-Poster.jpg\" alt=\"Avatar-Teaser-Poster.jpg\"></a><br>By Source, <a href=\"//en.wikipedia.org/wiki/File:Avatar-Teaser-Poster.jpg\" title=\"Fair use of copyrighted material in the context of Avatar (2009 film)\">Fair use</a>, <a href=\"https://en.wikipedia.org/w/index.php?curid=23732044\">Link</a></p>',\n \"https://youtu.be/5PSNL1qE6VY\")\n\n# print(avatar.storyline)\n# avatar.show_trailer()\nmovies = [toy_story, avatar]\nfresh_tomatoes.open_movies_page(movies)\n# print(media.Movie.__doc__)\n# print(media.Movie.__name__)\n# print(media.Movie.__module__)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
from gpiozero import Motor class Car: def __init__(self, speed: float=1): self.speed = speed self.forward_right_motor = Motor(forward=12, backward=16) self.backward_right_motor = Motor(forward=21, backward=20) self.forward_left_motor = Motor(forward=23, backward=18) self.backward_left_motor = Motor(forward=24, backward=25) def stop(self): self.forward_left_motor.stop() self.forward_right_motor.stop() self.backward_left_motor.stop() self.backward_right_motor.stop() def forward(self, speed: float=None): speed = max(min(speed if speed else self.speed, 1), 0) self.forward_left_motor.forward(speed=speed) self.forward_right_motor.forward(speed=speed) self.backward_left_motor.forward(speed=speed) self.backward_right_motor.forward(speed=speed) def backward(self, speed: float=None): speed = max(min(speed if speed else self.speed, 1), 0) self.forward_left_motor.backward(speed=speed) self.forward_right_motor.backward(speed=speed) self.backward_left_motor.backward(speed=speed) self.backward_right_motor.backward(speed=speed) def left(self, speed: float=None): speed = max(min(speed if speed else self.speed, 1), 0) self.forward_left_motor.backward(speed=speed) self.forward_right_motor.forward(speed=speed) self.backward_left_motor.backward(speed=speed) self.backward_right_motor.forward(speed=speed) def right(self, speed: float=None): speed = max(min(speed if speed else self.speed, 1), 0) self.forward_left_motor.forward(speed=speed) self.forward_right_motor.backward(speed=speed) self.backward_left_motor.forward(speed=speed) self.backward_right_motor.backward(speed=speed)
normal
{ "blob_id": "6bf1a0fbf65895eac9baa71bc5e04e861f0a3ed5", "index": 4190, "step-1": "<mask token>\n\n\nclass Car:\n\n def __init__(self, speed: float=1):\n self.speed = speed\n self.forward_right_motor = Motor(forward=12, backward=16)\n self.backward_right_motor = Motor(forward=21, backward=20)\n self.forward_left_motor = Motor(forward=23, backward=18)\n self.backward_left_motor = Motor(forward=24, backward=25)\n\n def stop(self):\n self.forward_left_motor.stop()\n self.forward_right_motor.stop()\n self.backward_left_motor.stop()\n self.backward_right_motor.stop()\n <mask token>\n <mask token>\n\n def left(self, speed: float=None):\n speed = max(min(speed if speed else self.speed, 1), 0)\n self.forward_left_motor.backward(speed=speed)\n self.forward_right_motor.forward(speed=speed)\n self.backward_left_motor.backward(speed=speed)\n self.backward_right_motor.forward(speed=speed)\n\n def right(self, speed: float=None):\n speed = max(min(speed if speed else self.speed, 1), 0)\n self.forward_left_motor.forward(speed=speed)\n self.forward_right_motor.backward(speed=speed)\n self.backward_left_motor.forward(speed=speed)\n self.backward_right_motor.backward(speed=speed)\n", "step-2": "<mask token>\n\n\nclass Car:\n\n def __init__(self, speed: float=1):\n self.speed = speed\n self.forward_right_motor = Motor(forward=12, backward=16)\n self.backward_right_motor = Motor(forward=21, backward=20)\n self.forward_left_motor = Motor(forward=23, backward=18)\n self.backward_left_motor = Motor(forward=24, backward=25)\n\n def stop(self):\n self.forward_left_motor.stop()\n self.forward_right_motor.stop()\n self.backward_left_motor.stop()\n self.backward_right_motor.stop()\n <mask token>\n\n def backward(self, speed: float=None):\n speed = max(min(speed if speed else self.speed, 1), 0)\n self.forward_left_motor.backward(speed=speed)\n self.forward_right_motor.backward(speed=speed)\n self.backward_left_motor.backward(speed=speed)\n self.backward_right_motor.backward(speed=speed)\n\n def left(self, speed: float=None):\n speed = max(min(speed if speed else self.speed, 1), 0)\n self.forward_left_motor.backward(speed=speed)\n self.forward_right_motor.forward(speed=speed)\n self.backward_left_motor.backward(speed=speed)\n self.backward_right_motor.forward(speed=speed)\n\n def right(self, speed: float=None):\n speed = max(min(speed if speed else self.speed, 1), 0)\n self.forward_left_motor.forward(speed=speed)\n self.forward_right_motor.backward(speed=speed)\n self.backward_left_motor.forward(speed=speed)\n self.backward_right_motor.backward(speed=speed)\n", "step-3": "<mask token>\n\n\nclass Car:\n\n def __init__(self, speed: float=1):\n self.speed = speed\n self.forward_right_motor = Motor(forward=12, backward=16)\n self.backward_right_motor = Motor(forward=21, backward=20)\n self.forward_left_motor = Motor(forward=23, backward=18)\n self.backward_left_motor = Motor(forward=24, backward=25)\n\n def stop(self):\n self.forward_left_motor.stop()\n self.forward_right_motor.stop()\n self.backward_left_motor.stop()\n self.backward_right_motor.stop()\n\n def forward(self, speed: float=None):\n speed = max(min(speed if speed else self.speed, 1), 0)\n self.forward_left_motor.forward(speed=speed)\n self.forward_right_motor.forward(speed=speed)\n self.backward_left_motor.forward(speed=speed)\n self.backward_right_motor.forward(speed=speed)\n\n def backward(self, speed: float=None):\n speed = max(min(speed if speed else self.speed, 1), 0)\n self.forward_left_motor.backward(speed=speed)\n self.forward_right_motor.backward(speed=speed)\n self.backward_left_motor.backward(speed=speed)\n self.backward_right_motor.backward(speed=speed)\n\n def left(self, speed: float=None):\n speed = max(min(speed if speed else self.speed, 1), 0)\n self.forward_left_motor.backward(speed=speed)\n self.forward_right_motor.forward(speed=speed)\n self.backward_left_motor.backward(speed=speed)\n self.backward_right_motor.forward(speed=speed)\n\n def right(self, speed: float=None):\n speed = max(min(speed if speed else self.speed, 1), 0)\n self.forward_left_motor.forward(speed=speed)\n self.forward_right_motor.backward(speed=speed)\n self.backward_left_motor.forward(speed=speed)\n self.backward_right_motor.backward(speed=speed)\n", "step-4": "from gpiozero import Motor\n\n\nclass Car:\n\n def __init__(self, speed: float=1):\n self.speed = speed\n self.forward_right_motor = Motor(forward=12, backward=16)\n self.backward_right_motor = Motor(forward=21, backward=20)\n self.forward_left_motor = Motor(forward=23, backward=18)\n self.backward_left_motor = Motor(forward=24, backward=25)\n\n def stop(self):\n self.forward_left_motor.stop()\n self.forward_right_motor.stop()\n self.backward_left_motor.stop()\n self.backward_right_motor.stop()\n\n def forward(self, speed: float=None):\n speed = max(min(speed if speed else self.speed, 1), 0)\n self.forward_left_motor.forward(speed=speed)\n self.forward_right_motor.forward(speed=speed)\n self.backward_left_motor.forward(speed=speed)\n self.backward_right_motor.forward(speed=speed)\n\n def backward(self, speed: float=None):\n speed = max(min(speed if speed else self.speed, 1), 0)\n self.forward_left_motor.backward(speed=speed)\n self.forward_right_motor.backward(speed=speed)\n self.backward_left_motor.backward(speed=speed)\n self.backward_right_motor.backward(speed=speed)\n\n def left(self, speed: float=None):\n speed = max(min(speed if speed else self.speed, 1), 0)\n self.forward_left_motor.backward(speed=speed)\n self.forward_right_motor.forward(speed=speed)\n self.backward_left_motor.backward(speed=speed)\n self.backward_right_motor.forward(speed=speed)\n\n def right(self, speed: float=None):\n speed = max(min(speed if speed else self.speed, 1), 0)\n self.forward_left_motor.forward(speed=speed)\n self.forward_right_motor.backward(speed=speed)\n self.backward_left_motor.forward(speed=speed)\n self.backward_right_motor.backward(speed=speed)\n", "step-5": null, "step-ids": [ 5, 6, 7, 8 ] }
[ 5, 6, 7, 8 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> channel_routing = [route('slack.rtm.message', message_consumer)] <|reserved_special_token_1|> from channels.routing import route from .consumers import message_consumer channel_routing = [route('slack.rtm.message', message_consumer)] <|reserved_special_token_1|> from channels.routing import route from .consumers import message_consumer channel_routing = [ route("slack.rtm.message", message_consumer) ]
flexible
{ "blob_id": "8439972b4458ba66d98f6a80a82a35576df472a4", "index": 8096, "step-1": "<mask token>\n", "step-2": "<mask token>\nchannel_routing = [route('slack.rtm.message', message_consumer)]\n", "step-3": "from channels.routing import route\nfrom .consumers import message_consumer\nchannel_routing = [route('slack.rtm.message', message_consumer)]\n", "step-4": "from channels.routing import route\nfrom .consumers import message_consumer\n\nchannel_routing = [\n route(\"slack.rtm.message\", message_consumer)\n]", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import bcrypt as bcrypt from config.configuration import Configuration class Usuario(Configuration.db.Model): __tablename__ = "usuario" id = Configuration.db.Column(Configuration.db.BIGINT, primary_key=True, autoincrement=True) code = Configuration.db.Column(Configuration.db.String(80), unique=True, nullable=False) email = Configuration.db.Column(Configuration.db.String(120),unique=True, nullable=True) senha = Configuration.db.Column(Configuration.db.String(300), nullable=True) nome = Configuration.db.Column(Configuration.db.String(100), nullable=True) def __repr__(self): return '<Usuario %r>' % self.id def get_id(self): return self.id def get_code(self): return self.code def get_email(self): return self.email def get_senha(self): return self.senha def get_nome(self): return self.nome def set_id(self,id): self.id = id def set_code(self,code): self.code = code def set_email(self,email): self.email = email def set_senha(self,senha): self.senha = bcrypt.encrypt(senha) def set_nome(self, nome): self.nome = nome def validate_password(self,senha): return bcrypt.verify(senha,self.senha)
normal
{ "blob_id": "598a0771dd1447034f2db95c67dd0dcf968f43a7", "index": 8229, "step-1": "<mask token>\n\n\nclass Usuario(Configuration.db.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __repr__(self):\n return '<Usuario %r>' % self.id\n <mask token>\n\n def get_code(self):\n return self.code\n <mask token>\n\n def get_senha(self):\n return self.senha\n <mask token>\n\n def set_id(self, id):\n self.id = id\n <mask token>\n\n def set_email(self, email):\n self.email = email\n <mask token>\n\n def set_nome(self, nome):\n self.nome = nome\n\n def validate_password(self, senha):\n return bcrypt.verify(senha, self.senha)\n", "step-2": "<mask token>\n\n\nclass Usuario(Configuration.db.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __repr__(self):\n return '<Usuario %r>' % self.id\n\n def get_id(self):\n return self.id\n\n def get_code(self):\n return self.code\n <mask token>\n\n def get_senha(self):\n return self.senha\n <mask token>\n\n def set_id(self, id):\n self.id = id\n <mask token>\n\n def set_email(self, email):\n self.email = email\n\n def set_senha(self, senha):\n self.senha = bcrypt.encrypt(senha)\n\n def set_nome(self, nome):\n self.nome = nome\n\n def validate_password(self, senha):\n return bcrypt.verify(senha, self.senha)\n", "step-3": "<mask token>\n\n\nclass Usuario(Configuration.db.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __repr__(self):\n return '<Usuario %r>' % self.id\n\n def get_id(self):\n return self.id\n\n def get_code(self):\n return self.code\n\n def get_email(self):\n return self.email\n\n def get_senha(self):\n return self.senha\n <mask token>\n\n def set_id(self, id):\n self.id = id\n\n def set_code(self, code):\n self.code = code\n\n def set_email(self, email):\n self.email = email\n\n def set_senha(self, senha):\n self.senha = bcrypt.encrypt(senha)\n\n def set_nome(self, nome):\n self.nome = nome\n\n def validate_password(self, senha):\n return bcrypt.verify(senha, self.senha)\n", "step-4": "<mask token>\n\n\nclass Usuario(Configuration.db.Model):\n __tablename__ = 'usuario'\n id = Configuration.db.Column(Configuration.db.BIGINT, primary_key=True,\n autoincrement=True)\n code = Configuration.db.Column(Configuration.db.String(80), unique=True,\n nullable=False)\n email = Configuration.db.Column(Configuration.db.String(120), unique=\n True, nullable=True)\n senha = Configuration.db.Column(Configuration.db.String(300), nullable=True\n )\n nome = Configuration.db.Column(Configuration.db.String(100), nullable=True)\n\n def __repr__(self):\n return '<Usuario %r>' % self.id\n\n def get_id(self):\n return self.id\n\n def get_code(self):\n return self.code\n\n def get_email(self):\n return self.email\n\n def get_senha(self):\n return self.senha\n\n def get_nome(self):\n return self.nome\n\n def set_id(self, id):\n self.id = id\n\n def set_code(self, code):\n self.code = code\n\n def set_email(self, email):\n self.email = email\n\n def set_senha(self, senha):\n self.senha = bcrypt.encrypt(senha)\n\n def set_nome(self, nome):\n self.nome = nome\n\n def validate_password(self, senha):\n return bcrypt.verify(senha, self.senha)\n", "step-5": "import bcrypt as bcrypt\n\nfrom config.configuration import Configuration\n\nclass Usuario(Configuration.db.Model):\n\n __tablename__ = \"usuario\"\n\n id = Configuration.db.Column(Configuration.db.BIGINT, primary_key=True, autoincrement=True)\n code = Configuration.db.Column(Configuration.db.String(80), unique=True, nullable=False)\n email = Configuration.db.Column(Configuration.db.String(120),unique=True, nullable=True)\n senha = Configuration.db.Column(Configuration.db.String(300), nullable=True)\n nome = Configuration.db.Column(Configuration.db.String(100), nullable=True)\n\n\n def __repr__(self):\n return '<Usuario %r>' % self.id\n\n def get_id(self):\n return self.id\n\n def get_code(self):\n return self.code\n\n def get_email(self):\n return self.email\n\n def get_senha(self):\n return self.senha\n\n def get_nome(self):\n return self.nome\n\n def set_id(self,id):\n self.id = id\n\n def set_code(self,code):\n self.code = code\n\n def set_email(self,email):\n self.email = email\n\n def set_senha(self,senha):\n self.senha = bcrypt.encrypt(senha)\n\n def set_nome(self, nome):\n self.nome = nome\n\n def validate_password(self,senha):\n return bcrypt.verify(senha,self.senha)", "step-ids": [ 8, 10, 12, 14, 16 ] }
[ 8, 10, 12, 14, 16 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> seconds_per_unit_time = 0.01 pars_spont = {'tau_p': 2.5, 'tau_d': 5.0, 'amp_p': 0.08, 'amp_d': -0.0533, 'rho': 0.0015, 'N': 50, 'w_max': 0.05, 'mu': 0.07, 'seed': None, 'tend': 50000000, 'r_in': 0.04, 'w_in': 0.05, 'init_W': 'random', 'init_scale': 0.2 } pars_avg_dw = {'tau_p': 2.5, 'tau_d': 5.0, 'amp_p': 0.08, 'amp_d': -0.0533, 'rho': 0.0015, 'N': 50, 'w_max': 0.05, 'mu': 0.07, 'seed': None, 'tend': 50000000, 'init_W': None} pars_learn = {'tau_p': 3.5, 'tau_d': 5.0, 'amp_p': 0.08, 'amp_d': -0.065, 'rho': 0.0015, 'rho_ext': 0.0418, 'N': 81, 'w_max': 0.026, 'w_ext': 0.26, 'mu': 0.07, 'seed': None, 'assembly_size': 20, 'inputs': 1, 't_ON': 18000, 't_OFF': 10000000, 'init_W': 'random', 'init_scale': 0.1} pars_drift = {'tau_p': 2.5, 'tau_d': 5.0, 'amp_p': 0.08, 'amp_d': -0.0533, 'rho': 0.002, 'N': 72, 'w_max': 0.056, 'mu': 0.148, 'seed': None, 'T1': 50000000, 'T2': 50000000, 'init_W': 'random', 'init_scale': 0.25} pars_drift2 = {'tau_p': 2.5, 'tau_d': 5.0, 'amp_p': 0.08, 'amp_d': -0.0533, 'rho': 0.0015, 'rho_small': 0.0003, 'N': 120, 'w_max': 0.024, 'mu': 0.05, 'seed': None, 't_switch': 30000000, 'p_switch': 0.03, 'init_W': 'assemblies', 'num_assemblies': 6, 'assembly_size': 20} pars_sizes = {'tau_p': 2.5, 'tau_d': 5.0, 'amp_p': 0.08, 'amp_d': -0.0533, 'rho': 0.0015, 'N': 150, 'mu': 0.04, 'seed': None, 'tend': 150000000, 'init_W': 'random', 'init_scale': 0.2} pars_intertwined = {'seconds_per_unit_time': 0.01, 'tau_p': 2.6, 'tau_d': 6.5, 'amp_p': 0.08, 'amp_d': -0.042, 'rho': 0.0015, 'w_max': 0.018, 'N': 190, 'num_assemblies': 20, 'swaps': 0, 'mu': 0.017, 'seed': None, 't_eq': 20000000, 'n_sims': 900, 't_sim': 100000, 'init_W': 'intertwined'} pars_avg_dw = {'tau_p': 2.5, 'tau_d': 5.0, 'amp_p': 0.08, 'amp_d': -0.0533, 'rho': 0.0015, 'N': 50, 'w_max': 0.05, 'mu': 0.07, 'seed': None, 'tend': 50000000, 'init_W': None} pars_overlap = {'tau_p': 2.5, 'tau_d': 5.0, 'amp_p': 0.08, 'amp_d': -0.0533, 'rho': 0.0015, 'rho_small': 0.0001, 'N': 60, 'w_max': 0.024, 'mu': 0.045, 'seed': None, 't_end': 100000000, 'init_W': 'assemblies', 'num_assemblies': 3, 'assembly_size': 20} pars_sparse = {'tau_p': 2.5, 'tau_d': 5.0, 'amp_p': 0.08, 'amp_d': -0.0533, 'rho': 0.0015, 'N': 50, 'w_max': 0.05, 'mu': 0.07, 'seed': None, 'tend': 20000000, 'init_W': None, 'density': 0.8} pars_input_strength = {'tau_p': 3.5, 'tau_d': 5.0, 'amp_p': 0.08, 'amp_d': -0.066, 'rho': 0.0015, 'N': 50, 'N_target': 20, 'w_max': 0.026, 'mu': 0.01, 'seed': None, 'r_in': 0.04, 'w_in': 0.05, 'init_W': None} <|reserved_special_token_1|> ### Global parameters ### seconds_per_unit_time = 0.01 ######################### pars_spont = { "tau_p": 2.5, "tau_d": 5.0, "amp_p": 0.08, "amp_d": -0.0533, "rho": 0.0015, "N": 50, "w_max": 0.05, "mu": 0.07, "seed": None, "tend": 50_000_000, "r_in": 0.04, "w_in": 0.05, "init_W": "random", "init_scale": 0.2, } pars_avg_dw = { "tau_p": 2.5, "tau_d": 5.0, "amp_p": 0.08, "amp_d": -0.0533, "rho": 0.0015, "N": 50, "w_max": 0.05, "mu": 0.07, "seed": None, "tend": 50_000_000, "init_W": None, } pars_learn = { "tau_p": 3.5, "tau_d": 5.0, "amp_p": 0.08, "amp_d": -0.065, "rho": 0.0015, "rho_ext": 0.0418, "N": 81, "w_max": 0.026, "w_ext": 0.26, "mu": 0.07, "seed": None, "assembly_size": 20, "inputs": 1, "t_ON": 18_000, "t_OFF": 10_000_000, "init_W": "random", "init_scale": 0.1, } pars_drift = { "tau_p": 2.5, "tau_d": 5.0, "amp_p": 0.08, "amp_d": -0.0533, "rho": 0.002, "N": 72, "w_max": 0.056, "mu": 0.148, "seed": None, "T1": 50_000_000, "T2": 50_000_000, "init_W": "random", "init_scale": 0.25, } pars_drift2 = { "tau_p": 2.5, "tau_d": 5.0, "amp_p": 0.08, "amp_d": -0.0533, "rho": 0.0015, "rho_small": 0.0003, "N": 120, "w_max": 0.024, "mu": 0.05, "seed": None, "t_switch": 30_000_000, "p_switch": 0.03, "init_W": "assemblies", "num_assemblies": 6, "assembly_size": 20, } pars_sizes = { "tau_p": 2.5, "tau_d": 5.0, "amp_p": 0.08, "amp_d": -0.0533, "rho": 0.0015, "N": 150, "mu": 0.04, "seed": None, "tend": 150_000_000, "init_W": "random", "init_scale": 0.2, } pars_intertwined = { "seconds_per_unit_time": 0.01, "tau_p": 2.6, "tau_d": 6.5, "amp_p": 0.08, "amp_d": -0.042, "rho": 0.0015, "w_max": 0.018, "N": 190, "num_assemblies": 20, "swaps": 0, "mu": 0.017, "seed": None, "t_eq": 20_000_000, "n_sims": 900, "t_sim": 100_000, "init_W": "intertwined", } pars_avg_dw = { "tau_p": 2.5, "tau_d": 5.0, "amp_p": 0.08, "amp_d": -0.0533, "rho": 0.0015, "N": 50, "w_max": 0.05, "mu": 0.07, "seed": None, "tend": 50_000_000, "init_W": None, } pars_overlap = { "tau_p": 2.5, "tau_d": 5.0, "amp_p": 0.08, "amp_d": -0.0533, "rho": 0.0015, "rho_small": 0.0001, "N": 60, "w_max": 0.024, "mu": 0.045, "seed": None, "t_end": 100_000_000, "init_W": "assemblies", "num_assemblies": 3, "assembly_size": 20, } pars_sparse = { "tau_p": 2.5, "tau_d": 5.0, "amp_p": 0.08, "amp_d": -0.0533, "rho": 0.0015, "N": 50, "w_max": 0.05, "mu": 0.07, "seed": None, "tend": 20_000_000, "init_W": None, "density": 0.8, } pars_input_strength = { "tau_p": 3.5, "tau_d": 5.0, "amp_p": 0.08, "amp_d": -0.066, "rho": 0.0015, "N": 50, "N_target": 20, "w_max": 0.026, "mu": 0.01, "seed": None, "r_in": 0.04, "w_in": 0.05, "init_W": None, }
flexible
{ "blob_id": "8f17c1ed0cb273a88b986cd7fe7a45439211d536", "index": 8641, "step-1": "<mask token>\n", "step-2": "seconds_per_unit_time = 0.01\npars_spont = {'tau_p': 2.5, 'tau_d': 5.0, 'amp_p': 0.08, 'amp_d': -0.0533,\n 'rho': 0.0015, 'N': 50, 'w_max': 0.05, 'mu': 0.07, 'seed': None, 'tend':\n 50000000, 'r_in': 0.04, 'w_in': 0.05, 'init_W': 'random', 'init_scale': 0.2\n }\npars_avg_dw = {'tau_p': 2.5, 'tau_d': 5.0, 'amp_p': 0.08, 'amp_d': -0.0533,\n 'rho': 0.0015, 'N': 50, 'w_max': 0.05, 'mu': 0.07, 'seed': None, 'tend':\n 50000000, 'init_W': None}\npars_learn = {'tau_p': 3.5, 'tau_d': 5.0, 'amp_p': 0.08, 'amp_d': -0.065,\n 'rho': 0.0015, 'rho_ext': 0.0418, 'N': 81, 'w_max': 0.026, 'w_ext': \n 0.26, 'mu': 0.07, 'seed': None, 'assembly_size': 20, 'inputs': 1,\n 't_ON': 18000, 't_OFF': 10000000, 'init_W': 'random', 'init_scale': 0.1}\npars_drift = {'tau_p': 2.5, 'tau_d': 5.0, 'amp_p': 0.08, 'amp_d': -0.0533,\n 'rho': 0.002, 'N': 72, 'w_max': 0.056, 'mu': 0.148, 'seed': None, 'T1':\n 50000000, 'T2': 50000000, 'init_W': 'random', 'init_scale': 0.25}\npars_drift2 = {'tau_p': 2.5, 'tau_d': 5.0, 'amp_p': 0.08, 'amp_d': -0.0533,\n 'rho': 0.0015, 'rho_small': 0.0003, 'N': 120, 'w_max': 0.024, 'mu': \n 0.05, 'seed': None, 't_switch': 30000000, 'p_switch': 0.03, 'init_W':\n 'assemblies', 'num_assemblies': 6, 'assembly_size': 20}\npars_sizes = {'tau_p': 2.5, 'tau_d': 5.0, 'amp_p': 0.08, 'amp_d': -0.0533,\n 'rho': 0.0015, 'N': 150, 'mu': 0.04, 'seed': None, 'tend': 150000000,\n 'init_W': 'random', 'init_scale': 0.2}\npars_intertwined = {'seconds_per_unit_time': 0.01, 'tau_p': 2.6, 'tau_d': \n 6.5, 'amp_p': 0.08, 'amp_d': -0.042, 'rho': 0.0015, 'w_max': 0.018, 'N':\n 190, 'num_assemblies': 20, 'swaps': 0, 'mu': 0.017, 'seed': None,\n 't_eq': 20000000, 'n_sims': 900, 't_sim': 100000, 'init_W': 'intertwined'}\npars_avg_dw = {'tau_p': 2.5, 'tau_d': 5.0, 'amp_p': 0.08, 'amp_d': -0.0533,\n 'rho': 0.0015, 'N': 50, 'w_max': 0.05, 'mu': 0.07, 'seed': None, 'tend':\n 50000000, 'init_W': None}\npars_overlap = {'tau_p': 2.5, 'tau_d': 5.0, 'amp_p': 0.08, 'amp_d': -0.0533,\n 'rho': 0.0015, 'rho_small': 0.0001, 'N': 60, 'w_max': 0.024, 'mu': \n 0.045, 'seed': None, 't_end': 100000000, 'init_W': 'assemblies',\n 'num_assemblies': 3, 'assembly_size': 20}\npars_sparse = {'tau_p': 2.5, 'tau_d': 5.0, 'amp_p': 0.08, 'amp_d': -0.0533,\n 'rho': 0.0015, 'N': 50, 'w_max': 0.05, 'mu': 0.07, 'seed': None, 'tend':\n 20000000, 'init_W': None, 'density': 0.8}\npars_input_strength = {'tau_p': 3.5, 'tau_d': 5.0, 'amp_p': 0.08, 'amp_d': \n -0.066, 'rho': 0.0015, 'N': 50, 'N_target': 20, 'w_max': 0.026, 'mu': \n 0.01, 'seed': None, 'r_in': 0.04, 'w_in': 0.05, 'init_W': None}\n", "step-3": "### Global parameters ###\n\nseconds_per_unit_time = 0.01\n\n#########################\n\npars_spont = {\n \"tau_p\": 2.5,\n \"tau_d\": 5.0,\n \"amp_p\": 0.08,\n \"amp_d\": -0.0533,\n \"rho\": 0.0015,\n \"N\": 50,\n \"w_max\": 0.05,\n \"mu\": 0.07,\n \"seed\": None,\n \"tend\": 50_000_000,\n \"r_in\": 0.04,\n \"w_in\": 0.05,\n \"init_W\": \"random\",\n \"init_scale\": 0.2,\n}\n\npars_avg_dw = {\n \"tau_p\": 2.5,\n \"tau_d\": 5.0,\n \"amp_p\": 0.08,\n \"amp_d\": -0.0533,\n \"rho\": 0.0015,\n \"N\": 50,\n \"w_max\": 0.05,\n \"mu\": 0.07,\n \"seed\": None,\n \"tend\": 50_000_000,\n \"init_W\": None,\n}\n\npars_learn = {\n \"tau_p\": 3.5,\n \"tau_d\": 5.0,\n \"amp_p\": 0.08,\n \"amp_d\": -0.065,\n \"rho\": 0.0015,\n \"rho_ext\": 0.0418,\n \"N\": 81,\n \"w_max\": 0.026,\n \"w_ext\": 0.26,\n \"mu\": 0.07,\n \"seed\": None,\n \"assembly_size\": 20,\n \"inputs\": 1,\n \"t_ON\": 18_000,\n \"t_OFF\": 10_000_000,\n \"init_W\": \"random\",\n \"init_scale\": 0.1,\n}\n\n\npars_drift = {\n \"tau_p\": 2.5,\n \"tau_d\": 5.0,\n \"amp_p\": 0.08,\n \"amp_d\": -0.0533,\n \"rho\": 0.002,\n \"N\": 72,\n \"w_max\": 0.056,\n \"mu\": 0.148,\n \"seed\": None,\n \"T1\": 50_000_000,\n \"T2\": 50_000_000,\n \"init_W\": \"random\",\n \"init_scale\": 0.25,\n}\n\n\npars_drift2 = {\n \"tau_p\": 2.5,\n \"tau_d\": 5.0,\n \"amp_p\": 0.08,\n \"amp_d\": -0.0533,\n \"rho\": 0.0015,\n \"rho_small\": 0.0003,\n \"N\": 120,\n \"w_max\": 0.024,\n \"mu\": 0.05,\n \"seed\": None,\n \"t_switch\": 30_000_000,\n \"p_switch\": 0.03,\n \"init_W\": \"assemblies\",\n \"num_assemblies\": 6,\n \"assembly_size\": 20,\n}\n\npars_sizes = {\n \"tau_p\": 2.5,\n \"tau_d\": 5.0,\n \"amp_p\": 0.08,\n \"amp_d\": -0.0533,\n \"rho\": 0.0015,\n \"N\": 150,\n \"mu\": 0.04,\n \"seed\": None,\n \"tend\": 150_000_000,\n \"init_W\": \"random\",\n \"init_scale\": 0.2,\n}\n\n\npars_intertwined = {\n \"seconds_per_unit_time\": 0.01,\n \"tau_p\": 2.6,\n \"tau_d\": 6.5,\n \"amp_p\": 0.08,\n \"amp_d\": -0.042,\n \"rho\": 0.0015,\n \"w_max\": 0.018,\n \"N\": 190,\n \"num_assemblies\": 20,\n \"swaps\": 0,\n \"mu\": 0.017,\n \"seed\": None,\n \"t_eq\": 20_000_000,\n \"n_sims\": 900,\n \"t_sim\": 100_000,\n \"init_W\": \"intertwined\",\n}\n\npars_avg_dw = {\n \"tau_p\": 2.5,\n \"tau_d\": 5.0,\n \"amp_p\": 0.08,\n \"amp_d\": -0.0533,\n \"rho\": 0.0015,\n \"N\": 50,\n \"w_max\": 0.05,\n \"mu\": 0.07,\n \"seed\": None,\n \"tend\": 50_000_000,\n \"init_W\": None,\n}\n\npars_overlap = {\n \"tau_p\": 2.5,\n \"tau_d\": 5.0,\n \"amp_p\": 0.08,\n \"amp_d\": -0.0533,\n \"rho\": 0.0015,\n \"rho_small\": 0.0001,\n \"N\": 60,\n \"w_max\": 0.024,\n \"mu\": 0.045,\n \"seed\": None,\n \"t_end\": 100_000_000,\n \"init_W\": \"assemblies\",\n \"num_assemblies\": 3,\n \"assembly_size\": 20,\n}\n\n\npars_sparse = {\n \"tau_p\": 2.5,\n \"tau_d\": 5.0,\n \"amp_p\": 0.08,\n \"amp_d\": -0.0533,\n \"rho\": 0.0015,\n \"N\": 50,\n \"w_max\": 0.05,\n \"mu\": 0.07,\n \"seed\": None,\n \"tend\": 20_000_000,\n \"init_W\": None,\n \"density\": 0.8,\n}\n\npars_input_strength = {\n \"tau_p\": 3.5,\n \"tau_d\": 5.0,\n \"amp_p\": 0.08,\n \"amp_d\": -0.066,\n \"rho\": 0.0015,\n \"N\": 50,\n \"N_target\": 20,\n \"w_max\": 0.026,\n \"mu\": 0.01,\n \"seed\": None,\n \"r_in\": 0.04,\n \"w_in\": 0.05,\n \"init_W\": None,\n}\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): dependencies = [('historiasClinicas', '0001_initial')] operations = [migrations.AlterField(model_name='actualizacion', name= 'valoracion_medica', field=models.CharField(choices=[( 'Apto para desempeñar el cargo sin patologia aparente', 'Apto para desempeñar el cargo sin patologia aparente'), ( 'Apto para desempañar el cargo con patologia que no limita la labor', 'Apto para desempañar el cargo con patologia que no limita la labor' ), ('Apto con restricciones o adaptaciones para la labor', 'Apto con restricciones o adaptaciones para la labor'), ('Aplazado', 'Aplazado'), ('Apto para labor el alturas', 'Apto para labor el alturas'), ( 'Apto para continuar desempeñando su labor', 'Apto para continuar desempeñando su labor'), ('Examen de retiro', 'Examen de retiro'), ('Apto para manipulación de alimentos', 'Apto para manipulación de alimentos')], max_length=50, verbose_name='Concepto de valoracion medica'))] <|reserved_special_token_1|> from django.db import migrations, models class Migration(migrations.Migration): dependencies = [('historiasClinicas', '0001_initial')] operations = [migrations.AlterField(model_name='actualizacion', name= 'valoracion_medica', field=models.CharField(choices=[( 'Apto para desempeñar el cargo sin patologia aparente', 'Apto para desempeñar el cargo sin patologia aparente'), ( 'Apto para desempañar el cargo con patologia que no limita la labor', 'Apto para desempañar el cargo con patologia que no limita la labor' ), ('Apto con restricciones o adaptaciones para la labor', 'Apto con restricciones o adaptaciones para la labor'), ('Aplazado', 'Aplazado'), ('Apto para labor el alturas', 'Apto para labor el alturas'), ( 'Apto para continuar desempeñando su labor', 'Apto para continuar desempeñando su labor'), ('Examen de retiro', 'Examen de retiro'), ('Apto para manipulación de alimentos', 'Apto para manipulación de alimentos')], max_length=50, verbose_name='Concepto de valoracion medica'))] <|reserved_special_token_1|> # Generated by Django 2.1.4 on 2019-04-17 03:56 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('historiasClinicas', '0001_initial'), ] operations = [ migrations.AlterField( model_name='actualizacion', name='valoracion_medica', field=models.CharField(choices=[('Apto para desempeñar el cargo sin patologia aparente', 'Apto para desempeñar el cargo sin patologia aparente'), ('Apto para desempañar el cargo con patologia que no limita la labor', 'Apto para desempañar el cargo con patologia que no limita la labor'), ('Apto con restricciones o adaptaciones para la labor', 'Apto con restricciones o adaptaciones para la labor'), ('Aplazado', 'Aplazado'), ('Apto para labor el alturas', 'Apto para labor el alturas'), ('Apto para continuar desempeñando su labor', 'Apto para continuar desempeñando su labor'), ('Examen de retiro', 'Examen de retiro'), ('Apto para manipulación de alimentos', 'Apto para manipulación de alimentos')], max_length=50, verbose_name='Concepto de valoracion medica'), ), ]
flexible
{ "blob_id": "4aefabf064cdef963f9c62bd5c93892207c301d3", "index": 3076, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('historiasClinicas', '0001_initial')]\n operations = [migrations.AlterField(model_name='actualizacion', name=\n 'valoracion_medica', field=models.CharField(choices=[(\n 'Apto para desempeñar el cargo sin patologia aparente',\n 'Apto para desempeñar el cargo sin patologia aparente'), (\n 'Apto para desempañar el cargo con patologia que no limita la labor',\n 'Apto para desempañar el cargo con patologia que no limita la labor'\n ), ('Apto con restricciones o adaptaciones para la labor',\n 'Apto con restricciones o adaptaciones para la labor'), ('Aplazado',\n 'Aplazado'), ('Apto para labor el alturas',\n 'Apto para labor el alturas'), (\n 'Apto para continuar desempeñando su labor',\n 'Apto para continuar desempeñando su labor'), ('Examen de retiro',\n 'Examen de retiro'), ('Apto para manipulación de alimentos',\n 'Apto para manipulación de alimentos')], max_length=50,\n verbose_name='Concepto de valoracion medica'))]\n", "step-4": "from django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('historiasClinicas', '0001_initial')]\n operations = [migrations.AlterField(model_name='actualizacion', name=\n 'valoracion_medica', field=models.CharField(choices=[(\n 'Apto para desempeñar el cargo sin patologia aparente',\n 'Apto para desempeñar el cargo sin patologia aparente'), (\n 'Apto para desempañar el cargo con patologia que no limita la labor',\n 'Apto para desempañar el cargo con patologia que no limita la labor'\n ), ('Apto con restricciones o adaptaciones para la labor',\n 'Apto con restricciones o adaptaciones para la labor'), ('Aplazado',\n 'Aplazado'), ('Apto para labor el alturas',\n 'Apto para labor el alturas'), (\n 'Apto para continuar desempeñando su labor',\n 'Apto para continuar desempeñando su labor'), ('Examen de retiro',\n 'Examen de retiro'), ('Apto para manipulación de alimentos',\n 'Apto para manipulación de alimentos')], max_length=50,\n verbose_name='Concepto de valoracion medica'))]\n", "step-5": "# Generated by Django 2.1.4 on 2019-04-17 03:56\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('historiasClinicas', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='actualizacion',\n name='valoracion_medica',\n field=models.CharField(choices=[('Apto para desempeñar el cargo sin patologia aparente', 'Apto para desempeñar el cargo sin patologia aparente'), ('Apto para desempañar el cargo con patologia que no limita la labor', 'Apto para desempañar el cargo con patologia que no limita la labor'), ('Apto con restricciones o adaptaciones para la labor', 'Apto con restricciones o adaptaciones para la labor'), ('Aplazado', 'Aplazado'), ('Apto para labor el alturas', 'Apto para labor el alturas'), ('Apto para continuar desempeñando su labor', 'Apto para continuar desempeñando su labor'), ('Examen de retiro', 'Examen de retiro'), ('Apto para manipulación de alimentos', 'Apto para manipulación de alimentos')], max_length=50, verbose_name='Concepto de valoracion medica'),\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import plotly.figure_factory as ff import pandas as pd import csv df=pd.read_csv("phone.csv") fig=ff.create_distplot([df["Avg Rating"].tolist()],["Samsung"],show_hist=False) fig.show()
normal
{ "blob_id": "5ae4f489da7b4f0913c9b16c86cc60537cc51234", "index": 9858, "step-1": "<mask token>\n", "step-2": "<mask token>\nfig.show()\n", "step-3": "<mask token>\ndf = pd.read_csv('phone.csv')\nfig = ff.create_distplot([df['Avg Rating'].tolist()], ['Samsung'],\n show_hist=False)\nfig.show()\n", "step-4": "import plotly.figure_factory as ff\nimport pandas as pd\nimport csv\ndf = pd.read_csv('phone.csv')\nfig = ff.create_distplot([df['Avg Rating'].tolist()], ['Samsung'],\n show_hist=False)\nfig.show()\n", "step-5": "import plotly.figure_factory as ff\r\nimport pandas as pd\r\nimport csv\r\n\r\ndf=pd.read_csv(\"phone.csv\")\r\nfig=ff.create_distplot([df[\"Avg Rating\"].tolist()],[\"Samsung\"],show_hist=False)\r\nfig.show()", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> def ridge_orient(im, gradientsigma, blocksigma, orientsmoothsigma): sze = np.fix(6 * gradientsigma) if np.remainder(sze, 2) == 0: sze = sze + 1 gauss = cv2.getGaussianKernel(np.int(sze), gradientsigma) f = gauss * gauss.T fy, fx = np.gradient(f) Gx = signal.convolve2d(im, fx, mode='same') Gy = signal.convolve2d(im, fy, mode='same') Gxx = np.power(Gx, 2) Gyy = np.power(Gy, 2) Gxy = Gx * Gy sze = np.fix(6 * blocksigma) gauss = cv2.getGaussianKernel(np.int(sze), blocksigma) f = gauss * gauss.T Gxx = scipy.ndimage.convolve(Gxx, f) Gyy = scipy.ndimage.convolve(Gyy, f) Gxy = 2 * scipy.ndimage.convolve(Gxy, f) denom = np.sqrt(np.power(Gxy, 2) + np.power(Gxx - Gyy, 2)) + np.finfo(float ).eps sin2theta = Gxy / denom cos2theta = (Gxx - Gyy) / denom if orientsmoothsigma: sze = np.fix(6 * orientsmoothsigma) if np.remainder(sze, 2) == 0: sze = sze + 1 gauss = cv2.getGaussianKernel(np.int(sze), orientsmoothsigma) f = gauss * gauss.T cos2theta = scipy.ndimage.convolve(cos2theta, f) sin2theta = scipy.ndimage.convolve(sin2theta, f) orientim = np.pi / 2 + np.arctan2(sin2theta, cos2theta) / 2 return orientim def frequest(im, orientim, windsze, minWaveLength, maxWaveLength): rows, cols = np.shape(im) cosorient = np.mean(np.cos(2 * orientim)) sinorient = np.mean(np.sin(2 * orientim)) orient = math.atan2(sinorient, cosorient) / 2 rotim = scipy.ndimage.rotate(im, orient / np.pi * 180 + 90, axes=(1, 0), reshape=False, order=3, mode='nearest') cropsze = int(np.fix(rows / np.sqrt(2))) offset = int(np.fix((rows - cropsze) / 2)) rotim = rotim[offset:offset + cropsze][:, offset:offset + cropsze] proj = np.sum(rotim, axis=0) dilation = scipy.ndimage.grey_dilation(proj, windsze, structure=np.ones (windsze)) temp = np.abs(dilation - proj) peak_thresh = 2 maxpts = (temp < peak_thresh) & (proj > np.mean(proj)) maxind = np.where(maxpts) rows_maxind, cols_maxind = np.shape(maxind) if cols_maxind < 2: freqim = np.zeros(im.shape) else: NoOfPeaks = cols_maxind waveLength = (maxind[0][cols_maxind - 1] - maxind[0][0]) / (NoOfPeaks - 1) if waveLength >= minWaveLength and waveLength <= maxWaveLength: freqim = 1 / np.double(waveLength) * np.ones(im.shape) else: freqim = np.zeros(im.shape) return freqim def ridge_freq(im, mask, orient, blksze, windsze, minWaveLength, maxWaveLength ): rows, cols = im.shape freq = np.zeros((rows, cols)) for r in range(0, rows - blksze, blksze): for c in range(0, cols - blksze, blksze): blkim = im[r:r + blksze][:, c:c + blksze] blkor = orient[r:r + blksze][:, c:c + blksze] freq[r:r + blksze][:, c:c + blksze] = frequest(blkim, blkor, windsze, minWaveLength, maxWaveLength) freq = freq * mask freq_1d = np.reshape(freq, (1, rows * cols)) ind = np.where(freq_1d > 0) ind = np.array(ind) ind = ind[1, :] non_zero_elems_in_freq = freq_1d[0][ind] meanfreq = np.mean(non_zero_elems_in_freq) medianfreq = np.median(non_zero_elems_in_freq) return freq, meanfreq def ridge_filter(im, orient, freq, kx, ky): angleInc = 3 im = np.double(im) rows, cols = im.shape new_im = np.zeros((rows, cols)) freq_1d = np.reshape(freq, (1, rows * cols)) ind = np.where(freq_1d > 0) ind = np.array(ind) ind = ind[1, :] non_zero_elems_in_freq = freq_1d[0][ind] non_zero_elems_in_freq = np.double(np.round(non_zero_elems_in_freq * 100) ) / 100 unfreq = np.unique(non_zero_elems_in_freq) sigmax = 1 / unfreq[0] * kx sigmay = 1 / unfreq[0] * ky sze = np.round(3 * np.max([sigmax, sigmay])) x, y = np.meshgrid(np.linspace(-sze, sze, 2 * sze + 1), np.linspace(- sze, sze, 2 * sze + 1)) reffilter = np.exp(-(np.power(x, 2) / (sigmax * sigmax) + np.power(y, 2 ) / (sigmay * sigmay))) * np.cos(2 * np.pi * unfreq[0] * x) filt_rows, filt_cols = reffilter.shape gabor_filter = np.array(np.zeros((180 // angleInc, filt_rows, filt_cols))) for o in range(0, 180 // angleInc): rot_filt = scipy.ndimage.rotate(reffilter, -(o * angleInc + 90), reshape=False) gabor_filter[o] = rot_filt maxsze = int(sze) temp = freq > 0 validr, validc = np.where(temp) temp1 = validr > maxsze temp2 = validr < rows - maxsze temp3 = validc > maxsze temp4 = validc < cols - maxsze final_temp = temp1 & temp2 & temp3 & temp4 finalind = np.where(final_temp) maxorient_index = np.round(180 / angleInc) orient_index = np.round(orient / np.pi * 180 / angleInc) for i in range(0, rows): for j in range(0, cols): if orient_index[i][j] < 1: orient_index[i][j] = orient_index[i][j] + maxorient_index if orient_index[i][j] > maxorient_index: orient_index[i][j] = orient_index[i][j] - maxorient_index finalind_rows, finalind_cols = np.shape(finalind) sze = int(sze) for k in range(0, finalind_cols): r = validr[finalind[0][k]] c = validc[finalind[0][k]] img_block = im[r - sze:r + sze + 1][:, c - sze:c + sze + 1] new_im[r][c] = np.sum(img_block * gabor_filter[int(orient_index[r][ c]) - 1]) return new_im def image_enhance(img): blksze = 16 thresh = 0.1 normim, mask = ridge_segment(img, blksze, thresh) gradientsigma = 1 blocksigma = 7 orientsmoothsigma = 7 orientim = ridge_orient(normim, gradientsigma, blocksigma, orientsmoothsigma) blksze = 38 windsze = 5 min_wave_length = 5 max_wave_length = 15 freq, medfreq = ridge_freq(normim, mask, orientim, blksze, windsze, min_wave_length, max_wave_length) freq = medfreq * mask kx = ky = 0.65 new_im = ridge_filter(normim, orientim, freq, kx, ky) return new_im < -3 <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def normalise(img): normed = (img - np.mean(img)) / np.std(img) return normed <|reserved_special_token_0|> def ridge_orient(im, gradientsigma, blocksigma, orientsmoothsigma): sze = np.fix(6 * gradientsigma) if np.remainder(sze, 2) == 0: sze = sze + 1 gauss = cv2.getGaussianKernel(np.int(sze), gradientsigma) f = gauss * gauss.T fy, fx = np.gradient(f) Gx = signal.convolve2d(im, fx, mode='same') Gy = signal.convolve2d(im, fy, mode='same') Gxx = np.power(Gx, 2) Gyy = np.power(Gy, 2) Gxy = Gx * Gy sze = np.fix(6 * blocksigma) gauss = cv2.getGaussianKernel(np.int(sze), blocksigma) f = gauss * gauss.T Gxx = scipy.ndimage.convolve(Gxx, f) Gyy = scipy.ndimage.convolve(Gyy, f) Gxy = 2 * scipy.ndimage.convolve(Gxy, f) denom = np.sqrt(np.power(Gxy, 2) + np.power(Gxx - Gyy, 2)) + np.finfo(float ).eps sin2theta = Gxy / denom cos2theta = (Gxx - Gyy) / denom if orientsmoothsigma: sze = np.fix(6 * orientsmoothsigma) if np.remainder(sze, 2) == 0: sze = sze + 1 gauss = cv2.getGaussianKernel(np.int(sze), orientsmoothsigma) f = gauss * gauss.T cos2theta = scipy.ndimage.convolve(cos2theta, f) sin2theta = scipy.ndimage.convolve(sin2theta, f) orientim = np.pi / 2 + np.arctan2(sin2theta, cos2theta) / 2 return orientim def frequest(im, orientim, windsze, minWaveLength, maxWaveLength): rows, cols = np.shape(im) cosorient = np.mean(np.cos(2 * orientim)) sinorient = np.mean(np.sin(2 * orientim)) orient = math.atan2(sinorient, cosorient) / 2 rotim = scipy.ndimage.rotate(im, orient / np.pi * 180 + 90, axes=(1, 0), reshape=False, order=3, mode='nearest') cropsze = int(np.fix(rows / np.sqrt(2))) offset = int(np.fix((rows - cropsze) / 2)) rotim = rotim[offset:offset + cropsze][:, offset:offset + cropsze] proj = np.sum(rotim, axis=0) dilation = scipy.ndimage.grey_dilation(proj, windsze, structure=np.ones (windsze)) temp = np.abs(dilation - proj) peak_thresh = 2 maxpts = (temp < peak_thresh) & (proj > np.mean(proj)) maxind = np.where(maxpts) rows_maxind, cols_maxind = np.shape(maxind) if cols_maxind < 2: freqim = np.zeros(im.shape) else: NoOfPeaks = cols_maxind waveLength = (maxind[0][cols_maxind - 1] - maxind[0][0]) / (NoOfPeaks - 1) if waveLength >= minWaveLength and waveLength <= maxWaveLength: freqim = 1 / np.double(waveLength) * np.ones(im.shape) else: freqim = np.zeros(im.shape) return freqim def ridge_freq(im, mask, orient, blksze, windsze, minWaveLength, maxWaveLength ): rows, cols = im.shape freq = np.zeros((rows, cols)) for r in range(0, rows - blksze, blksze): for c in range(0, cols - blksze, blksze): blkim = im[r:r + blksze][:, c:c + blksze] blkor = orient[r:r + blksze][:, c:c + blksze] freq[r:r + blksze][:, c:c + blksze] = frequest(blkim, blkor, windsze, minWaveLength, maxWaveLength) freq = freq * mask freq_1d = np.reshape(freq, (1, rows * cols)) ind = np.where(freq_1d > 0) ind = np.array(ind) ind = ind[1, :] non_zero_elems_in_freq = freq_1d[0][ind] meanfreq = np.mean(non_zero_elems_in_freq) medianfreq = np.median(non_zero_elems_in_freq) return freq, meanfreq def ridge_filter(im, orient, freq, kx, ky): angleInc = 3 im = np.double(im) rows, cols = im.shape new_im = np.zeros((rows, cols)) freq_1d = np.reshape(freq, (1, rows * cols)) ind = np.where(freq_1d > 0) ind = np.array(ind) ind = ind[1, :] non_zero_elems_in_freq = freq_1d[0][ind] non_zero_elems_in_freq = np.double(np.round(non_zero_elems_in_freq * 100) ) / 100 unfreq = np.unique(non_zero_elems_in_freq) sigmax = 1 / unfreq[0] * kx sigmay = 1 / unfreq[0] * ky sze = np.round(3 * np.max([sigmax, sigmay])) x, y = np.meshgrid(np.linspace(-sze, sze, 2 * sze + 1), np.linspace(- sze, sze, 2 * sze + 1)) reffilter = np.exp(-(np.power(x, 2) / (sigmax * sigmax) + np.power(y, 2 ) / (sigmay * sigmay))) * np.cos(2 * np.pi * unfreq[0] * x) filt_rows, filt_cols = reffilter.shape gabor_filter = np.array(np.zeros((180 // angleInc, filt_rows, filt_cols))) for o in range(0, 180 // angleInc): rot_filt = scipy.ndimage.rotate(reffilter, -(o * angleInc + 90), reshape=False) gabor_filter[o] = rot_filt maxsze = int(sze) temp = freq > 0 validr, validc = np.where(temp) temp1 = validr > maxsze temp2 = validr < rows - maxsze temp3 = validc > maxsze temp4 = validc < cols - maxsze final_temp = temp1 & temp2 & temp3 & temp4 finalind = np.where(final_temp) maxorient_index = np.round(180 / angleInc) orient_index = np.round(orient / np.pi * 180 / angleInc) for i in range(0, rows): for j in range(0, cols): if orient_index[i][j] < 1: orient_index[i][j] = orient_index[i][j] + maxorient_index if orient_index[i][j] > maxorient_index: orient_index[i][j] = orient_index[i][j] - maxorient_index finalind_rows, finalind_cols = np.shape(finalind) sze = int(sze) for k in range(0, finalind_cols): r = validr[finalind[0][k]] c = validc[finalind[0][k]] img_block = im[r - sze:r + sze + 1][:, c - sze:c + sze + 1] new_im[r][c] = np.sum(img_block * gabor_filter[int(orient_index[r][ c]) - 1]) return new_im def image_enhance(img): blksze = 16 thresh = 0.1 normim, mask = ridge_segment(img, blksze, thresh) gradientsigma = 1 blocksigma = 7 orientsmoothsigma = 7 orientim = ridge_orient(normim, gradientsigma, blocksigma, orientsmoothsigma) blksze = 38 windsze = 5 min_wave_length = 5 max_wave_length = 15 freq, medfreq = ridge_freq(normim, mask, orientim, blksze, windsze, min_wave_length, max_wave_length) freq = medfreq * mask kx = ky = 0.65 new_im = ridge_filter(normim, orientim, freq, kx, ky) return new_im < -3 def gabor_enhance(in_path, out_dir='./'): img = cv2.imread(in_path, 0) enhanced_img = image_enhance(img) enhanced_img = np.invert(enhanced_img) img = enhanced_img * 255 base_image_name = os.path.splitext(os.path.basename(in_path))[0] prefix = base_image_name.split('_normal')[0] img_out = out_dir + prefix + '_enhanced.png' cv2.imwrite(img_out, img) return img_out <|reserved_special_token_1|> <|reserved_special_token_0|> def normalise(img): normed = (img - np.mean(img)) / np.std(img) return normed def ridge_segment(im, blksze, thresh): rows, cols = im.shape im = normalise(im) new_rows = np.int(blksze * np.ceil(rows / blksze)) new_cols = np.int(blksze * np.ceil(cols / blksze)) padded_img = np.zeros((new_rows, new_cols)) stddevim = np.zeros((new_rows, new_cols)) padded_img[0:rows][:, 0:cols] = im for i in range(0, new_rows, blksze): for j in range(0, new_cols, blksze): block = padded_img[i:i + blksze][:, j:j + blksze] stddevim[i:i + blksze][:, j:j + blksze] = np.std(block) * np.ones( block.shape) stddevim = stddevim[0:rows][:, 0:cols] mask = stddevim > thresh mean_val = np.mean(im[mask]) std_val = np.std(im[mask]) normim = (im - mean_val) / std_val return normim, mask def ridge_orient(im, gradientsigma, blocksigma, orientsmoothsigma): sze = np.fix(6 * gradientsigma) if np.remainder(sze, 2) == 0: sze = sze + 1 gauss = cv2.getGaussianKernel(np.int(sze), gradientsigma) f = gauss * gauss.T fy, fx = np.gradient(f) Gx = signal.convolve2d(im, fx, mode='same') Gy = signal.convolve2d(im, fy, mode='same') Gxx = np.power(Gx, 2) Gyy = np.power(Gy, 2) Gxy = Gx * Gy sze = np.fix(6 * blocksigma) gauss = cv2.getGaussianKernel(np.int(sze), blocksigma) f = gauss * gauss.T Gxx = scipy.ndimage.convolve(Gxx, f) Gyy = scipy.ndimage.convolve(Gyy, f) Gxy = 2 * scipy.ndimage.convolve(Gxy, f) denom = np.sqrt(np.power(Gxy, 2) + np.power(Gxx - Gyy, 2)) + np.finfo(float ).eps sin2theta = Gxy / denom cos2theta = (Gxx - Gyy) / denom if orientsmoothsigma: sze = np.fix(6 * orientsmoothsigma) if np.remainder(sze, 2) == 0: sze = sze + 1 gauss = cv2.getGaussianKernel(np.int(sze), orientsmoothsigma) f = gauss * gauss.T cos2theta = scipy.ndimage.convolve(cos2theta, f) sin2theta = scipy.ndimage.convolve(sin2theta, f) orientim = np.pi / 2 + np.arctan2(sin2theta, cos2theta) / 2 return orientim def frequest(im, orientim, windsze, minWaveLength, maxWaveLength): rows, cols = np.shape(im) cosorient = np.mean(np.cos(2 * orientim)) sinorient = np.mean(np.sin(2 * orientim)) orient = math.atan2(sinorient, cosorient) / 2 rotim = scipy.ndimage.rotate(im, orient / np.pi * 180 + 90, axes=(1, 0), reshape=False, order=3, mode='nearest') cropsze = int(np.fix(rows / np.sqrt(2))) offset = int(np.fix((rows - cropsze) / 2)) rotim = rotim[offset:offset + cropsze][:, offset:offset + cropsze] proj = np.sum(rotim, axis=0) dilation = scipy.ndimage.grey_dilation(proj, windsze, structure=np.ones (windsze)) temp = np.abs(dilation - proj) peak_thresh = 2 maxpts = (temp < peak_thresh) & (proj > np.mean(proj)) maxind = np.where(maxpts) rows_maxind, cols_maxind = np.shape(maxind) if cols_maxind < 2: freqim = np.zeros(im.shape) else: NoOfPeaks = cols_maxind waveLength = (maxind[0][cols_maxind - 1] - maxind[0][0]) / (NoOfPeaks - 1) if waveLength >= minWaveLength and waveLength <= maxWaveLength: freqim = 1 / np.double(waveLength) * np.ones(im.shape) else: freqim = np.zeros(im.shape) return freqim def ridge_freq(im, mask, orient, blksze, windsze, minWaveLength, maxWaveLength ): rows, cols = im.shape freq = np.zeros((rows, cols)) for r in range(0, rows - blksze, blksze): for c in range(0, cols - blksze, blksze): blkim = im[r:r + blksze][:, c:c + blksze] blkor = orient[r:r + blksze][:, c:c + blksze] freq[r:r + blksze][:, c:c + blksze] = frequest(blkim, blkor, windsze, minWaveLength, maxWaveLength) freq = freq * mask freq_1d = np.reshape(freq, (1, rows * cols)) ind = np.where(freq_1d > 0) ind = np.array(ind) ind = ind[1, :] non_zero_elems_in_freq = freq_1d[0][ind] meanfreq = np.mean(non_zero_elems_in_freq) medianfreq = np.median(non_zero_elems_in_freq) return freq, meanfreq def ridge_filter(im, orient, freq, kx, ky): angleInc = 3 im = np.double(im) rows, cols = im.shape new_im = np.zeros((rows, cols)) freq_1d = np.reshape(freq, (1, rows * cols)) ind = np.where(freq_1d > 0) ind = np.array(ind) ind = ind[1, :] non_zero_elems_in_freq = freq_1d[0][ind] non_zero_elems_in_freq = np.double(np.round(non_zero_elems_in_freq * 100) ) / 100 unfreq = np.unique(non_zero_elems_in_freq) sigmax = 1 / unfreq[0] * kx sigmay = 1 / unfreq[0] * ky sze = np.round(3 * np.max([sigmax, sigmay])) x, y = np.meshgrid(np.linspace(-sze, sze, 2 * sze + 1), np.linspace(- sze, sze, 2 * sze + 1)) reffilter = np.exp(-(np.power(x, 2) / (sigmax * sigmax) + np.power(y, 2 ) / (sigmay * sigmay))) * np.cos(2 * np.pi * unfreq[0] * x) filt_rows, filt_cols = reffilter.shape gabor_filter = np.array(np.zeros((180 // angleInc, filt_rows, filt_cols))) for o in range(0, 180 // angleInc): rot_filt = scipy.ndimage.rotate(reffilter, -(o * angleInc + 90), reshape=False) gabor_filter[o] = rot_filt maxsze = int(sze) temp = freq > 0 validr, validc = np.where(temp) temp1 = validr > maxsze temp2 = validr < rows - maxsze temp3 = validc > maxsze temp4 = validc < cols - maxsze final_temp = temp1 & temp2 & temp3 & temp4 finalind = np.where(final_temp) maxorient_index = np.round(180 / angleInc) orient_index = np.round(orient / np.pi * 180 / angleInc) for i in range(0, rows): for j in range(0, cols): if orient_index[i][j] < 1: orient_index[i][j] = orient_index[i][j] + maxorient_index if orient_index[i][j] > maxorient_index: orient_index[i][j] = orient_index[i][j] - maxorient_index finalind_rows, finalind_cols = np.shape(finalind) sze = int(sze) for k in range(0, finalind_cols): r = validr[finalind[0][k]] c = validc[finalind[0][k]] img_block = im[r - sze:r + sze + 1][:, c - sze:c + sze + 1] new_im[r][c] = np.sum(img_block * gabor_filter[int(orient_index[r][ c]) - 1]) return new_im def image_enhance(img): blksze = 16 thresh = 0.1 normim, mask = ridge_segment(img, blksze, thresh) gradientsigma = 1 blocksigma = 7 orientsmoothsigma = 7 orientim = ridge_orient(normim, gradientsigma, blocksigma, orientsmoothsigma) blksze = 38 windsze = 5 min_wave_length = 5 max_wave_length = 15 freq, medfreq = ridge_freq(normim, mask, orientim, blksze, windsze, min_wave_length, max_wave_length) freq = medfreq * mask kx = ky = 0.65 new_im = ridge_filter(normim, orientim, freq, kx, ky) return new_im < -3 def gabor_enhance(in_path, out_dir='./'): img = cv2.imread(in_path, 0) enhanced_img = image_enhance(img) enhanced_img = np.invert(enhanced_img) img = enhanced_img * 255 base_image_name = os.path.splitext(os.path.basename(in_path))[0] prefix = base_image_name.split('_normal')[0] img_out = out_dir + prefix + '_enhanced.png' cv2.imwrite(img_out, img) return img_out <|reserved_special_token_1|> <|reserved_special_token_0|> import os import cv2 import math import scipy import numpy as np from scipy import signal def normalise(img): normed = (img - np.mean(img)) / np.std(img) return normed def ridge_segment(im, blksze, thresh): rows, cols = im.shape im = normalise(im) new_rows = np.int(blksze * np.ceil(rows / blksze)) new_cols = np.int(blksze * np.ceil(cols / blksze)) padded_img = np.zeros((new_rows, new_cols)) stddevim = np.zeros((new_rows, new_cols)) padded_img[0:rows][:, 0:cols] = im for i in range(0, new_rows, blksze): for j in range(0, new_cols, blksze): block = padded_img[i:i + blksze][:, j:j + blksze] stddevim[i:i + blksze][:, j:j + blksze] = np.std(block) * np.ones( block.shape) stddevim = stddevim[0:rows][:, 0:cols] mask = stddevim > thresh mean_val = np.mean(im[mask]) std_val = np.std(im[mask]) normim = (im - mean_val) / std_val return normim, mask def ridge_orient(im, gradientsigma, blocksigma, orientsmoothsigma): sze = np.fix(6 * gradientsigma) if np.remainder(sze, 2) == 0: sze = sze + 1 gauss = cv2.getGaussianKernel(np.int(sze), gradientsigma) f = gauss * gauss.T fy, fx = np.gradient(f) Gx = signal.convolve2d(im, fx, mode='same') Gy = signal.convolve2d(im, fy, mode='same') Gxx = np.power(Gx, 2) Gyy = np.power(Gy, 2) Gxy = Gx * Gy sze = np.fix(6 * blocksigma) gauss = cv2.getGaussianKernel(np.int(sze), blocksigma) f = gauss * gauss.T Gxx = scipy.ndimage.convolve(Gxx, f) Gyy = scipy.ndimage.convolve(Gyy, f) Gxy = 2 * scipy.ndimage.convolve(Gxy, f) denom = np.sqrt(np.power(Gxy, 2) + np.power(Gxx - Gyy, 2)) + np.finfo(float ).eps sin2theta = Gxy / denom cos2theta = (Gxx - Gyy) / denom if orientsmoothsigma: sze = np.fix(6 * orientsmoothsigma) if np.remainder(sze, 2) == 0: sze = sze + 1 gauss = cv2.getGaussianKernel(np.int(sze), orientsmoothsigma) f = gauss * gauss.T cos2theta = scipy.ndimage.convolve(cos2theta, f) sin2theta = scipy.ndimage.convolve(sin2theta, f) orientim = np.pi / 2 + np.arctan2(sin2theta, cos2theta) / 2 return orientim def frequest(im, orientim, windsze, minWaveLength, maxWaveLength): rows, cols = np.shape(im) cosorient = np.mean(np.cos(2 * orientim)) sinorient = np.mean(np.sin(2 * orientim)) orient = math.atan2(sinorient, cosorient) / 2 rotim = scipy.ndimage.rotate(im, orient / np.pi * 180 + 90, axes=(1, 0), reshape=False, order=3, mode='nearest') cropsze = int(np.fix(rows / np.sqrt(2))) offset = int(np.fix((rows - cropsze) / 2)) rotim = rotim[offset:offset + cropsze][:, offset:offset + cropsze] proj = np.sum(rotim, axis=0) dilation = scipy.ndimage.grey_dilation(proj, windsze, structure=np.ones (windsze)) temp = np.abs(dilation - proj) peak_thresh = 2 maxpts = (temp < peak_thresh) & (proj > np.mean(proj)) maxind = np.where(maxpts) rows_maxind, cols_maxind = np.shape(maxind) if cols_maxind < 2: freqim = np.zeros(im.shape) else: NoOfPeaks = cols_maxind waveLength = (maxind[0][cols_maxind - 1] - maxind[0][0]) / (NoOfPeaks - 1) if waveLength >= minWaveLength and waveLength <= maxWaveLength: freqim = 1 / np.double(waveLength) * np.ones(im.shape) else: freqim = np.zeros(im.shape) return freqim def ridge_freq(im, mask, orient, blksze, windsze, minWaveLength, maxWaveLength ): rows, cols = im.shape freq = np.zeros((rows, cols)) for r in range(0, rows - blksze, blksze): for c in range(0, cols - blksze, blksze): blkim = im[r:r + blksze][:, c:c + blksze] blkor = orient[r:r + blksze][:, c:c + blksze] freq[r:r + blksze][:, c:c + blksze] = frequest(blkim, blkor, windsze, minWaveLength, maxWaveLength) freq = freq * mask freq_1d = np.reshape(freq, (1, rows * cols)) ind = np.where(freq_1d > 0) ind = np.array(ind) ind = ind[1, :] non_zero_elems_in_freq = freq_1d[0][ind] meanfreq = np.mean(non_zero_elems_in_freq) medianfreq = np.median(non_zero_elems_in_freq) return freq, meanfreq def ridge_filter(im, orient, freq, kx, ky): angleInc = 3 im = np.double(im) rows, cols = im.shape new_im = np.zeros((rows, cols)) freq_1d = np.reshape(freq, (1, rows * cols)) ind = np.where(freq_1d > 0) ind = np.array(ind) ind = ind[1, :] non_zero_elems_in_freq = freq_1d[0][ind] non_zero_elems_in_freq = np.double(np.round(non_zero_elems_in_freq * 100) ) / 100 unfreq = np.unique(non_zero_elems_in_freq) sigmax = 1 / unfreq[0] * kx sigmay = 1 / unfreq[0] * ky sze = np.round(3 * np.max([sigmax, sigmay])) x, y = np.meshgrid(np.linspace(-sze, sze, 2 * sze + 1), np.linspace(- sze, sze, 2 * sze + 1)) reffilter = np.exp(-(np.power(x, 2) / (sigmax * sigmax) + np.power(y, 2 ) / (sigmay * sigmay))) * np.cos(2 * np.pi * unfreq[0] * x) filt_rows, filt_cols = reffilter.shape gabor_filter = np.array(np.zeros((180 // angleInc, filt_rows, filt_cols))) for o in range(0, 180 // angleInc): rot_filt = scipy.ndimage.rotate(reffilter, -(o * angleInc + 90), reshape=False) gabor_filter[o] = rot_filt maxsze = int(sze) temp = freq > 0 validr, validc = np.where(temp) temp1 = validr > maxsze temp2 = validr < rows - maxsze temp3 = validc > maxsze temp4 = validc < cols - maxsze final_temp = temp1 & temp2 & temp3 & temp4 finalind = np.where(final_temp) maxorient_index = np.round(180 / angleInc) orient_index = np.round(orient / np.pi * 180 / angleInc) for i in range(0, rows): for j in range(0, cols): if orient_index[i][j] < 1: orient_index[i][j] = orient_index[i][j] + maxorient_index if orient_index[i][j] > maxorient_index: orient_index[i][j] = orient_index[i][j] - maxorient_index finalind_rows, finalind_cols = np.shape(finalind) sze = int(sze) for k in range(0, finalind_cols): r = validr[finalind[0][k]] c = validc[finalind[0][k]] img_block = im[r - sze:r + sze + 1][:, c - sze:c + sze + 1] new_im[r][c] = np.sum(img_block * gabor_filter[int(orient_index[r][ c]) - 1]) return new_im def image_enhance(img): blksze = 16 thresh = 0.1 normim, mask = ridge_segment(img, blksze, thresh) gradientsigma = 1 blocksigma = 7 orientsmoothsigma = 7 orientim = ridge_orient(normim, gradientsigma, blocksigma, orientsmoothsigma) blksze = 38 windsze = 5 min_wave_length = 5 max_wave_length = 15 freq, medfreq = ridge_freq(normim, mask, orientim, blksze, windsze, min_wave_length, max_wave_length) freq = medfreq * mask kx = ky = 0.65 new_im = ridge_filter(normim, orientim, freq, kx, ky) return new_im < -3 def gabor_enhance(in_path, out_dir='./'): img = cv2.imread(in_path, 0) enhanced_img = image_enhance(img) enhanced_img = np.invert(enhanced_img) img = enhanced_img * 255 base_image_name = os.path.splitext(os.path.basename(in_path))[0] prefix = base_image_name.split('_normal')[0] img_out = out_dir + prefix + '_enhanced.png' cv2.imwrite(img_out, img) return img_out <|reserved_special_token_1|> # -*- coding: utf-8 -*- """ python3 description :Fingerprint image enhancement by using gabor """ import os import cv2 import math import scipy import numpy as np from scipy import signal def normalise(img): normed = (img - np.mean(img)) / (np.std(img)) return normed def ridge_segment(im, blksze, thresh): rows, cols = im.shape im = normalise(im) new_rows = np.int(blksze * np.ceil(rows / blksze)) new_cols = np.int(blksze * np.ceil(cols / blksze)) padded_img = np.zeros((new_rows, new_cols)) stddevim = np.zeros((new_rows, new_cols)) padded_img[0:rows][:, 0:cols] = im for i in range(0, new_rows, blksze): for j in range(0, new_cols, blksze): block = padded_img[i:i + blksze][:, j:j + blksze] stddevim[i:i + blksze][:, j:j + blksze] = np.std(block) * np.ones(block.shape) stddevim = stddevim[0:rows][:, 0:cols] mask = stddevim > thresh mean_val = np.mean(im[mask]) std_val = np.std(im[mask]) normim = (im - mean_val) / (std_val) return (normim, mask) def ridge_orient(im, gradientsigma, blocksigma, orientsmoothsigma): # Calculate image gradients. sze = np.fix(6 * gradientsigma) if np.remainder(sze, 2) == 0: sze = sze + 1 gauss = cv2.getGaussianKernel(np.int(sze), gradientsigma) f = gauss * gauss.T fy, fx = np.gradient(f) # Gradient of Gaussian Gx = signal.convolve2d(im, fx, mode='same') Gy = signal.convolve2d(im, fy, mode='same') Gxx = np.power(Gx, 2) Gyy = np.power(Gy, 2) Gxy = Gx * Gy # Now smooth the covariance data to perform a weighted summation of the data. sze = np.fix(6 * blocksigma) gauss = cv2.getGaussianKernel(np.int(sze), blocksigma) f = gauss * gauss.T Gxx = scipy.ndimage.convolve(Gxx, f) Gyy = scipy.ndimage.convolve(Gyy, f) Gxy = 2 * scipy.ndimage.convolve(Gxy, f) # Analytic solution of principal direction denom = np.sqrt(np.power(Gxy, 2) + np.power((Gxx - Gyy), 2) ) + np.finfo(float).eps sin2theta = Gxy / denom # Sine and cosine of doubled angles cos2theta = (Gxx - Gyy) / denom if orientsmoothsigma: sze = np.fix(6 * orientsmoothsigma) if np.remainder(sze, 2) == 0: sze = sze + 1 gauss = cv2.getGaussianKernel(np.int(sze), orientsmoothsigma) f = gauss * gauss.T # Smoothed sine and cosine of cos2theta = scipy.ndimage.convolve(cos2theta, f) sin2theta = scipy.ndimage.convolve(sin2theta, f) # doubled angles orientim = np.pi / 2 + np.arctan2(sin2theta, cos2theta) / 2 return (orientim) def frequest(im, orientim, windsze, minWaveLength, maxWaveLength): rows, cols = np.shape(im) # Find mean orientation within the block. This is done by averaging the # sines and cosines of the doubled angles before reconstructing the # angle again. This avoids wraparound problems at the origin. cosorient = np.mean(np.cos(2 * orientim)) sinorient = np.mean(np.sin(2 * orientim)) orient = math.atan2(sinorient, cosorient) / 2 # Rotate the image block so that the ridges are vertical # ROT_mat = cv2.getRotationMatrix2D((cols/2,rows/2),orient/np.pi*180 + 90,1) # rotim = cv2.warpAffine(im,ROT_mat,(cols,rows)) rotim = scipy.ndimage.rotate( im, orient / np.pi * 180 + 90, axes=(1, 0), reshape=False, order=3, mode='nearest') # Now crop the image so that the rotated image does not contain any # invalid regions. This prevents the projection down the columns # from being mucked up. cropsze = int(np.fix(rows / np.sqrt(2))) offset = int(np.fix((rows - cropsze) / 2)) rotim = rotim[offset:offset + cropsze][:, offset:offset + cropsze] # Sum down the columns to get a projection of the grey values down # the ridges. proj = np.sum(rotim, axis=0) dilation = scipy.ndimage.grey_dilation( proj, windsze, structure=np.ones(windsze)) temp = np.abs(dilation - proj) peak_thresh = 2 maxpts = (temp < peak_thresh) & (proj > np.mean(proj)) maxind = np.where(maxpts) rows_maxind, cols_maxind = np.shape(maxind) # Determine the spatial frequency of the ridges by divinding the # distance between the 1st and last peaks by the (No of peaks-1). If no # peaks are detected, or the wavelength is outside the allowed bounds, # the frequency image is set to 0 if cols_maxind < 2: freqim = np.zeros(im.shape) else: NoOfPeaks = cols_maxind waveLength = (maxind[0][cols_maxind - 1] - maxind[0][0]) / (NoOfPeaks - 1) if waveLength >= minWaveLength and waveLength <= maxWaveLength: freqim = 1 / np.double(waveLength) * np.ones(im.shape) else: freqim = np.zeros(im.shape) return freqim def ridge_freq(im, mask, orient, blksze, windsze, minWaveLength, maxWaveLength): rows, cols = im.shape freq = np.zeros((rows, cols)) for r in range(0, rows - blksze, blksze): for c in range(0, cols - blksze, blksze): blkim = im[r:r + blksze][:, c:c + blksze] blkor = orient[r:r + blksze][:, c:c + blksze] freq[r:r + blksze][:, c:c + blksze] = frequest(blkim, blkor, windsze, minWaveLength, maxWaveLength) freq = freq * mask freq_1d = np.reshape(freq, (1, rows * cols)) ind = np.where(freq_1d > 0) ind = np.array(ind) ind = ind[1, :] non_zero_elems_in_freq = freq_1d[0][ind] meanfreq = np.mean(non_zero_elems_in_freq) # does not work properly medianfreq = np.median(non_zero_elems_in_freq) return freq, meanfreq def ridge_filter(im, orient, freq, kx, ky): angleInc = 3 im = np.double(im) rows, cols = im.shape new_im = np.zeros((rows, cols)) freq_1d = np.reshape(freq, (1, rows * cols)) ind = np.where(freq_1d > 0) ind = np.array(ind) ind = ind[1, :] # Round the array of frequencies to the nearest 0.01 to reduce the # number of distinct frequencies we have to deal with. non_zero_elems_in_freq = freq_1d[0][ind] non_zero_elems_in_freq = np.double( np.round((non_zero_elems_in_freq * 100))) / 100 unfreq = np.unique(non_zero_elems_in_freq) # Generate filters corresponding to these distinct frequencies and # orientations in 'angleInc' increments. sigmax = 1 / unfreq[0] * kx sigmay = 1 / unfreq[0] * ky sze = np.round(3 * np.max([sigmax, sigmay])) x, y = np.meshgrid(np.linspace(-sze, sze, (2 * sze + 1)), np.linspace(-sze, sze, (2 * sze + 1))) reffilter = np.exp(-((np.power(x, 2)) / (sigmax * sigmax) + (np.power(y, 2)) / (sigmay * sigmay)) ) * np.cos(2 * np.pi * unfreq[0] * x) # this is the original gabor filter filt_rows, filt_cols = reffilter.shape gabor_filter = np.array(np.zeros((180 // angleInc, filt_rows, filt_cols))) for o in range(0, 180 // angleInc): # Generate rotated versions of the filter. Note orientation # image provides orientation *along* the ridges, hence +90 # degrees, and imrotate requires angles +ve anticlockwise, hence # the minus sign. rot_filt = scipy.ndimage.rotate(reffilter, -(o * angleInc + 90), reshape=False) gabor_filter[o] = rot_filt # Find indices of matrix points greater than maxsze from the image # boundary maxsze = int(sze) temp = freq > 0 validr, validc = np.where(temp) temp1 = validr > maxsze temp2 = validr < rows - maxsze temp3 = validc > maxsze temp4 = validc < cols - maxsze final_temp = temp1 & temp2 & temp3 & temp4 finalind = np.where(final_temp) # Convert orientation matrix values from radians to an index value # that corresponds to round(degrees/angleInc) maxorient_index = np.round(180 / angleInc) orient_index = np.round(orient / np.pi * 180 / angleInc) # do the filtering for i in range(0, rows): for j in range(0, cols): if orient_index[i][j] < 1: orient_index[i][j] = orient_index[i][j] + maxorient_index if orient_index[i][j] > maxorient_index: orient_index[i][j] = orient_index[i][j] - maxorient_index finalind_rows, finalind_cols = np.shape(finalind) sze = int(sze) for k in range(0, finalind_cols): r = validr[finalind[0][k]] c = validc[finalind[0][k]] img_block = im[r - sze:r + sze + 1][:, c - sze:c + sze + 1] new_im[r][c] = np.sum( img_block * gabor_filter[int(orient_index[r][c]) - 1]) return new_im def image_enhance(img): blksze = 16 thresh = 0.1 # normalise the image and find a ROI normim, mask = ridge_segment(img, blksze, thresh) gradientsigma = 1 blocksigma = 7 orientsmoothsigma = 7 # find orientation of every pixel orientim = ridge_orient(normim, gradientsigma, blocksigma, orientsmoothsigma) blksze = 38 windsze = 5 min_wave_length = 5 max_wave_length = 15 # find the overall frequency of ridges freq, medfreq = ridge_freq( normim, mask, orientim, blksze, windsze, min_wave_length, max_wave_length) freq = medfreq * mask kx = ky = 0.65 # create gabor filter and do the actual filtering new_im = ridge_filter(normim, orientim, freq, kx, ky) return (new_im < -3) def gabor_enhance(in_path, out_dir='./'): img = cv2.imread(in_path, 0) enhanced_img = image_enhance(img) enhanced_img = np.invert(enhanced_img) # print('saving the image') img = enhanced_img * 255 base_image_name = os.path.splitext(os.path.basename(in_path))[0] prefix = base_image_name.split('_normal')[0] img_out = out_dir + prefix + '_enhanced.png' # img.save(base_image_name + "_enhanced.png", "PNG") cv2.imwrite(img_out, img) return img_out
flexible
{ "blob_id": "9447d0d0481df3d0ee4273256d02977bc8044e4e", "index": 8603, "step-1": "<mask token>\n\n\ndef ridge_orient(im, gradientsigma, blocksigma, orientsmoothsigma):\n sze = np.fix(6 * gradientsigma)\n if np.remainder(sze, 2) == 0:\n sze = sze + 1\n gauss = cv2.getGaussianKernel(np.int(sze), gradientsigma)\n f = gauss * gauss.T\n fy, fx = np.gradient(f)\n Gx = signal.convolve2d(im, fx, mode='same')\n Gy = signal.convolve2d(im, fy, mode='same')\n Gxx = np.power(Gx, 2)\n Gyy = np.power(Gy, 2)\n Gxy = Gx * Gy\n sze = np.fix(6 * blocksigma)\n gauss = cv2.getGaussianKernel(np.int(sze), blocksigma)\n f = gauss * gauss.T\n Gxx = scipy.ndimage.convolve(Gxx, f)\n Gyy = scipy.ndimage.convolve(Gyy, f)\n Gxy = 2 * scipy.ndimage.convolve(Gxy, f)\n denom = np.sqrt(np.power(Gxy, 2) + np.power(Gxx - Gyy, 2)) + np.finfo(float\n ).eps\n sin2theta = Gxy / denom\n cos2theta = (Gxx - Gyy) / denom\n if orientsmoothsigma:\n sze = np.fix(6 * orientsmoothsigma)\n if np.remainder(sze, 2) == 0:\n sze = sze + 1\n gauss = cv2.getGaussianKernel(np.int(sze), orientsmoothsigma)\n f = gauss * gauss.T\n cos2theta = scipy.ndimage.convolve(cos2theta, f)\n sin2theta = scipy.ndimage.convolve(sin2theta, f)\n orientim = np.pi / 2 + np.arctan2(sin2theta, cos2theta) / 2\n return orientim\n\n\ndef frequest(im, orientim, windsze, minWaveLength, maxWaveLength):\n rows, cols = np.shape(im)\n cosorient = np.mean(np.cos(2 * orientim))\n sinorient = np.mean(np.sin(2 * orientim))\n orient = math.atan2(sinorient, cosorient) / 2\n rotim = scipy.ndimage.rotate(im, orient / np.pi * 180 + 90, axes=(1, 0),\n reshape=False, order=3, mode='nearest')\n cropsze = int(np.fix(rows / np.sqrt(2)))\n offset = int(np.fix((rows - cropsze) / 2))\n rotim = rotim[offset:offset + cropsze][:, offset:offset + cropsze]\n proj = np.sum(rotim, axis=0)\n dilation = scipy.ndimage.grey_dilation(proj, windsze, structure=np.ones\n (windsze))\n temp = np.abs(dilation - proj)\n peak_thresh = 2\n maxpts = (temp < peak_thresh) & (proj > np.mean(proj))\n maxind = np.where(maxpts)\n rows_maxind, cols_maxind = np.shape(maxind)\n if cols_maxind < 2:\n freqim = np.zeros(im.shape)\n else:\n NoOfPeaks = cols_maxind\n waveLength = (maxind[0][cols_maxind - 1] - maxind[0][0]) / (NoOfPeaks -\n 1)\n if waveLength >= minWaveLength and waveLength <= maxWaveLength:\n freqim = 1 / np.double(waveLength) * np.ones(im.shape)\n else:\n freqim = np.zeros(im.shape)\n return freqim\n\n\ndef ridge_freq(im, mask, orient, blksze, windsze, minWaveLength, maxWaveLength\n ):\n rows, cols = im.shape\n freq = np.zeros((rows, cols))\n for r in range(0, rows - blksze, blksze):\n for c in range(0, cols - blksze, blksze):\n blkim = im[r:r + blksze][:, c:c + blksze]\n blkor = orient[r:r + blksze][:, c:c + blksze]\n freq[r:r + blksze][:, c:c + blksze] = frequest(blkim, blkor,\n windsze, minWaveLength, maxWaveLength)\n freq = freq * mask\n freq_1d = np.reshape(freq, (1, rows * cols))\n ind = np.where(freq_1d > 0)\n ind = np.array(ind)\n ind = ind[1, :]\n non_zero_elems_in_freq = freq_1d[0][ind]\n meanfreq = np.mean(non_zero_elems_in_freq)\n medianfreq = np.median(non_zero_elems_in_freq)\n return freq, meanfreq\n\n\ndef ridge_filter(im, orient, freq, kx, ky):\n angleInc = 3\n im = np.double(im)\n rows, cols = im.shape\n new_im = np.zeros((rows, cols))\n freq_1d = np.reshape(freq, (1, rows * cols))\n ind = np.where(freq_1d > 0)\n ind = np.array(ind)\n ind = ind[1, :]\n non_zero_elems_in_freq = freq_1d[0][ind]\n non_zero_elems_in_freq = np.double(np.round(non_zero_elems_in_freq * 100)\n ) / 100\n unfreq = np.unique(non_zero_elems_in_freq)\n sigmax = 1 / unfreq[0] * kx\n sigmay = 1 / unfreq[0] * ky\n sze = np.round(3 * np.max([sigmax, sigmay]))\n x, y = np.meshgrid(np.linspace(-sze, sze, 2 * sze + 1), np.linspace(-\n sze, sze, 2 * sze + 1))\n reffilter = np.exp(-(np.power(x, 2) / (sigmax * sigmax) + np.power(y, 2\n ) / (sigmay * sigmay))) * np.cos(2 * np.pi * unfreq[0] * x)\n filt_rows, filt_cols = reffilter.shape\n gabor_filter = np.array(np.zeros((180 // angleInc, filt_rows, filt_cols)))\n for o in range(0, 180 // angleInc):\n rot_filt = scipy.ndimage.rotate(reffilter, -(o * angleInc + 90),\n reshape=False)\n gabor_filter[o] = rot_filt\n maxsze = int(sze)\n temp = freq > 0\n validr, validc = np.where(temp)\n temp1 = validr > maxsze\n temp2 = validr < rows - maxsze\n temp3 = validc > maxsze\n temp4 = validc < cols - maxsze\n final_temp = temp1 & temp2 & temp3 & temp4\n finalind = np.where(final_temp)\n maxorient_index = np.round(180 / angleInc)\n orient_index = np.round(orient / np.pi * 180 / angleInc)\n for i in range(0, rows):\n for j in range(0, cols):\n if orient_index[i][j] < 1:\n orient_index[i][j] = orient_index[i][j] + maxorient_index\n if orient_index[i][j] > maxorient_index:\n orient_index[i][j] = orient_index[i][j] - maxorient_index\n finalind_rows, finalind_cols = np.shape(finalind)\n sze = int(sze)\n for k in range(0, finalind_cols):\n r = validr[finalind[0][k]]\n c = validc[finalind[0][k]]\n img_block = im[r - sze:r + sze + 1][:, c - sze:c + sze + 1]\n new_im[r][c] = np.sum(img_block * gabor_filter[int(orient_index[r][\n c]) - 1])\n return new_im\n\n\ndef image_enhance(img):\n blksze = 16\n thresh = 0.1\n normim, mask = ridge_segment(img, blksze, thresh)\n gradientsigma = 1\n blocksigma = 7\n orientsmoothsigma = 7\n orientim = ridge_orient(normim, gradientsigma, blocksigma,\n orientsmoothsigma)\n blksze = 38\n windsze = 5\n min_wave_length = 5\n max_wave_length = 15\n freq, medfreq = ridge_freq(normim, mask, orientim, blksze, windsze,\n min_wave_length, max_wave_length)\n freq = medfreq * mask\n kx = ky = 0.65\n new_im = ridge_filter(normim, orientim, freq, kx, ky)\n return new_im < -3\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef normalise(img):\n normed = (img - np.mean(img)) / np.std(img)\n return normed\n\n\n<mask token>\n\n\ndef ridge_orient(im, gradientsigma, blocksigma, orientsmoothsigma):\n sze = np.fix(6 * gradientsigma)\n if np.remainder(sze, 2) == 0:\n sze = sze + 1\n gauss = cv2.getGaussianKernel(np.int(sze), gradientsigma)\n f = gauss * gauss.T\n fy, fx = np.gradient(f)\n Gx = signal.convolve2d(im, fx, mode='same')\n Gy = signal.convolve2d(im, fy, mode='same')\n Gxx = np.power(Gx, 2)\n Gyy = np.power(Gy, 2)\n Gxy = Gx * Gy\n sze = np.fix(6 * blocksigma)\n gauss = cv2.getGaussianKernel(np.int(sze), blocksigma)\n f = gauss * gauss.T\n Gxx = scipy.ndimage.convolve(Gxx, f)\n Gyy = scipy.ndimage.convolve(Gyy, f)\n Gxy = 2 * scipy.ndimage.convolve(Gxy, f)\n denom = np.sqrt(np.power(Gxy, 2) + np.power(Gxx - Gyy, 2)) + np.finfo(float\n ).eps\n sin2theta = Gxy / denom\n cos2theta = (Gxx - Gyy) / denom\n if orientsmoothsigma:\n sze = np.fix(6 * orientsmoothsigma)\n if np.remainder(sze, 2) == 0:\n sze = sze + 1\n gauss = cv2.getGaussianKernel(np.int(sze), orientsmoothsigma)\n f = gauss * gauss.T\n cos2theta = scipy.ndimage.convolve(cos2theta, f)\n sin2theta = scipy.ndimage.convolve(sin2theta, f)\n orientim = np.pi / 2 + np.arctan2(sin2theta, cos2theta) / 2\n return orientim\n\n\ndef frequest(im, orientim, windsze, minWaveLength, maxWaveLength):\n rows, cols = np.shape(im)\n cosorient = np.mean(np.cos(2 * orientim))\n sinorient = np.mean(np.sin(2 * orientim))\n orient = math.atan2(sinorient, cosorient) / 2\n rotim = scipy.ndimage.rotate(im, orient / np.pi * 180 + 90, axes=(1, 0),\n reshape=False, order=3, mode='nearest')\n cropsze = int(np.fix(rows / np.sqrt(2)))\n offset = int(np.fix((rows - cropsze) / 2))\n rotim = rotim[offset:offset + cropsze][:, offset:offset + cropsze]\n proj = np.sum(rotim, axis=0)\n dilation = scipy.ndimage.grey_dilation(proj, windsze, structure=np.ones\n (windsze))\n temp = np.abs(dilation - proj)\n peak_thresh = 2\n maxpts = (temp < peak_thresh) & (proj > np.mean(proj))\n maxind = np.where(maxpts)\n rows_maxind, cols_maxind = np.shape(maxind)\n if cols_maxind < 2:\n freqim = np.zeros(im.shape)\n else:\n NoOfPeaks = cols_maxind\n waveLength = (maxind[0][cols_maxind - 1] - maxind[0][0]) / (NoOfPeaks -\n 1)\n if waveLength >= minWaveLength and waveLength <= maxWaveLength:\n freqim = 1 / np.double(waveLength) * np.ones(im.shape)\n else:\n freqim = np.zeros(im.shape)\n return freqim\n\n\ndef ridge_freq(im, mask, orient, blksze, windsze, minWaveLength, maxWaveLength\n ):\n rows, cols = im.shape\n freq = np.zeros((rows, cols))\n for r in range(0, rows - blksze, blksze):\n for c in range(0, cols - blksze, blksze):\n blkim = im[r:r + blksze][:, c:c + blksze]\n blkor = orient[r:r + blksze][:, c:c + blksze]\n freq[r:r + blksze][:, c:c + blksze] = frequest(blkim, blkor,\n windsze, minWaveLength, maxWaveLength)\n freq = freq * mask\n freq_1d = np.reshape(freq, (1, rows * cols))\n ind = np.where(freq_1d > 0)\n ind = np.array(ind)\n ind = ind[1, :]\n non_zero_elems_in_freq = freq_1d[0][ind]\n meanfreq = np.mean(non_zero_elems_in_freq)\n medianfreq = np.median(non_zero_elems_in_freq)\n return freq, meanfreq\n\n\ndef ridge_filter(im, orient, freq, kx, ky):\n angleInc = 3\n im = np.double(im)\n rows, cols = im.shape\n new_im = np.zeros((rows, cols))\n freq_1d = np.reshape(freq, (1, rows * cols))\n ind = np.where(freq_1d > 0)\n ind = np.array(ind)\n ind = ind[1, :]\n non_zero_elems_in_freq = freq_1d[0][ind]\n non_zero_elems_in_freq = np.double(np.round(non_zero_elems_in_freq * 100)\n ) / 100\n unfreq = np.unique(non_zero_elems_in_freq)\n sigmax = 1 / unfreq[0] * kx\n sigmay = 1 / unfreq[0] * ky\n sze = np.round(3 * np.max([sigmax, sigmay]))\n x, y = np.meshgrid(np.linspace(-sze, sze, 2 * sze + 1), np.linspace(-\n sze, sze, 2 * sze + 1))\n reffilter = np.exp(-(np.power(x, 2) / (sigmax * sigmax) + np.power(y, 2\n ) / (sigmay * sigmay))) * np.cos(2 * np.pi * unfreq[0] * x)\n filt_rows, filt_cols = reffilter.shape\n gabor_filter = np.array(np.zeros((180 // angleInc, filt_rows, filt_cols)))\n for o in range(0, 180 // angleInc):\n rot_filt = scipy.ndimage.rotate(reffilter, -(o * angleInc + 90),\n reshape=False)\n gabor_filter[o] = rot_filt\n maxsze = int(sze)\n temp = freq > 0\n validr, validc = np.where(temp)\n temp1 = validr > maxsze\n temp2 = validr < rows - maxsze\n temp3 = validc > maxsze\n temp4 = validc < cols - maxsze\n final_temp = temp1 & temp2 & temp3 & temp4\n finalind = np.where(final_temp)\n maxorient_index = np.round(180 / angleInc)\n orient_index = np.round(orient / np.pi * 180 / angleInc)\n for i in range(0, rows):\n for j in range(0, cols):\n if orient_index[i][j] < 1:\n orient_index[i][j] = orient_index[i][j] + maxorient_index\n if orient_index[i][j] > maxorient_index:\n orient_index[i][j] = orient_index[i][j] - maxorient_index\n finalind_rows, finalind_cols = np.shape(finalind)\n sze = int(sze)\n for k in range(0, finalind_cols):\n r = validr[finalind[0][k]]\n c = validc[finalind[0][k]]\n img_block = im[r - sze:r + sze + 1][:, c - sze:c + sze + 1]\n new_im[r][c] = np.sum(img_block * gabor_filter[int(orient_index[r][\n c]) - 1])\n return new_im\n\n\ndef image_enhance(img):\n blksze = 16\n thresh = 0.1\n normim, mask = ridge_segment(img, blksze, thresh)\n gradientsigma = 1\n blocksigma = 7\n orientsmoothsigma = 7\n orientim = ridge_orient(normim, gradientsigma, blocksigma,\n orientsmoothsigma)\n blksze = 38\n windsze = 5\n min_wave_length = 5\n max_wave_length = 15\n freq, medfreq = ridge_freq(normim, mask, orientim, blksze, windsze,\n min_wave_length, max_wave_length)\n freq = medfreq * mask\n kx = ky = 0.65\n new_im = ridge_filter(normim, orientim, freq, kx, ky)\n return new_im < -3\n\n\ndef gabor_enhance(in_path, out_dir='./'):\n img = cv2.imread(in_path, 0)\n enhanced_img = image_enhance(img)\n enhanced_img = np.invert(enhanced_img)\n img = enhanced_img * 255\n base_image_name = os.path.splitext(os.path.basename(in_path))[0]\n prefix = base_image_name.split('_normal')[0]\n img_out = out_dir + prefix + '_enhanced.png'\n cv2.imwrite(img_out, img)\n return img_out\n", "step-3": "<mask token>\n\n\ndef normalise(img):\n normed = (img - np.mean(img)) / np.std(img)\n return normed\n\n\ndef ridge_segment(im, blksze, thresh):\n rows, cols = im.shape\n im = normalise(im)\n new_rows = np.int(blksze * np.ceil(rows / blksze))\n new_cols = np.int(blksze * np.ceil(cols / blksze))\n padded_img = np.zeros((new_rows, new_cols))\n stddevim = np.zeros((new_rows, new_cols))\n padded_img[0:rows][:, 0:cols] = im\n for i in range(0, new_rows, blksze):\n for j in range(0, new_cols, blksze):\n block = padded_img[i:i + blksze][:, j:j + blksze]\n stddevim[i:i + blksze][:, j:j + blksze] = np.std(block) * np.ones(\n block.shape)\n stddevim = stddevim[0:rows][:, 0:cols]\n mask = stddevim > thresh\n mean_val = np.mean(im[mask])\n std_val = np.std(im[mask])\n normim = (im - mean_val) / std_val\n return normim, mask\n\n\ndef ridge_orient(im, gradientsigma, blocksigma, orientsmoothsigma):\n sze = np.fix(6 * gradientsigma)\n if np.remainder(sze, 2) == 0:\n sze = sze + 1\n gauss = cv2.getGaussianKernel(np.int(sze), gradientsigma)\n f = gauss * gauss.T\n fy, fx = np.gradient(f)\n Gx = signal.convolve2d(im, fx, mode='same')\n Gy = signal.convolve2d(im, fy, mode='same')\n Gxx = np.power(Gx, 2)\n Gyy = np.power(Gy, 2)\n Gxy = Gx * Gy\n sze = np.fix(6 * blocksigma)\n gauss = cv2.getGaussianKernel(np.int(sze), blocksigma)\n f = gauss * gauss.T\n Gxx = scipy.ndimage.convolve(Gxx, f)\n Gyy = scipy.ndimage.convolve(Gyy, f)\n Gxy = 2 * scipy.ndimage.convolve(Gxy, f)\n denom = np.sqrt(np.power(Gxy, 2) + np.power(Gxx - Gyy, 2)) + np.finfo(float\n ).eps\n sin2theta = Gxy / denom\n cos2theta = (Gxx - Gyy) / denom\n if orientsmoothsigma:\n sze = np.fix(6 * orientsmoothsigma)\n if np.remainder(sze, 2) == 0:\n sze = sze + 1\n gauss = cv2.getGaussianKernel(np.int(sze), orientsmoothsigma)\n f = gauss * gauss.T\n cos2theta = scipy.ndimage.convolve(cos2theta, f)\n sin2theta = scipy.ndimage.convolve(sin2theta, f)\n orientim = np.pi / 2 + np.arctan2(sin2theta, cos2theta) / 2\n return orientim\n\n\ndef frequest(im, orientim, windsze, minWaveLength, maxWaveLength):\n rows, cols = np.shape(im)\n cosorient = np.mean(np.cos(2 * orientim))\n sinorient = np.mean(np.sin(2 * orientim))\n orient = math.atan2(sinorient, cosorient) / 2\n rotim = scipy.ndimage.rotate(im, orient / np.pi * 180 + 90, axes=(1, 0),\n reshape=False, order=3, mode='nearest')\n cropsze = int(np.fix(rows / np.sqrt(2)))\n offset = int(np.fix((rows - cropsze) / 2))\n rotim = rotim[offset:offset + cropsze][:, offset:offset + cropsze]\n proj = np.sum(rotim, axis=0)\n dilation = scipy.ndimage.grey_dilation(proj, windsze, structure=np.ones\n (windsze))\n temp = np.abs(dilation - proj)\n peak_thresh = 2\n maxpts = (temp < peak_thresh) & (proj > np.mean(proj))\n maxind = np.where(maxpts)\n rows_maxind, cols_maxind = np.shape(maxind)\n if cols_maxind < 2:\n freqim = np.zeros(im.shape)\n else:\n NoOfPeaks = cols_maxind\n waveLength = (maxind[0][cols_maxind - 1] - maxind[0][0]) / (NoOfPeaks -\n 1)\n if waveLength >= minWaveLength and waveLength <= maxWaveLength:\n freqim = 1 / np.double(waveLength) * np.ones(im.shape)\n else:\n freqim = np.zeros(im.shape)\n return freqim\n\n\ndef ridge_freq(im, mask, orient, blksze, windsze, minWaveLength, maxWaveLength\n ):\n rows, cols = im.shape\n freq = np.zeros((rows, cols))\n for r in range(0, rows - blksze, blksze):\n for c in range(0, cols - blksze, blksze):\n blkim = im[r:r + blksze][:, c:c + blksze]\n blkor = orient[r:r + blksze][:, c:c + blksze]\n freq[r:r + blksze][:, c:c + blksze] = frequest(blkim, blkor,\n windsze, minWaveLength, maxWaveLength)\n freq = freq * mask\n freq_1d = np.reshape(freq, (1, rows * cols))\n ind = np.where(freq_1d > 0)\n ind = np.array(ind)\n ind = ind[1, :]\n non_zero_elems_in_freq = freq_1d[0][ind]\n meanfreq = np.mean(non_zero_elems_in_freq)\n medianfreq = np.median(non_zero_elems_in_freq)\n return freq, meanfreq\n\n\ndef ridge_filter(im, orient, freq, kx, ky):\n angleInc = 3\n im = np.double(im)\n rows, cols = im.shape\n new_im = np.zeros((rows, cols))\n freq_1d = np.reshape(freq, (1, rows * cols))\n ind = np.where(freq_1d > 0)\n ind = np.array(ind)\n ind = ind[1, :]\n non_zero_elems_in_freq = freq_1d[0][ind]\n non_zero_elems_in_freq = np.double(np.round(non_zero_elems_in_freq * 100)\n ) / 100\n unfreq = np.unique(non_zero_elems_in_freq)\n sigmax = 1 / unfreq[0] * kx\n sigmay = 1 / unfreq[0] * ky\n sze = np.round(3 * np.max([sigmax, sigmay]))\n x, y = np.meshgrid(np.linspace(-sze, sze, 2 * sze + 1), np.linspace(-\n sze, sze, 2 * sze + 1))\n reffilter = np.exp(-(np.power(x, 2) / (sigmax * sigmax) + np.power(y, 2\n ) / (sigmay * sigmay))) * np.cos(2 * np.pi * unfreq[0] * x)\n filt_rows, filt_cols = reffilter.shape\n gabor_filter = np.array(np.zeros((180 // angleInc, filt_rows, filt_cols)))\n for o in range(0, 180 // angleInc):\n rot_filt = scipy.ndimage.rotate(reffilter, -(o * angleInc + 90),\n reshape=False)\n gabor_filter[o] = rot_filt\n maxsze = int(sze)\n temp = freq > 0\n validr, validc = np.where(temp)\n temp1 = validr > maxsze\n temp2 = validr < rows - maxsze\n temp3 = validc > maxsze\n temp4 = validc < cols - maxsze\n final_temp = temp1 & temp2 & temp3 & temp4\n finalind = np.where(final_temp)\n maxorient_index = np.round(180 / angleInc)\n orient_index = np.round(orient / np.pi * 180 / angleInc)\n for i in range(0, rows):\n for j in range(0, cols):\n if orient_index[i][j] < 1:\n orient_index[i][j] = orient_index[i][j] + maxorient_index\n if orient_index[i][j] > maxorient_index:\n orient_index[i][j] = orient_index[i][j] - maxorient_index\n finalind_rows, finalind_cols = np.shape(finalind)\n sze = int(sze)\n for k in range(0, finalind_cols):\n r = validr[finalind[0][k]]\n c = validc[finalind[0][k]]\n img_block = im[r - sze:r + sze + 1][:, c - sze:c + sze + 1]\n new_im[r][c] = np.sum(img_block * gabor_filter[int(orient_index[r][\n c]) - 1])\n return new_im\n\n\ndef image_enhance(img):\n blksze = 16\n thresh = 0.1\n normim, mask = ridge_segment(img, blksze, thresh)\n gradientsigma = 1\n blocksigma = 7\n orientsmoothsigma = 7\n orientim = ridge_orient(normim, gradientsigma, blocksigma,\n orientsmoothsigma)\n blksze = 38\n windsze = 5\n min_wave_length = 5\n max_wave_length = 15\n freq, medfreq = ridge_freq(normim, mask, orientim, blksze, windsze,\n min_wave_length, max_wave_length)\n freq = medfreq * mask\n kx = ky = 0.65\n new_im = ridge_filter(normim, orientim, freq, kx, ky)\n return new_im < -3\n\n\ndef gabor_enhance(in_path, out_dir='./'):\n img = cv2.imread(in_path, 0)\n enhanced_img = image_enhance(img)\n enhanced_img = np.invert(enhanced_img)\n img = enhanced_img * 255\n base_image_name = os.path.splitext(os.path.basename(in_path))[0]\n prefix = base_image_name.split('_normal')[0]\n img_out = out_dir + prefix + '_enhanced.png'\n cv2.imwrite(img_out, img)\n return img_out\n", "step-4": "<mask token>\nimport os\nimport cv2\nimport math\nimport scipy\nimport numpy as np\nfrom scipy import signal\n\n\ndef normalise(img):\n normed = (img - np.mean(img)) / np.std(img)\n return normed\n\n\ndef ridge_segment(im, blksze, thresh):\n rows, cols = im.shape\n im = normalise(im)\n new_rows = np.int(blksze * np.ceil(rows / blksze))\n new_cols = np.int(blksze * np.ceil(cols / blksze))\n padded_img = np.zeros((new_rows, new_cols))\n stddevim = np.zeros((new_rows, new_cols))\n padded_img[0:rows][:, 0:cols] = im\n for i in range(0, new_rows, blksze):\n for j in range(0, new_cols, blksze):\n block = padded_img[i:i + blksze][:, j:j + blksze]\n stddevim[i:i + blksze][:, j:j + blksze] = np.std(block) * np.ones(\n block.shape)\n stddevim = stddevim[0:rows][:, 0:cols]\n mask = stddevim > thresh\n mean_val = np.mean(im[mask])\n std_val = np.std(im[mask])\n normim = (im - mean_val) / std_val\n return normim, mask\n\n\ndef ridge_orient(im, gradientsigma, blocksigma, orientsmoothsigma):\n sze = np.fix(6 * gradientsigma)\n if np.remainder(sze, 2) == 0:\n sze = sze + 1\n gauss = cv2.getGaussianKernel(np.int(sze), gradientsigma)\n f = gauss * gauss.T\n fy, fx = np.gradient(f)\n Gx = signal.convolve2d(im, fx, mode='same')\n Gy = signal.convolve2d(im, fy, mode='same')\n Gxx = np.power(Gx, 2)\n Gyy = np.power(Gy, 2)\n Gxy = Gx * Gy\n sze = np.fix(6 * blocksigma)\n gauss = cv2.getGaussianKernel(np.int(sze), blocksigma)\n f = gauss * gauss.T\n Gxx = scipy.ndimage.convolve(Gxx, f)\n Gyy = scipy.ndimage.convolve(Gyy, f)\n Gxy = 2 * scipy.ndimage.convolve(Gxy, f)\n denom = np.sqrt(np.power(Gxy, 2) + np.power(Gxx - Gyy, 2)) + np.finfo(float\n ).eps\n sin2theta = Gxy / denom\n cos2theta = (Gxx - Gyy) / denom\n if orientsmoothsigma:\n sze = np.fix(6 * orientsmoothsigma)\n if np.remainder(sze, 2) == 0:\n sze = sze + 1\n gauss = cv2.getGaussianKernel(np.int(sze), orientsmoothsigma)\n f = gauss * gauss.T\n cos2theta = scipy.ndimage.convolve(cos2theta, f)\n sin2theta = scipy.ndimage.convolve(sin2theta, f)\n orientim = np.pi / 2 + np.arctan2(sin2theta, cos2theta) / 2\n return orientim\n\n\ndef frequest(im, orientim, windsze, minWaveLength, maxWaveLength):\n rows, cols = np.shape(im)\n cosorient = np.mean(np.cos(2 * orientim))\n sinorient = np.mean(np.sin(2 * orientim))\n orient = math.atan2(sinorient, cosorient) / 2\n rotim = scipy.ndimage.rotate(im, orient / np.pi * 180 + 90, axes=(1, 0),\n reshape=False, order=3, mode='nearest')\n cropsze = int(np.fix(rows / np.sqrt(2)))\n offset = int(np.fix((rows - cropsze) / 2))\n rotim = rotim[offset:offset + cropsze][:, offset:offset + cropsze]\n proj = np.sum(rotim, axis=0)\n dilation = scipy.ndimage.grey_dilation(proj, windsze, structure=np.ones\n (windsze))\n temp = np.abs(dilation - proj)\n peak_thresh = 2\n maxpts = (temp < peak_thresh) & (proj > np.mean(proj))\n maxind = np.where(maxpts)\n rows_maxind, cols_maxind = np.shape(maxind)\n if cols_maxind < 2:\n freqim = np.zeros(im.shape)\n else:\n NoOfPeaks = cols_maxind\n waveLength = (maxind[0][cols_maxind - 1] - maxind[0][0]) / (NoOfPeaks -\n 1)\n if waveLength >= minWaveLength and waveLength <= maxWaveLength:\n freqim = 1 / np.double(waveLength) * np.ones(im.shape)\n else:\n freqim = np.zeros(im.shape)\n return freqim\n\n\ndef ridge_freq(im, mask, orient, blksze, windsze, minWaveLength, maxWaveLength\n ):\n rows, cols = im.shape\n freq = np.zeros((rows, cols))\n for r in range(0, rows - blksze, blksze):\n for c in range(0, cols - blksze, blksze):\n blkim = im[r:r + blksze][:, c:c + blksze]\n blkor = orient[r:r + blksze][:, c:c + blksze]\n freq[r:r + blksze][:, c:c + blksze] = frequest(blkim, blkor,\n windsze, minWaveLength, maxWaveLength)\n freq = freq * mask\n freq_1d = np.reshape(freq, (1, rows * cols))\n ind = np.where(freq_1d > 0)\n ind = np.array(ind)\n ind = ind[1, :]\n non_zero_elems_in_freq = freq_1d[0][ind]\n meanfreq = np.mean(non_zero_elems_in_freq)\n medianfreq = np.median(non_zero_elems_in_freq)\n return freq, meanfreq\n\n\ndef ridge_filter(im, orient, freq, kx, ky):\n angleInc = 3\n im = np.double(im)\n rows, cols = im.shape\n new_im = np.zeros((rows, cols))\n freq_1d = np.reshape(freq, (1, rows * cols))\n ind = np.where(freq_1d > 0)\n ind = np.array(ind)\n ind = ind[1, :]\n non_zero_elems_in_freq = freq_1d[0][ind]\n non_zero_elems_in_freq = np.double(np.round(non_zero_elems_in_freq * 100)\n ) / 100\n unfreq = np.unique(non_zero_elems_in_freq)\n sigmax = 1 / unfreq[0] * kx\n sigmay = 1 / unfreq[0] * ky\n sze = np.round(3 * np.max([sigmax, sigmay]))\n x, y = np.meshgrid(np.linspace(-sze, sze, 2 * sze + 1), np.linspace(-\n sze, sze, 2 * sze + 1))\n reffilter = np.exp(-(np.power(x, 2) / (sigmax * sigmax) + np.power(y, 2\n ) / (sigmay * sigmay))) * np.cos(2 * np.pi * unfreq[0] * x)\n filt_rows, filt_cols = reffilter.shape\n gabor_filter = np.array(np.zeros((180 // angleInc, filt_rows, filt_cols)))\n for o in range(0, 180 // angleInc):\n rot_filt = scipy.ndimage.rotate(reffilter, -(o * angleInc + 90),\n reshape=False)\n gabor_filter[o] = rot_filt\n maxsze = int(sze)\n temp = freq > 0\n validr, validc = np.where(temp)\n temp1 = validr > maxsze\n temp2 = validr < rows - maxsze\n temp3 = validc > maxsze\n temp4 = validc < cols - maxsze\n final_temp = temp1 & temp2 & temp3 & temp4\n finalind = np.where(final_temp)\n maxorient_index = np.round(180 / angleInc)\n orient_index = np.round(orient / np.pi * 180 / angleInc)\n for i in range(0, rows):\n for j in range(0, cols):\n if orient_index[i][j] < 1:\n orient_index[i][j] = orient_index[i][j] + maxorient_index\n if orient_index[i][j] > maxorient_index:\n orient_index[i][j] = orient_index[i][j] - maxorient_index\n finalind_rows, finalind_cols = np.shape(finalind)\n sze = int(sze)\n for k in range(0, finalind_cols):\n r = validr[finalind[0][k]]\n c = validc[finalind[0][k]]\n img_block = im[r - sze:r + sze + 1][:, c - sze:c + sze + 1]\n new_im[r][c] = np.sum(img_block * gabor_filter[int(orient_index[r][\n c]) - 1])\n return new_im\n\n\ndef image_enhance(img):\n blksze = 16\n thresh = 0.1\n normim, mask = ridge_segment(img, blksze, thresh)\n gradientsigma = 1\n blocksigma = 7\n orientsmoothsigma = 7\n orientim = ridge_orient(normim, gradientsigma, blocksigma,\n orientsmoothsigma)\n blksze = 38\n windsze = 5\n min_wave_length = 5\n max_wave_length = 15\n freq, medfreq = ridge_freq(normim, mask, orientim, blksze, windsze,\n min_wave_length, max_wave_length)\n freq = medfreq * mask\n kx = ky = 0.65\n new_im = ridge_filter(normim, orientim, freq, kx, ky)\n return new_im < -3\n\n\ndef gabor_enhance(in_path, out_dir='./'):\n img = cv2.imread(in_path, 0)\n enhanced_img = image_enhance(img)\n enhanced_img = np.invert(enhanced_img)\n img = enhanced_img * 255\n base_image_name = os.path.splitext(os.path.basename(in_path))[0]\n prefix = base_image_name.split('_normal')[0]\n img_out = out_dir + prefix + '_enhanced.png'\n cv2.imwrite(img_out, img)\n return img_out\n", "step-5": "# -*- coding: utf-8 -*-\n\"\"\"\npython3\ndescription :Fingerprint image enhancement by using gabor\n\"\"\"\nimport os\nimport cv2\nimport math\nimport scipy\nimport numpy as np\nfrom scipy import signal\n\n\ndef normalise(img):\n normed = (img - np.mean(img)) / (np.std(img))\n return normed\n\n\ndef ridge_segment(im, blksze, thresh):\n rows, cols = im.shape\n im = normalise(im)\n new_rows = np.int(blksze * np.ceil(rows / blksze))\n new_cols = np.int(blksze * np.ceil(cols / blksze))\n\n padded_img = np.zeros((new_rows, new_cols))\n stddevim = np.zeros((new_rows, new_cols))\n\n padded_img[0:rows][:, 0:cols] = im\n\n for i in range(0, new_rows, blksze):\n for j in range(0, new_cols, blksze):\n block = padded_img[i:i + blksze][:, j:j + blksze]\n\n stddevim[i:i + blksze][:, j:j +\n blksze] = np.std(block) * np.ones(block.shape)\n\n stddevim = stddevim[0:rows][:, 0:cols]\n\n mask = stddevim > thresh\n\n mean_val = np.mean(im[mask])\n\n std_val = np.std(im[mask])\n\n normim = (im - mean_val) / (std_val)\n\n return (normim, mask)\n\n\ndef ridge_orient(im, gradientsigma, blocksigma, orientsmoothsigma):\n # Calculate image gradients.\n sze = np.fix(6 * gradientsigma)\n if np.remainder(sze, 2) == 0:\n sze = sze + 1\n\n gauss = cv2.getGaussianKernel(np.int(sze), gradientsigma)\n f = gauss * gauss.T\n\n fy, fx = np.gradient(f) # Gradient of Gaussian\n Gx = signal.convolve2d(im, fx, mode='same')\n Gy = signal.convolve2d(im, fy, mode='same')\n\n Gxx = np.power(Gx, 2)\n Gyy = np.power(Gy, 2)\n Gxy = Gx * Gy\n\n # Now smooth the covariance data to perform a weighted summation of the data.\n\n sze = np.fix(6 * blocksigma)\n\n gauss = cv2.getGaussianKernel(np.int(sze), blocksigma)\n f = gauss * gauss.T\n\n Gxx = scipy.ndimage.convolve(Gxx, f)\n Gyy = scipy.ndimage.convolve(Gyy, f)\n Gxy = 2 * scipy.ndimage.convolve(Gxy, f)\n\n # Analytic solution of principal direction\n denom = np.sqrt(np.power(Gxy, 2) + np.power((Gxx - Gyy), 2)\n ) + np.finfo(float).eps\n\n sin2theta = Gxy / denom # Sine and cosine of doubled angles\n cos2theta = (Gxx - Gyy) / denom\n\n if orientsmoothsigma:\n sze = np.fix(6 * orientsmoothsigma)\n if np.remainder(sze, 2) == 0:\n sze = sze + 1\n gauss = cv2.getGaussianKernel(np.int(sze), orientsmoothsigma)\n f = gauss * gauss.T\n # Smoothed sine and cosine of\n cos2theta = scipy.ndimage.convolve(cos2theta, f)\n sin2theta = scipy.ndimage.convolve(sin2theta, f) # doubled angles\n\n orientim = np.pi / 2 + np.arctan2(sin2theta, cos2theta) / 2\n return (orientim)\n\n\ndef frequest(im, orientim, windsze, minWaveLength, maxWaveLength):\n rows, cols = np.shape(im)\n\n # Find mean orientation within the block. This is done by averaging the\n # sines and cosines of the doubled angles before reconstructing the\n # angle again. This avoids wraparound problems at the origin.\n\n cosorient = np.mean(np.cos(2 * orientim))\n sinorient = np.mean(np.sin(2 * orientim))\n orient = math.atan2(sinorient, cosorient) / 2\n\n # Rotate the image block so that the ridges are vertical\n\n # ROT_mat = cv2.getRotationMatrix2D((cols/2,rows/2),orient/np.pi*180 + 90,1)\n # rotim = cv2.warpAffine(im,ROT_mat,(cols,rows))\n rotim = scipy.ndimage.rotate(\n im, orient / np.pi * 180 + 90, axes=(1, 0), reshape=False, order=3, mode='nearest')\n\n # Now crop the image so that the rotated image does not contain any\n # invalid regions. This prevents the projection down the columns\n # from being mucked up.\n\n cropsze = int(np.fix(rows / np.sqrt(2)))\n offset = int(np.fix((rows - cropsze) / 2))\n rotim = rotim[offset:offset + cropsze][:, offset:offset + cropsze]\n\n # Sum down the columns to get a projection of the grey values down\n # the ridges.\n\n proj = np.sum(rotim, axis=0)\n dilation = scipy.ndimage.grey_dilation(\n proj, windsze, structure=np.ones(windsze))\n\n temp = np.abs(dilation - proj)\n\n peak_thresh = 2\n\n maxpts = (temp < peak_thresh) & (proj > np.mean(proj))\n maxind = np.where(maxpts)\n\n rows_maxind, cols_maxind = np.shape(maxind)\n\n # Determine the spatial frequency of the ridges by divinding the\n # distance between the 1st and last peaks by the (No of peaks-1). If no\n # peaks are detected, or the wavelength is outside the allowed bounds,\n # the frequency image is set to 0\n\n if cols_maxind < 2:\n freqim = np.zeros(im.shape)\n else:\n NoOfPeaks = cols_maxind\n waveLength = (maxind[0][cols_maxind - 1] - maxind[0][0]) / (NoOfPeaks - 1)\n if waveLength >= minWaveLength and waveLength <= maxWaveLength:\n freqim = 1 / np.double(waveLength) * np.ones(im.shape)\n else:\n freqim = np.zeros(im.shape)\n\n return freqim\n\n\ndef ridge_freq(im, mask, orient, blksze, windsze, minWaveLength, maxWaveLength):\n rows, cols = im.shape\n freq = np.zeros((rows, cols))\n\n for r in range(0, rows - blksze, blksze):\n for c in range(0, cols - blksze, blksze):\n blkim = im[r:r + blksze][:, c:c + blksze]\n blkor = orient[r:r + blksze][:, c:c + blksze]\n\n freq[r:r + blksze][:, c:c +\n blksze] = frequest(blkim, blkor, windsze, minWaveLength, maxWaveLength)\n\n freq = freq * mask\n freq_1d = np.reshape(freq, (1, rows * cols))\n ind = np.where(freq_1d > 0)\n\n ind = np.array(ind)\n ind = ind[1, :]\n\n non_zero_elems_in_freq = freq_1d[0][ind]\n\n meanfreq = np.mean(non_zero_elems_in_freq)\n # does not work properly\n medianfreq = np.median(non_zero_elems_in_freq)\n return freq, meanfreq\n\n\ndef ridge_filter(im, orient, freq, kx, ky):\n angleInc = 3\n im = np.double(im)\n rows, cols = im.shape\n new_im = np.zeros((rows, cols))\n\n freq_1d = np.reshape(freq, (1, rows * cols))\n ind = np.where(freq_1d > 0)\n\n ind = np.array(ind)\n ind = ind[1, :]\n\n # Round the array of frequencies to the nearest 0.01 to reduce the\n # number of distinct frequencies we have to deal with.\n\n non_zero_elems_in_freq = freq_1d[0][ind]\n non_zero_elems_in_freq = np.double(\n np.round((non_zero_elems_in_freq * 100))) / 100\n\n unfreq = np.unique(non_zero_elems_in_freq)\n\n # Generate filters corresponding to these distinct frequencies and\n # orientations in 'angleInc' increments.\n\n sigmax = 1 / unfreq[0] * kx\n sigmay = 1 / unfreq[0] * ky\n\n sze = np.round(3 * np.max([sigmax, sigmay]))\n\n x, y = np.meshgrid(np.linspace(-sze, sze, (2 * sze + 1)),\n np.linspace(-sze, sze, (2 * sze + 1)))\n\n reffilter = np.exp(-((np.power(x, 2)) / (sigmax * sigmax) + (np.power(y, 2)) / (sigmay * sigmay))\n ) * np.cos(2 * np.pi * unfreq[0] * x) # this is the original gabor filter\n\n filt_rows, filt_cols = reffilter.shape\n\n gabor_filter = np.array(np.zeros((180 // angleInc, filt_rows, filt_cols)))\n\n for o in range(0, 180 // angleInc):\n # Generate rotated versions of the filter. Note orientation\n # image provides orientation *along* the ridges, hence +90\n # degrees, and imrotate requires angles +ve anticlockwise, hence\n # the minus sign.\n\n rot_filt = scipy.ndimage.rotate(reffilter, -(o * angleInc + 90), reshape=False)\n gabor_filter[o] = rot_filt\n\n # Find indices of matrix points greater than maxsze from the image\n # boundary\n\n maxsze = int(sze)\n\n temp = freq > 0\n validr, validc = np.where(temp)\n\n temp1 = validr > maxsze\n temp2 = validr < rows - maxsze\n temp3 = validc > maxsze\n temp4 = validc < cols - maxsze\n\n final_temp = temp1 & temp2 & temp3 & temp4\n\n finalind = np.where(final_temp)\n\n # Convert orientation matrix values from radians to an index value\n # that corresponds to round(degrees/angleInc)\n\n maxorient_index = np.round(180 / angleInc)\n orient_index = np.round(orient / np.pi * 180 / angleInc)\n\n # do the filtering\n\n for i in range(0, rows):\n for j in range(0, cols):\n if orient_index[i][j] < 1:\n orient_index[i][j] = orient_index[i][j] + maxorient_index\n if orient_index[i][j] > maxorient_index:\n orient_index[i][j] = orient_index[i][j] - maxorient_index\n finalind_rows, finalind_cols = np.shape(finalind)\n sze = int(sze)\n for k in range(0, finalind_cols):\n r = validr[finalind[0][k]]\n c = validc[finalind[0][k]]\n\n img_block = im[r - sze:r + sze + 1][:, c - sze:c + sze + 1]\n\n new_im[r][c] = np.sum(\n img_block * gabor_filter[int(orient_index[r][c]) - 1])\n\n return new_im\n\n\ndef image_enhance(img):\n blksze = 16\n thresh = 0.1\n # normalise the image and find a ROI\n normim, mask = ridge_segment(img, blksze, thresh)\n\n gradientsigma = 1\n blocksigma = 7\n orientsmoothsigma = 7\n # find orientation of every pixel\n orientim = ridge_orient(normim, gradientsigma,\n blocksigma, orientsmoothsigma)\n\n blksze = 38\n windsze = 5\n min_wave_length = 5\n max_wave_length = 15\n # find the overall frequency of ridges\n freq, medfreq = ridge_freq(\n normim, mask, orientim, blksze, windsze, min_wave_length, max_wave_length)\n\n freq = medfreq * mask\n kx = ky = 0.65\n # create gabor filter and do the actual filtering\n new_im = ridge_filter(normim, orientim, freq, kx, ky)\n\n return (new_im < -3)\n\n\ndef gabor_enhance(in_path, out_dir='./'):\n img = cv2.imread(in_path, 0)\n enhanced_img = image_enhance(img)\n enhanced_img = np.invert(enhanced_img)\n # print('saving the image')\n img = enhanced_img * 255\n base_image_name = os.path.splitext(os.path.basename(in_path))[0]\n prefix = base_image_name.split('_normal')[0]\n img_out = out_dir + prefix + '_enhanced.png'\n # img.save(base_image_name + \"_enhanced.png\", \"PNG\")\n cv2.imwrite(img_out, img)\n return img_out\n\n\n", "step-ids": [ 5, 7, 8, 9, 10 ] }
[ 5, 7, 8, 9, 10 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> print('START') <|reserved_special_token_0|> print(' - Imports data and formats the data') <|reserved_special_token_0|> timeseries_to_supervised(df_train, n_past, n_future) <|reserved_special_token_0|> if with_without == 'with training': print(' - Training the LSTM model') model_trainer(df_train, n_past, n_future, model_name) print(' - Loading the LSTM model') <|reserved_special_token_0|> prediction_run_forward(df_predict, target_date, scaler, model) <|reserved_special_token_0|> print('Price of WTI oil on {}: $ {}'.format(target_date, target_WTI_price)) if show_plot == 'yes': data_plot() plot_real_prediction(df_train) plot_prediction(df_predict, target_WTI_price, target_date) print('END') <|reserved_special_token_1|> <|reserved_special_token_0|> with_without = 'without training' show_plot = 'yes' print('START') n_past = 8 n_future = 1 target_date = '2018-11-16' past = ['t'] + [('t-' + str(i)) for i in range(1, n_past)] future = [('t+' + str(i)) for i in range(1, n_future + 1)] print(' - Imports data and formats the data') data = data_import() df = data_imputing(data) df_train, df_predict = train_predict_split(df, n_past, n_future) scaler = data_scaler(df_train) timeseries_to_supervised(df_train, n_past, n_future) model_name = 'WTI_oil_price.mdl' if with_without == 'with training': print(' - Training the LSTM model') model_trainer(df_train, n_past, n_future, model_name) print(' - Loading the LSTM model') model = tf.keras.models.load_model(model_name, custom_objects=None, compile =True) df_train = make_many_predictions(df_train, model, past, n_future) df_train = real_price_prediction(df_train, scaler) prediction_run_forward(df_predict, target_date, scaler, model) target_WTI_price = df_predict[df_predict['DATE'] == target_date]['WTI'].values[ 0] print('Price of WTI oil on {}: $ {}'.format(target_date, target_WTI_price)) if show_plot == 'yes': data_plot() plot_real_prediction(df_train) plot_prediction(df_predict, target_WTI_price, target_date) print('END') <|reserved_special_token_1|> from oil_prices import * with_without = 'without training' show_plot = 'yes' print('START') n_past = 8 n_future = 1 target_date = '2018-11-16' past = ['t'] + [('t-' + str(i)) for i in range(1, n_past)] future = [('t+' + str(i)) for i in range(1, n_future + 1)] print(' - Imports data and formats the data') data = data_import() df = data_imputing(data) df_train, df_predict = train_predict_split(df, n_past, n_future) scaler = data_scaler(df_train) timeseries_to_supervised(df_train, n_past, n_future) model_name = 'WTI_oil_price.mdl' if with_without == 'with training': print(' - Training the LSTM model') model_trainer(df_train, n_past, n_future, model_name) print(' - Loading the LSTM model') model = tf.keras.models.load_model(model_name, custom_objects=None, compile =True) df_train = make_many_predictions(df_train, model, past, n_future) df_train = real_price_prediction(df_train, scaler) prediction_run_forward(df_predict, target_date, scaler, model) target_WTI_price = df_predict[df_predict['DATE'] == target_date]['WTI'].values[ 0] print('Price of WTI oil on {}: $ {}'.format(target_date, target_WTI_price)) if show_plot == 'yes': data_plot() plot_real_prediction(df_train) plot_prediction(df_predict, target_WTI_price, target_date) print('END') <|reserved_special_token_1|> from oil_prices import * with_without = 'without training' show_plot = 'yes' print('START') # Defining the past and future sequences for the LSTM training n_past = 8 n_future = 1 target_date = '2018-11-16' past = ['t']+['t-'+str(i) for i in range(1,n_past)] future = ['t+'+str(i) for i in range(1,n_future+1)] # Importing and feature engineering data print(' - Imports data and formats the data') data = data_import() df = data_imputing(data) df_train, df_predict = train_predict_split(df, n_past, n_future) scaler = data_scaler(df_train) timeseries_to_supervised(df_train, n_past, n_future) # Training the model anew if needed, otherwise, just loaded a pre-trained model model_name = 'WTI_oil_price.mdl' if with_without == 'with training': print(' - Training the LSTM model') model_trainer(df_train, n_past, n_future, model_name) print(' - Loading the LSTM model') model = tf.keras.models.load_model(model_name, custom_objects=None, compile=True) # Validating the neural net by predicting all of the set and comparing with the observed data df_train = make_many_predictions(df_train, model, past, n_future) df_train = real_price_prediction(df_train, scaler) # Predicting the oil price on Friday, November 16th, 2018. prediction_run_forward(df_predict, target_date, scaler, model) target_WTI_price = df_predict[df_predict['DATE'] == target_date]['WTI'].values[0] print('Price of WTI oil on {}: $ {}'.format(target_date, target_WTI_price)) if show_plot == 'yes': data_plot() plot_real_prediction(df_train) plot_prediction(df_predict, target_WTI_price, target_date) print('END')
flexible
{ "blob_id": "ec6067cc86b6ac702123d13911cc4ab97be6a857", "index": 4077, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint('START')\n<mask token>\nprint(' - Imports data and formats the data')\n<mask token>\ntimeseries_to_supervised(df_train, n_past, n_future)\n<mask token>\nif with_without == 'with training':\n print(' - Training the LSTM model')\n model_trainer(df_train, n_past, n_future, model_name)\nprint(' - Loading the LSTM model')\n<mask token>\nprediction_run_forward(df_predict, target_date, scaler, model)\n<mask token>\nprint('Price of WTI oil on {}: $ {}'.format(target_date, target_WTI_price))\nif show_plot == 'yes':\n data_plot()\n plot_real_prediction(df_train)\n plot_prediction(df_predict, target_WTI_price, target_date)\nprint('END')\n", "step-3": "<mask token>\nwith_without = 'without training'\nshow_plot = 'yes'\nprint('START')\nn_past = 8\nn_future = 1\ntarget_date = '2018-11-16'\npast = ['t'] + [('t-' + str(i)) for i in range(1, n_past)]\nfuture = [('t+' + str(i)) for i in range(1, n_future + 1)]\nprint(' - Imports data and formats the data')\ndata = data_import()\ndf = data_imputing(data)\ndf_train, df_predict = train_predict_split(df, n_past, n_future)\nscaler = data_scaler(df_train)\ntimeseries_to_supervised(df_train, n_past, n_future)\nmodel_name = 'WTI_oil_price.mdl'\nif with_without == 'with training':\n print(' - Training the LSTM model')\n model_trainer(df_train, n_past, n_future, model_name)\nprint(' - Loading the LSTM model')\nmodel = tf.keras.models.load_model(model_name, custom_objects=None, compile\n =True)\ndf_train = make_many_predictions(df_train, model, past, n_future)\ndf_train = real_price_prediction(df_train, scaler)\nprediction_run_forward(df_predict, target_date, scaler, model)\ntarget_WTI_price = df_predict[df_predict['DATE'] == target_date]['WTI'].values[\n 0]\nprint('Price of WTI oil on {}: $ {}'.format(target_date, target_WTI_price))\nif show_plot == 'yes':\n data_plot()\n plot_real_prediction(df_train)\n plot_prediction(df_predict, target_WTI_price, target_date)\nprint('END')\n", "step-4": "from oil_prices import *\nwith_without = 'without training'\nshow_plot = 'yes'\nprint('START')\nn_past = 8\nn_future = 1\ntarget_date = '2018-11-16'\npast = ['t'] + [('t-' + str(i)) for i in range(1, n_past)]\nfuture = [('t+' + str(i)) for i in range(1, n_future + 1)]\nprint(' - Imports data and formats the data')\ndata = data_import()\ndf = data_imputing(data)\ndf_train, df_predict = train_predict_split(df, n_past, n_future)\nscaler = data_scaler(df_train)\ntimeseries_to_supervised(df_train, n_past, n_future)\nmodel_name = 'WTI_oil_price.mdl'\nif with_without == 'with training':\n print(' - Training the LSTM model')\n model_trainer(df_train, n_past, n_future, model_name)\nprint(' - Loading the LSTM model')\nmodel = tf.keras.models.load_model(model_name, custom_objects=None, compile\n =True)\ndf_train = make_many_predictions(df_train, model, past, n_future)\ndf_train = real_price_prediction(df_train, scaler)\nprediction_run_forward(df_predict, target_date, scaler, model)\ntarget_WTI_price = df_predict[df_predict['DATE'] == target_date]['WTI'].values[\n 0]\nprint('Price of WTI oil on {}: $ {}'.format(target_date, target_WTI_price))\nif show_plot == 'yes':\n data_plot()\n plot_real_prediction(df_train)\n plot_prediction(df_predict, target_WTI_price, target_date)\nprint('END')\n", "step-5": "from oil_prices import *\n\n\nwith_without = 'without training'\nshow_plot = 'yes'\n\nprint('START')\n\n# Defining the past and future sequences for the LSTM training\nn_past = 8\nn_future = 1\ntarget_date = '2018-11-16'\npast = ['t']+['t-'+str(i) for i in range(1,n_past)]\nfuture = ['t+'+str(i) for i in range(1,n_future+1)]\n\n# Importing and feature engineering data\nprint(' - Imports data and formats the data')\ndata = data_import()\ndf = data_imputing(data)\ndf_train, df_predict = train_predict_split(df, n_past, n_future)\nscaler = data_scaler(df_train)\ntimeseries_to_supervised(df_train, n_past, n_future)\n\n# Training the model anew if needed, otherwise, just loaded a pre-trained model\nmodel_name = 'WTI_oil_price.mdl'\nif with_without == 'with training':\n\tprint(' - Training the LSTM model')\n\tmodel_trainer(df_train, n_past, n_future, model_name)\nprint(' - Loading the LSTM model')\nmodel = tf.keras.models.load_model(model_name, custom_objects=None, compile=True)\n\n# Validating the neural net by predicting all of the set and comparing with the observed data\ndf_train = make_many_predictions(df_train, model, past, n_future)\ndf_train = real_price_prediction(df_train, scaler)\n\n\n# Predicting the oil price on Friday, November 16th, 2018.\nprediction_run_forward(df_predict, target_date, scaler, model)\ntarget_WTI_price = df_predict[df_predict['DATE'] == target_date]['WTI'].values[0]\nprint('Price of WTI oil on {}: $ {}'.format(target_date, target_WTI_price))\n\nif show_plot == 'yes':\n\tdata_plot()\n\tplot_real_prediction(df_train)\n\tplot_prediction(df_predict, target_WTI_price, target_date)\n\nprint('END')\n\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> class NFO: <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def __repr__(self) ->str: return '<{c} {attrs}>'.format(c=self.__class__.__name__, attrs=' '. join('{}={!r}'.format(k, v) for k, v in self.__dict__.items())) def run(self, template: str, art: Optional[str]=None, **kwargs: Any) ->str: """ Evaluate and apply formatting on template, apply any art if provided. Any additional parameters are passed as extra variables to the template. The extra variables have priority when there's conflicting variable names. """ variables = self.__dict__ variables.update(kwargs) template = CustomFormats().format(template, **variables) if art: art = art.format(nfo=template) template = art for m in re.finditer('<\\?([01])\\?([\\D\\d]*?)\\?>', template): template = template.replace(m.group(0), m.group(2) if int(m. group(1)) else '') template = '\n'.join(map(str.rstrip, template.splitlines(keepends= False))) return template def set_config(self, file: str, **config: Any) ->None: self.file = file self.media_info = MediaInfo.parse(self.file) self.fanart_api_key = config.get('fanart_api_key') self.source = config.get('source') self.note = config.get('note') self.preview = config.get('preview') self.season = config.get('season') self.episode, self.episode_name = config.get('episode') or (None, None) self.episodes = self.get_tv_episodes() self.release_name = self.get_release_name() self.videos = self.media_info.video_tracks self.audio = self.media_info.audio_tracks self.subtitles = self.media_info.text_tracks tracks_without_language = [x for x in self.videos + self.audio + self.subtitles if not x.language or x.language == 'und'] if tracks_without_language: print( 'The following tracks have no language tag! All tracks need a language tag!' ) for track in tracks_without_language: print( f'{track.track_type} Track #{track.track_id} ({track.format}, {track.bit_rate / 1000} kb/s)' ) print( """Yes, even Video Track's have language e.g., Credits, Signs, Letters, Different Intro Sequence, etc. Don't forget to verify and add language tags to the rest of the files too!""" ) sys.exit(1) chapters = next(iter(self.media_info.menu_tracks), None) if chapters: self.chapters = {'.'.join([k.replace('_', '.')[:-3], k[-3:]]): v.strip(':') for k, v in chapters.to_data().items() if f"1{k.replace('_', '')}".isdigit()} self.chapters_numbered = all(x.split(':', 1)[-1].lower() in [ f'chapter {i + 1}', f'chapter {str(i + 1).zfill(2)}'] for i, x in enumerate(self.chapters.values())) else: self.chapters = {} self.chapters_numbered = False self.imdb = self.get_imdb_id(config.get('imdb')) self.tmdb = self.get_tmdb_id(config.get('tmdb')) self.tvdb = self.get_tvdb_id(config.get('tvdb')) self.title_name, self.title_year = self.get_title_name_year() self.banner_image = self.get_banner_image(self.tvdb ) if self.tvdb and self.fanart_api_key else None self.preview_images = self.get_preview_images(self.preview ) if self.preview else [] def get_imdb_id(self, imdb_id: Any) ->str: """ Get an IMDB ID from either the media's global tags, or the config. Since IMDB IDs are required for this project, it will bug the user for one interactively if not found. """ if not imdb_id: general_track = self.media_info.general_tracks[0].to_data() imdb_id = general_track.get('imdb') if not imdb_id: print('No IMDB ID was provided but is required...') while not imdb_id or not isinstance(imdb_id, str): user_id = input("IMDB ID (e.g., 'tt0487831'): ") if not self.IMDB_ID_T.match(user_id): print(f'The provided IMDB ID {user_id!r} is not valid...') print( "Expected e.g., 'tt0487831', 'tt10810424', (include the 'tt')." ) else: imdb_id = user_id return imdb_id def get_tmdb_id(self, tmdb_id: Any) ->Optional[str]: """ Get a TMDB ID from either the media's global tags, or the config. It will raise a ValueError if the provided ID is invalid. """ if not tmdb_id: general_track = self.media_info.general_tracks[0].to_data() tmdb_id = general_track.get('tmdb') if not tmdb_id: print('Warning: No TMDB ID was provided...') return None if not self.TMDB_ID_T.match(tmdb_id) or not isinstance(tmdb_id, str): print(f'The provided TMDB ID {tmdb_id!r} is not valid...') print( "Expected e.g., 'tv/2490', 'movie/14836', (include the 'tv/' or 'movie/')." ) raise ValueError('Invalid TMDB ID') return tmdb_id def get_tvdb_id(self, tvdb_id: Any) ->Optional[int]: """ Get a TVDB ID from either the media's global tags, or the config. It will raise a ValueError if the provided ID is invalid. """ if not tvdb_id: general_track = self.media_info.general_tracks[0].to_data() tvdb_id = general_track.get('tvdb') if not tvdb_id: print('Warning: No TVDB ID was provided...') return None if isinstance(tvdb_id, int): tvdb_id = str(tvdb_id) if not self.TVDB_ID_T.match(tvdb_id) or not isinstance(tvdb_id, str): print(f'The provided TVDB ID {tvdb_id!r} is not valid...') print( "Expected e.g., '79216', '1395', (not the url slug e.g., 'the-office-us')." ) raise ValueError('Invalid TVDB ID') return int(tvdb_id) <|reserved_special_token_0|> <|reserved_special_token_0|> def get_release_name(self) ->str: """ Retrieve the release name based on the file used during MediaInfo. If a season was specified, but an episode number was not, it presumes the release is a Pack. Hence when pack, it uses the parent folder's name as the release name. """ if self.season is not None and self.episode is None: return os.path.basename(os.path.dirname(self.file)) return os.path.splitext(os.path.basename(self.file))[0] def get_banner_image(self, tvdb_id: int) ->Optional[str]: """ Get a wide banner image from fanart.tv. Currently restricts banners to English-only. """ if not tvdb_id: return None if not self.fanart_api_key: raise ValueError('Need Fanart.tv api key for TV titles!') r = self.session.get( f'http://webservice.fanart.tv/v3/tv/{tvdb_id}?api_key={self.fanart_api_key}' ) if r.status_code == 404: return None res = r.json() error = res.get('error message') if error: if error == 'Not found': return None raise ValueError( f'An unexpected error occurred while calling Fanart.tv, {res}') banner = next((x['url'] for x in res.get('tvbanner') or [] if x[ 'lang'] == sorted(self.audio, key=lambda x: x.streamorder)[0]. language), None) return banner def get_preview_images(self, url: str) ->List[Dict[str, str]]: if not url: return [] images = [] for domain in ['imgbox.com', 'beyondhd.co']: if domain not in url.lower(): continue page = self.session.get(url).text if domain == 'imgbox.com': for m in re.finditer( 'src="(https://thumbs2.imgbox.com.+/)(\\w+)_b.([^"]+)', page): images.append({'url': f'https://imgbox.com/{m.group(2)}', 'src': f'{m.group(1)}{m.group(2)}_t.{m.group(3)}'}) elif domain == 'beyondhd.co': for m in re.finditer( '/image/([^"]+)"\\D+src="(https://.*beyondhd.co/images.+/(\\w+).md.[^"]+)' , page): images.append({'url': f'https://beyondhd.co/image/{m.group(1)}', 'src': m .group(2)}) break return images def get_video_print(self, videos: List[Track]) ->List[List[str]]: if not videos: return [['--']] data = [] for video in videos: codec = {'MPEG Video': f"MPEG-{(video.format_version or '').replace('Version ', '')}" }.get(video.format, video.format) scan_overview = video.scan_type vst = False if codec in ['MPEG-1', 'MPEG-2']: d2v = D2V.load(Path(self.file)) self.file = d2v.path flags = [f for line in [[dict(**y, vob=x['vob'], cell=x[ 'cell']) for y in x['flags']] for x in d2v.data] for f in line] interlaced_percent = sum(1 for f in flags if not f[ 'progressive_frame']) / len(flags) * 100 if interlaced_percent == 100: scan_overview = 'Interlaced (CST)' else: scan_overview = ( f'{round(interlaced_percent, 2)}% Interlaced (VST)') vst = True for ext in ['log', 'd2v', 'mpg', 'mpeg']: fp = os.path.splitext(self.file)[0] + '.' + ext if os.path.exists(fp): os.unlink(fp) line_1 = ( '- {language}, {codec} ({profile}) {width}x{height} ({aspect}) @ {bitrate}' .format(language=pycountry.languages.get(alpha_2=video. language).name, codec=codec, profile=video.format_profile, width=video.width, height=video.height, aspect=video. other_display_aspect_ratio[0], bitrate= f"{video.other_bit_rate[0]}{f' ({video.bit_rate_mode})' if video.bit_rate_mode else ''}" )) line_2 = ( ' {fps} FPS ({fps_mode}), {color_space}{subsampling}P{bit_depth}, {scan}' .format(fps=f'{video.framerate_num}/{video.framerate_den}' if video.framerate_num else video.frame_rate, fps_mode='VFR' if vst else video.frame_rate_mode, color_space=video. color_space, subsampling=video.chroma_subsampling.replace( ':', ''), bit_depth=video.bit_depth, scan=scan_overview)) data.append([line_1, line_2]) return data def get_audio_print(self, audio: List[Track]) ->List[str]: if not audio: return ['--'] data = [] for t in audio: if t.title and 'Commentary' in t.title: title = t.title else: title = pycountry.languages.get(alpha_2=t.language).name if t.channel_layout: channels = float(sum(self.AUDIO_CHANNEL_LAYOUT_WEIGHT.get(x, 1) for x in t.channel_layout.split(' '))) else: channels = float(t.channel_s) bit_rate_mode = f' ({t.bit_rate_mode})' if t.bit_rate_mode else '' l1 = ( f'- {title}, {t.format} {channels} @ {t.other_bit_rate[0]}{bit_rate_mode}' ) data += [(' ' + x if i > 0 else x) for i, x in enumerate( textwrap.wrap(l1, 64))] return data <|reserved_special_token_0|> <|reserved_special_token_0|> def get_chapter_print_short(self, chapters: Dict[str, str]) ->str: if not chapters: return 'No' if self.chapters_numbered: return f'Yes (Numbered 01-{str(len(chapters)).zfill(2)})' return 'Yes (Named)' @staticmethod def get_session() ->requests.Session: session = requests.Session() session.headers.update({'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0' , 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' , 'Accept-Language': 'en-US,en;q=0.5', 'DNT': '1', 'UPGRADE-INSECURE-REQUESTS': '1'}) return session <|reserved_special_token_1|> <|reserved_special_token_0|> class NFO: <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def __repr__(self) ->str: return '<{c} {attrs}>'.format(c=self.__class__.__name__, attrs=' '. join('{}={!r}'.format(k, v) for k, v in self.__dict__.items())) def run(self, template: str, art: Optional[str]=None, **kwargs: Any) ->str: """ Evaluate and apply formatting on template, apply any art if provided. Any additional parameters are passed as extra variables to the template. The extra variables have priority when there's conflicting variable names. """ variables = self.__dict__ variables.update(kwargs) template = CustomFormats().format(template, **variables) if art: art = art.format(nfo=template) template = art for m in re.finditer('<\\?([01])\\?([\\D\\d]*?)\\?>', template): template = template.replace(m.group(0), m.group(2) if int(m. group(1)) else '') template = '\n'.join(map(str.rstrip, template.splitlines(keepends= False))) return template def set_config(self, file: str, **config: Any) ->None: self.file = file self.media_info = MediaInfo.parse(self.file) self.fanart_api_key = config.get('fanart_api_key') self.source = config.get('source') self.note = config.get('note') self.preview = config.get('preview') self.season = config.get('season') self.episode, self.episode_name = config.get('episode') or (None, None) self.episodes = self.get_tv_episodes() self.release_name = self.get_release_name() self.videos = self.media_info.video_tracks self.audio = self.media_info.audio_tracks self.subtitles = self.media_info.text_tracks tracks_without_language = [x for x in self.videos + self.audio + self.subtitles if not x.language or x.language == 'und'] if tracks_without_language: print( 'The following tracks have no language tag! All tracks need a language tag!' ) for track in tracks_without_language: print( f'{track.track_type} Track #{track.track_id} ({track.format}, {track.bit_rate / 1000} kb/s)' ) print( """Yes, even Video Track's have language e.g., Credits, Signs, Letters, Different Intro Sequence, etc. Don't forget to verify and add language tags to the rest of the files too!""" ) sys.exit(1) chapters = next(iter(self.media_info.menu_tracks), None) if chapters: self.chapters = {'.'.join([k.replace('_', '.')[:-3], k[-3:]]): v.strip(':') for k, v in chapters.to_data().items() if f"1{k.replace('_', '')}".isdigit()} self.chapters_numbered = all(x.split(':', 1)[-1].lower() in [ f'chapter {i + 1}', f'chapter {str(i + 1).zfill(2)}'] for i, x in enumerate(self.chapters.values())) else: self.chapters = {} self.chapters_numbered = False self.imdb = self.get_imdb_id(config.get('imdb')) self.tmdb = self.get_tmdb_id(config.get('tmdb')) self.tvdb = self.get_tvdb_id(config.get('tvdb')) self.title_name, self.title_year = self.get_title_name_year() self.banner_image = self.get_banner_image(self.tvdb ) if self.tvdb and self.fanart_api_key else None self.preview_images = self.get_preview_images(self.preview ) if self.preview else [] def get_imdb_id(self, imdb_id: Any) ->str: """ Get an IMDB ID from either the media's global tags, or the config. Since IMDB IDs are required for this project, it will bug the user for one interactively if not found. """ if not imdb_id: general_track = self.media_info.general_tracks[0].to_data() imdb_id = general_track.get('imdb') if not imdb_id: print('No IMDB ID was provided but is required...') while not imdb_id or not isinstance(imdb_id, str): user_id = input("IMDB ID (e.g., 'tt0487831'): ") if not self.IMDB_ID_T.match(user_id): print(f'The provided IMDB ID {user_id!r} is not valid...') print( "Expected e.g., 'tt0487831', 'tt10810424', (include the 'tt')." ) else: imdb_id = user_id return imdb_id def get_tmdb_id(self, tmdb_id: Any) ->Optional[str]: """ Get a TMDB ID from either the media's global tags, or the config. It will raise a ValueError if the provided ID is invalid. """ if not tmdb_id: general_track = self.media_info.general_tracks[0].to_data() tmdb_id = general_track.get('tmdb') if not tmdb_id: print('Warning: No TMDB ID was provided...') return None if not self.TMDB_ID_T.match(tmdb_id) or not isinstance(tmdb_id, str): print(f'The provided TMDB ID {tmdb_id!r} is not valid...') print( "Expected e.g., 'tv/2490', 'movie/14836', (include the 'tv/' or 'movie/')." ) raise ValueError('Invalid TMDB ID') return tmdb_id def get_tvdb_id(self, tvdb_id: Any) ->Optional[int]: """ Get a TVDB ID from either the media's global tags, or the config. It will raise a ValueError if the provided ID is invalid. """ if not tvdb_id: general_track = self.media_info.general_tracks[0].to_data() tvdb_id = general_track.get('tvdb') if not tvdb_id: print('Warning: No TVDB ID was provided...') return None if isinstance(tvdb_id, int): tvdb_id = str(tvdb_id) if not self.TVDB_ID_T.match(tvdb_id) or not isinstance(tvdb_id, str): print(f'The provided TVDB ID {tvdb_id!r} is not valid...') print( "Expected e.g., '79216', '1395', (not the url slug e.g., 'the-office-us')." ) raise ValueError('Invalid TVDB ID') return int(tvdb_id) def get_title_name_year(self) ->Tuple[str, str]: """Scrape Title Name and Year (including e.g. 2019-) from IMDB""" r = self.session.get(f'https://www.imdb.com/title/{self.imdb}') if r.status_code != 200: raise ValueError( f'An unexpected error occurred getting IMDB Title Page [{r.status_code}]' ) imdb_page = html.unescape(r.text) imdb_title = re.search( '<title>(?P<name>.+) \\(((?P<type>TV (Movie|Series|Mini[- ]Series|Short|Episode) |Video |Short |)(?P<year>(\\d{4})(|– |–\\d{4})))\\) - IMDb</title>' , imdb_page) if not imdb_title: raise ValueError( f'Could not scrape Movie Title or Year for {self.imdb}...') return imdb_title.group('name').strip(), imdb_title.group('year' ).strip() <|reserved_special_token_0|> def get_release_name(self) ->str: """ Retrieve the release name based on the file used during MediaInfo. If a season was specified, but an episode number was not, it presumes the release is a Pack. Hence when pack, it uses the parent folder's name as the release name. """ if self.season is not None and self.episode is None: return os.path.basename(os.path.dirname(self.file)) return os.path.splitext(os.path.basename(self.file))[0] def get_banner_image(self, tvdb_id: int) ->Optional[str]: """ Get a wide banner image from fanart.tv. Currently restricts banners to English-only. """ if not tvdb_id: return None if not self.fanart_api_key: raise ValueError('Need Fanart.tv api key for TV titles!') r = self.session.get( f'http://webservice.fanart.tv/v3/tv/{tvdb_id}?api_key={self.fanart_api_key}' ) if r.status_code == 404: return None res = r.json() error = res.get('error message') if error: if error == 'Not found': return None raise ValueError( f'An unexpected error occurred while calling Fanart.tv, {res}') banner = next((x['url'] for x in res.get('tvbanner') or [] if x[ 'lang'] == sorted(self.audio, key=lambda x: x.streamorder)[0]. language), None) return banner def get_preview_images(self, url: str) ->List[Dict[str, str]]: if not url: return [] images = [] for domain in ['imgbox.com', 'beyondhd.co']: if domain not in url.lower(): continue page = self.session.get(url).text if domain == 'imgbox.com': for m in re.finditer( 'src="(https://thumbs2.imgbox.com.+/)(\\w+)_b.([^"]+)', page): images.append({'url': f'https://imgbox.com/{m.group(2)}', 'src': f'{m.group(1)}{m.group(2)}_t.{m.group(3)}'}) elif domain == 'beyondhd.co': for m in re.finditer( '/image/([^"]+)"\\D+src="(https://.*beyondhd.co/images.+/(\\w+).md.[^"]+)' , page): images.append({'url': f'https://beyondhd.co/image/{m.group(1)}', 'src': m .group(2)}) break return images def get_video_print(self, videos: List[Track]) ->List[List[str]]: if not videos: return [['--']] data = [] for video in videos: codec = {'MPEG Video': f"MPEG-{(video.format_version or '').replace('Version ', '')}" }.get(video.format, video.format) scan_overview = video.scan_type vst = False if codec in ['MPEG-1', 'MPEG-2']: d2v = D2V.load(Path(self.file)) self.file = d2v.path flags = [f for line in [[dict(**y, vob=x['vob'], cell=x[ 'cell']) for y in x['flags']] for x in d2v.data] for f in line] interlaced_percent = sum(1 for f in flags if not f[ 'progressive_frame']) / len(flags) * 100 if interlaced_percent == 100: scan_overview = 'Interlaced (CST)' else: scan_overview = ( f'{round(interlaced_percent, 2)}% Interlaced (VST)') vst = True for ext in ['log', 'd2v', 'mpg', 'mpeg']: fp = os.path.splitext(self.file)[0] + '.' + ext if os.path.exists(fp): os.unlink(fp) line_1 = ( '- {language}, {codec} ({profile}) {width}x{height} ({aspect}) @ {bitrate}' .format(language=pycountry.languages.get(alpha_2=video. language).name, codec=codec, profile=video.format_profile, width=video.width, height=video.height, aspect=video. other_display_aspect_ratio[0], bitrate= f"{video.other_bit_rate[0]}{f' ({video.bit_rate_mode})' if video.bit_rate_mode else ''}" )) line_2 = ( ' {fps} FPS ({fps_mode}), {color_space}{subsampling}P{bit_depth}, {scan}' .format(fps=f'{video.framerate_num}/{video.framerate_den}' if video.framerate_num else video.frame_rate, fps_mode='VFR' if vst else video.frame_rate_mode, color_space=video. color_space, subsampling=video.chroma_subsampling.replace( ':', ''), bit_depth=video.bit_depth, scan=scan_overview)) data.append([line_1, line_2]) return data def get_audio_print(self, audio: List[Track]) ->List[str]: if not audio: return ['--'] data = [] for t in audio: if t.title and 'Commentary' in t.title: title = t.title else: title = pycountry.languages.get(alpha_2=t.language).name if t.channel_layout: channels = float(sum(self.AUDIO_CHANNEL_LAYOUT_WEIGHT.get(x, 1) for x in t.channel_layout.split(' '))) else: channels = float(t.channel_s) bit_rate_mode = f' ({t.bit_rate_mode})' if t.bit_rate_mode else '' l1 = ( f'- {title}, {t.format} {channels} @ {t.other_bit_rate[0]}{bit_rate_mode}' ) data += [(' ' + x if i > 0 else x) for i, x in enumerate( textwrap.wrap(l1, 64))] return data @staticmethod def get_subtitle_print(subs: List[Track]) ->List[str]: """ Return a list of a brief subtitle overview per-subtitle. e.g. - English, Forced, SubRip (SRT) - English, SubRip (SRT) - English, SDH, SubRip (SRT) - Spanish, Latin American (SDH), SubRip (SRT) The bit of text between the Language and the Subtitle format is the Track Title. It can be of any format, but it is recommended to be used as shown above. It will be returned as a list of strings with the `- ` already pre-pended to each entry. """ data = [] if not subs: data.append('--') for sub in subs: line_items = [] language = pycountry.languages.get(alpha_2=sub.language).name if sub.title: if language.lower() in sub.title.lower(): line_items.append(sub.title) else: line_items.append(f'{language}, {sub.title}') else: line_items.append(language) line_items.append(sub.format.replace('UTF-8', 'SubRip (SRT)')) line = '- ' + ', '.join(line_items) data += [(' ' + x if i > 0 else x) for i, x in enumerate( textwrap.wrap(line, 64))] return data <|reserved_special_token_0|> def get_chapter_print_short(self, chapters: Dict[str, str]) ->str: if not chapters: return 'No' if self.chapters_numbered: return f'Yes (Numbered 01-{str(len(chapters)).zfill(2)})' return 'Yes (Named)' @staticmethod def get_session() ->requests.Session: session = requests.Session() session.headers.update({'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0' , 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' , 'Accept-Language': 'en-US,en;q=0.5', 'DNT': '1', 'UPGRADE-INSECURE-REQUESTS': '1'}) return session <|reserved_special_token_1|> <|reserved_special_token_0|> class NFO: <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def __repr__(self) ->str: return '<{c} {attrs}>'.format(c=self.__class__.__name__, attrs=' '. join('{}={!r}'.format(k, v) for k, v in self.__dict__.items())) def run(self, template: str, art: Optional[str]=None, **kwargs: Any) ->str: """ Evaluate and apply formatting on template, apply any art if provided. Any additional parameters are passed as extra variables to the template. The extra variables have priority when there's conflicting variable names. """ variables = self.__dict__ variables.update(kwargs) template = CustomFormats().format(template, **variables) if art: art = art.format(nfo=template) template = art for m in re.finditer('<\\?([01])\\?([\\D\\d]*?)\\?>', template): template = template.replace(m.group(0), m.group(2) if int(m. group(1)) else '') template = '\n'.join(map(str.rstrip, template.splitlines(keepends= False))) return template def set_config(self, file: str, **config: Any) ->None: self.file = file self.media_info = MediaInfo.parse(self.file) self.fanart_api_key = config.get('fanart_api_key') self.source = config.get('source') self.note = config.get('note') self.preview = config.get('preview') self.season = config.get('season') self.episode, self.episode_name = config.get('episode') or (None, None) self.episodes = self.get_tv_episodes() self.release_name = self.get_release_name() self.videos = self.media_info.video_tracks self.audio = self.media_info.audio_tracks self.subtitles = self.media_info.text_tracks tracks_without_language = [x for x in self.videos + self.audio + self.subtitles if not x.language or x.language == 'und'] if tracks_without_language: print( 'The following tracks have no language tag! All tracks need a language tag!' ) for track in tracks_without_language: print( f'{track.track_type} Track #{track.track_id} ({track.format}, {track.bit_rate / 1000} kb/s)' ) print( """Yes, even Video Track's have language e.g., Credits, Signs, Letters, Different Intro Sequence, etc. Don't forget to verify and add language tags to the rest of the files too!""" ) sys.exit(1) chapters = next(iter(self.media_info.menu_tracks), None) if chapters: self.chapters = {'.'.join([k.replace('_', '.')[:-3], k[-3:]]): v.strip(':') for k, v in chapters.to_data().items() if f"1{k.replace('_', '')}".isdigit()} self.chapters_numbered = all(x.split(':', 1)[-1].lower() in [ f'chapter {i + 1}', f'chapter {str(i + 1).zfill(2)}'] for i, x in enumerate(self.chapters.values())) else: self.chapters = {} self.chapters_numbered = False self.imdb = self.get_imdb_id(config.get('imdb')) self.tmdb = self.get_tmdb_id(config.get('tmdb')) self.tvdb = self.get_tvdb_id(config.get('tvdb')) self.title_name, self.title_year = self.get_title_name_year() self.banner_image = self.get_banner_image(self.tvdb ) if self.tvdb and self.fanart_api_key else None self.preview_images = self.get_preview_images(self.preview ) if self.preview else [] def get_imdb_id(self, imdb_id: Any) ->str: """ Get an IMDB ID from either the media's global tags, or the config. Since IMDB IDs are required for this project, it will bug the user for one interactively if not found. """ if not imdb_id: general_track = self.media_info.general_tracks[0].to_data() imdb_id = general_track.get('imdb') if not imdb_id: print('No IMDB ID was provided but is required...') while not imdb_id or not isinstance(imdb_id, str): user_id = input("IMDB ID (e.g., 'tt0487831'): ") if not self.IMDB_ID_T.match(user_id): print(f'The provided IMDB ID {user_id!r} is not valid...') print( "Expected e.g., 'tt0487831', 'tt10810424', (include the 'tt')." ) else: imdb_id = user_id return imdb_id def get_tmdb_id(self, tmdb_id: Any) ->Optional[str]: """ Get a TMDB ID from either the media's global tags, or the config. It will raise a ValueError if the provided ID is invalid. """ if not tmdb_id: general_track = self.media_info.general_tracks[0].to_data() tmdb_id = general_track.get('tmdb') if not tmdb_id: print('Warning: No TMDB ID was provided...') return None if not self.TMDB_ID_T.match(tmdb_id) or not isinstance(tmdb_id, str): print(f'The provided TMDB ID {tmdb_id!r} is not valid...') print( "Expected e.g., 'tv/2490', 'movie/14836', (include the 'tv/' or 'movie/')." ) raise ValueError('Invalid TMDB ID') return tmdb_id def get_tvdb_id(self, tvdb_id: Any) ->Optional[int]: """ Get a TVDB ID from either the media's global tags, or the config. It will raise a ValueError if the provided ID is invalid. """ if not tvdb_id: general_track = self.media_info.general_tracks[0].to_data() tvdb_id = general_track.get('tvdb') if not tvdb_id: print('Warning: No TVDB ID was provided...') return None if isinstance(tvdb_id, int): tvdb_id = str(tvdb_id) if not self.TVDB_ID_T.match(tvdb_id) or not isinstance(tvdb_id, str): print(f'The provided TVDB ID {tvdb_id!r} is not valid...') print( "Expected e.g., '79216', '1395', (not the url slug e.g., 'the-office-us')." ) raise ValueError('Invalid TVDB ID') return int(tvdb_id) def get_title_name_year(self) ->Tuple[str, str]: """Scrape Title Name and Year (including e.g. 2019-) from IMDB""" r = self.session.get(f'https://www.imdb.com/title/{self.imdb}') if r.status_code != 200: raise ValueError( f'An unexpected error occurred getting IMDB Title Page [{r.status_code}]' ) imdb_page = html.unescape(r.text) imdb_title = re.search( '<title>(?P<name>.+) \\(((?P<type>TV (Movie|Series|Mini[- ]Series|Short|Episode) |Video |Short |)(?P<year>(\\d{4})(|– |–\\d{4})))\\) - IMDb</title>' , imdb_page) if not imdb_title: raise ValueError( f'Could not scrape Movie Title or Year for {self.imdb}...') return imdb_title.group('name').strip(), imdb_title.group('year' ).strip() def get_tv_episodes(self) ->int: """Calculate total episode count based on neighbouring same-extension files.""" return len(glob.glob(os.path.join(os.path.dirname(self.file), f'*{os.path.splitext(self.file)[-1]}'))) def get_release_name(self) ->str: """ Retrieve the release name based on the file used during MediaInfo. If a season was specified, but an episode number was not, it presumes the release is a Pack. Hence when pack, it uses the parent folder's name as the release name. """ if self.season is not None and self.episode is None: return os.path.basename(os.path.dirname(self.file)) return os.path.splitext(os.path.basename(self.file))[0] def get_banner_image(self, tvdb_id: int) ->Optional[str]: """ Get a wide banner image from fanart.tv. Currently restricts banners to English-only. """ if not tvdb_id: return None if not self.fanart_api_key: raise ValueError('Need Fanart.tv api key for TV titles!') r = self.session.get( f'http://webservice.fanart.tv/v3/tv/{tvdb_id}?api_key={self.fanart_api_key}' ) if r.status_code == 404: return None res = r.json() error = res.get('error message') if error: if error == 'Not found': return None raise ValueError( f'An unexpected error occurred while calling Fanart.tv, {res}') banner = next((x['url'] for x in res.get('tvbanner') or [] if x[ 'lang'] == sorted(self.audio, key=lambda x: x.streamorder)[0]. language), None) return banner def get_preview_images(self, url: str) ->List[Dict[str, str]]: if not url: return [] images = [] for domain in ['imgbox.com', 'beyondhd.co']: if domain not in url.lower(): continue page = self.session.get(url).text if domain == 'imgbox.com': for m in re.finditer( 'src="(https://thumbs2.imgbox.com.+/)(\\w+)_b.([^"]+)', page): images.append({'url': f'https://imgbox.com/{m.group(2)}', 'src': f'{m.group(1)}{m.group(2)}_t.{m.group(3)}'}) elif domain == 'beyondhd.co': for m in re.finditer( '/image/([^"]+)"\\D+src="(https://.*beyondhd.co/images.+/(\\w+).md.[^"]+)' , page): images.append({'url': f'https://beyondhd.co/image/{m.group(1)}', 'src': m .group(2)}) break return images def get_video_print(self, videos: List[Track]) ->List[List[str]]: if not videos: return [['--']] data = [] for video in videos: codec = {'MPEG Video': f"MPEG-{(video.format_version or '').replace('Version ', '')}" }.get(video.format, video.format) scan_overview = video.scan_type vst = False if codec in ['MPEG-1', 'MPEG-2']: d2v = D2V.load(Path(self.file)) self.file = d2v.path flags = [f for line in [[dict(**y, vob=x['vob'], cell=x[ 'cell']) for y in x['flags']] for x in d2v.data] for f in line] interlaced_percent = sum(1 for f in flags if not f[ 'progressive_frame']) / len(flags) * 100 if interlaced_percent == 100: scan_overview = 'Interlaced (CST)' else: scan_overview = ( f'{round(interlaced_percent, 2)}% Interlaced (VST)') vst = True for ext in ['log', 'd2v', 'mpg', 'mpeg']: fp = os.path.splitext(self.file)[0] + '.' + ext if os.path.exists(fp): os.unlink(fp) line_1 = ( '- {language}, {codec} ({profile}) {width}x{height} ({aspect}) @ {bitrate}' .format(language=pycountry.languages.get(alpha_2=video. language).name, codec=codec, profile=video.format_profile, width=video.width, height=video.height, aspect=video. other_display_aspect_ratio[0], bitrate= f"{video.other_bit_rate[0]}{f' ({video.bit_rate_mode})' if video.bit_rate_mode else ''}" )) line_2 = ( ' {fps} FPS ({fps_mode}), {color_space}{subsampling}P{bit_depth}, {scan}' .format(fps=f'{video.framerate_num}/{video.framerate_den}' if video.framerate_num else video.frame_rate, fps_mode='VFR' if vst else video.frame_rate_mode, color_space=video. color_space, subsampling=video.chroma_subsampling.replace( ':', ''), bit_depth=video.bit_depth, scan=scan_overview)) data.append([line_1, line_2]) return data def get_audio_print(self, audio: List[Track]) ->List[str]: if not audio: return ['--'] data = [] for t in audio: if t.title and 'Commentary' in t.title: title = t.title else: title = pycountry.languages.get(alpha_2=t.language).name if t.channel_layout: channels = float(sum(self.AUDIO_CHANNEL_LAYOUT_WEIGHT.get(x, 1) for x in t.channel_layout.split(' '))) else: channels = float(t.channel_s) bit_rate_mode = f' ({t.bit_rate_mode})' if t.bit_rate_mode else '' l1 = ( f'- {title}, {t.format} {channels} @ {t.other_bit_rate[0]}{bit_rate_mode}' ) data += [(' ' + x if i > 0 else x) for i, x in enumerate( textwrap.wrap(l1, 64))] return data @staticmethod def get_subtitle_print(subs: List[Track]) ->List[str]: """ Return a list of a brief subtitle overview per-subtitle. e.g. - English, Forced, SubRip (SRT) - English, SubRip (SRT) - English, SDH, SubRip (SRT) - Spanish, Latin American (SDH), SubRip (SRT) The bit of text between the Language and the Subtitle format is the Track Title. It can be of any format, but it is recommended to be used as shown above. It will be returned as a list of strings with the `- ` already pre-pended to each entry. """ data = [] if not subs: data.append('--') for sub in subs: line_items = [] language = pycountry.languages.get(alpha_2=sub.language).name if sub.title: if language.lower() in sub.title.lower(): line_items.append(sub.title) else: line_items.append(f'{language}, {sub.title}') else: line_items.append(language) line_items.append(sub.format.replace('UTF-8', 'SubRip (SRT)')) line = '- ' + ', '.join(line_items) data += [(' ' + x if i > 0 else x) for i, x in enumerate( textwrap.wrap(line, 64))] return data @staticmethod def get_chapter_print(chapters: Dict[str, str]) ->List[str]: if not chapters: return ['--'] return [f'- {k}: {v}' for k, v in chapters.items()] def get_chapter_print_short(self, chapters: Dict[str, str]) ->str: if not chapters: return 'No' if self.chapters_numbered: return f'Yes (Numbered 01-{str(len(chapters)).zfill(2)})' return 'Yes (Named)' @staticmethod def get_session() ->requests.Session: session = requests.Session() session.headers.update({'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0' , 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' , 'Accept-Language': 'en-US,en;q=0.5', 'DNT': '1', 'UPGRADE-INSECURE-REQUESTS': '1'}) return session <|reserved_special_token_1|> <|reserved_special_token_0|> class NFO: <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def __init__(self) ->None: self.media_info: MediaInfo self.file: str self.season: Optional[Union[int, str]] self.episode: Optional[int] self.episode_name: Optional[str] self.videos: List[Track] self.audio: List[Track] self.subtitles: List[Track] self.chapters: Dict[str, str] self.chapters_numbered: bool self.fanart_api_key: Optional[str] self.source: Optional[str] self.note: Optional[str] self.preview: Optional[str] self.imdb: str self.tmdb: Optional[str] self.tvdb: Optional[int] self.title_name: str self.title_year: str self.episodes: int self.release_name: str self.preview_images: List[dict[str, str]] self.banner_image: Optional[str] self.session = self.get_session() def __repr__(self) ->str: return '<{c} {attrs}>'.format(c=self.__class__.__name__, attrs=' '. join('{}={!r}'.format(k, v) for k, v in self.__dict__.items())) def run(self, template: str, art: Optional[str]=None, **kwargs: Any) ->str: """ Evaluate and apply formatting on template, apply any art if provided. Any additional parameters are passed as extra variables to the template. The extra variables have priority when there's conflicting variable names. """ variables = self.__dict__ variables.update(kwargs) template = CustomFormats().format(template, **variables) if art: art = art.format(nfo=template) template = art for m in re.finditer('<\\?([01])\\?([\\D\\d]*?)\\?>', template): template = template.replace(m.group(0), m.group(2) if int(m. group(1)) else '') template = '\n'.join(map(str.rstrip, template.splitlines(keepends= False))) return template def set_config(self, file: str, **config: Any) ->None: self.file = file self.media_info = MediaInfo.parse(self.file) self.fanart_api_key = config.get('fanart_api_key') self.source = config.get('source') self.note = config.get('note') self.preview = config.get('preview') self.season = config.get('season') self.episode, self.episode_name = config.get('episode') or (None, None) self.episodes = self.get_tv_episodes() self.release_name = self.get_release_name() self.videos = self.media_info.video_tracks self.audio = self.media_info.audio_tracks self.subtitles = self.media_info.text_tracks tracks_without_language = [x for x in self.videos + self.audio + self.subtitles if not x.language or x.language == 'und'] if tracks_without_language: print( 'The following tracks have no language tag! All tracks need a language tag!' ) for track in tracks_without_language: print( f'{track.track_type} Track #{track.track_id} ({track.format}, {track.bit_rate / 1000} kb/s)' ) print( """Yes, even Video Track's have language e.g., Credits, Signs, Letters, Different Intro Sequence, etc. Don't forget to verify and add language tags to the rest of the files too!""" ) sys.exit(1) chapters = next(iter(self.media_info.menu_tracks), None) if chapters: self.chapters = {'.'.join([k.replace('_', '.')[:-3], k[-3:]]): v.strip(':') for k, v in chapters.to_data().items() if f"1{k.replace('_', '')}".isdigit()} self.chapters_numbered = all(x.split(':', 1)[-1].lower() in [ f'chapter {i + 1}', f'chapter {str(i + 1).zfill(2)}'] for i, x in enumerate(self.chapters.values())) else: self.chapters = {} self.chapters_numbered = False self.imdb = self.get_imdb_id(config.get('imdb')) self.tmdb = self.get_tmdb_id(config.get('tmdb')) self.tvdb = self.get_tvdb_id(config.get('tvdb')) self.title_name, self.title_year = self.get_title_name_year() self.banner_image = self.get_banner_image(self.tvdb ) if self.tvdb and self.fanart_api_key else None self.preview_images = self.get_preview_images(self.preview ) if self.preview else [] def get_imdb_id(self, imdb_id: Any) ->str: """ Get an IMDB ID from either the media's global tags, or the config. Since IMDB IDs are required for this project, it will bug the user for one interactively if not found. """ if not imdb_id: general_track = self.media_info.general_tracks[0].to_data() imdb_id = general_track.get('imdb') if not imdb_id: print('No IMDB ID was provided but is required...') while not imdb_id or not isinstance(imdb_id, str): user_id = input("IMDB ID (e.g., 'tt0487831'): ") if not self.IMDB_ID_T.match(user_id): print(f'The provided IMDB ID {user_id!r} is not valid...') print( "Expected e.g., 'tt0487831', 'tt10810424', (include the 'tt')." ) else: imdb_id = user_id return imdb_id def get_tmdb_id(self, tmdb_id: Any) ->Optional[str]: """ Get a TMDB ID from either the media's global tags, or the config. It will raise a ValueError if the provided ID is invalid. """ if not tmdb_id: general_track = self.media_info.general_tracks[0].to_data() tmdb_id = general_track.get('tmdb') if not tmdb_id: print('Warning: No TMDB ID was provided...') return None if not self.TMDB_ID_T.match(tmdb_id) or not isinstance(tmdb_id, str): print(f'The provided TMDB ID {tmdb_id!r} is not valid...') print( "Expected e.g., 'tv/2490', 'movie/14836', (include the 'tv/' or 'movie/')." ) raise ValueError('Invalid TMDB ID') return tmdb_id def get_tvdb_id(self, tvdb_id: Any) ->Optional[int]: """ Get a TVDB ID from either the media's global tags, or the config. It will raise a ValueError if the provided ID is invalid. """ if not tvdb_id: general_track = self.media_info.general_tracks[0].to_data() tvdb_id = general_track.get('tvdb') if not tvdb_id: print('Warning: No TVDB ID was provided...') return None if isinstance(tvdb_id, int): tvdb_id = str(tvdb_id) if not self.TVDB_ID_T.match(tvdb_id) or not isinstance(tvdb_id, str): print(f'The provided TVDB ID {tvdb_id!r} is not valid...') print( "Expected e.g., '79216', '1395', (not the url slug e.g., 'the-office-us')." ) raise ValueError('Invalid TVDB ID') return int(tvdb_id) def get_title_name_year(self) ->Tuple[str, str]: """Scrape Title Name and Year (including e.g. 2019-) from IMDB""" r = self.session.get(f'https://www.imdb.com/title/{self.imdb}') if r.status_code != 200: raise ValueError( f'An unexpected error occurred getting IMDB Title Page [{r.status_code}]' ) imdb_page = html.unescape(r.text) imdb_title = re.search( '<title>(?P<name>.+) \\(((?P<type>TV (Movie|Series|Mini[- ]Series|Short|Episode) |Video |Short |)(?P<year>(\\d{4})(|– |–\\d{4})))\\) - IMDb</title>' , imdb_page) if not imdb_title: raise ValueError( f'Could not scrape Movie Title or Year for {self.imdb}...') return imdb_title.group('name').strip(), imdb_title.group('year' ).strip() def get_tv_episodes(self) ->int: """Calculate total episode count based on neighbouring same-extension files.""" return len(glob.glob(os.path.join(os.path.dirname(self.file), f'*{os.path.splitext(self.file)[-1]}'))) def get_release_name(self) ->str: """ Retrieve the release name based on the file used during MediaInfo. If a season was specified, but an episode number was not, it presumes the release is a Pack. Hence when pack, it uses the parent folder's name as the release name. """ if self.season is not None and self.episode is None: return os.path.basename(os.path.dirname(self.file)) return os.path.splitext(os.path.basename(self.file))[0] def get_banner_image(self, tvdb_id: int) ->Optional[str]: """ Get a wide banner image from fanart.tv. Currently restricts banners to English-only. """ if not tvdb_id: return None if not self.fanart_api_key: raise ValueError('Need Fanart.tv api key for TV titles!') r = self.session.get( f'http://webservice.fanart.tv/v3/tv/{tvdb_id}?api_key={self.fanart_api_key}' ) if r.status_code == 404: return None res = r.json() error = res.get('error message') if error: if error == 'Not found': return None raise ValueError( f'An unexpected error occurred while calling Fanart.tv, {res}') banner = next((x['url'] for x in res.get('tvbanner') or [] if x[ 'lang'] == sorted(self.audio, key=lambda x: x.streamorder)[0]. language), None) return banner def get_preview_images(self, url: str) ->List[Dict[str, str]]: if not url: return [] images = [] for domain in ['imgbox.com', 'beyondhd.co']: if domain not in url.lower(): continue page = self.session.get(url).text if domain == 'imgbox.com': for m in re.finditer( 'src="(https://thumbs2.imgbox.com.+/)(\\w+)_b.([^"]+)', page): images.append({'url': f'https://imgbox.com/{m.group(2)}', 'src': f'{m.group(1)}{m.group(2)}_t.{m.group(3)}'}) elif domain == 'beyondhd.co': for m in re.finditer( '/image/([^"]+)"\\D+src="(https://.*beyondhd.co/images.+/(\\w+).md.[^"]+)' , page): images.append({'url': f'https://beyondhd.co/image/{m.group(1)}', 'src': m .group(2)}) break return images def get_video_print(self, videos: List[Track]) ->List[List[str]]: if not videos: return [['--']] data = [] for video in videos: codec = {'MPEG Video': f"MPEG-{(video.format_version or '').replace('Version ', '')}" }.get(video.format, video.format) scan_overview = video.scan_type vst = False if codec in ['MPEG-1', 'MPEG-2']: d2v = D2V.load(Path(self.file)) self.file = d2v.path flags = [f for line in [[dict(**y, vob=x['vob'], cell=x[ 'cell']) for y in x['flags']] for x in d2v.data] for f in line] interlaced_percent = sum(1 for f in flags if not f[ 'progressive_frame']) / len(flags) * 100 if interlaced_percent == 100: scan_overview = 'Interlaced (CST)' else: scan_overview = ( f'{round(interlaced_percent, 2)}% Interlaced (VST)') vst = True for ext in ['log', 'd2v', 'mpg', 'mpeg']: fp = os.path.splitext(self.file)[0] + '.' + ext if os.path.exists(fp): os.unlink(fp) line_1 = ( '- {language}, {codec} ({profile}) {width}x{height} ({aspect}) @ {bitrate}' .format(language=pycountry.languages.get(alpha_2=video. language).name, codec=codec, profile=video.format_profile, width=video.width, height=video.height, aspect=video. other_display_aspect_ratio[0], bitrate= f"{video.other_bit_rate[0]}{f' ({video.bit_rate_mode})' if video.bit_rate_mode else ''}" )) line_2 = ( ' {fps} FPS ({fps_mode}), {color_space}{subsampling}P{bit_depth}, {scan}' .format(fps=f'{video.framerate_num}/{video.framerate_den}' if video.framerate_num else video.frame_rate, fps_mode='VFR' if vst else video.frame_rate_mode, color_space=video. color_space, subsampling=video.chroma_subsampling.replace( ':', ''), bit_depth=video.bit_depth, scan=scan_overview)) data.append([line_1, line_2]) return data def get_audio_print(self, audio: List[Track]) ->List[str]: if not audio: return ['--'] data = [] for t in audio: if t.title and 'Commentary' in t.title: title = t.title else: title = pycountry.languages.get(alpha_2=t.language).name if t.channel_layout: channels = float(sum(self.AUDIO_CHANNEL_LAYOUT_WEIGHT.get(x, 1) for x in t.channel_layout.split(' '))) else: channels = float(t.channel_s) bit_rate_mode = f' ({t.bit_rate_mode})' if t.bit_rate_mode else '' l1 = ( f'- {title}, {t.format} {channels} @ {t.other_bit_rate[0]}{bit_rate_mode}' ) data += [(' ' + x if i > 0 else x) for i, x in enumerate( textwrap.wrap(l1, 64))] return data @staticmethod def get_subtitle_print(subs: List[Track]) ->List[str]: """ Return a list of a brief subtitle overview per-subtitle. e.g. - English, Forced, SubRip (SRT) - English, SubRip (SRT) - English, SDH, SubRip (SRT) - Spanish, Latin American (SDH), SubRip (SRT) The bit of text between the Language and the Subtitle format is the Track Title. It can be of any format, but it is recommended to be used as shown above. It will be returned as a list of strings with the `- ` already pre-pended to each entry. """ data = [] if not subs: data.append('--') for sub in subs: line_items = [] language = pycountry.languages.get(alpha_2=sub.language).name if sub.title: if language.lower() in sub.title.lower(): line_items.append(sub.title) else: line_items.append(f'{language}, {sub.title}') else: line_items.append(language) line_items.append(sub.format.replace('UTF-8', 'SubRip (SRT)')) line = '- ' + ', '.join(line_items) data += [(' ' + x if i > 0 else x) for i, x in enumerate( textwrap.wrap(line, 64))] return data @staticmethod def get_chapter_print(chapters: Dict[str, str]) ->List[str]: if not chapters: return ['--'] return [f'- {k}: {v}' for k, v in chapters.items()] def get_chapter_print_short(self, chapters: Dict[str, str]) ->str: if not chapters: return 'No' if self.chapters_numbered: return f'Yes (Numbered 01-{str(len(chapters)).zfill(2)})' return 'Yes (Named)' @staticmethod def get_session() ->requests.Session: session = requests.Session() session.headers.update({'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0' , 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' , 'Accept-Language': 'en-US,en;q=0.5', 'DNT': '1', 'UPGRADE-INSECURE-REQUESTS': '1'}) return session <|reserved_special_token_1|> import glob import html import os import re import sys import textwrap from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Union import pycountry import requests from pyd2v import D2V from pymediainfo import MediaInfo, Track from pynfogen.formatter import CustomFormats class NFO: AUDIO_CHANNEL_LAYOUT_WEIGHT = { "LFE": 0.1 } IMDB_ID_T = re.compile(r"^tt\d{7,8}$") TMDB_ID_T = re.compile(r"^(tv|movie)/\d+$") TVDB_ID_T = re.compile(r"^\d+$") def __init__(self) -> None: self.media_info: MediaInfo self.file: str self.season: Optional[Union[int, str]] self.episode: Optional[int] self.episode_name: Optional[str] self.videos: List[Track] self.audio: List[Track] self.subtitles: List[Track] self.chapters: Dict[str, str] self.chapters_numbered: bool self.fanart_api_key: Optional[str] self.source: Optional[str] self.note: Optional[str] self.preview: Optional[str] self.imdb: str self.tmdb: Optional[str] self.tvdb: Optional[int] self.title_name: str self.title_year: str self.episodes: int self.release_name: str self.preview_images: List[dict[str, str]] self.banner_image: Optional[str] self.session = self.get_session() def __repr__(self) -> str: return "<{c} {attrs}>".format( c=self.__class__.__name__, attrs=" ".join("{}={!r}".format(k, v) for k, v in self.__dict__.items()), ) def run(self, template: str, art: Optional[str] = None, **kwargs: Any) -> str: """ Evaluate and apply formatting on template, apply any art if provided. Any additional parameters are passed as extra variables to the template. The extra variables have priority when there's conflicting variable names. """ variables = self.__dict__ variables.update(kwargs) template = CustomFormats().format(template, **variables) if art: art = art.format(nfo=template) template = art for m in re.finditer(r"<\?([01])\?([\D\d]*?)\?>", template): # TODO: This if check is quite yucky, look into alternative options. # Ideally a custom format spec would be great. template = template.replace( m.group(0), m.group(2) if int(m.group(1)) else "" ) template = "\n".join(map(str.rstrip, template.splitlines(keepends=False))) return template def set_config(self, file: str, **config: Any) -> None: self.file = file self.media_info = MediaInfo.parse(self.file) self.fanart_api_key = config.get("fanart_api_key") self.source = config.get("source") self.note = config.get("note") self.preview = config.get("preview") self.season = config.get("season") self.episode, self.episode_name = config.get("episode") or (None, None) self.episodes = self.get_tv_episodes() self.release_name = self.get_release_name() self.videos = self.media_info.video_tracks self.audio = self.media_info.audio_tracks self.subtitles = self.media_info.text_tracks tracks_without_language = [ x for x in self.videos + self.audio + self.subtitles if not x.language or x.language == "und" ] if tracks_without_language: print("The following tracks have no language tag! All tracks need a language tag!") for track in tracks_without_language: print(f"{track.track_type} Track #{track.track_id} ({track.format}, {track.bit_rate / 1000} kb/s)") print( "Yes, even Video Track's have language e.g., Credits, Signs, Letters, Different Intro Sequence, etc.\n" "Don't forget to verify and add language tags to the rest of the files too!" ) sys.exit(1) chapters = next(iter(self.media_info.menu_tracks), None) if chapters: self.chapters = { ".".join([k.replace("_", ".")[:-3], k[-3:]]): v.strip(":") for k, v in chapters.to_data().items() if f"1{k.replace('_', '')}".isdigit() } self.chapters_numbered = all( x.split(":", 1)[-1].lower() in [f"chapter {i + 1}", f"chapter {str(i + 1).zfill(2)}"] for i, x in enumerate(self.chapters.values()) ) else: self.chapters = {} self.chapters_numbered = False self.imdb = self.get_imdb_id(config.get("imdb")) self.tmdb = self.get_tmdb_id(config.get("tmdb")) self.tvdb = self.get_tvdb_id(config.get("tvdb")) self.title_name, self.title_year = self.get_title_name_year() self.banner_image = self.get_banner_image(self.tvdb) if self.tvdb and self.fanart_api_key else None self.preview_images = self.get_preview_images(self.preview) if self.preview else [] def get_imdb_id(self, imdb_id: Any) -> str: """ Get an IMDB ID from either the media's global tags, or the config. Since IMDB IDs are required for this project, it will bug the user for one interactively if not found. """ if not imdb_id: general_track = self.media_info.general_tracks[0].to_data() imdb_id = general_track.get("imdb") if not imdb_id: print("No IMDB ID was provided but is required...") while not imdb_id or not isinstance(imdb_id, str): user_id = input("IMDB ID (e.g., 'tt0487831'): ") if not self.IMDB_ID_T.match(user_id): print(f"The provided IMDB ID {user_id!r} is not valid...") print("Expected e.g., 'tt0487831', 'tt10810424', (include the 'tt').") else: imdb_id = user_id return imdb_id def get_tmdb_id(self, tmdb_id: Any) -> Optional[str]: """ Get a TMDB ID from either the media's global tags, or the config. It will raise a ValueError if the provided ID is invalid. """ if not tmdb_id: general_track = self.media_info.general_tracks[0].to_data() tmdb_id = general_track.get("tmdb") if not tmdb_id: print("Warning: No TMDB ID was provided...") return None if not self.TMDB_ID_T.match(tmdb_id) or not isinstance(tmdb_id, str): print(f"The provided TMDB ID {tmdb_id!r} is not valid...") print("Expected e.g., 'tv/2490', 'movie/14836', (include the 'tv/' or 'movie/').") raise ValueError("Invalid TMDB ID") return tmdb_id def get_tvdb_id(self, tvdb_id: Any) -> Optional[int]: """ Get a TVDB ID from either the media's global tags, or the config. It will raise a ValueError if the provided ID is invalid. """ if not tvdb_id: general_track = self.media_info.general_tracks[0].to_data() tvdb_id = general_track.get("tvdb") if not tvdb_id: print("Warning: No TVDB ID was provided...") return None if isinstance(tvdb_id, int): tvdb_id = str(tvdb_id) if not self.TVDB_ID_T.match(tvdb_id) or not isinstance(tvdb_id, str): print(f"The provided TVDB ID {tvdb_id!r} is not valid...") print("Expected e.g., '79216', '1395', (not the url slug e.g., 'the-office-us').") raise ValueError("Invalid TVDB ID") return int(tvdb_id) def get_title_name_year(self) -> Tuple[str, str]: """Scrape Title Name and Year (including e.g. 2019-) from IMDB""" r = self.session.get(f"https://www.imdb.com/title/{self.imdb}") if r.status_code != 200: raise ValueError(f"An unexpected error occurred getting IMDB Title Page [{r.status_code}]") imdb_page = html.unescape(r.text) imdb_title = re.search( # testing ground: https://regex101.com/r/bEoEDn/1 r"<title>(?P<name>.+) \(((?P<type>TV (Movie|Series|Mini[- ]Series|Short|Episode) |Video |Short |)" r"(?P<year>(\d{4})(|– |–\d{4})))\) - IMDb</title>", imdb_page ) if not imdb_title: raise ValueError(f"Could not scrape Movie Title or Year for {self.imdb}...") return imdb_title.group("name").strip(), imdb_title.group("year").strip() def get_tv_episodes(self) -> int: """Calculate total episode count based on neighbouring same-extension files.""" return len(glob.glob(os.path.join( os.path.dirname(self.file), f"*{os.path.splitext(self.file)[-1]}" ))) def get_release_name(self) -> str: """ Retrieve the release name based on the file used during MediaInfo. If a season was specified, but an episode number was not, it presumes the release is a Pack. Hence when pack, it uses the parent folder's name as the release name. """ if self.season is not None and self.episode is None: return os.path.basename(os.path.dirname(self.file)) return os.path.splitext(os.path.basename(self.file))[0] def get_banner_image(self, tvdb_id: int) -> Optional[str]: """ Get a wide banner image from fanart.tv. Currently restricts banners to English-only. """ if not tvdb_id: return None if not self.fanart_api_key: raise ValueError("Need Fanart.tv api key for TV titles!") r = self.session.get(f"http://webservice.fanart.tv/v3/tv/{tvdb_id}?api_key={self.fanart_api_key}") if r.status_code == 404: return None res = r.json() error = res.get("error message") if error: if error == "Not found": return None raise ValueError(f"An unexpected error occurred while calling Fanart.tv, {res}") banner = next(( x["url"] for x in (res.get("tvbanner") or []) if x["lang"] == sorted(self.audio, key=lambda x: x.streamorder)[0].language ), None) return banner def get_preview_images(self, url: str) -> List[Dict[str, str]]: if not url: return [] images = [] for domain in ["imgbox.com", "beyondhd.co"]: if domain not in url.lower(): continue page = self.session.get(url).text if domain == "imgbox.com": for m in re.finditer('src="(https://thumbs2.imgbox.com.+/)(\\w+)_b.([^"]+)', page): images.append({ "url": f"https://imgbox.com/{m.group(2)}", "src": f"{m.group(1)}{m.group(2)}_t.{m.group(3)}" }) elif domain == "beyondhd.co": for m in re.finditer('/image/([^"]+)"\\D+src="(https://.*beyondhd.co/images.+/(\\w+).md.[^"]+)', page): images.append({ "url": f"https://beyondhd.co/image/{m.group(1)}", "src": m.group(2) }) break return images def get_video_print(self, videos: List[Track]) -> List[List[str]]: if not videos: return [["--"]] data = [] for video in videos: codec = { "MPEG Video": f"MPEG-{(video.format_version or '').replace('Version ', '')}" }.get(video.format, video.format) scan_overview = video.scan_type vst = False if codec in ["MPEG-1", "MPEG-2"]: # parse d2v file with pyd2v, generates D2V if needed d2v = D2V.load(Path(self.file)) self.file = d2v.path # get every frames' flag data, this contains information on displaying frames # add vob and cell number to each frames flag data as well flags = [f for line in [ [dict(**y, vob=x["vob"], cell=x["cell"]) for y in x["flags"]] for x in d2v.data ] for f in line] interlaced_percent = (sum(1 for f in flags if not f["progressive_frame"]) / len(flags)) * 100 if interlaced_percent == 100: scan_overview = "Interlaced (CST)" else: scan_overview = f"{round(interlaced_percent, 2)}% Interlaced (VST)" vst = True for ext in ["log", "d2v", "mpg", "mpeg"]: fp = os.path.splitext(self.file)[0] + "." + ext if os.path.exists(fp): os.unlink(fp) line_1 = "- {language}, {codec} ({profile}) {width}x{height} ({aspect}) @ {bitrate}".format( language=pycountry.languages.get(alpha_2=video.language).name, codec=codec, profile=video.format_profile, width=video.width, height=video.height, aspect=video.other_display_aspect_ratio[0], bitrate=f"{video.other_bit_rate[0]}{f' ({video.bit_rate_mode})' if video.bit_rate_mode else ''}" ) line_2 = " {fps} FPS ({fps_mode}), {color_space}{subsampling}P{bit_depth}, {scan}".format( fps=f"{video.framerate_num}/{video.framerate_den}" if video.framerate_num else video.frame_rate, fps_mode="VFR" if vst else video.frame_rate_mode, color_space=video.color_space, subsampling=video.chroma_subsampling.replace(":", ""), bit_depth=video.bit_depth, scan=scan_overview ) data.append([line_1, line_2]) return data def get_audio_print(self, audio: List[Track]) -> List[str]: if not audio: return ["--"] data = [] for t in audio: if t.title and "Commentary" in t.title: title = t.title else: title = pycountry.languages.get(alpha_2=t.language).name if t.channel_layout: channels = float(sum(self.AUDIO_CHANNEL_LAYOUT_WEIGHT.get(x, 1) for x in t.channel_layout.split(" "))) else: channels = float(t.channel_s) bit_rate_mode = f" ({t.bit_rate_mode})" if t.bit_rate_mode else "" l1 = f"- {title}, {t.format} {channels} @ {t.other_bit_rate[0]}{bit_rate_mode}" data += [(" " + x if i > 0 else x) for i, x in enumerate(textwrap.wrap(l1, 64))] return data @staticmethod def get_subtitle_print(subs: List[Track]) -> List[str]: """ Return a list of a brief subtitle overview per-subtitle. e.g. - English, Forced, SubRip (SRT) - English, SubRip (SRT) - English, SDH, SubRip (SRT) - Spanish, Latin American (SDH), SubRip (SRT) The bit of text between the Language and the Subtitle format is the Track Title. It can be of any format, but it is recommended to be used as shown above. It will be returned as a list of strings with the `- ` already pre-pended to each entry. """ data = [] if not subs: data.append("--") for sub in subs: line_items = [] # following sub.title tree checks and supports three different language and title scenarios # The second scenario is the recommended option to choose if you are open to choosing any # The third scenario should be used if you have nothing unique to state about the track # | Language | Track Title | Output | # | ------------ | ----------------------------- | --------------------------------------------- | # | es / Spanish | Spanish (Latin American, SDH) | - Spanish (Latin American, SDH), SubRip (SRT) | # | es / Spanish | Latin American (SDH) | - Spanish, Latin American (SDH), SubRip (SRT) | # | es / Spanish | None | - Spanish, SubRip (SRT) | language = pycountry.languages.get(alpha_2=sub.language).name if sub.title: if language.lower() in sub.title.lower(): line_items.append(sub.title) else: line_items.append(f"{language}, {sub.title}") else: line_items.append(language) line_items.append(sub.format.replace("UTF-8", "SubRip (SRT)")) line = "- " + ", ".join(line_items) data += [ (" " + x if i > 0 else x) for i, x in enumerate(textwrap.wrap(line, 64)) ] return data @staticmethod def get_chapter_print(chapters: Dict[str, str]) -> List[str]: if not chapters: return ["--"] return [ f"- {k}: {v}" for k, v in chapters.items() ] def get_chapter_print_short(self, chapters: Dict[str, str]) -> str: if not chapters: return "No" if self.chapters_numbered: return f"Yes (Numbered 01-{str(len(chapters)).zfill(2)})" return "Yes (Named)" @staticmethod def get_session() -> requests.Session: session = requests.Session() session.headers.update({ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "Accept-Language": "en-US,en;q=0.5", "DNT": "1", "UPGRADE-INSECURE-REQUESTS": "1" }) return session
flexible
{ "blob_id": "e434d5519e3ba4255ed928769070de391cb0955b", "index": 3462, "step-1": "<mask token>\n\n\nclass NFO:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __repr__(self) ->str:\n return '<{c} {attrs}>'.format(c=self.__class__.__name__, attrs=' '.\n join('{}={!r}'.format(k, v) for k, v in self.__dict__.items()))\n\n def run(self, template: str, art: Optional[str]=None, **kwargs: Any) ->str:\n \"\"\"\n Evaluate and apply formatting on template, apply any art if provided.\n Any additional parameters are passed as extra variables to the template.\n The extra variables have priority when there's conflicting variable names.\n \"\"\"\n variables = self.__dict__\n variables.update(kwargs)\n template = CustomFormats().format(template, **variables)\n if art:\n art = art.format(nfo=template)\n template = art\n for m in re.finditer('<\\\\?([01])\\\\?([\\\\D\\\\d]*?)\\\\?>', template):\n template = template.replace(m.group(0), m.group(2) if int(m.\n group(1)) else '')\n template = '\\n'.join(map(str.rstrip, template.splitlines(keepends=\n False)))\n return template\n\n def set_config(self, file: str, **config: Any) ->None:\n self.file = file\n self.media_info = MediaInfo.parse(self.file)\n self.fanart_api_key = config.get('fanart_api_key')\n self.source = config.get('source')\n self.note = config.get('note')\n self.preview = config.get('preview')\n self.season = config.get('season')\n self.episode, self.episode_name = config.get('episode') or (None, None)\n self.episodes = self.get_tv_episodes()\n self.release_name = self.get_release_name()\n self.videos = self.media_info.video_tracks\n self.audio = self.media_info.audio_tracks\n self.subtitles = self.media_info.text_tracks\n tracks_without_language = [x for x in self.videos + self.audio +\n self.subtitles if not x.language or x.language == 'und']\n if tracks_without_language:\n print(\n 'The following tracks have no language tag! All tracks need a language tag!'\n )\n for track in tracks_without_language:\n print(\n f'{track.track_type} Track #{track.track_id} ({track.format}, {track.bit_rate / 1000} kb/s)'\n )\n print(\n \"\"\"Yes, even Video Track's have language e.g., Credits, Signs, Letters, Different Intro Sequence, etc.\nDon't forget to verify and add language tags to the rest of the files too!\"\"\"\n )\n sys.exit(1)\n chapters = next(iter(self.media_info.menu_tracks), None)\n if chapters:\n self.chapters = {'.'.join([k.replace('_', '.')[:-3], k[-3:]]):\n v.strip(':') for k, v in chapters.to_data().items() if\n f\"1{k.replace('_', '')}\".isdigit()}\n self.chapters_numbered = all(x.split(':', 1)[-1].lower() in [\n f'chapter {i + 1}', f'chapter {str(i + 1).zfill(2)}'] for i,\n x in enumerate(self.chapters.values()))\n else:\n self.chapters = {}\n self.chapters_numbered = False\n self.imdb = self.get_imdb_id(config.get('imdb'))\n self.tmdb = self.get_tmdb_id(config.get('tmdb'))\n self.tvdb = self.get_tvdb_id(config.get('tvdb'))\n self.title_name, self.title_year = self.get_title_name_year()\n self.banner_image = self.get_banner_image(self.tvdb\n ) if self.tvdb and self.fanart_api_key else None\n self.preview_images = self.get_preview_images(self.preview\n ) if self.preview else []\n\n def get_imdb_id(self, imdb_id: Any) ->str:\n \"\"\"\n Get an IMDB ID from either the media's global tags, or the config.\n Since IMDB IDs are required for this project, it will bug the user for\n one interactively if not found.\n \"\"\"\n if not imdb_id:\n general_track = self.media_info.general_tracks[0].to_data()\n imdb_id = general_track.get('imdb')\n if not imdb_id:\n print('No IMDB ID was provided but is required...')\n while not imdb_id or not isinstance(imdb_id, str):\n user_id = input(\"IMDB ID (e.g., 'tt0487831'): \")\n if not self.IMDB_ID_T.match(user_id):\n print(f'The provided IMDB ID {user_id!r} is not valid...')\n print(\n \"Expected e.g., 'tt0487831', 'tt10810424', (include the 'tt').\"\n )\n else:\n imdb_id = user_id\n return imdb_id\n\n def get_tmdb_id(self, tmdb_id: Any) ->Optional[str]:\n \"\"\"\n Get a TMDB ID from either the media's global tags, or the config.\n It will raise a ValueError if the provided ID is invalid.\n \"\"\"\n if not tmdb_id:\n general_track = self.media_info.general_tracks[0].to_data()\n tmdb_id = general_track.get('tmdb')\n if not tmdb_id:\n print('Warning: No TMDB ID was provided...')\n return None\n if not self.TMDB_ID_T.match(tmdb_id) or not isinstance(tmdb_id, str):\n print(f'The provided TMDB ID {tmdb_id!r} is not valid...')\n print(\n \"Expected e.g., 'tv/2490', 'movie/14836', (include the 'tv/' or 'movie/').\"\n )\n raise ValueError('Invalid TMDB ID')\n return tmdb_id\n\n def get_tvdb_id(self, tvdb_id: Any) ->Optional[int]:\n \"\"\"\n Get a TVDB ID from either the media's global tags, or the config.\n It will raise a ValueError if the provided ID is invalid.\n \"\"\"\n if not tvdb_id:\n general_track = self.media_info.general_tracks[0].to_data()\n tvdb_id = general_track.get('tvdb')\n if not tvdb_id:\n print('Warning: No TVDB ID was provided...')\n return None\n if isinstance(tvdb_id, int):\n tvdb_id = str(tvdb_id)\n if not self.TVDB_ID_T.match(tvdb_id) or not isinstance(tvdb_id, str):\n print(f'The provided TVDB ID {tvdb_id!r} is not valid...')\n print(\n \"Expected e.g., '79216', '1395', (not the url slug e.g., 'the-office-us').\"\n )\n raise ValueError('Invalid TVDB ID')\n return int(tvdb_id)\n <mask token>\n <mask token>\n\n def get_release_name(self) ->str:\n \"\"\"\n Retrieve the release name based on the file used during MediaInfo.\n If a season was specified, but an episode number was not, it presumes the release is a Pack.\n Hence when pack, it uses the parent folder's name as the release name.\n \"\"\"\n if self.season is not None and self.episode is None:\n return os.path.basename(os.path.dirname(self.file))\n return os.path.splitext(os.path.basename(self.file))[0]\n\n def get_banner_image(self, tvdb_id: int) ->Optional[str]:\n \"\"\"\n Get a wide banner image from fanart.tv.\n Currently restricts banners to English-only.\n \"\"\"\n if not tvdb_id:\n return None\n if not self.fanart_api_key:\n raise ValueError('Need Fanart.tv api key for TV titles!')\n r = self.session.get(\n f'http://webservice.fanart.tv/v3/tv/{tvdb_id}?api_key={self.fanart_api_key}'\n )\n if r.status_code == 404:\n return None\n res = r.json()\n error = res.get('error message')\n if error:\n if error == 'Not found':\n return None\n raise ValueError(\n f'An unexpected error occurred while calling Fanart.tv, {res}')\n banner = next((x['url'] for x in res.get('tvbanner') or [] if x[\n 'lang'] == sorted(self.audio, key=lambda x: x.streamorder)[0].\n language), None)\n return banner\n\n def get_preview_images(self, url: str) ->List[Dict[str, str]]:\n if not url:\n return []\n images = []\n for domain in ['imgbox.com', 'beyondhd.co']:\n if domain not in url.lower():\n continue\n page = self.session.get(url).text\n if domain == 'imgbox.com':\n for m in re.finditer(\n 'src=\"(https://thumbs2.imgbox.com.+/)(\\\\w+)_b.([^\"]+)',\n page):\n images.append({'url':\n f'https://imgbox.com/{m.group(2)}', 'src':\n f'{m.group(1)}{m.group(2)}_t.{m.group(3)}'})\n elif domain == 'beyondhd.co':\n for m in re.finditer(\n '/image/([^\"]+)\"\\\\D+src=\"(https://.*beyondhd.co/images.+/(\\\\w+).md.[^\"]+)'\n , page):\n images.append({'url':\n f'https://beyondhd.co/image/{m.group(1)}', 'src': m\n .group(2)})\n break\n return images\n\n def get_video_print(self, videos: List[Track]) ->List[List[str]]:\n if not videos:\n return [['--']]\n data = []\n for video in videos:\n codec = {'MPEG Video':\n f\"MPEG-{(video.format_version or '').replace('Version ', '')}\"\n }.get(video.format, video.format)\n scan_overview = video.scan_type\n vst = False\n if codec in ['MPEG-1', 'MPEG-2']:\n d2v = D2V.load(Path(self.file))\n self.file = d2v.path\n flags = [f for line in [[dict(**y, vob=x['vob'], cell=x[\n 'cell']) for y in x['flags']] for x in d2v.data] for f in\n line]\n interlaced_percent = sum(1 for f in flags if not f[\n 'progressive_frame']) / len(flags) * 100\n if interlaced_percent == 100:\n scan_overview = 'Interlaced (CST)'\n else:\n scan_overview = (\n f'{round(interlaced_percent, 2)}% Interlaced (VST)')\n vst = True\n for ext in ['log', 'd2v', 'mpg', 'mpeg']:\n fp = os.path.splitext(self.file)[0] + '.' + ext\n if os.path.exists(fp):\n os.unlink(fp)\n line_1 = (\n '- {language}, {codec} ({profile}) {width}x{height} ({aspect}) @ {bitrate}'\n .format(language=pycountry.languages.get(alpha_2=video.\n language).name, codec=codec, profile=video.format_profile,\n width=video.width, height=video.height, aspect=video.\n other_display_aspect_ratio[0], bitrate=\n f\"{video.other_bit_rate[0]}{f' ({video.bit_rate_mode})' if video.bit_rate_mode else ''}\"\n ))\n line_2 = (\n ' {fps} FPS ({fps_mode}), {color_space}{subsampling}P{bit_depth}, {scan}'\n .format(fps=f'{video.framerate_num}/{video.framerate_den}' if\n video.framerate_num else video.frame_rate, fps_mode='VFR' if\n vst else video.frame_rate_mode, color_space=video.\n color_space, subsampling=video.chroma_subsampling.replace(\n ':', ''), bit_depth=video.bit_depth, scan=scan_overview))\n data.append([line_1, line_2])\n return data\n\n def get_audio_print(self, audio: List[Track]) ->List[str]:\n if not audio:\n return ['--']\n data = []\n for t in audio:\n if t.title and 'Commentary' in t.title:\n title = t.title\n else:\n title = pycountry.languages.get(alpha_2=t.language).name\n if t.channel_layout:\n channels = float(sum(self.AUDIO_CHANNEL_LAYOUT_WEIGHT.get(x,\n 1) for x in t.channel_layout.split(' ')))\n else:\n channels = float(t.channel_s)\n bit_rate_mode = f' ({t.bit_rate_mode})' if t.bit_rate_mode else ''\n l1 = (\n f'- {title}, {t.format} {channels} @ {t.other_bit_rate[0]}{bit_rate_mode}'\n )\n data += [(' ' + x if i > 0 else x) for i, x in enumerate(\n textwrap.wrap(l1, 64))]\n return data\n <mask token>\n <mask token>\n\n def get_chapter_print_short(self, chapters: Dict[str, str]) ->str:\n if not chapters:\n return 'No'\n if self.chapters_numbered:\n return f'Yes (Numbered 01-{str(len(chapters)).zfill(2)})'\n return 'Yes (Named)'\n\n @staticmethod\n def get_session() ->requests.Session:\n session = requests.Session()\n session.headers.update({'User-Agent':\n 'Mozilla/5.0 (X11; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0'\n , 'Accept':\n 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'\n , 'Accept-Language': 'en-US,en;q=0.5', 'DNT': '1',\n 'UPGRADE-INSECURE-REQUESTS': '1'})\n return session\n", "step-2": "<mask token>\n\n\nclass NFO:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __repr__(self) ->str:\n return '<{c} {attrs}>'.format(c=self.__class__.__name__, attrs=' '.\n join('{}={!r}'.format(k, v) for k, v in self.__dict__.items()))\n\n def run(self, template: str, art: Optional[str]=None, **kwargs: Any) ->str:\n \"\"\"\n Evaluate and apply formatting on template, apply any art if provided.\n Any additional parameters are passed as extra variables to the template.\n The extra variables have priority when there's conflicting variable names.\n \"\"\"\n variables = self.__dict__\n variables.update(kwargs)\n template = CustomFormats().format(template, **variables)\n if art:\n art = art.format(nfo=template)\n template = art\n for m in re.finditer('<\\\\?([01])\\\\?([\\\\D\\\\d]*?)\\\\?>', template):\n template = template.replace(m.group(0), m.group(2) if int(m.\n group(1)) else '')\n template = '\\n'.join(map(str.rstrip, template.splitlines(keepends=\n False)))\n return template\n\n def set_config(self, file: str, **config: Any) ->None:\n self.file = file\n self.media_info = MediaInfo.parse(self.file)\n self.fanart_api_key = config.get('fanart_api_key')\n self.source = config.get('source')\n self.note = config.get('note')\n self.preview = config.get('preview')\n self.season = config.get('season')\n self.episode, self.episode_name = config.get('episode') or (None, None)\n self.episodes = self.get_tv_episodes()\n self.release_name = self.get_release_name()\n self.videos = self.media_info.video_tracks\n self.audio = self.media_info.audio_tracks\n self.subtitles = self.media_info.text_tracks\n tracks_without_language = [x for x in self.videos + self.audio +\n self.subtitles if not x.language or x.language == 'und']\n if tracks_without_language:\n print(\n 'The following tracks have no language tag! All tracks need a language tag!'\n )\n for track in tracks_without_language:\n print(\n f'{track.track_type} Track #{track.track_id} ({track.format}, {track.bit_rate / 1000} kb/s)'\n )\n print(\n \"\"\"Yes, even Video Track's have language e.g., Credits, Signs, Letters, Different Intro Sequence, etc.\nDon't forget to verify and add language tags to the rest of the files too!\"\"\"\n )\n sys.exit(1)\n chapters = next(iter(self.media_info.menu_tracks), None)\n if chapters:\n self.chapters = {'.'.join([k.replace('_', '.')[:-3], k[-3:]]):\n v.strip(':') for k, v in chapters.to_data().items() if\n f\"1{k.replace('_', '')}\".isdigit()}\n self.chapters_numbered = all(x.split(':', 1)[-1].lower() in [\n f'chapter {i + 1}', f'chapter {str(i + 1).zfill(2)}'] for i,\n x in enumerate(self.chapters.values()))\n else:\n self.chapters = {}\n self.chapters_numbered = False\n self.imdb = self.get_imdb_id(config.get('imdb'))\n self.tmdb = self.get_tmdb_id(config.get('tmdb'))\n self.tvdb = self.get_tvdb_id(config.get('tvdb'))\n self.title_name, self.title_year = self.get_title_name_year()\n self.banner_image = self.get_banner_image(self.tvdb\n ) if self.tvdb and self.fanart_api_key else None\n self.preview_images = self.get_preview_images(self.preview\n ) if self.preview else []\n\n def get_imdb_id(self, imdb_id: Any) ->str:\n \"\"\"\n Get an IMDB ID from either the media's global tags, or the config.\n Since IMDB IDs are required for this project, it will bug the user for\n one interactively if not found.\n \"\"\"\n if not imdb_id:\n general_track = self.media_info.general_tracks[0].to_data()\n imdb_id = general_track.get('imdb')\n if not imdb_id:\n print('No IMDB ID was provided but is required...')\n while not imdb_id or not isinstance(imdb_id, str):\n user_id = input(\"IMDB ID (e.g., 'tt0487831'): \")\n if not self.IMDB_ID_T.match(user_id):\n print(f'The provided IMDB ID {user_id!r} is not valid...')\n print(\n \"Expected e.g., 'tt0487831', 'tt10810424', (include the 'tt').\"\n )\n else:\n imdb_id = user_id\n return imdb_id\n\n def get_tmdb_id(self, tmdb_id: Any) ->Optional[str]:\n \"\"\"\n Get a TMDB ID from either the media's global tags, or the config.\n It will raise a ValueError if the provided ID is invalid.\n \"\"\"\n if not tmdb_id:\n general_track = self.media_info.general_tracks[0].to_data()\n tmdb_id = general_track.get('tmdb')\n if not tmdb_id:\n print('Warning: No TMDB ID was provided...')\n return None\n if not self.TMDB_ID_T.match(tmdb_id) or not isinstance(tmdb_id, str):\n print(f'The provided TMDB ID {tmdb_id!r} is not valid...')\n print(\n \"Expected e.g., 'tv/2490', 'movie/14836', (include the 'tv/' or 'movie/').\"\n )\n raise ValueError('Invalid TMDB ID')\n return tmdb_id\n\n def get_tvdb_id(self, tvdb_id: Any) ->Optional[int]:\n \"\"\"\n Get a TVDB ID from either the media's global tags, or the config.\n It will raise a ValueError if the provided ID is invalid.\n \"\"\"\n if not tvdb_id:\n general_track = self.media_info.general_tracks[0].to_data()\n tvdb_id = general_track.get('tvdb')\n if not tvdb_id:\n print('Warning: No TVDB ID was provided...')\n return None\n if isinstance(tvdb_id, int):\n tvdb_id = str(tvdb_id)\n if not self.TVDB_ID_T.match(tvdb_id) or not isinstance(tvdb_id, str):\n print(f'The provided TVDB ID {tvdb_id!r} is not valid...')\n print(\n \"Expected e.g., '79216', '1395', (not the url slug e.g., 'the-office-us').\"\n )\n raise ValueError('Invalid TVDB ID')\n return int(tvdb_id)\n\n def get_title_name_year(self) ->Tuple[str, str]:\n \"\"\"Scrape Title Name and Year (including e.g. 2019-) from IMDB\"\"\"\n r = self.session.get(f'https://www.imdb.com/title/{self.imdb}')\n if r.status_code != 200:\n raise ValueError(\n f'An unexpected error occurred getting IMDB Title Page [{r.status_code}]'\n )\n imdb_page = html.unescape(r.text)\n imdb_title = re.search(\n '<title>(?P<name>.+) \\\\(((?P<type>TV (Movie|Series|Mini[- ]Series|Short|Episode) |Video |Short |)(?P<year>(\\\\d{4})(|– |–\\\\d{4})))\\\\) - IMDb</title>'\n , imdb_page)\n if not imdb_title:\n raise ValueError(\n f'Could not scrape Movie Title or Year for {self.imdb}...')\n return imdb_title.group('name').strip(), imdb_title.group('year'\n ).strip()\n <mask token>\n\n def get_release_name(self) ->str:\n \"\"\"\n Retrieve the release name based on the file used during MediaInfo.\n If a season was specified, but an episode number was not, it presumes the release is a Pack.\n Hence when pack, it uses the parent folder's name as the release name.\n \"\"\"\n if self.season is not None and self.episode is None:\n return os.path.basename(os.path.dirname(self.file))\n return os.path.splitext(os.path.basename(self.file))[0]\n\n def get_banner_image(self, tvdb_id: int) ->Optional[str]:\n \"\"\"\n Get a wide banner image from fanart.tv.\n Currently restricts banners to English-only.\n \"\"\"\n if not tvdb_id:\n return None\n if not self.fanart_api_key:\n raise ValueError('Need Fanart.tv api key for TV titles!')\n r = self.session.get(\n f'http://webservice.fanart.tv/v3/tv/{tvdb_id}?api_key={self.fanart_api_key}'\n )\n if r.status_code == 404:\n return None\n res = r.json()\n error = res.get('error message')\n if error:\n if error == 'Not found':\n return None\n raise ValueError(\n f'An unexpected error occurred while calling Fanart.tv, {res}')\n banner = next((x['url'] for x in res.get('tvbanner') or [] if x[\n 'lang'] == sorted(self.audio, key=lambda x: x.streamorder)[0].\n language), None)\n return banner\n\n def get_preview_images(self, url: str) ->List[Dict[str, str]]:\n if not url:\n return []\n images = []\n for domain in ['imgbox.com', 'beyondhd.co']:\n if domain not in url.lower():\n continue\n page = self.session.get(url).text\n if domain == 'imgbox.com':\n for m in re.finditer(\n 'src=\"(https://thumbs2.imgbox.com.+/)(\\\\w+)_b.([^\"]+)',\n page):\n images.append({'url':\n f'https://imgbox.com/{m.group(2)}', 'src':\n f'{m.group(1)}{m.group(2)}_t.{m.group(3)}'})\n elif domain == 'beyondhd.co':\n for m in re.finditer(\n '/image/([^\"]+)\"\\\\D+src=\"(https://.*beyondhd.co/images.+/(\\\\w+).md.[^\"]+)'\n , page):\n images.append({'url':\n f'https://beyondhd.co/image/{m.group(1)}', 'src': m\n .group(2)})\n break\n return images\n\n def get_video_print(self, videos: List[Track]) ->List[List[str]]:\n if not videos:\n return [['--']]\n data = []\n for video in videos:\n codec = {'MPEG Video':\n f\"MPEG-{(video.format_version or '').replace('Version ', '')}\"\n }.get(video.format, video.format)\n scan_overview = video.scan_type\n vst = False\n if codec in ['MPEG-1', 'MPEG-2']:\n d2v = D2V.load(Path(self.file))\n self.file = d2v.path\n flags = [f for line in [[dict(**y, vob=x['vob'], cell=x[\n 'cell']) for y in x['flags']] for x in d2v.data] for f in\n line]\n interlaced_percent = sum(1 for f in flags if not f[\n 'progressive_frame']) / len(flags) * 100\n if interlaced_percent == 100:\n scan_overview = 'Interlaced (CST)'\n else:\n scan_overview = (\n f'{round(interlaced_percent, 2)}% Interlaced (VST)')\n vst = True\n for ext in ['log', 'd2v', 'mpg', 'mpeg']:\n fp = os.path.splitext(self.file)[0] + '.' + ext\n if os.path.exists(fp):\n os.unlink(fp)\n line_1 = (\n '- {language}, {codec} ({profile}) {width}x{height} ({aspect}) @ {bitrate}'\n .format(language=pycountry.languages.get(alpha_2=video.\n language).name, codec=codec, profile=video.format_profile,\n width=video.width, height=video.height, aspect=video.\n other_display_aspect_ratio[0], bitrate=\n f\"{video.other_bit_rate[0]}{f' ({video.bit_rate_mode})' if video.bit_rate_mode else ''}\"\n ))\n line_2 = (\n ' {fps} FPS ({fps_mode}), {color_space}{subsampling}P{bit_depth}, {scan}'\n .format(fps=f'{video.framerate_num}/{video.framerate_den}' if\n video.framerate_num else video.frame_rate, fps_mode='VFR' if\n vst else video.frame_rate_mode, color_space=video.\n color_space, subsampling=video.chroma_subsampling.replace(\n ':', ''), bit_depth=video.bit_depth, scan=scan_overview))\n data.append([line_1, line_2])\n return data\n\n def get_audio_print(self, audio: List[Track]) ->List[str]:\n if not audio:\n return ['--']\n data = []\n for t in audio:\n if t.title and 'Commentary' in t.title:\n title = t.title\n else:\n title = pycountry.languages.get(alpha_2=t.language).name\n if t.channel_layout:\n channels = float(sum(self.AUDIO_CHANNEL_LAYOUT_WEIGHT.get(x,\n 1) for x in t.channel_layout.split(' ')))\n else:\n channels = float(t.channel_s)\n bit_rate_mode = f' ({t.bit_rate_mode})' if t.bit_rate_mode else ''\n l1 = (\n f'- {title}, {t.format} {channels} @ {t.other_bit_rate[0]}{bit_rate_mode}'\n )\n data += [(' ' + x if i > 0 else x) for i, x in enumerate(\n textwrap.wrap(l1, 64))]\n return data\n\n @staticmethod\n def get_subtitle_print(subs: List[Track]) ->List[str]:\n \"\"\"\n Return a list of a brief subtitle overview per-subtitle.\n\n e.g.\n - English, Forced, SubRip (SRT)\n - English, SubRip (SRT)\n - English, SDH, SubRip (SRT)\n - Spanish, Latin American (SDH), SubRip (SRT)\n\n The bit of text between the Language and the Subtitle format is the Track Title.\n It can be of any format, but it is recommended to be used as shown above.\n\n It will be returned as a list of strings with the `- ` already pre-pended to each entry.\n \"\"\"\n data = []\n if not subs:\n data.append('--')\n for sub in subs:\n line_items = []\n language = pycountry.languages.get(alpha_2=sub.language).name\n if sub.title:\n if language.lower() in sub.title.lower():\n line_items.append(sub.title)\n else:\n line_items.append(f'{language}, {sub.title}')\n else:\n line_items.append(language)\n line_items.append(sub.format.replace('UTF-8', 'SubRip (SRT)'))\n line = '- ' + ', '.join(line_items)\n data += [(' ' + x if i > 0 else x) for i, x in enumerate(\n textwrap.wrap(line, 64))]\n return data\n <mask token>\n\n def get_chapter_print_short(self, chapters: Dict[str, str]) ->str:\n if not chapters:\n return 'No'\n if self.chapters_numbered:\n return f'Yes (Numbered 01-{str(len(chapters)).zfill(2)})'\n return 'Yes (Named)'\n\n @staticmethod\n def get_session() ->requests.Session:\n session = requests.Session()\n session.headers.update({'User-Agent':\n 'Mozilla/5.0 (X11; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0'\n , 'Accept':\n 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'\n , 'Accept-Language': 'en-US,en;q=0.5', 'DNT': '1',\n 'UPGRADE-INSECURE-REQUESTS': '1'})\n return session\n", "step-3": "<mask token>\n\n\nclass NFO:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __repr__(self) ->str:\n return '<{c} {attrs}>'.format(c=self.__class__.__name__, attrs=' '.\n join('{}={!r}'.format(k, v) for k, v in self.__dict__.items()))\n\n def run(self, template: str, art: Optional[str]=None, **kwargs: Any) ->str:\n \"\"\"\n Evaluate and apply formatting on template, apply any art if provided.\n Any additional parameters are passed as extra variables to the template.\n The extra variables have priority when there's conflicting variable names.\n \"\"\"\n variables = self.__dict__\n variables.update(kwargs)\n template = CustomFormats().format(template, **variables)\n if art:\n art = art.format(nfo=template)\n template = art\n for m in re.finditer('<\\\\?([01])\\\\?([\\\\D\\\\d]*?)\\\\?>', template):\n template = template.replace(m.group(0), m.group(2) if int(m.\n group(1)) else '')\n template = '\\n'.join(map(str.rstrip, template.splitlines(keepends=\n False)))\n return template\n\n def set_config(self, file: str, **config: Any) ->None:\n self.file = file\n self.media_info = MediaInfo.parse(self.file)\n self.fanart_api_key = config.get('fanart_api_key')\n self.source = config.get('source')\n self.note = config.get('note')\n self.preview = config.get('preview')\n self.season = config.get('season')\n self.episode, self.episode_name = config.get('episode') or (None, None)\n self.episodes = self.get_tv_episodes()\n self.release_name = self.get_release_name()\n self.videos = self.media_info.video_tracks\n self.audio = self.media_info.audio_tracks\n self.subtitles = self.media_info.text_tracks\n tracks_without_language = [x for x in self.videos + self.audio +\n self.subtitles if not x.language or x.language == 'und']\n if tracks_without_language:\n print(\n 'The following tracks have no language tag! All tracks need a language tag!'\n )\n for track in tracks_without_language:\n print(\n f'{track.track_type} Track #{track.track_id} ({track.format}, {track.bit_rate / 1000} kb/s)'\n )\n print(\n \"\"\"Yes, even Video Track's have language e.g., Credits, Signs, Letters, Different Intro Sequence, etc.\nDon't forget to verify and add language tags to the rest of the files too!\"\"\"\n )\n sys.exit(1)\n chapters = next(iter(self.media_info.menu_tracks), None)\n if chapters:\n self.chapters = {'.'.join([k.replace('_', '.')[:-3], k[-3:]]):\n v.strip(':') for k, v in chapters.to_data().items() if\n f\"1{k.replace('_', '')}\".isdigit()}\n self.chapters_numbered = all(x.split(':', 1)[-1].lower() in [\n f'chapter {i + 1}', f'chapter {str(i + 1).zfill(2)}'] for i,\n x in enumerate(self.chapters.values()))\n else:\n self.chapters = {}\n self.chapters_numbered = False\n self.imdb = self.get_imdb_id(config.get('imdb'))\n self.tmdb = self.get_tmdb_id(config.get('tmdb'))\n self.tvdb = self.get_tvdb_id(config.get('tvdb'))\n self.title_name, self.title_year = self.get_title_name_year()\n self.banner_image = self.get_banner_image(self.tvdb\n ) if self.tvdb and self.fanart_api_key else None\n self.preview_images = self.get_preview_images(self.preview\n ) if self.preview else []\n\n def get_imdb_id(self, imdb_id: Any) ->str:\n \"\"\"\n Get an IMDB ID from either the media's global tags, or the config.\n Since IMDB IDs are required for this project, it will bug the user for\n one interactively if not found.\n \"\"\"\n if not imdb_id:\n general_track = self.media_info.general_tracks[0].to_data()\n imdb_id = general_track.get('imdb')\n if not imdb_id:\n print('No IMDB ID was provided but is required...')\n while not imdb_id or not isinstance(imdb_id, str):\n user_id = input(\"IMDB ID (e.g., 'tt0487831'): \")\n if not self.IMDB_ID_T.match(user_id):\n print(f'The provided IMDB ID {user_id!r} is not valid...')\n print(\n \"Expected e.g., 'tt0487831', 'tt10810424', (include the 'tt').\"\n )\n else:\n imdb_id = user_id\n return imdb_id\n\n def get_tmdb_id(self, tmdb_id: Any) ->Optional[str]:\n \"\"\"\n Get a TMDB ID from either the media's global tags, or the config.\n It will raise a ValueError if the provided ID is invalid.\n \"\"\"\n if not tmdb_id:\n general_track = self.media_info.general_tracks[0].to_data()\n tmdb_id = general_track.get('tmdb')\n if not tmdb_id:\n print('Warning: No TMDB ID was provided...')\n return None\n if not self.TMDB_ID_T.match(tmdb_id) or not isinstance(tmdb_id, str):\n print(f'The provided TMDB ID {tmdb_id!r} is not valid...')\n print(\n \"Expected e.g., 'tv/2490', 'movie/14836', (include the 'tv/' or 'movie/').\"\n )\n raise ValueError('Invalid TMDB ID')\n return tmdb_id\n\n def get_tvdb_id(self, tvdb_id: Any) ->Optional[int]:\n \"\"\"\n Get a TVDB ID from either the media's global tags, or the config.\n It will raise a ValueError if the provided ID is invalid.\n \"\"\"\n if not tvdb_id:\n general_track = self.media_info.general_tracks[0].to_data()\n tvdb_id = general_track.get('tvdb')\n if not tvdb_id:\n print('Warning: No TVDB ID was provided...')\n return None\n if isinstance(tvdb_id, int):\n tvdb_id = str(tvdb_id)\n if not self.TVDB_ID_T.match(tvdb_id) or not isinstance(tvdb_id, str):\n print(f'The provided TVDB ID {tvdb_id!r} is not valid...')\n print(\n \"Expected e.g., '79216', '1395', (not the url slug e.g., 'the-office-us').\"\n )\n raise ValueError('Invalid TVDB ID')\n return int(tvdb_id)\n\n def get_title_name_year(self) ->Tuple[str, str]:\n \"\"\"Scrape Title Name and Year (including e.g. 2019-) from IMDB\"\"\"\n r = self.session.get(f'https://www.imdb.com/title/{self.imdb}')\n if r.status_code != 200:\n raise ValueError(\n f'An unexpected error occurred getting IMDB Title Page [{r.status_code}]'\n )\n imdb_page = html.unescape(r.text)\n imdb_title = re.search(\n '<title>(?P<name>.+) \\\\(((?P<type>TV (Movie|Series|Mini[- ]Series|Short|Episode) |Video |Short |)(?P<year>(\\\\d{4})(|– |–\\\\d{4})))\\\\) - IMDb</title>'\n , imdb_page)\n if not imdb_title:\n raise ValueError(\n f'Could not scrape Movie Title or Year for {self.imdb}...')\n return imdb_title.group('name').strip(), imdb_title.group('year'\n ).strip()\n\n def get_tv_episodes(self) ->int:\n \"\"\"Calculate total episode count based on neighbouring same-extension files.\"\"\"\n return len(glob.glob(os.path.join(os.path.dirname(self.file),\n f'*{os.path.splitext(self.file)[-1]}')))\n\n def get_release_name(self) ->str:\n \"\"\"\n Retrieve the release name based on the file used during MediaInfo.\n If a season was specified, but an episode number was not, it presumes the release is a Pack.\n Hence when pack, it uses the parent folder's name as the release name.\n \"\"\"\n if self.season is not None and self.episode is None:\n return os.path.basename(os.path.dirname(self.file))\n return os.path.splitext(os.path.basename(self.file))[0]\n\n def get_banner_image(self, tvdb_id: int) ->Optional[str]:\n \"\"\"\n Get a wide banner image from fanart.tv.\n Currently restricts banners to English-only.\n \"\"\"\n if not tvdb_id:\n return None\n if not self.fanart_api_key:\n raise ValueError('Need Fanart.tv api key for TV titles!')\n r = self.session.get(\n f'http://webservice.fanart.tv/v3/tv/{tvdb_id}?api_key={self.fanart_api_key}'\n )\n if r.status_code == 404:\n return None\n res = r.json()\n error = res.get('error message')\n if error:\n if error == 'Not found':\n return None\n raise ValueError(\n f'An unexpected error occurred while calling Fanart.tv, {res}')\n banner = next((x['url'] for x in res.get('tvbanner') or [] if x[\n 'lang'] == sorted(self.audio, key=lambda x: x.streamorder)[0].\n language), None)\n return banner\n\n def get_preview_images(self, url: str) ->List[Dict[str, str]]:\n if not url:\n return []\n images = []\n for domain in ['imgbox.com', 'beyondhd.co']:\n if domain not in url.lower():\n continue\n page = self.session.get(url).text\n if domain == 'imgbox.com':\n for m in re.finditer(\n 'src=\"(https://thumbs2.imgbox.com.+/)(\\\\w+)_b.([^\"]+)',\n page):\n images.append({'url':\n f'https://imgbox.com/{m.group(2)}', 'src':\n f'{m.group(1)}{m.group(2)}_t.{m.group(3)}'})\n elif domain == 'beyondhd.co':\n for m in re.finditer(\n '/image/([^\"]+)\"\\\\D+src=\"(https://.*beyondhd.co/images.+/(\\\\w+).md.[^\"]+)'\n , page):\n images.append({'url':\n f'https://beyondhd.co/image/{m.group(1)}', 'src': m\n .group(2)})\n break\n return images\n\n def get_video_print(self, videos: List[Track]) ->List[List[str]]:\n if not videos:\n return [['--']]\n data = []\n for video in videos:\n codec = {'MPEG Video':\n f\"MPEG-{(video.format_version or '').replace('Version ', '')}\"\n }.get(video.format, video.format)\n scan_overview = video.scan_type\n vst = False\n if codec in ['MPEG-1', 'MPEG-2']:\n d2v = D2V.load(Path(self.file))\n self.file = d2v.path\n flags = [f for line in [[dict(**y, vob=x['vob'], cell=x[\n 'cell']) for y in x['flags']] for x in d2v.data] for f in\n line]\n interlaced_percent = sum(1 for f in flags if not f[\n 'progressive_frame']) / len(flags) * 100\n if interlaced_percent == 100:\n scan_overview = 'Interlaced (CST)'\n else:\n scan_overview = (\n f'{round(interlaced_percent, 2)}% Interlaced (VST)')\n vst = True\n for ext in ['log', 'd2v', 'mpg', 'mpeg']:\n fp = os.path.splitext(self.file)[0] + '.' + ext\n if os.path.exists(fp):\n os.unlink(fp)\n line_1 = (\n '- {language}, {codec} ({profile}) {width}x{height} ({aspect}) @ {bitrate}'\n .format(language=pycountry.languages.get(alpha_2=video.\n language).name, codec=codec, profile=video.format_profile,\n width=video.width, height=video.height, aspect=video.\n other_display_aspect_ratio[0], bitrate=\n f\"{video.other_bit_rate[0]}{f' ({video.bit_rate_mode})' if video.bit_rate_mode else ''}\"\n ))\n line_2 = (\n ' {fps} FPS ({fps_mode}), {color_space}{subsampling}P{bit_depth}, {scan}'\n .format(fps=f'{video.framerate_num}/{video.framerate_den}' if\n video.framerate_num else video.frame_rate, fps_mode='VFR' if\n vst else video.frame_rate_mode, color_space=video.\n color_space, subsampling=video.chroma_subsampling.replace(\n ':', ''), bit_depth=video.bit_depth, scan=scan_overview))\n data.append([line_1, line_2])\n return data\n\n def get_audio_print(self, audio: List[Track]) ->List[str]:\n if not audio:\n return ['--']\n data = []\n for t in audio:\n if t.title and 'Commentary' in t.title:\n title = t.title\n else:\n title = pycountry.languages.get(alpha_2=t.language).name\n if t.channel_layout:\n channels = float(sum(self.AUDIO_CHANNEL_LAYOUT_WEIGHT.get(x,\n 1) for x in t.channel_layout.split(' ')))\n else:\n channels = float(t.channel_s)\n bit_rate_mode = f' ({t.bit_rate_mode})' if t.bit_rate_mode else ''\n l1 = (\n f'- {title}, {t.format} {channels} @ {t.other_bit_rate[0]}{bit_rate_mode}'\n )\n data += [(' ' + x if i > 0 else x) for i, x in enumerate(\n textwrap.wrap(l1, 64))]\n return data\n\n @staticmethod\n def get_subtitle_print(subs: List[Track]) ->List[str]:\n \"\"\"\n Return a list of a brief subtitle overview per-subtitle.\n\n e.g.\n - English, Forced, SubRip (SRT)\n - English, SubRip (SRT)\n - English, SDH, SubRip (SRT)\n - Spanish, Latin American (SDH), SubRip (SRT)\n\n The bit of text between the Language and the Subtitle format is the Track Title.\n It can be of any format, but it is recommended to be used as shown above.\n\n It will be returned as a list of strings with the `- ` already pre-pended to each entry.\n \"\"\"\n data = []\n if not subs:\n data.append('--')\n for sub in subs:\n line_items = []\n language = pycountry.languages.get(alpha_2=sub.language).name\n if sub.title:\n if language.lower() in sub.title.lower():\n line_items.append(sub.title)\n else:\n line_items.append(f'{language}, {sub.title}')\n else:\n line_items.append(language)\n line_items.append(sub.format.replace('UTF-8', 'SubRip (SRT)'))\n line = '- ' + ', '.join(line_items)\n data += [(' ' + x if i > 0 else x) for i, x in enumerate(\n textwrap.wrap(line, 64))]\n return data\n\n @staticmethod\n def get_chapter_print(chapters: Dict[str, str]) ->List[str]:\n if not chapters:\n return ['--']\n return [f'- {k}: {v}' for k, v in chapters.items()]\n\n def get_chapter_print_short(self, chapters: Dict[str, str]) ->str:\n if not chapters:\n return 'No'\n if self.chapters_numbered:\n return f'Yes (Numbered 01-{str(len(chapters)).zfill(2)})'\n return 'Yes (Named)'\n\n @staticmethod\n def get_session() ->requests.Session:\n session = requests.Session()\n session.headers.update({'User-Agent':\n 'Mozilla/5.0 (X11; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0'\n , 'Accept':\n 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'\n , 'Accept-Language': 'en-US,en;q=0.5', 'DNT': '1',\n 'UPGRADE-INSECURE-REQUESTS': '1'})\n return session\n", "step-4": "<mask token>\n\n\nclass NFO:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self) ->None:\n self.media_info: MediaInfo\n self.file: str\n self.season: Optional[Union[int, str]]\n self.episode: Optional[int]\n self.episode_name: Optional[str]\n self.videos: List[Track]\n self.audio: List[Track]\n self.subtitles: List[Track]\n self.chapters: Dict[str, str]\n self.chapters_numbered: bool\n self.fanart_api_key: Optional[str]\n self.source: Optional[str]\n self.note: Optional[str]\n self.preview: Optional[str]\n self.imdb: str\n self.tmdb: Optional[str]\n self.tvdb: Optional[int]\n self.title_name: str\n self.title_year: str\n self.episodes: int\n self.release_name: str\n self.preview_images: List[dict[str, str]]\n self.banner_image: Optional[str]\n self.session = self.get_session()\n\n def __repr__(self) ->str:\n return '<{c} {attrs}>'.format(c=self.__class__.__name__, attrs=' '.\n join('{}={!r}'.format(k, v) for k, v in self.__dict__.items()))\n\n def run(self, template: str, art: Optional[str]=None, **kwargs: Any) ->str:\n \"\"\"\n Evaluate and apply formatting on template, apply any art if provided.\n Any additional parameters are passed as extra variables to the template.\n The extra variables have priority when there's conflicting variable names.\n \"\"\"\n variables = self.__dict__\n variables.update(kwargs)\n template = CustomFormats().format(template, **variables)\n if art:\n art = art.format(nfo=template)\n template = art\n for m in re.finditer('<\\\\?([01])\\\\?([\\\\D\\\\d]*?)\\\\?>', template):\n template = template.replace(m.group(0), m.group(2) if int(m.\n group(1)) else '')\n template = '\\n'.join(map(str.rstrip, template.splitlines(keepends=\n False)))\n return template\n\n def set_config(self, file: str, **config: Any) ->None:\n self.file = file\n self.media_info = MediaInfo.parse(self.file)\n self.fanart_api_key = config.get('fanart_api_key')\n self.source = config.get('source')\n self.note = config.get('note')\n self.preview = config.get('preview')\n self.season = config.get('season')\n self.episode, self.episode_name = config.get('episode') or (None, None)\n self.episodes = self.get_tv_episodes()\n self.release_name = self.get_release_name()\n self.videos = self.media_info.video_tracks\n self.audio = self.media_info.audio_tracks\n self.subtitles = self.media_info.text_tracks\n tracks_without_language = [x for x in self.videos + self.audio +\n self.subtitles if not x.language or x.language == 'und']\n if tracks_without_language:\n print(\n 'The following tracks have no language tag! All tracks need a language tag!'\n )\n for track in tracks_without_language:\n print(\n f'{track.track_type} Track #{track.track_id} ({track.format}, {track.bit_rate / 1000} kb/s)'\n )\n print(\n \"\"\"Yes, even Video Track's have language e.g., Credits, Signs, Letters, Different Intro Sequence, etc.\nDon't forget to verify and add language tags to the rest of the files too!\"\"\"\n )\n sys.exit(1)\n chapters = next(iter(self.media_info.menu_tracks), None)\n if chapters:\n self.chapters = {'.'.join([k.replace('_', '.')[:-3], k[-3:]]):\n v.strip(':') for k, v in chapters.to_data().items() if\n f\"1{k.replace('_', '')}\".isdigit()}\n self.chapters_numbered = all(x.split(':', 1)[-1].lower() in [\n f'chapter {i + 1}', f'chapter {str(i + 1).zfill(2)}'] for i,\n x in enumerate(self.chapters.values()))\n else:\n self.chapters = {}\n self.chapters_numbered = False\n self.imdb = self.get_imdb_id(config.get('imdb'))\n self.tmdb = self.get_tmdb_id(config.get('tmdb'))\n self.tvdb = self.get_tvdb_id(config.get('tvdb'))\n self.title_name, self.title_year = self.get_title_name_year()\n self.banner_image = self.get_banner_image(self.tvdb\n ) if self.tvdb and self.fanart_api_key else None\n self.preview_images = self.get_preview_images(self.preview\n ) if self.preview else []\n\n def get_imdb_id(self, imdb_id: Any) ->str:\n \"\"\"\n Get an IMDB ID from either the media's global tags, or the config.\n Since IMDB IDs are required for this project, it will bug the user for\n one interactively if not found.\n \"\"\"\n if not imdb_id:\n general_track = self.media_info.general_tracks[0].to_data()\n imdb_id = general_track.get('imdb')\n if not imdb_id:\n print('No IMDB ID was provided but is required...')\n while not imdb_id or not isinstance(imdb_id, str):\n user_id = input(\"IMDB ID (e.g., 'tt0487831'): \")\n if not self.IMDB_ID_T.match(user_id):\n print(f'The provided IMDB ID {user_id!r} is not valid...')\n print(\n \"Expected e.g., 'tt0487831', 'tt10810424', (include the 'tt').\"\n )\n else:\n imdb_id = user_id\n return imdb_id\n\n def get_tmdb_id(self, tmdb_id: Any) ->Optional[str]:\n \"\"\"\n Get a TMDB ID from either the media's global tags, or the config.\n It will raise a ValueError if the provided ID is invalid.\n \"\"\"\n if not tmdb_id:\n general_track = self.media_info.general_tracks[0].to_data()\n tmdb_id = general_track.get('tmdb')\n if not tmdb_id:\n print('Warning: No TMDB ID was provided...')\n return None\n if not self.TMDB_ID_T.match(tmdb_id) or not isinstance(tmdb_id, str):\n print(f'The provided TMDB ID {tmdb_id!r} is not valid...')\n print(\n \"Expected e.g., 'tv/2490', 'movie/14836', (include the 'tv/' or 'movie/').\"\n )\n raise ValueError('Invalid TMDB ID')\n return tmdb_id\n\n def get_tvdb_id(self, tvdb_id: Any) ->Optional[int]:\n \"\"\"\n Get a TVDB ID from either the media's global tags, or the config.\n It will raise a ValueError if the provided ID is invalid.\n \"\"\"\n if not tvdb_id:\n general_track = self.media_info.general_tracks[0].to_data()\n tvdb_id = general_track.get('tvdb')\n if not tvdb_id:\n print('Warning: No TVDB ID was provided...')\n return None\n if isinstance(tvdb_id, int):\n tvdb_id = str(tvdb_id)\n if not self.TVDB_ID_T.match(tvdb_id) or not isinstance(tvdb_id, str):\n print(f'The provided TVDB ID {tvdb_id!r} is not valid...')\n print(\n \"Expected e.g., '79216', '1395', (not the url slug e.g., 'the-office-us').\"\n )\n raise ValueError('Invalid TVDB ID')\n return int(tvdb_id)\n\n def get_title_name_year(self) ->Tuple[str, str]:\n \"\"\"Scrape Title Name and Year (including e.g. 2019-) from IMDB\"\"\"\n r = self.session.get(f'https://www.imdb.com/title/{self.imdb}')\n if r.status_code != 200:\n raise ValueError(\n f'An unexpected error occurred getting IMDB Title Page [{r.status_code}]'\n )\n imdb_page = html.unescape(r.text)\n imdb_title = re.search(\n '<title>(?P<name>.+) \\\\(((?P<type>TV (Movie|Series|Mini[- ]Series|Short|Episode) |Video |Short |)(?P<year>(\\\\d{4})(|– |–\\\\d{4})))\\\\) - IMDb</title>'\n , imdb_page)\n if not imdb_title:\n raise ValueError(\n f'Could not scrape Movie Title or Year for {self.imdb}...')\n return imdb_title.group('name').strip(), imdb_title.group('year'\n ).strip()\n\n def get_tv_episodes(self) ->int:\n \"\"\"Calculate total episode count based on neighbouring same-extension files.\"\"\"\n return len(glob.glob(os.path.join(os.path.dirname(self.file),\n f'*{os.path.splitext(self.file)[-1]}')))\n\n def get_release_name(self) ->str:\n \"\"\"\n Retrieve the release name based on the file used during MediaInfo.\n If a season was specified, but an episode number was not, it presumes the release is a Pack.\n Hence when pack, it uses the parent folder's name as the release name.\n \"\"\"\n if self.season is not None and self.episode is None:\n return os.path.basename(os.path.dirname(self.file))\n return os.path.splitext(os.path.basename(self.file))[0]\n\n def get_banner_image(self, tvdb_id: int) ->Optional[str]:\n \"\"\"\n Get a wide banner image from fanart.tv.\n Currently restricts banners to English-only.\n \"\"\"\n if not tvdb_id:\n return None\n if not self.fanart_api_key:\n raise ValueError('Need Fanart.tv api key for TV titles!')\n r = self.session.get(\n f'http://webservice.fanart.tv/v3/tv/{tvdb_id}?api_key={self.fanart_api_key}'\n )\n if r.status_code == 404:\n return None\n res = r.json()\n error = res.get('error message')\n if error:\n if error == 'Not found':\n return None\n raise ValueError(\n f'An unexpected error occurred while calling Fanart.tv, {res}')\n banner = next((x['url'] for x in res.get('tvbanner') or [] if x[\n 'lang'] == sorted(self.audio, key=lambda x: x.streamorder)[0].\n language), None)\n return banner\n\n def get_preview_images(self, url: str) ->List[Dict[str, str]]:\n if not url:\n return []\n images = []\n for domain in ['imgbox.com', 'beyondhd.co']:\n if domain not in url.lower():\n continue\n page = self.session.get(url).text\n if domain == 'imgbox.com':\n for m in re.finditer(\n 'src=\"(https://thumbs2.imgbox.com.+/)(\\\\w+)_b.([^\"]+)',\n page):\n images.append({'url':\n f'https://imgbox.com/{m.group(2)}', 'src':\n f'{m.group(1)}{m.group(2)}_t.{m.group(3)}'})\n elif domain == 'beyondhd.co':\n for m in re.finditer(\n '/image/([^\"]+)\"\\\\D+src=\"(https://.*beyondhd.co/images.+/(\\\\w+).md.[^\"]+)'\n , page):\n images.append({'url':\n f'https://beyondhd.co/image/{m.group(1)}', 'src': m\n .group(2)})\n break\n return images\n\n def get_video_print(self, videos: List[Track]) ->List[List[str]]:\n if not videos:\n return [['--']]\n data = []\n for video in videos:\n codec = {'MPEG Video':\n f\"MPEG-{(video.format_version or '').replace('Version ', '')}\"\n }.get(video.format, video.format)\n scan_overview = video.scan_type\n vst = False\n if codec in ['MPEG-1', 'MPEG-2']:\n d2v = D2V.load(Path(self.file))\n self.file = d2v.path\n flags = [f for line in [[dict(**y, vob=x['vob'], cell=x[\n 'cell']) for y in x['flags']] for x in d2v.data] for f in\n line]\n interlaced_percent = sum(1 for f in flags if not f[\n 'progressive_frame']) / len(flags) * 100\n if interlaced_percent == 100:\n scan_overview = 'Interlaced (CST)'\n else:\n scan_overview = (\n f'{round(interlaced_percent, 2)}% Interlaced (VST)')\n vst = True\n for ext in ['log', 'd2v', 'mpg', 'mpeg']:\n fp = os.path.splitext(self.file)[0] + '.' + ext\n if os.path.exists(fp):\n os.unlink(fp)\n line_1 = (\n '- {language}, {codec} ({profile}) {width}x{height} ({aspect}) @ {bitrate}'\n .format(language=pycountry.languages.get(alpha_2=video.\n language).name, codec=codec, profile=video.format_profile,\n width=video.width, height=video.height, aspect=video.\n other_display_aspect_ratio[0], bitrate=\n f\"{video.other_bit_rate[0]}{f' ({video.bit_rate_mode})' if video.bit_rate_mode else ''}\"\n ))\n line_2 = (\n ' {fps} FPS ({fps_mode}), {color_space}{subsampling}P{bit_depth}, {scan}'\n .format(fps=f'{video.framerate_num}/{video.framerate_den}' if\n video.framerate_num else video.frame_rate, fps_mode='VFR' if\n vst else video.frame_rate_mode, color_space=video.\n color_space, subsampling=video.chroma_subsampling.replace(\n ':', ''), bit_depth=video.bit_depth, scan=scan_overview))\n data.append([line_1, line_2])\n return data\n\n def get_audio_print(self, audio: List[Track]) ->List[str]:\n if not audio:\n return ['--']\n data = []\n for t in audio:\n if t.title and 'Commentary' in t.title:\n title = t.title\n else:\n title = pycountry.languages.get(alpha_2=t.language).name\n if t.channel_layout:\n channels = float(sum(self.AUDIO_CHANNEL_LAYOUT_WEIGHT.get(x,\n 1) for x in t.channel_layout.split(' ')))\n else:\n channels = float(t.channel_s)\n bit_rate_mode = f' ({t.bit_rate_mode})' if t.bit_rate_mode else ''\n l1 = (\n f'- {title}, {t.format} {channels} @ {t.other_bit_rate[0]}{bit_rate_mode}'\n )\n data += [(' ' + x if i > 0 else x) for i, x in enumerate(\n textwrap.wrap(l1, 64))]\n return data\n\n @staticmethod\n def get_subtitle_print(subs: List[Track]) ->List[str]:\n \"\"\"\n Return a list of a brief subtitle overview per-subtitle.\n\n e.g.\n - English, Forced, SubRip (SRT)\n - English, SubRip (SRT)\n - English, SDH, SubRip (SRT)\n - Spanish, Latin American (SDH), SubRip (SRT)\n\n The bit of text between the Language and the Subtitle format is the Track Title.\n It can be of any format, but it is recommended to be used as shown above.\n\n It will be returned as a list of strings with the `- ` already pre-pended to each entry.\n \"\"\"\n data = []\n if not subs:\n data.append('--')\n for sub in subs:\n line_items = []\n language = pycountry.languages.get(alpha_2=sub.language).name\n if sub.title:\n if language.lower() in sub.title.lower():\n line_items.append(sub.title)\n else:\n line_items.append(f'{language}, {sub.title}')\n else:\n line_items.append(language)\n line_items.append(sub.format.replace('UTF-8', 'SubRip (SRT)'))\n line = '- ' + ', '.join(line_items)\n data += [(' ' + x if i > 0 else x) for i, x in enumerate(\n textwrap.wrap(line, 64))]\n return data\n\n @staticmethod\n def get_chapter_print(chapters: Dict[str, str]) ->List[str]:\n if not chapters:\n return ['--']\n return [f'- {k}: {v}' for k, v in chapters.items()]\n\n def get_chapter_print_short(self, chapters: Dict[str, str]) ->str:\n if not chapters:\n return 'No'\n if self.chapters_numbered:\n return f'Yes (Numbered 01-{str(len(chapters)).zfill(2)})'\n return 'Yes (Named)'\n\n @staticmethod\n def get_session() ->requests.Session:\n session = requests.Session()\n session.headers.update({'User-Agent':\n 'Mozilla/5.0 (X11; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0'\n , 'Accept':\n 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'\n , 'Accept-Language': 'en-US,en;q=0.5', 'DNT': '1',\n 'UPGRADE-INSECURE-REQUESTS': '1'})\n return session\n", "step-5": "import glob\nimport html\nimport os\nimport re\nimport sys\nimport textwrap\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional, Tuple, Union\n\nimport pycountry\nimport requests\nfrom pyd2v import D2V\nfrom pymediainfo import MediaInfo, Track\n\nfrom pynfogen.formatter import CustomFormats\n\n\nclass NFO:\n AUDIO_CHANNEL_LAYOUT_WEIGHT = {\n \"LFE\": 0.1\n }\n IMDB_ID_T = re.compile(r\"^tt\\d{7,8}$\")\n TMDB_ID_T = re.compile(r\"^(tv|movie)/\\d+$\")\n TVDB_ID_T = re.compile(r\"^\\d+$\")\n\n def __init__(self) -> None:\n self.media_info: MediaInfo\n\n self.file: str\n self.season: Optional[Union[int, str]]\n self.episode: Optional[int]\n self.episode_name: Optional[str]\n\n self.videos: List[Track]\n self.audio: List[Track]\n self.subtitles: List[Track]\n self.chapters: Dict[str, str]\n self.chapters_numbered: bool\n\n self.fanart_api_key: Optional[str]\n self.source: Optional[str]\n self.note: Optional[str]\n self.preview: Optional[str]\n\n self.imdb: str\n self.tmdb: Optional[str]\n self.tvdb: Optional[int]\n\n self.title_name: str\n self.title_year: str\n self.episodes: int\n self.release_name: str\n self.preview_images: List[dict[str, str]]\n self.banner_image: Optional[str]\n\n self.session = self.get_session()\n\n def __repr__(self) -> str:\n return \"<{c} {attrs}>\".format(\n c=self.__class__.__name__,\n attrs=\" \".join(\"{}={!r}\".format(k, v) for k, v in self.__dict__.items()),\n )\n\n def run(self, template: str, art: Optional[str] = None, **kwargs: Any) -> str:\n \"\"\"\n Evaluate and apply formatting on template, apply any art if provided.\n Any additional parameters are passed as extra variables to the template.\n The extra variables have priority when there's conflicting variable names.\n \"\"\"\n variables = self.__dict__\n variables.update(kwargs)\n\n template = CustomFormats().format(template, **variables)\n if art:\n art = art.format(nfo=template)\n template = art\n\n for m in re.finditer(r\"<\\?([01])\\?([\\D\\d]*?)\\?>\", template):\n # TODO: This if check is quite yucky, look into alternative options.\n # Ideally a custom format spec would be great.\n template = template.replace(\n m.group(0),\n m.group(2) if int(m.group(1)) else \"\"\n )\n\n template = \"\\n\".join(map(str.rstrip, template.splitlines(keepends=False)))\n\n return template\n\n def set_config(self, file: str, **config: Any) -> None:\n self.file = file\n self.media_info = MediaInfo.parse(self.file)\n\n self.fanart_api_key = config.get(\"fanart_api_key\")\n self.source = config.get(\"source\")\n self.note = config.get(\"note\")\n self.preview = config.get(\"preview\")\n\n self.season = config.get(\"season\")\n self.episode, self.episode_name = config.get(\"episode\") or (None, None)\n self.episodes = self.get_tv_episodes()\n self.release_name = self.get_release_name()\n\n self.videos = self.media_info.video_tracks\n self.audio = self.media_info.audio_tracks\n self.subtitles = self.media_info.text_tracks\n\n tracks_without_language = [\n x for x in self.videos + self.audio + self.subtitles\n if not x.language or x.language == \"und\"\n ]\n if tracks_without_language:\n print(\"The following tracks have no language tag! All tracks need a language tag!\")\n for track in tracks_without_language:\n print(f\"{track.track_type} Track #{track.track_id} ({track.format}, {track.bit_rate / 1000} kb/s)\")\n print(\n \"Yes, even Video Track's have language e.g., Credits, Signs, Letters, Different Intro Sequence, etc.\\n\"\n \"Don't forget to verify and add language tags to the rest of the files too!\"\n )\n sys.exit(1)\n\n chapters = next(iter(self.media_info.menu_tracks), None)\n if chapters:\n self.chapters = {\n \".\".join([k.replace(\"_\", \".\")[:-3], k[-3:]]): v.strip(\":\")\n for k, v in chapters.to_data().items()\n if f\"1{k.replace('_', '')}\".isdigit()\n }\n self.chapters_numbered = all(\n x.split(\":\", 1)[-1].lower() in [f\"chapter {i + 1}\", f\"chapter {str(i + 1).zfill(2)}\"]\n for i, x in enumerate(self.chapters.values())\n )\n else:\n self.chapters = {}\n self.chapters_numbered = False\n\n self.imdb = self.get_imdb_id(config.get(\"imdb\"))\n self.tmdb = self.get_tmdb_id(config.get(\"tmdb\"))\n self.tvdb = self.get_tvdb_id(config.get(\"tvdb\"))\n\n self.title_name, self.title_year = self.get_title_name_year()\n self.banner_image = self.get_banner_image(self.tvdb) if self.tvdb and self.fanart_api_key else None\n self.preview_images = self.get_preview_images(self.preview) if self.preview else []\n\n def get_imdb_id(self, imdb_id: Any) -> str:\n \"\"\"\n Get an IMDB ID from either the media's global tags, or the config.\n Since IMDB IDs are required for this project, it will bug the user for\n one interactively if not found.\n \"\"\"\n if not imdb_id:\n general_track = self.media_info.general_tracks[0].to_data()\n imdb_id = general_track.get(\"imdb\")\n if not imdb_id:\n print(\"No IMDB ID was provided but is required...\")\n while not imdb_id or not isinstance(imdb_id, str):\n user_id = input(\"IMDB ID (e.g., 'tt0487831'): \")\n if not self.IMDB_ID_T.match(user_id):\n print(f\"The provided IMDB ID {user_id!r} is not valid...\")\n print(\"Expected e.g., 'tt0487831', 'tt10810424', (include the 'tt').\")\n else:\n imdb_id = user_id\n return imdb_id\n\n def get_tmdb_id(self, tmdb_id: Any) -> Optional[str]:\n \"\"\"\n Get a TMDB ID from either the media's global tags, or the config.\n It will raise a ValueError if the provided ID is invalid.\n \"\"\"\n if not tmdb_id:\n general_track = self.media_info.general_tracks[0].to_data()\n tmdb_id = general_track.get(\"tmdb\")\n if not tmdb_id:\n print(\"Warning: No TMDB ID was provided...\")\n return None\n if not self.TMDB_ID_T.match(tmdb_id) or not isinstance(tmdb_id, str):\n print(f\"The provided TMDB ID {tmdb_id!r} is not valid...\")\n print(\"Expected e.g., 'tv/2490', 'movie/14836', (include the 'tv/' or 'movie/').\")\n raise ValueError(\"Invalid TMDB ID\")\n return tmdb_id\n\n def get_tvdb_id(self, tvdb_id: Any) -> Optional[int]:\n \"\"\"\n Get a TVDB ID from either the media's global tags, or the config.\n It will raise a ValueError if the provided ID is invalid.\n \"\"\"\n if not tvdb_id:\n general_track = self.media_info.general_tracks[0].to_data()\n tvdb_id = general_track.get(\"tvdb\")\n if not tvdb_id:\n print(\"Warning: No TVDB ID was provided...\")\n return None\n if isinstance(tvdb_id, int):\n tvdb_id = str(tvdb_id)\n if not self.TVDB_ID_T.match(tvdb_id) or not isinstance(tvdb_id, str):\n print(f\"The provided TVDB ID {tvdb_id!r} is not valid...\")\n print(\"Expected e.g., '79216', '1395', (not the url slug e.g., 'the-office-us').\")\n raise ValueError(\"Invalid TVDB ID\")\n return int(tvdb_id)\n\n def get_title_name_year(self) -> Tuple[str, str]:\n \"\"\"Scrape Title Name and Year (including e.g. 2019-) from IMDB\"\"\"\n r = self.session.get(f\"https://www.imdb.com/title/{self.imdb}\")\n if r.status_code != 200:\n raise ValueError(f\"An unexpected error occurred getting IMDB Title Page [{r.status_code}]\")\n imdb_page = html.unescape(r.text)\n imdb_title = re.search(\n # testing ground: https://regex101.com/r/bEoEDn/1\n r\"<title>(?P<name>.+) \\(((?P<type>TV (Movie|Series|Mini[- ]Series|Short|Episode) |Video |Short |)\"\n r\"(?P<year>(\\d{4})(|– |–\\d{4})))\\) - IMDb</title>\",\n imdb_page\n )\n if not imdb_title:\n raise ValueError(f\"Could not scrape Movie Title or Year for {self.imdb}...\")\n return imdb_title.group(\"name\").strip(), imdb_title.group(\"year\").strip()\n\n def get_tv_episodes(self) -> int:\n \"\"\"Calculate total episode count based on neighbouring same-extension files.\"\"\"\n return len(glob.glob(os.path.join(\n os.path.dirname(self.file),\n f\"*{os.path.splitext(self.file)[-1]}\"\n )))\n\n def get_release_name(self) -> str:\n \"\"\"\n Retrieve the release name based on the file used during MediaInfo.\n If a season was specified, but an episode number was not, it presumes the release is a Pack.\n Hence when pack, it uses the parent folder's name as the release name.\n \"\"\"\n if self.season is not None and self.episode is None:\n return os.path.basename(os.path.dirname(self.file))\n return os.path.splitext(os.path.basename(self.file))[0]\n\n def get_banner_image(self, tvdb_id: int) -> Optional[str]:\n \"\"\"\n Get a wide banner image from fanart.tv.\n Currently restricts banners to English-only.\n \"\"\"\n if not tvdb_id:\n return None\n if not self.fanart_api_key:\n raise ValueError(\"Need Fanart.tv api key for TV titles!\")\n\n r = self.session.get(f\"http://webservice.fanart.tv/v3/tv/{tvdb_id}?api_key={self.fanart_api_key}\")\n if r.status_code == 404:\n return None\n res = r.json()\n\n error = res.get(\"error message\")\n if error:\n if error == \"Not found\":\n return None\n raise ValueError(f\"An unexpected error occurred while calling Fanart.tv, {res}\")\n\n banner = next((\n x[\"url\"] for x in (res.get(\"tvbanner\") or [])\n if x[\"lang\"] == sorted(self.audio, key=lambda x: x.streamorder)[0].language\n ), None)\n\n return banner\n\n def get_preview_images(self, url: str) -> List[Dict[str, str]]:\n if not url:\n return []\n images = []\n for domain in [\"imgbox.com\", \"beyondhd.co\"]:\n if domain not in url.lower():\n continue\n page = self.session.get(url).text\n if domain == \"imgbox.com\":\n for m in re.finditer('src=\"(https://thumbs2.imgbox.com.+/)(\\\\w+)_b.([^\"]+)', page):\n images.append({\n \"url\": f\"https://imgbox.com/{m.group(2)}\",\n \"src\": f\"{m.group(1)}{m.group(2)}_t.{m.group(3)}\"\n })\n elif domain == \"beyondhd.co\":\n for m in re.finditer('/image/([^\"]+)\"\\\\D+src=\"(https://.*beyondhd.co/images.+/(\\\\w+).md.[^\"]+)', page):\n images.append({\n \"url\": f\"https://beyondhd.co/image/{m.group(1)}\",\n \"src\": m.group(2)\n })\n break\n return images\n\n def get_video_print(self, videos: List[Track]) -> List[List[str]]:\n if not videos:\n return [[\"--\"]]\n data = []\n for video in videos:\n codec = {\n \"MPEG Video\": f\"MPEG-{(video.format_version or '').replace('Version ', '')}\"\n }.get(video.format, video.format)\n scan_overview = video.scan_type\n vst = False\n if codec in [\"MPEG-1\", \"MPEG-2\"]:\n # parse d2v file with pyd2v, generates D2V if needed\n d2v = D2V.load(Path(self.file))\n self.file = d2v.path\n # get every frames' flag data, this contains information on displaying frames\n # add vob and cell number to each frames flag data as well\n flags = [f for line in [\n [dict(**y, vob=x[\"vob\"], cell=x[\"cell\"]) for y in x[\"flags\"]] for x in d2v.data\n ] for f in line]\n interlaced_percent = (sum(1 for f in flags if not f[\"progressive_frame\"]) / len(flags)) * 100\n if interlaced_percent == 100:\n scan_overview = \"Interlaced (CST)\"\n else:\n scan_overview = f\"{round(interlaced_percent, 2)}% Interlaced (VST)\"\n vst = True\n for ext in [\"log\", \"d2v\", \"mpg\", \"mpeg\"]:\n fp = os.path.splitext(self.file)[0] + \".\" + ext\n if os.path.exists(fp):\n os.unlink(fp)\n line_1 = \"- {language}, {codec} ({profile}) {width}x{height} ({aspect}) @ {bitrate}\".format(\n language=pycountry.languages.get(alpha_2=video.language).name,\n codec=codec,\n profile=video.format_profile,\n width=video.width, height=video.height,\n aspect=video.other_display_aspect_ratio[0],\n bitrate=f\"{video.other_bit_rate[0]}{f' ({video.bit_rate_mode})' if video.bit_rate_mode else ''}\"\n )\n line_2 = \" {fps} FPS ({fps_mode}), {color_space}{subsampling}P{bit_depth}, {scan}\".format(\n fps=f\"{video.framerate_num}/{video.framerate_den}\" if video.framerate_num else video.frame_rate,\n fps_mode=\"VFR\" if vst else video.frame_rate_mode,\n color_space=video.color_space,\n subsampling=video.chroma_subsampling.replace(\":\", \"\"),\n bit_depth=video.bit_depth,\n scan=scan_overview\n )\n data.append([line_1, line_2])\n return data\n\n def get_audio_print(self, audio: List[Track]) -> List[str]:\n if not audio:\n return [\"--\"]\n data = []\n for t in audio:\n if t.title and \"Commentary\" in t.title:\n title = t.title\n else:\n title = pycountry.languages.get(alpha_2=t.language).name\n if t.channel_layout:\n channels = float(sum(self.AUDIO_CHANNEL_LAYOUT_WEIGHT.get(x, 1) for x in t.channel_layout.split(\" \")))\n else:\n channels = float(t.channel_s)\n bit_rate_mode = f\" ({t.bit_rate_mode})\" if t.bit_rate_mode else \"\"\n l1 = f\"- {title}, {t.format} {channels} @ {t.other_bit_rate[0]}{bit_rate_mode}\"\n data += [(\" \" + x if i > 0 else x) for i, x in enumerate(textwrap.wrap(l1, 64))]\n return data\n\n @staticmethod\n def get_subtitle_print(subs: List[Track]) -> List[str]:\n \"\"\"\n Return a list of a brief subtitle overview per-subtitle.\n\n e.g.\n - English, Forced, SubRip (SRT)\n - English, SubRip (SRT)\n - English, SDH, SubRip (SRT)\n - Spanish, Latin American (SDH), SubRip (SRT)\n\n The bit of text between the Language and the Subtitle format is the Track Title.\n It can be of any format, but it is recommended to be used as shown above.\n\n It will be returned as a list of strings with the `- ` already pre-pended to each entry.\n \"\"\"\n data = []\n if not subs:\n data.append(\"--\")\n for sub in subs:\n line_items = []\n\n # following sub.title tree checks and supports three different language and title scenarios\n # The second scenario is the recommended option to choose if you are open to choosing any\n # The third scenario should be used if you have nothing unique to state about the track\n # | Language | Track Title | Output |\n # | ------------ | ----------------------------- | --------------------------------------------- |\n # | es / Spanish | Spanish (Latin American, SDH) | - Spanish (Latin American, SDH), SubRip (SRT) |\n # | es / Spanish | Latin American (SDH) | - Spanish, Latin American (SDH), SubRip (SRT) |\n # | es / Spanish | None | - Spanish, SubRip (SRT) |\n language = pycountry.languages.get(alpha_2=sub.language).name\n if sub.title:\n if language.lower() in sub.title.lower():\n line_items.append(sub.title)\n else:\n line_items.append(f\"{language}, {sub.title}\")\n else:\n line_items.append(language)\n\n line_items.append(sub.format.replace(\"UTF-8\", \"SubRip (SRT)\"))\n\n line = \"- \" + \", \".join(line_items)\n data += [\n (\" \" + x if i > 0 else x)\n for i, x in enumerate(textwrap.wrap(line, 64))\n ]\n return data\n\n @staticmethod\n def get_chapter_print(chapters: Dict[str, str]) -> List[str]:\n if not chapters:\n return [\"--\"]\n return [\n f\"- {k}: {v}\"\n for k, v in chapters.items()\n ]\n\n def get_chapter_print_short(self, chapters: Dict[str, str]) -> str:\n if not chapters:\n return \"No\"\n if self.chapters_numbered:\n return f\"Yes (Numbered 01-{str(len(chapters)).zfill(2)})\"\n return \"Yes (Named)\"\n\n @staticmethod\n def get_session() -> requests.Session:\n session = requests.Session()\n session.headers.update({\n \"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\",\n \"Accept-Language\": \"en-US,en;q=0.5\",\n \"DNT\": \"1\",\n \"UPGRADE-INSECURE-REQUESTS\": \"1\"\n })\n return session\n", "step-ids": [ 14, 16, 18, 19, 22 ] }
[ 14, 16, 18, 19, 22 ]
import typing from rest_framework.exceptions import ValidationError from rest_framework.request import Request def extract_organization_id_from_request_query(request): return request.query_params.get('organization') or request.query_params.get('organization_id') def extract_organization_id_from_request_data(request) -> (int, bool): """ Returns the organization id from the request.data and a bool indicating if the key was present in the data (to distinguish between missing data and empty input value) :param request: :return: """ for source in (request.data, request.GET): if 'organization' in source: return source.get('organization'), True if 'organization_id' in request.data: return source.get('organization_id'), True return None, False def extract_field_from_request(request: Request, field_name: str) -> typing.Optional[int]: """ Extracts attribte from request if attribute is present in data it has precedence over query parameters """ try: # Try to get value from data value = request.data.get(field_name) except AttributeError: raise ValidationError('Malformed request') if not value: # Try to get value from query parameters value = request.query_params.get(field_name) if value: try: return int(value) except ValueError: raise ValidationError(f"Value of field '{field_name}' is not a valid integer ({value})") return None
normal
{ "blob_id": "0b7523035fdad74454e51dc9da9fc4e9bea2f6bf", "index": 6904, "step-1": "<mask token>\n\n\ndef extract_field_from_request(request: Request, field_name: str\n ) ->typing.Optional[int]:\n \"\"\"\n Extracts attribte from request\n if attribute is present in data it has precedence over query parameters\n \"\"\"\n try:\n value = request.data.get(field_name)\n except AttributeError:\n raise ValidationError('Malformed request')\n if not value:\n value = request.query_params.get(field_name)\n if value:\n try:\n return int(value)\n except ValueError:\n raise ValidationError(\n f\"Value of field '{field_name}' is not a valid integer ({value})\"\n )\n return None\n", "step-2": "<mask token>\n\n\ndef extract_organization_id_from_request_query(request):\n return request.query_params.get('organization'\n ) or request.query_params.get('organization_id')\n\n\n<mask token>\n\n\ndef extract_field_from_request(request: Request, field_name: str\n ) ->typing.Optional[int]:\n \"\"\"\n Extracts attribte from request\n if attribute is present in data it has precedence over query parameters\n \"\"\"\n try:\n value = request.data.get(field_name)\n except AttributeError:\n raise ValidationError('Malformed request')\n if not value:\n value = request.query_params.get(field_name)\n if value:\n try:\n return int(value)\n except ValueError:\n raise ValidationError(\n f\"Value of field '{field_name}' is not a valid integer ({value})\"\n )\n return None\n", "step-3": "<mask token>\n\n\ndef extract_organization_id_from_request_query(request):\n return request.query_params.get('organization'\n ) or request.query_params.get('organization_id')\n\n\ndef extract_organization_id_from_request_data(request) ->(int, bool):\n \"\"\"\n Returns the organization id from the request.data and a bool indicating if the key\n was present in the data (to distinguish between missing data and empty input value)\n :param request:\n :return:\n \"\"\"\n for source in (request.data, request.GET):\n if 'organization' in source:\n return source.get('organization'), True\n if 'organization_id' in request.data:\n return source.get('organization_id'), True\n return None, False\n\n\ndef extract_field_from_request(request: Request, field_name: str\n ) ->typing.Optional[int]:\n \"\"\"\n Extracts attribte from request\n if attribute is present in data it has precedence over query parameters\n \"\"\"\n try:\n value = request.data.get(field_name)\n except AttributeError:\n raise ValidationError('Malformed request')\n if not value:\n value = request.query_params.get(field_name)\n if value:\n try:\n return int(value)\n except ValueError:\n raise ValidationError(\n f\"Value of field '{field_name}' is not a valid integer ({value})\"\n )\n return None\n", "step-4": "import typing\nfrom rest_framework.exceptions import ValidationError\nfrom rest_framework.request import Request\n\n\ndef extract_organization_id_from_request_query(request):\n return request.query_params.get('organization'\n ) or request.query_params.get('organization_id')\n\n\ndef extract_organization_id_from_request_data(request) ->(int, bool):\n \"\"\"\n Returns the organization id from the request.data and a bool indicating if the key\n was present in the data (to distinguish between missing data and empty input value)\n :param request:\n :return:\n \"\"\"\n for source in (request.data, request.GET):\n if 'organization' in source:\n return source.get('organization'), True\n if 'organization_id' in request.data:\n return source.get('organization_id'), True\n return None, False\n\n\ndef extract_field_from_request(request: Request, field_name: str\n ) ->typing.Optional[int]:\n \"\"\"\n Extracts attribte from request\n if attribute is present in data it has precedence over query parameters\n \"\"\"\n try:\n value = request.data.get(field_name)\n except AttributeError:\n raise ValidationError('Malformed request')\n if not value:\n value = request.query_params.get(field_name)\n if value:\n try:\n return int(value)\n except ValueError:\n raise ValidationError(\n f\"Value of field '{field_name}' is not a valid integer ({value})\"\n )\n return None\n", "step-5": "import typing\n\nfrom rest_framework.exceptions import ValidationError\nfrom rest_framework.request import Request\n\n\ndef extract_organization_id_from_request_query(request):\n return request.query_params.get('organization') or request.query_params.get('organization_id')\n\n\ndef extract_organization_id_from_request_data(request) -> (int, bool):\n \"\"\"\n Returns the organization id from the request.data and a bool indicating if the key\n was present in the data (to distinguish between missing data and empty input value)\n :param request:\n :return:\n \"\"\"\n for source in (request.data, request.GET):\n if 'organization' in source:\n return source.get('organization'), True\n if 'organization_id' in request.data:\n return source.get('organization_id'), True\n return None, False\n\n\ndef extract_field_from_request(request: Request, field_name: str) -> typing.Optional[int]:\n \"\"\"\n Extracts attribte from request\n if attribute is present in data it has precedence over query parameters\n \"\"\"\n\n try:\n # Try to get value from data\n value = request.data.get(field_name)\n except AttributeError:\n raise ValidationError('Malformed request')\n\n if not value:\n # Try to get value from query parameters\n value = request.query_params.get(field_name)\n\n if value:\n try:\n return int(value)\n except ValueError:\n raise ValidationError(f\"Value of field '{field_name}' is not a valid integer ({value})\")\n\n return None\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> dol_001.set_description('dolen do mivkata') dol_001.rendModul() <|reserved_special_token_0|> dol_002.set_description('долен втори с 2 врати') dol_002.rendModul() <|reserved_special_token_1|> <|reserved_special_token_0|> st = Person('Stoian') Stoian = Person('Ivanov') dolni = Skeleton(st, 900, 600, 2, 18, 28, 40) dolni_st = Skeleton(Stoian, 900, 590, 2, 18, 28, 40) dol_001 = Base_dolni(dolni_st, 550) dol_001.set_description('dolen do mivkata') dol_001.rendModul() dol_002 = Dolen_vrata(dolni_st, 400, 2) dol_002.set_description('долен втори с 2 врати') dol_002.rendModul() <|reserved_special_token_1|> from models import Person from models import Skeleton from models import Base_dolni from models import Dolen_vrata st = Person('Stoian') Stoian = Person('Ivanov') dolni = Skeleton(st, 900, 600, 2, 18, 28, 40) dolni_st = Skeleton(Stoian, 900, 590, 2, 18, 28, 40) dol_001 = Base_dolni(dolni_st, 550) dol_001.set_description('dolen do mivkata') dol_001.rendModul() dol_002 = Dolen_vrata(dolni_st, 400, 2) dol_002.set_description('долен втори с 2 врати') dol_002.rendModul() <|reserved_special_token_1|> from models import Person from models import Skeleton from models import Base_dolni from models import Dolen_vrata st = Person("Stoian") Stoian = Person("Ivanov") dolni = Skeleton(st, 900, 600, 2, 18, 28, 40) dolni_st = Skeleton(Stoian, 900, 590, 2, 18, 28, 40) dol_001 = Base_dolni(dolni_st, 550) dol_001.set_description("dolen do mivkata") dol_001.rendModul() dol_002 = Dolen_vrata(dolni_st, 400, 2) dol_002.set_description("долен втори с 2 врати") dol_002.rendModul()
flexible
{ "blob_id": "3d10f8810594303beb0ccabce3497de86149b2e5", "index": 6666, "step-1": "<mask token>\n", "step-2": "<mask token>\ndol_001.set_description('dolen do mivkata')\ndol_001.rendModul()\n<mask token>\ndol_002.set_description('долен втори с 2 врати')\ndol_002.rendModul()\n", "step-3": "<mask token>\nst = Person('Stoian')\nStoian = Person('Ivanov')\ndolni = Skeleton(st, 900, 600, 2, 18, 28, 40)\ndolni_st = Skeleton(Stoian, 900, 590, 2, 18, 28, 40)\ndol_001 = Base_dolni(dolni_st, 550)\ndol_001.set_description('dolen do mivkata')\ndol_001.rendModul()\ndol_002 = Dolen_vrata(dolni_st, 400, 2)\ndol_002.set_description('долен втори с 2 врати')\ndol_002.rendModul()\n", "step-4": "from models import Person\nfrom models import Skeleton\nfrom models import Base_dolni\nfrom models import Dolen_vrata\nst = Person('Stoian')\nStoian = Person('Ivanov')\ndolni = Skeleton(st, 900, 600, 2, 18, 28, 40)\ndolni_st = Skeleton(Stoian, 900, 590, 2, 18, 28, 40)\ndol_001 = Base_dolni(dolni_st, 550)\ndol_001.set_description('dolen do mivkata')\ndol_001.rendModul()\ndol_002 = Dolen_vrata(dolni_st, 400, 2)\ndol_002.set_description('долен втори с 2 врати')\ndol_002.rendModul()\n", "step-5": "from models import Person\nfrom models import Skeleton\nfrom models import Base_dolni\nfrom models import Dolen_vrata\n\nst = Person(\"Stoian\")\nStoian = Person(\"Ivanov\")\n\ndolni = Skeleton(st, 900, 600, 2, 18, 28, 40)\ndolni_st = Skeleton(Stoian, 900, 590, 2, 18, 28, 40)\n\ndol_001 = Base_dolni(dolni_st, 550)\ndol_001.set_description(\"dolen do mivkata\")\ndol_001.rendModul()\n\ndol_002 = Dolen_vrata(dolni_st, 400, 2)\ndol_002.set_description(\"долен втори с 2 врати\")\ndol_002.rendModul()\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import webbrowser as wb points = 0 import time as t import pyautogui as pg name = pg.prompt("What is your name? ").title() pg.alert(name) if name == "Caroline": pg.alert ("Hi " + name) points += 5 t.sleep(1) wb.open ("https://www.textgiraffe.com/Caroline/Page2/") elif name == "Bob": pg.alert (name + ",you are a great person!") points += 3 t.sleep(1) wb.open("http://dreamworks.wikia.com/wiki/File:Bob_the_Builder.jpeg") elif name == "Catherine": pg.alert (name + "I like you already.") points += 2 t.sleep(2) wb.open ("https://www.amazon.com/Catherine-Street-Sign-Reflective-Aluminum/dp/B00KY6ZDZW") elif name == "James": pg.alert ("nice to meet you" + name) points += 1 t.sleep(1) wb.open ("https://www.youtube.com/watch?v=uV9LYMAEnRA") elif name == "Kate": pg.alert ("Hello!") points += 2 t.sleep (1) wb.open ("https://www.google.com/search?q=kate+name&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj-3cyIyJzeAhVRnOAKHRnoCtQQ_AUIDigB&biw=924&bih=639#imgrc=sbQIiK5VLfo7kM:") elif name == "Will": pg.alert ("Coool!") ponts += 3 t.sleep (2) wb.open ("https://www.google.com/search?q=will+name&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj3n93PyJzeAhWvY98KHcoWCFEQ_AUIDigB&biw=924&bih=639#imgrc=Z0hfeIoXQgHxJM:") else: pg.alert ("I don't know you!") points += 0 t.sleep(2) wb.open ("https://www.google.com/search?q=smiley+face&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjwsdL4gYveAhXtc98KHaGcAz0Q_AUIDigB&biw=1366&bih=657") color = pg.prompt ("what is your favorite color? ").title() if color == "Blue": pg.alert ("mine too!") points += 5 t.sleep(1) wb.open ("https://www.youtube.com/watch?v=SoIKv3xxuMA") elif color == "Pink": pg.alert ("Do you like unicorns too?") points += 2 t.sleep(2) wb.open ("https://www.youtube.com/watch?v=a-xWhG4UU_Y") elif color == "Purple": pg.alert ("cool!") points += 3 t.sleep(1) wb.open ("https://www.youtube.com/watch?v=TvnYmWpD_T8") elif color == "Black": pg.alert ("ok...") points -= 2 t.sleep(2) wb.open ("https://www.google.com/search?q=goth&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiJ-tDj-oreAhUpUt8KHWZsAzQQ_AUIDigB&biw=1366&bih=657#imgrc=odGcWJwuqRcJsM:") elif color == "Yellow": pg.alert ("Like a sunflower!") points += 1 t.sleep (1) wb.open ("https://www.google.com/search?q=sunflower&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiZyKCTyZzeAhXGc98KHd8kDJ8Q_AUIDigB&biw=924&bih=639#imgrc=8kZ1NZp_9-nr5M:") elif color == "Brown": pg.alert ("wow.") points -= 5 t.sleep (1) wb.open ("https://www.youtube.com/watch?v=dsJtgmAhFF4") else: pg.alert("nice") points += 1 t.sleep(2) wb.open ("https://giphy.com/explore/rainbow") sport = pg.prompt ("What is your favorite sport? ").title() if sport == "Hockey": pg.alert ("yep, I guess your cool") points += 5 t.sleep(2) wb.open ("https://www.youtube.com/watch?v=JDnZTUkCOBQ") elif sport == "Soccer": pg.alert ("you mean futbol...") points += 5 t.sleep(2) wb.open ("https://www.youtube.com/watch?v=K-U1ZgrsGGg") elif sport == "Lacrosse": pg.alert (" I used to play..") points += 2 t.sleep(2) wb.open ("https://www.youtube.com/watch?v=o5hsPBsGD44") elif sport == "Football": pg.alert ("that cool.") points += 4 t.sleep(3) wb.open ("https://www.google.com/search?q=football&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwimsOqj_IreAhUumeAKHd-FD6kQ_AUIDigB&biw=1366&bih=657#imgrc=GCqjPQ-jqckcfM:") elif sport == "Field Hockey": pg.alert ("Nice!") points += 2 t.sleep(3) wb.open ("https://www.google.com/search?q=field+hockey&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwieus2jypzeAhWvVN8KHeK1CJ8Q_AUIDigB&biw=924&bih=639#imgrc=FCpGZY2CS5KVXM:") elif sport == "Surfing": pg.alert ("WOAH") points += 7 t.sleep(1) wb.open ("https://www.youtube.com/watch?v=HBklS2vYEPo") else: pg.alert ("cool") points += 0 t.sleep(2) wb.open ("https://www.google.com/search?q=no+sports&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiGqOK-_IreAhXFneAKHcEGANIQ_AUIDigB&biw=1366&bih=657#imgrc=y7acx-yoEouoUM:") subject = pg.prompt ("What is your favorite subject?").title() if subject == "Math": pg.alert ("so your a mathmatician") points += 2 t.sleep(3) wb.open ("https://www.google.com/search?rlz=1C1GCEA_enUS752US774&biw=1366&bih=657&tbm=isch&sa=1&ei=HNvFW9yoDYTm_QbUyKzgDw&q=addiong&oq=addiong&gs_l=img.3..0i10i24.5226.6666..6852...1.0..0.56.417.8......0....1..gws-wiz-img.......0j0i67j0i10.kcqMNDR26RY#imgrc=LqznGvY1fJpCGM:") elif subject == "Computer science": pg.alert ("nice") points += 9 t.sleep(3) wb.open ("https://www.google.com/search?q=computers&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiom6vv_IreAhUuneAKHXVGA4kQ_AUIDygC&biw=1366&bih=657") elif subject == "English": pg.alert ("I like it too.") points += 3 t.sleep(3) wb.open ("https://www.google.com/search?rlz=1C1GCEA_enUS752US774&biw=1366&bih=657&tbm=isch&sa=1&ei=hNvFW4e3Jafp_QbR26mIDw&q=+book&oq=+book&gs_l=img.3..0i67l3j0j0i67j0l5.3464.3464..3690...0.0..0.51.51.1......0....1..gws-wiz-img.2n6KjdjVyU0") elif subject == "Science": pg.alert ("Bill Nye the Science Guy.") points += 3 t.sleep(2) wb.open("https://www.youtube.com/watch?v=nDN7M0J3HXc") elif subject == "Spanish": pg.alert ("Hola! Como estas?") points += 3 t.sleep(2) wb.open ("https://www.google.com/search?hl=en&authuser=0&rlz=1C1GCEA_enUS752US774&tbm=isch&q=fiesta&chips=q:fiesta,online_chips:mexican+fiesta&usg=AI4_-kQGU87DySQyv0Aqat3pdqhIpYYwjA&sa=X&ved=0ahUKEwjzjvL6lq7eAhWpTd8KHQ6-CIoQ4lYIKygE&biw=924&bih=639&dpr=1#imgrc=6H_w7py8kTIUHM:") elif subject == "History": pg.alert ("In 1492 Christopher Columbus sailed the ocean blue") points += 3 t.sleep(2) wb.open ("https://www.google.com/search?q=history&rlz=1C1GCEA_enUS752US774&biw=1366&bih=657&tbm=isch&source=lnms&sa=X&ved=0ahUKEwiZ_YDvutHeAhXOVN8KHdEUDEkQ_AUICygC") else: pg.alert ("cool") points += 1 t.sleep(2) wb.open ("https://www.google.com/search?q=school+gif&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjqpI_f_YreAhWsd98KHblYBY8Q_AUIDigB&biw=1366&bih=657#imgrc=kk5pi12VrUoKGM:") food = pg.prompt ("What is your favorite food?").title() if food == "Pizza": pg.alert ("Pizza Hut? Dominos?") points += 2 t.sleep(2) wb.open ("https://cooking.nytimes.com/guides/1-how-to-make-pizza") elif food == "Chocolate cake": pg.alert ("Now I want one") points += 9 t.sleep(3) wb.open ("https://www.youtube.com/watch?v=dsJtgmAhFF4") elif food == "Pasta": pg.alert ("I like pasta!") points += 3 t.sleep(3) wb.open ("https://www.google.com/search?q=pasta&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiH_JXSlK7eAhWKT98KHScQASEQ_AUIDigB&biw=924&bih=639") elif food == "Ice cream": pg.alert ("What kind? I like cookie monster.") points += 3 t.sleep(2) wb.open("https://barefeetinthekitchen.com/homemade-ice-cream-recipe/") elif food == "Fruit": pg.alert ("Refreshing!") points += 3 t.sleep(2) wb.open ("https://www.google.com/search?q=fruit&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwijobOcla7eAhVyUt8KHfONDGUQ_AUIDigB&biw=924&bih=639#imgrc=ACrdFKwEzni-QM:") elif food == "Chicken": pg.alert ("Yum!") points += 2 t.sleep(2) wb.open ("https://www.google.com/search?q=chicken&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj59fTCutHeAhXLct8KHRV6D88Q_AUIEygB&biw=1366&bih=657") else: pg.alert ("YUUMMM") points += 1 t.sleep(2) wb.open ("https://www.youtube.com/watch?v=11HK5EuYwSk") movie = pg.prompt ("What is your favorite movie series?").title() if "Divergent" in movie: number = pg.prompt("Which movie is your favorite").title() if number == "1": pg.alert("Nice!") ice_cream = pg.confirm("Which of these flavors is your favorite?", "Choose one", ["chocolate", "vanilla", "cookies and cream"]) if ice_cream == "cookies and cream": pg.alert("YES") pg.alert ("Your final score is " + str(points))
normal
{ "blob_id": "16e10db90a0a0d8ee7ca5b0c7f86cc81432d87d1", "index": 4391, "step-1": "<mask token>\n", "step-2": "<mask token>\npg.alert(name)\nif name == 'Caroline':\n pg.alert('Hi ' + name)\n points += 5\n t.sleep(1)\n wb.open('https://www.textgiraffe.com/Caroline/Page2/')\nelif name == 'Bob':\n pg.alert(name + ',you are a great person!')\n points += 3\n t.sleep(1)\n wb.open('http://dreamworks.wikia.com/wiki/File:Bob_the_Builder.jpeg')\nelif name == 'Catherine':\n pg.alert(name + 'I like you already.')\n points += 2\n t.sleep(2)\n wb.open(\n 'https://www.amazon.com/Catherine-Street-Sign-Reflective-Aluminum/dp/B00KY6ZDZW'\n )\nelif name == 'James':\n pg.alert('nice to meet you' + name)\n points += 1\n t.sleep(1)\n wb.open('https://www.youtube.com/watch?v=uV9LYMAEnRA')\nelif name == 'Kate':\n pg.alert('Hello!')\n points += 2\n t.sleep(1)\n wb.open(\n 'https://www.google.com/search?q=kate+name&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj-3cyIyJzeAhVRnOAKHRnoCtQQ_AUIDigB&biw=924&bih=639#imgrc=sbQIiK5VLfo7kM:'\n )\nelif name == 'Will':\n pg.alert('Coool!')\n ponts += 3\n t.sleep(2)\n wb.open(\n 'https://www.google.com/search?q=will+name&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj3n93PyJzeAhWvY98KHcoWCFEQ_AUIDigB&biw=924&bih=639#imgrc=Z0hfeIoXQgHxJM:'\n )\nelse:\n pg.alert(\"I don't know you!\")\n points += 0\n t.sleep(2)\n wb.open(\n 'https://www.google.com/search?q=smiley+face&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjwsdL4gYveAhXtc98KHaGcAz0Q_AUIDigB&biw=1366&bih=657'\n )\n<mask token>\nif color == 'Blue':\n pg.alert('mine too!')\n points += 5\n t.sleep(1)\n wb.open('https://www.youtube.com/watch?v=SoIKv3xxuMA')\nelif color == 'Pink':\n pg.alert('Do you like unicorns too?')\n points += 2\n t.sleep(2)\n wb.open('https://www.youtube.com/watch?v=a-xWhG4UU_Y')\nelif color == 'Purple':\n pg.alert('cool!')\n points += 3\n t.sleep(1)\n wb.open('https://www.youtube.com/watch?v=TvnYmWpD_T8')\nelif color == 'Black':\n pg.alert('ok...')\n points -= 2\n t.sleep(2)\n wb.open(\n 'https://www.google.com/search?q=goth&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiJ-tDj-oreAhUpUt8KHWZsAzQQ_AUIDigB&biw=1366&bih=657#imgrc=odGcWJwuqRcJsM:'\n )\nelif color == 'Yellow':\n pg.alert('Like a sunflower!')\n points += 1\n t.sleep(1)\n wb.open(\n 'https://www.google.com/search?q=sunflower&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiZyKCTyZzeAhXGc98KHd8kDJ8Q_AUIDigB&biw=924&bih=639#imgrc=8kZ1NZp_9-nr5M:'\n )\nelif color == 'Brown':\n pg.alert('wow.')\n points -= 5\n t.sleep(1)\n wb.open('https://www.youtube.com/watch?v=dsJtgmAhFF4')\nelse:\n pg.alert('nice')\n points += 1\n t.sleep(2)\n wb.open('https://giphy.com/explore/rainbow')\n<mask token>\nif sport == 'Hockey':\n pg.alert('yep, I guess your cool')\n points += 5\n t.sleep(2)\n wb.open('https://www.youtube.com/watch?v=JDnZTUkCOBQ')\nelif sport == 'Soccer':\n pg.alert('you mean futbol...')\n points += 5\n t.sleep(2)\n wb.open('https://www.youtube.com/watch?v=K-U1ZgrsGGg')\nelif sport == 'Lacrosse':\n pg.alert(' I used to play..')\n points += 2\n t.sleep(2)\n wb.open('https://www.youtube.com/watch?v=o5hsPBsGD44')\nelif sport == 'Football':\n pg.alert('that cool.')\n points += 4\n t.sleep(3)\n wb.open(\n 'https://www.google.com/search?q=football&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwimsOqj_IreAhUumeAKHd-FD6kQ_AUIDigB&biw=1366&bih=657#imgrc=GCqjPQ-jqckcfM:'\n )\nelif sport == 'Field Hockey':\n pg.alert('Nice!')\n points += 2\n t.sleep(3)\n wb.open(\n 'https://www.google.com/search?q=field+hockey&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwieus2jypzeAhWvVN8KHeK1CJ8Q_AUIDigB&biw=924&bih=639#imgrc=FCpGZY2CS5KVXM:'\n )\nelif sport == 'Surfing':\n pg.alert('WOAH')\n points += 7\n t.sleep(1)\n wb.open('https://www.youtube.com/watch?v=HBklS2vYEPo')\nelse:\n pg.alert('cool')\n points += 0\n t.sleep(2)\n wb.open(\n 'https://www.google.com/search?q=no+sports&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiGqOK-_IreAhXFneAKHcEGANIQ_AUIDigB&biw=1366&bih=657#imgrc=y7acx-yoEouoUM:'\n )\n<mask token>\nif subject == 'Math':\n pg.alert('so your a mathmatician')\n points += 2\n t.sleep(3)\n wb.open(\n 'https://www.google.com/search?rlz=1C1GCEA_enUS752US774&biw=1366&bih=657&tbm=isch&sa=1&ei=HNvFW9yoDYTm_QbUyKzgDw&q=addiong&oq=addiong&gs_l=img.3..0i10i24.5226.6666..6852...1.0..0.56.417.8......0....1..gws-wiz-img.......0j0i67j0i10.kcqMNDR26RY#imgrc=LqznGvY1fJpCGM:'\n )\nelif subject == 'Computer science':\n pg.alert('nice')\n points += 9\n t.sleep(3)\n wb.open(\n 'https://www.google.com/search?q=computers&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiom6vv_IreAhUuneAKHXVGA4kQ_AUIDygC&biw=1366&bih=657'\n )\nelif subject == 'English':\n pg.alert('I like it too.')\n points += 3\n t.sleep(3)\n wb.open(\n 'https://www.google.com/search?rlz=1C1GCEA_enUS752US774&biw=1366&bih=657&tbm=isch&sa=1&ei=hNvFW4e3Jafp_QbR26mIDw&q=+book&oq=+book&gs_l=img.3..0i67l3j0j0i67j0l5.3464.3464..3690...0.0..0.51.51.1......0....1..gws-wiz-img.2n6KjdjVyU0'\n )\nelif subject == 'Science':\n pg.alert('Bill Nye the Science Guy.')\n points += 3\n t.sleep(2)\n wb.open('https://www.youtube.com/watch?v=nDN7M0J3HXc')\nelif subject == 'Spanish':\n pg.alert('Hola! Como estas?')\n points += 3\n t.sleep(2)\n wb.open(\n 'https://www.google.com/search?hl=en&authuser=0&rlz=1C1GCEA_enUS752US774&tbm=isch&q=fiesta&chips=q:fiesta,online_chips:mexican+fiesta&usg=AI4_-kQGU87DySQyv0Aqat3pdqhIpYYwjA&sa=X&ved=0ahUKEwjzjvL6lq7eAhWpTd8KHQ6-CIoQ4lYIKygE&biw=924&bih=639&dpr=1#imgrc=6H_w7py8kTIUHM:'\n )\nelif subject == 'History':\n pg.alert('In 1492 Christopher Columbus sailed the ocean blue')\n points += 3\n t.sleep(2)\n wb.open(\n 'https://www.google.com/search?q=history&rlz=1C1GCEA_enUS752US774&biw=1366&bih=657&tbm=isch&source=lnms&sa=X&ved=0ahUKEwiZ_YDvutHeAhXOVN8KHdEUDEkQ_AUICygC'\n )\nelse:\n pg.alert('cool')\n points += 1\n t.sleep(2)\n wb.open(\n 'https://www.google.com/search?q=school+gif&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjqpI_f_YreAhWsd98KHblYBY8Q_AUIDigB&biw=1366&bih=657#imgrc=kk5pi12VrUoKGM:'\n )\n<mask token>\nif food == 'Pizza':\n pg.alert('Pizza Hut? Dominos?')\n points += 2\n t.sleep(2)\n wb.open('https://cooking.nytimes.com/guides/1-how-to-make-pizza')\nelif food == 'Chocolate cake':\n pg.alert('Now I want one')\n points += 9\n t.sleep(3)\n wb.open('https://www.youtube.com/watch?v=dsJtgmAhFF4')\nelif food == 'Pasta':\n pg.alert('I like pasta!')\n points += 3\n t.sleep(3)\n wb.open(\n 'https://www.google.com/search?q=pasta&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiH_JXSlK7eAhWKT98KHScQASEQ_AUIDigB&biw=924&bih=639'\n )\nelif food == 'Ice cream':\n pg.alert('What kind? I like cookie monster.')\n points += 3\n t.sleep(2)\n wb.open('https://barefeetinthekitchen.com/homemade-ice-cream-recipe/')\nelif food == 'Fruit':\n pg.alert('Refreshing!')\n points += 3\n t.sleep(2)\n wb.open(\n 'https://www.google.com/search?q=fruit&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwijobOcla7eAhVyUt8KHfONDGUQ_AUIDigB&biw=924&bih=639#imgrc=ACrdFKwEzni-QM:'\n )\nelif food == 'Chicken':\n pg.alert('Yum!')\n points += 2\n t.sleep(2)\n wb.open(\n 'https://www.google.com/search?q=chicken&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj59fTCutHeAhXLct8KHRV6D88Q_AUIEygB&biw=1366&bih=657'\n )\nelse:\n pg.alert('YUUMMM')\n points += 1\n t.sleep(2)\n wb.open('https://www.youtube.com/watch?v=11HK5EuYwSk')\n<mask token>\nif 'Divergent' in movie:\n number = pg.prompt('Which movie is your favorite').title()\n if number == '1':\n pg.alert('Nice!')\n<mask token>\nif ice_cream == 'cookies and cream':\n pg.alert('YES')\npg.alert('Your final score is ' + str(points))\n", "step-3": "<mask token>\npoints = 0\n<mask token>\nname = pg.prompt('What is your name? ').title()\npg.alert(name)\nif name == 'Caroline':\n pg.alert('Hi ' + name)\n points += 5\n t.sleep(1)\n wb.open('https://www.textgiraffe.com/Caroline/Page2/')\nelif name == 'Bob':\n pg.alert(name + ',you are a great person!')\n points += 3\n t.sleep(1)\n wb.open('http://dreamworks.wikia.com/wiki/File:Bob_the_Builder.jpeg')\nelif name == 'Catherine':\n pg.alert(name + 'I like you already.')\n points += 2\n t.sleep(2)\n wb.open(\n 'https://www.amazon.com/Catherine-Street-Sign-Reflective-Aluminum/dp/B00KY6ZDZW'\n )\nelif name == 'James':\n pg.alert('nice to meet you' + name)\n points += 1\n t.sleep(1)\n wb.open('https://www.youtube.com/watch?v=uV9LYMAEnRA')\nelif name == 'Kate':\n pg.alert('Hello!')\n points += 2\n t.sleep(1)\n wb.open(\n 'https://www.google.com/search?q=kate+name&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj-3cyIyJzeAhVRnOAKHRnoCtQQ_AUIDigB&biw=924&bih=639#imgrc=sbQIiK5VLfo7kM:'\n )\nelif name == 'Will':\n pg.alert('Coool!')\n ponts += 3\n t.sleep(2)\n wb.open(\n 'https://www.google.com/search?q=will+name&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj3n93PyJzeAhWvY98KHcoWCFEQ_AUIDigB&biw=924&bih=639#imgrc=Z0hfeIoXQgHxJM:'\n )\nelse:\n pg.alert(\"I don't know you!\")\n points += 0\n t.sleep(2)\n wb.open(\n 'https://www.google.com/search?q=smiley+face&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjwsdL4gYveAhXtc98KHaGcAz0Q_AUIDigB&biw=1366&bih=657'\n )\ncolor = pg.prompt('what is your favorite color? ').title()\nif color == 'Blue':\n pg.alert('mine too!')\n points += 5\n t.sleep(1)\n wb.open('https://www.youtube.com/watch?v=SoIKv3xxuMA')\nelif color == 'Pink':\n pg.alert('Do you like unicorns too?')\n points += 2\n t.sleep(2)\n wb.open('https://www.youtube.com/watch?v=a-xWhG4UU_Y')\nelif color == 'Purple':\n pg.alert('cool!')\n points += 3\n t.sleep(1)\n wb.open('https://www.youtube.com/watch?v=TvnYmWpD_T8')\nelif color == 'Black':\n pg.alert('ok...')\n points -= 2\n t.sleep(2)\n wb.open(\n 'https://www.google.com/search?q=goth&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiJ-tDj-oreAhUpUt8KHWZsAzQQ_AUIDigB&biw=1366&bih=657#imgrc=odGcWJwuqRcJsM:'\n )\nelif color == 'Yellow':\n pg.alert('Like a sunflower!')\n points += 1\n t.sleep(1)\n wb.open(\n 'https://www.google.com/search?q=sunflower&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiZyKCTyZzeAhXGc98KHd8kDJ8Q_AUIDigB&biw=924&bih=639#imgrc=8kZ1NZp_9-nr5M:'\n )\nelif color == 'Brown':\n pg.alert('wow.')\n points -= 5\n t.sleep(1)\n wb.open('https://www.youtube.com/watch?v=dsJtgmAhFF4')\nelse:\n pg.alert('nice')\n points += 1\n t.sleep(2)\n wb.open('https://giphy.com/explore/rainbow')\nsport = pg.prompt('What is your favorite sport? ').title()\nif sport == 'Hockey':\n pg.alert('yep, I guess your cool')\n points += 5\n t.sleep(2)\n wb.open('https://www.youtube.com/watch?v=JDnZTUkCOBQ')\nelif sport == 'Soccer':\n pg.alert('you mean futbol...')\n points += 5\n t.sleep(2)\n wb.open('https://www.youtube.com/watch?v=K-U1ZgrsGGg')\nelif sport == 'Lacrosse':\n pg.alert(' I used to play..')\n points += 2\n t.sleep(2)\n wb.open('https://www.youtube.com/watch?v=o5hsPBsGD44')\nelif sport == 'Football':\n pg.alert('that cool.')\n points += 4\n t.sleep(3)\n wb.open(\n 'https://www.google.com/search?q=football&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwimsOqj_IreAhUumeAKHd-FD6kQ_AUIDigB&biw=1366&bih=657#imgrc=GCqjPQ-jqckcfM:'\n )\nelif sport == 'Field Hockey':\n pg.alert('Nice!')\n points += 2\n t.sleep(3)\n wb.open(\n 'https://www.google.com/search?q=field+hockey&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwieus2jypzeAhWvVN8KHeK1CJ8Q_AUIDigB&biw=924&bih=639#imgrc=FCpGZY2CS5KVXM:'\n )\nelif sport == 'Surfing':\n pg.alert('WOAH')\n points += 7\n t.sleep(1)\n wb.open('https://www.youtube.com/watch?v=HBklS2vYEPo')\nelse:\n pg.alert('cool')\n points += 0\n t.sleep(2)\n wb.open(\n 'https://www.google.com/search?q=no+sports&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiGqOK-_IreAhXFneAKHcEGANIQ_AUIDigB&biw=1366&bih=657#imgrc=y7acx-yoEouoUM:'\n )\nsubject = pg.prompt('What is your favorite subject?').title()\nif subject == 'Math':\n pg.alert('so your a mathmatician')\n points += 2\n t.sleep(3)\n wb.open(\n 'https://www.google.com/search?rlz=1C1GCEA_enUS752US774&biw=1366&bih=657&tbm=isch&sa=1&ei=HNvFW9yoDYTm_QbUyKzgDw&q=addiong&oq=addiong&gs_l=img.3..0i10i24.5226.6666..6852...1.0..0.56.417.8......0....1..gws-wiz-img.......0j0i67j0i10.kcqMNDR26RY#imgrc=LqznGvY1fJpCGM:'\n )\nelif subject == 'Computer science':\n pg.alert('nice')\n points += 9\n t.sleep(3)\n wb.open(\n 'https://www.google.com/search?q=computers&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiom6vv_IreAhUuneAKHXVGA4kQ_AUIDygC&biw=1366&bih=657'\n )\nelif subject == 'English':\n pg.alert('I like it too.')\n points += 3\n t.sleep(3)\n wb.open(\n 'https://www.google.com/search?rlz=1C1GCEA_enUS752US774&biw=1366&bih=657&tbm=isch&sa=1&ei=hNvFW4e3Jafp_QbR26mIDw&q=+book&oq=+book&gs_l=img.3..0i67l3j0j0i67j0l5.3464.3464..3690...0.0..0.51.51.1......0....1..gws-wiz-img.2n6KjdjVyU0'\n )\nelif subject == 'Science':\n pg.alert('Bill Nye the Science Guy.')\n points += 3\n t.sleep(2)\n wb.open('https://www.youtube.com/watch?v=nDN7M0J3HXc')\nelif subject == 'Spanish':\n pg.alert('Hola! Como estas?')\n points += 3\n t.sleep(2)\n wb.open(\n 'https://www.google.com/search?hl=en&authuser=0&rlz=1C1GCEA_enUS752US774&tbm=isch&q=fiesta&chips=q:fiesta,online_chips:mexican+fiesta&usg=AI4_-kQGU87DySQyv0Aqat3pdqhIpYYwjA&sa=X&ved=0ahUKEwjzjvL6lq7eAhWpTd8KHQ6-CIoQ4lYIKygE&biw=924&bih=639&dpr=1#imgrc=6H_w7py8kTIUHM:'\n )\nelif subject == 'History':\n pg.alert('In 1492 Christopher Columbus sailed the ocean blue')\n points += 3\n t.sleep(2)\n wb.open(\n 'https://www.google.com/search?q=history&rlz=1C1GCEA_enUS752US774&biw=1366&bih=657&tbm=isch&source=lnms&sa=X&ved=0ahUKEwiZ_YDvutHeAhXOVN8KHdEUDEkQ_AUICygC'\n )\nelse:\n pg.alert('cool')\n points += 1\n t.sleep(2)\n wb.open(\n 'https://www.google.com/search?q=school+gif&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjqpI_f_YreAhWsd98KHblYBY8Q_AUIDigB&biw=1366&bih=657#imgrc=kk5pi12VrUoKGM:'\n )\nfood = pg.prompt('What is your favorite food?').title()\nif food == 'Pizza':\n pg.alert('Pizza Hut? Dominos?')\n points += 2\n t.sleep(2)\n wb.open('https://cooking.nytimes.com/guides/1-how-to-make-pizza')\nelif food == 'Chocolate cake':\n pg.alert('Now I want one')\n points += 9\n t.sleep(3)\n wb.open('https://www.youtube.com/watch?v=dsJtgmAhFF4')\nelif food == 'Pasta':\n pg.alert('I like pasta!')\n points += 3\n t.sleep(3)\n wb.open(\n 'https://www.google.com/search?q=pasta&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiH_JXSlK7eAhWKT98KHScQASEQ_AUIDigB&biw=924&bih=639'\n )\nelif food == 'Ice cream':\n pg.alert('What kind? I like cookie monster.')\n points += 3\n t.sleep(2)\n wb.open('https://barefeetinthekitchen.com/homemade-ice-cream-recipe/')\nelif food == 'Fruit':\n pg.alert('Refreshing!')\n points += 3\n t.sleep(2)\n wb.open(\n 'https://www.google.com/search?q=fruit&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwijobOcla7eAhVyUt8KHfONDGUQ_AUIDigB&biw=924&bih=639#imgrc=ACrdFKwEzni-QM:'\n )\nelif food == 'Chicken':\n pg.alert('Yum!')\n points += 2\n t.sleep(2)\n wb.open(\n 'https://www.google.com/search?q=chicken&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj59fTCutHeAhXLct8KHRV6D88Q_AUIEygB&biw=1366&bih=657'\n )\nelse:\n pg.alert('YUUMMM')\n points += 1\n t.sleep(2)\n wb.open('https://www.youtube.com/watch?v=11HK5EuYwSk')\nmovie = pg.prompt('What is your favorite movie series?').title()\nif 'Divergent' in movie:\n number = pg.prompt('Which movie is your favorite').title()\n if number == '1':\n pg.alert('Nice!')\nice_cream = pg.confirm('Which of these flavors is your favorite?',\n 'Choose one', ['chocolate', 'vanilla', 'cookies and cream'])\nif ice_cream == 'cookies and cream':\n pg.alert('YES')\npg.alert('Your final score is ' + str(points))\n", "step-4": "import webbrowser as wb\npoints = 0\nimport time as t\nimport pyautogui as pg\nname = pg.prompt('What is your name? ').title()\npg.alert(name)\nif name == 'Caroline':\n pg.alert('Hi ' + name)\n points += 5\n t.sleep(1)\n wb.open('https://www.textgiraffe.com/Caroline/Page2/')\nelif name == 'Bob':\n pg.alert(name + ',you are a great person!')\n points += 3\n t.sleep(1)\n wb.open('http://dreamworks.wikia.com/wiki/File:Bob_the_Builder.jpeg')\nelif name == 'Catherine':\n pg.alert(name + 'I like you already.')\n points += 2\n t.sleep(2)\n wb.open(\n 'https://www.amazon.com/Catherine-Street-Sign-Reflective-Aluminum/dp/B00KY6ZDZW'\n )\nelif name == 'James':\n pg.alert('nice to meet you' + name)\n points += 1\n t.sleep(1)\n wb.open('https://www.youtube.com/watch?v=uV9LYMAEnRA')\nelif name == 'Kate':\n pg.alert('Hello!')\n points += 2\n t.sleep(1)\n wb.open(\n 'https://www.google.com/search?q=kate+name&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj-3cyIyJzeAhVRnOAKHRnoCtQQ_AUIDigB&biw=924&bih=639#imgrc=sbQIiK5VLfo7kM:'\n )\nelif name == 'Will':\n pg.alert('Coool!')\n ponts += 3\n t.sleep(2)\n wb.open(\n 'https://www.google.com/search?q=will+name&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj3n93PyJzeAhWvY98KHcoWCFEQ_AUIDigB&biw=924&bih=639#imgrc=Z0hfeIoXQgHxJM:'\n )\nelse:\n pg.alert(\"I don't know you!\")\n points += 0\n t.sleep(2)\n wb.open(\n 'https://www.google.com/search?q=smiley+face&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjwsdL4gYveAhXtc98KHaGcAz0Q_AUIDigB&biw=1366&bih=657'\n )\ncolor = pg.prompt('what is your favorite color? ').title()\nif color == 'Blue':\n pg.alert('mine too!')\n points += 5\n t.sleep(1)\n wb.open('https://www.youtube.com/watch?v=SoIKv3xxuMA')\nelif color == 'Pink':\n pg.alert('Do you like unicorns too?')\n points += 2\n t.sleep(2)\n wb.open('https://www.youtube.com/watch?v=a-xWhG4UU_Y')\nelif color == 'Purple':\n pg.alert('cool!')\n points += 3\n t.sleep(1)\n wb.open('https://www.youtube.com/watch?v=TvnYmWpD_T8')\nelif color == 'Black':\n pg.alert('ok...')\n points -= 2\n t.sleep(2)\n wb.open(\n 'https://www.google.com/search?q=goth&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiJ-tDj-oreAhUpUt8KHWZsAzQQ_AUIDigB&biw=1366&bih=657#imgrc=odGcWJwuqRcJsM:'\n )\nelif color == 'Yellow':\n pg.alert('Like a sunflower!')\n points += 1\n t.sleep(1)\n wb.open(\n 'https://www.google.com/search?q=sunflower&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiZyKCTyZzeAhXGc98KHd8kDJ8Q_AUIDigB&biw=924&bih=639#imgrc=8kZ1NZp_9-nr5M:'\n )\nelif color == 'Brown':\n pg.alert('wow.')\n points -= 5\n t.sleep(1)\n wb.open('https://www.youtube.com/watch?v=dsJtgmAhFF4')\nelse:\n pg.alert('nice')\n points += 1\n t.sleep(2)\n wb.open('https://giphy.com/explore/rainbow')\nsport = pg.prompt('What is your favorite sport? ').title()\nif sport == 'Hockey':\n pg.alert('yep, I guess your cool')\n points += 5\n t.sleep(2)\n wb.open('https://www.youtube.com/watch?v=JDnZTUkCOBQ')\nelif sport == 'Soccer':\n pg.alert('you mean futbol...')\n points += 5\n t.sleep(2)\n wb.open('https://www.youtube.com/watch?v=K-U1ZgrsGGg')\nelif sport == 'Lacrosse':\n pg.alert(' I used to play..')\n points += 2\n t.sleep(2)\n wb.open('https://www.youtube.com/watch?v=o5hsPBsGD44')\nelif sport == 'Football':\n pg.alert('that cool.')\n points += 4\n t.sleep(3)\n wb.open(\n 'https://www.google.com/search?q=football&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwimsOqj_IreAhUumeAKHd-FD6kQ_AUIDigB&biw=1366&bih=657#imgrc=GCqjPQ-jqckcfM:'\n )\nelif sport == 'Field Hockey':\n pg.alert('Nice!')\n points += 2\n t.sleep(3)\n wb.open(\n 'https://www.google.com/search?q=field+hockey&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwieus2jypzeAhWvVN8KHeK1CJ8Q_AUIDigB&biw=924&bih=639#imgrc=FCpGZY2CS5KVXM:'\n )\nelif sport == 'Surfing':\n pg.alert('WOAH')\n points += 7\n t.sleep(1)\n wb.open('https://www.youtube.com/watch?v=HBklS2vYEPo')\nelse:\n pg.alert('cool')\n points += 0\n t.sleep(2)\n wb.open(\n 'https://www.google.com/search?q=no+sports&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiGqOK-_IreAhXFneAKHcEGANIQ_AUIDigB&biw=1366&bih=657#imgrc=y7acx-yoEouoUM:'\n )\nsubject = pg.prompt('What is your favorite subject?').title()\nif subject == 'Math':\n pg.alert('so your a mathmatician')\n points += 2\n t.sleep(3)\n wb.open(\n 'https://www.google.com/search?rlz=1C1GCEA_enUS752US774&biw=1366&bih=657&tbm=isch&sa=1&ei=HNvFW9yoDYTm_QbUyKzgDw&q=addiong&oq=addiong&gs_l=img.3..0i10i24.5226.6666..6852...1.0..0.56.417.8......0....1..gws-wiz-img.......0j0i67j0i10.kcqMNDR26RY#imgrc=LqznGvY1fJpCGM:'\n )\nelif subject == 'Computer science':\n pg.alert('nice')\n points += 9\n t.sleep(3)\n wb.open(\n 'https://www.google.com/search?q=computers&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiom6vv_IreAhUuneAKHXVGA4kQ_AUIDygC&biw=1366&bih=657'\n )\nelif subject == 'English':\n pg.alert('I like it too.')\n points += 3\n t.sleep(3)\n wb.open(\n 'https://www.google.com/search?rlz=1C1GCEA_enUS752US774&biw=1366&bih=657&tbm=isch&sa=1&ei=hNvFW4e3Jafp_QbR26mIDw&q=+book&oq=+book&gs_l=img.3..0i67l3j0j0i67j0l5.3464.3464..3690...0.0..0.51.51.1......0....1..gws-wiz-img.2n6KjdjVyU0'\n )\nelif subject == 'Science':\n pg.alert('Bill Nye the Science Guy.')\n points += 3\n t.sleep(2)\n wb.open('https://www.youtube.com/watch?v=nDN7M0J3HXc')\nelif subject == 'Spanish':\n pg.alert('Hola! Como estas?')\n points += 3\n t.sleep(2)\n wb.open(\n 'https://www.google.com/search?hl=en&authuser=0&rlz=1C1GCEA_enUS752US774&tbm=isch&q=fiesta&chips=q:fiesta,online_chips:mexican+fiesta&usg=AI4_-kQGU87DySQyv0Aqat3pdqhIpYYwjA&sa=X&ved=0ahUKEwjzjvL6lq7eAhWpTd8KHQ6-CIoQ4lYIKygE&biw=924&bih=639&dpr=1#imgrc=6H_w7py8kTIUHM:'\n )\nelif subject == 'History':\n pg.alert('In 1492 Christopher Columbus sailed the ocean blue')\n points += 3\n t.sleep(2)\n wb.open(\n 'https://www.google.com/search?q=history&rlz=1C1GCEA_enUS752US774&biw=1366&bih=657&tbm=isch&source=lnms&sa=X&ved=0ahUKEwiZ_YDvutHeAhXOVN8KHdEUDEkQ_AUICygC'\n )\nelse:\n pg.alert('cool')\n points += 1\n t.sleep(2)\n wb.open(\n 'https://www.google.com/search?q=school+gif&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjqpI_f_YreAhWsd98KHblYBY8Q_AUIDigB&biw=1366&bih=657#imgrc=kk5pi12VrUoKGM:'\n )\nfood = pg.prompt('What is your favorite food?').title()\nif food == 'Pizza':\n pg.alert('Pizza Hut? Dominos?')\n points += 2\n t.sleep(2)\n wb.open('https://cooking.nytimes.com/guides/1-how-to-make-pizza')\nelif food == 'Chocolate cake':\n pg.alert('Now I want one')\n points += 9\n t.sleep(3)\n wb.open('https://www.youtube.com/watch?v=dsJtgmAhFF4')\nelif food == 'Pasta':\n pg.alert('I like pasta!')\n points += 3\n t.sleep(3)\n wb.open(\n 'https://www.google.com/search?q=pasta&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiH_JXSlK7eAhWKT98KHScQASEQ_AUIDigB&biw=924&bih=639'\n )\nelif food == 'Ice cream':\n pg.alert('What kind? I like cookie monster.')\n points += 3\n t.sleep(2)\n wb.open('https://barefeetinthekitchen.com/homemade-ice-cream-recipe/')\nelif food == 'Fruit':\n pg.alert('Refreshing!')\n points += 3\n t.sleep(2)\n wb.open(\n 'https://www.google.com/search?q=fruit&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwijobOcla7eAhVyUt8KHfONDGUQ_AUIDigB&biw=924&bih=639#imgrc=ACrdFKwEzni-QM:'\n )\nelif food == 'Chicken':\n pg.alert('Yum!')\n points += 2\n t.sleep(2)\n wb.open(\n 'https://www.google.com/search?q=chicken&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj59fTCutHeAhXLct8KHRV6D88Q_AUIEygB&biw=1366&bih=657'\n )\nelse:\n pg.alert('YUUMMM')\n points += 1\n t.sleep(2)\n wb.open('https://www.youtube.com/watch?v=11HK5EuYwSk')\nmovie = pg.prompt('What is your favorite movie series?').title()\nif 'Divergent' in movie:\n number = pg.prompt('Which movie is your favorite').title()\n if number == '1':\n pg.alert('Nice!')\nice_cream = pg.confirm('Which of these flavors is your favorite?',\n 'Choose one', ['chocolate', 'vanilla', 'cookies and cream'])\nif ice_cream == 'cookies and cream':\n pg.alert('YES')\npg.alert('Your final score is ' + str(points))\n", "step-5": "import webbrowser as wb\r\npoints = 0\r\nimport time as t\r\nimport pyautogui as pg\r\n\r\n\r\nname = pg.prompt(\"What is your name? \").title()\r\n\r\npg.alert(name)\r\nif name == \"Caroline\":\r\n pg.alert (\"Hi \" + name)\r\n points += 5\r\n t.sleep(1) \r\n wb.open (\"https://www.textgiraffe.com/Caroline/Page2/\")\r\nelif name == \"Bob\":\r\n pg.alert (name + \",you are a great person!\")\r\n points += 3\r\n t.sleep(1)\r\n wb.open(\"http://dreamworks.wikia.com/wiki/File:Bob_the_Builder.jpeg\")\r\nelif name == \"Catherine\":\r\n pg.alert (name + \"I like you already.\")\r\n points += 2\r\n t.sleep(2)\r\n wb.open (\"https://www.amazon.com/Catherine-Street-Sign-Reflective-Aluminum/dp/B00KY6ZDZW\")\r\nelif name == \"James\":\r\n pg.alert (\"nice to meet you\" + name)\r\n points += 1\r\n t.sleep(1)\r\n wb.open (\"https://www.youtube.com/watch?v=uV9LYMAEnRA\")\r\nelif name == \"Kate\":\r\n pg.alert (\"Hello!\")\r\n points += 2\r\n t.sleep (1)\r\n wb.open (\"https://www.google.com/search?q=kate+name&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj-3cyIyJzeAhVRnOAKHRnoCtQQ_AUIDigB&biw=924&bih=639#imgrc=sbQIiK5VLfo7kM:\")\r\nelif name == \"Will\":\r\n pg.alert (\"Coool!\")\r\n ponts += 3\r\n t.sleep (2)\r\n wb.open (\"https://www.google.com/search?q=will+name&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj3n93PyJzeAhWvY98KHcoWCFEQ_AUIDigB&biw=924&bih=639#imgrc=Z0hfeIoXQgHxJM:\")\r\nelse:\r\n pg.alert (\"I don't know you!\")\r\n points += 0\r\n t.sleep(2)\r\n wb.open (\"https://www.google.com/search?q=smiley+face&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjwsdL4gYveAhXtc98KHaGcAz0Q_AUIDigB&biw=1366&bih=657\")\r\ncolor = pg.prompt (\"what is your favorite color? \").title()\r\nif color == \"Blue\":\r\n pg.alert (\"mine too!\")\r\n points += 5\r\n t.sleep(1)\r\n wb.open (\"https://www.youtube.com/watch?v=SoIKv3xxuMA\")\r\nelif color == \"Pink\":\r\n pg.alert (\"Do you like unicorns too?\")\r\n points += 2\r\n t.sleep(2)\r\n wb.open (\"https://www.youtube.com/watch?v=a-xWhG4UU_Y\")\r\nelif color == \"Purple\":\r\n pg.alert (\"cool!\")\r\n points += 3\r\n t.sleep(1)\r\n wb.open (\"https://www.youtube.com/watch?v=TvnYmWpD_T8\")\r\nelif color == \"Black\":\r\n pg.alert (\"ok...\")\r\n points -= 2\r\n t.sleep(2)\r\n wb.open (\"https://www.google.com/search?q=goth&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiJ-tDj-oreAhUpUt8KHWZsAzQQ_AUIDigB&biw=1366&bih=657#imgrc=odGcWJwuqRcJsM:\")\r\nelif color == \"Yellow\":\r\n pg.alert (\"Like a sunflower!\")\r\n points += 1\r\n t.sleep (1)\r\n wb.open (\"https://www.google.com/search?q=sunflower&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiZyKCTyZzeAhXGc98KHd8kDJ8Q_AUIDigB&biw=924&bih=639#imgrc=8kZ1NZp_9-nr5M:\")\r\nelif color == \"Brown\":\r\n pg.alert (\"wow.\")\r\n points -= 5\r\n t.sleep (1)\r\n wb.open (\"https://www.youtube.com/watch?v=dsJtgmAhFF4\")\r\nelse:\r\n pg.alert(\"nice\")\r\n points += 1\r\n t.sleep(2)\r\n wb.open (\"https://giphy.com/explore/rainbow\")\r\nsport = pg.prompt (\"What is your favorite sport? \").title()\r\nif sport == \"Hockey\":\r\n pg.alert (\"yep, I guess your cool\")\r\n points += 5\r\n t.sleep(2)\r\n wb.open (\"https://www.youtube.com/watch?v=JDnZTUkCOBQ\")\r\nelif sport == \"Soccer\":\r\n pg.alert (\"you mean futbol...\")\r\n points += 5\r\n t.sleep(2)\r\n wb.open (\"https://www.youtube.com/watch?v=K-U1ZgrsGGg\")\r\nelif sport == \"Lacrosse\":\r\n pg.alert (\" I used to play..\")\r\n points += 2\r\n t.sleep(2)\r\n wb.open (\"https://www.youtube.com/watch?v=o5hsPBsGD44\")\r\nelif sport == \"Football\":\r\n pg.alert (\"that cool.\")\r\n points += 4\r\n t.sleep(3)\r\n wb.open (\"https://www.google.com/search?q=football&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwimsOqj_IreAhUumeAKHd-FD6kQ_AUIDigB&biw=1366&bih=657#imgrc=GCqjPQ-jqckcfM:\")\r\nelif sport == \"Field Hockey\":\r\n pg.alert (\"Nice!\")\r\n points += 2\r\n t.sleep(3)\r\n wb.open (\"https://www.google.com/search?q=field+hockey&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwieus2jypzeAhWvVN8KHeK1CJ8Q_AUIDigB&biw=924&bih=639#imgrc=FCpGZY2CS5KVXM:\")\r\nelif sport == \"Surfing\":\r\n pg.alert (\"WOAH\")\r\n points += 7\r\n t.sleep(1)\r\n wb.open (\"https://www.youtube.com/watch?v=HBklS2vYEPo\")\r\nelse:\r\n pg.alert (\"cool\")\r\n points += 0\r\n t.sleep(2)\r\n wb.open (\"https://www.google.com/search?q=no+sports&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiGqOK-_IreAhXFneAKHcEGANIQ_AUIDigB&biw=1366&bih=657#imgrc=y7acx-yoEouoUM:\")\r\nsubject = pg.prompt (\"What is your favorite subject?\").title()\r\nif subject == \"Math\":\r\n pg.alert (\"so your a mathmatician\")\r\n points += 2\r\n t.sleep(3)\r\n wb.open (\"https://www.google.com/search?rlz=1C1GCEA_enUS752US774&biw=1366&bih=657&tbm=isch&sa=1&ei=HNvFW9yoDYTm_QbUyKzgDw&q=addiong&oq=addiong&gs_l=img.3..0i10i24.5226.6666..6852...1.0..0.56.417.8......0....1..gws-wiz-img.......0j0i67j0i10.kcqMNDR26RY#imgrc=LqznGvY1fJpCGM:\")\r\nelif subject == \"Computer science\":\r\n pg.alert (\"nice\")\r\n points += 9\r\n t.sleep(3)\r\n wb.open (\"https://www.google.com/search?q=computers&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiom6vv_IreAhUuneAKHXVGA4kQ_AUIDygC&biw=1366&bih=657\")\r\nelif subject == \"English\":\r\n pg.alert (\"I like it too.\")\r\n points += 3\r\n t.sleep(3)\r\n wb.open (\"https://www.google.com/search?rlz=1C1GCEA_enUS752US774&biw=1366&bih=657&tbm=isch&sa=1&ei=hNvFW4e3Jafp_QbR26mIDw&q=+book&oq=+book&gs_l=img.3..0i67l3j0j0i67j0l5.3464.3464..3690...0.0..0.51.51.1......0....1..gws-wiz-img.2n6KjdjVyU0\")\r\nelif subject == \"Science\":\r\n pg.alert (\"Bill Nye the Science Guy.\")\r\n points += 3\r\n t.sleep(2)\r\n wb.open(\"https://www.youtube.com/watch?v=nDN7M0J3HXc\")\r\nelif subject == \"Spanish\":\r\n pg.alert (\"Hola! Como estas?\")\r\n points += 3\r\n t.sleep(2)\r\n wb.open (\"https://www.google.com/search?hl=en&authuser=0&rlz=1C1GCEA_enUS752US774&tbm=isch&q=fiesta&chips=q:fiesta,online_chips:mexican+fiesta&usg=AI4_-kQGU87DySQyv0Aqat3pdqhIpYYwjA&sa=X&ved=0ahUKEwjzjvL6lq7eAhWpTd8KHQ6-CIoQ4lYIKygE&biw=924&bih=639&dpr=1#imgrc=6H_w7py8kTIUHM:\")\r\nelif subject == \"History\":\r\n pg.alert (\"In 1492 Christopher Columbus sailed the ocean blue\")\r\n points += 3\r\n t.sleep(2)\r\n wb.open (\"https://www.google.com/search?q=history&rlz=1C1GCEA_enUS752US774&biw=1366&bih=657&tbm=isch&source=lnms&sa=X&ved=0ahUKEwiZ_YDvutHeAhXOVN8KHdEUDEkQ_AUICygC\")\r\nelse:\r\n pg.alert (\"cool\")\r\n points += 1\r\n t.sleep(2)\r\n wb.open (\"https://www.google.com/search?q=school+gif&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjqpI_f_YreAhWsd98KHblYBY8Q_AUIDigB&biw=1366&bih=657#imgrc=kk5pi12VrUoKGM:\")\r\n\r\nfood = pg.prompt (\"What is your favorite food?\").title()\r\nif food == \"Pizza\":\r\n pg.alert (\"Pizza Hut? Dominos?\")\r\n points += 2\r\n t.sleep(2)\r\n wb.open (\"https://cooking.nytimes.com/guides/1-how-to-make-pizza\")\r\nelif food == \"Chocolate cake\":\r\n pg.alert (\"Now I want one\")\r\n points += 9\r\n t.sleep(3)\r\n wb.open (\"https://www.youtube.com/watch?v=dsJtgmAhFF4\")\r\nelif food == \"Pasta\":\r\n pg.alert (\"I like pasta!\")\r\n points += 3\r\n t.sleep(3)\r\n wb.open (\"https://www.google.com/search?q=pasta&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiH_JXSlK7eAhWKT98KHScQASEQ_AUIDigB&biw=924&bih=639\")\r\nelif food == \"Ice cream\":\r\n pg.alert (\"What kind? I like cookie monster.\")\r\n points += 3\r\n t.sleep(2)\r\n wb.open(\"https://barefeetinthekitchen.com/homemade-ice-cream-recipe/\")\r\nelif food == \"Fruit\":\r\n pg.alert (\"Refreshing!\")\r\n points += 3\r\n t.sleep(2)\r\n wb.open (\"https://www.google.com/search?q=fruit&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwijobOcla7eAhVyUt8KHfONDGUQ_AUIDigB&biw=924&bih=639#imgrc=ACrdFKwEzni-QM:\")\r\nelif food == \"Chicken\":\r\n pg.alert (\"Yum!\")\r\n points += 2\r\n t.sleep(2)\r\n wb.open (\"https://www.google.com/search?q=chicken&rlz=1C1GCEA_enUS752US774&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj59fTCutHeAhXLct8KHRV6D88Q_AUIEygB&biw=1366&bih=657\")\r\nelse:\r\n pg.alert (\"YUUMMM\")\r\n points += 1\r\n t.sleep(2)\r\n wb.open (\"https://www.youtube.com/watch?v=11HK5EuYwSk\")\r\n\r\nmovie = pg.prompt (\"What is your favorite movie series?\").title()\r\nif \"Divergent\" in movie:\r\n number = pg.prompt(\"Which movie is your favorite\").title()\r\n\r\n if number == \"1\":\r\n pg.alert(\"Nice!\")\r\n\r\nice_cream = pg.confirm(\"Which of these flavors is your favorite?\", \"Choose one\", [\"chocolate\", \"vanilla\", \"cookies and cream\"])\r\nif ice_cream == \"cookies and cream\":\r\n pg.alert(\"YES\")\r\n\r\npg.alert (\"Your final score is \" + str(points))\r\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# 파이썬 딕셔너리 # 범용적으로 가장 많이 사용되는 타입 # key와 value의 대용관계 type # 순서 X, key 중복 X, 수정 O, 삭제 O # {} # class란 실세계(오브젝트)의 명사,동사적인 특징들을 추상화시키는 것, 즉 프로그램 내 인스턴트(객체)를 추출하는 템플릿이다 # class는 틀이고 인스턴스는 틀에의해 만들어지는 결과물.하여 instance.class()로 표현 #temp = {} #print(type(temp)) dic01 = {'name' : 'seop', 'age' : 48, 'address' : 'seoul', 'birth' : '730919', 'gender' : True} #print('dic - ',dic01,type(dic01)) #print(dir(dic01)) #iter가 있으므로 순환반복가능 # key 유무를 판단하기 위해서 #print('name' in dic01) # 요소를 추가하는 방법 #dic01['marriage'] = False #print(dic01) #dic01['marriage'] = True #print(dic01) # 데이터 확인 #print("데이터 확인 - ",dic01['birth']) #개발자성향에 따라 데이터를 리스트하여 관리하기도함, 각각의 값들은 튜플 이용 dic02 = dict( [('name' , 'seop'), ('age' , 48), ('address' , 'seoul'), ('birth','730919'), ('gender' , True)] ) #print("tuple을 이용한 dict 생성 -",dic02) #변수에다 값을 할당하는 방법 dic03 = dict( name = 'seop', age = 48, address = 'seoul', birth = '730919', gender = True) #출력 #print('dic03 -',dic03['Name']) #키값을 이용, 대소문자 Name때문에 오류남 #print('dic03 -',dic03.get('Name')) #함수를 이용, 해당하는 밸류를 가져오는 것이라 Name에 담긴 값들이 없어서 None을 출력 #print('len - ', len(dic03)) # dict_keys(키), dict_values(값), dict_items(키와값) #print('dict_keys -',list(dic03.keys())) #각각의 키들은 리스트, 루프를 돌려서 값들을 꺼내올 수도 있다, 리스트화 시킬수도 있음 #print('dict_values -', list(dic03.values())) #밸류도 키와 마찬가지로 각각의 값 리스트 #print('dict_items -',list(dic03.items())) # for key in dic03.keys() : # print("{0},{1}".format(key,dic03[key])) # print("key : {0}, value : {1}".format(key,dic03.get(key))) # for value in dic03.values() : # print(value) # 튜플 패킹 & 언패킹 #t = ('foo','bar','baz','qux') ##괄호형 쳐주고 선언하는 것,패킹 #print(type(t)) #(x1,x2,x3,x4) = t ##다른변수에 담을때 언패킹해서 담아준다(괄호형은 보기편하게묶은것), 언패킹할때 튜플에 있는 값들의 개수가 담을 변수의 개수에 맞게 선언이 되어있어야함 #(x1,x2,x3,x4) = ('foo','bar','baz','qux') #print(x1,x2,x3,x4) a, *b, c = (0,1,2,3,4,5) #언패킹할때 개수가 안맞을때 *를 사용하여 처리할 수도 있음, 보통 *이 하나만 나오는 경우가 많음 #print(a) #print(b) #print(c) #for (key , value) in dic03.items() : # print("key : {0}, value : {1}".format(key,value)) # 삭제 pop(), del #del dic03['gender'] #print(dic03) #print('pop -', dic03.pop('birth')) #print('dic03 - ',dic03) #dic03.clear() #print('dic03 - ', dic03)
normal
{ "blob_id": "d1077107a5cd3a9f489f74b030a698b0521841f3", "index": 7721, "step-1": "<mask token>\n", "step-2": "dic01 = {'name': 'seop', 'age': 48, 'address': 'seoul', 'birth': '730919',\n 'gender': True}\ndic02 = dict([('name', 'seop'), ('age', 48), ('address', 'seoul'), ('birth',\n '730919'), ('gender', True)])\ndic03 = dict(name='seop', age=48, address='seoul', birth='730919', gender=True)\na, *b, c = 0, 1, 2, 3, 4, 5\n", "step-3": "# 파이썬 딕셔너리\r\n# 범용적으로 가장 많이 사용되는 타입\r\n# key와 value의 대용관계 type\r\n# 순서 X, key 중복 X, 수정 O, 삭제 O\r\n# {}\r\n# class란 실세계(오브젝트)의 명사,동사적인 특징들을 추상화시키는 것, 즉 프로그램 내 인스턴트(객체)를 추출하는 템플릿이다\r\n# class는 틀이고 인스턴스는 틀에의해 만들어지는 결과물.하여 instance.class()로 표현\r\n\r\n#temp = {}\r\n#print(type(temp))\r\n\r\ndic01 = {'name' : 'seop',\r\n 'age' : 48,\r\n 'address' : 'seoul',\r\n 'birth' : '730919',\r\n 'gender' : True}\r\n#print('dic - ',dic01,type(dic01))\r\n#print(dir(dic01)) #iter가 있으므로 순환반복가능\r\n\r\n# key 유무를 판단하기 위해서\r\n#print('name' in dic01)\r\n\r\n# 요소를 추가하는 방법\r\n#dic01['marriage'] = False\r\n#print(dic01)\r\n\r\n#dic01['marriage'] = True\r\n#print(dic01)\r\n\r\n# 데이터 확인\r\n#print(\"데이터 확인 - \",dic01['birth'])\r\n\r\n#개발자성향에 따라 데이터를 리스트하여 관리하기도함, 각각의 값들은 튜플 이용\r\ndic02 = dict( [('name' , 'seop'),\r\n ('age' , 48),\r\n ('address' , 'seoul'),\r\n ('birth','730919'),\r\n ('gender' , True)] )\r\n#print(\"tuple을 이용한 dict 생성 -\",dic02)\r\n\r\n#변수에다 값을 할당하는 방법\r\ndic03 = dict( name = 'seop',\r\n age = 48,\r\n address = 'seoul',\r\n birth = '730919',\r\n gender = True)\r\n\r\n\r\n#출력\r\n#print('dic03 -',dic03['Name']) #키값을 이용, 대소문자 Name때문에 오류남\r\n#print('dic03 -',dic03.get('Name')) #함수를 이용, 해당하는 밸류를 가져오는 것이라 Name에 담긴 값들이 없어서 None을 출력\r\n\r\n#print('len - ', len(dic03))\r\n\r\n# dict_keys(키), dict_values(값), dict_items(키와값)\r\n#print('dict_keys -',list(dic03.keys())) #각각의 키들은 리스트, 루프를 돌려서 값들을 꺼내올 수도 있다, 리스트화 시킬수도 있음\r\n#print('dict_values -', list(dic03.values())) #밸류도 키와 마찬가지로 각각의 값 리스트\r\n#print('dict_items -',list(dic03.items()))\r\n\r\n# for key in dic03.keys() :\r\n # print(\"{0},{1}\".format(key,dic03[key]))\r\n # print(\"key : {0}, value : {1}\".format(key,dic03.get(key)))\r\n# for value in dic03.values() :\r\n# print(value)\r\n\r\n# 튜플 패킹 & 언패킹\r\n#t = ('foo','bar','baz','qux') ##괄호형 쳐주고 선언하는 것,패킹\r\n#print(type(t))\r\n#(x1,x2,x3,x4) = t ##다른변수에 담을때 언패킹해서 담아준다(괄호형은 보기편하게묶은것), 언패킹할때 튜플에 있는 값들의 개수가 담을 변수의 개수에 맞게 선언이 되어있어야함\r\n#(x1,x2,x3,x4) = ('foo','bar','baz','qux')\r\n#print(x1,x2,x3,x4)\r\n\r\na, *b, c = (0,1,2,3,4,5) #언패킹할때 개수가 안맞을때 *를 사용하여 처리할 수도 있음, 보통 *이 하나만 나오는 경우가 많음\r\n#print(a)\r\n#print(b)\r\n#print(c)\r\n\r\n#for (key , value) in dic03.items() :\r\n# print(\"key : {0}, value : {1}\".format(key,value))\r\n\r\n\r\n# 삭제 pop(), del\r\n#del dic03['gender']\r\n#print(dic03)\r\n\r\n#print('pop -', dic03.pop('birth'))\r\n#print('dic03 - ',dic03)\r\n\r\n#dic03.clear()\r\n#print('dic03 - ', dic03)", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
<|reserved_special_token_0|> def load(): with open(filename.get()) as file: contents.delete('1.0', END) contents.insert(INSERT, file.read()) def save(): with open(filename.get(), 'w') as file: file.write(contents.get('1.0', END)) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def load(): with open(filename.get()) as file: contents.delete('1.0', END) contents.insert(INSERT, file.read()) def save(): with open(filename.get(), 'w') as file: file.write(contents.get('1.0', END)) <|reserved_special_token_0|> top.title('Simple Editor') <|reserved_special_token_0|> contents.pack(side=BOTTOM, expand=True, fill=BOTH) <|reserved_special_token_0|> filename.pack(side=LEFT, expand=True, fill=X) Button(text='Open', command=load).pack(side=LEFT) Button(text='Save', command=save).pack(side=LEFT) mainloop() <|reserved_special_token_1|> <|reserved_special_token_0|> def load(): with open(filename.get()) as file: contents.delete('1.0', END) contents.insert(INSERT, file.read()) def save(): with open(filename.get(), 'w') as file: file.write(contents.get('1.0', END)) top = Tk() top.title('Simple Editor') contents = ScrolledText() contents.pack(side=BOTTOM, expand=True, fill=BOTH) filename = Entry() filename.pack(side=LEFT, expand=True, fill=X) Button(text='Open', command=load).pack(side=LEFT) Button(text='Save', command=save).pack(side=LEFT) mainloop() <|reserved_special_token_1|> from tkinter import * from tkinter.scrolledtext import ScrolledText def load(): with open(filename.get()) as file: contents.delete('1.0', END) contents.insert(INSERT, file.read()) def save(): with open(filename.get(), 'w') as file: file.write(contents.get('1.0', END)) top = Tk() top.title('Simple Editor') contents = ScrolledText() contents.pack(side=BOTTOM, expand=True, fill=BOTH) filename = Entry() filename.pack(side=LEFT, expand=True, fill=X) Button(text='Open', command=load).pack(side=LEFT) Button(text='Save', command=save).pack(side=LEFT) mainloop() <|reserved_special_token_1|> from tkinter import * from tkinter.scrolledtext import ScrolledText def load(): with open(filename.get()) as file: # delete every between line 1 char 0 to END # INSERT is the current insertion point contents.delete('1.0', END) contents.insert(INSERT, file.read()) def save(): with open(filename.get(), 'w') as file: file.write(contents.get('1.0', END)) # initialize window widget top = Tk() top.title("Simple Editor") # initialize text field with scroll bar contents = ScrolledText() # pack manager contents.pack(side=BOTTOM, expand=True, fill=BOTH) # text field filename = Entry() filename.pack(side=LEFT, expand=True, fill=X) Button(text='Open', command=load).pack(side=LEFT) Button(text='Save', command=save).pack(side=LEFT) mainloop()
flexible
{ "blob_id": "fcf4cb5c47e4aa51d97b633ecdfec65246e82bd8", "index": 9011, "step-1": "<mask token>\n\n\ndef load():\n with open(filename.get()) as file:\n contents.delete('1.0', END)\n contents.insert(INSERT, file.read())\n\n\ndef save():\n with open(filename.get(), 'w') as file:\n file.write(contents.get('1.0', END))\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef load():\n with open(filename.get()) as file:\n contents.delete('1.0', END)\n contents.insert(INSERT, file.read())\n\n\ndef save():\n with open(filename.get(), 'w') as file:\n file.write(contents.get('1.0', END))\n\n\n<mask token>\ntop.title('Simple Editor')\n<mask token>\ncontents.pack(side=BOTTOM, expand=True, fill=BOTH)\n<mask token>\nfilename.pack(side=LEFT, expand=True, fill=X)\nButton(text='Open', command=load).pack(side=LEFT)\nButton(text='Save', command=save).pack(side=LEFT)\nmainloop()\n", "step-3": "<mask token>\n\n\ndef load():\n with open(filename.get()) as file:\n contents.delete('1.0', END)\n contents.insert(INSERT, file.read())\n\n\ndef save():\n with open(filename.get(), 'w') as file:\n file.write(contents.get('1.0', END))\n\n\ntop = Tk()\ntop.title('Simple Editor')\ncontents = ScrolledText()\ncontents.pack(side=BOTTOM, expand=True, fill=BOTH)\nfilename = Entry()\nfilename.pack(side=LEFT, expand=True, fill=X)\nButton(text='Open', command=load).pack(side=LEFT)\nButton(text='Save', command=save).pack(side=LEFT)\nmainloop()\n", "step-4": "from tkinter import *\nfrom tkinter.scrolledtext import ScrolledText\n\n\ndef load():\n with open(filename.get()) as file:\n contents.delete('1.0', END)\n contents.insert(INSERT, file.read())\n\n\ndef save():\n with open(filename.get(), 'w') as file:\n file.write(contents.get('1.0', END))\n\n\ntop = Tk()\ntop.title('Simple Editor')\ncontents = ScrolledText()\ncontents.pack(side=BOTTOM, expand=True, fill=BOTH)\nfilename = Entry()\nfilename.pack(side=LEFT, expand=True, fill=X)\nButton(text='Open', command=load).pack(side=LEFT)\nButton(text='Save', command=save).pack(side=LEFT)\nmainloop()\n", "step-5": "from tkinter import *\nfrom tkinter.scrolledtext import ScrolledText\n\n\ndef load():\n with open(filename.get()) as file:\n # delete every between line 1 char 0 to END\n # INSERT is the current insertion point\n contents.delete('1.0', END)\n contents.insert(INSERT, file.read())\n\n\ndef save():\n with open(filename.get(), 'w') as file:\n file.write(contents.get('1.0', END))\n\n\n# initialize window widget\ntop = Tk()\ntop.title(\"Simple Editor\")\n\n\n# initialize text field with scroll bar\ncontents = ScrolledText()\n# pack manager\ncontents.pack(side=BOTTOM, expand=True, fill=BOTH)\n\n\n# text field\nfilename = Entry()\nfilename.pack(side=LEFT, expand=True, fill=X)\n\n\nButton(text='Open', command=load).pack(side=LEFT)\nButton(text='Save', command=save).pack(side=LEFT)\n\nmainloop()\n", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
quotes = [ "Today you are you! That is truer than true! There is no one alive who is you-er than you!", "Don't cry because it's over. Smile because it happened.", "You have brains in your head. You have feet in your shoes. You can steer yourself in any direction you choose. You're on your own, and you know what you know. And you are the guy who'll decide where to go.", "The more that you read, the more things you will know. The more that you learn, the more places you'll go. ", "I like nonsense; it wakes up the brain cells.", "Step with care and great tact, and remember that Life's a Great Balancing Act.", "How did it get so late so soon? Its night before its afternoon. December is here before its June. My goodness how the time has flewn. How did it get so late so soon?", "Think left and think right and think low and think high. Oh, the thinks you can think up if only you try!", "A person's a person, no matter how small.", "You can get help from teachers, but you are going to have to learn a lot by yourself, sitting alone in a room.", "Unless someone like you cares a whole awful lot, nothing is going to get better. It's not.", "You're never too old, too wacky, too wild, to pick up a book and read to a child.", "Today was good. Today was fun. Tomorrow is another one.", "I meant what I said and I said what I meant.", "You're in pretty good shape for the shape you are in.", "Only you can control your future.", "I am not a consecutive writer.", "Maybe Christmas, the Grinch thought, doesn't come from a store.", "Preachers in pulpits talked about what a great message is in the book. No matter what you do, somebody always imputes meaning into your books.", "Sometimes, when I see my granddaughters make small discoveries of their own, I wish I were a child.", "Adults are obsolete children.", "Whenever things go a bit sour in a job I'm doing, I always tell myself, 'You can do better than this.'", "From there to here, and here to there, funny things are everywhere.", "I stay out of politics because if I begin thinking too much about politics, I'll probably... drop writing children's books and become a political cartoonist again.", "I was saving the name of 'Geisel' for the Great American Novel.", "You make 'em, I amuse 'em." ]
normal
{ "blob_id": "f9ba944724b262afb39f2859b5726b961536cdf0", "index": 2092, "step-1": "<mask token>\n", "step-2": "quotes = [\n 'Today you are you! That is truer than true! There is no one alive who is you-er than you!'\n , \"Don't cry because it's over. Smile because it happened.\",\n \"You have brains in your head. You have feet in your shoes. You can steer yourself in any direction you choose. You're on your own, and you know what you know. And you are the guy who'll decide where to go.\"\n ,\n \"The more that you read, the more things you will know. The more that you learn, the more places you'll go. \"\n , 'I like nonsense; it wakes up the brain cells.',\n \"Step with care and great tact, and remember that Life's a Great Balancing Act.\"\n ,\n 'How did it get so late so soon? Its night before its afternoon. December is here before its June. My goodness how the time has flewn. How did it get so late so soon?'\n ,\n 'Think left and think right and think low and think high. Oh, the thinks you can think up if only you try!'\n , \"A person's a person, no matter how small.\",\n 'You can get help from teachers, but you are going to have to learn a lot by yourself, sitting alone in a room.'\n ,\n \"Unless someone like you cares a whole awful lot, nothing is going to get better. It's not.\"\n ,\n \"You're never too old, too wacky, too wild, to pick up a book and read to a child.\"\n , 'Today was good. Today was fun. Tomorrow is another one.',\n 'I meant what I said and I said what I meant.',\n \"You're in pretty good shape for the shape you are in.\",\n 'Only you can control your future.', 'I am not a consecutive writer.',\n \"Maybe Christmas, the Grinch thought, doesn't come from a store.\",\n 'Preachers in pulpits talked about what a great message is in the book. No matter what you do, somebody always imputes meaning into your books.'\n ,\n 'Sometimes, when I see my granddaughters make small discoveries of their own, I wish I were a child.'\n , 'Adults are obsolete children.',\n \"Whenever things go a bit sour in a job I'm doing, I always tell myself, 'You can do better than this.'\"\n , 'From there to here, and here to there, funny things are everywhere.',\n \"I stay out of politics because if I begin thinking too much about politics, I'll probably... drop writing children's books and become a political cartoonist again.\"\n , \"I was saving the name of 'Geisel' for the Great American Novel.\",\n \"You make 'em, I amuse 'em.\"]\n", "step-3": "quotes = [\n\"Today you are you! That is truer than true! There is no one alive who is you-er than you!\",\n\"Don't cry because it's over. Smile because it happened.\",\n\"You have brains in your head. You have feet in your shoes. You can steer yourself in any direction you choose. You're on your own, and you know what you know. And you are the guy who'll decide where to go.\",\n\"The more that you read, the more things you will know. The more that you learn, the more places you'll go. \",\n\"I like nonsense; it wakes up the brain cells.\",\n\"Step with care and great tact, and remember that Life's a Great Balancing Act.\",\n\"How did it get so late so soon? Its night before its afternoon. December is here before its June. My goodness how the time has flewn. How did it get so late so soon?\",\n\"Think left and think right and think low and think high. Oh, the thinks you can think up if only you try!\",\n\"A person's a person, no matter how small.\",\n\"You can get help from teachers, but you are going to have to learn a lot by yourself, sitting alone in a room.\",\n\"Unless someone like you cares a whole awful lot, nothing is going to get better. It's not.\",\n\"You're never too old, too wacky, too wild, to pick up a book and read to a child.\",\n\"Today was good. Today was fun. Tomorrow is another one.\",\n\"I meant what I said and I said what I meant.\", \n\"You're in pretty good shape for the shape you are in.\",\n\"Only you can control your future.\",\n\"I am not a consecutive writer.\",\n\"Maybe Christmas, the Grinch thought, doesn't come from a store.\",\n\"Preachers in pulpits talked about what a great message is in the book. No matter what you do, somebody always imputes meaning into your books.\", \n\"Sometimes, when I see my granddaughters make small discoveries of their own, I wish I were a child.\",\n\"Adults are obsolete children.\",\n\"Whenever things go a bit sour in a job I'm doing, I always tell myself, 'You can do better than this.'\",\n\"From there to here, and here to there, funny things are everywhere.\",\n\"I stay out of politics because if I begin thinking too much about politics, I'll probably... drop writing children's books and become a political cartoonist again.\",\n\"I was saving the name of 'Geisel' for the Great American Novel.\",\n\"You make 'em, I amuse 'em.\"\n]", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
import datetime as dt import numpy as np import pandas as pd import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func from flask import Flask, jsonify, render_template, abort #creating engine to connect with hawaii sqlite database engine = create_engine("sqlite:///hawaii.sqlite") #using automap to load orm automatically Base = automap_base() # reflecting the tables from orm classes Base.prepare(engine, reflect = True) Measurement = Base.classes.measurement Station = Base.classes.station # print(Base.classes.keys()) #initiating session session = Session(engine) # initiating flask api app = Flask(__name__) @app.route('/') def welcome(): return jsonify({"Title": "Welcome to hawaii weather info app", "description": "This api gives you the information about Hawaii stations, precipitation and temperature in a daterange", "endpoints":["/api/v1.0/precipitation", "/api/v1.0/stations", "/api/v1.0/tobs", "/api/v1.0/<start>", "/api/v1.0/<start>/<end>"]}) @app.route("/api/v1.0/precipitation") def prcp(): prev_year = dt.date.today() - dt.timedelta(days=365) # date_string = prev_year.strftime("%Y-%m-%d") prcp_each_day = session.query(Measurement.date,func.sum(Measurement.prcp)).filter(Measurement.date >= prev_year).group_by(Measurement.date).order_by(Measurement.date).all() prcp_dict = dict(prcp_each_day) return jsonify(prcp_dict) @app.route('/api/v1.0/stations') def stations(): """return a json list of stations from the dataset.""" stationquery = session.query(Station.station).all() stationlist = list(np.ravel(stationquery)) return jsonify(stationlist) @app.route('/api/v1.0/tobs') def tobs(): """Return a json list of Temperature Observations (tobs) for the previous year""" prev_year = dt.date.today() - dt.timedelta(days=365) # date_string = prev_year.strftime("%Y-%m-%d") tobsquery = session.query(Measurement.tobs).filter(Measurement.date >= prev_year).all() tobslist = list(np.ravel(tobsquery)) return jsonify(tobslist) #executing the error handler page using 404 abort @app.errorhandler(404) def page_not_found(e): return ("<h2> 404: Page Not Found </h2>" "Please enter a date in database range: <b>2010-01-01</b> to <b>2017-08-23</b>"),404 @app.route('/api/v1.0/<start>', methods=["GET"]) # Return a json list of the minimum temperature, the average temperature, and the max temperature for a given start or start-end range. # When given the start only, calculate TMIN, TAVG, and TMAX for all dates greater than and equal to the start date. # When given the start and the end date, calculate the TMIN, TAVG, and TMAX for dates between the start and end date inclusive. def tobsinfo_start(start): # daterange = [date for dates in session.query(Measurement.date).all()] try: if start:# in daterange: # start = func.strftime('%Y-%m-%d', 'start') sel = [func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)] calcs = session.query(*sel).filter(func.strftime('%Y-%m-%d',Measurement.date) >= start).one() return ( f"<h2> Temperature(F) informtion from {start} </h2>" f"Minimum temp: {calcs[0]}<br>" f"Average temp: {round(calcs[1],2)}<br>" f"Maximum temp: {round(calcs[2],2)}<br>" ) except: abort(404) @app.route("/api/v1.0/tobs/<startDate>/<endDate>") def getTempObs(startDate,endDate): """Return the date and temperateure for 2017""" # Query all the date and the temperature details results = session.query(Measurement.tobs). filter(Measurement.date >= startDate).filter(Measurement.date <= endDate).all() # Convert list of tuples into normal list all_names = list(np.ravel(results)) return jsonify(all_names) # 12. Get the temperature stats for given date @app.route("/api/v1.0/<startDate>/<endDate>") @app.route("/api/v1.0/<startDate>") def getTempStats(startDate,endDate='2018-31-12'): """Return temperature stats""" #If end date is not given if endDate == '2018-31-12': results = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\ filter(Measurement.date >= startDate).all() else: # Query all the date and the temperature details og results = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\ filter(Measurement.date >= startDate).filter(Measurement.date <= endDate).all() # Convert list of tuples into normal list all_names = list(np.ravel(results)) return jsonify(all_names) if __name__ == '__main__': app.run(debug=True)
normal
{ "blob_id": "c295d769b85943a6ca89f9d213e79b78129a6ce9", "index": 2031, "step-1": "<mask token>\n\n\[email protected]('/api/v1.0/stations')\ndef stations():\n \"\"\"return a json list of stations from the dataset.\"\"\"\n stationquery = session.query(Station.station).all()\n stationlist = list(np.ravel(stationquery))\n return jsonify(stationlist)\n\n\n<mask token>\n\n\[email protected]('/api/v1.0/tobs/<startDate>/<endDate>')\ndef getTempObs(startDate, endDate):\n \"\"\"Return the date and temperateure for 2017\"\"\"\n results = session.query(Measurement.tobs).filter(Measurement.date >=\n startDate).filter(Measurement.date <= endDate).all()\n all_names = list(np.ravel(results))\n return jsonify(all_names)\n\n\[email protected]('/api/v1.0/<startDate>/<endDate>')\[email protected]('/api/v1.0/<startDate>')\ndef getTempStats(startDate, endDate='2018-31-12'):\n \"\"\"Return temperature stats\"\"\"\n if endDate == '2018-31-12':\n results = session.query(func.min(Measurement.tobs), func.avg(\n Measurement.tobs), func.max(Measurement.tobs)).filter(\n Measurement.date >= startDate).all()\n else:\n results = session.query(func.min(Measurement.tobs), func.avg(\n Measurement.tobs), func.max(Measurement.tobs)).filter(\n Measurement.date >= startDate).filter(Measurement.date <= endDate\n ).all()\n all_names = list(np.ravel(results))\n return jsonify(all_names)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\[email protected]('/')\ndef welcome():\n return jsonify({'Title': 'Welcome to hawaii weather info app',\n 'description':\n 'This api gives you the information about Hawaii stations, precipitation and temperature in a daterange'\n , 'endpoints': ['/api/v1.0/precipitation', '/api/v1.0/stations',\n '/api/v1.0/tobs', '/api/v1.0/<start>', '/api/v1.0/<start>/<end>']})\n\n\[email protected]('/api/v1.0/precipitation')\ndef prcp():\n prev_year = dt.date.today() - dt.timedelta(days=365)\n prcp_each_day = session.query(Measurement.date, func.sum(Measurement.prcp)\n ).filter(Measurement.date >= prev_year).group_by(Measurement.date\n ).order_by(Measurement.date).all()\n prcp_dict = dict(prcp_each_day)\n return jsonify(prcp_dict)\n\n\[email protected]('/api/v1.0/stations')\ndef stations():\n \"\"\"return a json list of stations from the dataset.\"\"\"\n stationquery = session.query(Station.station).all()\n stationlist = list(np.ravel(stationquery))\n return jsonify(stationlist)\n\n\[email protected]('/api/v1.0/tobs')\ndef tobs():\n \"\"\"Return a json list of Temperature Observations (tobs) for the previous year\"\"\"\n prev_year = dt.date.today() - dt.timedelta(days=365)\n tobsquery = session.query(Measurement.tobs).filter(Measurement.date >=\n prev_year).all()\n tobslist = list(np.ravel(tobsquery))\n return jsonify(tobslist)\n\n\[email protected](404)\ndef page_not_found(e):\n return (\n '<h2> 404: Page Not Found </h2>Please enter a date in database range: <b>2010-01-01</b> to <b>2017-08-23</b>'\n , 404)\n\n\[email protected]('/api/v1.0/<start>', methods=['GET'])\ndef tobsinfo_start(start):\n try:\n if start:\n sel = [func.min(Measurement.tobs), func.avg(Measurement.tobs),\n func.max(Measurement.tobs)]\n calcs = session.query(*sel).filter(func.strftime('%Y-%m-%d',\n Measurement.date) >= start).one()\n return (\n f'<h2> Temperature(F) informtion from {start} </h2>Minimum temp: {calcs[0]}<br>Average temp: {round(calcs[1], 2)}<br>Maximum temp: {round(calcs[2], 2)}<br>'\n )\n except:\n abort(404)\n\n\[email protected]('/api/v1.0/tobs/<startDate>/<endDate>')\ndef getTempObs(startDate, endDate):\n \"\"\"Return the date and temperateure for 2017\"\"\"\n results = session.query(Measurement.tobs).filter(Measurement.date >=\n startDate).filter(Measurement.date <= endDate).all()\n all_names = list(np.ravel(results))\n return jsonify(all_names)\n\n\[email protected]('/api/v1.0/<startDate>/<endDate>')\[email protected]('/api/v1.0/<startDate>')\ndef getTempStats(startDate, endDate='2018-31-12'):\n \"\"\"Return temperature stats\"\"\"\n if endDate == '2018-31-12':\n results = session.query(func.min(Measurement.tobs), func.avg(\n Measurement.tobs), func.max(Measurement.tobs)).filter(\n Measurement.date >= startDate).all()\n else:\n results = session.query(func.min(Measurement.tobs), func.avg(\n Measurement.tobs), func.max(Measurement.tobs)).filter(\n Measurement.date >= startDate).filter(Measurement.date <= endDate\n ).all()\n all_names = list(np.ravel(results))\n return jsonify(all_names)\n\n\n<mask token>\n", "step-3": "<mask token>\nBase.prepare(engine, reflect=True)\n<mask token>\n\n\[email protected]('/')\ndef welcome():\n return jsonify({'Title': 'Welcome to hawaii weather info app',\n 'description':\n 'This api gives you the information about Hawaii stations, precipitation and temperature in a daterange'\n , 'endpoints': ['/api/v1.0/precipitation', '/api/v1.0/stations',\n '/api/v1.0/tobs', '/api/v1.0/<start>', '/api/v1.0/<start>/<end>']})\n\n\[email protected]('/api/v1.0/precipitation')\ndef prcp():\n prev_year = dt.date.today() - dt.timedelta(days=365)\n prcp_each_day = session.query(Measurement.date, func.sum(Measurement.prcp)\n ).filter(Measurement.date >= prev_year).group_by(Measurement.date\n ).order_by(Measurement.date).all()\n prcp_dict = dict(prcp_each_day)\n return jsonify(prcp_dict)\n\n\[email protected]('/api/v1.0/stations')\ndef stations():\n \"\"\"return a json list of stations from the dataset.\"\"\"\n stationquery = session.query(Station.station).all()\n stationlist = list(np.ravel(stationquery))\n return jsonify(stationlist)\n\n\[email protected]('/api/v1.0/tobs')\ndef tobs():\n \"\"\"Return a json list of Temperature Observations (tobs) for the previous year\"\"\"\n prev_year = dt.date.today() - dt.timedelta(days=365)\n tobsquery = session.query(Measurement.tobs).filter(Measurement.date >=\n prev_year).all()\n tobslist = list(np.ravel(tobsquery))\n return jsonify(tobslist)\n\n\[email protected](404)\ndef page_not_found(e):\n return (\n '<h2> 404: Page Not Found </h2>Please enter a date in database range: <b>2010-01-01</b> to <b>2017-08-23</b>'\n , 404)\n\n\[email protected]('/api/v1.0/<start>', methods=['GET'])\ndef tobsinfo_start(start):\n try:\n if start:\n sel = [func.min(Measurement.tobs), func.avg(Measurement.tobs),\n func.max(Measurement.tobs)]\n calcs = session.query(*sel).filter(func.strftime('%Y-%m-%d',\n Measurement.date) >= start).one()\n return (\n f'<h2> Temperature(F) informtion from {start} </h2>Minimum temp: {calcs[0]}<br>Average temp: {round(calcs[1], 2)}<br>Maximum temp: {round(calcs[2], 2)}<br>'\n )\n except:\n abort(404)\n\n\[email protected]('/api/v1.0/tobs/<startDate>/<endDate>')\ndef getTempObs(startDate, endDate):\n \"\"\"Return the date and temperateure for 2017\"\"\"\n results = session.query(Measurement.tobs).filter(Measurement.date >=\n startDate).filter(Measurement.date <= endDate).all()\n all_names = list(np.ravel(results))\n return jsonify(all_names)\n\n\[email protected]('/api/v1.0/<startDate>/<endDate>')\[email protected]('/api/v1.0/<startDate>')\ndef getTempStats(startDate, endDate='2018-31-12'):\n \"\"\"Return temperature stats\"\"\"\n if endDate == '2018-31-12':\n results = session.query(func.min(Measurement.tobs), func.avg(\n Measurement.tobs), func.max(Measurement.tobs)).filter(\n Measurement.date >= startDate).all()\n else:\n results = session.query(func.min(Measurement.tobs), func.avg(\n Measurement.tobs), func.max(Measurement.tobs)).filter(\n Measurement.date >= startDate).filter(Measurement.date <= endDate\n ).all()\n all_names = list(np.ravel(results))\n return jsonify(all_names)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n", "step-4": "<mask token>\nengine = create_engine('sqlite:///hawaii.sqlite')\nBase = automap_base()\nBase.prepare(engine, reflect=True)\nMeasurement = Base.classes.measurement\nStation = Base.classes.station\nsession = Session(engine)\napp = Flask(__name__)\n\n\[email protected]('/')\ndef welcome():\n return jsonify({'Title': 'Welcome to hawaii weather info app',\n 'description':\n 'This api gives you the information about Hawaii stations, precipitation and temperature in a daterange'\n , 'endpoints': ['/api/v1.0/precipitation', '/api/v1.0/stations',\n '/api/v1.0/tobs', '/api/v1.0/<start>', '/api/v1.0/<start>/<end>']})\n\n\[email protected]('/api/v1.0/precipitation')\ndef prcp():\n prev_year = dt.date.today() - dt.timedelta(days=365)\n prcp_each_day = session.query(Measurement.date, func.sum(Measurement.prcp)\n ).filter(Measurement.date >= prev_year).group_by(Measurement.date\n ).order_by(Measurement.date).all()\n prcp_dict = dict(prcp_each_day)\n return jsonify(prcp_dict)\n\n\[email protected]('/api/v1.0/stations')\ndef stations():\n \"\"\"return a json list of stations from the dataset.\"\"\"\n stationquery = session.query(Station.station).all()\n stationlist = list(np.ravel(stationquery))\n return jsonify(stationlist)\n\n\[email protected]('/api/v1.0/tobs')\ndef tobs():\n \"\"\"Return a json list of Temperature Observations (tobs) for the previous year\"\"\"\n prev_year = dt.date.today() - dt.timedelta(days=365)\n tobsquery = session.query(Measurement.tobs).filter(Measurement.date >=\n prev_year).all()\n tobslist = list(np.ravel(tobsquery))\n return jsonify(tobslist)\n\n\[email protected](404)\ndef page_not_found(e):\n return (\n '<h2> 404: Page Not Found </h2>Please enter a date in database range: <b>2010-01-01</b> to <b>2017-08-23</b>'\n , 404)\n\n\[email protected]('/api/v1.0/<start>', methods=['GET'])\ndef tobsinfo_start(start):\n try:\n if start:\n sel = [func.min(Measurement.tobs), func.avg(Measurement.tobs),\n func.max(Measurement.tobs)]\n calcs = session.query(*sel).filter(func.strftime('%Y-%m-%d',\n Measurement.date) >= start).one()\n return (\n f'<h2> Temperature(F) informtion from {start} </h2>Minimum temp: {calcs[0]}<br>Average temp: {round(calcs[1], 2)}<br>Maximum temp: {round(calcs[2], 2)}<br>'\n )\n except:\n abort(404)\n\n\[email protected]('/api/v1.0/tobs/<startDate>/<endDate>')\ndef getTempObs(startDate, endDate):\n \"\"\"Return the date and temperateure for 2017\"\"\"\n results = session.query(Measurement.tobs).filter(Measurement.date >=\n startDate).filter(Measurement.date <= endDate).all()\n all_names = list(np.ravel(results))\n return jsonify(all_names)\n\n\[email protected]('/api/v1.0/<startDate>/<endDate>')\[email protected]('/api/v1.0/<startDate>')\ndef getTempStats(startDate, endDate='2018-31-12'):\n \"\"\"Return temperature stats\"\"\"\n if endDate == '2018-31-12':\n results = session.query(func.min(Measurement.tobs), func.avg(\n Measurement.tobs), func.max(Measurement.tobs)).filter(\n Measurement.date >= startDate).all()\n else:\n results = session.query(func.min(Measurement.tobs), func.avg(\n Measurement.tobs), func.max(Measurement.tobs)).filter(\n Measurement.date >= startDate).filter(Measurement.date <= endDate\n ).all()\n all_names = list(np.ravel(results))\n return jsonify(all_names)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n", "step-5": "import datetime as dt\nimport numpy as np\nimport pandas as pd\n\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\n\nfrom flask import Flask, jsonify, render_template, abort\n\n#creating engine to connect with hawaii sqlite database\n\t\nengine = create_engine(\"sqlite:///hawaii.sqlite\")\n\n#using automap to load orm automatically\n\nBase = automap_base()\n\n# reflecting the tables from orm classes\n\nBase.prepare(engine, reflect = True)\n\nMeasurement = Base.classes.measurement\nStation = Base.classes.station\n# print(Base.classes.keys())\n\n#initiating session\nsession = Session(engine)\n\n# initiating flask api\n\napp = Flask(__name__)\n\[email protected]('/')\ndef welcome():\n return jsonify({\"Title\": \"Welcome to hawaii weather info app\",\n \t\"description\": \"This api gives you the information about Hawaii stations, precipitation and temperature in a daterange\",\n \t\"endpoints\":[\"/api/v1.0/precipitation\",\n \t\"/api/v1.0/stations\",\n \t\"/api/v1.0/tobs\",\n \t\"/api/v1.0/<start>\",\n \t\"/api/v1.0/<start>/<end>\"]})\n\n\[email protected](\"/api/v1.0/precipitation\")\n\ndef prcp():\n\tprev_year = dt.date.today() - dt.timedelta(days=365)\n\t# date_string = prev_year.strftime(\"%Y-%m-%d\")\n\n\tprcp_each_day = session.query(Measurement.date,func.sum(Measurement.prcp)).filter(Measurement.date >= prev_year).group_by(Measurement.date).order_by(Measurement.date).all()\n\t\n\tprcp_dict = dict(prcp_each_day)\n\treturn jsonify(prcp_dict)\n\t\n\[email protected]('/api/v1.0/stations')\n\ndef stations():\n\t\"\"\"return a json list of stations from the dataset.\"\"\"\n\t\n\n\tstationquery = session.query(Station.station).all()\n\n\tstationlist = list(np.ravel(stationquery))\n\t\n\treturn jsonify(stationlist)\n\n\[email protected]('/api/v1.0/tobs')\n\ndef tobs():\n\t\"\"\"Return a json list of Temperature Observations (tobs) for the previous year\"\"\"\n\tprev_year = dt.date.today() - dt.timedelta(days=365)\n\t# date_string = prev_year.strftime(\"%Y-%m-%d\")\n\n\ttobsquery = session.query(Measurement.tobs).filter(Measurement.date >= prev_year).all()\n\n\ttobslist = list(np.ravel(tobsquery))\n\n\treturn jsonify(tobslist)\n\n#executing the error handler page using 404 abort\[email protected](404)\ndef page_not_found(e):\n \n\treturn (\"<h2> 404: Page Not Found </h2>\"\n\t\t\t\"Please enter a date in database range: <b>2010-01-01</b> to <b>2017-08-23</b>\"),404\n\n\n\[email protected]('/api/v1.0/<start>', methods=[\"GET\"])\n\n# Return a json list of the minimum temperature, the average temperature, and the max temperature for a given start or start-end range.\n# When given the start only, calculate TMIN, TAVG, and TMAX for all dates greater than and equal to the start date.\n# When given the start and the end date, calculate the TMIN, TAVG, and TMAX for dates between the start and end date inclusive.\n\n\ndef tobsinfo_start(start):\n\t\n\t# daterange = [date for dates in session.query(Measurement.date).all()]\n\ttry:\n\t\tif start:# in daterange:\n\t\t\t# start = func.strftime('%Y-%m-%d', 'start')\n\n\t\t\tsel = [func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)]\n\n\t\t\tcalcs = session.query(*sel).filter(func.strftime('%Y-%m-%d',Measurement.date) >= start).one()\n\n\n\t\t\treturn (\n\t\t\t\tf\"<h2> Temperature(F) informtion from {start} </h2>\"\n\t\t\t\tf\"Minimum temp: {calcs[0]}<br>\"\n\t\t\t\tf\"Average temp: {round(calcs[1],2)}<br>\"\n\t\t\t\tf\"Maximum temp: {round(calcs[2],2)}<br>\"\n\t\t\t\t)\n\texcept:\n\t\tabort(404)\n\t\t\n\n\[email protected](\"/api/v1.0/tobs/<startDate>/<endDate>\")\n\ndef getTempObs(startDate,endDate):\n\n \"\"\"Return the date and temperateure for 2017\"\"\"\n\n # Query all the date and the temperature details\n\n results = session.query(Measurement.tobs). filter(Measurement.date >= startDate).filter(Measurement.date <= endDate).all()\n\n # Convert list of tuples into normal list\n\n all_names = list(np.ravel(results))\n\n\n\n return jsonify(all_names)\n\n\n# 12. Get the temperature stats for given date\n\[email protected](\"/api/v1.0/<startDate>/<endDate>\")\n\[email protected](\"/api/v1.0/<startDate>\")\n\ndef getTempStats(startDate,endDate='2018-31-12'):\n\n \"\"\"Return temperature stats\"\"\"\n\n #If end date is not given\n\n if endDate == '2018-31-12':\n\n results = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\\n filter(Measurement.date >= startDate).all()\n\n else: \n\n # Query all the date and the temperature details og\n\n results = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\\n filter(Measurement.date >= startDate).filter(Measurement.date <= endDate).all()\n\n # Convert list of tuples into normal list\n\n \n\n all_names = list(np.ravel(results))\n\n return jsonify(all_names)\n\nif __name__ == '__main__':\n\tapp.run(debug=True)\n", "step-ids": [ 3, 8, 9, 10, 12 ] }
[ 3, 8, 9, 10, 12 ]
""" 实战练习: 1.打开网页 https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable 2.操作窗口右侧页面,将元素1拖拽到元素2 3.这时候会有一个alert弹框,点击弹框中的‘确定’ 3.然后再按’点击运行’ 4.关闭网页 """ import pytest from selenium import webdriver from time import sleep from selenium.webdriver import ActionChains class TestFrame: def setup(self): self.driver = webdriver.Chrome() self.driver.get("https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable") self.driver.implicitly_wait(5) self.driver.maximize_window() def teardown(self): self.driver.quit() def test_frame(self): # 检查要打印的元素,可以发现他们属于iframe元素,也就是需要先使用switch_to.frame("新frame的id")切换到对应的frame页 self.driver.switch_to.frame("iframeResult") # 拖拽需要调用ActionChains方法 action=ActionChains(self.driver) drag=self.driver.find_element_by_id("draggable") drop=self.driver.find_element_by_id("droppable") action.drag_and_drop(drag,drop).perform() sleep(2) # 拖拽完成后会弹出一个alert弹框,所以需要切换到alert,并调用.accept()进行确认操作 self.driver.switch_to.alert.accept() # 点击确认后,alert弹框消失,默认还是在拖拽的iframe页面,接下来要点击运行,所以要再次进行切换 self.driver.switch_to.default_content() # 切换到默认frame,第一种方式 #self.driver.switch_to.parent_frame() # 切换到父frame第二种方式,两种方式都可以 self.driver.find_element_by_id("submitBTN").click() sleep(3) if __name__ == '__main__': pytest.main()
normal
{ "blob_id": "74843dea00a88513c3a9237eb024e1e14e8b1ff8", "index": 3088, "step-1": "<mask token>\n\n\nclass TestFrame:\n <mask token>\n\n def teardown(self):\n self.driver.quit()\n\n def test_frame(self):\n self.driver.switch_to.frame('iframeResult')\n action = ActionChains(self.driver)\n drag = self.driver.find_element_by_id('draggable')\n drop = self.driver.find_element_by_id('droppable')\n action.drag_and_drop(drag, drop).perform()\n sleep(2)\n self.driver.switch_to.alert.accept()\n self.driver.switch_to.default_content()\n self.driver.find_element_by_id('submitBTN').click()\n sleep(3)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass TestFrame:\n\n def setup(self):\n self.driver = webdriver.Chrome()\n self.driver.get(\n 'https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable'\n )\n self.driver.implicitly_wait(5)\n self.driver.maximize_window()\n\n def teardown(self):\n self.driver.quit()\n\n def test_frame(self):\n self.driver.switch_to.frame('iframeResult')\n action = ActionChains(self.driver)\n drag = self.driver.find_element_by_id('draggable')\n drop = self.driver.find_element_by_id('droppable')\n action.drag_and_drop(drag, drop).perform()\n sleep(2)\n self.driver.switch_to.alert.accept()\n self.driver.switch_to.default_content()\n self.driver.find_element_by_id('submitBTN').click()\n sleep(3)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass TestFrame:\n\n def setup(self):\n self.driver = webdriver.Chrome()\n self.driver.get(\n 'https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable'\n )\n self.driver.implicitly_wait(5)\n self.driver.maximize_window()\n\n def teardown(self):\n self.driver.quit()\n\n def test_frame(self):\n self.driver.switch_to.frame('iframeResult')\n action = ActionChains(self.driver)\n drag = self.driver.find_element_by_id('draggable')\n drop = self.driver.find_element_by_id('droppable')\n action.drag_and_drop(drag, drop).perform()\n sleep(2)\n self.driver.switch_to.alert.accept()\n self.driver.switch_to.default_content()\n self.driver.find_element_by_id('submitBTN').click()\n sleep(3)\n\n\nif __name__ == '__main__':\n pytest.main()\n", "step-4": "<mask token>\nimport pytest\nfrom selenium import webdriver\nfrom time import sleep\nfrom selenium.webdriver import ActionChains\n\n\nclass TestFrame:\n\n def setup(self):\n self.driver = webdriver.Chrome()\n self.driver.get(\n 'https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable'\n )\n self.driver.implicitly_wait(5)\n self.driver.maximize_window()\n\n def teardown(self):\n self.driver.quit()\n\n def test_frame(self):\n self.driver.switch_to.frame('iframeResult')\n action = ActionChains(self.driver)\n drag = self.driver.find_element_by_id('draggable')\n drop = self.driver.find_element_by_id('droppable')\n action.drag_and_drop(drag, drop).perform()\n sleep(2)\n self.driver.switch_to.alert.accept()\n self.driver.switch_to.default_content()\n self.driver.find_element_by_id('submitBTN').click()\n sleep(3)\n\n\nif __name__ == '__main__':\n pytest.main()\n", "step-5": "\"\"\"\n实战练习:\n1.打开网页\nhttps://www.runoob.com/try/try.php?filename=jqueryui-api-droppable\n2.操作窗口右侧页面,将元素1拖拽到元素2\n3.这时候会有一个alert弹框,点击弹框中的‘确定’\n3.然后再按’点击运行’\n4.关闭网页\n\"\"\"\nimport pytest\nfrom selenium import webdriver\nfrom time import sleep\nfrom selenium.webdriver import ActionChains\nclass TestFrame:\n def setup(self):\n self.driver = webdriver.Chrome()\n self.driver.get(\"https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable\")\n self.driver.implicitly_wait(5)\n self.driver.maximize_window()\n def teardown(self):\n self.driver.quit()\n def test_frame(self):\n # 检查要打印的元素,可以发现他们属于iframe元素,也就是需要先使用switch_to.frame(\"新frame的id\")切换到对应的frame页\n self.driver.switch_to.frame(\"iframeResult\")\n # 拖拽需要调用ActionChains方法\n action=ActionChains(self.driver)\n drag=self.driver.find_element_by_id(\"draggable\")\n drop=self.driver.find_element_by_id(\"droppable\")\n action.drag_and_drop(drag,drop).perform()\n sleep(2)\n # 拖拽完成后会弹出一个alert弹框,所以需要切换到alert,并调用.accept()进行确认操作\n self.driver.switch_to.alert.accept()\n # 点击确认后,alert弹框消失,默认还是在拖拽的iframe页面,接下来要点击运行,所以要再次进行切换\n self.driver.switch_to.default_content() # 切换到默认frame,第一种方式\n #self.driver.switch_to.parent_frame() # 切换到父frame第二种方式,两种方式都可以\n self.driver.find_element_by_id(\"submitBTN\").click()\n sleep(3)\nif __name__ == '__main__':\n pytest.main()\n", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
from snake.snake import Snake # Start application if __name__ == '__main__': s = Snake() s.run()
normal
{ "blob_id": "efed5c113e085e5b41d9169901c18c06111b9077", "index": 8894, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n s = Snake()\n s.run()\n", "step-3": "from snake.snake import Snake\nif __name__ == '__main__':\n s = Snake()\n s.run()\n", "step-4": "from snake.snake import Snake\n\n# Start application\nif __name__ == '__main__':\n s = Snake()\n s.run()", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 处理与合约名字有关的变量 """ import re # 上期所 PRODUCTS_SHFE = {'cu', 'al', 'zn', 'pb', 'ni', 'sn', 'au', 'ag', 'rb', 'wr', 'hc', 'fu', 'bu', 'ru'} # 中金所 PRODUCTS_CFFEX = {'IF', 'IC', 'IH', 'T', 'TF'} # 郑商所 PRODUCTS_CZCE = {'SR', 'CF', 'ZC', 'FG', 'TA', 'WH', 'PM', 'RI', 'LR', 'JR', 'RS', 'OI', 'RM', 'SF', 'SM', 'MA', 'WT', 'WS', 'RO', 'ER', 'ME', 'TC'} # 大商所 PRODUCTS_DCE = {'m', 'y', 'a', 'b', 'p', 'c', 'cs', 'jd', 'fb', 'bb', 'l', 'v', 'pp', 'j', 'jm', 'i'} EXCHANGES_wind_code_xapi = { 'CFE': 'CFFEX', 'SHF': 'SHFE', 'CZC': 'CZCE', 'DCE': 'DCE', 'SH': 'SSE', 'SZ': 'SZSE', } EXCHANGES_xapi_wind_code = dict((v, k) for k, v in EXCHANGES_wind_code_xapi.items()) def product_to_exchange(product): """ 将合约产品码转成交易所 :param product: :return: """ PRODUCT_ = product.upper() if PRODUCT_ in PRODUCTS_CFFEX: return 'CFFEX' if PRODUCT_ in PRODUCTS_CZCE: return 'CZCE' product_ = product.lower() if product_ in PRODUCTS_SHFE: return 'SHFE' if product_ in PRODUCTS_DCE: return 'DCE' return 'Unknown' def is_shfe(product): """ 是否上期所 多添加此函数的主要原因是上期所需要区分平今与平昨 :param product: :return: """ product_ = product.lower() return product_ in PRODUCTS_SHFE def get_product(symbol): """ 从合约名中提取产品名 :param symbol: :return: """ pattern = re.compile(r'(\D{1,2})(\d{0,1})(\d{3})') match = pattern.match(symbol) if match: return match.expand(r'\g<1>') else: return symbol def get_exchange(symbol): """ 从带.的合约名中提取交易所 :param symbol: :return: """ pattern = re.compile(r'(\.)(\D{1,4})') match = pattern.match(symbol) if match: return match.expand(r'\g<2>') else: return symbol if __name__ == '__main__': import pandas as pd df = pd.DataFrame({'Symbol': ['IF1603', 'rb1708','600000']}) df['IsSHFE'] = list(map(is_shfe, map(get_product, df['Symbol']))) df['product'] = list(map(get_product, df['Symbol'])) df['IsSHFE'] = list(map(is_shfe, df['product'])) print(df) print(get_product('IF1406')) print(EXCHANGES_wind_code_xapi.get('SH'))
normal
{ "blob_id": "8bb39149a5b7f4f4b1d3d62a002ab97421905ea1", "index": 551, "step-1": "<mask token>\n\n\ndef get_product(symbol):\n \"\"\"\n 从合约名中提取产品名\n :param symbol:\n :return:\n \"\"\"\n pattern = re.compile('(\\\\D{1,2})(\\\\d{0,1})(\\\\d{3})')\n match = pattern.match(symbol)\n if match:\n return match.expand('\\\\g<1>')\n else:\n return symbol\n\n\ndef get_exchange(symbol):\n \"\"\"\n 从带.的合约名中提取交易所\n :param symbol:\n :return:\n \"\"\"\n pattern = re.compile('(\\\\.)(\\\\D{1,4})')\n match = pattern.match(symbol)\n if match:\n return match.expand('\\\\g<2>')\n else:\n return symbol\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef product_to_exchange(product):\n \"\"\"\n 将合约产品码转成交易所\n :param product:\n :return:\n \"\"\"\n PRODUCT_ = product.upper()\n if PRODUCT_ in PRODUCTS_CFFEX:\n return 'CFFEX'\n if PRODUCT_ in PRODUCTS_CZCE:\n return 'CZCE'\n product_ = product.lower()\n if product_ in PRODUCTS_SHFE:\n return 'SHFE'\n if product_ in PRODUCTS_DCE:\n return 'DCE'\n return 'Unknown'\n\n\ndef is_shfe(product):\n \"\"\"\n 是否上期所\n 多添加此函数的主要原因是上期所需要区分平今与平昨\n :param product:\n :return:\n \"\"\"\n product_ = product.lower()\n return product_ in PRODUCTS_SHFE\n\n\ndef get_product(symbol):\n \"\"\"\n 从合约名中提取产品名\n :param symbol:\n :return:\n \"\"\"\n pattern = re.compile('(\\\\D{1,2})(\\\\d{0,1})(\\\\d{3})')\n match = pattern.match(symbol)\n if match:\n return match.expand('\\\\g<1>')\n else:\n return symbol\n\n\ndef get_exchange(symbol):\n \"\"\"\n 从带.的合约名中提取交易所\n :param symbol:\n :return:\n \"\"\"\n pattern = re.compile('(\\\\.)(\\\\D{1,4})')\n match = pattern.match(symbol)\n if match:\n return match.expand('\\\\g<2>')\n else:\n return symbol\n\n\nif __name__ == '__main__':\n import pandas as pd\n df = pd.DataFrame({'Symbol': ['IF1603', 'rb1708', '600000']})\n df['IsSHFE'] = list(map(is_shfe, map(get_product, df['Symbol'])))\n df['product'] = list(map(get_product, df['Symbol']))\n df['IsSHFE'] = list(map(is_shfe, df['product']))\n print(df)\n print(get_product('IF1406'))\n print(EXCHANGES_wind_code_xapi.get('SH'))\n", "step-3": "<mask token>\nPRODUCTS_SHFE = {'cu', 'al', 'zn', 'pb', 'ni', 'sn', 'au', 'ag', 'rb', 'wr',\n 'hc', 'fu', 'bu', 'ru'}\nPRODUCTS_CFFEX = {'IF', 'IC', 'IH', 'T', 'TF'}\nPRODUCTS_CZCE = {'SR', 'CF', 'ZC', 'FG', 'TA', 'WH', 'PM', 'RI', 'LR', 'JR',\n 'RS', 'OI', 'RM', 'SF', 'SM', 'MA', 'WT', 'WS', 'RO', 'ER', 'ME', 'TC'}\nPRODUCTS_DCE = {'m', 'y', 'a', 'b', 'p', 'c', 'cs', 'jd', 'fb', 'bb', 'l',\n 'v', 'pp', 'j', 'jm', 'i'}\nEXCHANGES_wind_code_xapi = {'CFE': 'CFFEX', 'SHF': 'SHFE', 'CZC': 'CZCE',\n 'DCE': 'DCE', 'SH': 'SSE', 'SZ': 'SZSE'}\nEXCHANGES_xapi_wind_code = dict((v, k) for k, v in EXCHANGES_wind_code_xapi\n .items())\n\n\ndef product_to_exchange(product):\n \"\"\"\n 将合约产品码转成交易所\n :param product:\n :return:\n \"\"\"\n PRODUCT_ = product.upper()\n if PRODUCT_ in PRODUCTS_CFFEX:\n return 'CFFEX'\n if PRODUCT_ in PRODUCTS_CZCE:\n return 'CZCE'\n product_ = product.lower()\n if product_ in PRODUCTS_SHFE:\n return 'SHFE'\n if product_ in PRODUCTS_DCE:\n return 'DCE'\n return 'Unknown'\n\n\ndef is_shfe(product):\n \"\"\"\n 是否上期所\n 多添加此函数的主要原因是上期所需要区分平今与平昨\n :param product:\n :return:\n \"\"\"\n product_ = product.lower()\n return product_ in PRODUCTS_SHFE\n\n\ndef get_product(symbol):\n \"\"\"\n 从合约名中提取产品名\n :param symbol:\n :return:\n \"\"\"\n pattern = re.compile('(\\\\D{1,2})(\\\\d{0,1})(\\\\d{3})')\n match = pattern.match(symbol)\n if match:\n return match.expand('\\\\g<1>')\n else:\n return symbol\n\n\ndef get_exchange(symbol):\n \"\"\"\n 从带.的合约名中提取交易所\n :param symbol:\n :return:\n \"\"\"\n pattern = re.compile('(\\\\.)(\\\\D{1,4})')\n match = pattern.match(symbol)\n if match:\n return match.expand('\\\\g<2>')\n else:\n return symbol\n\n\nif __name__ == '__main__':\n import pandas as pd\n df = pd.DataFrame({'Symbol': ['IF1603', 'rb1708', '600000']})\n df['IsSHFE'] = list(map(is_shfe, map(get_product, df['Symbol'])))\n df['product'] = list(map(get_product, df['Symbol']))\n df['IsSHFE'] = list(map(is_shfe, df['product']))\n print(df)\n print(get_product('IF1406'))\n print(EXCHANGES_wind_code_xapi.get('SH'))\n", "step-4": "<mask token>\nimport re\nPRODUCTS_SHFE = {'cu', 'al', 'zn', 'pb', 'ni', 'sn', 'au', 'ag', 'rb', 'wr',\n 'hc', 'fu', 'bu', 'ru'}\nPRODUCTS_CFFEX = {'IF', 'IC', 'IH', 'T', 'TF'}\nPRODUCTS_CZCE = {'SR', 'CF', 'ZC', 'FG', 'TA', 'WH', 'PM', 'RI', 'LR', 'JR',\n 'RS', 'OI', 'RM', 'SF', 'SM', 'MA', 'WT', 'WS', 'RO', 'ER', 'ME', 'TC'}\nPRODUCTS_DCE = {'m', 'y', 'a', 'b', 'p', 'c', 'cs', 'jd', 'fb', 'bb', 'l',\n 'v', 'pp', 'j', 'jm', 'i'}\nEXCHANGES_wind_code_xapi = {'CFE': 'CFFEX', 'SHF': 'SHFE', 'CZC': 'CZCE',\n 'DCE': 'DCE', 'SH': 'SSE', 'SZ': 'SZSE'}\nEXCHANGES_xapi_wind_code = dict((v, k) for k, v in EXCHANGES_wind_code_xapi\n .items())\n\n\ndef product_to_exchange(product):\n \"\"\"\n 将合约产品码转成交易所\n :param product:\n :return:\n \"\"\"\n PRODUCT_ = product.upper()\n if PRODUCT_ in PRODUCTS_CFFEX:\n return 'CFFEX'\n if PRODUCT_ in PRODUCTS_CZCE:\n return 'CZCE'\n product_ = product.lower()\n if product_ in PRODUCTS_SHFE:\n return 'SHFE'\n if product_ in PRODUCTS_DCE:\n return 'DCE'\n return 'Unknown'\n\n\ndef is_shfe(product):\n \"\"\"\n 是否上期所\n 多添加此函数的主要原因是上期所需要区分平今与平昨\n :param product:\n :return:\n \"\"\"\n product_ = product.lower()\n return product_ in PRODUCTS_SHFE\n\n\ndef get_product(symbol):\n \"\"\"\n 从合约名中提取产品名\n :param symbol:\n :return:\n \"\"\"\n pattern = re.compile('(\\\\D{1,2})(\\\\d{0,1})(\\\\d{3})')\n match = pattern.match(symbol)\n if match:\n return match.expand('\\\\g<1>')\n else:\n return symbol\n\n\ndef get_exchange(symbol):\n \"\"\"\n 从带.的合约名中提取交易所\n :param symbol:\n :return:\n \"\"\"\n pattern = re.compile('(\\\\.)(\\\\D{1,4})')\n match = pattern.match(symbol)\n if match:\n return match.expand('\\\\g<2>')\n else:\n return symbol\n\n\nif __name__ == '__main__':\n import pandas as pd\n df = pd.DataFrame({'Symbol': ['IF1603', 'rb1708', '600000']})\n df['IsSHFE'] = list(map(is_shfe, map(get_product, df['Symbol'])))\n df['product'] = list(map(get_product, df['Symbol']))\n df['IsSHFE'] = list(map(is_shfe, df['product']))\n print(df)\n print(get_product('IF1406'))\n print(EXCHANGES_wind_code_xapi.get('SH'))\n", "step-5": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n处理与合约名字有关的变量\n\"\"\"\nimport re\n\n# 上期所\nPRODUCTS_SHFE = {'cu', 'al', 'zn', 'pb', 'ni', 'sn', 'au', 'ag', 'rb', 'wr', 'hc', 'fu', 'bu', 'ru'}\n# 中金所\nPRODUCTS_CFFEX = {'IF', 'IC', 'IH', 'T', 'TF'}\n# 郑商所\nPRODUCTS_CZCE = {'SR', 'CF', 'ZC', 'FG', 'TA', 'WH', 'PM', 'RI', 'LR', 'JR', 'RS', 'OI', 'RM', 'SF', 'SM', 'MA', 'WT',\n 'WS', 'RO', 'ER', 'ME', 'TC'}\n# 大商所\nPRODUCTS_DCE = {'m', 'y', 'a', 'b', 'p', 'c', 'cs', 'jd', 'fb', 'bb', 'l', 'v', 'pp', 'j', 'jm', 'i'}\n\nEXCHANGES_wind_code_xapi = {\n 'CFE': 'CFFEX',\n 'SHF': 'SHFE',\n 'CZC': 'CZCE',\n 'DCE': 'DCE',\n 'SH': 'SSE',\n 'SZ': 'SZSE',\n}\n\nEXCHANGES_xapi_wind_code = dict((v, k) for k, v in EXCHANGES_wind_code_xapi.items())\n\n\ndef product_to_exchange(product):\n \"\"\"\n 将合约产品码转成交易所\n :param product:\n :return:\n \"\"\"\n PRODUCT_ = product.upper()\n if PRODUCT_ in PRODUCTS_CFFEX:\n return 'CFFEX'\n if PRODUCT_ in PRODUCTS_CZCE:\n return 'CZCE'\n product_ = product.lower()\n if product_ in PRODUCTS_SHFE:\n return 'SHFE'\n if product_ in PRODUCTS_DCE:\n return 'DCE'\n return 'Unknown'\n\n\ndef is_shfe(product):\n \"\"\"\n 是否上期所\n 多添加此函数的主要原因是上期所需要区分平今与平昨\n :param product:\n :return:\n \"\"\"\n product_ = product.lower()\n return product_ in PRODUCTS_SHFE\n\n\ndef get_product(symbol):\n \"\"\"\n 从合约名中提取产品名\n :param symbol:\n :return:\n \"\"\"\n pattern = re.compile(r'(\\D{1,2})(\\d{0,1})(\\d{3})')\n match = pattern.match(symbol)\n if match:\n return match.expand(r'\\g<1>')\n else:\n return symbol\n\n\ndef get_exchange(symbol):\n \"\"\"\n 从带.的合约名中提取交易所\n :param symbol:\n :return:\n \"\"\"\n pattern = re.compile(r'(\\.)(\\D{1,4})')\n match = pattern.match(symbol)\n if match:\n return match.expand(r'\\g<2>')\n else:\n return symbol\n\n\nif __name__ == '__main__':\n import pandas as pd\n\n df = pd.DataFrame({'Symbol': ['IF1603', 'rb1708','600000']})\n df['IsSHFE'] = list(map(is_shfe, map(get_product, df['Symbol'])))\n\n df['product'] = list(map(get_product, df['Symbol']))\n df['IsSHFE'] = list(map(is_shfe, df['product']))\n print(df)\n print(get_product('IF1406'))\n print(EXCHANGES_wind_code_xapi.get('SH'))\n", "step-ids": [ 2, 5, 6, 7, 8 ] }
[ 2, 5, 6, 7, 8 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> def countOfZeros(num): cnt = 0 while num != 0: cnt += 1 num = num & num - 1 return 32 - cnt <|reserved_special_token_0|> <|reserved_special_token_1|> def countOfZeros(num): cnt = 0 while num != 0: cnt += 1 num = num & num - 1 return 32 - cnt def main(): num = eval(input("Enter number to count zeros in it's binary: ")) print('Assumung int is of 32 bits.') result = countOfZeros(num) print("Number of zero's in %d = %d" % (num, result)) <|reserved_special_token_0|> <|reserved_special_token_1|> def countOfZeros(num): cnt = 0 while num != 0: cnt += 1 num = num & num - 1 return 32 - cnt def main(): num = eval(input("Enter number to count zeros in it's binary: ")) print('Assumung int is of 32 bits.') result = countOfZeros(num) print("Number of zero's in %d = %d" % (num, result)) if __name__ == '__main__': main() <|reserved_special_token_1|> # Write a program to accept a no & count number of zeros in it.(int=32bits) def countOfZeros(num): cnt = 0 while(num!=0): cnt+=1 num = num&(num-1) return (32-cnt) def main(): num = eval(input('Enter number to count zeros in it\'s binary: ')) print('Assumung int is of 32 bits.') result = countOfZeros(num) print('Number of zero\'s in %d = %d'%(num,result)) if __name__ == '__main__': main()
flexible
{ "blob_id": "7affd79fb0bb47283bbd9a7fbcaa0ba43aa8e6a6", "index": 106, "step-1": "<mask token>\n", "step-2": "def countOfZeros(num):\n cnt = 0\n while num != 0:\n cnt += 1\n num = num & num - 1\n return 32 - cnt\n\n\n<mask token>\n", "step-3": "def countOfZeros(num):\n cnt = 0\n while num != 0:\n cnt += 1\n num = num & num - 1\n return 32 - cnt\n\n\ndef main():\n num = eval(input(\"Enter number to count zeros in it's binary: \"))\n print('Assumung int is of 32 bits.')\n result = countOfZeros(num)\n print(\"Number of zero's in %d = %d\" % (num, result))\n\n\n<mask token>\n", "step-4": "def countOfZeros(num):\n cnt = 0\n while num != 0:\n cnt += 1\n num = num & num - 1\n return 32 - cnt\n\n\ndef main():\n num = eval(input(\"Enter number to count zeros in it's binary: \"))\n print('Assumung int is of 32 bits.')\n result = countOfZeros(num)\n print(\"Number of zero's in %d = %d\" % (num, result))\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "# Write a program to accept a no & count number of zeros in it.(int=32bits)\r\n\r\ndef countOfZeros(num):\r\n cnt = 0\r\n while(num!=0):\r\n cnt+=1\r\n num = num&(num-1)\r\n return (32-cnt)\r\n \r\n\r\ndef main():\r\n num = eval(input('Enter number to count zeros in it\\'s binary: '))\r\n print('Assumung int is of 32 bits.')\r\n result = countOfZeros(num)\r\n print('Number of zero\\'s in %d = %d'%(num,result))\r\n\r\nif __name__ == '__main__':\r\n main()\r\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> class MMU: <|reserved_special_token_0|> def dma(self, val: int) ->None: dest = 65024 offset = val * 256 for n in range(160): self.mem[dest + n] = self.mem[n + offset] <|reserved_special_token_0|> def __setitem__(self, key: int, val: int) ->None: if key < 32768: self.mbc[key] = val elif key < 40960: self._vram[key - 32768] = val elif key < 49152: if self.mbc.ram_enabled: self._eram[key - 40960] = val elif key < 57344: self._wram[key - 49152] = val elif key < 65024: self._wram[key - 57344] = val elif key < 65184: self.OAM[key - 65024] = val elif key < 65280: pass elif key < 65408: if key in self._io_handlers: self._io_handlers[key].value = val if key == 65280: self._ui.input = val elif key == 65281: self.link_buffer = val elif key == 65282: if val == 129: self.serial_buff += chr(self.link_buffer) if self.link_buffer == ord('\n'): print(self.serial_buff, end='', file=sys.stderr) if self.serial_buff == 'Passed\n': pass elif self.serial_buff == 'Failed\n': pass self.serial_buff = '' else: self.IO[key - 65280] = val elif key < 65535: self._HiRAM[key - 65408] = val else: self.mem[65535] = val def add_io_handler(self, val: int, handler: Register) ->None: self._io_handlers[val] = handler <|reserved_special_token_1|> <|reserved_special_token_0|> class MMU: def __init__(self, interface: Interface, mbc: MBC) ->None: self._ui = interface self.mem = bytearray(random.getrandbits(8) for _ in range(65536)) view = memoryview(self.mem) self._rom0 = view[0:16384] self._rom1 = view[16384:32768] self._vram = view[32768:40960] self._eram = view[40960:49152] self._wram = view[49152:57344] self._wram2 = view[57344:65024] self.OAM = view[65024:65184] self.IO = view[65280:65408] self._HiRAM = view[65408:65535] self.view = view self.mbc = mbc self.mbc.bank0 = self._rom0 self.mbc.bank1 = self._rom1 self.view[65024:65535] = bytearray([(0) for _ in range(511)]) self.mem[65535] = 255 self.link_buffer = 0 self.serial_buff = '' self._io_handlers: Dict[int, Register] = {} self.add_io_handler(65350, HandlerProxy(self.dma)) self.add_io_handler(65360, HandlerProxy(self.mbc.disable_bootrom)) def dma(self, val: int) ->None: dest = 65024 offset = val * 256 for n in range(160): self.mem[dest + n] = self.mem[n + offset] def __getitem__(self, val: int) ->int: if val < 57344: return self.view[val] elif val < 65024: return self.view[val - 8192] elif val < 65152: return self.OAM[val - 65024] elif val < 65280: return 255 elif val < 65408: if val in self._io_handlers: return self._io_handlers[val].value elif val == 65280: return self._ui.input else: return self.IO[val - 65280] elif val < 65535: return self._HiRAM[val - 65408] elif val == 65535: return self.mem[65535] raise ValueError('Access out of bounds') def __setitem__(self, key: int, val: int) ->None: if key < 32768: self.mbc[key] = val elif key < 40960: self._vram[key - 32768] = val elif key < 49152: if self.mbc.ram_enabled: self._eram[key - 40960] = val elif key < 57344: self._wram[key - 49152] = val elif key < 65024: self._wram[key - 57344] = val elif key < 65184: self.OAM[key - 65024] = val elif key < 65280: pass elif key < 65408: if key in self._io_handlers: self._io_handlers[key].value = val if key == 65280: self._ui.input = val elif key == 65281: self.link_buffer = val elif key == 65282: if val == 129: self.serial_buff += chr(self.link_buffer) if self.link_buffer == ord('\n'): print(self.serial_buff, end='', file=sys.stderr) if self.serial_buff == 'Passed\n': pass elif self.serial_buff == 'Failed\n': pass self.serial_buff = '' else: self.IO[key - 65280] = val elif key < 65535: self._HiRAM[key - 65408] = val else: self.mem[65535] = val def add_io_handler(self, val: int, handler: Register) ->None: self._io_handlers[val] = handler <|reserved_special_token_1|> <|reserved_special_token_0|> IE = 65535 DIV = 65284 TIMA = 65285 TMA = 65286 TAC = 65287 IF = 65295 LY = 65348 class MMU: def __init__(self, interface: Interface, mbc: MBC) ->None: self._ui = interface self.mem = bytearray(random.getrandbits(8) for _ in range(65536)) view = memoryview(self.mem) self._rom0 = view[0:16384] self._rom1 = view[16384:32768] self._vram = view[32768:40960] self._eram = view[40960:49152] self._wram = view[49152:57344] self._wram2 = view[57344:65024] self.OAM = view[65024:65184] self.IO = view[65280:65408] self._HiRAM = view[65408:65535] self.view = view self.mbc = mbc self.mbc.bank0 = self._rom0 self.mbc.bank1 = self._rom1 self.view[65024:65535] = bytearray([(0) for _ in range(511)]) self.mem[65535] = 255 self.link_buffer = 0 self.serial_buff = '' self._io_handlers: Dict[int, Register] = {} self.add_io_handler(65350, HandlerProxy(self.dma)) self.add_io_handler(65360, HandlerProxy(self.mbc.disable_bootrom)) def dma(self, val: int) ->None: dest = 65024 offset = val * 256 for n in range(160): self.mem[dest + n] = self.mem[n + offset] def __getitem__(self, val: int) ->int: if val < 57344: return self.view[val] elif val < 65024: return self.view[val - 8192] elif val < 65152: return self.OAM[val - 65024] elif val < 65280: return 255 elif val < 65408: if val in self._io_handlers: return self._io_handlers[val].value elif val == 65280: return self._ui.input else: return self.IO[val - 65280] elif val < 65535: return self._HiRAM[val - 65408] elif val == 65535: return self.mem[65535] raise ValueError('Access out of bounds') def __setitem__(self, key: int, val: int) ->None: if key < 32768: self.mbc[key] = val elif key < 40960: self._vram[key - 32768] = val elif key < 49152: if self.mbc.ram_enabled: self._eram[key - 40960] = val elif key < 57344: self._wram[key - 49152] = val elif key < 65024: self._wram[key - 57344] = val elif key < 65184: self.OAM[key - 65024] = val elif key < 65280: pass elif key < 65408: if key in self._io_handlers: self._io_handlers[key].value = val if key == 65280: self._ui.input = val elif key == 65281: self.link_buffer = val elif key == 65282: if val == 129: self.serial_buff += chr(self.link_buffer) if self.link_buffer == ord('\n'): print(self.serial_buff, end='', file=sys.stderr) if self.serial_buff == 'Passed\n': pass elif self.serial_buff == 'Failed\n': pass self.serial_buff = '' else: self.IO[key - 65280] = val elif key < 65535: self._HiRAM[key - 65408] = val else: self.mem[65535] = val def add_io_handler(self, val: int, handler: Register) ->None: self._io_handlers[val] = handler <|reserved_special_token_1|> from mbc import MBC import random import sys from typing import Dict from interface import Interface from reg import Register, HandlerProxy IE = 65535 DIV = 65284 TIMA = 65285 TMA = 65286 TAC = 65287 IF = 65295 LY = 65348 class MMU: def __init__(self, interface: Interface, mbc: MBC) ->None: self._ui = interface self.mem = bytearray(random.getrandbits(8) for _ in range(65536)) view = memoryview(self.mem) self._rom0 = view[0:16384] self._rom1 = view[16384:32768] self._vram = view[32768:40960] self._eram = view[40960:49152] self._wram = view[49152:57344] self._wram2 = view[57344:65024] self.OAM = view[65024:65184] self.IO = view[65280:65408] self._HiRAM = view[65408:65535] self.view = view self.mbc = mbc self.mbc.bank0 = self._rom0 self.mbc.bank1 = self._rom1 self.view[65024:65535] = bytearray([(0) for _ in range(511)]) self.mem[65535] = 255 self.link_buffer = 0 self.serial_buff = '' self._io_handlers: Dict[int, Register] = {} self.add_io_handler(65350, HandlerProxy(self.dma)) self.add_io_handler(65360, HandlerProxy(self.mbc.disable_bootrom)) def dma(self, val: int) ->None: dest = 65024 offset = val * 256 for n in range(160): self.mem[dest + n] = self.mem[n + offset] def __getitem__(self, val: int) ->int: if val < 57344: return self.view[val] elif val < 65024: return self.view[val - 8192] elif val < 65152: return self.OAM[val - 65024] elif val < 65280: return 255 elif val < 65408: if val in self._io_handlers: return self._io_handlers[val].value elif val == 65280: return self._ui.input else: return self.IO[val - 65280] elif val < 65535: return self._HiRAM[val - 65408] elif val == 65535: return self.mem[65535] raise ValueError('Access out of bounds') def __setitem__(self, key: int, val: int) ->None: if key < 32768: self.mbc[key] = val elif key < 40960: self._vram[key - 32768] = val elif key < 49152: if self.mbc.ram_enabled: self._eram[key - 40960] = val elif key < 57344: self._wram[key - 49152] = val elif key < 65024: self._wram[key - 57344] = val elif key < 65184: self.OAM[key - 65024] = val elif key < 65280: pass elif key < 65408: if key in self._io_handlers: self._io_handlers[key].value = val if key == 65280: self._ui.input = val elif key == 65281: self.link_buffer = val elif key == 65282: if val == 129: self.serial_buff += chr(self.link_buffer) if self.link_buffer == ord('\n'): print(self.serial_buff, end='', file=sys.stderr) if self.serial_buff == 'Passed\n': pass elif self.serial_buff == 'Failed\n': pass self.serial_buff = '' else: self.IO[key - 65280] = val elif key < 65535: self._HiRAM[key - 65408] = val else: self.mem[65535] = val def add_io_handler(self, val: int, handler: Register) ->None: self._io_handlers[val] = handler <|reserved_special_token_1|> from mbc import MBC import random import sys from typing import Dict from interface import Interface from reg import Register, HandlerProxy # I/O Registers IE = 0xFFFF DIV = 0xFF04 TIMA= 0xFF05 TMA = 0xFF06 TAC = 0xFF07 IF = 0xFF0F LY = 0xFF44 class MMU(): #0000 3FFF 16KB ROM bank 00 From cartridge, usually a fixed bank #4000 7FFF 16KB ROM Bank 01~NN From cartridge, switchable bank via MBC (if any) #8000 9FFF 8KB Video RAM (VRAM) Only bank 0 in Non-CGB mode #Switchable bank 0/1 in CGB mode # #A000 BFFF 8KB External RAM In cartridge, switchable bank if any #C000 CFFF 4KB Work RAM (WRAM) bank 0 #D000 DFFF 4KB Work RAM (WRAM) bank 1~N Only bank 1 in Non-CGB mode #Switchable bank 1~7 in CGB mode # #E000 FDFF Mirror of C000~DDFF (ECHO RAM) Typically not used #FE00 FE9F Sprite attribute table (OAM) #FEA0 FEFF Not Usable #FF00 FF7F I/O Registers #FF80 FFFE High RAM (HRAM) #FFFF FFFF Interrupts Enable Register (IE) def __init__(self, interface:Interface, mbc:MBC) -> None: self._ui = interface self.mem = bytearray(random.getrandbits(8) for _ in range(65536)) # type: ignore # Randomise RAM view = memoryview(self.mem) self._rom0 = view[0:0x4000] self._rom1 = view[0x4000:0x8000] self._vram = view[0x8000:0xA000] self._eram = view[0xA000:0xC000] self._wram = view[0xC000:0xE000] self._wram2 = view[0xE000:0xFE00] self.OAM = view[0xFE00:0xFEA0] self.IO = view[0xFF00:0xFF80] self._HiRAM = view[0xFF80:0xFFFF] self.view = view self.mbc = mbc self.mbc.bank0 = self._rom0 self.mbc.bank1 = self._rom1 self.view[0xFE00:0xFFFF] = bytearray([0x00 for _ in range(0x1FF)]) # IO, etc defaults to blank self.mem[0xFFFF] = 0xFF # IE self.link_buffer = 0 self.serial_buff = "" self._io_handlers:Dict[int, Register] = {} self.add_io_handler(0xFF46, HandlerProxy(self.dma)) # Add bootrom disable handler self.add_io_handler(0xFF50, HandlerProxy(self.mbc.disable_bootrom)) def dma(self, val:int) -> None: dest = 0xFE00 offset = val * 0x100 for n in range(0xA0): self.mem[dest + n] = self.mem[n + offset] def __getitem__(self, val:int) -> int: if val < 0xE000: return self.view[val] elif val < 0xFE00: # Echo RAM, subtract 0x2000 return self.view[val-0x2000] elif val < 0xFE80: return self.OAM[val-0xFE00] elif val < 0xFF00: return 0xFF elif val < 0xFF80: if val in self._io_handlers: return self._io_handlers[val].value elif val == 0xFF00: return self._ui.input else: return self.IO[val-0xFF00] elif val < 0xFFFF: return self._HiRAM[val-0xFF80] elif val == 0xFFFF: return self.mem[0xFFFF] raise ValueError("Access out of bounds") def __setitem__(self, key:int, val:int) -> None: if key < 0x8000: self.mbc[key] = val elif key < 0xA000: self._vram[key-0x8000] = val elif key < 0xC000: if self.mbc.ram_enabled: # TODO: Read $0x149 and determine RAM Size # TODO: Pass to MBC self._eram[key-0xA000] = val elif key < 0xE000: self._wram[key-0xC000] = val elif key < 0xFE00: self._wram[key-0xE000] = val elif key < 0xFEA0: self.OAM[key-0xFE00] = val elif key < 0xFF00: pass elif key < 0xFF80: if key in self._io_handlers: self._io_handlers[key].value = val if key == 0xFF00: self._ui.input = val elif key == 0xFF01: self.link_buffer = val elif key == 0xFF02: if val == 0x81: self.serial_buff += chr(self.link_buffer) if self.link_buffer == ord("\n"): print(self.serial_buff, end='', file=sys.stderr) # Test ROM Routines if self.serial_buff == "Passed\n": #sys.exit(0) pass elif self.serial_buff == "Failed\n": #sys.exit(1) pass self.serial_buff = "" else: self.IO[key-0xFF00] = val elif key < 0xFFFF: self._HiRAM[key-0xFF80] = val else: self.mem[65535] = val def add_io_handler(self, val:int, handler:Register) -> None: self._io_handlers[val] = handler
flexible
{ "blob_id": "1a7363736076620b7704d7264b2f0bb24514165c", "index": 9816, "step-1": "<mask token>\n\n\nclass MMU:\n <mask token>\n\n def dma(self, val: int) ->None:\n dest = 65024\n offset = val * 256\n for n in range(160):\n self.mem[dest + n] = self.mem[n + offset]\n <mask token>\n\n def __setitem__(self, key: int, val: int) ->None:\n if key < 32768:\n self.mbc[key] = val\n elif key < 40960:\n self._vram[key - 32768] = val\n elif key < 49152:\n if self.mbc.ram_enabled:\n self._eram[key - 40960] = val\n elif key < 57344:\n self._wram[key - 49152] = val\n elif key < 65024:\n self._wram[key - 57344] = val\n elif key < 65184:\n self.OAM[key - 65024] = val\n elif key < 65280:\n pass\n elif key < 65408:\n if key in self._io_handlers:\n self._io_handlers[key].value = val\n if key == 65280:\n self._ui.input = val\n elif key == 65281:\n self.link_buffer = val\n elif key == 65282:\n if val == 129:\n self.serial_buff += chr(self.link_buffer)\n if self.link_buffer == ord('\\n'):\n print(self.serial_buff, end='', file=sys.stderr)\n if self.serial_buff == 'Passed\\n':\n pass\n elif self.serial_buff == 'Failed\\n':\n pass\n self.serial_buff = ''\n else:\n self.IO[key - 65280] = val\n elif key < 65535:\n self._HiRAM[key - 65408] = val\n else:\n self.mem[65535] = val\n\n def add_io_handler(self, val: int, handler: Register) ->None:\n self._io_handlers[val] = handler\n", "step-2": "<mask token>\n\n\nclass MMU:\n\n def __init__(self, interface: Interface, mbc: MBC) ->None:\n self._ui = interface\n self.mem = bytearray(random.getrandbits(8) for _ in range(65536))\n view = memoryview(self.mem)\n self._rom0 = view[0:16384]\n self._rom1 = view[16384:32768]\n self._vram = view[32768:40960]\n self._eram = view[40960:49152]\n self._wram = view[49152:57344]\n self._wram2 = view[57344:65024]\n self.OAM = view[65024:65184]\n self.IO = view[65280:65408]\n self._HiRAM = view[65408:65535]\n self.view = view\n self.mbc = mbc\n self.mbc.bank0 = self._rom0\n self.mbc.bank1 = self._rom1\n self.view[65024:65535] = bytearray([(0) for _ in range(511)])\n self.mem[65535] = 255\n self.link_buffer = 0\n self.serial_buff = ''\n self._io_handlers: Dict[int, Register] = {}\n self.add_io_handler(65350, HandlerProxy(self.dma))\n self.add_io_handler(65360, HandlerProxy(self.mbc.disable_bootrom))\n\n def dma(self, val: int) ->None:\n dest = 65024\n offset = val * 256\n for n in range(160):\n self.mem[dest + n] = self.mem[n + offset]\n\n def __getitem__(self, val: int) ->int:\n if val < 57344:\n return self.view[val]\n elif val < 65024:\n return self.view[val - 8192]\n elif val < 65152:\n return self.OAM[val - 65024]\n elif val < 65280:\n return 255\n elif val < 65408:\n if val in self._io_handlers:\n return self._io_handlers[val].value\n elif val == 65280:\n return self._ui.input\n else:\n return self.IO[val - 65280]\n elif val < 65535:\n return self._HiRAM[val - 65408]\n elif val == 65535:\n return self.mem[65535]\n raise ValueError('Access out of bounds')\n\n def __setitem__(self, key: int, val: int) ->None:\n if key < 32768:\n self.mbc[key] = val\n elif key < 40960:\n self._vram[key - 32768] = val\n elif key < 49152:\n if self.mbc.ram_enabled:\n self._eram[key - 40960] = val\n elif key < 57344:\n self._wram[key - 49152] = val\n elif key < 65024:\n self._wram[key - 57344] = val\n elif key < 65184:\n self.OAM[key - 65024] = val\n elif key < 65280:\n pass\n elif key < 65408:\n if key in self._io_handlers:\n self._io_handlers[key].value = val\n if key == 65280:\n self._ui.input = val\n elif key == 65281:\n self.link_buffer = val\n elif key == 65282:\n if val == 129:\n self.serial_buff += chr(self.link_buffer)\n if self.link_buffer == ord('\\n'):\n print(self.serial_buff, end='', file=sys.stderr)\n if self.serial_buff == 'Passed\\n':\n pass\n elif self.serial_buff == 'Failed\\n':\n pass\n self.serial_buff = ''\n else:\n self.IO[key - 65280] = val\n elif key < 65535:\n self._HiRAM[key - 65408] = val\n else:\n self.mem[65535] = val\n\n def add_io_handler(self, val: int, handler: Register) ->None:\n self._io_handlers[val] = handler\n", "step-3": "<mask token>\nIE = 65535\nDIV = 65284\nTIMA = 65285\nTMA = 65286\nTAC = 65287\nIF = 65295\nLY = 65348\n\n\nclass MMU:\n\n def __init__(self, interface: Interface, mbc: MBC) ->None:\n self._ui = interface\n self.mem = bytearray(random.getrandbits(8) for _ in range(65536))\n view = memoryview(self.mem)\n self._rom0 = view[0:16384]\n self._rom1 = view[16384:32768]\n self._vram = view[32768:40960]\n self._eram = view[40960:49152]\n self._wram = view[49152:57344]\n self._wram2 = view[57344:65024]\n self.OAM = view[65024:65184]\n self.IO = view[65280:65408]\n self._HiRAM = view[65408:65535]\n self.view = view\n self.mbc = mbc\n self.mbc.bank0 = self._rom0\n self.mbc.bank1 = self._rom1\n self.view[65024:65535] = bytearray([(0) for _ in range(511)])\n self.mem[65535] = 255\n self.link_buffer = 0\n self.serial_buff = ''\n self._io_handlers: Dict[int, Register] = {}\n self.add_io_handler(65350, HandlerProxy(self.dma))\n self.add_io_handler(65360, HandlerProxy(self.mbc.disable_bootrom))\n\n def dma(self, val: int) ->None:\n dest = 65024\n offset = val * 256\n for n in range(160):\n self.mem[dest + n] = self.mem[n + offset]\n\n def __getitem__(self, val: int) ->int:\n if val < 57344:\n return self.view[val]\n elif val < 65024:\n return self.view[val - 8192]\n elif val < 65152:\n return self.OAM[val - 65024]\n elif val < 65280:\n return 255\n elif val < 65408:\n if val in self._io_handlers:\n return self._io_handlers[val].value\n elif val == 65280:\n return self._ui.input\n else:\n return self.IO[val - 65280]\n elif val < 65535:\n return self._HiRAM[val - 65408]\n elif val == 65535:\n return self.mem[65535]\n raise ValueError('Access out of bounds')\n\n def __setitem__(self, key: int, val: int) ->None:\n if key < 32768:\n self.mbc[key] = val\n elif key < 40960:\n self._vram[key - 32768] = val\n elif key < 49152:\n if self.mbc.ram_enabled:\n self._eram[key - 40960] = val\n elif key < 57344:\n self._wram[key - 49152] = val\n elif key < 65024:\n self._wram[key - 57344] = val\n elif key < 65184:\n self.OAM[key - 65024] = val\n elif key < 65280:\n pass\n elif key < 65408:\n if key in self._io_handlers:\n self._io_handlers[key].value = val\n if key == 65280:\n self._ui.input = val\n elif key == 65281:\n self.link_buffer = val\n elif key == 65282:\n if val == 129:\n self.serial_buff += chr(self.link_buffer)\n if self.link_buffer == ord('\\n'):\n print(self.serial_buff, end='', file=sys.stderr)\n if self.serial_buff == 'Passed\\n':\n pass\n elif self.serial_buff == 'Failed\\n':\n pass\n self.serial_buff = ''\n else:\n self.IO[key - 65280] = val\n elif key < 65535:\n self._HiRAM[key - 65408] = val\n else:\n self.mem[65535] = val\n\n def add_io_handler(self, val: int, handler: Register) ->None:\n self._io_handlers[val] = handler\n", "step-4": "from mbc import MBC\nimport random\nimport sys\nfrom typing import Dict\nfrom interface import Interface\nfrom reg import Register, HandlerProxy\nIE = 65535\nDIV = 65284\nTIMA = 65285\nTMA = 65286\nTAC = 65287\nIF = 65295\nLY = 65348\n\n\nclass MMU:\n\n def __init__(self, interface: Interface, mbc: MBC) ->None:\n self._ui = interface\n self.mem = bytearray(random.getrandbits(8) for _ in range(65536))\n view = memoryview(self.mem)\n self._rom0 = view[0:16384]\n self._rom1 = view[16384:32768]\n self._vram = view[32768:40960]\n self._eram = view[40960:49152]\n self._wram = view[49152:57344]\n self._wram2 = view[57344:65024]\n self.OAM = view[65024:65184]\n self.IO = view[65280:65408]\n self._HiRAM = view[65408:65535]\n self.view = view\n self.mbc = mbc\n self.mbc.bank0 = self._rom0\n self.mbc.bank1 = self._rom1\n self.view[65024:65535] = bytearray([(0) for _ in range(511)])\n self.mem[65535] = 255\n self.link_buffer = 0\n self.serial_buff = ''\n self._io_handlers: Dict[int, Register] = {}\n self.add_io_handler(65350, HandlerProxy(self.dma))\n self.add_io_handler(65360, HandlerProxy(self.mbc.disable_bootrom))\n\n def dma(self, val: int) ->None:\n dest = 65024\n offset = val * 256\n for n in range(160):\n self.mem[dest + n] = self.mem[n + offset]\n\n def __getitem__(self, val: int) ->int:\n if val < 57344:\n return self.view[val]\n elif val < 65024:\n return self.view[val - 8192]\n elif val < 65152:\n return self.OAM[val - 65024]\n elif val < 65280:\n return 255\n elif val < 65408:\n if val in self._io_handlers:\n return self._io_handlers[val].value\n elif val == 65280:\n return self._ui.input\n else:\n return self.IO[val - 65280]\n elif val < 65535:\n return self._HiRAM[val - 65408]\n elif val == 65535:\n return self.mem[65535]\n raise ValueError('Access out of bounds')\n\n def __setitem__(self, key: int, val: int) ->None:\n if key < 32768:\n self.mbc[key] = val\n elif key < 40960:\n self._vram[key - 32768] = val\n elif key < 49152:\n if self.mbc.ram_enabled:\n self._eram[key - 40960] = val\n elif key < 57344:\n self._wram[key - 49152] = val\n elif key < 65024:\n self._wram[key - 57344] = val\n elif key < 65184:\n self.OAM[key - 65024] = val\n elif key < 65280:\n pass\n elif key < 65408:\n if key in self._io_handlers:\n self._io_handlers[key].value = val\n if key == 65280:\n self._ui.input = val\n elif key == 65281:\n self.link_buffer = val\n elif key == 65282:\n if val == 129:\n self.serial_buff += chr(self.link_buffer)\n if self.link_buffer == ord('\\n'):\n print(self.serial_buff, end='', file=sys.stderr)\n if self.serial_buff == 'Passed\\n':\n pass\n elif self.serial_buff == 'Failed\\n':\n pass\n self.serial_buff = ''\n else:\n self.IO[key - 65280] = val\n elif key < 65535:\n self._HiRAM[key - 65408] = val\n else:\n self.mem[65535] = val\n\n def add_io_handler(self, val: int, handler: Register) ->None:\n self._io_handlers[val] = handler\n", "step-5": "from mbc import MBC\nimport random\nimport sys\nfrom typing import Dict\n\nfrom interface import Interface\nfrom reg import Register, HandlerProxy\n\n# I/O Registers\nIE = 0xFFFF\nDIV = 0xFF04 \nTIMA= 0xFF05\nTMA = 0xFF06\nTAC = 0xFF07\nIF = 0xFF0F\nLY = 0xFF44\n\n\n\nclass MMU():\n\n #0000\t3FFF\t16KB ROM bank 00\tFrom cartridge, usually a fixed bank\n #4000\t7FFF\t16KB ROM Bank 01~NN\tFrom cartridge, switchable bank via MBC (if any)\n #8000\t9FFF\t8KB Video RAM (VRAM)\tOnly bank 0 in Non-CGB mode\n #Switchable bank 0/1 in CGB mode\n #\n #A000\tBFFF\t8KB External RAM\tIn cartridge, switchable bank if any\n #C000\tCFFF\t4KB Work RAM (WRAM) bank 0\t\n #D000\tDFFF\t4KB Work RAM (WRAM) bank 1~N\tOnly bank 1 in Non-CGB mode\n #Switchable bank 1~7 in CGB mode\n #\n #E000\tFDFF\tMirror of C000~DDFF (ECHO RAM)\tTypically not used\n #FE00\tFE9F\tSprite attribute table (OAM)\t\n #FEA0\tFEFF\tNot Usable\t\n #FF00\tFF7F\tI/O Registers\t\n #FF80\tFFFE\tHigh RAM (HRAM)\t\n #FFFF\tFFFF\tInterrupts Enable Register (IE)\n\n def __init__(self, interface:Interface, mbc:MBC) -> None:\n self._ui = interface\n\n self.mem = bytearray(random.getrandbits(8) for _ in range(65536)) # type: ignore # Randomise RAM\n view = memoryview(self.mem)\n self._rom0 = view[0:0x4000]\n self._rom1 = view[0x4000:0x8000]\n self._vram = view[0x8000:0xA000]\n self._eram = view[0xA000:0xC000]\n self._wram = view[0xC000:0xE000]\n self._wram2 = view[0xE000:0xFE00]\n self.OAM = view[0xFE00:0xFEA0]\n self.IO = view[0xFF00:0xFF80]\n self._HiRAM = view[0xFF80:0xFFFF]\n\n self.view = view\n self.mbc = mbc\n self.mbc.bank0 = self._rom0\n self.mbc.bank1 = self._rom1\n\n self.view[0xFE00:0xFFFF] = bytearray([0x00 for _ in range(0x1FF)]) # IO, etc defaults to blank\n self.mem[0xFFFF] = 0xFF # IE\n\n self.link_buffer = 0\n\n self.serial_buff = \"\"\n self._io_handlers:Dict[int, Register] = {}\n self.add_io_handler(0xFF46, HandlerProxy(self.dma))\n # Add bootrom disable handler\n self.add_io_handler(0xFF50, HandlerProxy(self.mbc.disable_bootrom))\n\n def dma(self, val:int) -> None:\n dest = 0xFE00\n offset = val * 0x100\n for n in range(0xA0):\n self.mem[dest + n] = self.mem[n + offset]\n\n def __getitem__(self, val:int) -> int:\n if val < 0xE000:\n return self.view[val]\n elif val < 0xFE00:\n # Echo RAM, subtract 0x2000\n return self.view[val-0x2000]\n elif val < 0xFE80:\n return self.OAM[val-0xFE00]\n elif val < 0xFF00:\n return 0xFF\n elif val < 0xFF80:\n if val in self._io_handlers:\n return self._io_handlers[val].value\n elif val == 0xFF00:\n return self._ui.input\n else:\n return self.IO[val-0xFF00]\n elif val < 0xFFFF:\n return self._HiRAM[val-0xFF80]\n elif val == 0xFFFF:\n return self.mem[0xFFFF]\n raise ValueError(\"Access out of bounds\")\n\n def __setitem__(self, key:int, val:int) -> None:\n if key < 0x8000:\n self.mbc[key] = val\n elif key < 0xA000:\n\t self._vram[key-0x8000] = val\n elif key < 0xC000:\n if self.mbc.ram_enabled:\n # TODO: Read $0x149 and determine RAM Size\n # TODO: Pass to MBC\n self._eram[key-0xA000] = val\n elif key < 0xE000:\n\t self._wram[key-0xC000] = val\n elif key < 0xFE00:\n\t self._wram[key-0xE000] = val\n elif key < 0xFEA0:\n\t self.OAM[key-0xFE00] = val\n elif key < 0xFF00:\n pass\n elif key < 0xFF80:\n if key in self._io_handlers:\n self._io_handlers[key].value = val\n if key == 0xFF00:\n self._ui.input = val\n elif key == 0xFF01:\n self.link_buffer = val\n elif key == 0xFF02:\n if val == 0x81:\n self.serial_buff += chr(self.link_buffer)\n if self.link_buffer == ord(\"\\n\"):\n print(self.serial_buff, end='', file=sys.stderr)\n # Test ROM Routines\n if self.serial_buff == \"Passed\\n\":\n #sys.exit(0)\n pass\n elif self.serial_buff == \"Failed\\n\":\n #sys.exit(1)\n pass\n self.serial_buff = \"\"\n else:\n self.IO[key-0xFF00] = val\n elif key < 0xFFFF:\n\t self._HiRAM[key-0xFF80] = val\n else:\n self.mem[65535] = val\n\n def add_io_handler(self, val:int, handler:Register) -> None:\n self._io_handlers[val] = handler\n", "step-ids": [ 4, 6, 7, 8, 9 ] }
[ 4, 6, 7, 8, 9 ]
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2016-12-19 15:25 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='OpenHumansMember', fields=[ ('oh_id', models.CharField(max_length=16, primary_key=True, serialize=False, unique=True)), ('access_token', models.CharField(max_length=256)), ('refresh_token', models.CharField(max_length=256)), ('token_expires', models.DateTimeField()), ('seeq_id', models.IntegerField(null=True)), ], ), ]
normal
{ "blob_id": "28854823b1edc7df6cf025175811c1858efd2c42", "index": 862, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n initial = True\n dependencies = []\n operations = [migrations.CreateModel(name='OpenHumansMember', fields=[(\n 'oh_id', models.CharField(max_length=16, primary_key=True,\n serialize=False, unique=True)), ('access_token', models.CharField(\n max_length=256)), ('refresh_token', models.CharField(max_length=256\n )), ('token_expires', models.DateTimeField()), ('seeq_id', models.\n IntegerField(null=True))])]\n", "step-4": "from __future__ import unicode_literals\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n initial = True\n dependencies = []\n operations = [migrations.CreateModel(name='OpenHumansMember', fields=[(\n 'oh_id', models.CharField(max_length=16, primary_key=True,\n serialize=False, unique=True)), ('access_token', models.CharField(\n max_length=256)), ('refresh_token', models.CharField(max_length=256\n )), ('token_expires', models.DateTimeField()), ('seeq_id', models.\n IntegerField(null=True))])]\n", "step-5": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10.4 on 2016-12-19 15:25\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='OpenHumansMember',\n fields=[\n ('oh_id', models.CharField(max_length=16, primary_key=True, serialize=False, unique=True)),\n ('access_token', models.CharField(max_length=256)),\n ('refresh_token', models.CharField(max_length=256)),\n ('token_expires', models.DateTimeField()),\n ('seeq_id', models.IntegerField(null=True)),\n ],\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]