Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Continue the code snippet: <|code_start|> self.fast = TssJsStarterThread(self.project)
self.fast.start()
self._wait_for_finish_and_notify_user()
def kill(self):
""" Trigger killing of adapter, tss.js and queue. """
Debug('tss+', "Killing tss.js process and adapter thread (for slow and fast lane) (Closing project %s)"
% self.project.tsconfigfile)
self.slow.kill_tssjs_queue_and_adapter()
self.fast.kill_tssjs_queue_and_adapter()
def _wait_for_finish_and_notify_user(self, i=1, dir=-1):
""" Displays animated Message as long as TSS is initing. Is recoursive function. """
if self.get_initialisation_error_message():
sublime.error_message('Typescript initializion error for : %s\n >>> %s\n ArcticTypescript is disabled until you restart sublime.'
% (self.project.tsconfigfile, self.get_initialisation_error_message()))
set_plugin_temporarily_disabled()
return
if not self.is_initialized():
(i, dir) = self._display_animated_init_message(i, dir)
# recursive:
sublime.set_timeout(lambda: self._wait_for_finish_and_notify_user(i, dir), 100)
else:
# starting finished ->
<|code_end|>
. Use current file imports:
from subprocess import Popen, PIPE
from threading import Thread
from queue import Queue, Empty
from Queue import Queue, Empty
from ..display.Message import MESSAGE
from ..utils import encode, Debug
from ..utils.pathutils import get_tss_path, find_tsconfigdir, default_node_path
from ..utils.osutils import get_kwargs
from ..utils.disabling import set_plugin_temporarily_disabled
import sublime
import os
import time
and context (classes, functions, or code) from other files:
# Path: lib/display/Message.py
# MESSAGE = Message()
#
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/utils.py
# def encode(message):
# return bytes(message,'UTF-8')
#
# Path: lib/utils/pathutils.py
# def get_tss_path():
# """ Return path to tss.js """
# return os.path.join(package_path, 'bin', 'tss.js')
#
# def find_tsconfigdir(rootdir):
# """ Returns the normalized dir, in which the tsconfig.json file is located"""
# rootdir = os.path.abspath(rootdir)
# try:
# if file_exists(os.path.join(rootdir, "tsconfig.json")):
# return os.path.normcase(rootdir)
# except FileNotFoundError:
# pass
#
# parentdir = os.path.abspath(os.path.join(rootdir, os.pardir))
# if parentdir == rootdir:
# return None
# else:
# return find_tsconfigdir(parentdir)
#
# def default_node_path(node_path, project=None):
# if node_path == 'none':
# Debug('notify', 'The setting node_path is set to "none". That is depreciated. Remove the setting.')
# node_path = None
#
# if node_path == "" or node_path is None:
# if sys.platform == "linux":
# return "nodejs"
# elif sys.platform == "nt":
# return "node"
# elif sys.platform == "darwin":
# return "/usr/local/bin/node"
# else:
# return "node"
# else:
# return expand_variables(node_path, project)
#
# Path: lib/utils/osutils.py
# def get_kwargs(stderr=True):
# if os.name == 'nt':
# startupinfo = subprocess.STARTUPINFO()
# startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
# if stderr:
# #errorlog = open(os.devnull, 'w')
# return {'stderr':subprocess.DEVNULL, 'startupinfo': startupinfo}
# return {'startupinfo': startupinfo}
# else:
# return {}
#
# Path: lib/utils/disabling.py
# def set_plugin_temporarily_disabled(folder=None):
# """ Enables the plugin globally or for folder.
# Folder can be a view """
# if folder is None:
# if not is_plugin_globally_disabled():
# plugin_disabled_for_folders.append("*global")
# else:
# if isinstance(folder, sublime.View):
# folder = os.path.dirname(folder.file_name())
# folder = os.path.normcase(folder)
# Debug('project', 'Disable ArcticTypescript for %s' % folder)
# if folder not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append(folder)
. Output only the next line. | MESSAGE.show('Typescript project intialized for file : %s' % self.project.tsconfigfile, True, with_panel=False) |
Predict the next line after this snippet: <|code_start|> Keeps two tss.js Processes and adapters for each project root.
Process SLOW is for slow commands like tss>errors which can last more than 5s easily.
Process FAST is for fast reacting commands eg. for autocompletion or type.
"""
def __init__(self, project):
""" starts the two processes """
self.project = project
self.slow = None
self.fast = None
self.start_tss_processes()
def is_initialized(self):
""" Returns True if both processes (SLOW and FAST) have been started. """
return self.slow.started and self.fast.started
def get_initialisation_error_message(self):
""" Returns Errormessage if initializing has failed, otherwise false"""
if self.slow.error:
return self.slow.error
if self.fast.error:
return self.fast.error
return False
def start_tss_processes(self):
"""
Start tss.js (2 times).
Displays message to user while starting and calls project.on_services_started() afterwards
"""
<|code_end|>
using the current file's imports:
from subprocess import Popen, PIPE
from threading import Thread
from queue import Queue, Empty
from Queue import Queue, Empty
from ..display.Message import MESSAGE
from ..utils import encode, Debug
from ..utils.pathutils import get_tss_path, find_tsconfigdir, default_node_path
from ..utils.osutils import get_kwargs
from ..utils.disabling import set_plugin_temporarily_disabled
import sublime
import os
import time
and any relevant context from other files:
# Path: lib/display/Message.py
# MESSAGE = Message()
#
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/utils.py
# def encode(message):
# return bytes(message,'UTF-8')
#
# Path: lib/utils/pathutils.py
# def get_tss_path():
# """ Return path to tss.js """
# return os.path.join(package_path, 'bin', 'tss.js')
#
# def find_tsconfigdir(rootdir):
# """ Returns the normalized dir, in which the tsconfig.json file is located"""
# rootdir = os.path.abspath(rootdir)
# try:
# if file_exists(os.path.join(rootdir, "tsconfig.json")):
# return os.path.normcase(rootdir)
# except FileNotFoundError:
# pass
#
# parentdir = os.path.abspath(os.path.join(rootdir, os.pardir))
# if parentdir == rootdir:
# return None
# else:
# return find_tsconfigdir(parentdir)
#
# def default_node_path(node_path, project=None):
# if node_path == 'none':
# Debug('notify', 'The setting node_path is set to "none". That is depreciated. Remove the setting.')
# node_path = None
#
# if node_path == "" or node_path is None:
# if sys.platform == "linux":
# return "nodejs"
# elif sys.platform == "nt":
# return "node"
# elif sys.platform == "darwin":
# return "/usr/local/bin/node"
# else:
# return "node"
# else:
# return expand_variables(node_path, project)
#
# Path: lib/utils/osutils.py
# def get_kwargs(stderr=True):
# if os.name == 'nt':
# startupinfo = subprocess.STARTUPINFO()
# startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
# if stderr:
# #errorlog = open(os.devnull, 'w')
# return {'stderr':subprocess.DEVNULL, 'startupinfo': startupinfo}
# return {'startupinfo': startupinfo}
# else:
# return {}
#
# Path: lib/utils/disabling.py
# def set_plugin_temporarily_disabled(folder=None):
# """ Enables the plugin globally or for folder.
# Folder can be a view """
# if folder is None:
# if not is_plugin_globally_disabled():
# plugin_disabled_for_folders.append("*global")
# else:
# if isinstance(folder, sublime.View):
# folder = os.path.dirname(folder.file_name())
# folder = os.path.normcase(folder)
# Debug('project', 'Disable ArcticTypescript for %s' % folder)
# if folder not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append(folder)
. Output only the next line. | Debug('notify', 'starting tsserver ' + self.project.tsconfigfile) |
Continue the code snippet: <|code_start|> """
commands_to_remove = []
for possible_duplicate in self.middleware_queue: # from old to new
if possible_duplicate.id == command.id:
commands_to_remove.append(possible_duplicate)
if len(commands_to_remove) > 0:
newest_command = commands_to_remove.pop() # don't delete newest duplicate command.
command.on_replaced(newest_command)
for c in commands_to_remove:
c.on_replaced(newest_command)
self.middleware_queue.remove(c)
Debug('adapter+', "MERGED with %i other commands (procrastinated): %s" % (len(commands_to_remove), command.id) )
return None # defer, no execution in this round
else:
return command # no defer, execute now, command has already been poped
def execute(self, async_command):
"""
Executes Command.
If debouncing enabled und timeout not finished, add back to the end of the queue.
This may cause unexpected behaviour but should be unnoticed mostly.
"""
if not async_command.can_be_executed_now():
self.append_to_middlewarequeue(async_command, set_timer=True) # reappend to end
Debug('adapter+', "MOVED to end of queue, debouncing")
return
async_command.time_execute = time.time()
try:
<|code_end|>
. Use current file imports:
from subprocess import Popen, PIPE
from threading import Thread
from queue import Queue, Empty
from Queue import Queue, Empty
from ..display.Message import MESSAGE
from ..utils import encode, Debug
from ..utils.pathutils import get_tss_path, find_tsconfigdir, default_node_path
from ..utils.osutils import get_kwargs
from ..utils.disabling import set_plugin_temporarily_disabled
import sublime
import os
import time
and context (classes, functions, or code) from other files:
# Path: lib/display/Message.py
# MESSAGE = Message()
#
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/utils.py
# def encode(message):
# return bytes(message,'UTF-8')
#
# Path: lib/utils/pathutils.py
# def get_tss_path():
# """ Return path to tss.js """
# return os.path.join(package_path, 'bin', 'tss.js')
#
# def find_tsconfigdir(rootdir):
# """ Returns the normalized dir, in which the tsconfig.json file is located"""
# rootdir = os.path.abspath(rootdir)
# try:
# if file_exists(os.path.join(rootdir, "tsconfig.json")):
# return os.path.normcase(rootdir)
# except FileNotFoundError:
# pass
#
# parentdir = os.path.abspath(os.path.join(rootdir, os.pardir))
# if parentdir == rootdir:
# return None
# else:
# return find_tsconfigdir(parentdir)
#
# def default_node_path(node_path, project=None):
# if node_path == 'none':
# Debug('notify', 'The setting node_path is set to "none". That is depreciated. Remove the setting.')
# node_path = None
#
# if node_path == "" or node_path is None:
# if sys.platform == "linux":
# return "nodejs"
# elif sys.platform == "nt":
# return "node"
# elif sys.platform == "darwin":
# return "/usr/local/bin/node"
# else:
# return "node"
# else:
# return expand_variables(node_path, project)
#
# Path: lib/utils/osutils.py
# def get_kwargs(stderr=True):
# if os.name == 'nt':
# startupinfo = subprocess.STARTUPINFO()
# startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
# if stderr:
# #errorlog = open(os.devnull, 'w')
# return {'stderr':subprocess.DEVNULL, 'startupinfo': startupinfo}
# return {'startupinfo': startupinfo}
# else:
# return {}
#
# Path: lib/utils/disabling.py
# def set_plugin_temporarily_disabled(folder=None):
# """ Enables the plugin globally or for folder.
# Folder can be a view """
# if folder is None:
# if not is_plugin_globally_disabled():
# plugin_disabled_for_folders.append("*global")
# else:
# if isinstance(folder, sublime.View):
# folder = os.path.dirname(folder.file_name())
# folder = os.path.normcase(folder)
# Debug('project', 'Disable ArcticTypescript for %s' % folder)
# if folder not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append(folder)
. Output only the next line. | self.stdin.write(encode(async_command.command)) |
Given the following code snippet before the placeholder: <|code_start|> "I have tried this path: %s" % node_path,
"Please install nodejs and/or set node_path in the project or plugin settings to the actual executable.",
"If you are on windows and just have installed node, you first need to logout and login again."])
return
except Exception as e:
self.error = "Unexpected Error while starting typescript-tools."
print(e)
return
first_out = self.tss_process.stdout.readline()
Debug('tss', 'FIRST TSS MESSAGE: %s' % first_out)
self.check_process_health()
self.tss_queue = Queue()
self.tss_adapter = TssAdapterThread(self.tss_process.stdin,
self.tss_process.stdout,
self.tss_queue,
self.check_process_health)
self.tss_adapter.daemon = True
self.tss_adapter.start()
self.started = True
def _make_commandline(self):
""" generates the commandline to start either tss.js or tsserver.js,
depending on the project settings """
node_path = default_node_path(self.project.get_setting('node_path'))
<|code_end|>
, predict the next line using imports from the current file:
from subprocess import Popen, PIPE
from threading import Thread
from queue import Queue, Empty
from Queue import Queue, Empty
from ..display.Message import MESSAGE
from ..utils import encode, Debug
from ..utils.pathutils import get_tss_path, find_tsconfigdir, default_node_path
from ..utils.osutils import get_kwargs
from ..utils.disabling import set_plugin_temporarily_disabled
import sublime
import os
import time
and context including class names, function names, and sometimes code from other files:
# Path: lib/display/Message.py
# MESSAGE = Message()
#
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/utils.py
# def encode(message):
# return bytes(message,'UTF-8')
#
# Path: lib/utils/pathutils.py
# def get_tss_path():
# """ Return path to tss.js """
# return os.path.join(package_path, 'bin', 'tss.js')
#
# def find_tsconfigdir(rootdir):
# """ Returns the normalized dir, in which the tsconfig.json file is located"""
# rootdir = os.path.abspath(rootdir)
# try:
# if file_exists(os.path.join(rootdir, "tsconfig.json")):
# return os.path.normcase(rootdir)
# except FileNotFoundError:
# pass
#
# parentdir = os.path.abspath(os.path.join(rootdir, os.pardir))
# if parentdir == rootdir:
# return None
# else:
# return find_tsconfigdir(parentdir)
#
# def default_node_path(node_path, project=None):
# if node_path == 'none':
# Debug('notify', 'The setting node_path is set to "none". That is depreciated. Remove the setting.')
# node_path = None
#
# if node_path == "" or node_path is None:
# if sys.platform == "linux":
# return "nodejs"
# elif sys.platform == "nt":
# return "node"
# elif sys.platform == "darwin":
# return "/usr/local/bin/node"
# else:
# return "node"
# else:
# return expand_variables(node_path, project)
#
# Path: lib/utils/osutils.py
# def get_kwargs(stderr=True):
# if os.name == 'nt':
# startupinfo = subprocess.STARTUPINFO()
# startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
# if stderr:
# #errorlog = open(os.devnull, 'w')
# return {'stderr':subprocess.DEVNULL, 'startupinfo': startupinfo}
# return {'startupinfo': startupinfo}
# else:
# return {}
#
# Path: lib/utils/disabling.py
# def set_plugin_temporarily_disabled(folder=None):
# """ Enables the plugin globally or for folder.
# Folder can be a view """
# if folder is None:
# if not is_plugin_globally_disabled():
# plugin_disabled_for_folders.append("*global")
# else:
# if isinstance(folder, sublime.View):
# folder = os.path.dirname(folder.file_name())
# folder = os.path.normcase(folder)
# Debug('project', 'Disable ArcticTypescript for %s' % folder)
# if folder not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append(folder)
. Output only the next line. | tss_path = get_tss_path() |
Using the snippet: <|code_start|> self.error = "\n".join(["Could not find nodejs.",
"I have tried this path: %s" % node_path,
"Please install nodejs and/or set node_path in the project or plugin settings to the actual executable.",
"If you are on windows and just have installed node, you first need to logout and login again."])
return
except Exception as e:
self.error = "Unexpected Error while starting typescript-tools."
print(e)
return
first_out = self.tss_process.stdout.readline()
Debug('tss', 'FIRST TSS MESSAGE: %s' % first_out)
self.check_process_health()
self.tss_queue = Queue()
self.tss_adapter = TssAdapterThread(self.tss_process.stdin,
self.tss_process.stdout,
self.tss_queue,
self.check_process_health)
self.tss_adapter.daemon = True
self.tss_adapter.start()
self.started = True
def _make_commandline(self):
""" generates the commandline to start either tss.js or tsserver.js,
depending on the project settings """
<|code_end|>
, determine the next line of code. You have imports:
from subprocess import Popen, PIPE
from threading import Thread
from queue import Queue, Empty
from Queue import Queue, Empty
from ..display.Message import MESSAGE
from ..utils import encode, Debug
from ..utils.pathutils import get_tss_path, find_tsconfigdir, default_node_path
from ..utils.osutils import get_kwargs
from ..utils.disabling import set_plugin_temporarily_disabled
import sublime
import os
import time
and context (class names, function names, or code) available:
# Path: lib/display/Message.py
# MESSAGE = Message()
#
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/utils.py
# def encode(message):
# return bytes(message,'UTF-8')
#
# Path: lib/utils/pathutils.py
# def get_tss_path():
# """ Return path to tss.js """
# return os.path.join(package_path, 'bin', 'tss.js')
#
# def find_tsconfigdir(rootdir):
# """ Returns the normalized dir, in which the tsconfig.json file is located"""
# rootdir = os.path.abspath(rootdir)
# try:
# if file_exists(os.path.join(rootdir, "tsconfig.json")):
# return os.path.normcase(rootdir)
# except FileNotFoundError:
# pass
#
# parentdir = os.path.abspath(os.path.join(rootdir, os.pardir))
# if parentdir == rootdir:
# return None
# else:
# return find_tsconfigdir(parentdir)
#
# def default_node_path(node_path, project=None):
# if node_path == 'none':
# Debug('notify', 'The setting node_path is set to "none". That is depreciated. Remove the setting.')
# node_path = None
#
# if node_path == "" or node_path is None:
# if sys.platform == "linux":
# return "nodejs"
# elif sys.platform == "nt":
# return "node"
# elif sys.platform == "darwin":
# return "/usr/local/bin/node"
# else:
# return "node"
# else:
# return expand_variables(node_path, project)
#
# Path: lib/utils/osutils.py
# def get_kwargs(stderr=True):
# if os.name == 'nt':
# startupinfo = subprocess.STARTUPINFO()
# startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
# if stderr:
# #errorlog = open(os.devnull, 'w')
# return {'stderr':subprocess.DEVNULL, 'startupinfo': startupinfo}
# return {'startupinfo': startupinfo}
# else:
# return {}
#
# Path: lib/utils/disabling.py
# def set_plugin_temporarily_disabled(folder=None):
# """ Enables the plugin globally or for folder.
# Folder can be a view """
# if folder is None:
# if not is_plugin_globally_disabled():
# plugin_disabled_for_folders.append("*global")
# else:
# if isinstance(folder, sublime.View):
# folder = os.path.dirname(folder.file_name())
# folder = os.path.normcase(folder)
# Debug('project', 'Disable ArcticTypescript for %s' % folder)
# if folder not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append(folder)
. Output only the next line. | node_path = default_node_path(self.project.get_setting('node_path')) |
Here is a snippet: <|code_start|>
return (i, dir)
# ----------------------------------------- THREAD: (tss.js and adapter starter) ------------------------ #
class TssJsStarterThread(Thread):
"""
After starting, this class provides the methods and fields
* send_async_command(...)
* kill_tssjs_queue_and_adapter()
* started
for communication with the started Adapter and therewith the tss.js script.
tss.js from: https://github.com/clausreinke/typescript-tools
"""
def __init__(self, project):
""" init for project <project> """
self.project = project
self.started = False
self.error = False
Thread.__init__(self)
def run(self):
"""
Starts the tss.js typescript services server process and the adapter thread.
"""
node_path, cwd, cmdline = self._make_commandline()
<|code_end|>
. Write the next line using the current file imports:
from subprocess import Popen, PIPE
from threading import Thread
from queue import Queue, Empty
from Queue import Queue, Empty
from ..display.Message import MESSAGE
from ..utils import encode, Debug
from ..utils.pathutils import get_tss_path, find_tsconfigdir, default_node_path
from ..utils.osutils import get_kwargs
from ..utils.disabling import set_plugin_temporarily_disabled
import sublime
import os
import time
and context from other files:
# Path: lib/display/Message.py
# MESSAGE = Message()
#
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/utils.py
# def encode(message):
# return bytes(message,'UTF-8')
#
# Path: lib/utils/pathutils.py
# def get_tss_path():
# """ Return path to tss.js """
# return os.path.join(package_path, 'bin', 'tss.js')
#
# def find_tsconfigdir(rootdir):
# """ Returns the normalized dir, in which the tsconfig.json file is located"""
# rootdir = os.path.abspath(rootdir)
# try:
# if file_exists(os.path.join(rootdir, "tsconfig.json")):
# return os.path.normcase(rootdir)
# except FileNotFoundError:
# pass
#
# parentdir = os.path.abspath(os.path.join(rootdir, os.pardir))
# if parentdir == rootdir:
# return None
# else:
# return find_tsconfigdir(parentdir)
#
# def default_node_path(node_path, project=None):
# if node_path == 'none':
# Debug('notify', 'The setting node_path is set to "none". That is depreciated. Remove the setting.')
# node_path = None
#
# if node_path == "" or node_path is None:
# if sys.platform == "linux":
# return "nodejs"
# elif sys.platform == "nt":
# return "node"
# elif sys.platform == "darwin":
# return "/usr/local/bin/node"
# else:
# return "node"
# else:
# return expand_variables(node_path, project)
#
# Path: lib/utils/osutils.py
# def get_kwargs(stderr=True):
# if os.name == 'nt':
# startupinfo = subprocess.STARTUPINFO()
# startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
# if stderr:
# #errorlog = open(os.devnull, 'w')
# return {'stderr':subprocess.DEVNULL, 'startupinfo': startupinfo}
# return {'startupinfo': startupinfo}
# else:
# return {}
#
# Path: lib/utils/disabling.py
# def set_plugin_temporarily_disabled(folder=None):
# """ Enables the plugin globally or for folder.
# Folder can be a view """
# if folder is None:
# if not is_plugin_globally_disabled():
# plugin_disabled_for_folders.append("*global")
# else:
# if isinstance(folder, sublime.View):
# folder = os.path.dirname(folder.file_name())
# folder = os.path.normcase(folder)
# Debug('project', 'Disable ArcticTypescript for %s' % folder)
# if folder not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append(folder)
, which may include functions, classes, or code. Output only the next line. | kwargs = get_kwargs(stderr=False) |
Given the code snippet: <|code_start|> def start_tss_processes(self):
"""
Start tss.js (2 times).
Displays message to user while starting and calls project.on_services_started() afterwards
"""
Debug('notify', 'starting tsserver ' + self.project.tsconfigfile)
self.slow = TssJsStarterThread(self.project)
self.slow.start()
self.fast = TssJsStarterThread(self.project)
self.fast.start()
self._wait_for_finish_and_notify_user()
def kill(self):
""" Trigger killing of adapter, tss.js and queue. """
Debug('tss+', "Killing tss.js process and adapter thread (for slow and fast lane) (Closing project %s)"
% self.project.tsconfigfile)
self.slow.kill_tssjs_queue_and_adapter()
self.fast.kill_tssjs_queue_and_adapter()
def _wait_for_finish_and_notify_user(self, i=1, dir=-1):
""" Displays animated Message as long as TSS is initing. Is recoursive function. """
if self.get_initialisation_error_message():
sublime.error_message('Typescript initializion error for : %s\n >>> %s\n ArcticTypescript is disabled until you restart sublime.'
% (self.project.tsconfigfile, self.get_initialisation_error_message()))
<|code_end|>
, generate the next line using the imports in this file:
from subprocess import Popen, PIPE
from threading import Thread
from queue import Queue, Empty
from Queue import Queue, Empty
from ..display.Message import MESSAGE
from ..utils import encode, Debug
from ..utils.pathutils import get_tss_path, find_tsconfigdir, default_node_path
from ..utils.osutils import get_kwargs
from ..utils.disabling import set_plugin_temporarily_disabled
import sublime
import os
import time
and context (functions, classes, or occasionally code) from other files:
# Path: lib/display/Message.py
# MESSAGE = Message()
#
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/utils.py
# def encode(message):
# return bytes(message,'UTF-8')
#
# Path: lib/utils/pathutils.py
# def get_tss_path():
# """ Return path to tss.js """
# return os.path.join(package_path, 'bin', 'tss.js')
#
# def find_tsconfigdir(rootdir):
# """ Returns the normalized dir, in which the tsconfig.json file is located"""
# rootdir = os.path.abspath(rootdir)
# try:
# if file_exists(os.path.join(rootdir, "tsconfig.json")):
# return os.path.normcase(rootdir)
# except FileNotFoundError:
# pass
#
# parentdir = os.path.abspath(os.path.join(rootdir, os.pardir))
# if parentdir == rootdir:
# return None
# else:
# return find_tsconfigdir(parentdir)
#
# def default_node_path(node_path, project=None):
# if node_path == 'none':
# Debug('notify', 'The setting node_path is set to "none". That is depreciated. Remove the setting.')
# node_path = None
#
# if node_path == "" or node_path is None:
# if sys.platform == "linux":
# return "nodejs"
# elif sys.platform == "nt":
# return "node"
# elif sys.platform == "darwin":
# return "/usr/local/bin/node"
# else:
# return "node"
# else:
# return expand_variables(node_path, project)
#
# Path: lib/utils/osutils.py
# def get_kwargs(stderr=True):
# if os.name == 'nt':
# startupinfo = subprocess.STARTUPINFO()
# startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
# if stderr:
# #errorlog = open(os.devnull, 'w')
# return {'stderr':subprocess.DEVNULL, 'startupinfo': startupinfo}
# return {'startupinfo': startupinfo}
# else:
# return {}
#
# Path: lib/utils/disabling.py
# def set_plugin_temporarily_disabled(folder=None):
# """ Enables the plugin globally or for folder.
# Folder can be a view """
# if folder is None:
# if not is_plugin_globally_disabled():
# plugin_disabled_for_folders.append("*global")
# else:
# if isinstance(folder, sublime.View):
# folder = os.path.dirname(folder.file_name())
# folder = os.path.normcase(folder)
# Debug('project', 'Disable ArcticTypescript for %s' % folder)
# if folder not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append(folder)
. Output only the next line. | set_plugin_temporarily_disabled() |
Predict the next line for this snippet: <|code_start|> return False
return line_text.endswith(".") or partial_completion()
def get_col_after_last_dot(line_text):
return line_text.rfind(".") + 1
class Completion(object):
completion_chars = ['.']#['.',':']
completion_list = []
interface = False
enabled_for_col_reference = '' # 'dot' or 'cursor'
enabled_for = {'line': 0, 'col': 0, 'viewid': -1}
def __init__(self, project):
self.project = project
# PREPARE LISTE
def prepare_list(self, tss_result_json):
del self.completion_list[:]
try:
entries = json.loads(tss_result_json)
entries = entries['entries']
except:
if tss_result_json.strip() == 'null':
sublime.status_message('ArcticTypescript: no completions available')
else:
<|code_end|>
with the help of current file imports:
import re
import json
import sublime
from ..utils import Debug
from ..utils.uiutils import get_prefix
from ..utils.viewutils import get_file_infos, get_content_of_line_at
and context from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/uiutils.py
# def get_prefix(token):
# if token in PREFIXES:
# return PREFIXES[token]
# else:
# return ''
#
# Path: lib/utils/viewutils.py
# def get_file_infos(view):
# return (view.file_name(), get_lines(view), get_content(view))
#
# def get_content_of_line_at(view, pos):
# return view.substr(sublime.Region(view.line(pos-1).a, pos))
, which may contain function names, class names, or code. Output only the next line. | Debug('error', 'Completion request failed: %s' % tss_result_json) |
Given the following code snippet before the placeholder: <|code_start|> return
Debug('autocomplete', " -> command to sublime to now show autocomplete box with prepared list" )
# this will trigger Listener.on_query_completions
# but on_query_completions needs to have the completion list
# already available
current_view.run_command('auto_complete',{
'disable_auto_insert': True,
'api_completions_only': True,
'next_completion_if_showing': True
})
Debug('autocomplete', " -> (sublime cmd finished)" )
self.project.tsserver.complete(view.file_name(), cursor_line, autocomplete_col, is_member_str, async_react_completions_available)
# ENTRY KEY
def _get_list_key(self,entry):
#{'name': 'SVGLineElement',
# 'kind': 'var',
# 'kindModifiers': 'declare',
# 'type': 'interface SVGLineElement\nvar SVGLineElement: {\n new (): SVGLineElement;\n prototype: SVGLineElement;\n}',
# 'docComment': ''}
<|code_end|>
, predict the next line using imports from the current file:
import re
import json
import sublime
from ..utils import Debug
from ..utils.uiutils import get_prefix
from ..utils.viewutils import get_file_infos, get_content_of_line_at
and context including class names, function names, and sometimes code from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/uiutils.py
# def get_prefix(token):
# if token in PREFIXES:
# return PREFIXES[token]
# else:
# return ''
#
# Path: lib/utils/viewutils.py
# def get_file_infos(view):
# return (view.file_name(), get_lines(view), get_content(view))
#
# def get_content_of_line_at(view, pos):
# return view.substr(sublime.Region(view.line(pos-1).a, pos))
. Output only the next line. | kindModifiers = get_prefix(entry['kindModifiers']) |
Based on the snippet: <|code_start|> for entry in entries:
if self.interface and entry['kind'] != 'primitive type' and entry['kind'] != 'interface' : continue
key = self._get_list_key(entry)
value = self._get_list_value(entry)
self.completion_list.append((key,value))
self.completion_list.sort()
return len(self.completion_list)
# GET LISTE
def get_list(self):
return self.completion_list
# TYPESCRIPT COMPLETION ?
def trigger(self, view, force_enable=False):
cursor_pos = view.sel()[0].begin() # cursor pos as int
(cursor_line, cursor_col) = view.rowcol(cursor_pos)
char = view.substr(cursor_pos-1)
enabled = force_enable or (char in self.completion_chars)
self.interface = char is ':'
if enabled:
Debug('autocomplete', "Autocompletion for line %i , %i, forced=%s" % (cursor_line+1, cursor_col+1, force_enable) )
<|code_end|>
, predict the immediate next line with the help of imports:
import re
import json
import sublime
from ..utils import Debug
from ..utils.uiutils import get_prefix
from ..utils.viewutils import get_file_infos, get_content_of_line_at
and context (classes, functions, sometimes code) from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/uiutils.py
# def get_prefix(token):
# if token in PREFIXES:
# return PREFIXES[token]
# else:
# return ''
#
# Path: lib/utils/viewutils.py
# def get_file_infos(view):
# return (view.file_name(), get_lines(view), get_content(view))
#
# def get_content_of_line_at(view, pos):
# return view.substr(sublime.Region(view.line(pos-1).a, pos))
. Output only the next line. | is_member = is_member_completion( get_content_of_line_at(view, cursor_pos) ) |
Based on the snippet: <|code_start|> previous_file = filename
text.append("\n%i >" % e['start']['line'])
text.append(re.sub(r'^.*?:\s*', '', e['text'].replace('\r','')))
line += 1
a = (e['start']['line']-1, e['start']['character']-1)
b = (e['end']['line']-1, e['end']['character']-1)
line_to_pos[line] = (a,b)
line_to_file[line] = e['file']
if len(errors) == 0:
text.append("\n\nno errors")
text.append('\n')
text = ''.join(text)
return text, line_to_file, line_to_pos
def tssjs_to_highlighter(self, errors, file_name):
"""
Creates a list of error and warning regions for all errors.
Returns error_regions, warning_regions
"""
error_regions = []
warning_regions = []
<|code_end|>
, predict the immediate next line with the help of imports:
import re
from ..utils.fileutils import fn2k
and context (classes, functions, sometimes code) from other files:
# Path: lib/utils/fileutils.py
# def fn2k(filename):
# """ shortcut for filename2key """
# return filename2key(filename)
. Output only the next line. | key = fn2k(file_name) |
Predict the next line after this snippet: <|code_start|>
#{'lineText': ' let total = 0;',
# 'file': '/home/daniel/.config/sublime-text-3/Packages/ArcticTypescript/tests/TDDTesting/main.ts',
# 'min': {'character': 13,
# 'line': 43},
# 'lim': {'character': 18,
# 'line': 43},
# 'ref': {'textSpan': {'start': 760,
# 'length': 5},
# 'fileName': '/home/daniel/.config/sublime-text-3/Packages/ArcticTypescript/tests/TDDTesting/main.ts',
# 'isWriteAccess': True}}
class Refactor():
def __init__(self, edit, project, refs, old_name, new_name):
Thread.__init__(self)
self.project = project
self.refs = {r['ref'] for r in refs}
self.old_name = old_name
self.new_name = new_name
self.edit_token = edit_token
def start(self):
self.run()
def run(self):
self.sort_by_file()
<|code_end|>
using the current file's imports:
from threading import Thread
from ..utils import Debug
from ..utils.fileutils import read_file, file_exists, fn2k
import sublime
import os
and any relevant context from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/fileutils.py
# def read_file(filename):
# """ returns None or file contents if available """
# filename = os.path.normcase(filename) # back to \\ in nt
# if os.path.isfile(filename):
# try:
# if os.name == 'nt':
# return open(filename, 'r', encoding='utf8').read()
# else:
# return codecs.open(filename, 'r', 'utf-8').read()
# except IOError:
# pass
# return None
#
# def file_exists(filename):
# """ returns weather the file exists """
# return os.path.isfile(os.path.normcase(filename))
#
# def fn2k(filename):
# """ shortcut for filename2key """
# return filename2key(filename)
. Output only the next line. | Debug('refactor', self.refs_by_file) |
Based on the snippet: <|code_start|>
class Refactor():
def __init__(self, edit, project, refs, old_name, new_name):
Thread.__init__(self)
self.project = project
self.refs = {r['ref'] for r in refs}
self.old_name = old_name
self.new_name = new_name
self.edit_token = edit_token
def start(self):
self.run()
def run(self):
self.sort_by_file()
Debug('refactor', self.refs_by_file)
for (file_, refs_in) in self.refs_by_file.values():
self.refactor_file(file_, refs_in)
def sort_by_file(self):
""" sort references by file """
self.refs_by_file = {} # key is the fn2k'ed filename
for ref in self.refs:
<|code_end|>
, predict the immediate next line with the help of imports:
from threading import Thread
from ..utils import Debug
from ..utils.fileutils import read_file, file_exists, fn2k
import sublime
import os
and context (classes, functions, sometimes code) from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/fileutils.py
# def read_file(filename):
# """ returns None or file contents if available """
# filename = os.path.normcase(filename) # back to \\ in nt
# if os.path.isfile(filename):
# try:
# if os.name == 'nt':
# return open(filename, 'r', encoding='utf8').read()
# else:
# return codecs.open(filename, 'r', 'utf-8').read()
# except IOError:
# pass
# return None
#
# def file_exists(filename):
# """ returns weather the file exists """
# return os.path.isfile(os.path.normcase(filename))
#
# def fn2k(filename):
# """ shortcut for filename2key """
# return filename2key(filename)
. Output only the next line. | file_ = fn2k(ref['file']) |
Based on the snippet: <|code_start|># coding=utf8
# delete code taken from sublime origami : https://github.com/SublimeText/Origami
XMIN, YMIN, XMAX, YMAX = list(range(4))
class Layout(object):
# CONSTRUCTEUR
def __init__(self):
super(Layout, self).__init__()
# UPDATE
@max_calls(name='Layout.update')
def update(self,window,group):
<|code_end|>
, predict the immediate next line with the help of imports:
import sublime
from ..utils import max_calls, Debug
and context (classes, functions, sometimes code) from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# def max_calls(limit = 1500, name=""):
# """Decorator which allows its wrapped function to be called `limit` times"""
# def decorator(func):
# # Disable limit:
# return func
# @wraps(func)
# def wrapper(*args, **kwargs):
# calls = getattr(wrapper, 'calls', 0)
# calls += 1
# setattr(wrapper, 'calls', calls)
# fname = name if name != "" else func.__name__
#
# if calls == limit + 1:
# Debug('max_calls', "LIMIT !! ## !!: Fkt %s has %i calls, stop" % (fname, calls - 1))
#
# if calls >= limit + 1:
# return None
#
# Debug('max_calls', "CALL: Fkt %s has %i calls -> +1" % (fname, calls - 1))
#
# return func(*args, **kwargs)
# setattr(wrapper, 'calls', 0)
# return wrapper
# return decorator
. Output only the next line. | Debug('layout', 'UPDATE: group: %i' % group) |
Using the snippet: <|code_start|># coding=utf8
# delete code taken from sublime origami : https://github.com/SublimeText/Origami
XMIN, YMIN, XMAX, YMAX = list(range(4))
class Layout(object):
# CONSTRUCTEUR
def __init__(self):
super(Layout, self).__init__()
# UPDATE
<|code_end|>
, determine the next line of code. You have imports:
import sublime
from ..utils import max_calls, Debug
and context (class names, function names, or code) available:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# def max_calls(limit = 1500, name=""):
# """Decorator which allows its wrapped function to be called `limit` times"""
# def decorator(func):
# # Disable limit:
# return func
# @wraps(func)
# def wrapper(*args, **kwargs):
# calls = getattr(wrapper, 'calls', 0)
# calls += 1
# setattr(wrapper, 'calls', calls)
# fname = name if name != "" else func.__name__
#
# if calls == limit + 1:
# Debug('max_calls', "LIMIT !! ## !!: Fkt %s has %i calls, stop" % (fname, calls - 1))
#
# if calls >= limit + 1:
# return None
#
# Debug('max_calls', "CALL: Fkt %s has %i calls -> +1" % (fname, calls - 1))
#
# return func(*args, **kwargs)
# setattr(wrapper, 'calls', 0)
# return wrapper
# return decorator
. Output only the next line. | @max_calls(name='Layout.update') |
Here is a snippet: <|code_start|># coding=utf8
class TsconfigEventListener(sublime_plugin.EventListener):
""" Listen to file events -> Activate TsconfigLinter.
check_tsconfig immediately returns if file is no tsconfig.json """
def on_activated_async(self, view):
<|code_end|>
. Write the next line using the current file imports:
import sublime
import sublime_plugin
import os
from .TsconfigLinter import check_tsconfig, show_lint_in_status
from .tsconfigglobexpand import expand_filesglob
from ..utils.CancelCommand import catch_CancelCommand, CancelCommand
from ..system.Project import opened_project_by_tsconfig
and context from other files:
# Path: lib/tsconfiglint/TsconfigLinter.py
# @catch_CancelCommand
# def check_tsconfig(view):
# """ Tests view for being a tsconfig.json.
# Reads the tsconfig.json and checks for errors.
# Show Errors using Regions.
# Set a error map [<(a,b), msg>] into views settings. """
#
# if not _is_valid_and_enabled(view):
# return
#
# Debug('tsconfig', 'tsconfig modified, check')
#
# linter = TsconfigLinter(view)
#
# return linter
#
# def show_lint_in_status(view):
# """ Uses the error map stored in view.settings() to display
# status messages if the cursor is above an error """
#
# if not _is_valid_and_enabled(view):
# return
#
# if view.settings().has('tsconfig-lints'):
# error_locations = view.settings().get('tsconfig-lints', [])
#
# current_errors = []
# current_selection = view.sel()[0]
#
# for pos, error in error_locations:
# error_region = sublime.Region(pos[0], pos[1])
# if current_selection.intersects(error_region):
# current_errors.append(error)
#
# if len(current_errors):
# view.set_status('tsconfig-errors', ' | '.join(current_errors))
# else:
# view.erase_status('tsconfig-errors')
#
# Path: lib/tsconfiglint/tsconfigglobexpand.py
# def expand_filesglob(linter):
# """
# This mimics the filesGlob behaviour of atom-typescript [2]
# If tsconfig.json has no HardErrors, it executes bin/expandglob.js
# and reloads linter.view from disk.
# This operates on the file contents, so the file should have been saved
# before.
# Returns immediately if not linted or linter is None
# Returns True if the filesGlob has been expanded
# Returns False if there was a linter error, so no expansion has been done
# """
#
# # Expanding?
#
# if is_tsglobexpansion_disabled():
# return False
#
# if linter is None or not linter or not linter.linted:
# return False
#
# if len(linter.harderrors) > 0:
# return False
#
# if len(linter.softerrors) != linter.numerrors:
# return False
#
# if linter.content == "":
# return False
#
# if "filesGlob" not in linter.tsconfig:
# return True # Should reopen project, so return True here
#
# # Expand!
# project_dir = os.path.dirname(linter.view.file_name())
# file_list = _expand_globs_with_javascript(project_dir, linter)
# Debug("tsconfig.json", "fileGlobs expaned")
#
# # reload file
# linter.view.run_command("revert")
#
# # lint again, so the soft errors are still displayed
# check_tsconfig(linter.view)
#
# return True
#
# Path: lib/utils/CancelCommand.py
# def catch_CancelCommand(func):
# """ Decorate every command with this one. It will check for
# the plugin disabled flag and catch CancelCommand exceptins. """
#
# def catcher(*kargs, **kwargs):
# if is_plugin_temporarily_disabled():
# return # do not execute command
# try:
# return func(*kargs, **kwargs)
# except CancelCommand:
# Debug('command', "A COMMAND WAS CANCELED")
# return False
# return catcher
#
# class CancelCommand(Exception):
# """ Throw this exception in a command. The decorator
# catch_CancelCommand will catch it and cancel silently """
# pass
#
# Path: lib/system/Project.py
# def opened_project_by_tsconfig(tsconfigfile):
# if not tsconfigfile:
# return None
# tsconfigfile = os.path.normcase(tsconfigfile)
# for p in OPENED_PROJECTS.values():
# if os.path.normcase(p.tsconfigfile) == tsconfigfile:
# return p
# return None
, which may include functions, classes, or code. Output only the next line. | check_tsconfig(view) |
Predict the next line after this snippet: <|code_start|> """ Listen to file events -> Activate TsconfigLinter.
check_tsconfig immediately returns if file is no tsconfig.json """
def on_activated_async(self, view):
check_tsconfig(view)
def on_load_async(self, view):
check_tsconfig(view)
def on_modified(self, view):
check_tsconfig(view)
def on_clone_async(self, view):
check_tsconfig(view)
@catch_CancelCommand
def on_post_save_async(self, view):
linter = check_tsconfig(view)
linting_succeeded = expand_filesglob(linter)
if linting_succeeded:
project = opened_project_by_tsconfig(linter.file_name)
if project:
project.reopen_project()
def on_selection_modified_async(self, view):
<|code_end|>
using the current file's imports:
import sublime
import sublime_plugin
import os
from .TsconfigLinter import check_tsconfig, show_lint_in_status
from .tsconfigglobexpand import expand_filesglob
from ..utils.CancelCommand import catch_CancelCommand, CancelCommand
from ..system.Project import opened_project_by_tsconfig
and any relevant context from other files:
# Path: lib/tsconfiglint/TsconfigLinter.py
# @catch_CancelCommand
# def check_tsconfig(view):
# """ Tests view for being a tsconfig.json.
# Reads the tsconfig.json and checks for errors.
# Show Errors using Regions.
# Set a error map [<(a,b), msg>] into views settings. """
#
# if not _is_valid_and_enabled(view):
# return
#
# Debug('tsconfig', 'tsconfig modified, check')
#
# linter = TsconfigLinter(view)
#
# return linter
#
# def show_lint_in_status(view):
# """ Uses the error map stored in view.settings() to display
# status messages if the cursor is above an error """
#
# if not _is_valid_and_enabled(view):
# return
#
# if view.settings().has('tsconfig-lints'):
# error_locations = view.settings().get('tsconfig-lints', [])
#
# current_errors = []
# current_selection = view.sel()[0]
#
# for pos, error in error_locations:
# error_region = sublime.Region(pos[0], pos[1])
# if current_selection.intersects(error_region):
# current_errors.append(error)
#
# if len(current_errors):
# view.set_status('tsconfig-errors', ' | '.join(current_errors))
# else:
# view.erase_status('tsconfig-errors')
#
# Path: lib/tsconfiglint/tsconfigglobexpand.py
# def expand_filesglob(linter):
# """
# This mimics the filesGlob behaviour of atom-typescript [2]
# If tsconfig.json has no HardErrors, it executes bin/expandglob.js
# and reloads linter.view from disk.
# This operates on the file contents, so the file should have been saved
# before.
# Returns immediately if not linted or linter is None
# Returns True if the filesGlob has been expanded
# Returns False if there was a linter error, so no expansion has been done
# """
#
# # Expanding?
#
# if is_tsglobexpansion_disabled():
# return False
#
# if linter is None or not linter or not linter.linted:
# return False
#
# if len(linter.harderrors) > 0:
# return False
#
# if len(linter.softerrors) != linter.numerrors:
# return False
#
# if linter.content == "":
# return False
#
# if "filesGlob" not in linter.tsconfig:
# return True # Should reopen project, so return True here
#
# # Expand!
# project_dir = os.path.dirname(linter.view.file_name())
# file_list = _expand_globs_with_javascript(project_dir, linter)
# Debug("tsconfig.json", "fileGlobs expaned")
#
# # reload file
# linter.view.run_command("revert")
#
# # lint again, so the soft errors are still displayed
# check_tsconfig(linter.view)
#
# return True
#
# Path: lib/utils/CancelCommand.py
# def catch_CancelCommand(func):
# """ Decorate every command with this one. It will check for
# the plugin disabled flag and catch CancelCommand exceptins. """
#
# def catcher(*kargs, **kwargs):
# if is_plugin_temporarily_disabled():
# return # do not execute command
# try:
# return func(*kargs, **kwargs)
# except CancelCommand:
# Debug('command', "A COMMAND WAS CANCELED")
# return False
# return catcher
#
# class CancelCommand(Exception):
# """ Throw this exception in a command. The decorator
# catch_CancelCommand will catch it and cancel silently """
# pass
#
# Path: lib/system/Project.py
# def opened_project_by_tsconfig(tsconfigfile):
# if not tsconfigfile:
# return None
# tsconfigfile = os.path.normcase(tsconfigfile)
# for p in OPENED_PROJECTS.values():
# if os.path.normcase(p.tsconfigfile) == tsconfigfile:
# return p
# return None
. Output only the next line. | show_lint_in_status(view) |
Continue the code snippet: <|code_start|># coding=utf8
class TsconfigEventListener(sublime_plugin.EventListener):
""" Listen to file events -> Activate TsconfigLinter.
check_tsconfig immediately returns if file is no tsconfig.json """
def on_activated_async(self, view):
check_tsconfig(view)
def on_load_async(self, view):
check_tsconfig(view)
def on_modified(self, view):
check_tsconfig(view)
def on_clone_async(self, view):
check_tsconfig(view)
@catch_CancelCommand
def on_post_save_async(self, view):
linter = check_tsconfig(view)
<|code_end|>
. Use current file imports:
import sublime
import sublime_plugin
import os
from .TsconfigLinter import check_tsconfig, show_lint_in_status
from .tsconfigglobexpand import expand_filesglob
from ..utils.CancelCommand import catch_CancelCommand, CancelCommand
from ..system.Project import opened_project_by_tsconfig
and context (classes, functions, or code) from other files:
# Path: lib/tsconfiglint/TsconfigLinter.py
# @catch_CancelCommand
# def check_tsconfig(view):
# """ Tests view for being a tsconfig.json.
# Reads the tsconfig.json and checks for errors.
# Show Errors using Regions.
# Set a error map [<(a,b), msg>] into views settings. """
#
# if not _is_valid_and_enabled(view):
# return
#
# Debug('tsconfig', 'tsconfig modified, check')
#
# linter = TsconfigLinter(view)
#
# return linter
#
# def show_lint_in_status(view):
# """ Uses the error map stored in view.settings() to display
# status messages if the cursor is above an error """
#
# if not _is_valid_and_enabled(view):
# return
#
# if view.settings().has('tsconfig-lints'):
# error_locations = view.settings().get('tsconfig-lints', [])
#
# current_errors = []
# current_selection = view.sel()[0]
#
# for pos, error in error_locations:
# error_region = sublime.Region(pos[0], pos[1])
# if current_selection.intersects(error_region):
# current_errors.append(error)
#
# if len(current_errors):
# view.set_status('tsconfig-errors', ' | '.join(current_errors))
# else:
# view.erase_status('tsconfig-errors')
#
# Path: lib/tsconfiglint/tsconfigglobexpand.py
# def expand_filesglob(linter):
# """
# This mimics the filesGlob behaviour of atom-typescript [2]
# If tsconfig.json has no HardErrors, it executes bin/expandglob.js
# and reloads linter.view from disk.
# This operates on the file contents, so the file should have been saved
# before.
# Returns immediately if not linted or linter is None
# Returns True if the filesGlob has been expanded
# Returns False if there was a linter error, so no expansion has been done
# """
#
# # Expanding?
#
# if is_tsglobexpansion_disabled():
# return False
#
# if linter is None or not linter or not linter.linted:
# return False
#
# if len(linter.harderrors) > 0:
# return False
#
# if len(linter.softerrors) != linter.numerrors:
# return False
#
# if linter.content == "":
# return False
#
# if "filesGlob" not in linter.tsconfig:
# return True # Should reopen project, so return True here
#
# # Expand!
# project_dir = os.path.dirname(linter.view.file_name())
# file_list = _expand_globs_with_javascript(project_dir, linter)
# Debug("tsconfig.json", "fileGlobs expaned")
#
# # reload file
# linter.view.run_command("revert")
#
# # lint again, so the soft errors are still displayed
# check_tsconfig(linter.view)
#
# return True
#
# Path: lib/utils/CancelCommand.py
# def catch_CancelCommand(func):
# """ Decorate every command with this one. It will check for
# the plugin disabled flag and catch CancelCommand exceptins. """
#
# def catcher(*kargs, **kwargs):
# if is_plugin_temporarily_disabled():
# return # do not execute command
# try:
# return func(*kargs, **kwargs)
# except CancelCommand:
# Debug('command', "A COMMAND WAS CANCELED")
# return False
# return catcher
#
# class CancelCommand(Exception):
# """ Throw this exception in a command. The decorator
# catch_CancelCommand will catch it and cancel silently """
# pass
#
# Path: lib/system/Project.py
# def opened_project_by_tsconfig(tsconfigfile):
# if not tsconfigfile:
# return None
# tsconfigfile = os.path.normcase(tsconfigfile)
# for p in OPENED_PROJECTS.values():
# if os.path.normcase(p.tsconfigfile) == tsconfigfile:
# return p
# return None
. Output only the next line. | linting_succeeded = expand_filesglob(linter) |
Based on the snippet: <|code_start|># coding=utf8
class TsconfigEventListener(sublime_plugin.EventListener):
""" Listen to file events -> Activate TsconfigLinter.
check_tsconfig immediately returns if file is no tsconfig.json """
def on_activated_async(self, view):
check_tsconfig(view)
def on_load_async(self, view):
check_tsconfig(view)
def on_modified(self, view):
check_tsconfig(view)
def on_clone_async(self, view):
check_tsconfig(view)
<|code_end|>
, predict the immediate next line with the help of imports:
import sublime
import sublime_plugin
import os
from .TsconfigLinter import check_tsconfig, show_lint_in_status
from .tsconfigglobexpand import expand_filesglob
from ..utils.CancelCommand import catch_CancelCommand, CancelCommand
from ..system.Project import opened_project_by_tsconfig
and context (classes, functions, sometimes code) from other files:
# Path: lib/tsconfiglint/TsconfigLinter.py
# @catch_CancelCommand
# def check_tsconfig(view):
# """ Tests view for being a tsconfig.json.
# Reads the tsconfig.json and checks for errors.
# Show Errors using Regions.
# Set a error map [<(a,b), msg>] into views settings. """
#
# if not _is_valid_and_enabled(view):
# return
#
# Debug('tsconfig', 'tsconfig modified, check')
#
# linter = TsconfigLinter(view)
#
# return linter
#
# def show_lint_in_status(view):
# """ Uses the error map stored in view.settings() to display
# status messages if the cursor is above an error """
#
# if not _is_valid_and_enabled(view):
# return
#
# if view.settings().has('tsconfig-lints'):
# error_locations = view.settings().get('tsconfig-lints', [])
#
# current_errors = []
# current_selection = view.sel()[0]
#
# for pos, error in error_locations:
# error_region = sublime.Region(pos[0], pos[1])
# if current_selection.intersects(error_region):
# current_errors.append(error)
#
# if len(current_errors):
# view.set_status('tsconfig-errors', ' | '.join(current_errors))
# else:
# view.erase_status('tsconfig-errors')
#
# Path: lib/tsconfiglint/tsconfigglobexpand.py
# def expand_filesglob(linter):
# """
# This mimics the filesGlob behaviour of atom-typescript [2]
# If tsconfig.json has no HardErrors, it executes bin/expandglob.js
# and reloads linter.view from disk.
# This operates on the file contents, so the file should have been saved
# before.
# Returns immediately if not linted or linter is None
# Returns True if the filesGlob has been expanded
# Returns False if there was a linter error, so no expansion has been done
# """
#
# # Expanding?
#
# if is_tsglobexpansion_disabled():
# return False
#
# if linter is None or not linter or not linter.linted:
# return False
#
# if len(linter.harderrors) > 0:
# return False
#
# if len(linter.softerrors) != linter.numerrors:
# return False
#
# if linter.content == "":
# return False
#
# if "filesGlob" not in linter.tsconfig:
# return True # Should reopen project, so return True here
#
# # Expand!
# project_dir = os.path.dirname(linter.view.file_name())
# file_list = _expand_globs_with_javascript(project_dir, linter)
# Debug("tsconfig.json", "fileGlobs expaned")
#
# # reload file
# linter.view.run_command("revert")
#
# # lint again, so the soft errors are still displayed
# check_tsconfig(linter.view)
#
# return True
#
# Path: lib/utils/CancelCommand.py
# def catch_CancelCommand(func):
# """ Decorate every command with this one. It will check for
# the plugin disabled flag and catch CancelCommand exceptins. """
#
# def catcher(*kargs, **kwargs):
# if is_plugin_temporarily_disabled():
# return # do not execute command
# try:
# return func(*kargs, **kwargs)
# except CancelCommand:
# Debug('command', "A COMMAND WAS CANCELED")
# return False
# return catcher
#
# class CancelCommand(Exception):
# """ Throw this exception in a command. The decorator
# catch_CancelCommand will catch it and cancel silently """
# pass
#
# Path: lib/system/Project.py
# def opened_project_by_tsconfig(tsconfigfile):
# if not tsconfigfile:
# return None
# tsconfigfile = os.path.normcase(tsconfigfile)
# for p in OPENED_PROJECTS.values():
# if os.path.normcase(p.tsconfigfile) == tsconfigfile:
# return p
# return None
. Output only the next line. | @catch_CancelCommand |
Using the snippet: <|code_start|># coding=utf8
class TsconfigEventListener(sublime_plugin.EventListener):
""" Listen to file events -> Activate TsconfigLinter.
check_tsconfig immediately returns if file is no tsconfig.json """
def on_activated_async(self, view):
check_tsconfig(view)
def on_load_async(self, view):
check_tsconfig(view)
def on_modified(self, view):
check_tsconfig(view)
def on_clone_async(self, view):
check_tsconfig(view)
@catch_CancelCommand
def on_post_save_async(self, view):
linter = check_tsconfig(view)
linting_succeeded = expand_filesglob(linter)
if linting_succeeded:
<|code_end|>
, determine the next line of code. You have imports:
import sublime
import sublime_plugin
import os
from .TsconfigLinter import check_tsconfig, show_lint_in_status
from .tsconfigglobexpand import expand_filesglob
from ..utils.CancelCommand import catch_CancelCommand, CancelCommand
from ..system.Project import opened_project_by_tsconfig
and context (class names, function names, or code) available:
# Path: lib/tsconfiglint/TsconfigLinter.py
# @catch_CancelCommand
# def check_tsconfig(view):
# """ Tests view for being a tsconfig.json.
# Reads the tsconfig.json and checks for errors.
# Show Errors using Regions.
# Set a error map [<(a,b), msg>] into views settings. """
#
# if not _is_valid_and_enabled(view):
# return
#
# Debug('tsconfig', 'tsconfig modified, check')
#
# linter = TsconfigLinter(view)
#
# return linter
#
# def show_lint_in_status(view):
# """ Uses the error map stored in view.settings() to display
# status messages if the cursor is above an error """
#
# if not _is_valid_and_enabled(view):
# return
#
# if view.settings().has('tsconfig-lints'):
# error_locations = view.settings().get('tsconfig-lints', [])
#
# current_errors = []
# current_selection = view.sel()[0]
#
# for pos, error in error_locations:
# error_region = sublime.Region(pos[0], pos[1])
# if current_selection.intersects(error_region):
# current_errors.append(error)
#
# if len(current_errors):
# view.set_status('tsconfig-errors', ' | '.join(current_errors))
# else:
# view.erase_status('tsconfig-errors')
#
# Path: lib/tsconfiglint/tsconfigglobexpand.py
# def expand_filesglob(linter):
# """
# This mimics the filesGlob behaviour of atom-typescript [2]
# If tsconfig.json has no HardErrors, it executes bin/expandglob.js
# and reloads linter.view from disk.
# This operates on the file contents, so the file should have been saved
# before.
# Returns immediately if not linted or linter is None
# Returns True if the filesGlob has been expanded
# Returns False if there was a linter error, so no expansion has been done
# """
#
# # Expanding?
#
# if is_tsglobexpansion_disabled():
# return False
#
# if linter is None or not linter or not linter.linted:
# return False
#
# if len(linter.harderrors) > 0:
# return False
#
# if len(linter.softerrors) != linter.numerrors:
# return False
#
# if linter.content == "":
# return False
#
# if "filesGlob" not in linter.tsconfig:
# return True # Should reopen project, so return True here
#
# # Expand!
# project_dir = os.path.dirname(linter.view.file_name())
# file_list = _expand_globs_with_javascript(project_dir, linter)
# Debug("tsconfig.json", "fileGlobs expaned")
#
# # reload file
# linter.view.run_command("revert")
#
# # lint again, so the soft errors are still displayed
# check_tsconfig(linter.view)
#
# return True
#
# Path: lib/utils/CancelCommand.py
# def catch_CancelCommand(func):
# """ Decorate every command with this one. It will check for
# the plugin disabled flag and catch CancelCommand exceptins. """
#
# def catcher(*kargs, **kwargs):
# if is_plugin_temporarily_disabled():
# return # do not execute command
# try:
# return func(*kargs, **kwargs)
# except CancelCommand:
# Debug('command', "A COMMAND WAS CANCELED")
# return False
# return catcher
#
# class CancelCommand(Exception):
# """ Throw this exception in a command. The decorator
# catch_CancelCommand will catch it and cancel silently """
# pass
#
# Path: lib/system/Project.py
# def opened_project_by_tsconfig(tsconfigfile):
# if not tsconfigfile:
# return None
# tsconfigfile = os.path.normcase(tsconfigfile)
# for p in OPENED_PROJECTS.values():
# if os.path.normcase(p.tsconfigfile) == tsconfigfile:
# return p
# return None
. Output only the next line. | project = opened_project_by_tsconfig(linter.file_name) |
Given snippet: <|code_start|># coding=utf8
DEFAULT_DEBOUNCE_DELAY = 0.2 # Will also be used for AsyncCommand debounce
# DEBOUNCE CALL
def debounce(fn, delay=DEFAULT_DEBOUNCE_DELAY, uid=None, *args):
uid = uid if uid else fn
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import threading
from ..system.globals import debounced_timers
and context:
# Path: lib/system/globals.py
# OPENED_PROJECTS = {}
which might include code, classes, or functions. Output only the next line. | if uid in debounced_timers: |
Given the following code snippet before the placeholder: <|code_start|># coding=utf8
# ----------------------------------- ERROR HIGHTLIGHTER -------------------------------------- #
class ErrorsHighlighter(object):
# Constants
underline = sublime.DRAW_SQUIGGLY_UNDERLINE | sublime.DRAW_NO_FILL | sublime.DRAW_NO_OUTLINE | sublime.DRAW_EMPTY_AS_OVERWRITE
def __init__(self, project):
self.project = project
self._icon_paths()
def _icon_paths(self):
""" defines paths for icons """
if os.name == 'nt':
self.error_icon = ".."+os.path.join(package_path.split('Packages')[1], 'icons', 'bright-illegal')
self.warning_icon = ".."+os.path.join(package_path.split('Packages')[1], 'icons', 'bright-warning')
else:
self.error_icon = "Packages"+os.path.join(package_path.split('Packages')[1], 'icons', 'bright-illegal.png')
self.warning_icon = "Packages"+os.path.join(package_path.split('Packages')[1], 'icons', 'bright-warning.png')
<|code_end|>
, predict the next line using imports from the current file:
from threading import Thread
from ..utils import package_path, max_calls
from ..utils.fileutils import fn2k, is_ts
import sublime
import os
import json
and context including class names, function names, and sometimes code from other files:
# Path: lib/utils/debug.py
# def max_calls(limit = 1500, name=""):
# """Decorator which allows its wrapped function to be called `limit` times"""
# def decorator(func):
# # Disable limit:
# return func
# @wraps(func)
# def wrapper(*args, **kwargs):
# calls = getattr(wrapper, 'calls', 0)
# calls += 1
# setattr(wrapper, 'calls', calls)
# fname = name if name != "" else func.__name__
#
# if calls == limit + 1:
# Debug('max_calls', "LIMIT !! ## !!: Fkt %s has %i calls, stop" % (fname, calls - 1))
#
# if calls >= limit + 1:
# return None
#
# Debug('max_calls', "CALL: Fkt %s has %i calls -> +1" % (fname, calls - 1))
#
# return func(*args, **kwargs)
# setattr(wrapper, 'calls', 0)
# return wrapper
# return decorator
#
# Path: lib/utils/pathutils.py
# def add_usr_local_bin_to_path_on_osx():
# def find_tsconfigdir(rootdir):
# def expand_variables(path, project=None, use_cache=False):
# def get_tss_path():
# def get_expandglob_path():
# def default_node_path(node_path, project=None):
# def default_tsc_path(tsc_path=None, project=None):
# def search_node_modules(rootdir):
#
# Path: lib/utils/fileutils.py
# def fn2k(filename):
# """ shortcut for filename2key """
# return filename2key(filename)
#
# def is_ts(view):
# if view is None:
# return False
# fn = view.file_name()
# fn2 = view.file_name()
# fn3 = view.file_name()
# if fn is None or fn2 is None:
# return False
# if fn is None or fn2 is None or fn3 is None:
# pass
# #import spdb ; spdb.start()
# return fn.endswith('.ts') and not fn.endswith('.d.ts')
. Output only the next line. | @max_calls(name='Errors.highlight') |
Continue the code snippet: <|code_start|># coding=utf8
# ----------------------------------- ERROR HIGHTLIGHTER -------------------------------------- #
class ErrorsHighlighter(object):
# Constants
underline = sublime.DRAW_SQUIGGLY_UNDERLINE | sublime.DRAW_NO_FILL | sublime.DRAW_NO_OUTLINE | sublime.DRAW_EMPTY_AS_OVERWRITE
def __init__(self, project):
self.project = project
self._icon_paths()
def _icon_paths(self):
""" defines paths for icons """
if os.name == 'nt':
<|code_end|>
. Use current file imports:
from threading import Thread
from ..utils import package_path, max_calls
from ..utils.fileutils import fn2k, is_ts
import sublime
import os
import json
and context (classes, functions, or code) from other files:
# Path: lib/utils/debug.py
# def max_calls(limit = 1500, name=""):
# """Decorator which allows its wrapped function to be called `limit` times"""
# def decorator(func):
# # Disable limit:
# return func
# @wraps(func)
# def wrapper(*args, **kwargs):
# calls = getattr(wrapper, 'calls', 0)
# calls += 1
# setattr(wrapper, 'calls', calls)
# fname = name if name != "" else func.__name__
#
# if calls == limit + 1:
# Debug('max_calls', "LIMIT !! ## !!: Fkt %s has %i calls, stop" % (fname, calls - 1))
#
# if calls >= limit + 1:
# return None
#
# Debug('max_calls', "CALL: Fkt %s has %i calls -> +1" % (fname, calls - 1))
#
# return func(*args, **kwargs)
# setattr(wrapper, 'calls', 0)
# return wrapper
# return decorator
#
# Path: lib/utils/pathutils.py
# def add_usr_local_bin_to_path_on_osx():
# def find_tsconfigdir(rootdir):
# def expand_variables(path, project=None, use_cache=False):
# def get_tss_path():
# def get_expandglob_path():
# def default_node_path(node_path, project=None):
# def default_tsc_path(tsc_path=None, project=None):
# def search_node_modules(rootdir):
#
# Path: lib/utils/fileutils.py
# def fn2k(filename):
# """ shortcut for filename2key """
# return filename2key(filename)
#
# def is_ts(view):
# if view is None:
# return False
# fn = view.file_name()
# fn2 = view.file_name()
# fn3 = view.file_name()
# if fn is None or fn2 is None:
# return False
# if fn is None or fn2 is None or fn3 is None:
# pass
# #import spdb ; spdb.start()
# return fn.endswith('.ts') and not fn.endswith('.d.ts')
. Output only the next line. | self.error_icon = ".."+os.path.join(package_path.split('Packages')[1], 'icons', 'bright-illegal') |
Predict the next line after this snippet: <|code_start|>
def __init__(self, project):
self.project = project
self._icon_paths()
def _icon_paths(self):
""" defines paths for icons """
if os.name == 'nt':
self.error_icon = ".."+os.path.join(package_path.split('Packages')[1], 'icons', 'bright-illegal')
self.warning_icon = ".."+os.path.join(package_path.split('Packages')[1], 'icons', 'bright-warning')
else:
self.error_icon = "Packages"+os.path.join(package_path.split('Packages')[1], 'icons', 'bright-illegal.png')
self.warning_icon = "Packages"+os.path.join(package_path.split('Packages')[1], 'icons', 'bright-warning.png')
@max_calls(name='Errors.highlight')
def highlight_all_open_files(self):
""" update hightlights (red underline) in all files, using the errors in project """
self.errors = {}
# iterate through all open views, to remove all remaining outdated underlinings
for window in sublime.windows():
for view in window.views():
if is_ts(view):
error_regions, warning_regions, error_texts = \
self.project.errors.tssjs_to_highlighter(view)
<|code_end|>
using the current file's imports:
from threading import Thread
from ..utils import package_path, max_calls
from ..utils.fileutils import fn2k, is_ts
import sublime
import os
import json
and any relevant context from other files:
# Path: lib/utils/debug.py
# def max_calls(limit = 1500, name=""):
# """Decorator which allows its wrapped function to be called `limit` times"""
# def decorator(func):
# # Disable limit:
# return func
# @wraps(func)
# def wrapper(*args, **kwargs):
# calls = getattr(wrapper, 'calls', 0)
# calls += 1
# setattr(wrapper, 'calls', calls)
# fname = name if name != "" else func.__name__
#
# if calls == limit + 1:
# Debug('max_calls', "LIMIT !! ## !!: Fkt %s has %i calls, stop" % (fname, calls - 1))
#
# if calls >= limit + 1:
# return None
#
# Debug('max_calls', "CALL: Fkt %s has %i calls -> +1" % (fname, calls - 1))
#
# return func(*args, **kwargs)
# setattr(wrapper, 'calls', 0)
# return wrapper
# return decorator
#
# Path: lib/utils/pathutils.py
# def add_usr_local_bin_to_path_on_osx():
# def find_tsconfigdir(rootdir):
# def expand_variables(path, project=None, use_cache=False):
# def get_tss_path():
# def get_expandglob_path():
# def default_node_path(node_path, project=None):
# def default_tsc_path(tsc_path=None, project=None):
# def search_node_modules(rootdir):
#
# Path: lib/utils/fileutils.py
# def fn2k(filename):
# """ shortcut for filename2key """
# return filename2key(filename)
#
# def is_ts(view):
# if view is None:
# return False
# fn = view.file_name()
# fn2 = view.file_name()
# fn3 = view.file_name()
# if fn is None or fn2 is None:
# return False
# if fn is None or fn2 is None or fn3 is None:
# pass
# #import spdb ; spdb.start()
# return fn.endswith('.ts') and not fn.endswith('.d.ts')
. Output only the next line. | self.errors[fn2k(view.file_name())] = error_texts |
Here is a snippet: <|code_start|>class ErrorsHighlighter(object):
# Constants
underline = sublime.DRAW_SQUIGGLY_UNDERLINE | sublime.DRAW_NO_FILL | sublime.DRAW_NO_OUTLINE | sublime.DRAW_EMPTY_AS_OVERWRITE
def __init__(self, project):
self.project = project
self._icon_paths()
def _icon_paths(self):
""" defines paths for icons """
if os.name == 'nt':
self.error_icon = ".."+os.path.join(package_path.split('Packages')[1], 'icons', 'bright-illegal')
self.warning_icon = ".."+os.path.join(package_path.split('Packages')[1], 'icons', 'bright-warning')
else:
self.error_icon = "Packages"+os.path.join(package_path.split('Packages')[1], 'icons', 'bright-illegal.png')
self.warning_icon = "Packages"+os.path.join(package_path.split('Packages')[1], 'icons', 'bright-warning.png')
@max_calls(name='Errors.highlight')
def highlight_all_open_files(self):
""" update hightlights (red underline) in all files, using the errors in project """
self.errors = {}
# iterate through all open views, to remove all remaining outdated underlinings
for window in sublime.windows():
for view in window.views():
<|code_end|>
. Write the next line using the current file imports:
from threading import Thread
from ..utils import package_path, max_calls
from ..utils.fileutils import fn2k, is_ts
import sublime
import os
import json
and context from other files:
# Path: lib/utils/debug.py
# def max_calls(limit = 1500, name=""):
# """Decorator which allows its wrapped function to be called `limit` times"""
# def decorator(func):
# # Disable limit:
# return func
# @wraps(func)
# def wrapper(*args, **kwargs):
# calls = getattr(wrapper, 'calls', 0)
# calls += 1
# setattr(wrapper, 'calls', calls)
# fname = name if name != "" else func.__name__
#
# if calls == limit + 1:
# Debug('max_calls', "LIMIT !! ## !!: Fkt %s has %i calls, stop" % (fname, calls - 1))
#
# if calls >= limit + 1:
# return None
#
# Debug('max_calls', "CALL: Fkt %s has %i calls -> +1" % (fname, calls - 1))
#
# return func(*args, **kwargs)
# setattr(wrapper, 'calls', 0)
# return wrapper
# return decorator
#
# Path: lib/utils/pathutils.py
# def add_usr_local_bin_to_path_on_osx():
# def find_tsconfigdir(rootdir):
# def expand_variables(path, project=None, use_cache=False):
# def get_tss_path():
# def get_expandglob_path():
# def default_node_path(node_path, project=None):
# def default_tsc_path(tsc_path=None, project=None):
# def search_node_modules(rootdir):
#
# Path: lib/utils/fileutils.py
# def fn2k(filename):
# """ shortcut for filename2key """
# return filename2key(filename)
#
# def is_ts(view):
# if view is None:
# return False
# fn = view.file_name()
# fn2 = view.file_name()
# fn3 = view.file_name()
# if fn is None or fn2 is None:
# return False
# if fn is None or fn2 is None or fn3 is None:
# pass
# #import spdb ; spdb.start()
# return fn.endswith('.ts') and not fn.endswith('.d.ts')
, which may include functions, classes, or code. Output only the next line. | if is_ts(view): |
Using the snippet: <|code_start|> return self
def set_callback_kwargs(self, **callback_kwargs):
""" Set additional arguments the callbacks will be called with. """
self.callback_kwargs = callback_kwargs
return self
def set_result_callback(self, result_callback=None):
""" Will be called as result_callback(tss_answer, **callback_kwargs). """
self.result_callback = result_callback
return self
def set_replaced_callback(self, replaced_callback=None):
"""
Will be called as replaced_callback(now_used_command, **callback_kwargs)
when this command has been deleted from queue without execution.
"""
self.replaced_callback = replaced_callback
return self
def set_executing_callback(self, executing_callback=None):
""" Will be called as soon as the command is sent to tss.js """
self.executing_callback = executing_callback
return self
# ------------------------- finish chain: execute ------------------------------ #
def append_to_fast_queue(self):
<|code_end|>
, determine the next line of code. You have imports:
import uuid
import time
import sublime
import json
from ..utils import Debug
from ..utils.debounce import DEFAULT_DEBOUNCE_DELAY
and context (class names, function names, or code) available:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/debounce.py
# DEFAULT_DEBOUNCE_DELAY = 0.2 # Will also be used for AsyncCommand debounce
. Output only the next line. | Debug('command', "CMD queued @FAST: %s" % self.id) |
Using the snippet: <|code_start|> self.command = command
self.project = project
self.id = "%s-rnd%s" % (command[:6][:-1], uuid.uuid4().hex[0:5])
self.result_callback = None
self.replaced_callback = None
self.executing_callback = None
self.callback_kwargs = {}
self.merge_behaviour = self.MERGE_IMMEDIATE
self.debounce_time = 0
self.json_decode_tss_answer = False
self.time_queue = 0
self.time_last_bounce = 0
self.time_execute = 0
self.time_finish = 0
self.is_executed = False
# ------------------------- chainable config ---------------------------------- #
def set_id(self, _id):
""" set id for merging. See AsyncCommand.__doc__ for more information about merging """
self.id = _id
return self
def procrastinate(self):
""" Set merging strategy to procastinate. See AsyncCommand.__doc__ for more information about merging """
self.merge_behaviour = self.MERGE_PROCRASTINATE
return self
<|code_end|>
, determine the next line of code. You have imports:
import uuid
import time
import sublime
import json
from ..utils import Debug
from ..utils.debounce import DEFAULT_DEBOUNCE_DELAY
and context (class names, function names, or code) available:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/debounce.py
# DEFAULT_DEBOUNCE_DELAY = 0.2 # Will also be used for AsyncCommand debounce
. Output only the next line. | def activate_debounce(self, delay=DEFAULT_DEBOUNCE_DELAY): |
Predict the next line for this snippet: <|code_start|># coding=utf8
# ------------------------------------- PROJECT WIZZARD ----------------------------------------- #
class ProjectWizzard(object):
def __init__(self, view, finished_callback):
self.finished_callback = finished_callback
self.window = view.window()
if not self.window: # workaround
self.window = view.window()
self.view = view
self.tsconfigfolder = None
self.module = None
self.outfile = None
self.outdir = None
self.target = "es5"
self.sourcemap = True
self.files = []
<|code_end|>
with the help of current file imports:
import sublime
import json
import os
from ..utils import package_path, Debug
from ..utils.disabling import set_plugin_temporarily_disabled, \
set_plugin_temporarily_enabled, \
is_plugin_temporarily_disabled
and context from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/pathutils.py
# def add_usr_local_bin_to_path_on_osx():
# def find_tsconfigdir(rootdir):
# def expand_variables(path, project=None, use_cache=False):
# def get_tss_path():
# def get_expandglob_path():
# def default_node_path(node_path, project=None):
# def default_tsc_path(tsc_path=None, project=None):
# def search_node_modules(rootdir):
#
# Path: lib/utils/disabling.py
# def set_plugin_temporarily_disabled(folder=None):
# """ Enables the plugin globally or for folder.
# Folder can be a view """
# if folder is None:
# if not is_plugin_globally_disabled():
# plugin_disabled_for_folders.append("*global")
# else:
# if isinstance(folder, sublime.View):
# folder = os.path.dirname(folder.file_name())
# folder = os.path.normcase(folder)
# Debug('project', 'Disable ArcticTypescript for %s' % folder)
# if folder not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append(folder)
#
# def set_plugin_temporarily_enabled(folder=None):
# """ Disables the plugin globally or for folder.
# Folder can be a view """
# if folder is None:
# if is_plugin_globally_disabled():
# plugin_disabled_for_folders.remove("*global")
# else:
# if isinstance(folder, sublime.View):
# folder = os.path.dirname(folder.file_name())
# folder = os.path.normcase(folder)
# Debug('project', 'Enable ArcticTypescript for %s' % folder)
# if folder in plugin_disabled_for_folders:
# plugin_disabled_for_folders.remove(folder)
#
# def is_plugin_temporarily_disabled(folder=None):
# """ Returns True if the plugin is disabled globally or for folder.
# Folder can be a view """
# if is_plugin_globally_disabled() or folder is None:
# return is_plugin_globally_disabled()
# if folder is not None and isinstance(folder, sublime.View):
# if folder.file_name() is None:
# return is_plugin_globally_disabled()
# folder = os.path.dirname(folder.file_name())
# folder = os.path.normcase(folder)
# return folder in plugin_disabled_for_folders
, which may contain function names, class names, or code. Output only the next line. | Debug('project+', 'Disable ArcticTypescript while in WizzardMode') |
Given the code snippet: <|code_start|> max_lines = 0
for m in self.messages:
max_lines = max(max_lines, len(m))
for m in self.messages:
while len(m) < max_lines:
m.append('')
def on_select(i):
#self.window.run_command("hide_overlay")
if i == -1:
Debug('project+', '-1: Quick panel canceled')
sublime.set_timeout(self._cleanup, 50)
if self.action_cancel is not None:
sublime.set_timeout(self.action_cancel, 50)
elif i >= 0:
if self.actions[i] is not None:
sublime.set_timeout(self.actions[i], 50)
elif self.action_default is not None:
sublime.set_timeout(self.action_default, 50)
Debug('project+', 'Nr %i selected' % i)
self.window.show_quick_panel(self.messages, on_select)
def handle_tsconfig_error(self, tsconfigfile, message=""):
""" User will be asked to create a tsconfig.json file """
self._prepare(message)
self.messages.append(['> Open your tsconfig.json and Edit it'])
self.actions.append(lambda: [self.window.open_file(tsconfigfile), self._cleanup()])
self.messages.append(['> Show tsconfig.json example'])
<|code_end|>
, generate the next line using the imports in this file:
import sublime
import json
import os
from ..utils import package_path, Debug
from ..utils.disabling import set_plugin_temporarily_disabled, \
set_plugin_temporarily_enabled, \
is_plugin_temporarily_disabled
and context (functions, classes, or occasionally code) from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/pathutils.py
# def add_usr_local_bin_to_path_on_osx():
# def find_tsconfigdir(rootdir):
# def expand_variables(path, project=None, use_cache=False):
# def get_tss_path():
# def get_expandglob_path():
# def default_node_path(node_path, project=None):
# def default_tsc_path(tsc_path=None, project=None):
# def search_node_modules(rootdir):
#
# Path: lib/utils/disabling.py
# def set_plugin_temporarily_disabled(folder=None):
# """ Enables the plugin globally or for folder.
# Folder can be a view """
# if folder is None:
# if not is_plugin_globally_disabled():
# plugin_disabled_for_folders.append("*global")
# else:
# if isinstance(folder, sublime.View):
# folder = os.path.dirname(folder.file_name())
# folder = os.path.normcase(folder)
# Debug('project', 'Disable ArcticTypescript for %s' % folder)
# if folder not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append(folder)
#
# def set_plugin_temporarily_enabled(folder=None):
# """ Disables the plugin globally or for folder.
# Folder can be a view """
# if folder is None:
# if is_plugin_globally_disabled():
# plugin_disabled_for_folders.remove("*global")
# else:
# if isinstance(folder, sublime.View):
# folder = os.path.dirname(folder.file_name())
# folder = os.path.normcase(folder)
# Debug('project', 'Enable ArcticTypescript for %s' % folder)
# if folder in plugin_disabled_for_folders:
# plugin_disabled_for_folders.remove(folder)
#
# def is_plugin_temporarily_disabled(folder=None):
# """ Returns True if the plugin is disabled globally or for folder.
# Folder can be a view """
# if is_plugin_globally_disabled() or folder is None:
# return is_plugin_globally_disabled()
# if folder is not None and isinstance(folder, sublime.View):
# if folder.file_name() is None:
# return is_plugin_globally_disabled()
# folder = os.path.dirname(folder.file_name())
# folder = os.path.normcase(folder)
# return folder in plugin_disabled_for_folders
. Output only the next line. | self.actions.append(lambda: [self.window.open_file(package_path + '/examples/basic_browser_project/tsconfig.json'), self._cleanup()]) |
Next line prediction: <|code_start|># coding=utf8
# ------------------------------------- PROJECT WIZZARD ----------------------------------------- #
class ProjectWizzard(object):
def __init__(self, view, finished_callback):
self.finished_callback = finished_callback
self.window = view.window()
if not self.window: # workaround
self.window = view.window()
self.view = view
self.tsconfigfolder = None
self.module = None
self.outfile = None
self.outdir = None
self.target = "es5"
self.sourcemap = True
self.files = []
Debug('project+', 'Disable ArcticTypescript while in WizzardMode')
<|code_end|>
. Use current file imports:
(import sublime
import json
import os
from ..utils import package_path, Debug
from ..utils.disabling import set_plugin_temporarily_disabled, \
set_plugin_temporarily_enabled, \
is_plugin_temporarily_disabled)
and context including class names, function names, or small code snippets from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/pathutils.py
# def add_usr_local_bin_to_path_on_osx():
# def find_tsconfigdir(rootdir):
# def expand_variables(path, project=None, use_cache=False):
# def get_tss_path():
# def get_expandglob_path():
# def default_node_path(node_path, project=None):
# def default_tsc_path(tsc_path=None, project=None):
# def search_node_modules(rootdir):
#
# Path: lib/utils/disabling.py
# def set_plugin_temporarily_disabled(folder=None):
# """ Enables the plugin globally or for folder.
# Folder can be a view """
# if folder is None:
# if not is_plugin_globally_disabled():
# plugin_disabled_for_folders.append("*global")
# else:
# if isinstance(folder, sublime.View):
# folder = os.path.dirname(folder.file_name())
# folder = os.path.normcase(folder)
# Debug('project', 'Disable ArcticTypescript for %s' % folder)
# if folder not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append(folder)
#
# def set_plugin_temporarily_enabled(folder=None):
# """ Disables the plugin globally or for folder.
# Folder can be a view """
# if folder is None:
# if is_plugin_globally_disabled():
# plugin_disabled_for_folders.remove("*global")
# else:
# if isinstance(folder, sublime.View):
# folder = os.path.dirname(folder.file_name())
# folder = os.path.normcase(folder)
# Debug('project', 'Enable ArcticTypescript for %s' % folder)
# if folder in plugin_disabled_for_folders:
# plugin_disabled_for_folders.remove(folder)
#
# def is_plugin_temporarily_disabled(folder=None):
# """ Returns True if the plugin is disabled globally or for folder.
# Folder can be a view """
# if is_plugin_globally_disabled() or folder is None:
# return is_plugin_globally_disabled()
# if folder is not None and isinstance(folder, sublime.View):
# if folder.file_name() is None:
# return is_plugin_globally_disabled()
# folder = os.path.dirname(folder.file_name())
# folder = os.path.normcase(folder)
# return folder in plugin_disabled_for_folders
. Output only the next line. | set_plugin_temporarily_disabled() # Disable global until wizzard is cancled or finished |
Using the snippet: <|code_start|>
def _finish(self):
""" make and write tsconfig.json. Call finished_callback """
Debug('project+', 'Wizzard finished: Create and write tsconfig.json')
content = { "compilerOptions" : {}, "files" : {}}
if self.module is None:
content['compilerOptions']['out'] = self.outfile
content['compilerOptions']['target'] = self.target
content['compilerOptions']['sourceMap'] = self.sourcemap
elif self.module == "commonjs" or self.module == "amd":
content['compilerOptions']['outDir'] = self.outdir
content['compilerOptions']['target'] = self.target
content['compilerOptions']['sourceMap'] = self.sourcemap
content['compilerOptions']['module'] = self.module
content['files'] = self.files
self.write_json_to_tsconfigfile(content)
if self.finished_callback:
self.finished_callback()
sublime.active_window().open_file(self.tspath)
sublime.message_dialog("For more compilerOptions, see tsc --help.\n\n To configure ArcticTypescript, see README.md")
self._cleanup()
def _cleanup(self):
Debug('project+', 'Enable ArcticTypescript again')
<|code_end|>
, determine the next line of code. You have imports:
import sublime
import json
import os
from ..utils import package_path, Debug
from ..utils.disabling import set_plugin_temporarily_disabled, \
set_plugin_temporarily_enabled, \
is_plugin_temporarily_disabled
and context (class names, function names, or code) available:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/pathutils.py
# def add_usr_local_bin_to_path_on_osx():
# def find_tsconfigdir(rootdir):
# def expand_variables(path, project=None, use_cache=False):
# def get_tss_path():
# def get_expandglob_path():
# def default_node_path(node_path, project=None):
# def default_tsc_path(tsc_path=None, project=None):
# def search_node_modules(rootdir):
#
# Path: lib/utils/disabling.py
# def set_plugin_temporarily_disabled(folder=None):
# """ Enables the plugin globally or for folder.
# Folder can be a view """
# if folder is None:
# if not is_plugin_globally_disabled():
# plugin_disabled_for_folders.append("*global")
# else:
# if isinstance(folder, sublime.View):
# folder = os.path.dirname(folder.file_name())
# folder = os.path.normcase(folder)
# Debug('project', 'Disable ArcticTypescript for %s' % folder)
# if folder not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append(folder)
#
# def set_plugin_temporarily_enabled(folder=None):
# """ Disables the plugin globally or for folder.
# Folder can be a view """
# if folder is None:
# if is_plugin_globally_disabled():
# plugin_disabled_for_folders.remove("*global")
# else:
# if isinstance(folder, sublime.View):
# folder = os.path.dirname(folder.file_name())
# folder = os.path.normcase(folder)
# Debug('project', 'Enable ArcticTypescript for %s' % folder)
# if folder in plugin_disabled_for_folders:
# plugin_disabled_for_folders.remove(folder)
#
# def is_plugin_temporarily_disabled(folder=None):
# """ Returns True if the plugin is disabled globally or for folder.
# Folder can be a view """
# if is_plugin_globally_disabled() or folder is None:
# return is_plugin_globally_disabled()
# if folder is not None and isinstance(folder, sublime.View):
# if folder.file_name() is None:
# return is_plugin_globally_disabled()
# folder = os.path.dirname(folder.file_name())
# folder = os.path.normcase(folder)
# return folder in plugin_disabled_for_folders
. Output only the next line. | set_plugin_temporarily_enabled() |
Using the snippet: <|code_start|># coding=utf8
# ------------------------------------- PROJECT WIZZARD ----------------------------------------- #
class ProjectWizzard(object):
def __init__(self, view, finished_callback):
self.finished_callback = finished_callback
self.window = view.window()
if not self.window: # workaround
self.window = view.window()
self.view = view
self.tsconfigfolder = None
self.module = None
self.outfile = None
self.outdir = None
self.target = "es5"
self.sourcemap = True
self.files = []
Debug('project+', 'Disable ArcticTypescript while in WizzardMode')
set_plugin_temporarily_disabled() # Disable global until wizzard is cancled or finished
<|code_end|>
, determine the next line of code. You have imports:
import sublime
import json
import os
from ..utils import package_path, Debug
from ..utils.disabling import set_plugin_temporarily_disabled, \
set_plugin_temporarily_enabled, \
is_plugin_temporarily_disabled
and context (class names, function names, or code) available:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/pathutils.py
# def add_usr_local_bin_to_path_on_osx():
# def find_tsconfigdir(rootdir):
# def expand_variables(path, project=None, use_cache=False):
# def get_tss_path():
# def get_expandglob_path():
# def default_node_path(node_path, project=None):
# def default_tsc_path(tsc_path=None, project=None):
# def search_node_modules(rootdir):
#
# Path: lib/utils/disabling.py
# def set_plugin_temporarily_disabled(folder=None):
# """ Enables the plugin globally or for folder.
# Folder can be a view """
# if folder is None:
# if not is_plugin_globally_disabled():
# plugin_disabled_for_folders.append("*global")
# else:
# if isinstance(folder, sublime.View):
# folder = os.path.dirname(folder.file_name())
# folder = os.path.normcase(folder)
# Debug('project', 'Disable ArcticTypescript for %s' % folder)
# if folder not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append(folder)
#
# def set_plugin_temporarily_enabled(folder=None):
# """ Disables the plugin globally or for folder.
# Folder can be a view """
# if folder is None:
# if is_plugin_globally_disabled():
# plugin_disabled_for_folders.remove("*global")
# else:
# if isinstance(folder, sublime.View):
# folder = os.path.dirname(folder.file_name())
# folder = os.path.normcase(folder)
# Debug('project', 'Enable ArcticTypescript for %s' % folder)
# if folder in plugin_disabled_for_folders:
# plugin_disabled_for_folders.remove(folder)
#
# def is_plugin_temporarily_disabled(folder=None):
# """ Returns True if the plugin is disabled globally or for folder.
# Folder can be a view """
# if is_plugin_globally_disabled() or folder is None:
# return is_plugin_globally_disabled()
# if folder is not None and isinstance(folder, sublime.View):
# if folder.file_name() is None:
# return is_plugin_globally_disabled()
# folder = os.path.dirname(folder.file_name())
# folder = os.path.normcase(folder)
# return folder in plugin_disabled_for_folders
. Output only the next line. | assert is_plugin_temporarily_disabled() |
Here is a snippet: <|code_start|> and uses them. If no such view can be found, it creates one and layoutes it to group 1
"""
if self.get_view() is None:
## add next to existing t3s views
## or create layout if not created yet
self.t3sviews.get_window_and_group_for_new_views()
if not self.t3sviews.has_open_views():
self.t3sviews.layout.create(self.t3sviews.window)
view = self.t3sviews.window.new_file()
self._set_up_view(view)
self.t3sviews.layout.add_view(self.t3sviews.window, view, self.t3sviews.group)
self._view_reference = view
return self._view_reference
@max_calls()
def _set_up_view(self, view):
view.set_name(self.name)
view.set_scratch(True)
view.set_read_only(True)
view.set_syntax_file('Packages/ArcticTypescript/theme/Typescript.tmLanguage')
view.settings().set('line_numbers', False)
view.settings().set('word_wrap', True)
view.settings().set('extensions',['js'])
@max_calls()
def bring_to_top(self, back_to=None):
<|code_end|>
. Write the next line using the current file imports:
import sublime
from ...utils import Debug, max_calls
and context from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# def max_calls(limit = 1500, name=""):
# """Decorator which allows its wrapped function to be called `limit` times"""
# def decorator(func):
# # Disable limit:
# return func
# @wraps(func)
# def wrapper(*args, **kwargs):
# calls = getattr(wrapper, 'calls', 0)
# calls += 1
# setattr(wrapper, 'calls', calls)
# fname = name if name != "" else func.__name__
#
# if calls == limit + 1:
# Debug('max_calls', "LIMIT !! ## !!: Fkt %s has %i calls, stop" % (fname, calls - 1))
#
# if calls >= limit + 1:
# return None
#
# Debug('max_calls', "CALL: Fkt %s has %i calls -> +1" % (fname, calls - 1))
#
# return func(*args, **kwargs)
# setattr(wrapper, 'calls', 0)
# return wrapper
# return decorator
, which may include functions, classes, or code. Output only the next line. | Debug('focus', 'bring_to_top: focus view %i' % self._view_reference.id()) |
Using the snippet: <|code_start|># coding=utf8
class Base(object):
"""
This object represents a special view to display ArcticTypescript information like
the error list or the outline structure
"""
def __init__(self, name, t3sviews):
self.name = name
self.t3sviews = t3sviews
self.is_updating = False # text changes
self._view_reference = None
<|code_end|>
, determine the next line of code. You have imports:
import sublime
from ...utils import Debug, max_calls
and context (class names, function names, or code) available:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# def max_calls(limit = 1500, name=""):
# """Decorator which allows its wrapped function to be called `limit` times"""
# def decorator(func):
# # Disable limit:
# return func
# @wraps(func)
# def wrapper(*args, **kwargs):
# calls = getattr(wrapper, 'calls', 0)
# calls += 1
# setattr(wrapper, 'calls', calls)
# fname = name if name != "" else func.__name__
#
# if calls == limit + 1:
# Debug('max_calls', "LIMIT !! ## !!: Fkt %s has %i calls, stop" % (fname, calls - 1))
#
# if calls >= limit + 1:
# return None
#
# Debug('max_calls', "CALL: Fkt %s has %i calls -> +1" % (fname, calls - 1))
#
# return func(*args, **kwargs)
# setattr(wrapper, 'calls', 0)
# return wrapper
# return decorator
. Output only the next line. | @max_calls() |
Predict the next line after this snippet: <|code_start|># --------------------------------------- ERRORS -------------------------------------- #
class Errors(object):
def __init__(self, project):
self.project = project
self.lasterrors = []
self.message = "" # contains exception message if an error occured
pass
@max_calls()
def start_recalculation(self):
self.project.tsserver.errors(self.on_results)
@max_calls()
def on_results(self, errors):
""" this is the callback from the async process if new errors have been calculated """
try:
self.failure = ""
self.lasterrors = json.loads(errors)
if isinstance(self.lasterrors, str):
self.lasterrors = [ self._provide_better_explanations_for_tss_errors(self.lasterrors)]
# self.lasterrors is a list or None
if not isinstance(self.lasterrors, list):
raise Warning("tss.js internal error: %s" % errors)
self._provide_better_explanations_for_some_errors()
self._tssjs_to_errorview()
except BaseException as e: # Also catches JSON exceptions
self.lasterrors = []
self.failure = "%s" % e
<|code_end|>
using the current file's imports:
import sublime
import json
import re
from ..utils import max_calls, Debug
from ..utils.fileutils import fn2k
and any relevant context from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# def max_calls(limit = 1500, name=""):
# """Decorator which allows its wrapped function to be called `limit` times"""
# def decorator(func):
# # Disable limit:
# return func
# @wraps(func)
# def wrapper(*args, **kwargs):
# calls = getattr(wrapper, 'calls', 0)
# calls += 1
# setattr(wrapper, 'calls', calls)
# fname = name if name != "" else func.__name__
#
# if calls == limit + 1:
# Debug('max_calls', "LIMIT !! ## !!: Fkt %s has %i calls, stop" % (fname, calls - 1))
#
# if calls >= limit + 1:
# return None
#
# Debug('max_calls', "CALL: Fkt %s has %i calls -> +1" % (fname, calls - 1))
#
# return func(*args, **kwargs)
# setattr(wrapper, 'calls', 0)
# return wrapper
# return decorator
#
# Path: lib/utils/fileutils.py
# def fn2k(filename):
# """ shortcut for filename2key """
# return filename2key(filename)
. Output only the next line. | Debug('error', 'Internal ArcticTypescript error during show_errors: %s (Exception Message: %s)' % (errors, e)) |
Predict the next line after this snippet: <|code_start|># coding=utf8
# --------------------------------------- ERRORS -------------------------------------- #
class Errors(object):
def __init__(self, project):
self.project = project
self.lasterrors = []
self.message = "" # contains exception message if an error occured
pass
<|code_end|>
using the current file's imports:
import sublime
import json
import re
from ..utils import max_calls, Debug
from ..utils.fileutils import fn2k
and any relevant context from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# def max_calls(limit = 1500, name=""):
# """Decorator which allows its wrapped function to be called `limit` times"""
# def decorator(func):
# # Disable limit:
# return func
# @wraps(func)
# def wrapper(*args, **kwargs):
# calls = getattr(wrapper, 'calls', 0)
# calls += 1
# setattr(wrapper, 'calls', calls)
# fname = name if name != "" else func.__name__
#
# if calls == limit + 1:
# Debug('max_calls', "LIMIT !! ## !!: Fkt %s has %i calls, stop" % (fname, calls - 1))
#
# if calls >= limit + 1:
# return None
#
# Debug('max_calls', "CALL: Fkt %s has %i calls -> +1" % (fname, calls - 1))
#
# return func(*args, **kwargs)
# setattr(wrapper, 'calls', 0)
# return wrapper
# return decorator
#
# Path: lib/utils/fileutils.py
# def fn2k(filename):
# """ shortcut for filename2key """
# return filename2key(filename)
. Output only the next line. | @max_calls() |
Given the code snippet: <|code_start|> self.line_to_file = line_to_file
self.line_to_pos = line_to_pos
self.text = ''.join(text)
def _flatten_errortext(self, text_or_dict):
text = []
if isinstance(text_or_dict, str):
text.append(text_or_dict.replace('\r',''))
elif isinstance(text_or_dict, dict) and 'messageText' in text_or_dict:
text.append(text_or_dict['messageText'])
if 'next' in text_or_dict and 'messageText' in text_or_dict['next']:
text.append('\n >')
text.append(text_or_dict['next']['messageText'])
else:
Debug('error', 'typescript-tools error["text"] has unexpected type %s.' % type(text_or_dict))
return text
def tssjs_to_highlighter(self, view):
"""
Creates a list of error and warning regions for all errors.
Returns error_regions, warning_regions, error_texts
"""
error_texts = {} # key: textpoint start and end, value: description
error_regions = []
warning_regions = []
for e in self.lasterrors:
<|code_end|>
, generate the next line using the imports in this file:
import sublime
import json
import re
from ..utils import max_calls, Debug
from ..utils.fileutils import fn2k
and context (functions, classes, or occasionally code) from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# def max_calls(limit = 1500, name=""):
# """Decorator which allows its wrapped function to be called `limit` times"""
# def decorator(func):
# # Disable limit:
# return func
# @wraps(func)
# def wrapper(*args, **kwargs):
# calls = getattr(wrapper, 'calls', 0)
# calls += 1
# setattr(wrapper, 'calls', calls)
# fname = name if name != "" else func.__name__
#
# if calls == limit + 1:
# Debug('max_calls', "LIMIT !! ## !!: Fkt %s has %i calls, stop" % (fname, calls - 1))
#
# if calls >= limit + 1:
# return None
#
# Debug('max_calls', "CALL: Fkt %s has %i calls -> +1" % (fname, calls - 1))
#
# return func(*args, **kwargs)
# setattr(wrapper, 'calls', 0)
# return wrapper
# return decorator
#
# Path: lib/utils/fileutils.py
# def fn2k(filename):
# """ shortcut for filename2key """
# return filename2key(filename)
. Output only the next line. | if fn2k(e['file']) == fn2k(view.file_name()): |
Given the code snippet: <|code_start|>
def kwargs_to_namedtuple(func):
def wrapper(**kwargs):
controls = namedtuple('Controls', list(kwargs.keys()))(**kwargs)
return func(controls)
return wrapper
def namedtuple_to_kwargs(func):
def wrapper(controls):
return func(**(controls._todict()))
return wrapper
#
# private data shared among functions
#
class Private(object):
pass
private = Private()
#
# functions
#
#def initialize(**kwargs):
@kwargs_to_namedtuple
def initialize(C):
# store data in a GrawableArray so we can efficiently append to it
<|code_end|>
, generate the next line using the imports in this file:
from collections import namedtuple
from pythics.lib import GrowableArray
import numpy as np
and context (functions, classes, or occasionally code) from other files:
# Path: pythics/lib.py
# class GrowableArray(object):
# def __init__(self, length, cols=1, dtype=np.float64):
# self.__cols = cols
# self.__initial_length = int(length)
# # number of rows to grow by if we run out of space
# self.__n_grow = self.__initial_length
# self.__dtype = dtype
# self.clear()
# # properties of arrays
# self.ndim = 2
#
# def clear(self):
# # actual array size
# self.__N = self.__initial_length
# # the next place to put a value in the buffer
# # also the number of rows that have been filled
# self.__n = 0
# # allocate the initial data
# self.__data = np.zeros((self.__N, self.__cols), dtype=self.__dtype)
#
# def append(self, value):
# # convert the appended object to an array if it starts as something else
# if type(value) is not np.ndarray:
# value = np.array(value)
# # add the data
# if value.ndim == 1:
# # adding a single row of data
# n = self.__n
# if n + 1 > self.__N:
# # need to allocate more memory
# self.__N += self.__n_grow
# self.__data = np.resize(self.__data, (self.__N, self.__cols))
# self.__data[n] = value
# self.__n = n + 1
# elif value.ndim == 2:
# # adding multiple rows of data
# # avoid loops for appending large arrays
# n = self.__n
# L = value.shape[0]
# N_needed = n + L - self.__N
# if N_needed > 0:
# # need to allocate more memory
# self.__N += (N_needed / self.__n_grow + 1) * self.__n_grow
# self.__data = np.resize(self.__data, (self.__N, self.__cols))
# self.__data[n:n+L] = value
# self.__n += L
#
# def __as_array(self):
# return self.__data[:self.__n]
#
# # some standard array methods
#
# @property
# def shape(self):
# return (self.__n, self.__cols)
#
# def __getitem__(self, key):
# return self.__as_array().__getitem__(key)
#
# def __iter__(self):
# return self.__as_array().__iter__()
#
# def __len__(self):
# return self.__n
#
# def __repr__(self):
# return self.__as_array().__repr__()
#
# def __setitem__(self, key, value):
# return self.__as_array().__setitem__(key, value)
#
# def __str__(self):
# return self.__as_array().__str__()
#
# def sum(self, *args, **kwargs):
# return self.__as_array().sum(*args, **kwargs)
. Output only the next line. | private.data = GrowableArray(cols=5, length=1000) |
Next line prediction: <|code_start|># Copyright 2008 - 2019 Brian R. D'Urso
#
# This file is part of Python Instrument Control System, also known as Pythics.
#
# Pythics is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pythics is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Pythics. If not, see <http://www.gnu.org/licenses/>.
#
#
# load libraries
#
try:
lxml_loaded = True
except ImportError as e:
sys.stderr.write("Error: failed to import lxml module ({})".format(e))
lxml_loaded = False
try:
<|code_end|>
. Use current file imports:
(import importlib
import re
import io
import sys, traceback
import PySide2.QtCore as _QtCore
import PySide2.QtGui as _QtGui
import PySide2.QtWidgets as _QtWidgets
import PySide2.QtPrintSupport as _QtPrintSupport
import PyQt5.QtCore as _QtCore
import PyQt5.QtGui as _QtGui
import PyQt5.QtWidgets as _QtWidgets
import PyQt5.QtPrintSupport as _QtPrintSupport
from lxml import etree as ElementTree
from xml.etree import ElementTree
from pythics.settings import _TRY_PYSIDE)
and context including class names, function names, or small code snippets from other files:
# Path: pythics/settings.py
# _TRY_PYSIDE = True
. Output only the next line. | if not _TRY_PYSIDE: |
Predict the next line after this snippet: <|code_start|>
#
# private data shared among functions
#
class Private(object):
pass
private = Private()
#
# functions
#
def initialize(log_text_box, data_chart, **kwargs):
# setup the logger and log display box
# examples of how to use:
# private.logger.debug('this is a debug message')
# private.logger.info('this is an info message')
# private.logger.warning('this is a warning message')
# private.logger.error('this is an error message')
# private.logger.critical('this is a critical error message')
# private.logger.exception('this is an exception')
private.logger = logging.getLogger('log')
#private.logger.setLevel(logging.DEBUG)
private.logger.setLevel(logging.INFO)
sh = logging.StreamHandler(log_text_box)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
sh.setFormatter(formatter)
private.logger.addHandler(sh)
# store data in a GrawableArray so we can efficiently append to it
<|code_end|>
using the current file's imports:
import logging
import time
import numpy as np
from pythics.lib import GrowableArray
and any relevant context from other files:
# Path: pythics/lib.py
# class GrowableArray(object):
# def __init__(self, length, cols=1, dtype=np.float64):
# self.__cols = cols
# self.__initial_length = int(length)
# # number of rows to grow by if we run out of space
# self.__n_grow = self.__initial_length
# self.__dtype = dtype
# self.clear()
# # properties of arrays
# self.ndim = 2
#
# def clear(self):
# # actual array size
# self.__N = self.__initial_length
# # the next place to put a value in the buffer
# # also the number of rows that have been filled
# self.__n = 0
# # allocate the initial data
# self.__data = np.zeros((self.__N, self.__cols), dtype=self.__dtype)
#
# def append(self, value):
# # convert the appended object to an array if it starts as something else
# if type(value) is not np.ndarray:
# value = np.array(value)
# # add the data
# if value.ndim == 1:
# # adding a single row of data
# n = self.__n
# if n + 1 > self.__N:
# # need to allocate more memory
# self.__N += self.__n_grow
# self.__data = np.resize(self.__data, (self.__N, self.__cols))
# self.__data[n] = value
# self.__n = n + 1
# elif value.ndim == 2:
# # adding multiple rows of data
# # avoid loops for appending large arrays
# n = self.__n
# L = value.shape[0]
# N_needed = n + L - self.__N
# if N_needed > 0:
# # need to allocate more memory
# self.__N += (N_needed / self.__n_grow + 1) * self.__n_grow
# self.__data = np.resize(self.__data, (self.__N, self.__cols))
# self.__data[n:n+L] = value
# self.__n += L
#
# def __as_array(self):
# return self.__data[:self.__n]
#
# # some standard array methods
#
# @property
# def shape(self):
# return (self.__n, self.__cols)
#
# def __getitem__(self, key):
# return self.__as_array().__getitem__(key)
#
# def __iter__(self):
# return self.__as_array().__iter__()
#
# def __len__(self):
# return self.__n
#
# def __repr__(self):
# return self.__as_array().__repr__()
#
# def __setitem__(self, key, value):
# return self.__as_array().__setitem__(key, value)
#
# def __str__(self):
# return self.__as_array().__str__()
#
# def sum(self, *args, **kwargs):
# return self.__as_array().sum(*args, **kwargs)
. Output only the next line. | private.data = GrowableArray(cols=2, length=1000) |
Continue the code snippet: <|code_start|> pluck = w_pluck.value
monitor = w_monitor.value
N_tfft = w_N_tfft.value
N_tfft_display = w_N_tfft_display.value
drag = w_drag.value
messages.write('\n=== WAVES ===============================\n')
# spatial domain data and initial condition
N_pluck = int(round(N*pluck))
data_x = np.linspace(0.0, L, N+1)
ratio = (dt*c/(data_x[1]-data_x[0]))**2
data_y = np.zeros(N+1, float)
data_y[0:N_pluck+1] = np.linspace(0.0, 1.0, N_pluck+1)
data_y[N_pluck:] = np.linspace(1.0, 0.0, N-N_pluck+1)
data_y[N_pluck] = 1
data_y[-1] = 0
plot_1.set_data('xy', np.column_stack((data_x, data_y)))
last_data_y = data_y.copy()
last_last_data_y = data_y.copy()
# initialize last_data_y: need to take a 'half step'
last_data_y[1:-1] = last_last_data_y[1:-1] \
+0.5*ratio*(last_last_data_y[2:]+last_last_data_y[0:-2]-2*last_last_data_y[1:-1])
# spatial domain fft
spatial_fft_data_y = np.zeros(2*N, np.float)
spatial_fft_data_y[0:N+1] = data_y[:]
spatial_fft_data_y[N+1:] = -data_y[-2:0:-1]
spatial_fft_y = np.fft.rfft(spatial_fft_data_y)
spatial_fft_x = np.arange(spatial_fft_y.shape[0])
plot_2.set_data('xf', np.column_stack((spatial_fft_x, abs(spatial_fft_y))))
# time domain data stored in RingBuffer
N_monitor = int(round(N*monitor))
<|code_end|>
. Use current file imports:
import numpy as np
from pythics.lib import CircularArray
and context (classes, functions, or code) from other files:
# Path: pythics/lib.py
# class CircularArray(object):
# def __init__(self, length, cols=1, dtype=np.float64):
# self.__cols = cols
# # actual array size is twice the requested
# self.__N = int(length)
# # the next place to put a value in the buffer
# self.__n_next = 0
# self.__data = np.zeros((2*self.__N, self.__cols), dtype=dtype)
# # the number of rows that have been filled, max is self.__N
# self.__n_filled = 0
# # properties of arrays
# self.ndim = 2
#
# def clear(self):
# self.__n_filled = 0
#
# def append(self, value):
# # convert the appended object to an array if it starts as something else
# if type(value) is not np.ndarray:
# value = np.array(value)
# # add the data
# if value.ndim == 1:
# # adding a single row of data
# # put data in two places so we can always find a contiguous array
# n = self.__n_next
# m = n + self.__N
# self.__data[n] = value
# self.__data[m] = value
# self.__n_next = (self.__n_next + 1) % self.__N
# self.__n_filled = min(self.__n_filled+1, self.__N)
# elif value.ndim == 2:
# # adding multiple rows of data
# # avoid loops for appending large arrays
# n = self.__n_next
# m = n + self.__N
# L = value.shape[0]
# # grab only last N elements if value array is too long
# if L > self.__N:
# L = self.__N
# value = value[-L:]
# # n is smaller, so writing is contiguous starting at n
# self.__data[n:n+L] = value
# # writing at m must generally be broken up into two parts
# # the second part must be wrapped around
# wrapped_L = m + L - 2*self.__N
# if wrapped_L <= 0:
# # no need for wrapping
# self.__data[m:m+L] = value
# else:
# unwrapped_L = L - wrapped_L
# self.__data[m:m+unwrapped_L] = value[0:unwrapped_L]
# self.__data[0:wrapped_L] = value[unwrapped_L:L]
# self.__n_next = (self.__n_next + L) % self.__N
# self.__n_filled = min(self.__n_filled+L, self.__N)
#
# def __as_array(self):
# # choose the copy of the data which is guaranteed to be contiguous
# n = ((self.__n_next - 1) % self.__N) + self.__N + 1
# return self.__data[n-self.__n_filled:n]
#
# # some standard array methods
#
# @property
# def shape(self):
# return (self.__n_filled, self.__cols)
#
# def __getitem__(self, key):
# return self.__as_array().__getitem__(key)
#
# def __iter__(self):
# return self.__as_array().__iter__()
#
# def __len__(self):
# return self.__n_filled
#
# def __repr__(self):
# return self.__as_array().__repr__()
#
# def __setitem__(self, key, value):
# # this is inefficient but simple
# # rewrite the whole array for any change
# a = self.__as_array()
# a.__setitem__(key, value)
# self.clear()
# self.append(a)
#
# def __str__(self):
# return self.__as_array().__str__()
#
# def sum(self, *args, **kwargs):
# return self.__as_array().sum(*args, **kwargs)
. Output only the next line. | data_yt = CircularArray(length=N_tfft, cols=2) |
Based on the snippet: <|code_start|># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
'''Generate SQL that will create a suitable schema for storing data
from ATOC .TSI timetable files. This is done dynamically to ensure it
keeps in sync with the definitions in nrcif.py, tsi_reader.py and
nrcif_fields.py'''
def gen_sql(DDL, CONS):
SCHEMA = "tsi"
DDL.write('-- SQL DDL for data extracted from ATOC .TSI interchange \n'
'-- files in CSV format. Auto-generated by schemagen_tsi.py\n\n')
DDL.write("CREATE SCHEMA {0};\nSET search_path TO {0},public;\n\n"
.format(SCHEMA))
DDL.write('''-- Only one table\n''')
DDL.write("CREATE TABLE tsi (\n")
first_field = False
<|code_end|>
, predict the immediate next line with the help of imports:
from ..tsi_reader import TSI
and context (classes, functions, sometimes code) from other files:
# Path: nrcif/tsi_reader.py
# class TSI(object):
# '''A simple hander for TSI files.'''
#
# layout = [TextField("Station code", 3),
# TextField("Arriving train TOC", 2),
# TextField("Departing train TOC", 2),
# IntegerField("Minimum Interchange Time", 2),
# VarTextField("Comments", 100)]
#
# def __init__(self, cur):
#
# self.cur = cur
#
# def process(self, record):
# '''TSI files are in a simple CSV format with five columns. This
# function takes in a record and produces the appropriate SQL to insert
# the data into the database.'''
#
# fields = record.rstrip().split(",")
# if len(fields) != 5:
# raise ValueError("Line {} in the TSI file does not have "
# "five fields".format(record))
#
# result = [None] * 5
# for i in range(0, 5):
# result[i] = self.layout[i].read(fields[i])
#
# self.cur.execute("INSERT INTO tsi.tsi VALUES(%s,%s,%s,%s,%s);", result)
. Output only the next line. | for i in TSI.layout: |
Given the following code snippet before the placeholder: <|code_start|># Copyright 2013 - 2016, James Humphry
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
'''tsi_reader - Read ATOC TOC Specific Interchange times
This module reads data from a TSI file from ATOC containing additional
information on the interchange times between train companies at certain
TOCs (for example, where a particular company has its own set of
platforms at some distance from the others.'''
class TSI(object):
'''A simple hander for TSI files.'''
<|code_end|>
, predict the next line using imports from the current file:
from nrcif.fields import TextField, IntegerField, VarTextField
import nrcif.mockdb
and context including class names, function names, and sometimes code from other files:
# Path: nrcif/fields.py
# class TextField(CIFField):
# '''Represents a CIF field simply stored as text'''
#
# py_type = str
#
# def __init__(self, name, width):
# self.name = name
# self.width = width
# self.sql_type = "CHAR({})".format(width)
#
# class IntegerField(CIFField):
# '''Represents a CIF field simply stored as an integer'''
#
# sql_type = "INTEGER"
# py_type = int
#
# def __init__(self, name, width, optional=False):
# self.name = name
# self.width = width
# self.optional = optional
#
# def read(self, text):
# if self.optional and text.isspace():
# return None
# else:
# return int(text)
#
# class VarTextField(CIFField):
# '''Represents a CIF field simply stored as text'''
#
# py_type = str
#
# def __init__(self, name, width):
# self.name = name
# self.width = width
# self.sql_type = "VARCHAR({})".format(width)
. Output only the next line. | layout = [TextField("Station code", 3), |
Using the snippet: <|code_start|># it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
'''tsi_reader - Read ATOC TOC Specific Interchange times
This module reads data from a TSI file from ATOC containing additional
information on the interchange times between train companies at certain
TOCs (for example, where a particular company has its own set of
platforms at some distance from the others.'''
class TSI(object):
'''A simple hander for TSI files.'''
layout = [TextField("Station code", 3),
TextField("Arriving train TOC", 2),
TextField("Departing train TOC", 2),
<|code_end|>
, determine the next line of code. You have imports:
from nrcif.fields import TextField, IntegerField, VarTextField
import nrcif.mockdb
and context (class names, function names, or code) available:
# Path: nrcif/fields.py
# class TextField(CIFField):
# '''Represents a CIF field simply stored as text'''
#
# py_type = str
#
# def __init__(self, name, width):
# self.name = name
# self.width = width
# self.sql_type = "CHAR({})".format(width)
#
# class IntegerField(CIFField):
# '''Represents a CIF field simply stored as an integer'''
#
# sql_type = "INTEGER"
# py_type = int
#
# def __init__(self, name, width, optional=False):
# self.name = name
# self.width = width
# self.optional = optional
#
# def read(self, text):
# if self.optional and text.isspace():
# return None
# else:
# return int(text)
#
# class VarTextField(CIFField):
# '''Represents a CIF field simply stored as text'''
#
# py_type = str
#
# def __init__(self, name, width):
# self.name = name
# self.width = width
# self.sql_type = "VARCHAR({})".format(width)
. Output only the next line. | IntegerField("Minimum Interchange Time", 2), |
Given the code snippet: <|code_start|># the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
'''tsi_reader - Read ATOC TOC Specific Interchange times
This module reads data from a TSI file from ATOC containing additional
information on the interchange times between train companies at certain
TOCs (for example, where a particular company has its own set of
platforms at some distance from the others.'''
class TSI(object):
'''A simple hander for TSI files.'''
layout = [TextField("Station code", 3),
TextField("Arriving train TOC", 2),
TextField("Departing train TOC", 2),
IntegerField("Minimum Interchange Time", 2),
<|code_end|>
, generate the next line using the imports in this file:
from nrcif.fields import TextField, IntegerField, VarTextField
import nrcif.mockdb
and context (functions, classes, or occasionally code) from other files:
# Path: nrcif/fields.py
# class TextField(CIFField):
# '''Represents a CIF field simply stored as text'''
#
# py_type = str
#
# def __init__(self, name, width):
# self.name = name
# self.width = width
# self.sql_type = "CHAR({})".format(width)
#
# class IntegerField(CIFField):
# '''Represents a CIF field simply stored as an integer'''
#
# sql_type = "INTEGER"
# py_type = int
#
# def __init__(self, name, width, optional=False):
# self.name = name
# self.width = width
# self.optional = optional
#
# def read(self, text):
# if self.optional and text.isspace():
# return None
# else:
# return int(text)
#
# class VarTextField(CIFField):
# '''Represents a CIF field simply stored as text'''
#
# py_type = str
#
# def __init__(self, name, width):
# self.name = name
# self.width = width
# self.sql_type = "VARCHAR({})".format(width)
. Output only the next line. | VarTextField("Comments", 100)] |
Based on the snippet: <|code_start|># Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
'''Generate SQL that will create a suitable schema for storing data
from ATOC .ALF additional fixed link files. This is done dynamically to
ensure it keeps in sync with the definitions in nrcif.py, alf_reader.py
and nrcif_fields.py'''
def gen_sql(DDL, CONS):
SCHEMA = "alf"
DDL.write('-- SQL DDL for data extracted from ATOC .ALF fixed link files\n'
'-- in CSV format. Auto-generated by schemagen_alf.py\n\n')
CONS.write('-- SQL constraints & indexes definitions for data extracted \n'
'-- from ATOC .ALF timetable files in CSV format. \n'
'-- Auto-generated by schemagen_alf.py\n\n')
DDL.write("CREATE SCHEMA {0};\nSET search_path TO {0},public;\n\n"
.format(SCHEMA))
CONS.write("SET search_path TO {0},public;\n\n".format(SCHEMA))
DDL.write('''-- Only one table\n''')
DDL.write("CREATE TABLE alf (\n")
first_field = False
<|code_end|>
, predict the immediate next line with the help of imports:
from ..alf_reader import ALF
and context (classes, functions, sometimes code) from other files:
# Path: nrcif/alf_reader.py
# class ALF(object):
# '''A simple hander for ALF files.'''
#
# layout = collections.OrderedDict()
# layout["M"] = VarTextChoiceField("Mode", 8, ("BUS", "TUBE", "WALK",
# "FERRY", "METRO",
# "TRAM", "TAXI",
# "TRANSFER"))
# layout["O"] = TextField("Origin", 3)
# layout["D"] = TextField("Destination", 3)
# # changed to avoid clash with keyword
# layout["T"] = IntegerField("Link Time", 3)
# layout["S"] = TimeField("Start Time")
# layout["E"] = TimeField("End Time")
# layout["P"] = IntegerField("Priority", 1)
# layout["F"] = DD_MM_YYYYDateField("Start Date")
# layout["U"] = DD_MM_YYYYDateField("End Date")
# layout["R"] = DaysField("Days of Week")
#
# def __init__(self, cur):
#
# self.cur = cur
# self.sql_insert = "INSERT INTO alf.alf VALUES({})"\
# .format(",".join(["%s"]*10))
#
# def process(self, record):
# '''ALF files are in a CSV format with KEY=VALUE in each column. This
# function takes in a record and produces the appropriate SQL to insert
# the data into the database.'''
# fields = record.rstrip().split(",")
#
# values = {}
# for i in fields:
# key, ignore, value = i.partition("=")
# values[key] = self.layout[key].read(value)
#
# result = []
# for i in self.layout:
# if i in values:
# result.append(values[i])
# else:
# result.append(None)
#
# self.cur.execute(self.sql_insert, result)
. Output only the next line. | for i in ALF.layout: |
Given the code snippet: <|code_start|># You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
'''Generate SQL that will create a suitable schema for storing data
from ATOC .MCA timetable files. This is done dynamically to ensure it
keeps in sync with the definitions in nrcif.py and nrcif_fields.py'''
def gen_sql(DDL, CONS):
SCHEMA = "mca"
DDL.write('-- SQL DDL for data extracted from ATOC .MCA timetable files\n'
'-- in NR CIF format. Auto-generated by schemagen_mca.py\n\n')
CONS.write('-- SQL constraints & indexes definitions for data extracted\n'
'-- from ATOC .MCA timetable files in NR CIF format.\n'
'-- Auto-generated by schemagen_mca.py\n\n')
DDL.write("CREATE SCHEMA {0};\nSET search_path TO {0},public;\n\n"
.format(SCHEMA))
CONS.write("SET search_path TO {0},public;\n\n".format(SCHEMA))
DDL.write('-- The BS, BX and TN records are stored in the same table\n')
DDL.write("CREATE TABLE basic_schedule (\n")
<|code_end|>
, generate the next line using the imports in this file:
from ..records import layouts
and context (functions, classes, or occasionally code) from other files:
# Path: nrcif/records.py
. Output only the next line. | DDL.write(layouts['BS'].generate_sql_ddl()+",\n") |
Here is a snippet: <|code_start|># Copyright 2013 - 2016, James Humphry
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
'''Generate SQL that will create a suitable schema for storing data
from ATOC .ZTR timetable files. This is done dynamically to ensure it
keeps in sync with the definitions in nrcif.py, ztr_reader.py and
nrcif_fields.py'''
def gen_sql(DDL, CONS):
SCHEMA = "ztr"
<|code_end|>
. Write the next line using the current file imports:
from ..records import layouts as mca_layouts
from ..ztr_reader import reduced_hd, corrected_bx
and context from other files:
# Path: nrcif/records.py
#
# Path: nrcif/ztr_reader.py
# class ZTR(nrcif.mca_reader.MCA):
# def __init__(self, cur):
, which may include functions, classes, or code. Output only the next line. | layouts = mca_layouts.copy() |
Given the code snippet: <|code_start|>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
'''Generate SQL that will create a suitable schema for storing data
from ATOC .ZTR timetable files. This is done dynamically to ensure it
keeps in sync with the definitions in nrcif.py, ztr_reader.py and
nrcif_fields.py'''
def gen_sql(DDL, CONS):
SCHEMA = "ztr"
layouts = mca_layouts.copy()
<|code_end|>
, generate the next line using the imports in this file:
from ..records import layouts as mca_layouts
from ..ztr_reader import reduced_hd, corrected_bx
and context (functions, classes, or occasionally code) from other files:
# Path: nrcif/records.py
#
# Path: nrcif/ztr_reader.py
# class ZTR(nrcif.mca_reader.MCA):
# def __init__(self, cur):
. Output only the next line. | layouts["HD"] = reduced_hd |
Given the following code snippet before the placeholder: <|code_start|># This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
'''Generate SQL that will create a suitable schema for storing data
from ATOC .ZTR timetable files. This is done dynamically to ensure it
keeps in sync with the definitions in nrcif.py, ztr_reader.py and
nrcif_fields.py'''
def gen_sql(DDL, CONS):
SCHEMA = "ztr"
layouts = mca_layouts.copy()
layouts["HD"] = reduced_hd
<|code_end|>
, predict the next line using imports from the current file:
from ..records import layouts as mca_layouts
from ..ztr_reader import reduced_hd, corrected_bx
and context including class names, function names, and sometimes code from other files:
# Path: nrcif/records.py
#
# Path: nrcif/ztr_reader.py
# class ZTR(nrcif.mca_reader.MCA):
# def __init__(self, cur):
. Output only the next line. | layouts["BX"] = corrected_bx |
Predict the next line for this snippet: <|code_start|># You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
'''Generate SQL that will create a suitable schema for storing data
from ATOC .MSN timetable files. This is done dynamically to ensure it
keeps in sync with the definitions in nrcif.py and nrcif_fields.py'''
def gen_sql(DDL, CONS):
SCHEMA = "msn"
DDL.write('-- SQL DDL for data extracted from ATOC .MSN timetable files\n'
'-- in NR CIF format. Auto-generated by schemagen_msn.py\n\n')
CONS.write('-- SQL constraints & indexes definitions for data extracted\n'
'-- from ATOC .MSN timetable files in NR CIF format. \n'
'-- Auto-generated by schemagen_msn.py\n\n')
DDL.write('CREATE SCHEMA {0};\n'
'SET search_path TO {0},public;\n\n'.format(SCHEMA))
CONS.write("SET search_path TO {0},public;\n\n".format(SCHEMA))
normal_template = "CREATE TABLE {} (\n"
for i in ('A', 'L', 'V'):
<|code_end|>
with the help of current file imports:
from ..msn_records import layouts
and context from other files:
# Path: nrcif/msn_records.py
, which may contain function names, class names, or code. Output only the next line. | tablename = layouts[i].name.lower().replace(" ", "_") |
Using the snippet: <|code_start|>
def download_workflow():
utils.download_workflow()
def update_postrun_json_init(input_json, output_json):
utils.update_postrun_json_init(input_json, output_json)
def update_postrun_json_upload_output(input_json, execution_metadata_file, md5file, output_json, language, endpoint_url):
utils.update_postrun_json_upload_output(input_json, execution_metadata_file, md5file, output_json, language, endpoint_url=endpoint_url)
def upload_postrun_json(input_json):
utils.upload_postrun_json(input_json)
def update_postrun_json_final(input_json, output_json, logfile):
utils.update_postrun_json_final(input_json, output_json, logfile)
def main(Subcommands=Subcommands):
"""
Execute the program from the command line
"""
scs = Subcommands()
# the primary parser is used for awsf -v or -h
primary_parser = argparse.ArgumentParser(prog=PACKAGE_NAME, add_help=False)
primary_parser.add_argument('-v', '--version', action='version',
<|code_end|>
, determine the next line of code. You have imports:
import argparse
import inspect
from tibanna._version import __version__ # for now use the same version as tibanna
from . import utils
and context (class names, function names, or code) available:
# Path: tibanna/_version.py
. Output only the next line. | version='%(prog)s ' + __version__) |
Using the snippet: <|code_start|> "MaxAttempts": 10000,
"BackoffRate": 1.0
},
{
"ErrorEquals": ["EC2InstanceLimitWaitException"],
"IntervalSeconds": 600,
"MaxAttempts": 1008, # 1 wk
"BackoffRate": 1.0
},
lambda_error_retry_condition
]
sfn_check_task_retry_conditions = [
{
"ErrorEquals": ["EC2StartingException"],
"IntervalSeconds": 300,
"MaxAttempts": 25,
"BackoffRate": 1.0
},
{
"ErrorEquals": ["StillRunningException"],
"IntervalSeconds": 300,
"MaxAttempts": 100000,
"BackoffRate": 1.0
},
lambda_error_retry_condition
]
def __init__(self,
dev_suffix=None,
<|code_end|>
, determine the next line of code. You have imports:
from .vars import AWS_REGION, AWS_ACCOUNT_NUMBER
from .utils import create_tibanna_suffix
from .iam_utils import IAM
and context (class names, function names, or code) available:
# Path: tibanna/vars.py
# AWS_REGION = os.environ.get('TIBANNA_AWS_REGION', '')
#
# AWS_ACCOUNT_NUMBER = os.environ.get('AWS_ACCOUNT_NUMBER', '')
#
# Path: tibanna/utils.py
# def create_tibanna_suffix(suffix, usergroup):
# if usergroup and suffix:
# function_name_suffix = usergroup + '_' + suffix
# elif suffix:
# function_name_suffix = suffix
# elif usergroup:
# function_name_suffix = usergroup
# else:
# function_name_suffix = ''
#
# if function_name_suffix:
# return '_' + function_name_suffix
# else:
# return ''
. Output only the next line. | region_name=AWS_REGION, |
Given the following code snippet before the placeholder: <|code_start|> "BackoffRate": 1.0
},
{
"ErrorEquals": ["EC2InstanceLimitWaitException"],
"IntervalSeconds": 600,
"MaxAttempts": 1008, # 1 wk
"BackoffRate": 1.0
},
lambda_error_retry_condition
]
sfn_check_task_retry_conditions = [
{
"ErrorEquals": ["EC2StartingException"],
"IntervalSeconds": 300,
"MaxAttempts": 25,
"BackoffRate": 1.0
},
{
"ErrorEquals": ["StillRunningException"],
"IntervalSeconds": 300,
"MaxAttempts": 100000,
"BackoffRate": 1.0
},
lambda_error_retry_condition
]
def __init__(self,
dev_suffix=None,
region_name=AWS_REGION,
<|code_end|>
, predict the next line using imports from the current file:
from .vars import AWS_REGION, AWS_ACCOUNT_NUMBER
from .utils import create_tibanna_suffix
from .iam_utils import IAM
and context including class names, function names, and sometimes code from other files:
# Path: tibanna/vars.py
# AWS_REGION = os.environ.get('TIBANNA_AWS_REGION', '')
#
# AWS_ACCOUNT_NUMBER = os.environ.get('AWS_ACCOUNT_NUMBER', '')
#
# Path: tibanna/utils.py
# def create_tibanna_suffix(suffix, usergroup):
# if usergroup and suffix:
# function_name_suffix = usergroup + '_' + suffix
# elif suffix:
# function_name_suffix = suffix
# elif usergroup:
# function_name_suffix = usergroup
# else:
# function_name_suffix = ''
#
# if function_name_suffix:
# return '_' + function_name_suffix
# else:
# return ''
. Output only the next line. | aws_acc=AWS_ACCOUNT_NUMBER, |
Predict the next line for this snippet: <|code_start|> ]
sfn_check_task_retry_conditions = [
{
"ErrorEquals": ["EC2StartingException"],
"IntervalSeconds": 300,
"MaxAttempts": 25,
"BackoffRate": 1.0
},
{
"ErrorEquals": ["StillRunningException"],
"IntervalSeconds": 300,
"MaxAttempts": 100000,
"BackoffRate": 1.0
},
lambda_error_retry_condition
]
def __init__(self,
dev_suffix=None,
region_name=AWS_REGION,
aws_acc=AWS_ACCOUNT_NUMBER,
usergroup=None):
self.dev_suffix = dev_suffix
self.region_name = region_name
self.aws_acc = aws_acc
self.usergroup = usergroup
@property
def lambda_suffix(self):
<|code_end|>
with the help of current file imports:
from .vars import AWS_REGION, AWS_ACCOUNT_NUMBER
from .utils import create_tibanna_suffix
from .iam_utils import IAM
and context from other files:
# Path: tibanna/vars.py
# AWS_REGION = os.environ.get('TIBANNA_AWS_REGION', '')
#
# AWS_ACCOUNT_NUMBER = os.environ.get('AWS_ACCOUNT_NUMBER', '')
#
# Path: tibanna/utils.py
# def create_tibanna_suffix(suffix, usergroup):
# if usergroup and suffix:
# function_name_suffix = usergroup + '_' + suffix
# elif suffix:
# function_name_suffix = suffix
# elif usergroup:
# function_name_suffix = usergroup
# else:
# function_name_suffix = ''
#
# if function_name_suffix:
# return '_' + function_name_suffix
# else:
# return ''
, which may contain function names, class names, or code. Output only the next line. | return create_tibanna_suffix(self.dev_suffix, self.usergroup) |
Predict the next line after this snippet: <|code_start|>
config = {
'function_name': 'check_task_awsem',
'function_module': 'service',
'function_handler': 'handler',
'handler': 'service.handler',
'region': AWS_REGION,
'runtime': 'python3.6',
'role': 'tibanna_lambda_init_role',
'description': 'check status of AWSEM run by interegating appropriate files on S3 ',
'timeout': 300,
'memory_size': 256
}
def handler(event, context):
<|code_end|>
using the current file's imports:
from tibanna.check_task import check_task
from tibanna.vars import AWS_REGION
and any relevant context from other files:
# Path: tibanna/check_task.py
# def check_task(input_json):
# return CheckTask(input_json).run()
#
# Path: tibanna/vars.py
# AWS_REGION = os.environ.get('TIBANNA_AWS_REGION', '')
. Output only the next line. | return check_task(event) |
Given snippet: <|code_start|>
config = {
'function_name': 'check_task_awsem',
'function_module': 'service',
'function_handler': 'handler',
'handler': 'service.handler',
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from tibanna.check_task import check_task
from tibanna.vars import AWS_REGION
and context:
# Path: tibanna/check_task.py
# def check_task(input_json):
# return CheckTask(input_json).run()
#
# Path: tibanna/vars.py
# AWS_REGION = os.environ.get('TIBANNA_AWS_REGION', '')
which might include code, classes, or functions. Output only the next line. | 'region': AWS_REGION, |
Based on the snippet: <|code_start|>
class StepFunctionCostUpdater(object):
sfn_type = SFN_TYPE
def __init__(self,
dev_suffix=None,
<|code_end|>
, predict the immediate next line with the help of imports:
from .vars import (
AWS_REGION,
AWS_ACCOUNT_NUMBER,
SFN_TYPE,
UPDATE_COST_LAMBDA_NAME
)
from .utils import create_tibanna_suffix
from .iam_utils import IAM
and context (classes, functions, sometimes code) from other files:
# Path: tibanna/vars.py
# AWS_REGION = os.environ.get('TIBANNA_AWS_REGION', '')
#
# AWS_ACCOUNT_NUMBER = os.environ.get('AWS_ACCOUNT_NUMBER', '')
#
# SFN_TYPE = 'unicorn'
#
# UPDATE_COST_LAMBDA_NAME = 'update_cost_awsem'
#
# Path: tibanna/utils.py
# def create_tibanna_suffix(suffix, usergroup):
# if usergroup and suffix:
# function_name_suffix = usergroup + '_' + suffix
# elif suffix:
# function_name_suffix = suffix
# elif usergroup:
# function_name_suffix = usergroup
# else:
# function_name_suffix = ''
#
# if function_name_suffix:
# return '_' + function_name_suffix
# else:
# return ''
. Output only the next line. | region_name=AWS_REGION, |
Given snippet: <|code_start|>
class StepFunctionCostUpdater(object):
sfn_type = SFN_TYPE
def __init__(self,
dev_suffix=None,
region_name=AWS_REGION,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .vars import (
AWS_REGION,
AWS_ACCOUNT_NUMBER,
SFN_TYPE,
UPDATE_COST_LAMBDA_NAME
)
from .utils import create_tibanna_suffix
from .iam_utils import IAM
and context:
# Path: tibanna/vars.py
# AWS_REGION = os.environ.get('TIBANNA_AWS_REGION', '')
#
# AWS_ACCOUNT_NUMBER = os.environ.get('AWS_ACCOUNT_NUMBER', '')
#
# SFN_TYPE = 'unicorn'
#
# UPDATE_COST_LAMBDA_NAME = 'update_cost_awsem'
#
# Path: tibanna/utils.py
# def create_tibanna_suffix(suffix, usergroup):
# if usergroup and suffix:
# function_name_suffix = usergroup + '_' + suffix
# elif suffix:
# function_name_suffix = suffix
# elif usergroup:
# function_name_suffix = usergroup
# else:
# function_name_suffix = ''
#
# if function_name_suffix:
# return '_' + function_name_suffix
# else:
# return ''
which might include code, classes, or functions. Output only the next line. | aws_acc=AWS_ACCOUNT_NUMBER, |
Here is a snippet: <|code_start|> return "arn:aws:lambda:" + self.region_name + ":" + self.aws_acc + ":function:"
@property
def sfn_name(self):
return 'tibanna_' + self.sfn_type + self.lambda_suffix + '_costupdater'
@property
def iam(self):
return IAM(self.usergroup)
@property
def sfn_role_arn(self):
sfn_role_arn = "arn:aws:iam::" + self.aws_acc + ":role/" + \
self.iam.role_name('stepfunction')
return sfn_role_arn
@property
def sfn_start_lambda(self):
return 'Wait'
@property
def sfn_state_defs(self):
state_defs = {
"Wait": {
"Type": "Wait",
"Seconds": 43200, # Check every 12h
"Next": "UpdateCostAwsem"
},
"UpdateCostAwsem": {
"Type": "Task",
<|code_end|>
. Write the next line using the current file imports:
from .vars import (
AWS_REGION,
AWS_ACCOUNT_NUMBER,
SFN_TYPE,
UPDATE_COST_LAMBDA_NAME
)
from .utils import create_tibanna_suffix
from .iam_utils import IAM
and context from other files:
# Path: tibanna/vars.py
# AWS_REGION = os.environ.get('TIBANNA_AWS_REGION', '')
#
# AWS_ACCOUNT_NUMBER = os.environ.get('AWS_ACCOUNT_NUMBER', '')
#
# SFN_TYPE = 'unicorn'
#
# UPDATE_COST_LAMBDA_NAME = 'update_cost_awsem'
#
# Path: tibanna/utils.py
# def create_tibanna_suffix(suffix, usergroup):
# if usergroup and suffix:
# function_name_suffix = usergroup + '_' + suffix
# elif suffix:
# function_name_suffix = suffix
# elif usergroup:
# function_name_suffix = usergroup
# else:
# function_name_suffix = ''
#
# if function_name_suffix:
# return '_' + function_name_suffix
# else:
# return ''
, which may include functions, classes, or code. Output only the next line. | "Resource": self.lambda_arn_prefix + UPDATE_COST_LAMBDA_NAME + self.lambda_suffix, |
Given the code snippet: <|code_start|>
class StepFunctionCostUpdater(object):
sfn_type = SFN_TYPE
def __init__(self,
dev_suffix=None,
region_name=AWS_REGION,
aws_acc=AWS_ACCOUNT_NUMBER,
usergroup=None):
self.dev_suffix = dev_suffix
self.region_name = region_name
self.aws_acc = aws_acc
self.usergroup = usergroup
@property
def lambda_suffix(self):
<|code_end|>
, generate the next line using the imports in this file:
from .vars import (
AWS_REGION,
AWS_ACCOUNT_NUMBER,
SFN_TYPE,
UPDATE_COST_LAMBDA_NAME
)
from .utils import create_tibanna_suffix
from .iam_utils import IAM
and context (functions, classes, or occasionally code) from other files:
# Path: tibanna/vars.py
# AWS_REGION = os.environ.get('TIBANNA_AWS_REGION', '')
#
# AWS_ACCOUNT_NUMBER = os.environ.get('AWS_ACCOUNT_NUMBER', '')
#
# SFN_TYPE = 'unicorn'
#
# UPDATE_COST_LAMBDA_NAME = 'update_cost_awsem'
#
# Path: tibanna/utils.py
# def create_tibanna_suffix(suffix, usergroup):
# if usergroup and suffix:
# function_name_suffix = usergroup + '_' + suffix
# elif suffix:
# function_name_suffix = suffix
# elif usergroup:
# function_name_suffix = usergroup
# else:
# function_name_suffix = ''
#
# if function_name_suffix:
# return '_' + function_name_suffix
# else:
# return ''
. Output only the next line. | return create_tibanna_suffix(self.dev_suffix, self.usergroup) |
Given snippet: <|code_start|>
def test_upload():
randomstr = 'test-' + create_jobid()
os.mkdir(randomstr)
filepath = os.path.join(os.path.abspath(randomstr), randomstr)
with open(filepath, 'w') as f:
f.write('haha')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
import os
import shutil
import boto3
from tibanna.utils import (
create_jobid,
upload
)
and context:
# Path: tibanna/utils.py
# def create_jobid():
# return randomword(12) # date+random_string
#
# def upload(filepath, bucket, prefix='', public=True, encrypt_s3_upload=False, kms_key_id=None):
# """ Uploads a file to S3 under a prefix.
# The original directory structure is removed
# and only the filename is preserved.
# If filepath is none, upload an empty file with prefix
# itself as key
# If encrypt_s3_upload is True, default Server-Side encryption is enabled
# If kms_key_id is True as well, Server-Side encryption with the given key_id is enabled
# """
# if public:
# acl = 'public-read'
# else:
# acl = 'private'
# s3 = boto3.client('s3')
# if encrypt_s3_upload:
# upload_extra_args = {'ServerSideEncryption': 'aws:kms'}
# if kms_key_id:
# upload_extra_args['SSEKMSKeyId'] = kms_key_id
# else:
# upload_extra_args = {}
# if filepath:
# dirname, filename = os.path.split(filepath)
# key = os.path.join(prefix, filename)
# logger.debug('filepath=%s, filename=%s, key=%s' % (filepath, filename, key))
# content_type = mimetypes.guess_type(filename)[0]
# if content_type is None:
# content_type = 'binary/octet-stream'
# upload_extra_args.update({'ContentType': content_type})
# try:
# upload_extra_args.update({'ACL': acl})
# s3.upload_file(filepath, bucket, key, ExtraArgs=upload_extra_args)
# except Exception as e:
# upload_extra_args.update({'ACL': 'private'})
# s3.upload_file(filepath, bucket, key, ExtraArgs=upload_extra_args)
# else:
# try:
# s3.put_object(Body=b'', Bucket=bucket, Key=prefix, ACL=acl, **upload_extra_args)
# except Exception as e:
# s3.put_object(Body=b'', Bucket=bucket, Key=prefix, ACL='private', **upload_extra_args)
which might include code, classes, or functions. Output only the next line. | upload(filepath, 'tibanna-output', 'uploadtest') |
Based on the snippet: <|code_start|>
@pytest.fixture()
def check_task_input():
return {"config": {"log_bucket": "tibanna-output"},
"jobid": "test_job",
"push_error_to_end": True
}
@pytest.fixture()
def s3(check_task_input):
bucket_name = check_task_input['config']['log_bucket']
return boto3.resource('s3').Bucket(bucket_name)
@pytest.mark.webtest
def test_check_task_awsem_fails_if_no_job_started(check_task_input, s3):
# ensure there is no job started
jobid = 'notmyjobid'
check_task_input_modified = check_task_input
check_task_input_modified['jobid'] = jobid
check_task_input_modified['config']['start_time'] = datetime.strftime(datetime.now(tzutc()) - timedelta(minutes=4),
AWSEM_TIME_STAMP_FORMAT)
job_started = "%s.job_started" % jobid
s3.delete_objects(Delete={'Objects': [{'Key': job_started}]})
with pytest.raises(EC2StartingException) as excinfo:
<|code_end|>
, predict the immediate next line with the help of imports:
from tibanna.lambdas import check_task_awsem as service
from tibanna.exceptions import (
EC2StartingException,
StillRunningException,
MetricRetrievalException,
EC2IdleException,
JobAbortedException
)
from datetime import datetime, timedelta
from dateutil.tz import tzutc
from tibanna.vars import AWSEM_TIME_STAMP_FORMAT
import pytest
import boto3
import random
import string
import json
and context (classes, functions, sometimes code) from other files:
# Path: tibanna/lambdas/check_task_awsem.py
# def handler(event, context):
#
# Path: tibanna/exceptions.py
# class EC2StartingException(Exception):
# """EC2 AWSEM instance is still starting (job not complete)"""
# pass
#
# class StillRunningException(Exception):
# """EC2 AWSEM instance is still running (job not complete)"""
# pass
#
# class MetricRetrievalException(Exception):
# pass
#
# class EC2IdleException(Exception):
# pass
#
# class JobAbortedException(Exception):
# pass
#
# Path: tibanna/vars.py
# AWSEM_TIME_STAMP_FORMAT = '%Y%m%d-%H:%M:%S-UTC'
. Output only the next line. | service.handler(check_task_input_modified, '') |
Here is a snippet: <|code_start|>
@pytest.fixture()
def check_task_input():
return {"config": {"log_bucket": "tibanna-output"},
"jobid": "test_job",
"push_error_to_end": True
}
@pytest.fixture()
def s3(check_task_input):
bucket_name = check_task_input['config']['log_bucket']
return boto3.resource('s3').Bucket(bucket_name)
@pytest.mark.webtest
def test_check_task_awsem_fails_if_no_job_started(check_task_input, s3):
# ensure there is no job started
jobid = 'notmyjobid'
check_task_input_modified = check_task_input
check_task_input_modified['jobid'] = jobid
check_task_input_modified['config']['start_time'] = datetime.strftime(datetime.now(tzutc()) - timedelta(minutes=4),
AWSEM_TIME_STAMP_FORMAT)
job_started = "%s.job_started" % jobid
s3.delete_objects(Delete={'Objects': [{'Key': job_started}]})
<|code_end|>
. Write the next line using the current file imports:
from tibanna.lambdas import check_task_awsem as service
from tibanna.exceptions import (
EC2StartingException,
StillRunningException,
MetricRetrievalException,
EC2IdleException,
JobAbortedException
)
from datetime import datetime, timedelta
from dateutil.tz import tzutc
from tibanna.vars import AWSEM_TIME_STAMP_FORMAT
import pytest
import boto3
import random
import string
import json
and context from other files:
# Path: tibanna/lambdas/check_task_awsem.py
# def handler(event, context):
#
# Path: tibanna/exceptions.py
# class EC2StartingException(Exception):
# """EC2 AWSEM instance is still starting (job not complete)"""
# pass
#
# class StillRunningException(Exception):
# """EC2 AWSEM instance is still running (job not complete)"""
# pass
#
# class MetricRetrievalException(Exception):
# pass
#
# class EC2IdleException(Exception):
# pass
#
# class JobAbortedException(Exception):
# pass
#
# Path: tibanna/vars.py
# AWSEM_TIME_STAMP_FORMAT = '%Y%m%d-%H:%M:%S-UTC'
, which may include functions, classes, or code. Output only the next line. | with pytest.raises(EC2StartingException) as excinfo: |
Using the snippet: <|code_start|> jobid = 'notmyjobid'
check_task_input_modified = check_task_input
check_task_input_modified['jobid'] = jobid
check_task_input_modified['config']['start_time'] = datetime.strftime(datetime.now(tzutc()) - timedelta(minutes=13),
AWSEM_TIME_STAMP_FORMAT)
job_started = "%s.job_started" % jobid
s3.delete_objects(Delete={'Objects': [{'Key': job_started}]})
with pytest.raises(EC2IdleException) as excinfo:
service.handler(check_task_input_modified, '')
assert 'Failed to find jobid' in str(excinfo.value)
def test_check_task_awsem_aborted(check_task_input, s3):
jobid = 'lalala'
check_task_input_modified = check_task_input
check_task_input_modified['jobid'] = jobid
job_started = "%s.job_started" % jobid
job_aborted = "%s.aborted" % jobid
s3.put_object(Body=b'', Key=job_started)
s3.put_object(Body=b'', Key=job_aborted)
with pytest.raises(JobAbortedException) as excinfo:
service.handler(check_task_input, '')
assert 'aborted' in str(excinfo.value)
# cleanup
s3.delete_objects(Delete={'Objects': [{'Key': job_started}]})
s3.delete_objects(Delete={'Objects': [{'Key': job_aborted}]})
@pytest.mark.webtest
def test_check_task_awsem_throws_exception_if_not_done(check_task_input):
<|code_end|>
, determine the next line of code. You have imports:
from tibanna.lambdas import check_task_awsem as service
from tibanna.exceptions import (
EC2StartingException,
StillRunningException,
MetricRetrievalException,
EC2IdleException,
JobAbortedException
)
from datetime import datetime, timedelta
from dateutil.tz import tzutc
from tibanna.vars import AWSEM_TIME_STAMP_FORMAT
import pytest
import boto3
import random
import string
import json
and context (class names, function names, or code) available:
# Path: tibanna/lambdas/check_task_awsem.py
# def handler(event, context):
#
# Path: tibanna/exceptions.py
# class EC2StartingException(Exception):
# """EC2 AWSEM instance is still starting (job not complete)"""
# pass
#
# class StillRunningException(Exception):
# """EC2 AWSEM instance is still running (job not complete)"""
# pass
#
# class MetricRetrievalException(Exception):
# pass
#
# class EC2IdleException(Exception):
# pass
#
# class JobAbortedException(Exception):
# pass
#
# Path: tibanna/vars.py
# AWSEM_TIME_STAMP_FORMAT = '%Y%m%d-%H:%M:%S-UTC'
. Output only the next line. | with pytest.raises(StillRunningException) as excinfo: |
Based on the snippet: <|code_start|> assert 'aborted' in str(excinfo.value)
# cleanup
s3.delete_objects(Delete={'Objects': [{'Key': job_started}]})
s3.delete_objects(Delete={'Objects': [{'Key': job_aborted}]})
@pytest.mark.webtest
def test_check_task_awsem_throws_exception_if_not_done(check_task_input):
with pytest.raises(StillRunningException) as excinfo:
service.handler(check_task_input, '')
assert 'still running' in str(excinfo.value)
assert 'error' not in check_task_input
@pytest.mark.webtest
def test_check_task_awsem(check_task_input, s3):
jobid = 'lalala'
check_task_input_modified = check_task_input
check_task_input_modified['jobid'] = jobid
job_started = "%s.job_started" % jobid
s3.put_object(Body=b'', Key=job_started)
job_success = "%s.success" % jobid
s3.put_object(Body=b'', Key=job_success)
postrunjson = "%s.postrun.json" % jobid
jsondict = {"config": {"log_bucket": "somelogbucket"},
"Job": {"JOBID": jobid, "start_time": '20190814-21:01:07-UTC',
"App": {}, "Output": {},
"Input": {'Input_files_data': {}, 'Input_parameters': {}, 'Secondary_files_data': {}}}}
jsoncontent = json.dumps(jsondict)
s3.put_object(Body=jsoncontent.encode(), Key=postrunjson)
<|code_end|>
, predict the immediate next line with the help of imports:
from tibanna.lambdas import check_task_awsem as service
from tibanna.exceptions import (
EC2StartingException,
StillRunningException,
MetricRetrievalException,
EC2IdleException,
JobAbortedException
)
from datetime import datetime, timedelta
from dateutil.tz import tzutc
from tibanna.vars import AWSEM_TIME_STAMP_FORMAT
import pytest
import boto3
import random
import string
import json
and context (classes, functions, sometimes code) from other files:
# Path: tibanna/lambdas/check_task_awsem.py
# def handler(event, context):
#
# Path: tibanna/exceptions.py
# class EC2StartingException(Exception):
# """EC2 AWSEM instance is still starting (job not complete)"""
# pass
#
# class StillRunningException(Exception):
# """EC2 AWSEM instance is still running (job not complete)"""
# pass
#
# class MetricRetrievalException(Exception):
# pass
#
# class EC2IdleException(Exception):
# pass
#
# class JobAbortedException(Exception):
# pass
#
# Path: tibanna/vars.py
# AWSEM_TIME_STAMP_FORMAT = '%Y%m%d-%H:%M:%S-UTC'
. Output only the next line. | with pytest.raises(MetricRetrievalException) as excinfo: |
Given the following code snippet before the placeholder: <|code_start|>def s3(check_task_input):
bucket_name = check_task_input['config']['log_bucket']
return boto3.resource('s3').Bucket(bucket_name)
@pytest.mark.webtest
def test_check_task_awsem_fails_if_no_job_started(check_task_input, s3):
# ensure there is no job started
jobid = 'notmyjobid'
check_task_input_modified = check_task_input
check_task_input_modified['jobid'] = jobid
check_task_input_modified['config']['start_time'] = datetime.strftime(datetime.now(tzutc()) - timedelta(minutes=4),
AWSEM_TIME_STAMP_FORMAT)
job_started = "%s.job_started" % jobid
s3.delete_objects(Delete={'Objects': [{'Key': job_started}]})
with pytest.raises(EC2StartingException) as excinfo:
service.handler(check_task_input_modified, '')
assert 'Failed to find jobid' in str(excinfo.value)
@pytest.mark.webtest
def test_check_task_awsem_fails_if_no_job_started_for_too_long(check_task_input, s3):
# ensure there is no job started
jobid = 'notmyjobid'
check_task_input_modified = check_task_input
check_task_input_modified['jobid'] = jobid
check_task_input_modified['config']['start_time'] = datetime.strftime(datetime.now(tzutc()) - timedelta(minutes=13),
AWSEM_TIME_STAMP_FORMAT)
job_started = "%s.job_started" % jobid
s3.delete_objects(Delete={'Objects': [{'Key': job_started}]})
<|code_end|>
, predict the next line using imports from the current file:
from tibanna.lambdas import check_task_awsem as service
from tibanna.exceptions import (
EC2StartingException,
StillRunningException,
MetricRetrievalException,
EC2IdleException,
JobAbortedException
)
from datetime import datetime, timedelta
from dateutil.tz import tzutc
from tibanna.vars import AWSEM_TIME_STAMP_FORMAT
import pytest
import boto3
import random
import string
import json
and context including class names, function names, and sometimes code from other files:
# Path: tibanna/lambdas/check_task_awsem.py
# def handler(event, context):
#
# Path: tibanna/exceptions.py
# class EC2StartingException(Exception):
# """EC2 AWSEM instance is still starting (job not complete)"""
# pass
#
# class StillRunningException(Exception):
# """EC2 AWSEM instance is still running (job not complete)"""
# pass
#
# class MetricRetrievalException(Exception):
# pass
#
# class EC2IdleException(Exception):
# pass
#
# class JobAbortedException(Exception):
# pass
#
# Path: tibanna/vars.py
# AWSEM_TIME_STAMP_FORMAT = '%Y%m%d-%H:%M:%S-UTC'
. Output only the next line. | with pytest.raises(EC2IdleException) as excinfo: |
Here is a snippet: <|code_start|> job_started = "%s.job_started" % jobid
s3.delete_objects(Delete={'Objects': [{'Key': job_started}]})
with pytest.raises(EC2StartingException) as excinfo:
service.handler(check_task_input_modified, '')
assert 'Failed to find jobid' in str(excinfo.value)
@pytest.mark.webtest
def test_check_task_awsem_fails_if_no_job_started_for_too_long(check_task_input, s3):
# ensure there is no job started
jobid = 'notmyjobid'
check_task_input_modified = check_task_input
check_task_input_modified['jobid'] = jobid
check_task_input_modified['config']['start_time'] = datetime.strftime(datetime.now(tzutc()) - timedelta(minutes=13),
AWSEM_TIME_STAMP_FORMAT)
job_started = "%s.job_started" % jobid
s3.delete_objects(Delete={'Objects': [{'Key': job_started}]})
with pytest.raises(EC2IdleException) as excinfo:
service.handler(check_task_input_modified, '')
assert 'Failed to find jobid' in str(excinfo.value)
def test_check_task_awsem_aborted(check_task_input, s3):
jobid = 'lalala'
check_task_input_modified = check_task_input
check_task_input_modified['jobid'] = jobid
job_started = "%s.job_started" % jobid
job_aborted = "%s.aborted" % jobid
s3.put_object(Body=b'', Key=job_started)
s3.put_object(Body=b'', Key=job_aborted)
<|code_end|>
. Write the next line using the current file imports:
from tibanna.lambdas import check_task_awsem as service
from tibanna.exceptions import (
EC2StartingException,
StillRunningException,
MetricRetrievalException,
EC2IdleException,
JobAbortedException
)
from datetime import datetime, timedelta
from dateutil.tz import tzutc
from tibanna.vars import AWSEM_TIME_STAMP_FORMAT
import pytest
import boto3
import random
import string
import json
and context from other files:
# Path: tibanna/lambdas/check_task_awsem.py
# def handler(event, context):
#
# Path: tibanna/exceptions.py
# class EC2StartingException(Exception):
# """EC2 AWSEM instance is still starting (job not complete)"""
# pass
#
# class StillRunningException(Exception):
# """EC2 AWSEM instance is still running (job not complete)"""
# pass
#
# class MetricRetrievalException(Exception):
# pass
#
# class EC2IdleException(Exception):
# pass
#
# class JobAbortedException(Exception):
# pass
#
# Path: tibanna/vars.py
# AWSEM_TIME_STAMP_FORMAT = '%Y%m%d-%H:%M:%S-UTC'
, which may include functions, classes, or code. Output only the next line. | with pytest.raises(JobAbortedException) as excinfo: |
Here is a snippet: <|code_start|>
@pytest.fixture()
def check_task_input():
return {"config": {"log_bucket": "tibanna-output"},
"jobid": "test_job",
"push_error_to_end": True
}
@pytest.fixture()
def s3(check_task_input):
bucket_name = check_task_input['config']['log_bucket']
return boto3.resource('s3').Bucket(bucket_name)
@pytest.mark.webtest
def test_check_task_awsem_fails_if_no_job_started(check_task_input, s3):
# ensure there is no job started
jobid = 'notmyjobid'
check_task_input_modified = check_task_input
check_task_input_modified['jobid'] = jobid
check_task_input_modified['config']['start_time'] = datetime.strftime(datetime.now(tzutc()) - timedelta(minutes=4),
<|code_end|>
. Write the next line using the current file imports:
from tibanna.lambdas import check_task_awsem as service
from tibanna.exceptions import (
EC2StartingException,
StillRunningException,
MetricRetrievalException,
EC2IdleException,
JobAbortedException
)
from datetime import datetime, timedelta
from dateutil.tz import tzutc
from tibanna.vars import AWSEM_TIME_STAMP_FORMAT
import pytest
import boto3
import random
import string
import json
and context from other files:
# Path: tibanna/lambdas/check_task_awsem.py
# def handler(event, context):
#
# Path: tibanna/exceptions.py
# class EC2StartingException(Exception):
# """EC2 AWSEM instance is still starting (job not complete)"""
# pass
#
# class StillRunningException(Exception):
# """EC2 AWSEM instance is still running (job not complete)"""
# pass
#
# class MetricRetrievalException(Exception):
# pass
#
# class EC2IdleException(Exception):
# pass
#
# class JobAbortedException(Exception):
# pass
#
# Path: tibanna/vars.py
# AWSEM_TIME_STAMP_FORMAT = '%Y%m%d-%H:%M:%S-UTC'
, which may include functions, classes, or code. Output only the next line. | AWSEM_TIME_STAMP_FORMAT) |
Predict the next line for this snippet: <|code_start|>
top_contents = """
Timestamp: 2020-12-18-18:55:37
top - 18:55:37 up 4 days, 3:18, 2 users, load average: 2.00, 2.00, 2.30
Tasks: 344 total, 1 running, 343 sleeping, 0 stopped, 0 zombie
%Cpu(s): 6.6 us, 0.1 sy, 0.0 ni, 93.2 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem : 12971188+total, 95469344 free, 28933200 used, 5309352 buff/cache
KiB Swap: 0 total, 0 free, 0 used. 10002531+avail Mem
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
16962 root 20 0 36.456g 0.011t 19372 S 93.8 8.9 125:11.21 java -jar somejar.jar
17086 root 20 0 36.464g 0.016t 19572 S 70.0 13.0 178:59.28 bwa mem
17919 ubuntu 20 0 40676 3828 3144 R 6.2 0.0 0:00.01 top -b -n1 -c -i -w 10000
Timestamp: 2020-12-18-18:56:37
top - 18:56:37 up 4 days, 3:18, 2 users, load average: 2.00, 2.00, 2.30
Tasks: 344 total, 1 running, 343 sleeping, 0 stopped, 0 zombie
%Cpu(s): 6.6 us, 0.1 sy, 0.0 ni, 93.2 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem : 12971188+total, 95469344 free, 28933200 used, 5309352 buff/cache
KiB Swap: 0 total, 0 free, 0 used. 10002531+avail Mem
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
16962 root 20 0 36.456g 0.011t 19372 S 92.8 9.9 125:11.21 java -jar somejar.jar
17919 ubuntu 20 0 40676 3828 3144 R 5.2 0.0 0:00.01 top -b -n1 -c -i -w 10000
"""
def test_empty_top():
<|code_end|>
with the help of current file imports:
import os
from tibanna import top
and context from other files:
# Path: tibanna/top.py
# class Top(object):
# class Process(object):
# def __init__(self, contents):
# def parse_contents(self, contents):
# def digest(self, max_n_commands=16, sort_by='alphabetical'):
# def get_collapsed_commands(self, max_n_commands):
# def write_to_csv(self, csv_file, metric='cpu', delimiter=',', colname_for_timestamps='timepoints',
# timestamp_start=None, timestamp_end=None, base=0):
# def should_skip_process(self, process):
# def convert_command_to_collapsed_command(cmd, collapsed_commands):
# def total_cpu_per_command(self, command):
# def total_mem_per_command(self, command):
# def sort_commands(self, by='cpu'):
# def as_minutes(cls, timestamp, timestamp_start):
# def timestamps_as_minutes(self, timestamp_start):
# def as_datetime(cls, timestamp):
# def wrap_in_double_quotes(string):
# def first_words(string, n_words):
# def first_characters(string, n_letters):
# def as_dict(self):
# def __init__(self, top_line):
# def as_dict(self):
, which may contain function names, class names, or code. Output only the next line. | top1 = top.Top('') |
Here is a snippet: <|code_start|>
config = {
'function_name': 'run_task_awsem',
'function_module': 'service',
'function_handler': 'handler',
'handler': 'service.handler',
'region': AWS_REGION,
'runtime': 'python3.6',
'role': 'tibanna_lambda_init_role',
'description': 'launch an ec2 instance',
'timeout': 300,
'memory_size': 256
}
def handler(event, context):
<|code_end|>
. Write the next line using the current file imports:
from tibanna.run_task import run_task
from tibanna.vars import AWS_REGION
and context from other files:
# Path: tibanna/run_task.py
# def run_task(input_json):
# '''
# config:
# # required
# instance_type: EC2 instance type
# ebs_size: EBS storage size in GB
# ebs_type: EBS storage type (available values: gp2, io1, st1, sc1, standard (default: io1)
# ebs_iops: EBS storage IOPS
# ebs_throughput: EBS throughput for GP3 types
# password: password for ssh connection for user ec2-user
# EBS_optimized: Use this flag if the instance type is EBS-optimized (default: EBS-optimized)
# shutdown_min: Number of minutes before shutdown after the jobs are finished. (default now)
# log_bucket: bucket for collecting logs (started, postrun, success, error, log)
# # optional
# public_postrun_json (optional): whether postrun json should be made public (default false)
# cloudwatch_dashboard (optional) : create a cloudwatch dashboard named awsem-<jobid>
#
# args:
# # required (i.e. field must exist):
# input_files: input files in json format (parametername: {'bucket_name':bucketname, 'object_key':filename})
# output_S3_bucket: bucket name and subdirectory for output files and logs
# # optional
# app_name: name of the app, used by Benchmark
# app_version: version of the app
# secondary_files: secondary files in json format (parametername: {'bucket_name':bucketnname, 'object_ke':filename})
# input_parameters: input parameters in json format (parametername:value)
# secondary_output_target: secondary output files in json format (similar to secondary_files)
# # required for cwl
# cwl_main_filename: main cwl file name
# cwl_directory_url: the url (http:// or s3://) in which the cwl files resides
# cwl_version: the version of cwl (now only 'v1' is supported)
# cwl_child_filenames (optional): names of the other cwl files used by main cwl file, delimited by comma
# language (optional for cwl): now only 'cwl_v1' is supported
# # required for wdl
# language: 'wdl' (='wdl_draft2'), 'wdl_v1', or 'wdl_draft2'
# wdl_main_filename: main wdl file name
# wdl_directory_url: the url (http:// or s3://) in which the wdl files resides
# wdl_child_filenames (optional): names of the other wdl files used by main wdl file, delimited by comma
# # required for snakemake
# language: 'snakemake'
# snakemake_main_filename: main snakemake file name
# snakemake_directory_url: the url (http:// or s3://) in which the snakemake files resides
# snakemake_child_filenames (optional): names of the other snakemake files, delimited by comma
# # optional
# dependency: {'exec_arn': [exec_arns]}
# spot_duration: 60 # block minutes 60-360 if requesting spot instance
# '''
# # profile
# if TIBANNA_PROFILE_ACCESS_KEY and TIBANNA_PROFILE_SECRET_KEY:
# profile = {'access_key': TIBANNA_PROFILE_ACCESS_KEY,
# 'secret_key': TIBANNA_PROFILE_SECRET_KEY}
# else:
# profile = None
#
# execution = Execution(input_json)
# execution.prelaunch(profile=profile)
# execution.launch()
# execution.postlaunch()
# return(execution.input_dict)
#
# Path: tibanna/vars.py
# AWS_REGION = os.environ.get('TIBANNA_AWS_REGION', '')
, which may include functions, classes, or code. Output only the next line. | return run_task(event) |
Predict the next line after this snippet: <|code_start|>
config = {
'function_name': 'run_task_awsem',
'function_module': 'service',
'function_handler': 'handler',
'handler': 'service.handler',
<|code_end|>
using the current file's imports:
from tibanna.run_task import run_task
from tibanna.vars import AWS_REGION
and any relevant context from other files:
# Path: tibanna/run_task.py
# def run_task(input_json):
# '''
# config:
# # required
# instance_type: EC2 instance type
# ebs_size: EBS storage size in GB
# ebs_type: EBS storage type (available values: gp2, io1, st1, sc1, standard (default: io1)
# ebs_iops: EBS storage IOPS
# ebs_throughput: EBS throughput for GP3 types
# password: password for ssh connection for user ec2-user
# EBS_optimized: Use this flag if the instance type is EBS-optimized (default: EBS-optimized)
# shutdown_min: Number of minutes before shutdown after the jobs are finished. (default now)
# log_bucket: bucket for collecting logs (started, postrun, success, error, log)
# # optional
# public_postrun_json (optional): whether postrun json should be made public (default false)
# cloudwatch_dashboard (optional) : create a cloudwatch dashboard named awsem-<jobid>
#
# args:
# # required (i.e. field must exist):
# input_files: input files in json format (parametername: {'bucket_name':bucketname, 'object_key':filename})
# output_S3_bucket: bucket name and subdirectory for output files and logs
# # optional
# app_name: name of the app, used by Benchmark
# app_version: version of the app
# secondary_files: secondary files in json format (parametername: {'bucket_name':bucketnname, 'object_ke':filename})
# input_parameters: input parameters in json format (parametername:value)
# secondary_output_target: secondary output files in json format (similar to secondary_files)
# # required for cwl
# cwl_main_filename: main cwl file name
# cwl_directory_url: the url (http:// or s3://) in which the cwl files resides
# cwl_version: the version of cwl (now only 'v1' is supported)
# cwl_child_filenames (optional): names of the other cwl files used by main cwl file, delimited by comma
# language (optional for cwl): now only 'cwl_v1' is supported
# # required for wdl
# language: 'wdl' (='wdl_draft2'), 'wdl_v1', or 'wdl_draft2'
# wdl_main_filename: main wdl file name
# wdl_directory_url: the url (http:// or s3://) in which the wdl files resides
# wdl_child_filenames (optional): names of the other wdl files used by main wdl file, delimited by comma
# # required for snakemake
# language: 'snakemake'
# snakemake_main_filename: main snakemake file name
# snakemake_directory_url: the url (http:// or s3://) in which the snakemake files resides
# snakemake_child_filenames (optional): names of the other snakemake files, delimited by comma
# # optional
# dependency: {'exec_arn': [exec_arns]}
# spot_duration: 60 # block minutes 60-360 if requesting spot instance
# '''
# # profile
# if TIBANNA_PROFILE_ACCESS_KEY and TIBANNA_PROFILE_SECRET_KEY:
# profile = {'access_key': TIBANNA_PROFILE_ACCESS_KEY,
# 'secret_key': TIBANNA_PROFILE_SECRET_KEY}
# else:
# profile = None
#
# execution = Execution(input_json)
# execution.prelaunch(profile=profile)
# execution.launch()
# execution.postlaunch()
# return(execution.input_dict)
#
# Path: tibanna/vars.py
# AWS_REGION = os.environ.get('TIBANNA_AWS_REGION', '')
. Output only the next line. | 'region': AWS_REGION, |
Predict the next line for this snippet: <|code_start|>
def test_general_awsem_error_msg():
eh = AWSEMErrorHandler()
res = eh.general_awsem_error_msg('somejobid')
assert res == 'Job encountered an error check log using tibanna log --job-id=somejobid [--sfn=stepfunction]'
def test_general_awsem_check_log_msg():
eh = AWSEMErrorHandler()
res = eh.general_awsem_check_log_msg('somejobid')
assert res == 'check log using tibanna log --job-id=somejobid [--sfn=stepfunction]'
def test_awsem_exception_not_enough_space_for_input():
log = "sometext some text some other text " + \
"download failed: s3://somebucket/somefile to ../../data1/input/somefile " + \
"[Errno 28] No space left on device " + \
"some other text some other text"
eh = AWSEMErrorHandler()
res = eh.parse_log(log)
assert res
<|code_end|>
with the help of current file imports:
import pytest
from tibanna.exceptions import (
AWSEMErrorHandler,
AWSEMJobErrorException
)
and context from other files:
# Path: tibanna/exceptions.py
# class AWSEMErrorHandler(object):
#
# def __init__(self):
# self.ErrorList = self._ErrorList # initial error list, custom errors can be added
#
# class AWSEMError(object):
# def __init__(self, error_type, pattern_in_log, multiline=False):
# self.error_type = error_type
# if multiline:
# self.pattern_in_log = re.compile(pattern_in_log, re.MULTILINE)
# else:
# self.pattern_in_log = pattern_in_log
#
# def add_custom_errors(self, custom_err_list):
# """add custom errors to ErrorList.
# custom_err_list is a list of dictionaries w/ keys 'error_type', 'pattern', 'multiline'"""
# for err in custom_err_list:
# self.ErrorList.append(self.AWSEMError(err['error_type'], err['pattern'], err.get('multiline', False)))
#
# @property
# def _ErrorList(self):
# """add any specific error types with recognizable strings or patterns here.
# the order is important. The earlier ones are checked first and if there is a match,
# the later ones will not be checked."""
# return [
# # input download failure due to not enough disk space
# self.AWSEMError('Not enough space for input files', 'download failed: .+ No space left on device'),
# # Docker pull failure due to not enough root disk space
# self.AWSEMError('No space for docker', 'failed to register layer.+no space left on device'),
# # not enough disk space
# self.AWSEMError('Not enough space', '.+No space left on device'),
# # CWL missing input error
# self.AWSEMError('CWL missing input', 'Missing required input parameter\n.+\n', True),
# # Bucket access error
# self.AWSEMError('Bucket/file access denied', 'when calling the ListObjectsV2 operation: Access Denied')
# ]
#
# def parse_log(self, log):
# # for ex in self.AWSEMErrorExceptionList:
# for ex in self.ErrorList:
# res = re.search(ex.pattern_in_log, log)
# if res:
# match = res.string[res.regs[0][0]:res.regs[0][1]]
# match = re.sub('\n', ' ', match) # \n not recognized and subsequent content is dropped from Exception
# match = re.sub(' +', ' ', match)
# msg = "%s: %s" % (ex.error_type, match)
# return AWSEMJobErrorException(msg)
# return
#
# @property
# def general_awsem_check_log_msg_template(self):
# return "check log using tibanna log --job-id=%s [--sfn=stepfunction]"
#
# def general_awsem_check_log_msg(self, job_id):
# return self.general_awsem_check_log_msg_template % job_id
#
# @property
# def general_awsem_error_msg_template(self):
# return "Job encountered an error " + self.general_awsem_check_log_msg_template
#
# def general_awsem_error_msg(self, job_id):
# return self.general_awsem_error_msg_template % job_id
#
# class AWSEMJobErrorException(Exception):
# """There is an error from a worklow run on the EC2 AWSEM instance."""
# pass
, which may contain function names, class names, or code. Output only the next line. | with pytest.raises(AWSEMJobErrorException) as exec_info: |
Next line prediction: <|code_start|>
def test_combine_two():
x = combine_two('a', 'b')
assert x == 'a/b'
x = combine_two(['a1', 'a2'], ['b1', 'b2'])
assert x == ['a1/b1', 'a2/b2']
x = combine_two([['a1', 'a2'], ['b1', 'b2']], [['c1', 'c2'], ['d1', 'd2']])
assert x == [['a1/c1', 'a2/c2'], ['b1/d1', 'b2/d2']]
x = combine_two([[['a1', 'a2'], ['b1', 'b2']], [['c1', 'c2'], ['d1', 'd2']]],
[[['e1', 'e2'], ['f1', 'f2']], [['g1', 'g2'], ['h1', 'h2']]])
assert x == [[['a1/e1', 'a2/e2'], ['b1/f1', 'b2/f2']],
[['c1/g1', 'c2/g2'], ['d1/h1', 'd2/h2']]]
def test_run_on_nested_arrays2():
def sum0(a, b):
return(a + b)
<|code_end|>
. Use current file imports:
(from tibanna.nnested_array import (
combine_two,
run_on_nested_arrays2
))
and context including class names, function names, or small code snippets from other files:
# Path: tibanna/nnested_array.py
# def combine_two(a, b, delimiter='/'):
# """returns an n-nested array of strings a+delimiter+b
# a and b (e.g. uuids and object_keys) can be a singlet,
# an array, an array of arrays or an array of arrays of arrays ...
# example:
# >>> a = ['a','b',['c','d']]
# >>> b = ['e','f',['g','h']]
# >>> combine_two(a, b)
# ['a/e','b/f',['c/g','d/h']]
# """
# if isinstance(a, list):
# if not isinstance(b, list):
# raise Exception("can't combine list and non-list")
# if len(a) != len(b):
# raise Exception("Can't combine lists of different lengths")
# return [combine_two(a_, b_) for a_, b_, in zip(a, b)]
# else:
# return(str(a) + delimiter + str(b))
#
# def run_on_nested_arrays2(a, b, func, **param):
# """run func on each pair of element in a and b:
# a and b can be singlets, an array, an array of arrays, an array of arrays of arrays ...
# The return value is a flattened array
# """
# if isinstance(a, list):
# if not isinstance(b, list):
# raise Exception("can't combine list and non-list")
# if len(a) != len(b):
# raise Exception("Can't combine lists of different lengths")
# return([run_on_nested_arrays2(a_, b_, func, **param) for a_, b_ in zip(a, b)])
# else:
# return(func(a, b, **param))
. Output only the next line. | x = run_on_nested_arrays2(1, 2, sum0) |
Predict the next line after this snippet: <|code_start|> "end_time": "20190531-04:24:55-UTC",
"filesystem": "/dev/nvme1n1",
"instance_id": "i-08d1c54ed1f74ab36",
"status": "0",
"total_input_size": "2.2G",
"total_output_size": "4.2G",
"total_tmp_size": "7.4G",
"Metrics": {
"max_mem_used_MB": 13250.1,
"min_mem_available_MB": 18547.51953125,
"total_mem_MB": 31797.67578125,
"max_mem_utilization_percent": 41.67020363737768,
"max_cpu_utilization_percent": 99.4,
"max_disk_space_utilization_percent": 40.5262269248086,
"max_disk_space_used_GB": 15
}
})
return json
@pytest.fixture
def postrun_json(postrun_json_job, run_json_config):
return {
'Job': postrun_json_job,
'config': run_json_config,
'commands': ['command1', 'command2']
}
def test_PostRunJson(postrun_json):
<|code_end|>
using the current file's imports:
import pytest
import copy
from tibanna import awsem
from tibanna.exceptions import MalFormattedRunJsonException
and any relevant context from other files:
# Path: tibanna/awsem.py
# class AwsemRunJson(SerializableObject):
# class AwsemRunJsonJob(SerializableObject):
# class AwsemRunJsonLog(SerializableObject):
# class AwsemRunJsonApp(SerializableObject):
# class AwsemRunJsonInput(SerializableObject):
# class AwsemRunJsonInputFile(SerializableObject):
# class AwsemRunJsonOutput(SerializableObject):
# class AwsemPostRunJson(AwsemRunJson):
# class AwsemPostRunJsonJob(AwsemRunJsonJob):
# class AwsemPostRunJsonOutput(AwsemRunJsonOutput):
# class AwsemPostRunJsonOutputFile(SerializableObject):
# def __init__(self, Job=None, config=None, strict=True):
# def create_Job(self, Job, strict=True):
# def __init__(self, App=None, Input=None, Output=None, JOBID='',
# start_time=None, Log=None, strict=True):
# def create_Output(self, Output):
# def update(self, **kwargs):
# def start_time_as_datetime(self):
# def __init__(self, log_bucket_directory=None):
# def __init__(self, App_name=None, App_version=None, language=None,
# cwl_url=None, main_cwl=None, other_cwl_files=None,
# wdl_url=None, main_wdl=None, other_wdl_files=None, workflow_engine=None,
# container_image=None, command=None,
# snakemake_url=None, main_snakemake=None, other_snakemake_files=None):
# def __init__(self, Input_files_data=None, Input_parameters=None, Secondary_files_data=None,
# # Input_files_reference is for older postrunjson
# # Env is missing in older postrunjson
# Input_files_reference=None, Env=None):
# def as_dict_as_cwl_input(self, input_dir='', input_mount_dir_prefix=''):
# def as_dict_as_wdl_input(self, input_dir='', input_mount_dir_prefix=''):
# def check_input_files_key_compatibility(self, language):
# def __init__(self, path, profile='', rename='', unzip='', mount=False, **kwargs): # kwargs includes 'dir' and 'class'
# def as_dict(self):
# def as_dict_as_cwl_input(self, input_dir='', input_mount_dir_prefix=''):
# def as_dict_as_wdl_input(self, input_dir='', input_mount_dir_prefix=''):
# def __init__(self, output_bucket_directory=None, output_target=None,
# secondary_output_target=None, alt_cond_output_argnames=None):
# def alt_output_target(self, argname_list):
# def __init__(self, Job=None, config=None, commands=None,log=None, strict=True):
# def add_commands(self, command):
# def create_Job(self, Job, strict=True):
# def __init__(self, App=None, Input=None, Output=None, JOBID='',
# start_time=None, end_time=None, status=None, Log=None,
# total_input_size=None, total_output_size=None, total_tmp_size=None,
# # older postrunjsons don't have these fields
# filesystem='', instance_id='', instance_availablity_zone='',
# Metrics=None, strict=True):
# def create_Output(self, Output):
# def end_time_as_datetime(self):
# def add_filesystem(self, filesystem):
# def __init__(self, output_bucket_directory=None, output_target=None,
# secondary_output_target=None, alt_cond_output_argnames=None,
# **kwargs): # kwargs includes 'Output files'
# def output_files(self):
# def add_output_files(self, output_files):
# def as_dict(self):
# def __init__(self, path, target=None, basename=None, checksum=None,
# location=None, md5sum=None, size=None, secondaryFiles=None,
# **kwargs): # kwargs includes 'class'
# def add_target(self, target):
# def as_dict(self):
# def file2cwlfile(filename, dirname, unzip):
# def file2wdlfile(filename, dirname, unzip):
#
# Path: tibanna/exceptions.py
# class MalFormattedRunJsonException(Exception):
# pass
. Output only the next line. | r = awsem.AwsemPostRunJson(**postrun_json) |
Given the code snippet: <|code_start|> assert hasattr(r, 'class_')
assert hasattr(r, 'dir_')
assert hasattr(r, 'path')
assert hasattr(r, 'profile')
assert hasattr(r, 'unzip') # default '' if omitted
assert r.class_ == 'File'
assert r.dir_ == 'somebucket'
assert r.path == 'somefilepath'
assert r.profile == ''
assert r.unzip == ''
assert r.unzip == ''
r_dict = r.as_dict()
assert 'class' in r_dict
assert 'dir' in r_dict
assert 'path' in r_dict
assert 'profile' in r_dict
assert 'unzip' in r_dict
assert 'unzip' in r_dict
assert r_dict['class'] == 'File'
assert r_dict['dir'] == 'somebucket'
assert r_dict['path'] == 'somefilepath'
assert r_dict['profile'] == ''
assert r_dict['unzip'] == ''
assert r_dict['unzip'] == ''
def test_AwsemRunJsonInputFile_rename_mount_error(run_json_inputfile):
# rename and mount cannot be used together
run_json_inputfile['rename'] = 'somerenamedpath'
run_json_inputfile['mount'] = True
<|code_end|>
, generate the next line using the imports in this file:
import pytest
import copy
from tibanna import awsem
from tibanna.exceptions import MalFormattedRunJsonException
and context (functions, classes, or occasionally code) from other files:
# Path: tibanna/awsem.py
# class AwsemRunJson(SerializableObject):
# class AwsemRunJsonJob(SerializableObject):
# class AwsemRunJsonLog(SerializableObject):
# class AwsemRunJsonApp(SerializableObject):
# class AwsemRunJsonInput(SerializableObject):
# class AwsemRunJsonInputFile(SerializableObject):
# class AwsemRunJsonOutput(SerializableObject):
# class AwsemPostRunJson(AwsemRunJson):
# class AwsemPostRunJsonJob(AwsemRunJsonJob):
# class AwsemPostRunJsonOutput(AwsemRunJsonOutput):
# class AwsemPostRunJsonOutputFile(SerializableObject):
# def __init__(self, Job=None, config=None, strict=True):
# def create_Job(self, Job, strict=True):
# def __init__(self, App=None, Input=None, Output=None, JOBID='',
# start_time=None, Log=None, strict=True):
# def create_Output(self, Output):
# def update(self, **kwargs):
# def start_time_as_datetime(self):
# def __init__(self, log_bucket_directory=None):
# def __init__(self, App_name=None, App_version=None, language=None,
# cwl_url=None, main_cwl=None, other_cwl_files=None,
# wdl_url=None, main_wdl=None, other_wdl_files=None, workflow_engine=None,
# container_image=None, command=None,
# snakemake_url=None, main_snakemake=None, other_snakemake_files=None):
# def __init__(self, Input_files_data=None, Input_parameters=None, Secondary_files_data=None,
# # Input_files_reference is for older postrunjson
# # Env is missing in older postrunjson
# Input_files_reference=None, Env=None):
# def as_dict_as_cwl_input(self, input_dir='', input_mount_dir_prefix=''):
# def as_dict_as_wdl_input(self, input_dir='', input_mount_dir_prefix=''):
# def check_input_files_key_compatibility(self, language):
# def __init__(self, path, profile='', rename='', unzip='', mount=False, **kwargs): # kwargs includes 'dir' and 'class'
# def as_dict(self):
# def as_dict_as_cwl_input(self, input_dir='', input_mount_dir_prefix=''):
# def as_dict_as_wdl_input(self, input_dir='', input_mount_dir_prefix=''):
# def __init__(self, output_bucket_directory=None, output_target=None,
# secondary_output_target=None, alt_cond_output_argnames=None):
# def alt_output_target(self, argname_list):
# def __init__(self, Job=None, config=None, commands=None,log=None, strict=True):
# def add_commands(self, command):
# def create_Job(self, Job, strict=True):
# def __init__(self, App=None, Input=None, Output=None, JOBID='',
# start_time=None, end_time=None, status=None, Log=None,
# total_input_size=None, total_output_size=None, total_tmp_size=None,
# # older postrunjsons don't have these fields
# filesystem='', instance_id='', instance_availablity_zone='',
# Metrics=None, strict=True):
# def create_Output(self, Output):
# def end_time_as_datetime(self):
# def add_filesystem(self, filesystem):
# def __init__(self, output_bucket_directory=None, output_target=None,
# secondary_output_target=None, alt_cond_output_argnames=None,
# **kwargs): # kwargs includes 'Output files'
# def output_files(self):
# def add_output_files(self, output_files):
# def as_dict(self):
# def __init__(self, path, target=None, basename=None, checksum=None,
# location=None, md5sum=None, size=None, secondaryFiles=None,
# **kwargs): # kwargs includes 'class'
# def add_target(self, target):
# def as_dict(self):
# def file2cwlfile(filename, dirname, unzip):
# def file2wdlfile(filename, dirname, unzip):
#
# Path: tibanna/exceptions.py
# class MalFormattedRunJsonException(Exception):
# pass
. Output only the next line. | with pytest.raises(MalFormattedRunJsonException) as ex: |
Next line prediction: <|code_start|>
config = {
'function_name': 'update_cost_awsem',
'function_module': 'service',
'function_handler': 'handler',
'handler': 'service.handler',
'region': AWS_REGION,
'runtime': 'python3.6',
'role': 'tibanna_lambda_init_role',
'description': 'update costs of a workflow run',
'timeout': 300,
'memory_size': 256
}
def handler(event, context):
<|code_end|>
. Use current file imports:
(from tibanna.update_cost import update_cost
from tibanna.vars import AWS_REGION)
and context including class names, function names, or small code snippets from other files:
# Path: tibanna/update_cost.py
# def update_cost(input_json):
# return UpdateCost(input_json).run()
#
# Path: tibanna/vars.py
# AWS_REGION = os.environ.get('TIBANNA_AWS_REGION', '')
. Output only the next line. | return update_cost(event) |
Predict the next line for this snippet: <|code_start|>
config = {
'function_name': 'update_cost_awsem',
'function_module': 'service',
'function_handler': 'handler',
'handler': 'service.handler',
<|code_end|>
with the help of current file imports:
from tibanna.update_cost import update_cost
from tibanna.vars import AWS_REGION
and context from other files:
# Path: tibanna/update_cost.py
# def update_cost(input_json):
# return UpdateCost(input_json).run()
#
# Path: tibanna/vars.py
# AWS_REGION = os.environ.get('TIBANNA_AWS_REGION', '')
, which may contain function names, class names, or code. Output only the next line. | 'region': AWS_REGION, |
Based on the snippet: <|code_start|> entry = ccpnProject.currentNmrEntryStore.findFirstEntry()
strucGen = entry.findFirstStructureGeneration()
refStructure = strucGen.structureEnsemble.sortedModels()[0]
if outType == "mol2":
mol2Format = Mol2Format.Mol2Format(ccpnProject)
mol2Format.writeChemComp(
resTempFile,
chemCompVar=chain.findFirstResidue().chemCompVar,
coordSystem="pdb",
minimalPrompts=True,
forceNamingSystemName="XPLOR",
)
else:
pdbFormat = PdbFormat.PdbFormat(ccpnProject)
pdbFormat.writeCoordinates(
resTempFile,
exportChains=[chain],
structures=[refStructure],
minimalPrompts=True,
forceNamingSystemName="XPLOR",
)
origCwd = os.getcwd()
os.chdir(dirTemp)
t0 = time.time()
print(header)
try:
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import random
import string
import sys
import time
import traceback
from shutil import rmtree
from ccpnmr.format.converters import Mol2Format # type: ignore
from ccpnmr.format.converters import PdbFormat # type: ignore
from acpype.cli import ACTopol, elapsedTime, header
and context (classes, functions, sometimes code) from other files:
# Path: acpype/cli.py
# def _chk_py_ver():
# def _handle_exception(level):
# def init_main(binaries: Dict[str, str] = binaries, argv: Optional[List[str]] = None):
. Output only the next line. | molecule = ACTopol( |
Given the following code snippet before the placeholder: <|code_start|> )
if not molecule.acExe:
molecule.printError("no 'antechamber' executable... aborting!")
hint1 = "HINT1: is 'AMBERHOME' environment variable set?"
hint2 = (
"HINT2: is 'antechamber' in your $PATH?"
+ " What 'which antechamber' in your terminal says?"
+ " 'alias' doesn't work for ACPYPE."
)
molecule.printMess(hint1)
molecule.printMess(hint2)
sys.exit(1)
molecule.createACTopol()
molecule.createMolTopol()
acpypeFailed = False
except Exception:
raise
_exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
print("ACPYPE FAILED: %s" % exceptionValue)
if debug:
traceback.print_tb(exceptionTraceback, file=sys.stdout)
acpypeFailed = True
execTime = int(round(time.time() - t0))
if execTime == 0:
msg = "less than a second"
else:
<|code_end|>
, predict the next line using imports from the current file:
import os
import random
import string
import sys
import time
import traceback
from shutil import rmtree
from ccpnmr.format.converters import Mol2Format # type: ignore
from ccpnmr.format.converters import PdbFormat # type: ignore
from acpype.cli import ACTopol, elapsedTime, header
and context including class names, function names, and sometimes code from other files:
# Path: acpype/cli.py
# def _chk_py_ver():
# def _handle_exception(level):
# def init_main(binaries: Dict[str, str] = binaries, argv: Optional[List[str]] = None):
. Output only the next line. | msg = elapsedTime(execTime) |
Given snippet: <|code_start|> else:
resTempFile = os.path.join(dirTemp, "%s.pdb" % resName)
entry = ccpnProject.currentNmrEntryStore.findFirstEntry()
strucGen = entry.findFirstStructureGeneration()
refStructure = strucGen.structureEnsemble.sortedModels()[0]
if outType == "mol2":
mol2Format = Mol2Format.Mol2Format(ccpnProject)
mol2Format.writeChemComp(
resTempFile,
chemCompVar=chain.findFirstResidue().chemCompVar,
coordSystem="pdb",
minimalPrompts=True,
forceNamingSystemName="XPLOR",
)
else:
pdbFormat = PdbFormat.PdbFormat(ccpnProject)
pdbFormat.writeCoordinates(
resTempFile,
exportChains=[chain],
structures=[refStructure],
minimalPrompts=True,
forceNamingSystemName="XPLOR",
)
origCwd = os.getcwd()
os.chdir(dirTemp)
t0 = time.time()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import random
import string
import sys
import time
import traceback
from shutil import rmtree
from ccpnmr.format.converters import Mol2Format # type: ignore
from ccpnmr.format.converters import PdbFormat # type: ignore
from acpype.cli import ACTopol, elapsedTime, header
and context:
# Path: acpype/cli.py
# def _chk_py_ver():
# def _handle_exception(level):
# def init_main(binaries: Dict[str, str] = binaries, argv: Optional[List[str]] = None):
which might include code, classes, or functions. Output only the next line. | print(header) |
Using the snippet: <|code_start|>
r = "<[<Atom id=3, name=C1, c3>, <Atom id=4, name=H, hc>, <Atom id=5, name=H, hc>, <Atom id=6, name=H, hc>], ang=0.00>"
def test_atom():
atom = Atom("C1", "c3", 3, 5, 12.0, 0.5, (1.0, 0.9, 0.5))
assert str(atom) == "<Atom id=3, name=C1, c3>"
def test_bond():
a1 = Atom("C1", "c3", 3, 5, 12.0, 0.5, (1.0, 0.9, 0.5))
a2 = Atom("H", "hc", 4, 5, 1.0, -0.5, (2.0, 1.9, 1.5))
bond = Bond([a1, a2], 330.0, 1.0969)
assert str(bond) == repr(bond) == "<[<Atom id=3, name=C1, c3>, <Atom id=4, name=H, hc>], r=1.0969>"
def test_angle():
a1 = Atom("C1", "c3", 3, 5, 12.0, 0.5, (1.0, 0.9, 0.5))
a2 = Atom("H", "hc", 4, 5, 1.0, -0.5, (2.0, 1.9, 1.5))
a3 = Atom("H", "hc", 5, 5, 1.0, 0.1, (0.0, 0.1, -0.5))
<|code_end|>
, determine the next line of code. You have imports:
from acpype.mol import Angle, Atom, Bond, Dihedral
and context (class names, function names, or code) available:
# Path: acpype/mol.py
# class Angle:
#
# """
# attributes: 3 Atoms, spring constant (kcal/mol/rad^2), angle eq. (rad)
# """
#
# def __init__(self, atoms, kTheta, thetaEq):
# self.atoms = atoms
# self.kTheta = kTheta
# self.thetaEq = thetaEq # rad, to convert to degree: thetaEq * 180/Pi
#
# def __str__(self):
# return f"<{self.atoms}, ang={self.thetaEq * 180 / Pi:.2f}>"
#
# def __repr__(self):
# return f"<{self.atoms}, ang={self.thetaEq * 180 / Pi:.2f}>"
#
# class Atom:
# r"""
# Atom Object Definition
#
# Charges in *prmtop* file are divided by ``18.2223`` to be converted
# in units of the electron charge.
#
# To convert ``ACOEF`` and ``BCOEF`` to ``r0`` (Å) and ``epsilon`` (ε: kcal/mol), as seen
# in ``gaff.dat`` for example, for a same atom type (``i = j``):
#
# .. math::
# r_0 &= 1/2 * (2 * A_{coef}/B_{coef})^{1/6} \\
# \epsilon &= 1/(4 * A_{coef}) * B_{coef}^2
#
# To convert ``r0`` and ``epsilon`` to ``ACOEF`` and ``BCOEF``:
#
# .. math::
# A_{coef} &= \sqrt{\epsilon_i * \epsilon_j} * (r_{0i} + r_{0j})^{12} \\
# B_{coef} &= 2 * \sqrt{\epsilon_i * \epsilon_j} * (r_{0i} + r_{0j})^6 \\
# &= 2 * A_{coef}/(r_{0i} + r_{0j})^6
#
# where index ``i`` and ``j`` for atom types.
# Coordinates are given in Å and masses in Atomic Mass Unit.
#
# Returns:
# acpype.mol.Atom: atom object
# """
#
# def __init__(
# self, atomName: str, atomType: AtomType, id_: int, resid: int, mass: float, charge: float, coord: List[float]
# ):
# """
# Args:
# atomName (str): atom name
# atomType (AtomType): atomType object
# id_ (int): atom number index
# resid (int): residues number index
# mass (float): atom mass
# charge (float): atom charge
# coord (List[float]): atom (x,y,z) coordinates
# """
# self.atomName = atomName
# self.atomType = atomType
# self.id = id_
# self.cgnr = id_
# self.resid = resid
# self.mass = mass
# self.charge = charge # / qConv
# self.coords = coord
#
# def __str__(self):
# return f"<Atom id={self.id}, name={self.atomName}, {self.atomType}>"
#
# def __repr__(self):
# return f"<Atom id={self.id}, name={self.atomName}, {self.atomType}>"
#
# class Bond:
#
# """
# attributes: pair of Atoms, spring constant (kcal/mol), dist. eq. (Ang)
# """
#
# def __init__(self, atoms, kBond, rEq):
# self.atoms = atoms
# self.kBond = kBond
# self.rEq = rEq
#
# def __str__(self):
# return f"<{self.atoms}, r={self.rEq}>"
#
# def __repr__(self):
# return f"<{self.atoms}, r={self.rEq}>"
#
# class Dihedral:
#
# """
# attributes: 4 Atoms, spring constant (kcal/mol), periodicity,
# phase (rad)
# """
#
# def __init__(self, atoms, kPhi, period, phase):
# self.atoms = atoms
# self.kPhi = kPhi
# self.period = period
# self.phase = phase # rad, to convert to degree: kPhi * 180/Pi
#
# def __str__(self):
# return f"<{self.atoms}, ang={self.phase * 180 / Pi:.2f}>"
#
# def __repr__(self):
# return f"<{self.atoms}, ang={self.phase * 180 / Pi:.2f}>"
. Output only the next line. | angle = Angle([a1, a2, a3], 46.3, 1.91637234) |
Given snippet: <|code_start|>
r = "<[<Atom id=3, name=C1, c3>, <Atom id=4, name=H, hc>, <Atom id=5, name=H, hc>, <Atom id=6, name=H, hc>], ang=0.00>"
def test_atom():
atom = Atom("C1", "c3", 3, 5, 12.0, 0.5, (1.0, 0.9, 0.5))
assert str(atom) == "<Atom id=3, name=C1, c3>"
def test_bond():
a1 = Atom("C1", "c3", 3, 5, 12.0, 0.5, (1.0, 0.9, 0.5))
a2 = Atom("H", "hc", 4, 5, 1.0, -0.5, (2.0, 1.9, 1.5))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from acpype.mol import Angle, Atom, Bond, Dihedral
and context:
# Path: acpype/mol.py
# class Angle:
#
# """
# attributes: 3 Atoms, spring constant (kcal/mol/rad^2), angle eq. (rad)
# """
#
# def __init__(self, atoms, kTheta, thetaEq):
# self.atoms = atoms
# self.kTheta = kTheta
# self.thetaEq = thetaEq # rad, to convert to degree: thetaEq * 180/Pi
#
# def __str__(self):
# return f"<{self.atoms}, ang={self.thetaEq * 180 / Pi:.2f}>"
#
# def __repr__(self):
# return f"<{self.atoms}, ang={self.thetaEq * 180 / Pi:.2f}>"
#
# class Atom:
# r"""
# Atom Object Definition
#
# Charges in *prmtop* file are divided by ``18.2223`` to be converted
# in units of the electron charge.
#
# To convert ``ACOEF`` and ``BCOEF`` to ``r0`` (Å) and ``epsilon`` (ε: kcal/mol), as seen
# in ``gaff.dat`` for example, for a same atom type (``i = j``):
#
# .. math::
# r_0 &= 1/2 * (2 * A_{coef}/B_{coef})^{1/6} \\
# \epsilon &= 1/(4 * A_{coef}) * B_{coef}^2
#
# To convert ``r0`` and ``epsilon`` to ``ACOEF`` and ``BCOEF``:
#
# .. math::
# A_{coef} &= \sqrt{\epsilon_i * \epsilon_j} * (r_{0i} + r_{0j})^{12} \\
# B_{coef} &= 2 * \sqrt{\epsilon_i * \epsilon_j} * (r_{0i} + r_{0j})^6 \\
# &= 2 * A_{coef}/(r_{0i} + r_{0j})^6
#
# where index ``i`` and ``j`` for atom types.
# Coordinates are given in Å and masses in Atomic Mass Unit.
#
# Returns:
# acpype.mol.Atom: atom object
# """
#
# def __init__(
# self, atomName: str, atomType: AtomType, id_: int, resid: int, mass: float, charge: float, coord: List[float]
# ):
# """
# Args:
# atomName (str): atom name
# atomType (AtomType): atomType object
# id_ (int): atom number index
# resid (int): residues number index
# mass (float): atom mass
# charge (float): atom charge
# coord (List[float]): atom (x,y,z) coordinates
# """
# self.atomName = atomName
# self.atomType = atomType
# self.id = id_
# self.cgnr = id_
# self.resid = resid
# self.mass = mass
# self.charge = charge # / qConv
# self.coords = coord
#
# def __str__(self):
# return f"<Atom id={self.id}, name={self.atomName}, {self.atomType}>"
#
# def __repr__(self):
# return f"<Atom id={self.id}, name={self.atomName}, {self.atomType}>"
#
# class Bond:
#
# """
# attributes: pair of Atoms, spring constant (kcal/mol), dist. eq. (Ang)
# """
#
# def __init__(self, atoms, kBond, rEq):
# self.atoms = atoms
# self.kBond = kBond
# self.rEq = rEq
#
# def __str__(self):
# return f"<{self.atoms}, r={self.rEq}>"
#
# def __repr__(self):
# return f"<{self.atoms}, r={self.rEq}>"
#
# class Dihedral:
#
# """
# attributes: 4 Atoms, spring constant (kcal/mol), periodicity,
# phase (rad)
# """
#
# def __init__(self, atoms, kPhi, period, phase):
# self.atoms = atoms
# self.kPhi = kPhi
# self.period = period
# self.phase = phase # rad, to convert to degree: kPhi * 180/Pi
#
# def __str__(self):
# return f"<{self.atoms}, ang={self.phase * 180 / Pi:.2f}>"
#
# def __repr__(self):
# return f"<{self.atoms}, ang={self.phase * 180 / Pi:.2f}>"
which might include code, classes, or functions. Output only the next line. | bond = Bond([a1, a2], 330.0, 1.0969) |
Given the code snippet: <|code_start|>
file_types = (
("file_name"),
("em_mdp"),
("AC_frcmod"),
("AC_inpcrd"),
("AC_lib"),
("AC_prmtop"),
("mol2"),
("CHARMM_inp"),
("CHARMM_prm"),
("CHARMM_rtf"),
("CNS_inp"),
("CNS_par"),
("CNS_top"),
("GMX_OPLS_itp"),
("GMX_OPLS_top"),
("GMX_gro"),
("GMX_itp"),
("GMX_top"),
("NEW_pdb"),
("md_mdp"),
)
def test_json_simple(janitor):
<|code_end|>
, generate the next line using the imports in this file:
import json
from glob import glob
from acpype.acs_api import acpype_api
and context (functions, classes, or occasionally code) from other files:
# Path: acpype/acs_api.py
# def acpype_api(
# inputFile,
# chargeType="bcc",
# chargeVal=None,
# multiplicity="1",
# atomType="gaff2",
# force=False,
# basename=None,
# debug=False,
# outTopol="all",
# engine="tleap",
# allhdg=False,
# timeTol=MAXTIME,
# qprog="sqm",
# ekFlag=None,
# verbose=True,
# gmx4=False,
# merge=False,
# direct=False,
# is_sorted=False,
# chiral=False,
# is_smiles=False,
# ):
#
# at0 = time.time()
# print(header)
#
# if debug:
# texta = "Python Version %s" % sys.version
# print("DEBUG: %s" % while_replace(texta))
# try:
# molecule = ACTopol(
# inputFile=inputFile,
# chargeType=chargeType,
# chargeVal=chargeVal,
# debug=debug,
# multiplicity=multiplicity,
# atomType=atomType,
# force=force,
# outTopol=outTopol,
# allhdg=allhdg,
# basename=basename,
# timeTol=timeTol,
# qprog=qprog,
# ekFlag=ekFlag,
# verbose=verbose,
# gmx4=gmx4,
# merge=merge,
# direct=direct,
# is_sorted=is_sorted,
# chiral=chiral,
# )
#
# molecule.createACTopol()
# molecule.createMolTopol()
#
# "Output in JSON format"
# os.chdir(molecule.absHomeDir)
# readFiles(molecule.baseName, chargeType, atomType)
# output = {
# "file_name": molecule.baseName,
# "em_mdp": em_mdp.getvalue(),
# "AC_frcmod": AC_frcmod.getvalue(),
# "AC_inpcrd": AC_inpcrd.getvalue(),
# "AC_lib": AC_lib.getvalue(),
# "AC_prmtop": AC_prmtop.getvalue(),
# "mol2": mol2.getvalue(),
# "CHARMM_inp": CHARMM_inp.getvalue(),
# "CHARMM_prm": CHARMM_prm.getvalue(),
# "CHARMM_rtf": CHARMM_rtf.getvalue(),
# "CNS_inp": CNS_inp.getvalue(),
# "CNS_par": CNS_par.getvalue(),
# "CNS_top": CNS_top.getvalue(),
# "GMX_OPLS_itp": GMX_OPLS_itp.getvalue(),
# "GMX_OPLS_top": GMX_OPLS_top.getvalue(),
# "GMX_gro": GMX_gro.getvalue(),
# "GMX_itp": GMX_itp.getvalue(),
# "GMX_top": GMX_top.getvalue(),
# "NEW_pdb": NEW_pdb.getvalue(),
# "md_mdp": md_mdp.getvalue(),
# }
#
# except Exception:
# _exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
# print("ACPYPE FAILED: %s" % exceptionValue)
# if debug:
# traceback.print_tb(exceptionTraceback, file=sys.stdout)
# output = {"file_name": f"ERROR: {str(exceptionValue)}"}
#
# execTime = int(round(time.time() - at0))
# if execTime == 0:
# amsg = "less than a second"
# else:
# amsg = elapsedTime(execTime)
# print("Total time of execution: %s" % amsg)
# clearFileInMemory()
# try:
# shutil.rmtree(molecule.absHomeDir)
# except Exception:
# print("DEBUG: No folder left to be removed")
# return json.dumps(output)
. Output only the next line. | jj = json.loads(acpype_api(inputFile="benzene.pdb", debug=True)) |
Here is a snippet: <|code_start|>"""
Script to get energies from AMBER and GROMACS
for a given system and compare them
"""
def error(v1, v2):
"""percentage relative error"""
if v1 == v2:
return 0
return abs(v1 - v2) / max(abs(v1), abs(v2)) * 100
ff = 4.1840
vv = ["ANGLE", "BOND", "DIHED", "EPTOT", "VDW14", "VDW", "QQ14", "QQ"]
norm_gmx = {"POTENTIAL": "EPTOT", "LJ-14": "VDW14", "LJ_SR": "VDW", "COULOMB-14": "QQ14", "COULOMB_SR": "QQ"}
norm_amb = {"1-4_NB": "VDW14", "VDWAALS": "VDW", "1-4_EEL": "QQ14", "EELEC": "QQ"}
(e_amb, e_gmx) = sys.argv[1:]
cmd_amb = f"cat {e_amb}"
cmd_gmx = f"echo 1 2 3 4 5 6 7 8 9 | gmx energy -f {e_gmx}.edr"
amb_out = {
y[0].upper(): float(y[1]) * ff
for y in [
<|code_end|>
. Write the next line using the current file imports:
import re
import sys
from acpype.utils import _getoutput
and context from other files:
# Path: acpype/utils.py
# def _getoutput(cmd):
# """
# To simulate commands.getoutput
# shell=True is necessary despite security issues
# """
# out = sub.Popen(cmd, shell=True, stderr=sub.STDOUT, stdout=sub.PIPE).communicate()[0][:-1]
# return out.decode()
, which may include functions, classes, or code. Output only the next line. | x.split("=") for x in re.sub(r"\s+=\s+", "=", _getoutput(cmd_amb)).strip().replace("1-4 ", "1-4_").split() |
Given the code snippet: <|code_start|>
def dotproduct(aa, bb):
"""scalar product"""
return sum((a * b) for a, b in zip(aa, bb))
def cross_product(a, b):
"""cross product"""
c = [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
return c
def length(v):
"""distance between 2 vectors"""
return math.sqrt(dotproduct(v, v))
def vec_sub(aa, bb):
"""vector A - B"""
return [a - b for a, b in zip(aa, bb)]
def imprDihAngle(a, b, c, d):
"""calculate improper dihedral angle"""
ba = vec_sub(a, b)
bc = vec_sub(c, b)
cb = vec_sub(b, c)
cd = vec_sub(d, c)
n1 = cross_product(ba, bc)
n2 = cross_product(cb, cd)
<|code_end|>
, generate the next line using the imports in this file:
import math
import os
import subprocess as sub
import sys
import warnings
import openbabel as obl
from shutil import which
from acpype.params import Pi
and context (functions, classes, or occasionally code) from other files:
# Path: acpype/params.py
# MAXTIME = 3 * 3600
# TLEAP_TEMPLATE = """
# verbosity 1
# source %(leapAmberFile)s
# source %(leapGaffFile)s
# mods = loadamberparams %(acBase)s.frcmod
# %(res)s = loadmol2 %(acMol2FileName)s
# check %(res)s
# saveamberparm %(res)s %(acBase)s.prmtop %(acBase)s.inpcrd
# saveoff %(res)s %(acBase)s.lib
# quit
# """
. Output only the next line. | angle = math.acos(dotproduct(n1, n2) / (length(n1) * length(n2))) * 180 / Pi |
Next line prediction: <|code_start|> help="print nothing (not allowed with arg -d)",
)
parser.add_argument(
"-o",
"--outtop",
choices=["all"] + outTopols,
action="store",
default="all",
dest="outtop",
help="output topologies: all (default), gmx, cns or charmm",
)
parser.add_argument(
"-z",
"--gmx4",
action="store_true",
dest="gmx4",
help="write RB dihedrals old GMX 4.0",
)
parser.add_argument(
"-t",
"--cnstop",
action="store_true",
dest="cnstop",
help="write CNS topology with allhdg-like parameters (experimental)",
)
parser.add_argument(
"-s",
"--max_time",
type=int,
action="store",
<|code_end|>
. Use current file imports:
(import argparse
from acpype.params import MAXTIME, epilog, outTopols, usage)
and context including class names, function names, or small code snippets from other files:
# Path: acpype/params.py
# MAXTIME = 3 * 3600
# TLEAP_TEMPLATE = """
# verbosity 1
# source %(leapAmberFile)s
# source %(leapGaffFile)s
# mods = loadamberparams %(acBase)s.frcmod
# %(res)s = loadmol2 %(acMol2FileName)s
# check %(res)s
# saveamberparm %(res)s %(acBase)s.prmtop %(acBase)s.inpcrd
# saveoff %(res)s %(acBase)s.lib
# quit
# """
. Output only the next line. | default=MAXTIME, |
Next line prediction: <|code_start|> "--keyword",
action="store",
dest="keyword",
help="mopac or sqm keyword, inside quotes",
)
parser.add_argument(
"-f",
"--force",
action="store_true",
dest="force",
help="force topologies recalculation anew",
)
group.add_argument(
"-d",
"--debug",
action="store_true",
dest="debug",
help="for debugging purposes, keep any temporary file created (not allowed with arg -w)",
)
group.add_argument(
"-w",
"--verboseless",
action="store_false",
default=True,
dest="verboseless",
help="print nothing (not allowed with arg -d)",
)
parser.add_argument(
"-o",
"--outtop",
<|code_end|>
. Use current file imports:
(import argparse
from acpype.params import MAXTIME, epilog, outTopols, usage)
and context including class names, function names, or small code snippets from other files:
# Path: acpype/params.py
# MAXTIME = 3 * 3600
# TLEAP_TEMPLATE = """
# verbosity 1
# source %(leapAmberFile)s
# source %(leapGaffFile)s
# mods = loadamberparams %(acBase)s.frcmod
# %(res)s = loadmol2 %(acMol2FileName)s
# check %(res)s
# saveamberparm %(res)s %(acBase)s.prmtop %(acBase)s.inpcrd
# saveoff %(res)s %(acBase)s.lib
# quit
# """
. Output only the next line. | choices=["all"] + outTopols, |
Predict the next line for this snippet: <|code_start|>
allTotal = len(ccpCodes) * 2
jobsOK = [] # list of Mols that have at least a PDB or IDEAL clean: [[both],[pdb,ideal]]
totalTxt = ""
for group in groupResults:
header, subHead, dummy, lista = group
if "Mols clean" == subHead:
jobsOK = lista
subTot = printResults(lista, subHead, header)
if not subTot:
continue
totalTxt += "+ %i " % subTot
totalTxt = totalTxt[2:]
sumVal = eval(totalTxt)
print(f"{totalTxt}= {sumVal}")
# print results
# print 'execTime', execTime
# print 'jobsOK', jobsOK
if atomicDetailed:
print("\n>>> Detailed report per atom <<<\n")
if ET1:
print("=>Mols have duplicated coordinates")
for molLabel in ET1:
mol, structure = molLabel.split("_")
cmd = f"grep -e '^ATOM' {mol}/*{structure}.out"
<|code_end|>
with the help of current file imports:
import fnmatch
import os
import sys
from acpype.utils import _getoutput
and context from other files:
# Path: acpype/utils.py
# def _getoutput(cmd):
# """
# To simulate commands.getoutput
# shell=True is necessary despite security issues
# """
# out = sub.Popen(cmd, shell=True, stderr=sub.STDOUT, stdout=sub.PIPE).communicate()[0][:-1]
# return out.decode()
, which may contain function names, class names, or code. Output only the next line. | out = _getoutput(cmd) |
Given the following code snippet before the placeholder: <|code_start|>class Bond:
"""
attributes: pair of Atoms, spring constant (kcal/mol), dist. eq. (Ang)
"""
def __init__(self, atoms, kBond, rEq):
self.atoms = atoms
self.kBond = kBond
self.rEq = rEq
def __str__(self):
return f"<{self.atoms}, r={self.rEq}>"
def __repr__(self):
return f"<{self.atoms}, r={self.rEq}>"
class Angle:
"""
attributes: 3 Atoms, spring constant (kcal/mol/rad^2), angle eq. (rad)
"""
def __init__(self, atoms, kTheta, thetaEq):
self.atoms = atoms
self.kTheta = kTheta
self.thetaEq = thetaEq # rad, to convert to degree: thetaEq * 180/Pi
def __str__(self):
<|code_end|>
, predict the next line using imports from the current file:
from typing import List
from acpype.params import Pi
and context including class names, function names, and sometimes code from other files:
# Path: acpype/params.py
# MAXTIME = 3 * 3600
# TLEAP_TEMPLATE = """
# verbosity 1
# source %(leapAmberFile)s
# source %(leapGaffFile)s
# mods = loadamberparams %(acBase)s.frcmod
# %(res)s = loadmol2 %(acMol2FileName)s
# check %(res)s
# saveamberparm %(res)s %(acBase)s.prmtop %(acBase)s.inpcrd
# saveoff %(res)s %(acBase)s.lib
# quit
# """
. Output only the next line. | return f"<{self.atoms}, ang={self.thetaEq * 180 / Pi:.2f}>" |
Predict the next line for this snippet: <|code_start|>
def test_no_ac(janitor, capsys):
binaries = {"ac_bin": "no_ac", "obabel_bin": "obabel"}
msg = f"ERROR: no '{binaries['ac_bin']}' executable... aborting!"
inp = "AAA.mol2"
with pytest.raises(SystemExit) as e_info:
<|code_end|>
with the help of current file imports:
import pytest
from acpype import cli
from acpype.utils import _getoutput
and context from other files:
# Path: acpype/cli.py
# def _chk_py_ver():
# def _handle_exception(level):
# def init_main(binaries: Dict[str, str] = binaries, argv: Optional[List[str]] = None):
#
# Path: acpype/utils.py
# def _getoutput(cmd):
# """
# To simulate commands.getoutput
# shell=True is necessary despite security issues
# """
# out = sub.Popen(cmd, shell=True, stderr=sub.STDOUT, stdout=sub.PIPE).communicate()[0][:-1]
# return out.decode()
, which may contain function names, class names, or code. Output only the next line. | cli.init_main(argv=["-di", inp, "-c", "gas"], binaries=binaries) |
Next line prediction: <|code_start|>
def test_no_ac(janitor, capsys):
binaries = {"ac_bin": "no_ac", "obabel_bin": "obabel"}
msg = f"ERROR: no '{binaries['ac_bin']}' executable... aborting!"
inp = "AAA.mol2"
with pytest.raises(SystemExit) as e_info:
cli.init_main(argv=["-di", inp, "-c", "gas"], binaries=binaries)
captured = capsys.readouterr()
assert msg in captured.out
assert e_info.typename == "SystemExit"
assert e_info.value.code == 19
def test_only_ac(janitor, capsys):
binaries = {"ac_bin": "antechamber", "obabel_bin": "no_obabel"}
msg1 = f"WARNING: no '{binaries['obabel_bin']}' executable, no PDB file can be used as input!"
msg2 = "Total time of execution:"
msg3 = "WARNING: No Openbabel python module, no chiral groups"
inp = "AAA.mol2"
temp_base = "vir_temp"
cli.init_main(argv=["-di", inp, "-c", "gas", "-b", temp_base], binaries=binaries)
captured = capsys.readouterr()
assert msg1 in captured.out
assert msg2 in captured.out
assert msg3 in captured.out
<|code_end|>
. Use current file imports:
(import pytest
from acpype import cli
from acpype.utils import _getoutput)
and context including class names, function names, or small code snippets from other files:
# Path: acpype/cli.py
# def _chk_py_ver():
# def _handle_exception(level):
# def init_main(binaries: Dict[str, str] = binaries, argv: Optional[List[str]] = None):
#
# Path: acpype/utils.py
# def _getoutput(cmd):
# """
# To simulate commands.getoutput
# shell=True is necessary despite security issues
# """
# out = sub.Popen(cmd, shell=True, stderr=sub.STDOUT, stdout=sub.PIPE).communicate()[0][:-1]
# return out.decode()
. Output only the next line. | _getoutput(f"rm -vfr {temp_base}* .*{temp_base}*") |
Given the following code snippet before the placeholder: <|code_start|>
-----------------------------------------
|-----win1------|-----win2-----|---------
-----------------------------------------
To improve efficiency, there are several method to be adopted:
1) The section that have matched, we don't search it in next time.
2) If accuracy is too low when we have finished the majority search, directly search next file.
3) Use ".so".
'''
r = com.Compare(tdata, sdata, tlen, slen, compare_config)
return r.accuracy, r.position
###########################################################
# Get audio fingerprint
###########################################################
def get_fingerprint(wdata,framerate):
'''
Compute the fingerprint.
'''
#data length
data_len = wdata.shape[-1]
#hanning window
<|code_end|>
, predict the next line using imports from the current file:
import os
import numpy as np
from ctypes import *
from auana.common import hann
and context including class names, function names, and sometimes code from other files:
# Path: auana/common.py
# def hann(M, sym=True):
# '''
# hanning window.
# '''
# # Docstring adapted from NumPy's hanning function
# if M < 1:
# return np.array([])
# if M == 1:
# return np.ones(1, 'd')
# odd = M % 2
# if not sym and not odd:
# M = M + 1
# n = np.arange(0, M)
# w = 0.5 - 0.5 * np.cos(2.0 * np.pi * n / (M - 1))
# if not sym and not odd:
# w = w[:-1]
# return w
. Output only the next line. | hanning = hann(DEF_FFT_SIZE, sym=0) |
Here is a snippet: <|code_start|>
ZCR_FALG = False
SIGNAL_START_FLAG = False
EXPECT_ZCR = int(DEF_FFT_SIZE/framerate*base_frq*2)
#data length
data_len = len(wdata)
num = int(data_len/DEF_FFT_SIZE)
frames_num = t*framerate/DEF_FFT_SIZE
print frames_num
if frames_num>num:
frames_num = num
#frequency domain scale
scale = (framerate/2.0)/(DEF_FFT_SIZE/2.0+1.0)
max_freq = int(framerate/(2*scale))
#
NN = max_freq/(2*2000)
thd = 0
count = 0
zcr_last = 0
f_upper = int((base_frq+50)/scale)
f_lower = int((base_frq-50)/scale)
#hanning window
<|code_end|>
. Write the next line using the current file imports:
import math
import numpy as np
from auana.common import hann
and context from other files:
# Path: auana/common.py
# def hann(M, sym=True):
# '''
# hanning window.
# '''
# # Docstring adapted from NumPy's hanning function
# if M < 1:
# return np.array([])
# if M == 1:
# return np.ones(1, 'd')
# odd = M % 2
# if not sym and not odd:
# M = M + 1
# n = np.arange(0, M)
# w = 0.5 - 0.5 * np.cos(2.0 * np.pi * n / (M - 1))
# if not sym and not odd:
# w = w[:-1]
# return w
, which may include functions, classes, or code. Output only the next line. | hanning = hann(DEF_FFT_SIZE, sym=0) |
Given snippet: <|code_start|> start = Q.pop() # explore a cycle from start node
node = start # current node on cycle
while next_[node] < len(graph[node]): # visit all allowable arcs
neighbor = graph[node][next_[node]] # traverse an arc
next_[node] += 1 # mark arc traversed
R.append(neighbor) # append to path from start
node = neighbor # move on
while R:
Q.append(R.pop()) # add to Q the discovered cycle R
P.append(start) # resulting path P is extended
return P
# snip}
def write_cycle(filename, graph, cycle, directed):
"""Write an eulerian tour in DOT format
:param filename: the file to be written in DOT format
:param graph: graph in listlist format, cannot be listdict
:param bool directed: describes the graph
:param cycle: tour as a vertex list
:returns: nothing
:complexity: `O(|V|^2 + |E|)`
"""
n = len(graph)
weight = [[float('inf')] * n for _ in range(n)]
for r in range(1, len(cycle)):
weight[cycle[r-1]][cycle[r]] = r
if not directed:
weight[cycle[r]][cycle[r-1]] = r
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import random
from tryalgo.graph import write_graph
and context:
# Path: tryalgo/graph.py
# def write_graph(dotfile, graph, directed=False,
# node_label=None, arc_label=None, comment="",
# node_mark=set(), arc_mark=set()):
# """Writes a graph to a file in the DOT format
#
# :param dotfile: the filename.
# :param graph: directed graph in listlist or listdict format
# :param directed: true if graph is directed, false if undirected
# :param weight: in matrix format or same listdict graph or None
# :param node_label: vertex label table or None
# :param arc_label: arc label matrix or None
# :param comment: comment string for the dot file or None
# :param node_mark: set of nodes to be shown in gray
# :param arc_marc: set of arcs to be shown in red
# :complexity: `O(|V| + |E|)`
# """
# with open(dotfile, 'w') as f:
# if directed:
# f.write("digraph G{\n")
# else:
# f.write("graph G{\n")
# if comment:
# f.write('label="%s";\n' % comment)
# V = range(len(graph))
# # -- vertices
# for u in V:
# if node_mark and u in node_mark:
# f.write('%d [style=filled, color="lightgrey", ' % u)
# else:
# f.write('%d [' % u)
# if node_label:
# f.write('label="%u [%s]"];\n' % (u, node_label[u]))
# else:
# f.write('shape=circle, label="%u"];\n' % u)
# # -- edges
# if isinstance(arc_mark, list):
# arc_mark = set((u, arc_mark[u]) for u in V)
# for u in V:
# for v in graph[u]:
# if not directed and u > v:
# continue # don't show twice the edge
# if arc_label and arc_label[u][v] is None:
# continue # suppress arcs with no label
# if directed:
# arc = "%d -> %d " % (u, v)
# else:
# arc = "%d -- %d " % (u, v)
# if arc_mark and ((v, u) in arc_mark or
# (not directed and (u, v) in arc_mark)):
# pen = 'color="red"'
# else:
# pen = ""
# if arc_label:
# tag = 'label="%s"' % arc_label[u][v]
# else:
# tag = ""
# if tag and pen:
# sep = ", "
# else:
# sep = ""
# f.write(arc + "[" + tag + sep + pen + "];\n")
# f.write("}")
which might include code, classes, or functions. Output only the next line. | write_graph(filename, graph, arc_label=weight, directed=directed) |
Using the snippet: <|code_start|># jill-jênn vie et christoph dürr - 2020
# coding=utf8
# pylint: disable=missing-docstring
class TestNextPermutation(unittest.TestCase):
def test_solve_word_addition(self):
self.assertEqual(solve_word_addition(["A", "B", "C"]), 32)
self.assertEqual(solve_word_addition(["A", "B", "A"]), 0)
def test_next_permutation(self):
L = [2, 2, 0, 0, 1, 1, 0]
<|code_end|>
, determine the next line of code. You have imports:
import unittest
from tryalgo.next_permutation import next_permutation, solve_word_addition
and context (class names, function names, or code) available:
# Path: tryalgo/next_permutation.py
# def next_permutation(tab):
# """find the next permutation of tab in the lexicographical order
#
# :param tab: table with n elements from an ordered set
# :modifies: table to next permutation
# :returns: False if permutation is already lexicographical maximal
# :complexity: O(n)
# """
# n = len(tab)
# pivot = None # find pivot
# for i in range(n - 1):
# if tab[i] < tab[i + 1]:
# pivot = i
# if pivot is None: # tab is already the last perm.
# return False
# for i in range(pivot + 1, n): # find the element to swap
# if tab[i] > tab[pivot]:
# swap = i
# tab[swap], tab[pivot] = tab[pivot], tab[swap]
# i = pivot + 1
# j = n - 1 # invert suffix
# while i < j:
# tab[i], tab[j] = tab[j], tab[i]
# i += 1
# j -= 1
# return True
#
# def solve_word_addition(S): # returns number of solutions
# """returns number of solutions"""
# n = len(S)
# letters = sorted(list(set(''.join(S))))
# not_zero = '' # letters that cannot be 0
# for word in S:
# not_zero += word[0]
# tab = ['@'] * (10 - len(letters)) + letters # minimal lex permutation
# count = 0
# while True:
# ass = {tab[i]: i for i in range(10)} # dict = associative array
# if tab[0] not in not_zero:
# difference = -convert(S[n - 1], ass) # do the addition
# for word in S[:n - 1]:
# difference += convert(word, ass)
# if difference == 0: # does it add up?
# count += 1
# if not next_permutation(tab):
# break
# return count
. Output only the next line. | self.assertEqual(next_permutation(L), True) |
Continue the code snippet: <|code_start|>"""
def _alternate(u, bigraph, visitU, visitV, matchV):
"""extend alternating tree from free vertex u.
visitU, visitV marks all vertices covered by the tree.
"""
visitU[u] = True
for v in bigraph[u]:
if not visitV[v]:
visitV[v] = True
assert matchV[v] is not None # otherwise match is not maximum
_alternate(matchV[v], bigraph, visitU, visitV, matchV)
def bipartite_vertex_cover(bigraph):
"""Bipartite minimum vertex cover by Koenig's theorem
:param bigraph: adjacency list, index = vertex in U,
value = neighbor list in V
:assumption: U = V = {0, 1, 2, ..., n - 1} for n = len(bigraph)
:returns: boolean table for U, boolean table for V
:comment: selected vertices form a minimum vertex cover,
i.e. every edge is adjacent to at least one selected vertex
and number of selected vertices is minimum
:complexity: `O(|V|*|E|)`
"""
V = range(len(bigraph))
<|code_end|>
. Use current file imports:
from tryalgo.bipartite_matching import max_bipartite_matching
and context (classes, functions, or code) from other files:
# Path: tryalgo/bipartite_matching.py
# def max_bipartite_matching(bigraph):
# """Bipartie maximum matching
#
# :param bigraph: adjacency list, index = vertex in U,
# value = neighbor list in V
# :assumption: U = V = {0, 1, 2, ..., n - 1} for n = len(bigraph)
# :returns: matching list, match[v] == u iff (u, v) in matching
# :complexity: `O(|V|*|E|)`
# """
# n = len(bigraph) # same domain for U and V
# match = [None] * n
# for u in range(n):
# augment(u, bigraph, [False] * n, match)
# return match
. Output only the next line. | matchV = max_bipartite_matching(bigraph) |
Here is a snippet: <|code_start|># snip{
# pylint: disable=too-many-arguments
def _augment(graph, capacity, flow, val, u, target, visit):
"""Find an augmenting path from u to target with value at most val"""
visit[u] = True
if u == target:
return val
for v in graph[u]:
cuv = capacity[u][v]
if not visit[v] and cuv > flow[u][v]: # reachable arc
res = min(val, cuv - flow[u][v])
delta = _augment(graph, capacity, flow, res, v, target, visit)
if delta > 0:
flow[u][v] += delta # augment flow
flow[v][u] -= delta
return delta
return 0
def ford_fulkerson(graph, capacity, s, t):
"""Maximum flow by Ford-Fulkerson
:param graph: directed graph in listlist or listdict format
:param capacity: in matrix format or same listdict graph
:param int s: source vertex
:param int t: target vertex
:returns: flow matrix, flow value
:complexity: `O(|V|*|E|*max_capacity)`
"""
<|code_end|>
. Write the next line using the current file imports:
from tryalgo.graph import add_reverse_arcs
and context from other files:
# Path: tryalgo/graph.py
# def add_reverse_arcs(graph, capac=None):
# """Utility function for flow algorithms that need for every arc (u,v),
# the existence of an (v,u) arc, by default with zero capacity.
# graph can be in adjacency list, possibly with capacity matrix capac.
# or graph can be in adjacency dictionary, then capac parameter is ignored.
#
# :param capac: arc capacity matrix
# :param graph: in listlist representation, or in listdict representation,
# in this case capac is ignored
# :complexity: linear
# :returns: nothing, but graph is modified
# """
# for u, _ in enumerate(graph):
# for v in graph[u]:
# if u not in graph[v]:
# if type(graph[v]) is list:
# graph[v].append(u)
# if capac:
# capac[v][u] = 0
# else:
# assert type(graph[v]) is dict
# graph[v][u] = 0
, which may include functions, classes, or code. Output only the next line. | add_reverse_arcs(graph, capacity) |
Given snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
Decompose DAG into a minimum number of chains
jill-jenn vie et christoph durr - 2015-2018
"""
# snip{
def dilworth(graph):
"""Decompose a DAG into a minimum number of chains by Dilworth
:param graph: directed graph in listlist or listdict format
:assumes: graph is acyclic
:returns: table giving for each vertex the number of its chains
:complexity: same as matching
"""
n = len(graph)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from tryalgo.bipartite_matching import max_bipartite_matching
and context:
# Path: tryalgo/bipartite_matching.py
# def max_bipartite_matching(bigraph):
# """Bipartie maximum matching
#
# :param bigraph: adjacency list, index = vertex in U,
# value = neighbor list in V
# :assumption: U = V = {0, 1, 2, ..., n - 1} for n = len(bigraph)
# :returns: matching list, match[v] == u iff (u, v) in matching
# :complexity: `O(|V|*|E|)`
# """
# n = len(bigraph) # same domain for U and V
# match = [None] * n
# for u in range(n):
# augment(u, bigraph, [False] * n, match)
# return match
which might include code, classes, or functions. Output only the next line. | match = max_bipartite_matching(graph) # maximum matching |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
"""\
Largest area rectangle in a binary matrix
plus grand rectangle monochromatique
jill-jenn vie et christoph durr - 2014-2018
"""
# snip{
def rectangles_from_grid(P, black=1):
"""Largest area rectangle in a binary matrix
:param P: matrix
:param black: search for rectangles filled with value black
:returns: area, left, top, right, bottom of optimal rectangle
consisting of all (i,j) with
left <= j < right and top <= i <= bottom
:complexity: linear
"""
rows = len(P)
cols = len(P[0])
t = [0] * cols
best = None
for i in range(rows):
for j in range(cols):
if P[i][j] == black:
t[j] += 1
else:
t[j] = 0
<|code_end|>
, determine the next line of code. You have imports:
from tryalgo.rectangles_from_histogram import rectangles_from_histogram
and context (class names, function names, or code) available:
# Path: tryalgo/rectangles_from_histogram.py
# def rectangles_from_histogram(H):
# """Largest Rectangular Area in a Histogram
#
# :param H: histogram table
# :returns: area, left, height, right, rect. is [0, height] * [left, right)
# :complexity: linear
# """
# best = (float('-inf'), 0, 0, 0)
# S = []
# H2 = H + [float('-inf')] # extra element to empty the queue
# for right, _ in enumerate(H2):
# x = H2[right]
# left = right
# while len(S) > 0 and S[-1][1] >= x:
# left, height = S.pop()
# # first element is area of candidate
# rect = (height * (right - left), left, height, right)
# if rect > best:
# best = rect
# S.append((left, x))
# return best
. Output only the next line. | (area, left, height, right) = rectangles_from_histogram(t) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.