Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Continue the code snippet: <|code_start|>#!/usr/bin/env python
# encoding: utf-8
class UpdateGridImagesTask(object):
def __init__(self, rom_finder):
self.rom_finder = rom_finder
def __call__(self, app_settings, users, dry_run):
roms = self.rom_finder.roms_for_consoles(
app_settings.config,
app_settings.consoles,
)
provider = settings.image_provider(app_settings.config)
<|code_end|>
. Use current file imports:
from ice import settings
from ice import steam_grid_updater
from ice.logs import logger
and context (classes, functions, or code) from other files:
# Path: ice/settings.py
# def find_settings_file(name, filesystem):
# def settings_file_path(name, filesystem, override = None):
# def load_configuration(filesystem, override = None):
# def load_emulators(filesystem, override = None):
# def load_consoles(emulators, filesystem, override = None):
# def load_app_settings(filesystem, file_overrides = {}):
# def image_provider(config):
#
# Path: ice/steam_grid_updater.py
# class SteamGridUpdater(object):
# def __init__(self, provider):
# def update_rom_artwork(self, user, rom, dry_run=False):
# def update_artwork_for_rom_collection(self, user, roms, dry_run=False):
#
# Path: ice/logs.py
# STREAM_STRING_FORMAT = '%(leveltag)s%(message)s'
# FILE_STRING_FORMAT = '%(asctime)s [%(levelname)s][%(filename)s][%(funcName)s:%(lineno)s]: %(message)s'
# def is_test_stack_frame(frame):
# def is_running_in_test():
# def _tag_for_level(self, levelno):
# def filter(self, record):
# def create_stream_handler(level):
# def create_file_handler(level):
# def create_logger():
# class IceLevelTagFilter(logging.Formatter):
. Output only the next line. | grid_updater = steam_grid_updater.SteamGridUpdater(provider) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
# encoding: utf-8
class UpdateGridImagesTask(object):
def __init__(self, rom_finder):
self.rom_finder = rom_finder
def __call__(self, app_settings, users, dry_run):
roms = self.rom_finder.roms_for_consoles(
app_settings.config,
app_settings.consoles,
)
provider = settings.image_provider(app_settings.config)
grid_updater = steam_grid_updater.SteamGridUpdater(provider)
for user in users:
<|code_end|>
with the help of current file imports:
from ice import settings
from ice import steam_grid_updater
from ice.logs import logger
and context from other files:
# Path: ice/settings.py
# def find_settings_file(name, filesystem):
# def settings_file_path(name, filesystem, override = None):
# def load_configuration(filesystem, override = None):
# def load_emulators(filesystem, override = None):
# def load_consoles(emulators, filesystem, override = None):
# def load_app_settings(filesystem, file_overrides = {}):
# def image_provider(config):
#
# Path: ice/steam_grid_updater.py
# class SteamGridUpdater(object):
# def __init__(self, provider):
# def update_rom_artwork(self, user, rom, dry_run=False):
# def update_artwork_for_rom_collection(self, user, roms, dry_run=False):
#
# Path: ice/logs.py
# STREAM_STRING_FORMAT = '%(leveltag)s%(message)s'
# FILE_STRING_FORMAT = '%(asctime)s [%(levelname)s][%(filename)s][%(funcName)s:%(lineno)s]: %(message)s'
# def is_test_stack_frame(frame):
# def is_running_in_test():
# def _tag_for_level(self, levelno):
# def filter(self, record):
# def create_stream_handler(level):
# def create_file_handler(level):
# def create_logger():
# class IceLevelTagFilter(logging.Formatter):
, which may contain function names, class names, or code. Output only the next line. | logger.info("::Updating grid images for U:%s" % user.user_id) |
Here is a snippet: <|code_start|> self.assertEquals(self.synchronizer.added_shortcuts(old, new), [shortcut3, shortcut4])
def test_removed_shortcuts_doesnt_return_shortcuts_that_still_exist(self):
shortcut1 = steam_model.Shortcut("Game1", "/Path/to/game1", "/Path/to", "", [roms.ICE_FLAG_TAG])
shortcut2 = steam_model.Shortcut("Game2", "/Path/to/game2", "/Path/to", "", [roms.ICE_FLAG_TAG])
old = [shortcut1, shortcut2]
new = [shortcut1, shortcut2]
self.assertEquals(self.synchronizer.removed_shortcuts(old, new), [])
def test_removed_shortcuts_returns_shortcuts_that_dont_exist_anymore(self):
shortcut1 = steam_model.Shortcut("Game1", "/Path/to/game1", "/Path/to", "", [roms.ICE_FLAG_TAG])
shortcut2 = steam_model.Shortcut("Game2", "/Path/to/game2", "/Path/to", "", [roms.ICE_FLAG_TAG])
old = [shortcut1, shortcut2]
new = []
self.assertEquals(self.synchronizer.removed_shortcuts(old, new), [shortcut1, shortcut2])
def test_removed_shortcuts_only_returns_shortcuts_that_dont_exist_now_but_did_before(self):
shortcut1 = steam_model.Shortcut("Game1", "/Path/to/game1", "/Path/to", "", [roms.ICE_FLAG_TAG])
shortcut2 = steam_model.Shortcut("Game2", "/Path/to/game2", "/Path/to", "", [roms.ICE_FLAG_TAG])
shortcut3 = steam_model.Shortcut("Game3", "/Path/to/game3", "/Path/to", "", [roms.ICE_FLAG_TAG])
shortcut4 = steam_model.Shortcut("Game4", "/Path/to/game4", "/Path/to", "", [roms.ICE_FLAG_TAG])
old = [shortcut1, shortcut2, shortcut3, shortcut4]
new = [shortcut1, shortcut2]
self.assertEquals(self.synchronizer.removed_shortcuts(old, new), [shortcut3, shortcut4])
def test_sync_roms_for_user_keeps_unmanaged_shortcuts(self):
random_shortcut = steam_model.Shortcut("Plex", "/Some/Random/Path/plex", "/Some/Random/Path", "", [])
self._set_users_shortcuts([random_shortcut])
when(self.mock_archive).previous_managed_ids(self.user_fixture.get_context()).thenReturn([])
<|code_end|>
. Write the next line using the current file imports:
import unittest
from mockito import *
from pysteam import model as steam_model
from pysteam import shortcuts
from ice import model
from ice import steam_shortcut_synchronizer
from ice import roms
from testinfra import fixtures
and context from other files:
# Path: ice/model.py
# ROM = collections.namedtuple('ROM', [
# 'name',
# 'path',
# 'console',
# ])
#
# Path: ice/steam_shortcut_synchronizer.py
# class SteamShortcutSynchronizer(object):
# def __init__(self, config, managed_rom_archive):
# def _guess_whether_shortcut_is_managed_by_ice(self, shortcut, consoles):
# def shortcut_is_managed_by_console(console):
# def shortcut_is_managed_by_ice(self, managed_ids, shortcut, consoles):
# def unmanaged_shortcuts(self, managed_ids, shortcuts, consoles):
# def removed_shortcuts(self, current_shortcuts, new_shortcuts):
# def added_shortcuts(self, current_shortcuts, new_shortcuts):
# def sync_roms_for_user(self, user, users_roms, consoles, dry_run=False):
#
# Path: ice/roms.py
# ICE_FLAG_TAG = "~ManagedByIce"
# def roms_directory(config):
# def rom_shortcut_name(rom):
# def rom_to_shortcut(rom):
, which may include functions, classes, or code. Output only the next line. | rom1 = model.ROM(name = 'Game1', path = '/Path/to/game1', console = fixtures.consoles.flagged) |
Predict the next line after this snippet: <|code_start|>
class SteamShortcutSynchronizerTests(unittest.TestCase):
def setUp(self):
self.steam_fixture = fixtures.SteamFixture()
self.user_fixture = fixtures.UserFixture(self.steam_fixture)
self.mock_config = mock()
self.mock_archive = mock()
<|code_end|>
using the current file's imports:
import unittest
from mockito import *
from pysteam import model as steam_model
from pysteam import shortcuts
from ice import model
from ice import steam_shortcut_synchronizer
from ice import roms
from testinfra import fixtures
and any relevant context from other files:
# Path: ice/model.py
# ROM = collections.namedtuple('ROM', [
# 'name',
# 'path',
# 'console',
# ])
#
# Path: ice/steam_shortcut_synchronizer.py
# class SteamShortcutSynchronizer(object):
# def __init__(self, config, managed_rom_archive):
# def _guess_whether_shortcut_is_managed_by_ice(self, shortcut, consoles):
# def shortcut_is_managed_by_console(console):
# def shortcut_is_managed_by_ice(self, managed_ids, shortcut, consoles):
# def unmanaged_shortcuts(self, managed_ids, shortcuts, consoles):
# def removed_shortcuts(self, current_shortcuts, new_shortcuts):
# def added_shortcuts(self, current_shortcuts, new_shortcuts):
# def sync_roms_for_user(self, user, users_roms, consoles, dry_run=False):
#
# Path: ice/roms.py
# ICE_FLAG_TAG = "~ManagedByIce"
# def roms_directory(config):
# def rom_shortcut_name(rom):
# def rom_to_shortcut(rom):
. Output only the next line. | self.synchronizer = steam_shortcut_synchronizer.SteamShortcutSynchronizer(self.mock_config, self.mock_archive) |
Using the snippet: <|code_start|> def test_unmanaged_shortcuts_returns_all_shortcuts_when_given_no_history(self):
dummy_console = self._create_dummy_console("/Some/Other/Path")
random_shortcut = steam_model.Shortcut("Plex", "/Some/Random/Path/plex", "/Some/Random/Path", "", [])
unmanaged = self.synchronizer.unmanaged_shortcuts(None ,[random_shortcut], [dummy_console])
self.assertEquals(unmanaged, [random_shortcut])
def test_unmanaged_shortcuts_filters_suspicious_shortcuts_when_given_no_history(self):
dummy_console = self._create_dummy_console("/Some/Path")
random_shortcut = steam_model.Shortcut("Iron Man", "/Some/Emulator/Path/emulator /Some/Path/Iron Man", "/Some/Emulator/Path", "", [])
unmanaged = self.synchronizer.unmanaged_shortcuts(None ,[random_shortcut], [dummy_console])
self.assertEquals(unmanaged, [])
def test_unmanaged_shortcuts_doesnt_filter_suspicious_shortcuts_when_we_have_history(self):
dummy_console = self._create_dummy_console("/Some/Path")
random_shortcut = steam_model.Shortcut("Iron Man", "/Some/Emulator/Path/emulator /Some/Path/Iron Man", "/Some/Emulator/Path", "", [])
unmanaged = self.synchronizer.unmanaged_shortcuts([] ,[random_shortcut], [dummy_console])
self.assertEquals(unmanaged, [random_shortcut])
def test_unmanaged_shortcuts_returns_shortcut_not_affiliated_with_ice(self):
random_shortcut = steam_model.Shortcut("Plex", "/Some/Random/Path/plex", "/Some/Random/Path", "", [])
unmanaged = self.synchronizer.unmanaged_shortcuts([],[random_shortcut], None)
self.assertEquals(unmanaged, [random_shortcut])
def test_unmanaged_shortcuts_doesnt_return_shortcut_with_flag_tag(self):
<|code_end|>
, determine the next line of code. You have imports:
import unittest
from mockito import *
from pysteam import model as steam_model
from pysteam import shortcuts
from ice import model
from ice import steam_shortcut_synchronizer
from ice import roms
from testinfra import fixtures
and context (class names, function names, or code) available:
# Path: ice/model.py
# ROM = collections.namedtuple('ROM', [
# 'name',
# 'path',
# 'console',
# ])
#
# Path: ice/steam_shortcut_synchronizer.py
# class SteamShortcutSynchronizer(object):
# def __init__(self, config, managed_rom_archive):
# def _guess_whether_shortcut_is_managed_by_ice(self, shortcut, consoles):
# def shortcut_is_managed_by_console(console):
# def shortcut_is_managed_by_ice(self, managed_ids, shortcut, consoles):
# def unmanaged_shortcuts(self, managed_ids, shortcuts, consoles):
# def removed_shortcuts(self, current_shortcuts, new_shortcuts):
# def added_shortcuts(self, current_shortcuts, new_shortcuts):
# def sync_roms_for_user(self, user, users_roms, consoles, dry_run=False):
#
# Path: ice/roms.py
# ICE_FLAG_TAG = "~ManagedByIce"
# def roms_directory(config):
# def rom_shortcut_name(rom):
# def rom_to_shortcut(rom):
. Output only the next line. | tagged_shortcut = steam_model.Shortcut("Game", "/Path/to/game", "/Path/to", "", [roms.ICE_FLAG_TAG]) |
Predict the next line after this snippet: <|code_start|># encoding: utf-8
class LogsTests(unittest.TestCase):
def setUp(self):
self.tempdir = tempfile.mkdtemp()
<|code_end|>
using the current file's imports:
import os
import shutil
import tempfile
import unittest
from mockito import *
from ice import logs
and any relevant context from other files:
# Path: ice/logs.py
# STREAM_STRING_FORMAT = '%(leveltag)s%(message)s'
# FILE_STRING_FORMAT = '%(asctime)s [%(levelname)s][%(filename)s][%(funcName)s:%(lineno)s]: %(message)s'
# def is_test_stack_frame(frame):
# def is_running_in_test():
# def _tag_for_level(self, levelno):
# def filter(self, record):
# def create_stream_handler(level):
# def create_file_handler(level):
# def create_logger():
# class IceLevelTagFilter(logging.Formatter):
. Output only the next line. | self.old_log_file_location = logs.paths.log_file_location |
Based on the snippet: <|code_start|>
class EmulatorBackedObjectAdapter(object):
def __init__(self, filesystem):
self.filesystem = filesystem
def new(self, backing_store, identifier):
name = identifier
location = backing_store.get(identifier, 'location')
fmt = backing_store.get(identifier, 'command', "%l %r")
location = os.path.expanduser(location)
return Emulator(
name,
location,
fmt,
)
def verify(self, emulator):
if emulator.location is None or emulator.location == "":
<|code_end|>
, predict the immediate next line with the help of imports:
import os
from ice.logs import logger
from ice.model import Emulator
and context (classes, functions, sometimes code) from other files:
# Path: ice/logs.py
# STREAM_STRING_FORMAT = '%(leveltag)s%(message)s'
# FILE_STRING_FORMAT = '%(asctime)s [%(levelname)s][%(filename)s][%(funcName)s:%(lineno)s]: %(message)s'
# def is_test_stack_frame(frame):
# def is_running_in_test():
# def _tag_for_level(self, levelno):
# def filter(self, record):
# def create_stream_handler(level):
# def create_file_handler(level):
# def create_logger():
# class IceLevelTagFilter(logging.Formatter):
#
# Path: ice/model.py
# ROM = collections.namedtuple('ROM', [
# 'name',
# 'path',
# 'console',
# ])
. Output only the next line. | logger.error("Missing location for Emulator: `%s`" % emulator.name) |
Predict the next line after this snippet: <|code_start|>
class EmulatorBackedObjectAdapter(object):
def __init__(self, filesystem):
self.filesystem = filesystem
def new(self, backing_store, identifier):
name = identifier
location = backing_store.get(identifier, 'location')
fmt = backing_store.get(identifier, 'command', "%l %r")
location = os.path.expanduser(location)
<|code_end|>
using the current file's imports:
import os
from ice.logs import logger
from ice.model import Emulator
and any relevant context from other files:
# Path: ice/logs.py
# STREAM_STRING_FORMAT = '%(leveltag)s%(message)s'
# FILE_STRING_FORMAT = '%(asctime)s [%(levelname)s][%(filename)s][%(funcName)s:%(lineno)s]: %(message)s'
# def is_test_stack_frame(frame):
# def is_running_in_test():
# def _tag_for_level(self, levelno):
# def filter(self, record):
# def create_stream_handler(level):
# def create_file_handler(level):
# def create_logger():
# class IceLevelTagFilter(logging.Formatter):
#
# Path: ice/model.py
# ROM = collections.namedtuple('ROM', [
# 'name',
# 'path',
# 'console',
# ])
. Output only the next line. | return Emulator( |
Predict the next line after this snippet: <|code_start|> @parameterized.expand([
# NES has no custom image directory set, so it should use the default
(fixtures.consoles.nes, '/roms/', '/roms/NES'),
# SNES, on the other hand, does, so we should use the provided one
(fixtures.consoles.snes, '/roms/', '/external/consoles/roms/snes'),
])
def test_console_roms_directory(self, console, config_path, expected):
config = mock()
config.roms_directory = config_path
self.assertEqual(consoles.console_roms_directory(config, console), expected)
@parameterized.expand([
# No extensions passes everything
("", "/Games/rom.txt", True),
# Extensions that dont exist in the list dont pass
("nes", "/Games/rom.txt", False),
("nes, snes, n64", "/Games/rom.exe", False),
# Extensions that exist in the list are fine
("nes", "/Games/rom.nes", True),
("nes, snes, n64", "/Games/rom.snes", True),
# Even if they have a leading .
(".nes, .snes, n64", "/Games/rom.n64", True),
(".nes, .snes, n64", "/Games/rom.snes", True),
# And even if the capitalization is screwy
("NES, .snes", "/Games/ROM.SNES", True),
("NES, .snes", "/Games/ROM.nEs", True),
# Also with stupid whitespace
("NES, .snes", "/Games/ROM.SNES", True),
])
def test_path_is_rom(self, extensions, path, expected):
<|code_end|>
using the current file's imports:
import unittest
from mockito import *
from nose_parameterized import parameterized
from ice import consoles
from ice import model
from testinfra import fixtures
and any relevant context from other files:
# Path: ice/consoles.py
# def console_roms_directory(configuration, console):
# def path_is_rom(console, path):
#
# Path: ice/model.py
# ROM = collections.namedtuple('ROM', [
# 'name',
# 'path',
# 'console',
# ])
. Output only the next line. | console = model.Console("Nintendo", "NES", extensions, "", "", "", "", None) |
Predict the next line for this snippet: <|code_start|>"""
keyboard
A submodule inside tinygame that provides more game like keyboard input
This code is based largley on the post at http://effbot.org/pyfaq/how-do-i-get-a-single-keypress-at-a-time.htm
"""
# to get game keyboard control, first we load some low level operating system modules/libraries for terminal control
<|code_end|>
with the help of current file imports:
import termios # module get and set terminal attributes
import fcntl # module to manipulate a file descriptor (ie the standard input file descriptor)
import sys, os # opersting system wrapper module
import select # a module exposing the lowleve select() call which allows a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become "ready" for some class of I/O operation (e.g., input possible).
from tinygame.character_display import ESCAPE, CSI # we read ANSI escape sequences for special keys similar to printing them for display. See character_display.py
and context from other files:
# Path: tinygame/character_display.py
# ESCAPE = chr(27)
#
# CSI = ESCAPE + "[" # control sequences are started by writing a special sequence of characters to the terminal known as a Control Sequebce Introducer (CSI)
, which may contain function names, class names, or code. Output only the next line. | KEY_ESCAPE = ESCAPE |
Given snippet: <|code_start|>"""
keyboard
A submodule inside tinygame that provides more game like keyboard input
This code is based largley on the post at http://effbot.org/pyfaq/how-do-i-get-a-single-keypress-at-a-time.htm
"""
# to get game keyboard control, first we load some low level operating system modules/libraries for terminal control
KEY_ESCAPE = ESCAPE
KEY_TAB = chr(9)
KEY_ENTER = chr(10)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import termios # module get and set terminal attributes
import fcntl # module to manipulate a file descriptor (ie the standard input file descriptor)
import sys, os # opersting system wrapper module
import select # a module exposing the lowleve select() call which allows a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become "ready" for some class of I/O operation (e.g., input possible).
from tinygame.character_display import ESCAPE, CSI # we read ANSI escape sequences for special keys similar to printing them for display. See character_display.py
and context:
# Path: tinygame/character_display.py
# ESCAPE = chr(27)
#
# CSI = ESCAPE + "[" # control sequences are started by writing a special sequence of characters to the terminal known as a Control Sequebce Introducer (CSI)
which might include code, classes, or functions. Output only the next line. | KEY_DELETE = CSI + "3~" |
Based on the snippet: <|code_start|>
def extend(this, iterable_item):
if not iterable_item:
return
super(this.__class__, this).extend(iterable_item)
# Update population flag.
self.update_flag()
# }}}
self._individuals = IndvList()
def init(self, indvs=None):
''' Initialize current population with individuals.
:param indvs: Initial individuals in population, randomly initialized
individuals are created if not provided.
:type indvs: list of Individual object
'''
IndvType = self.indv_template.__class__
if indvs is None:
for _ in range(self.size):
indv = IndvType(ranges=self.indv_template.ranges,
eps=self.indv_template.eps)
self.individuals.append(indv)
else:
# Check individuals.
if len(indvs) != self.size:
raise ValueError('Invalid individuals number')
for indv in indvs:
<|code_end|>
, predict the immediate next line with the help of imports:
from .individual import IndividualBase
and context (classes, functions, sometimes code) from other files:
# Path: gaft/components/individual.py
# class IndividualBase(object):
# ''' Base class for individuals.
#
# :param ranges: value ranges for all entries in solution.
# :type ranges: tuple list
#
# :param eps: decrete precisions for binary encoding, default is 0.001.
# :type eps: float or float list (with the same length with ranges)
# '''
# # Solution ranges.
# ranges = SolutionRanges()
#
# # Orginal decrete precisions (provided by users).
# eps = DecretePrecision()
#
# # Actual decrete precisions used in GA.
# precisions = DecretePrecision()
#
# def __init__(self, ranges, eps):
# self.ranges = ranges
# self.eps = eps
# self.precisions = eps
#
# self.solution, self.chromsome = [], []
#
# def init(self, chromsome=None, solution=None):
# ''' Initialize the individual by providing chromsome or solution.
#
# :param chromsome: chromesome sequence for the individual
# :type chromsome: list of (float / int)
#
# :param solution: the variable vector of the target function.
# :type solution: list of float
#
# .. Note::
# If both chromsome and solution are provided, only the chromsome would
# be used. If neither is provided, individual would be initialized randomly.
# '''
# if not any([chromsome, solution]):
# self.solution = self._rand_solution()
# self.chromsome = self.encode()
# elif chromsome:
# self.chromsome = chromsome
# self.solution = self.decode()
# else:
# self.solution = solution
# self.chromsome = self.encode()
#
# return self
#
# def clone(self):
# ''' Clone a new individual from current one.
# '''
# indv = self.__class__(deepcopy(self.ranges), eps=deepcopy(self.eps))
# indv.init(chromsome=deepcopy(self.chromsome))
# return indv
#
#
# def encode(self):
# ''' **NEED IMPLIMENTATION**
#
# Convert solution to chromsome sequence.
#
# :return: The chromsome sequence
# :rtype: list of float
# '''
# raise NotImplementedError
#
# def decode(self):
# ''' **NEED IMPLIMENTATION**
#
# Convert chromsome sequence to solution.
#
# :return: The solution vector
# :rtype: list of float
# '''
# raise NotImplementedError
#
# def _rand_solution(self):
# ''' Initialize individual solution randomly.
# '''
# solution = []
# for eps, (a, b) in zip(self.precisions, self.ranges):
# n_intervals = (b - a)//eps
# n = int(uniform(0, n_intervals + 1))
# solution.append(a + n*eps)
# return solution
. Output only the next line. | if not isinstance(indv, IndividualBase): |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
''' Test case for Individual.
'''
class IndividualTest(unittest.TestCase):
def setUp(self):
self.maxDiff = True
def test_binary_encoding(self):
''' Make sure individual can decode and encode binary gene correctly.
'''
<|code_end|>
. Use current file imports:
import unittest
from ..components import BinaryIndividual
and context (classes, functions, or code) from other files:
# Path: gaft/components/binary_individual.py
# class BinaryIndividual(IndividualBase):
# '''
# Class for individual in population. Random solution will be initialized
# by default.
#
# :param ranges: value ranges for all entries in solution.
# :type ranges: tuple list
#
# :param eps: decrete precisions for binary encoding, default is 0.001.
# :type eps: float or float list (with the same length with ranges)
#
# .. Note:
#
# The decrete precisions for different components in varants may be
# adjusted automatically (possible precision loss) if eps and ranges
# are not appropriate.
# '''
# def __init__(self, ranges, eps=0.001):
# super(self.__class__, self).__init__(ranges, eps)
#
# # Lengths for all binary sequence in chromsome and adjusted decrete precisions.
# self.lengths = []
#
# for i, ((a, b), eps) in enumerate(zip(self.ranges, self.eps)):
# length = int(log2((b - a)/eps))
# precision = (b - a)/(2**length)
# self.lengths.append(length)
# self.precisions[i] = precision
#
# # The start and end indices for each gene segment for entries in solution.
# self.gene_indices = self._get_gene_indices()
#
# # Initialize individual randomly.
# self.init()
#
# def encode(self):
# ''' Encode solution to gene sequence in individual using different encoding.
# '''
# chromsome = []
# for var, (a, _), length, eps in zip(self.solution, self.ranges,
# self.lengths, self.precisions):
# chromsome.extend(self.binarize(var-a, eps, length))
#
# return chromsome
#
# def decode(self):
# ''' Decode gene sequence to solution of target function.
# '''
# solution = [self.decimalize(self.chromsome[start: end], eps, lower_bound)
# for (start, end), (lower_bound, _), eps in
# zip(self.gene_indices, self.ranges, self.precisions)]
# return solution
#
# def _get_gene_indices(self):
# '''
# Helper function to get gene slice indices.
# '''
# end_indices = list(accumulate(self.lengths))
# start_indices = [0] + end_indices[: -1]
# return list(zip(start_indices, end_indices))
#
# @staticmethod
# def binarize(decimal, eps, length):
# ''' Helper function to convert a float to binary sequence.
#
# :param decimal: the decimal number to be converted
# :type decimal: float
#
# :param eps: the decrete precision of binary sequence
# :type eps: float
#
# :param length: the length of binary sequence.
# :type length: int
# '''
# n = int(decimal/eps)
# bin_str = '{:0>{}b}'.format(n, length)
# return [int(i) for i in bin_str]
#
# @staticmethod
# def decimalize(binary, eps, lower_bound):
# ''' Helper function to convert a binary sequence back to decimal number.
#
# :param binary: The binary list to be converted
# :type binary: list of int
#
# :param eps: the decrete precision of binary sequence
# :type eps: float
#
# :param lower_bound: the lower bound for decimal number
# :type lower_bound: float
# '''
# bin_str = ''.join([str(bit) for bit in binary])
# return lower_bound + int(bin_str, 2)*eps
. Output only the next line. | indv = BinaryIndividual(ranges=[(0, 1)], eps=0.001) |
Using the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
''' Test case for built-in Uniform Crossover operator.
'''
class UniformCrossoverTest(unittest.TestCase):
def setUp(self):
self.maxDiff
def test_cross(self):
''' Make sure individuals can be crossed correctly.
'''
<|code_end|>
, determine the next line of code. You have imports:
import unittest
from gaft.components import BinaryIndividual
from gaft.operators.crossover.uniform_crossover import UniformCrossover
and context (class names, function names, or code) available:
# Path: gaft/components/binary_individual.py
# class BinaryIndividual(IndividualBase):
# '''
# Class for individual in population. Random solution will be initialized
# by default.
#
# :param ranges: value ranges for all entries in solution.
# :type ranges: tuple list
#
# :param eps: decrete precisions for binary encoding, default is 0.001.
# :type eps: float or float list (with the same length with ranges)
#
# .. Note:
#
# The decrete precisions for different components in varants may be
# adjusted automatically (possible precision loss) if eps and ranges
# are not appropriate.
# '''
# def __init__(self, ranges, eps=0.001):
# super(self.__class__, self).__init__(ranges, eps)
#
# # Lengths for all binary sequence in chromsome and adjusted decrete precisions.
# self.lengths = []
#
# for i, ((a, b), eps) in enumerate(zip(self.ranges, self.eps)):
# length = int(log2((b - a)/eps))
# precision = (b - a)/(2**length)
# self.lengths.append(length)
# self.precisions[i] = precision
#
# # The start and end indices for each gene segment for entries in solution.
# self.gene_indices = self._get_gene_indices()
#
# # Initialize individual randomly.
# self.init()
#
# def encode(self):
# ''' Encode solution to gene sequence in individual using different encoding.
# '''
# chromsome = []
# for var, (a, _), length, eps in zip(self.solution, self.ranges,
# self.lengths, self.precisions):
# chromsome.extend(self.binarize(var-a, eps, length))
#
# return chromsome
#
# def decode(self):
# ''' Decode gene sequence to solution of target function.
# '''
# solution = [self.decimalize(self.chromsome[start: end], eps, lower_bound)
# for (start, end), (lower_bound, _), eps in
# zip(self.gene_indices, self.ranges, self.precisions)]
# return solution
#
# def _get_gene_indices(self):
# '''
# Helper function to get gene slice indices.
# '''
# end_indices = list(accumulate(self.lengths))
# start_indices = [0] + end_indices[: -1]
# return list(zip(start_indices, end_indices))
#
# @staticmethod
# def binarize(decimal, eps, length):
# ''' Helper function to convert a float to binary sequence.
#
# :param decimal: the decimal number to be converted
# :type decimal: float
#
# :param eps: the decrete precision of binary sequence
# :type eps: float
#
# :param length: the length of binary sequence.
# :type length: int
# '''
# n = int(decimal/eps)
# bin_str = '{:0>{}b}'.format(n, length)
# return [int(i) for i in bin_str]
#
# @staticmethod
# def decimalize(binary, eps, lower_bound):
# ''' Helper function to convert a binary sequence back to decimal number.
#
# :param binary: The binary list to be converted
# :type binary: list of int
#
# :param eps: the decrete precision of binary sequence
# :type eps: float
#
# :param lower_bound: the lower bound for decimal number
# :type lower_bound: float
# '''
# bin_str = ''.join([str(bit) for bit in binary])
# return lower_bound + int(bin_str, 2)*eps
#
# Path: gaft/operators/crossover/uniform_crossover.py
# class UniformCrossover(Crossover):
# ''' Crossover operator with uniform crossover algorithm,
# see https://en.wikipedia.org/wiki/Crossover_(genetic_algorithm)
#
# :param pc: The probability of crossover (usaully between 0.25 ~ 1.0)
# :type pc: float in (0.0, 1.0]
#
# :param pe: Gene exchange probability.
# :type pe: float in range (0.0, 1.0]
# '''
# def __init__(self, pc, pe=0.5):
# if pc <= 0.0 or pc > 1.0:
# raise ValueError('Invalid crossover probability')
# self.pc = pc
#
# if pe <= 0.0 or pe > 1.0:
# raise ValueError('Invalid genome exchange probability')
# self.pe = pe
#
# def cross(self, father, mother):
# ''' Cross chromsomes of parent using uniform crossover method.
#
# :param population: Population where the selection operation occurs.
# :type population: :obj:`gaft.components.Population`
#
# :return: Selected parents (a father and a mother)
# :rtype: list of :obj:`gaft.components.IndividualBase`
# '''
# do_cross = True if random() <= self.pc else False
#
# if not do_cross:
# return father.clone(), mother.clone()
#
# # Chromsomes for two children.
# chrom1 = deepcopy(father.chromsome)
# chrom2 = deepcopy(mother.chromsome)
#
# for i, (g1, g2) in enumerate(zip(chrom1, chrom2)):
# do_exchange = True if random() < self.pe else False
# if do_exchange:
# chrom1[i], chrom2[i] = g2, g1
#
# child1, child2 = father.clone(), father.clone()
# child1.init(chromsome=chrom1)
# child2.init(chromsome=chrom2)
#
# return child1, child2
. Output only the next line. | father = BinaryIndividual(ranges=[(0, 1)]).init(solution=[0.398]) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
''' Test case for built-in Uniform Crossover operator.
'''
class UniformCrossoverTest(unittest.TestCase):
def setUp(self):
self.maxDiff
def test_cross(self):
''' Make sure individuals can be crossed correctly.
'''
father = BinaryIndividual(ranges=[(0, 1)]).init(solution=[0.398])
mother = BinaryIndividual(ranges=[(0, 1)]).init(solution=[0.298])
<|code_end|>
. Use current file imports:
import unittest
from gaft.components import BinaryIndividual
from gaft.operators.crossover.uniform_crossover import UniformCrossover
and context (classes, functions, or code) from other files:
# Path: gaft/components/binary_individual.py
# class BinaryIndividual(IndividualBase):
# '''
# Class for individual in population. Random solution will be initialized
# by default.
#
# :param ranges: value ranges for all entries in solution.
# :type ranges: tuple list
#
# :param eps: decrete precisions for binary encoding, default is 0.001.
# :type eps: float or float list (with the same length with ranges)
#
# .. Note:
#
# The decrete precisions for different components in varants may be
# adjusted automatically (possible precision loss) if eps and ranges
# are not appropriate.
# '''
# def __init__(self, ranges, eps=0.001):
# super(self.__class__, self).__init__(ranges, eps)
#
# # Lengths for all binary sequence in chromsome and adjusted decrete precisions.
# self.lengths = []
#
# for i, ((a, b), eps) in enumerate(zip(self.ranges, self.eps)):
# length = int(log2((b - a)/eps))
# precision = (b - a)/(2**length)
# self.lengths.append(length)
# self.precisions[i] = precision
#
# # The start and end indices for each gene segment for entries in solution.
# self.gene_indices = self._get_gene_indices()
#
# # Initialize individual randomly.
# self.init()
#
# def encode(self):
# ''' Encode solution to gene sequence in individual using different encoding.
# '''
# chromsome = []
# for var, (a, _), length, eps in zip(self.solution, self.ranges,
# self.lengths, self.precisions):
# chromsome.extend(self.binarize(var-a, eps, length))
#
# return chromsome
#
# def decode(self):
# ''' Decode gene sequence to solution of target function.
# '''
# solution = [self.decimalize(self.chromsome[start: end], eps, lower_bound)
# for (start, end), (lower_bound, _), eps in
# zip(self.gene_indices, self.ranges, self.precisions)]
# return solution
#
# def _get_gene_indices(self):
# '''
# Helper function to get gene slice indices.
# '''
# end_indices = list(accumulate(self.lengths))
# start_indices = [0] + end_indices[: -1]
# return list(zip(start_indices, end_indices))
#
# @staticmethod
# def binarize(decimal, eps, length):
# ''' Helper function to convert a float to binary sequence.
#
# :param decimal: the decimal number to be converted
# :type decimal: float
#
# :param eps: the decrete precision of binary sequence
# :type eps: float
#
# :param length: the length of binary sequence.
# :type length: int
# '''
# n = int(decimal/eps)
# bin_str = '{:0>{}b}'.format(n, length)
# return [int(i) for i in bin_str]
#
# @staticmethod
# def decimalize(binary, eps, lower_bound):
# ''' Helper function to convert a binary sequence back to decimal number.
#
# :param binary: The binary list to be converted
# :type binary: list of int
#
# :param eps: the decrete precision of binary sequence
# :type eps: float
#
# :param lower_bound: the lower bound for decimal number
# :type lower_bound: float
# '''
# bin_str = ''.join([str(bit) for bit in binary])
# return lower_bound + int(bin_str, 2)*eps
#
# Path: gaft/operators/crossover/uniform_crossover.py
# class UniformCrossover(Crossover):
# ''' Crossover operator with uniform crossover algorithm,
# see https://en.wikipedia.org/wiki/Crossover_(genetic_algorithm)
#
# :param pc: The probability of crossover (usaully between 0.25 ~ 1.0)
# :type pc: float in (0.0, 1.0]
#
# :param pe: Gene exchange probability.
# :type pe: float in range (0.0, 1.0]
# '''
# def __init__(self, pc, pe=0.5):
# if pc <= 0.0 or pc > 1.0:
# raise ValueError('Invalid crossover probability')
# self.pc = pc
#
# if pe <= 0.0 or pe > 1.0:
# raise ValueError('Invalid genome exchange probability')
# self.pe = pe
#
# def cross(self, father, mother):
# ''' Cross chromsomes of parent using uniform crossover method.
#
# :param population: Population where the selection operation occurs.
# :type population: :obj:`gaft.components.Population`
#
# :return: Selected parents (a father and a mother)
# :rtype: list of :obj:`gaft.components.IndividualBase`
# '''
# do_cross = True if random() <= self.pc else False
#
# if not do_cross:
# return father.clone(), mother.clone()
#
# # Chromsomes for two children.
# chrom1 = deepcopy(father.chromsome)
# chrom2 = deepcopy(mother.chromsome)
#
# for i, (g1, g2) in enumerate(zip(chrom1, chrom2)):
# do_exchange = True if random() < self.pe else False
# if do_exchange:
# chrom1[i], chrom2[i] = g2, g1
#
# child1, child2 = father.clone(), father.clone()
# child1.init(chromsome=chrom1)
# child2.init(chromsome=chrom2)
#
# return child1, child2
. Output only the next line. | crossover = UniformCrossover(pc=1.0, pe=0.5) |
Next line prediction: <|code_start|>
Logging transiently means that verbose logging messages like DEBUG
will only appear on the last line of your terminal for a short
period of time and important messages like WARNING will scroll
like normal text.
This allows you to log lots of messages without the important
stuff getting drowned out.
This module integrates with the standard Python logging module.
"""
def __init__(self, strm=sys.stderr, level=logging.WARNING):
logging.StreamHandler.__init__(self, strm)
if isinstance(level, int):
self.levelno = level
else:
self.levelno = logging._levelNames[level]
self.need_cr = False
self.last = ""
self.parent = logging.StreamHandler
def close(self):
if self.need_cr:
self.stream.write("\n")
self.need_cr = False
self.parent.close(self)
def write(self, data):
if self.need_cr:
<|code_end|>
. Use current file imports:
(import sys
import logging
from fabulous import utils)
and context including class names, function names, or small code snippets from other files:
# Path: fabulous/utils.py
# def memoize(function):
# def _memoize(*args):
# def __init__(self, bgcolor='black'):
# def termfd(self):
# def dimensions(self):
# def width(self):
# def height(self):
# def _get_bgcolor(self):
# def _set_bgcolor(self, color):
# def pil_check():
# class TerminalInfo(object):
. Output only the next line. | width = max(min(utils.term.width, len(self.last)), len(data)) |
Here is a snippet: <|code_start|>#!/usr/bin/env python
#
# Copyright 2016 The Fabulous Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This is a long timed progress bar. Don't expect it to finish any
time soon. It updates every 0 to 10 seconds. Send it a keyboard
interupt (Ctrl-C) to stop."""
print __doc__
<|code_end|>
. Write the next line using the current file imports:
from fabulous.widget import TimedProgressBar
import time
import random
and context from other files:
# Path: fabulous/widget.py
# class TimedProgressBar(ProgressBar):
# """A 3-line progress bar, which looks like::
# title
# 39% [================>----------------------------] ETA mm:ss
# message
#
# p = ProgressBar('spam') # create bar
# p.update(0, 'starting spam') # start printing it out
# p.update(50, 'spam almost ready') # progress
# p.update(100, 'spam complete')
# """
#
# BAR_FORMAT = {'text':' %3d%% ' + '[%s'+display('dim')+'%s'+display('default')+']',
# 'length':13,
# 'padding':2 }
# ' ETA 12:23'
#
# # what fraction of percent it acurate too
# precision = 100
#
# def __init__(self, title = None):
# ProgressBar.__init__(self, title)
# self.start = datetime.today()
#
# def get_bar(self, percent):
# now = datetime.today()
# timed = now - self.start
# etatext = ''
# etadiv = int(percent*self.precision)
# if timed.seconds >= 1:
# etatext += ' '
# if int(percent * self.precision) !=0:
# eta = (timed * 100 * self.precision)/int(percent * self.precision)
# days = eta.days
# min, sec = divmod(eta.seconds, 60)
# hours, min = divmod(min, 60)
# if days == 1: etatext += '1 day, '
# elif days: etatext += '%d days, ' % days
# if hours: etatext += '%02d:' % hours
# etatext += '%02d:%02d' % (min, sec)
# else:
# etatext += 'Never'
# barlength = (self.width - self.BAR_FORMAT['padding']*2
# - self.BAR_FORMAT['length'] - len(etatext))
# full = int( math.ceil(barlength * (percent / 100.0)) )
# empty = int(barlength - full)
# if full == 0 or empty == 0: fullpiece = ('=' * full)
# else: fullpiece = ('=' * (full-1)) + '>'
# emptypiece = ('-' * empty)
# return [(self.BAR_FORMAT['text'] % (percent, fullpiece, emptypiece))+etatext]
, which may include functions, classes, or code. Output only the next line. | p = TimedProgressBar('bar') |
Here is a snippet: <|code_start|>#!/usr/bin/env python
#
# Copyright 2016 The Fabulous Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""I am *not* responsible if this causes severe physical or mental injury
"""
try:
while True:
for c in Magic.COLORS.iterkeys():
<|code_end|>
. Write the next line using the current file imports:
from fabulous.term import display, stdout, Magic
and context from other files:
# Path: fabulous/term.py
# class Term(object):
# class UnixTerm(Term):
# class CursesTerm(UnixTerm):
# class WinTerm(Term):
# class Win32Term(WinTerm):
# class WinCTypesTerm(WinTerm):
# class Magic(object):
# def __init__(self, stream):
# def bell(self):
# def display(self, codes=[], fg=None, bg=None):
# def move(self, place, distance = 1):
# def clear(self, scope = 'screen'):
# def get_size(self):
# def set_title(self, name):
# def isatty(self):
# def fileno(self):
# def write(self, text):
# def writelines(self, sequence_of_strings):
# def flush(self):
# def getch(self):
# def raw_input(self, prompt):
# def next(self):
# def readline(self, *args, **kwargs):
# def readlines(self, *args, **kwargs):
# def read(self, *args, **kwargs):
# def mode(self):
# def newlines(self):
# def encoding(self):
# def softspace(self):
# def name(self):
# def __init__(self, stream):
# def getch(self):
# def __init__(self, stream):
# def bell(self):
# def display(self, codes=[], fg=None, bg=None):
# def move(self, place, distance = 1):
# def clear(self, scope = 'screen'):
# def get_size(self):
# def set_title(self, name):
# def _get_cap(self, cap):
# def __init__(self, stream):
# def display(self, codes=[], fg=None, bg=None):
# def get_size(self):
# def _get_std_handle(self, handleno):
# def _get_console_info(self):
# def _clear_console(self, length, start):
# def _set_attributes(self, code):
# def _split_attributes(self, attrs):
# def _undim(self):
# def _display_default(self):
# def _display_bright(self):
# def _display_dim(self):
# def _display_reverse(self):
# def _display_hidden(self):
# def _get_position(self):
# def _set_position(self, coord):
# def move(self, place, distance = 1):
# def clear(self, scope = 'screen'):
# def getch(self):
# def bell(self):
# def __init__(self, stream):
# def set_title(self, name):
# def _get_console_info(self):
# def _get_std_handle(self, handle):
# def _get_title(self):
# def _set_attributes(self, attr):
# def _set_position(self, coord):
# def _clear_console(self, length, start):
# def _pyCoord_dict(self, coord):
# def _pySMALL_RECTType_dict(self, rect):
# def __init__(self, stream):
# def set_title(self, name):
# def _get_console_info(self):
# def _get_std_handle(self, handle):
# def _get_title(self):
# def _set_attributes(self, attr):
# def _set_position(self, coord):
# def _clear_console(self, length, start):
# def _get_coord(self, coord):
# def displayformat(codes=[], fg=None, bg=None):
# def rdisplay(codes):
# def display(codes=[], fg=None, bg=None):
# def display(codes=[], fg=None, bg=None):
# def _get_terms():
# def _get_term(termclass):
# STD_INPUT_HANDLE = -10
# STD_OUTPUT_HANDLE = -11
# STD_ERROR_HANDLE = -12
# FG_BLUE = 1 << 0
# FG_GREEN = 1 << 1
# FG_RED = 1 << 2
# FG_INTENSITY = 1 << 3
# BG_BLUE = 1 << 4
# BG_GREEN = 1 << 5
# BG_RED = 1 << 6
# BG_INTENSITY = 1 << 7
# FG_ALL = FG_BLUE | FG_GREEN | FG_RED
# BG_ALL = BG_BLUE | BG_GREEN | BG_RED
# FG = {
# 'black': 0,
# 'red': FG_RED,
# 'green': FG_GREEN,
# 'yellow': FG_GREEN | FG_RED,
# 'blue': FG_BLUE,
# 'magenta': FG_BLUE | FG_RED,
# 'cyan': FG_BLUE | FG_GREEN,
# 'white': FG_BLUE | FG_GREEN | FG_RED,
# }
# BG = {
# 'black':0,
# 'red':BG_RED,
# 'green':BG_GREEN,
# 'yellow':BG_GREEN | BG_RED,
# 'blue':BG_BLUE,
# 'magenta':BG_BLUE | BG_RED,
# 'cyan':BG_BLUE | BG_GREEN,
# 'white':BG_BLUE | BG_GREEN | BG_RED,
# }
# ESCAPE = '\x1b'
# CSI = ESCAPE +'['
# OSC = ESCAPE +']'
# RESET = ESCAPE + 'c'
# DISPLAY = {'default':0, 'bright':1, 'dim':2, 'underline':4, 'blink':5,
# 'reverse':7, 'hidden':8 }
# COLORS = { 'black':0, 'red':1, 'green':2, 'yellow':3, 'blue':4, 'magenta':5,
# 'cyan':6, 'white':7 }
, which may include functions, classes, or code. Output only the next line. | stdout.write(display(bg=c)) |
Given snippet: <|code_start|>#!/usr/bin/env python
#
# Copyright 2016 The Fabulous Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""I am *not* responsible if this causes severe physical or mental injury
"""
try:
while True:
for c in Magic.COLORS.iterkeys():
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from fabulous.term import display, stdout, Magic
and context:
# Path: fabulous/term.py
# class Term(object):
# class UnixTerm(Term):
# class CursesTerm(UnixTerm):
# class WinTerm(Term):
# class Win32Term(WinTerm):
# class WinCTypesTerm(WinTerm):
# class Magic(object):
# def __init__(self, stream):
# def bell(self):
# def display(self, codes=[], fg=None, bg=None):
# def move(self, place, distance = 1):
# def clear(self, scope = 'screen'):
# def get_size(self):
# def set_title(self, name):
# def isatty(self):
# def fileno(self):
# def write(self, text):
# def writelines(self, sequence_of_strings):
# def flush(self):
# def getch(self):
# def raw_input(self, prompt):
# def next(self):
# def readline(self, *args, **kwargs):
# def readlines(self, *args, **kwargs):
# def read(self, *args, **kwargs):
# def mode(self):
# def newlines(self):
# def encoding(self):
# def softspace(self):
# def name(self):
# def __init__(self, stream):
# def getch(self):
# def __init__(self, stream):
# def bell(self):
# def display(self, codes=[], fg=None, bg=None):
# def move(self, place, distance = 1):
# def clear(self, scope = 'screen'):
# def get_size(self):
# def set_title(self, name):
# def _get_cap(self, cap):
# def __init__(self, stream):
# def display(self, codes=[], fg=None, bg=None):
# def get_size(self):
# def _get_std_handle(self, handleno):
# def _get_console_info(self):
# def _clear_console(self, length, start):
# def _set_attributes(self, code):
# def _split_attributes(self, attrs):
# def _undim(self):
# def _display_default(self):
# def _display_bright(self):
# def _display_dim(self):
# def _display_reverse(self):
# def _display_hidden(self):
# def _get_position(self):
# def _set_position(self, coord):
# def move(self, place, distance = 1):
# def clear(self, scope = 'screen'):
# def getch(self):
# def bell(self):
# def __init__(self, stream):
# def set_title(self, name):
# def _get_console_info(self):
# def _get_std_handle(self, handle):
# def _get_title(self):
# def _set_attributes(self, attr):
# def _set_position(self, coord):
# def _clear_console(self, length, start):
# def _pyCoord_dict(self, coord):
# def _pySMALL_RECTType_dict(self, rect):
# def __init__(self, stream):
# def set_title(self, name):
# def _get_console_info(self):
# def _get_std_handle(self, handle):
# def _get_title(self):
# def _set_attributes(self, attr):
# def _set_position(self, coord):
# def _clear_console(self, length, start):
# def _get_coord(self, coord):
# def displayformat(codes=[], fg=None, bg=None):
# def rdisplay(codes):
# def display(codes=[], fg=None, bg=None):
# def display(codes=[], fg=None, bg=None):
# def _get_terms():
# def _get_term(termclass):
# STD_INPUT_HANDLE = -10
# STD_OUTPUT_HANDLE = -11
# STD_ERROR_HANDLE = -12
# FG_BLUE = 1 << 0
# FG_GREEN = 1 << 1
# FG_RED = 1 << 2
# FG_INTENSITY = 1 << 3
# BG_BLUE = 1 << 4
# BG_GREEN = 1 << 5
# BG_RED = 1 << 6
# BG_INTENSITY = 1 << 7
# FG_ALL = FG_BLUE | FG_GREEN | FG_RED
# BG_ALL = BG_BLUE | BG_GREEN | BG_RED
# FG = {
# 'black': 0,
# 'red': FG_RED,
# 'green': FG_GREEN,
# 'yellow': FG_GREEN | FG_RED,
# 'blue': FG_BLUE,
# 'magenta': FG_BLUE | FG_RED,
# 'cyan': FG_BLUE | FG_GREEN,
# 'white': FG_BLUE | FG_GREEN | FG_RED,
# }
# BG = {
# 'black':0,
# 'red':BG_RED,
# 'green':BG_GREEN,
# 'yellow':BG_GREEN | BG_RED,
# 'blue':BG_BLUE,
# 'magenta':BG_BLUE | BG_RED,
# 'cyan':BG_BLUE | BG_GREEN,
# 'white':BG_BLUE | BG_GREEN | BG_RED,
# }
# ESCAPE = '\x1b'
# CSI = ESCAPE +'['
# OSC = ESCAPE +']'
# RESET = ESCAPE + 'c'
# DISPLAY = {'default':0, 'bright':1, 'dim':2, 'underline':4, 'blink':5,
# 'reverse':7, 'hidden':8 }
# COLORS = { 'black':0, 'red':1, 'green':2, 'yellow':3, 'blue':4, 'magenta':5,
# 'cyan':6, 'white':7 }
which might include code, classes, or functions. Output only the next line. | stdout.write(display(bg=c)) |
Predict the next line for this snippet: <|code_start|> fabdir = os.path.dirname(fabulous.__file__)
for fn in ['balls.png',
'fabulous/balls.png',
os.path.join(fabdir, 'balls.png')]:
if os.path.exists(fn):
balls = fn
break
if not os.path.exists(balls):
ugh = urllib.urlopen('http://lobstertech.com/media/img/balls.png')
open('balls.png', 'w').write(ugh.read())
balls = 'balls.png'
for line in image.Image(balls):
printy(line)
wait()
section("Yes the output is optimized (JELLY-FISH)")
imp = " from fabulous import debug\n "
printy(bold(imp + 'print debug.DebugImage("balls.png")\n'))
for line in debug.DebugImage(balls):
printy(line)
wait()
def demo_text():
section('Fabulous Text Rendering')
imp = " from fabulous import text\n "
printy(bold(imp + 'print text.Text("Fabulous", shadow=True, skew=5)\n'))
<|code_end|>
with the help of current file imports:
import os
import fabulous
import urllib
from fabulous import text, utils, image, debug, xterm256
from fabulous.color import *
from fabulous.compatibility import printy
and context from other files:
# Path: fabulous/text.py
# class Text(image.Image):
# class FontNotFound(ValueError):
# def __init__(self, text, fsize=23, color="#0099ff", shadow=False,
# skew=None, font='NotoSans-Bold'):
# def resolve_font(name):
# def get_font_files():
# def main():
#
# Path: fabulous/utils.py
# def memoize(function):
# def _memoize(*args):
# def __init__(self, bgcolor='black'):
# def termfd(self):
# def dimensions(self):
# def width(self):
# def height(self):
# def _get_bgcolor(self):
# def _set_bgcolor(self, color):
# def pil_check():
# class TerminalInfo(object):
#
# Path: fabulous/image.py
# class Image(object):
# def __init__(self, path, width=None):
# def __iter__(self):
# def __str__(self):
# def size(self):
# def resize(self, width=None):
# def reduce(self, colors):
# def convert(self):
# def main():
#
# Path: fabulous/debug.py
# class DebugImage(image.Image):
# def reduce(self, colors):
# def main():
#
# Path: fabulous/xterm256.py
# CUBE_STEPS = [0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF]
# BASIC16 = ((0, 0, 0), (205, 0, 0), (0, 205, 0), (205, 205, 0),
# (0, 0, 238), (205, 0, 205), (0, 205, 205), (229, 229, 229),
# (127, 127, 127), (255, 0, 0), (0, 255, 0), (255, 255, 0),
# (92, 92, 255), (255, 0, 255), (0, 255, 255), (255, 255, 255))
# COLOR_TABLE = [xterm_to_rgb(i) for i in range(256)]
# def xterm_to_rgb(xcolor):
# def rgb_to_xterm(r, g, b):
# def compile_speedup():
# def xterm_to_rgb(xcolor):
#
# Path: fabulous/compatibility.py
# def printy(s):
# """Python 2/3 compatible print-like function"""
# if hasattr(s, 'as_utf8'):
# if hasattr(sys.stdout, 'buffer'):
# sys.stdout.buffer.write(s.as_utf8)
# sys.stdout.buffer.write(b"\n")
# else:
# sys.stdout.write(s.as_utf8)
# sys.stdout.write(b"\n")
# else:
# print(s)
, which may contain function names, class names, or code. Output only the next line. | printy(text.Text("Fabulous", shadow=True, skew=5)) |
Given the code snippet: <|code_start|> cube_color = lambda x,y,z: 16 + x + y*6 + z*6*6
for y in range(6):
line = " "
for z in range(6):
for x in range(6):
line += bg256(cube_color(x, y, z), ' ')
line += " "
printy(line)
printy("")
def f(xc):
s = highlight256(xc, "color %03d" % (xc))
rgb = xterm256.xterm_to_rgb(xc)
rgbs = ' (%3d, %3d, %3d)' % rgb
if rgb[0] == rgb[1] == rgb[2]:
s += bold(rgbs)
else:
s += rgbs
s += ' (%08d, %08d, %08d)' % tuple([int(bin(n)[2:]) for n in rgb])
return s
def l(c1, c2):
c1, c2 = f(c1), f(c2)
assert len(c1) == len(c2)
half = width // 2
assert half > len(c1)
pad = " " * ((width // 2 - len(c1)) // 2)
printy("%(pad)s%(c1)s%(pad)s%(pad)s%(c2)s" % {
'pad': pad, 'c1': c1, 'c2': c2})
<|code_end|>
, generate the next line using the imports in this file:
import os
import fabulous
import urllib
from fabulous import text, utils, image, debug, xterm256
from fabulous.color import *
from fabulous.compatibility import printy
and context (functions, classes, or occasionally code) from other files:
# Path: fabulous/text.py
# class Text(image.Image):
# class FontNotFound(ValueError):
# def __init__(self, text, fsize=23, color="#0099ff", shadow=False,
# skew=None, font='NotoSans-Bold'):
# def resolve_font(name):
# def get_font_files():
# def main():
#
# Path: fabulous/utils.py
# def memoize(function):
# def _memoize(*args):
# def __init__(self, bgcolor='black'):
# def termfd(self):
# def dimensions(self):
# def width(self):
# def height(self):
# def _get_bgcolor(self):
# def _set_bgcolor(self, color):
# def pil_check():
# class TerminalInfo(object):
#
# Path: fabulous/image.py
# class Image(object):
# def __init__(self, path, width=None):
# def __iter__(self):
# def __str__(self):
# def size(self):
# def resize(self, width=None):
# def reduce(self, colors):
# def convert(self):
# def main():
#
# Path: fabulous/debug.py
# class DebugImage(image.Image):
# def reduce(self, colors):
# def main():
#
# Path: fabulous/xterm256.py
# CUBE_STEPS = [0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF]
# BASIC16 = ((0, 0, 0), (205, 0, 0), (0, 205, 0), (205, 205, 0),
# (0, 0, 238), (205, 0, 205), (0, 205, 205), (229, 229, 229),
# (127, 127, 127), (255, 0, 0), (0, 255, 0), (255, 255, 0),
# (92, 92, 255), (255, 0, 255), (0, 255, 255), (255, 255, 255))
# COLOR_TABLE = [xterm_to_rgb(i) for i in range(256)]
# def xterm_to_rgb(xcolor):
# def rgb_to_xterm(r, g, b):
# def compile_speedup():
# def xterm_to_rgb(xcolor):
#
# Path: fabulous/compatibility.py
# def printy(s):
# """Python 2/3 compatible print-like function"""
# if hasattr(s, 'as_utf8'):
# if hasattr(sys.stdout, 'buffer'):
# sys.stdout.buffer.write(s.as_utf8)
# sys.stdout.buffer.write(b"\n")
# else:
# sys.stdout.write(s.as_utf8)
# sys.stdout.write(b"\n")
# else:
# print(s)
. Output only the next line. | width = utils.term.width |
Continue the code snippet: <|code_start|> input = raw_input
except NameError:
pass
def wait():
input("\nPress " + bold("enter") + " for more fun... ")
printy("")
def demo_image():
section("Semi-Transparent PNG")
imp = " from fabulous import image\n "
printy(bold(imp + 'print image.Image("balls.png")\n'))
balls = 'balls.png'
fabdir = os.path.dirname(fabulous.__file__)
for fn in ['balls.png',
'fabulous/balls.png',
os.path.join(fabdir, 'balls.png')]:
if os.path.exists(fn):
balls = fn
break
if not os.path.exists(balls):
ugh = urllib.urlopen('http://lobstertech.com/media/img/balls.png')
open('balls.png', 'w').write(ugh.read())
balls = 'balls.png'
<|code_end|>
. Use current file imports:
import os
import fabulous
import urllib
from fabulous import text, utils, image, debug, xterm256
from fabulous.color import *
from fabulous.compatibility import printy
and context (classes, functions, or code) from other files:
# Path: fabulous/text.py
# class Text(image.Image):
# class FontNotFound(ValueError):
# def __init__(self, text, fsize=23, color="#0099ff", shadow=False,
# skew=None, font='NotoSans-Bold'):
# def resolve_font(name):
# def get_font_files():
# def main():
#
# Path: fabulous/utils.py
# def memoize(function):
# def _memoize(*args):
# def __init__(self, bgcolor='black'):
# def termfd(self):
# def dimensions(self):
# def width(self):
# def height(self):
# def _get_bgcolor(self):
# def _set_bgcolor(self, color):
# def pil_check():
# class TerminalInfo(object):
#
# Path: fabulous/image.py
# class Image(object):
# def __init__(self, path, width=None):
# def __iter__(self):
# def __str__(self):
# def size(self):
# def resize(self, width=None):
# def reduce(self, colors):
# def convert(self):
# def main():
#
# Path: fabulous/debug.py
# class DebugImage(image.Image):
# def reduce(self, colors):
# def main():
#
# Path: fabulous/xterm256.py
# CUBE_STEPS = [0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF]
# BASIC16 = ((0, 0, 0), (205, 0, 0), (0, 205, 0), (205, 205, 0),
# (0, 0, 238), (205, 0, 205), (0, 205, 205), (229, 229, 229),
# (127, 127, 127), (255, 0, 0), (0, 255, 0), (255, 255, 0),
# (92, 92, 255), (255, 0, 255), (0, 255, 255), (255, 255, 255))
# COLOR_TABLE = [xterm_to_rgb(i) for i in range(256)]
# def xterm_to_rgb(xcolor):
# def rgb_to_xterm(r, g, b):
# def compile_speedup():
# def xterm_to_rgb(xcolor):
#
# Path: fabulous/compatibility.py
# def printy(s):
# """Python 2/3 compatible print-like function"""
# if hasattr(s, 'as_utf8'):
# if hasattr(sys.stdout, 'buffer'):
# sys.stdout.buffer.write(s.as_utf8)
# sys.stdout.buffer.write(b"\n")
# else:
# sys.stdout.write(s.as_utf8)
# sys.stdout.write(b"\n")
# else:
# print(s)
. Output only the next line. | for line in image.Image(balls): |
Using the snippet: <|code_start|> printy("")
def demo_image():
section("Semi-Transparent PNG")
imp = " from fabulous import image\n "
printy(bold(imp + 'print image.Image("balls.png")\n'))
balls = 'balls.png'
fabdir = os.path.dirname(fabulous.__file__)
for fn in ['balls.png',
'fabulous/balls.png',
os.path.join(fabdir, 'balls.png')]:
if os.path.exists(fn):
balls = fn
break
if not os.path.exists(balls):
ugh = urllib.urlopen('http://lobstertech.com/media/img/balls.png')
open('balls.png', 'w').write(ugh.read())
balls = 'balls.png'
for line in image.Image(balls):
printy(line)
wait()
section("Yes the output is optimized (JELLY-FISH)")
imp = " from fabulous import debug\n "
printy(bold(imp + 'print debug.DebugImage("balls.png")\n'))
<|code_end|>
, determine the next line of code. You have imports:
import os
import fabulous
import urllib
from fabulous import text, utils, image, debug, xterm256
from fabulous.color import *
from fabulous.compatibility import printy
and context (class names, function names, or code) available:
# Path: fabulous/text.py
# class Text(image.Image):
# class FontNotFound(ValueError):
# def __init__(self, text, fsize=23, color="#0099ff", shadow=False,
# skew=None, font='NotoSans-Bold'):
# def resolve_font(name):
# def get_font_files():
# def main():
#
# Path: fabulous/utils.py
# def memoize(function):
# def _memoize(*args):
# def __init__(self, bgcolor='black'):
# def termfd(self):
# def dimensions(self):
# def width(self):
# def height(self):
# def _get_bgcolor(self):
# def _set_bgcolor(self, color):
# def pil_check():
# class TerminalInfo(object):
#
# Path: fabulous/image.py
# class Image(object):
# def __init__(self, path, width=None):
# def __iter__(self):
# def __str__(self):
# def size(self):
# def resize(self, width=None):
# def reduce(self, colors):
# def convert(self):
# def main():
#
# Path: fabulous/debug.py
# class DebugImage(image.Image):
# def reduce(self, colors):
# def main():
#
# Path: fabulous/xterm256.py
# CUBE_STEPS = [0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF]
# BASIC16 = ((0, 0, 0), (205, 0, 0), (0, 205, 0), (205, 205, 0),
# (0, 0, 238), (205, 0, 205), (0, 205, 205), (229, 229, 229),
# (127, 127, 127), (255, 0, 0), (0, 255, 0), (255, 255, 0),
# (92, 92, 255), (255, 0, 255), (0, 255, 255), (255, 255, 255))
# COLOR_TABLE = [xterm_to_rgb(i) for i in range(256)]
# def xterm_to_rgb(xcolor):
# def rgb_to_xterm(r, g, b):
# def compile_speedup():
# def xterm_to_rgb(xcolor):
#
# Path: fabulous/compatibility.py
# def printy(s):
# """Python 2/3 compatible print-like function"""
# if hasattr(s, 'as_utf8'):
# if hasattr(sys.stdout, 'buffer'):
# sys.stdout.buffer.write(s.as_utf8)
# sys.stdout.buffer.write(b"\n")
# else:
# sys.stdout.write(s.as_utf8)
# sys.stdout.write(b"\n")
# else:
# print(s)
. Output only the next line. | for line in debug.DebugImage(balls): |
Continue the code snippet: <|code_start|>
wait()
def full_chart():
# grayscales
line = " "
for xc in range(232, 256):
line += bg256(xc, ' ')
printy(line)
line = " "
for xc in range(232, 256)[::-1]:
line += bg256(xc, ' ')
printy(line)
printy('')
# cube
printy("")
cube_color = lambda x,y,z: 16 + x + y*6 + z*6*6
for y in range(6):
line = " "
for z in range(6):
for x in range(6):
line += bg256(cube_color(x, y, z), ' ')
line += " "
printy(line)
printy("")
def f(xc):
s = highlight256(xc, "color %03d" % (xc))
<|code_end|>
. Use current file imports:
import os
import fabulous
import urllib
from fabulous import text, utils, image, debug, xterm256
from fabulous.color import *
from fabulous.compatibility import printy
and context (classes, functions, or code) from other files:
# Path: fabulous/text.py
# class Text(image.Image):
# class FontNotFound(ValueError):
# def __init__(self, text, fsize=23, color="#0099ff", shadow=False,
# skew=None, font='NotoSans-Bold'):
# def resolve_font(name):
# def get_font_files():
# def main():
#
# Path: fabulous/utils.py
# def memoize(function):
# def _memoize(*args):
# def __init__(self, bgcolor='black'):
# def termfd(self):
# def dimensions(self):
# def width(self):
# def height(self):
# def _get_bgcolor(self):
# def _set_bgcolor(self, color):
# def pil_check():
# class TerminalInfo(object):
#
# Path: fabulous/image.py
# class Image(object):
# def __init__(self, path, width=None):
# def __iter__(self):
# def __str__(self):
# def size(self):
# def resize(self, width=None):
# def reduce(self, colors):
# def convert(self):
# def main():
#
# Path: fabulous/debug.py
# class DebugImage(image.Image):
# def reduce(self, colors):
# def main():
#
# Path: fabulous/xterm256.py
# CUBE_STEPS = [0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF]
# BASIC16 = ((0, 0, 0), (205, 0, 0), (0, 205, 0), (205, 205, 0),
# (0, 0, 238), (205, 0, 205), (0, 205, 205), (229, 229, 229),
# (127, 127, 127), (255, 0, 0), (0, 255, 0), (255, 255, 0),
# (92, 92, 255), (255, 0, 255), (0, 255, 255), (255, 255, 255))
# COLOR_TABLE = [xterm_to_rgb(i) for i in range(256)]
# def xterm_to_rgb(xcolor):
# def rgb_to_xterm(r, g, b):
# def compile_speedup():
# def xterm_to_rgb(xcolor):
#
# Path: fabulous/compatibility.py
# def printy(s):
# """Python 2/3 compatible print-like function"""
# if hasattr(s, 'as_utf8'):
# if hasattr(sys.stdout, 'buffer'):
# sys.stdout.buffer.write(s.as_utf8)
# sys.stdout.buffer.write(b"\n")
# else:
# sys.stdout.write(s.as_utf8)
# sys.stdout.write(b"\n")
# else:
# print(s)
. Output only the next line. | rgb = xterm256.xterm_to_rgb(xc) |
Next line prediction: <|code_start|># Copyright 2016 The Fabulous Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
input = raw_input
except NameError:
pass
def wait():
input("\nPress " + bold("enter") + " for more fun... ")
<|code_end|>
. Use current file imports:
(import os
import fabulous
import urllib
from fabulous import text, utils, image, debug, xterm256
from fabulous.color import *
from fabulous.compatibility import printy)
and context including class names, function names, or small code snippets from other files:
# Path: fabulous/text.py
# class Text(image.Image):
# class FontNotFound(ValueError):
# def __init__(self, text, fsize=23, color="#0099ff", shadow=False,
# skew=None, font='NotoSans-Bold'):
# def resolve_font(name):
# def get_font_files():
# def main():
#
# Path: fabulous/utils.py
# def memoize(function):
# def _memoize(*args):
# def __init__(self, bgcolor='black'):
# def termfd(self):
# def dimensions(self):
# def width(self):
# def height(self):
# def _get_bgcolor(self):
# def _set_bgcolor(self, color):
# def pil_check():
# class TerminalInfo(object):
#
# Path: fabulous/image.py
# class Image(object):
# def __init__(self, path, width=None):
# def __iter__(self):
# def __str__(self):
# def size(self):
# def resize(self, width=None):
# def reduce(self, colors):
# def convert(self):
# def main():
#
# Path: fabulous/debug.py
# class DebugImage(image.Image):
# def reduce(self, colors):
# def main():
#
# Path: fabulous/xterm256.py
# CUBE_STEPS = [0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF]
# BASIC16 = ((0, 0, 0), (205, 0, 0), (0, 205, 0), (205, 205, 0),
# (0, 0, 238), (205, 0, 205), (0, 205, 205), (229, 229, 229),
# (127, 127, 127), (255, 0, 0), (0, 255, 0), (255, 255, 0),
# (92, 92, 255), (255, 0, 255), (0, 255, 255), (255, 255, 255))
# COLOR_TABLE = [xterm_to_rgb(i) for i in range(256)]
# def xterm_to_rgb(xcolor):
# def rgb_to_xterm(r, g, b):
# def compile_speedup():
# def xterm_to_rgb(xcolor):
#
# Path: fabulous/compatibility.py
# def printy(s):
# """Python 2/3 compatible print-like function"""
# if hasattr(s, 'as_utf8'):
# if hasattr(sys.stdout, 'buffer'):
# sys.stdout.buffer.write(s.as_utf8)
# sys.stdout.buffer.write(b"\n")
# else:
# sys.stdout.write(s.as_utf8)
# sys.stdout.write(b"\n")
# else:
# print(s)
. Output only the next line. | printy("") |
Based on the snippet: <|code_start|>#!/usr/bin/env python
#
# Copyright 2016 The Fabulous Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
stdout.write(display('default'))
stdout.write("default text\n")
stdout.write("regular foreground test:\n")
<|code_end|>
, predict the immediate next line with the help of imports:
from fabulous.term import display, stdout, Magic
and context (classes, functions, sometimes code) from other files:
# Path: fabulous/term.py
# class Term(object):
# class UnixTerm(Term):
# class CursesTerm(UnixTerm):
# class WinTerm(Term):
# class Win32Term(WinTerm):
# class WinCTypesTerm(WinTerm):
# class Magic(object):
# def __init__(self, stream):
# def bell(self):
# def display(self, codes=[], fg=None, bg=None):
# def move(self, place, distance = 1):
# def clear(self, scope = 'screen'):
# def get_size(self):
# def set_title(self, name):
# def isatty(self):
# def fileno(self):
# def write(self, text):
# def writelines(self, sequence_of_strings):
# def flush(self):
# def getch(self):
# def raw_input(self, prompt):
# def next(self):
# def readline(self, *args, **kwargs):
# def readlines(self, *args, **kwargs):
# def read(self, *args, **kwargs):
# def mode(self):
# def newlines(self):
# def encoding(self):
# def softspace(self):
# def name(self):
# def __init__(self, stream):
# def getch(self):
# def __init__(self, stream):
# def bell(self):
# def display(self, codes=[], fg=None, bg=None):
# def move(self, place, distance = 1):
# def clear(self, scope = 'screen'):
# def get_size(self):
# def set_title(self, name):
# def _get_cap(self, cap):
# def __init__(self, stream):
# def display(self, codes=[], fg=None, bg=None):
# def get_size(self):
# def _get_std_handle(self, handleno):
# def _get_console_info(self):
# def _clear_console(self, length, start):
# def _set_attributes(self, code):
# def _split_attributes(self, attrs):
# def _undim(self):
# def _display_default(self):
# def _display_bright(self):
# def _display_dim(self):
# def _display_reverse(self):
# def _display_hidden(self):
# def _get_position(self):
# def _set_position(self, coord):
# def move(self, place, distance = 1):
# def clear(self, scope = 'screen'):
# def getch(self):
# def bell(self):
# def __init__(self, stream):
# def set_title(self, name):
# def _get_console_info(self):
# def _get_std_handle(self, handle):
# def _get_title(self):
# def _set_attributes(self, attr):
# def _set_position(self, coord):
# def _clear_console(self, length, start):
# def _pyCoord_dict(self, coord):
# def _pySMALL_RECTType_dict(self, rect):
# def __init__(self, stream):
# def set_title(self, name):
# def _get_console_info(self):
# def _get_std_handle(self, handle):
# def _get_title(self):
# def _set_attributes(self, attr):
# def _set_position(self, coord):
# def _clear_console(self, length, start):
# def _get_coord(self, coord):
# def displayformat(codes=[], fg=None, bg=None):
# def rdisplay(codes):
# def display(codes=[], fg=None, bg=None):
# def display(codes=[], fg=None, bg=None):
# def _get_terms():
# def _get_term(termclass):
# STD_INPUT_HANDLE = -10
# STD_OUTPUT_HANDLE = -11
# STD_ERROR_HANDLE = -12
# FG_BLUE = 1 << 0
# FG_GREEN = 1 << 1
# FG_RED = 1 << 2
# FG_INTENSITY = 1 << 3
# BG_BLUE = 1 << 4
# BG_GREEN = 1 << 5
# BG_RED = 1 << 6
# BG_INTENSITY = 1 << 7
# FG_ALL = FG_BLUE | FG_GREEN | FG_RED
# BG_ALL = BG_BLUE | BG_GREEN | BG_RED
# FG = {
# 'black': 0,
# 'red': FG_RED,
# 'green': FG_GREEN,
# 'yellow': FG_GREEN | FG_RED,
# 'blue': FG_BLUE,
# 'magenta': FG_BLUE | FG_RED,
# 'cyan': FG_BLUE | FG_GREEN,
# 'white': FG_BLUE | FG_GREEN | FG_RED,
# }
# BG = {
# 'black':0,
# 'red':BG_RED,
# 'green':BG_GREEN,
# 'yellow':BG_GREEN | BG_RED,
# 'blue':BG_BLUE,
# 'magenta':BG_BLUE | BG_RED,
# 'cyan':BG_BLUE | BG_GREEN,
# 'white':BG_BLUE | BG_GREEN | BG_RED,
# }
# ESCAPE = '\x1b'
# CSI = ESCAPE +'['
# OSC = ESCAPE +']'
# RESET = ESCAPE + 'c'
# DISPLAY = {'default':0, 'bright':1, 'dim':2, 'underline':4, 'blink':5,
# 'reverse':7, 'hidden':8 }
# COLORS = { 'black':0, 'red':1, 'green':2, 'yellow':3, 'blue':4, 'magenta':5,
# 'cyan':6, 'white':7 }
. Output only the next line. | for color in Magic.COLORS.iterkeys(): |
Continue the code snippet: <|code_start|># Copyright 2016 The Fabulous Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
fabulous.debug
~~~~~~~~~~~~~~
The debug module provides the ability to print images as ASCII. It isn't a
good ASCII representation like cacalib. This module is mostly intended for
debugging purposes (hence the name.)
"""
from __future__ import print_function
<|code_end|>
. Use current file imports:
import sys
import itertools
from fabulous import image
and context (classes, functions, or code) from other files:
# Path: fabulous/image.py
# class Image(object):
# def __init__(self, path, width=None):
# def __iter__(self):
# def __str__(self):
# def size(self):
# def resize(self, width=None):
# def reduce(self, colors):
# def convert(self):
# def main():
. Output only the next line. | class DebugImage(image.Image): |
Given snippet: <|code_start|># you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
fabulous.rotating_cube
~~~~~~~~~~~~~~~~~~~~~~
Command for animating a wireframe rotating cube in the terminal.
"""
from __future__ import with_statement
from __future__ import division
class Frame(object):
"""Canvas object for drawing a frame to be printed
"""
def __enter__(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import time
from math import cos, sin, pi
from fabulous import color, utils
and context:
# Path: fabulous/color.py
# OVERLINE = u'\u203e'
# def esc(*codes):
# def __init__(self, *items):
# def __str__(self):
# def __repr__(self):
# def __len__(self):
# def __len__(self):
# def __add__(self, cs):
# def __radd__(self, cs):
# def as_utf8(self):
# def join(self, iterable):
# def __init__(self, color, *items):
# def __str__(self):
# def __init__(self, color, *items):
# def __str__(self):
# def __init__(self, color, *items):
# def __str__(self):
# def __init__(self, color, *items):
# def __str__(self):
# def h1(title, line=OVERLINE):
# def parse_color(color):
# def complement(color):
# def section(title, bar=OVERLINE, strm=sys.stdout):
# class ColorString(object):
# class ColorString256(ColorString):
# class ColorStringTrue(ColorString):
# class plain(ColorString):
# class bold(ColorString):
# class italic(ColorString):
# class underline(ColorString):
# class underline2(ColorString):
# class strike(ColorString):
# class blink(ColorString):
# class flip(ColorString):
# class black(ColorString):
# class red(ColorString):
# class green(ColorString):
# class yellow(ColorString):
# class blue(ColorString):
# class magenta(ColorString):
# class cyan(ColorString):
# class white(ColorString):
# class highlight_black(ColorString):
# class highlight_red(ColorString):
# class highlight_green(ColorString):
# class highlight_yellow(ColorString):
# class highlight_blue(ColorString):
# class highlight_magenta(ColorString):
# class highlight_cyan(ColorString):
# class highlight_white(ColorString):
# class black_bg(ColorString):
# class red_bg(ColorString):
# class green_bg(ColorString):
# class yellow_bg(ColorString):
# class blue_bg(ColorString):
# class magenta_bg(ColorString):
# class cyan_bg(ColorString):
# class white_bg(ColorString):
# class fg256(ColorString256):
# class fgtrue(ColorStringTrue):
# class bg256(ColorString256):
# class bgtrue(ColorStringTrue):
# class highlight256(ColorString256):
# class highlighttrue(ColorStringTrue):
# class complement256(ColorString256):
# class complementtrue(ColorStringTrue):
#
# Path: fabulous/utils.py
# def memoize(function):
# def _memoize(*args):
# def __init__(self, bgcolor='black'):
# def termfd(self):
# def dimensions(self):
# def width(self):
# def height(self):
# def _get_bgcolor(self):
# def _set_bgcolor(self, color):
# def pil_check():
# class TerminalInfo(object):
which might include code, classes, or functions. Output only the next line. | self.width = utils.term.width |
Here is a snippet: <|code_start|>
PATHS = []
class TemplateNotFound(Exception):
pass
class TemplateLoader(dict):
def __init__(self, paths):
self.paths = [
(pathlib.Path.cwd() / path).resolve()
for path in paths
]
def load(self, name, raw=False):
for path in self.paths:
full_path = path / name
try:
full_path.relative_to(path)
except ValueError:
# XXX Raise Suspicious Op?
continue
if full_path.exists() and full_path.is_file():
with full_path.open(encoding='utf-8') as fin:
src = fin.read()
<|code_end|>
. Write the next line using the current file imports:
import pathlib
from .compiler import kompile
and context from other files:
# Path: knights/compiler.py
# def kompile(src, raw=False, filename='<compiler>', loader=None, **kwargs):
# '''
# Creates a new class based on the supplied template, and returnsit.
#
# class Template(object):
# def __call__(self, context):
# return ''.join(self._iterator(context))
#
# def _iterator(self, context):
# return map(str, self._root(context)
#
# def _root(self, context):
# yield ''
# yield ...
# yield from self.head(context)
#
# Blocks create new methods, and add a 'yield from self.{block}(context)' to
# the current function
#
# '''
#
# parser = Parser(src, loader=loader)
# parser.load_library('knights.tags')
# parser.load_library('knights.helpers')
#
# parser.build_method('_root')
#
# if parser.parent:
# # Remove _root from the method list
# parser.methods = [
# method for method in parser.methods if method.name != '_root'
# ]
#
# klass = parser.build_class()
#
# # Wrap it in a module
# inst = ast.Module(body=[klass])
#
# ast.fix_missing_locations(inst)
#
# if kwargs.get('astor', False):
# import astor
# print(astor.to_source(inst))
#
# # Compile code to create class
# code = compile(inst, filename=filename, mode='exec', optimize=2)
#
# # Execute it and return the instance
# g = {
# '_': Helpers(parser.helpers),
# 'parent': parser.parent,
# 'ContextScope': ContextScope,
# }
# eval(code, g)
#
# klass = g['Template']
# if raw:
# return klass
# return klass()
, which may include functions, classes, or code. Output only the next line. | return kompile(src, raw=raw, filename=str(full_path), loader=self) |
Given the code snippet: <|code_start|> ('{{ 12e-1 }}', '1.2'),
('{{ 12E-1 }}', '1.2'),
)
for src, expect in TESTS:
self.assertRendered(src, expect)
class VariableSyntaxTest(TemplateTestCase):
def test_direct(self):
# A list of (template, context, output)
TESTS = (
('{{ a }}', {'a': 'yes'}, 'yes'),
)
for src, ctx, expect in TESTS:
self.assertRendered(src, expect, ctx)
def test_index(self):
# A list of (template, context, output)
TESTS = (
('{{ a[1] }}', {'a': ['yes', 'no']}, 'no'),
('{{ a["b"] }}', {'a': {'b': 'yes'}}, 'yes'),
('{{ a[c] }}', {'a': {'b': 'yes', 'c': 'no'}, 'c': 'b'}, 'yes'),
)
for src, ctx, expect in TESTS:
self.assertRendered(src, expect, ctx)
def test_attribute(self):
# A list of (template, context, output)
TESTS = (
<|code_end|>
, generate the next line using the imports in this file:
from .utils import TemplateTestCase, Mock
and context (functions, classes, or occasionally code) from other files:
# Path: tests/utils.py
# class TemplateTestCase(unittest.TestCase):
# @classmethod
# def setUpClass(cls):
# cls.loader = loader.TemplateLoader([
# pathlib.Path(__file__).parent / 'templates',
# ])
#
# def assertRendered(self, source, expected, context=None):
# try:
# tmpl = compiler.kompile(source, loader=self.loader)
# rendered = tmpl({} if context is None else context)
# self.assertEqual(rendered, expected)
# except Exception as e:
# if hasattr(e, 'message'):
# standardMsg = e.message
# elif hasattr(e, 'args') and len(e.args) > 0:
# standardMsg = e.args[0]
# else:
# standardMsg = ''
# msg = 'Failed rendering template %s:\n%s: %s' % (
# source, e.__class__.__name__, standardMsg)
# self.fail(msg)
#
# class Mock(object):
# def __init__(self, **kwargs):
# for k, v in kwargs.items():
# setattr(self, k, v)
. Output only the next line. | ('{{ a.b }}', {'a': Mock(b=1)}, '1'), |
Based on the snippet: <|code_start|>
parser = Parser(src, loader=loader)
parser.load_library('knights.tags')
parser.load_library('knights.helpers')
parser.build_method('_root')
if parser.parent:
# Remove _root from the method list
parser.methods = [
method for method in parser.methods if method.name != '_root'
]
klass = parser.build_class()
# Wrap it in a module
inst = ast.Module(body=[klass])
ast.fix_missing_locations(inst)
if kwargs.get('astor', False):
print(astor.to_source(inst))
# Compile code to create class
code = compile(inst, filename=filename, mode='exec', optimize=2)
# Execute it and return the instance
g = {
'_': Helpers(parser.helpers),
'parent': parser.parent,
<|code_end|>
, predict the immediate next line with the help of imports:
import ast
import astor
from .context import ContextScope
from .parser import Parser
from .utils import Helpers
and context (classes, functions, sometimes code) from other files:
# Path: knights/context.py
# class ContextScope(dict):
# __slots__ = ('parent',)
#
# def __init__(self, parent, **kwargs):
# dict.__init__(self, **kwargs)
# self.parent = parent
#
# def __missing__(self, key):
# return self.parent[key]
#
# def __enter__(self):
# return self
#
# def __exit__(self, a, b, c):
# pass
#
# Path: knights/parser.py
# class Parser:
# def __init__(self, src, loader):
# self.loader = loader
# self.stream = tokenise(src)
# self.parent = None
# self.methods = []
# self.tags = {}
# self.helpers = {}
#
# def load_library(self, path):
# '''
# Load a template library into the state.
# '''
# module = import_module(path)
# self.tags.update(module.register.tags)
# self.helpers.update(module.register.helpers)
#
# def build_class(self):
# cls = ast.ClassDef(
# name='Template',
# bases=[
# _a.Name('parent' if self.parent else 'object')
# ],
# body=self.methods,
# keywords=[],
# starargs=None,
# kwargs=None,
# decorator_list=[]
# )
#
# cls.body.extend([
#
# # def _iterator(self, contetxt):
# # return map(str, self._root(context))
# ast.FunctionDef(
# name='_iterator',
# args=_a.arguments(_a.args('self', 'context')),
# body=[
# ast.Return(
# value=_a.Call(_a.Name('map'), [
# _a.Name('str'),
# _a.Call(_a.Attribute(_a.Name('self'), '_root'), [
# _a.Name('context'),
# ]),
# ])
# )
# ],
# decorator_list=[],
# ),
#
# # def __call__(self, context):
# # return ''.join(map(str, self._root(context)))
# ast.FunctionDef(
# name='__call__',
# args=_a.arguments(_a.args('self', 'context')),
# body=[
# ast.Return(
# value=_a.Call(
# _a.Attribute(ast.Str(s=''), 'join'),
# args=[
# _a.Call(_a.Name('map'), [
# _a.Name('str'),
# _a.Call(
# _a.Attribute(_a.Name('self'), '_root'),
# [_a.Name('context')]
# ),
# ]),
# ],
# )
# ),
# ],
# decorator_list=[],
# ),
#
# ])
#
# return cls
#
# def build_method(self, name, endnodes=None):
# # Build the body
# if endnodes:
# body, _ = self.parse_nodes_until(*endnodes)
# else:
# body = list(self.parse_node())
# # If it's empty include a blank
# if not body:
# body.append(ast.Expr(value=ast.Yield(value=ast.Str(s=''))))
#
# # Create the method
# func = ast.FunctionDef(
# name=name,
# args=_a.arguments(_a.args('self', 'context')),
# body=body,
# decorator_list=[],
# )
#
# self.methods.append(func)
#
# return func
#
# def parse_node(self, endnodes=None):
# for token in self.stream:
# if token.mode == TokenType.text:
# node = ast.Yield(value=ast.Str(s=token.content))
# elif token.mode == TokenType.var:
# code = self.parse_expression(token.content)
# node = ast.Yield(value=code)
# elif token.mode == TokenType.block:
# bits = token.content.strip().split(' ', 1)
# tag_name = bits.pop(0).strip()
# if endnodes and tag_name in endnodes:
# yield tag_name
# return
# func = self.tags[tag_name]
# node = func(self, *bits)
# else:
# # Must be a comment
# continue
#
# if node is None:
# continue
# if isinstance(node, (ast.Yield, ast.YieldFrom)):
# node = ast.Expr(value=node)
# node.lineno = token.lineno
# yield node
#
# def parse_nodes_until(self, *endnodes):
# '''
# '''
# *nodes, end = list(self.parse_node(endnodes=endnodes))
# if end not in endnodes:
# raise SyntaxError('Did not find end node %r - found %r instead' % (
# endnodes, end
# ))
# return nodes, end
#
# def parse_expression(self, expr):
# code = ast.parse(expr, mode='eval')
# visitor.visit(code)
# return code.body
#
# def parse_args(self, expr):
# code = ast.parse('x(%s)' % expr, mode='eval')
#
# return code.body.args, code.body.keywords
#
# Path: knights/utils.py
# class Helpers:
# '''
# Provide a cheaper way to access helpers
# '''
# def __init__(self, members):
# for key, value in members.items():
# setattr(self, key, value)
. Output only the next line. | 'ContextScope': ContextScope, |
Here is a snippet: <|code_start|>
def kompile(src, raw=False, filename='<compiler>', loader=None, **kwargs):
'''
Creates a new class based on the supplied template, and returnsit.
class Template(object):
def __call__(self, context):
return ''.join(self._iterator(context))
def _iterator(self, context):
return map(str, self._root(context)
def _root(self, context):
yield ''
yield ...
yield from self.head(context)
Blocks create new methods, and add a 'yield from self.{block}(context)' to
the current function
'''
<|code_end|>
. Write the next line using the current file imports:
import ast
import astor
from .context import ContextScope
from .parser import Parser
from .utils import Helpers
and context from other files:
# Path: knights/context.py
# class ContextScope(dict):
# __slots__ = ('parent',)
#
# def __init__(self, parent, **kwargs):
# dict.__init__(self, **kwargs)
# self.parent = parent
#
# def __missing__(self, key):
# return self.parent[key]
#
# def __enter__(self):
# return self
#
# def __exit__(self, a, b, c):
# pass
#
# Path: knights/parser.py
# class Parser:
# def __init__(self, src, loader):
# self.loader = loader
# self.stream = tokenise(src)
# self.parent = None
# self.methods = []
# self.tags = {}
# self.helpers = {}
#
# def load_library(self, path):
# '''
# Load a template library into the state.
# '''
# module = import_module(path)
# self.tags.update(module.register.tags)
# self.helpers.update(module.register.helpers)
#
# def build_class(self):
# cls = ast.ClassDef(
# name='Template',
# bases=[
# _a.Name('parent' if self.parent else 'object')
# ],
# body=self.methods,
# keywords=[],
# starargs=None,
# kwargs=None,
# decorator_list=[]
# )
#
# cls.body.extend([
#
# # def _iterator(self, contetxt):
# # return map(str, self._root(context))
# ast.FunctionDef(
# name='_iterator',
# args=_a.arguments(_a.args('self', 'context')),
# body=[
# ast.Return(
# value=_a.Call(_a.Name('map'), [
# _a.Name('str'),
# _a.Call(_a.Attribute(_a.Name('self'), '_root'), [
# _a.Name('context'),
# ]),
# ])
# )
# ],
# decorator_list=[],
# ),
#
# # def __call__(self, context):
# # return ''.join(map(str, self._root(context)))
# ast.FunctionDef(
# name='__call__',
# args=_a.arguments(_a.args('self', 'context')),
# body=[
# ast.Return(
# value=_a.Call(
# _a.Attribute(ast.Str(s=''), 'join'),
# args=[
# _a.Call(_a.Name('map'), [
# _a.Name('str'),
# _a.Call(
# _a.Attribute(_a.Name('self'), '_root'),
# [_a.Name('context')]
# ),
# ]),
# ],
# )
# ),
# ],
# decorator_list=[],
# ),
#
# ])
#
# return cls
#
# def build_method(self, name, endnodes=None):
# # Build the body
# if endnodes:
# body, _ = self.parse_nodes_until(*endnodes)
# else:
# body = list(self.parse_node())
# # If it's empty include a blank
# if not body:
# body.append(ast.Expr(value=ast.Yield(value=ast.Str(s=''))))
#
# # Create the method
# func = ast.FunctionDef(
# name=name,
# args=_a.arguments(_a.args('self', 'context')),
# body=body,
# decorator_list=[],
# )
#
# self.methods.append(func)
#
# return func
#
# def parse_node(self, endnodes=None):
# for token in self.stream:
# if token.mode == TokenType.text:
# node = ast.Yield(value=ast.Str(s=token.content))
# elif token.mode == TokenType.var:
# code = self.parse_expression(token.content)
# node = ast.Yield(value=code)
# elif token.mode == TokenType.block:
# bits = token.content.strip().split(' ', 1)
# tag_name = bits.pop(0).strip()
# if endnodes and tag_name in endnodes:
# yield tag_name
# return
# func = self.tags[tag_name]
# node = func(self, *bits)
# else:
# # Must be a comment
# continue
#
# if node is None:
# continue
# if isinstance(node, (ast.Yield, ast.YieldFrom)):
# node = ast.Expr(value=node)
# node.lineno = token.lineno
# yield node
#
# def parse_nodes_until(self, *endnodes):
# '''
# '''
# *nodes, end = list(self.parse_node(endnodes=endnodes))
# if end not in endnodes:
# raise SyntaxError('Did not find end node %r - found %r instead' % (
# endnodes, end
# ))
# return nodes, end
#
# def parse_expression(self, expr):
# code = ast.parse(expr, mode='eval')
# visitor.visit(code)
# return code.body
#
# def parse_args(self, expr):
# code = ast.parse('x(%s)' % expr, mode='eval')
#
# return code.body.args, code.body.keywords
#
# Path: knights/utils.py
# class Helpers:
# '''
# Provide a cheaper way to access helpers
# '''
# def __init__(self, members):
# for key, value in members.items():
# setattr(self, key, value)
, which may include functions, classes, or code. Output only the next line. | parser = Parser(src, loader=loader) |
Predict the next line after this snippet: <|code_start|>
'''
parser = Parser(src, loader=loader)
parser.load_library('knights.tags')
parser.load_library('knights.helpers')
parser.build_method('_root')
if parser.parent:
# Remove _root from the method list
parser.methods = [
method for method in parser.methods if method.name != '_root'
]
klass = parser.build_class()
# Wrap it in a module
inst = ast.Module(body=[klass])
ast.fix_missing_locations(inst)
if kwargs.get('astor', False):
print(astor.to_source(inst))
# Compile code to create class
code = compile(inst, filename=filename, mode='exec', optimize=2)
# Execute it and return the instance
g = {
<|code_end|>
using the current file's imports:
import ast
import astor
from .context import ContextScope
from .parser import Parser
from .utils import Helpers
and any relevant context from other files:
# Path: knights/context.py
# class ContextScope(dict):
# __slots__ = ('parent',)
#
# def __init__(self, parent, **kwargs):
# dict.__init__(self, **kwargs)
# self.parent = parent
#
# def __missing__(self, key):
# return self.parent[key]
#
# def __enter__(self):
# return self
#
# def __exit__(self, a, b, c):
# pass
#
# Path: knights/parser.py
# class Parser:
# def __init__(self, src, loader):
# self.loader = loader
# self.stream = tokenise(src)
# self.parent = None
# self.methods = []
# self.tags = {}
# self.helpers = {}
#
# def load_library(self, path):
# '''
# Load a template library into the state.
# '''
# module = import_module(path)
# self.tags.update(module.register.tags)
# self.helpers.update(module.register.helpers)
#
# def build_class(self):
# cls = ast.ClassDef(
# name='Template',
# bases=[
# _a.Name('parent' if self.parent else 'object')
# ],
# body=self.methods,
# keywords=[],
# starargs=None,
# kwargs=None,
# decorator_list=[]
# )
#
# cls.body.extend([
#
# # def _iterator(self, contetxt):
# # return map(str, self._root(context))
# ast.FunctionDef(
# name='_iterator',
# args=_a.arguments(_a.args('self', 'context')),
# body=[
# ast.Return(
# value=_a.Call(_a.Name('map'), [
# _a.Name('str'),
# _a.Call(_a.Attribute(_a.Name('self'), '_root'), [
# _a.Name('context'),
# ]),
# ])
# )
# ],
# decorator_list=[],
# ),
#
# # def __call__(self, context):
# # return ''.join(map(str, self._root(context)))
# ast.FunctionDef(
# name='__call__',
# args=_a.arguments(_a.args('self', 'context')),
# body=[
# ast.Return(
# value=_a.Call(
# _a.Attribute(ast.Str(s=''), 'join'),
# args=[
# _a.Call(_a.Name('map'), [
# _a.Name('str'),
# _a.Call(
# _a.Attribute(_a.Name('self'), '_root'),
# [_a.Name('context')]
# ),
# ]),
# ],
# )
# ),
# ],
# decorator_list=[],
# ),
#
# ])
#
# return cls
#
# def build_method(self, name, endnodes=None):
# # Build the body
# if endnodes:
# body, _ = self.parse_nodes_until(*endnodes)
# else:
# body = list(self.parse_node())
# # If it's empty include a blank
# if not body:
# body.append(ast.Expr(value=ast.Yield(value=ast.Str(s=''))))
#
# # Create the method
# func = ast.FunctionDef(
# name=name,
# args=_a.arguments(_a.args('self', 'context')),
# body=body,
# decorator_list=[],
# )
#
# self.methods.append(func)
#
# return func
#
# def parse_node(self, endnodes=None):
# for token in self.stream:
# if token.mode == TokenType.text:
# node = ast.Yield(value=ast.Str(s=token.content))
# elif token.mode == TokenType.var:
# code = self.parse_expression(token.content)
# node = ast.Yield(value=code)
# elif token.mode == TokenType.block:
# bits = token.content.strip().split(' ', 1)
# tag_name = bits.pop(0).strip()
# if endnodes and tag_name in endnodes:
# yield tag_name
# return
# func = self.tags[tag_name]
# node = func(self, *bits)
# else:
# # Must be a comment
# continue
#
# if node is None:
# continue
# if isinstance(node, (ast.Yield, ast.YieldFrom)):
# node = ast.Expr(value=node)
# node.lineno = token.lineno
# yield node
#
# def parse_nodes_until(self, *endnodes):
# '''
# '''
# *nodes, end = list(self.parse_node(endnodes=endnodes))
# if end not in endnodes:
# raise SyntaxError('Did not find end node %r - found %r instead' % (
# endnodes, end
# ))
# return nodes, end
#
# def parse_expression(self, expr):
# code = ast.parse(expr, mode='eval')
# visitor.visit(code)
# return code.body
#
# def parse_args(self, expr):
# code = ast.parse('x(%s)' % expr, mode='eval')
#
# return code.body.args, code.body.keywords
#
# Path: knights/utils.py
# class Helpers:
# '''
# Provide a cheaper way to access helpers
# '''
# def __init__(self, members):
# for key, value in members.items():
# setattr(self, key, value)
. Output only the next line. | '_': Helpers(parser.helpers), |
Given the following code snippet before the placeholder: <|code_start|>'''
Default helper functions
'''
register = Library()
@register.helper
def addslashes(value):
return value.replace('\\', '\\\\').replace('"', '\\"').replace("'", "\\'")
@register.helper
def capfirst(value):
return value and value[0].upper() + value[1:]
ESCAPES = {
<|code_end|>
, predict the next line using imports from the current file:
from .escape import escape_html, escape_js
from .library import Library
and context including class names, function names, and sometimes code from other files:
# Path: knights/escape.py
#
# Path: knights/library.py
# class Library:
# '''
# Container for registering tags and helpers
# '''
# def __init__(self):
# self.tags = {}
# self.helpers = {}
#
# def tag(self, func=None, name=None):
# if func is None:
# return partial(self.tag, name=name)
#
# if name is None:
# name = func.__name__
#
# self.tags[name] = func
# return func
#
# def helper(self, func=None, name=None):
# if func is None:
# return partial(self.helper, name=name)
#
# if name is None:
# name = func.__name__
#
# self.helpers[name] = func
# return func
. Output only the next line. | 'html': escape_html, |
Predict the next line after this snippet: <|code_start|>'''
Default helper functions
'''
register = Library()
@register.helper
def addslashes(value):
return value.replace('\\', '\\\\').replace('"', '\\"').replace("'", "\\'")
@register.helper
def capfirst(value):
return value and value[0].upper() + value[1:]
ESCAPES = {
'html': escape_html,
<|code_end|>
using the current file's imports:
from .escape import escape_html, escape_js
from .library import Library
and any relevant context from other files:
# Path: knights/escape.py
#
# Path: knights/library.py
# class Library:
# '''
# Container for registering tags and helpers
# '''
# def __init__(self):
# self.tags = {}
# self.helpers = {}
#
# def tag(self, func=None, name=None):
# if func is None:
# return partial(self.tag, name=name)
#
# if name is None:
# name = func.__name__
#
# self.tags[name] = func
# return func
#
# def helper(self, func=None, name=None):
# if func is None:
# return partial(self.helper, name=name)
#
# if name is None:
# name = func.__name__
#
# self.helpers[name] = func
# return func
. Output only the next line. | 'js': escape_js, |
Based on the snippet: <|code_start|> '{% for a, b in seq %}{{ a }} == {{ b }},{% endfor %}',
'a == 1,b == 2,',
{'seq': (('a', 1), ('b', 2))}
)
def test_for_empty_false(self):
self.assertRendered(
'{% for a, b in seq %}{{ a }} == {{ b }},{% empty %}empty{% endfor %}',
'a == 1,b == 2,',
{'seq': (('a', 1), ('b', 2))},
)
def test_for_empty_true(self):
self.assertRendered(
'{% for a, b in seq %}{{ a }} == {{ b }},{% empty %}empty{% endfor %}',
'empty',
{'seq': ()},
)
def test_scope(self):
self.assertRendered(
'{% for a in seq %}{{ a * b }} {% endfor %}',
'2 4 6 ',
{'seq': (1, 2, 3), 'b': 2},
)
def test_attr_source(self):
self.assertRendered(
'{% for a in obj.seq %}{{ a }}{% endfor %}',
'1234',
<|code_end|>
, predict the immediate next line with the help of imports:
import pathlib
from .utils import TemplateTestCase, Mock
and context (classes, functions, sometimes code) from other files:
# Path: tests/utils.py
# class TemplateTestCase(unittest.TestCase):
# @classmethod
# def setUpClass(cls):
# cls.loader = loader.TemplateLoader([
# pathlib.Path(__file__).parent / 'templates',
# ])
#
# def assertRendered(self, source, expected, context=None):
# try:
# tmpl = compiler.kompile(source, loader=self.loader)
# rendered = tmpl({} if context is None else context)
# self.assertEqual(rendered, expected)
# except Exception as e:
# if hasattr(e, 'message'):
# standardMsg = e.message
# elif hasattr(e, 'args') and len(e.args) > 0:
# standardMsg = e.args[0]
# else:
# standardMsg = ''
# msg = 'Failed rendering template %s:\n%s: %s' % (
# source, e.__class__.__name__, standardMsg)
# self.fail(msg)
#
# class Mock(object):
# def __init__(self, **kwargs):
# for k, v in kwargs.items():
# setattr(self, k, v)
. Output only the next line. | {'obj': Mock(seq=[1, 2, 3, 4])}, |
Given snippet: <|code_start|>
class KnightsTemplater(BaseEngine):
def __init__(self, params):
params = params.copy()
super(KnightsTemplater, self).__init__(params)
self.loader = TemplateLoader(self.template_dirs)
def from_string(self, template_code):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from collections import defaultdict
from django.template.backends.base import BaseEngine
from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
from django.template.base import (TemplateDoesNotExist, # NOQA
TemplateSyntaxError)
from .compiler import kompile
from .loader import TemplateLoader, TemplateNotFound
and context:
# Path: knights/compiler.py
# def kompile(src, raw=False, filename='<compiler>', loader=None, **kwargs):
# '''
# Creates a new class based on the supplied template, and returnsit.
#
# class Template(object):
# def __call__(self, context):
# return ''.join(self._iterator(context))
#
# def _iterator(self, context):
# return map(str, self._root(context)
#
# def _root(self, context):
# yield ''
# yield ...
# yield from self.head(context)
#
# Blocks create new methods, and add a 'yield from self.{block}(context)' to
# the current function
#
# '''
#
# parser = Parser(src, loader=loader)
# parser.load_library('knights.tags')
# parser.load_library('knights.helpers')
#
# parser.build_method('_root')
#
# if parser.parent:
# # Remove _root from the method list
# parser.methods = [
# method for method in parser.methods if method.name != '_root'
# ]
#
# klass = parser.build_class()
#
# # Wrap it in a module
# inst = ast.Module(body=[klass])
#
# ast.fix_missing_locations(inst)
#
# if kwargs.get('astor', False):
# import astor
# print(astor.to_source(inst))
#
# # Compile code to create class
# code = compile(inst, filename=filename, mode='exec', optimize=2)
#
# # Execute it and return the instance
# g = {
# '_': Helpers(parser.helpers),
# 'parent': parser.parent,
# 'ContextScope': ContextScope,
# }
# eval(code, g)
#
# klass = g['Template']
# if raw:
# return klass
# return klass()
#
# Path: knights/loader.py
# class TemplateLoader(dict):
# def __init__(self, paths):
# self.paths = [
# (pathlib.Path.cwd() / path).resolve()
# for path in paths
# ]
#
# def load(self, name, raw=False):
# for path in self.paths:
# full_path = path / name
# try:
# full_path.relative_to(path)
# except ValueError:
# # XXX Raise Suspicious Op?
# continue
# if full_path.exists() and full_path.is_file():
# with full_path.open(encoding='utf-8') as fin:
# src = fin.read()
#
# return kompile(src, raw=raw, filename=str(full_path), loader=self)
# raise TemplateNotFound(name)
#
# def __missing__(self, key):
# self[key] = tmpl = self.load(key)
# return tmpl
#
# class TemplateNotFound(Exception):
# pass
which might include code, classes, or functions. Output only the next line. | tmpl = kompile(template_code, loader=self.loader) |
Using the snippet: <|code_start|>
class KnightsTemplater(BaseEngine):
def __init__(self, params):
params = params.copy()
super(KnightsTemplater, self).__init__(params)
<|code_end|>
, determine the next line of code. You have imports:
from collections import defaultdict
from django.template.backends.base import BaseEngine
from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
from django.template.base import (TemplateDoesNotExist, # NOQA
TemplateSyntaxError)
from .compiler import kompile
from .loader import TemplateLoader, TemplateNotFound
and context (class names, function names, or code) available:
# Path: knights/compiler.py
# def kompile(src, raw=False, filename='<compiler>', loader=None, **kwargs):
# '''
# Creates a new class based on the supplied template, and returnsit.
#
# class Template(object):
# def __call__(self, context):
# return ''.join(self._iterator(context))
#
# def _iterator(self, context):
# return map(str, self._root(context)
#
# def _root(self, context):
# yield ''
# yield ...
# yield from self.head(context)
#
# Blocks create new methods, and add a 'yield from self.{block}(context)' to
# the current function
#
# '''
#
# parser = Parser(src, loader=loader)
# parser.load_library('knights.tags')
# parser.load_library('knights.helpers')
#
# parser.build_method('_root')
#
# if parser.parent:
# # Remove _root from the method list
# parser.methods = [
# method for method in parser.methods if method.name != '_root'
# ]
#
# klass = parser.build_class()
#
# # Wrap it in a module
# inst = ast.Module(body=[klass])
#
# ast.fix_missing_locations(inst)
#
# if kwargs.get('astor', False):
# import astor
# print(astor.to_source(inst))
#
# # Compile code to create class
# code = compile(inst, filename=filename, mode='exec', optimize=2)
#
# # Execute it and return the instance
# g = {
# '_': Helpers(parser.helpers),
# 'parent': parser.parent,
# 'ContextScope': ContextScope,
# }
# eval(code, g)
#
# klass = g['Template']
# if raw:
# return klass
# return klass()
#
# Path: knights/loader.py
# class TemplateLoader(dict):
# def __init__(self, paths):
# self.paths = [
# (pathlib.Path.cwd() / path).resolve()
# for path in paths
# ]
#
# def load(self, name, raw=False):
# for path in self.paths:
# full_path = path / name
# try:
# full_path.relative_to(path)
# except ValueError:
# # XXX Raise Suspicious Op?
# continue
# if full_path.exists() and full_path.is_file():
# with full_path.open(encoding='utf-8') as fin:
# src = fin.read()
#
# return kompile(src, raw=raw, filename=str(full_path), loader=self)
# raise TemplateNotFound(name)
#
# def __missing__(self, key):
# self[key] = tmpl = self.load(key)
# return tmpl
#
# class TemplateNotFound(Exception):
# pass
. Output only the next line. | self.loader = TemplateLoader(self.template_dirs) |
Next line prediction: <|code_start|>
class KnightsTemplater(BaseEngine):
def __init__(self, params):
params = params.copy()
super(KnightsTemplater, self).__init__(params)
self.loader = TemplateLoader(self.template_dirs)
def from_string(self, template_code):
tmpl = kompile(template_code, loader=self.loader)
return Template(tmpl)
def get_template(self, template_name):
try:
tmpl = self.loader[template_name]
<|code_end|>
. Use current file imports:
(from collections import defaultdict
from django.template.backends.base import BaseEngine
from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
from django.template.base import (TemplateDoesNotExist, # NOQA
TemplateSyntaxError)
from .compiler import kompile
from .loader import TemplateLoader, TemplateNotFound)
and context including class names, function names, or small code snippets from other files:
# Path: knights/compiler.py
# def kompile(src, raw=False, filename='<compiler>', loader=None, **kwargs):
# '''
# Creates a new class based on the supplied template, and returnsit.
#
# class Template(object):
# def __call__(self, context):
# return ''.join(self._iterator(context))
#
# def _iterator(self, context):
# return map(str, self._root(context)
#
# def _root(self, context):
# yield ''
# yield ...
# yield from self.head(context)
#
# Blocks create new methods, and add a 'yield from self.{block}(context)' to
# the current function
#
# '''
#
# parser = Parser(src, loader=loader)
# parser.load_library('knights.tags')
# parser.load_library('knights.helpers')
#
# parser.build_method('_root')
#
# if parser.parent:
# # Remove _root from the method list
# parser.methods = [
# method for method in parser.methods if method.name != '_root'
# ]
#
# klass = parser.build_class()
#
# # Wrap it in a module
# inst = ast.Module(body=[klass])
#
# ast.fix_missing_locations(inst)
#
# if kwargs.get('astor', False):
# import astor
# print(astor.to_source(inst))
#
# # Compile code to create class
# code = compile(inst, filename=filename, mode='exec', optimize=2)
#
# # Execute it and return the instance
# g = {
# '_': Helpers(parser.helpers),
# 'parent': parser.parent,
# 'ContextScope': ContextScope,
# }
# eval(code, g)
#
# klass = g['Template']
# if raw:
# return klass
# return klass()
#
# Path: knights/loader.py
# class TemplateLoader(dict):
# def __init__(self, paths):
# self.paths = [
# (pathlib.Path.cwd() / path).resolve()
# for path in paths
# ]
#
# def load(self, name, raw=False):
# for path in self.paths:
# full_path = path / name
# try:
# full_path.relative_to(path)
# except ValueError:
# # XXX Raise Suspicious Op?
# continue
# if full_path.exists() and full_path.is_file():
# with full_path.open(encoding='utf-8') as fin:
# src = fin.read()
#
# return kompile(src, raw=raw, filename=str(full_path), loader=self)
# raise TemplateNotFound(name)
#
# def __missing__(self, key):
# self[key] = tmpl = self.load(key)
# return tmpl
#
# class TemplateNotFound(Exception):
# pass
. Output only the next line. | except TemplateNotFound: |
Given the code snippet: <|code_start|>
class Mock(object):
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
class TemplateTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.loader = loader.TemplateLoader([
pathlib.Path(__file__).parent / 'templates',
])
def assertRendered(self, source, expected, context=None):
try:
<|code_end|>
, generate the next line using the imports in this file:
import pathlib
import unittest
from knights import compiler, loader
and context (functions, classes, or occasionally code) from other files:
# Path: knights/compiler.py
# def kompile(src, raw=False, filename='<compiler>', loader=None, **kwargs):
#
# Path: knights/loader.py
# PATHS = []
# class TemplateNotFound(Exception):
# class TemplateLoader(dict):
# def __init__(self, paths):
# def load(self, name, raw=False):
# def __missing__(self, key):
. Output only the next line. | tmpl = compiler.kompile(source, loader=self.loader) |
Based on the snippet: <|code_start|>
class Mock(object):
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
class TemplateTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
<|code_end|>
, predict the immediate next line with the help of imports:
import pathlib
import unittest
from knights import compiler, loader
and context (classes, functions, sometimes code) from other files:
# Path: knights/compiler.py
# def kompile(src, raw=False, filename='<compiler>', loader=None, **kwargs):
#
# Path: knights/loader.py
# PATHS = []
# class TemplateNotFound(Exception):
# class TemplateLoader(dict):
# def __init__(self, paths):
# def load(self, name, raw=False):
# def __missing__(self, key):
. Output only the next line. | cls.loader = loader.TemplateLoader([ |
Here is a snippet: <|code_start|> if style == self.langDic[self.langName]['m042_default']:
cmds.setAttr(self.moduleGrp+".style", 0)
# for Biped style:
if style == self.langDic[self.langName]['m026_biped']:
cmds.setAttr(self.moduleGrp+".style", 1)
def createGuide(self, *args):
dpBaseClass.StartClass.createGuide(self)
# Custom GUIDE:
cmds.setAttr(self.moduleGrp+".moduleNamespace", self.moduleGrp[:self.moduleGrp.rfind(":")], type='string')
cmds.addAttr(self.moduleGrp, longName="nJoints", attributeType='long', defaultValue=1)
cmds.addAttr(self.moduleGrp, longName="style", attributeType='enum', enumName=self.langDic[self.langName]['m042_default']+':'+self.langDic[self.langName]['m026_biped'])
self.cvJointLoc = self.ctrls.cvJointLoc(ctrlName=self.guideName+"_JointLoc1", r=0.5, d=1, guide=True)
self.cvEndJoint = self.ctrls.cvLocator(ctrlName=self.guideName+"_JointEnd", r=0.1, d=1, guide=True)
cmds.parent(self.cvEndJoint, self.cvJointLoc)
cmds.setAttr(self.cvEndJoint+".tz", 1.3)
cmds.transformLimits(self.cvEndJoint, tz=(0.01, 1), etz=(True, False))
self.ctrls.setLockHide([self.cvEndJoint], ['tx', 'ty', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'])
cmds.parent(self.cvJointLoc, self.moduleGrp)
# Edit GUIDE:
cmds.setAttr(self.moduleGrp+".rx", -90)
cmds.setAttr(self.moduleGrp+".ry", -90)
cmds.setAttr(self.moduleGrp+"_RadiusCtrl.tx", 4)
self.changeJointNumber(3)
def changeJointNumber(self, enteredNJoints, *args):
""" Edit the number of joints in the guide.
"""
<|code_end|>
. Write the next line using the current file imports:
from maya import cmds
from .Library import dpUtils
from . import dpBaseClass
from . import dpLayoutClass
and context from other files:
# Path: dpAutoRigSystem/Modules/Library/dpUtils.py
# def findEnv(key, path):
# def findPath(filename):
# def findAllFiles(path, dir, ext):
# def findAllModules(path, dir):
# def findAllModuleNames(path, dir):
# def findLastNumber(nameList, basename):
# def findModuleLastNumber(className, typeName):
# def normalizeText(enteredText="", prefixMax=4):
# def useDefaultRenderLayer():
# def zeroOut(transformList=[], offset=False):
# def originedFrom(objName="", attrString=""):
# def getOriginedFromDic():
# def addHook(objName="", hookType="staticHook"):
# def hook():
# def clearNodeGrp(nodeGrpName='dpAR_GuideMirror_Grp', attrFind='guideBaseMirror', unparent=False):
# def getGuideChildrenList(nodeName):
# def mirroredGuideFather(nodeName):
# def getParentsList(nodeName):
# def getModulesToBeRigged(instanceList):
# def getCtrlRadius(nodeName):
# def zeroOutJoints(jntList=None, displayBone=False):
# def clearDpArAttr(itemList):
# def deleteChildren(item):
# def setJointLabel(jointName, sideNumber, typeNumber, labelString):
# def deleteJointLabel(jointName):
# def extractSuffix(nodeName):
# def filterName(name, itemList, separator):
# def checkRawURLForUpdate(DPAR_VERSION, DPAR_RAWURL, *args):
# def visitWebSite(website, *args):
# def checkLoadedPlugin(pluginName, exceptName=None, message="Not loaded plugin", *args):
# def twistBoneMatrix(nodeA, nodeB, twistBoneName, twistBoneMD=None, axis='Z', inverse=True, *args):
# def validateName(nodeName, suffix=None, *args):
# def articulationJoint(fatherNode, brotherNode, corrNumber=0, dist=1, jarRadius=1.5, doScale=True, *args):
# def getNodeByMessage(grpAttrName, *args):
# def attachToMotionPath(nodeName, curveName, mopName, uValue):
# def profiler(func):
# def runProfile(*args, **kwargs):
# def extract_world_scale_from_matrix(obj):
# DPAR_PROFILE_MODE = False
, which may include functions, classes, or code. Output only the next line. | dpUtils.useDefaultRenderLayer() |
Continue the code snippet: <|code_start|> cmds.addAttr(self.moduleGrp, longName="flip", attributeType='bool')
cmds.setAttr(self.moduleGrp+".flip", 0)
cmds.setAttr(self.moduleGrp+".moduleNamespace", self.moduleGrp[:self.moduleGrp.rfind(":")], type='string')
cmds.addAttr(self.moduleGrp, longName="articulation", attributeType='bool')
cmds.setAttr(self.moduleGrp+".articulation", 0)
self.cvJointLoc = self.ctrls.cvJointLoc(ctrlName=self.guideName+"_JointLoc1", r=0.3, d=1, guide=True)
self.jGuide1 = cmds.joint(name=self.guideName+"_JGuide1", radius=0.001)
cmds.setAttr(self.jGuide1+".template", 1)
cmds.parent(self.jGuide1, self.moduleGrp, relative=True)
self.cvEndJoint = self.ctrls.cvLocator(ctrlName=self.guideName+"_JointEnd", r=0.1, d=1, guide=True)
cmds.parent(self.cvEndJoint, self.cvJointLoc)
cmds.setAttr(self.cvEndJoint+".tz", 1.3)
self.jGuideEnd = cmds.joint(name=self.guideName+"_JGuideEnd", radius=0.001)
cmds.setAttr(self.jGuideEnd+".template", 1)
cmds.transformLimits(self.cvEndJoint, tz=(0.01, 1), etz=(True, False))
self.ctrls.setLockHide([self.cvEndJoint], ['tx', 'ty', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'])
cmds.parent(self.cvJointLoc, self.moduleGrp)
cmds.parent(self.jGuideEnd, self.jGuide1)
cmds.parentConstraint(self.cvJointLoc, self.jGuide1, maintainOffset=False, name=self.jGuide1+"_PaC")
cmds.parentConstraint(self.cvEndJoint, self.jGuideEnd, maintainOffset=False, name=self.jGuideEnd+"_PaC")
def changeJointNumber(self, enteredNJoints, *args):
""" Edit the number of joints in the guide.
"""
<|code_end|>
. Use current file imports:
from maya import cmds
from .Library import dpUtils
from . import dpBaseClass
from . import dpLayoutClass
and context (classes, functions, or code) from other files:
# Path: dpAutoRigSystem/Modules/Library/dpUtils.py
# def findEnv(key, path):
# def findPath(filename):
# def findAllFiles(path, dir, ext):
# def findAllModules(path, dir):
# def findAllModuleNames(path, dir):
# def findLastNumber(nameList, basename):
# def findModuleLastNumber(className, typeName):
# def normalizeText(enteredText="", prefixMax=4):
# def useDefaultRenderLayer():
# def zeroOut(transformList=[], offset=False):
# def originedFrom(objName="", attrString=""):
# def getOriginedFromDic():
# def addHook(objName="", hookType="staticHook"):
# def hook():
# def clearNodeGrp(nodeGrpName='dpAR_GuideMirror_Grp', attrFind='guideBaseMirror', unparent=False):
# def getGuideChildrenList(nodeName):
# def mirroredGuideFather(nodeName):
# def getParentsList(nodeName):
# def getModulesToBeRigged(instanceList):
# def getCtrlRadius(nodeName):
# def zeroOutJoints(jntList=None, displayBone=False):
# def clearDpArAttr(itemList):
# def deleteChildren(item):
# def setJointLabel(jointName, sideNumber, typeNumber, labelString):
# def deleteJointLabel(jointName):
# def extractSuffix(nodeName):
# def filterName(name, itemList, separator):
# def checkRawURLForUpdate(DPAR_VERSION, DPAR_RAWURL, *args):
# def visitWebSite(website, *args):
# def checkLoadedPlugin(pluginName, exceptName=None, message="Not loaded plugin", *args):
# def twistBoneMatrix(nodeA, nodeB, twistBoneName, twistBoneMD=None, axis='Z', inverse=True, *args):
# def validateName(nodeName, suffix=None, *args):
# def articulationJoint(fatherNode, brotherNode, corrNumber=0, dist=1, jarRadius=1.5, doScale=True, *args):
# def getNodeByMessage(grpAttrName, *args):
# def attachToMotionPath(nodeName, curveName, mopName, uValue):
# def profiler(func):
# def runProfile(*args, **kwargs):
# def extract_world_scale_from_matrix(obj):
# DPAR_PROFILE_MODE = False
. Output only the next line. | dpUtils.useDefaultRenderLayer() |
Using the snippet: <|code_start|> noseName = dpUIinst.langDic[dpUIinst.langName]['m078_nose']
tongueName = dpUIinst.langDic[dpUIinst.langName]['m077_tongue']
tailName = dpUIinst.langDic[dpUIinst.langName]['m039_tail']
toeName = dpUIinst.langDic[dpUIinst.langName]['c013_RevFoot_D'].capitalize()
frontName = dpUIinst.langDic[dpUIinst.langName]['c056_front']
backName = dpUIinst.langDic[dpUIinst.langName]['c057_back']
simple = dpUIinst.langDic[dpUIinst.langName]['i175_simple']
complete = dpUIinst.langDic[dpUIinst.langName]['i176_complete']
cancel = dpUIinst.langDic[dpUIinst.langName]['i132_cancel']
userMessage = dpUIinst.langDic[dpUIinst.langName]['i177_chooseMessage']
# getting Simple or Complete module guides to create:
userDetail = getUserDetail(simple, complete, cancel, userMessage)
if not userDetail == cancel:
# number of modules to create:
if userDetail == simple:
maxProcess = 8
else:
maxProcess = 20
# Starting progress window
progressAmount = 0
cmds.progressWindow(title='Quadruped Guides', progress=progressAmount, status=doingName+': 0%', isInterruptable=False)
# Update progress window
progressAmount += 1
cmds.progressWindow(edit=True, maxValue=maxProcess, progress=progressAmount, status=(doingName+': ' + repr(progressAmount) + ' '+spineName))
# woking with SPINE system:
# create spine module instance:
<|code_end|>
, determine the next line of code. You have imports:
from maya import cmds
from maya import mel
from ..Modules.dpBaseClass import RigType
and context (class names, function names, or code) available:
# Path: dpAutoRigSystem/Modules/dpBaseClass.py
# class RigType(object):
# biped = "biped"
# quadruped = "quadruped"
# default = "unknown" #Support old guide system
. Output only the next line. | spineInstance = dpUIinst.initGuide('dpSpine', guideDir, RigType.quadruped) |
Using the snippet: <|code_start|> cmds.setAttr(self.cvUpperLipLoc+".translateY", 2.9)
cmds.setAttr(self.cvUpperLipLoc+".translateZ", 3.5)
cmds.setAttr(self.cvLowerLipLoc+".translateY", 2.3)
cmds.setAttr(self.cvLowerLipLoc+".translateZ", 3.5)
cmds.setAttr(self.cvLCornerLipLoc+".translateX", 0.6)
cmds.setAttr(self.cvLCornerLipLoc+".translateY", 2.6)
cmds.setAttr(self.cvLCornerLipLoc+".translateZ", 3.4)
self.lipMD = cmds.createNode("multiplyDivide", name=self.guideName+"_Lip_MD")
cmds.connectAttr(self.cvLCornerLipLoc+".translateX", self.lipMD+".input1X", force=True)
cmds.connectAttr(self.cvLCornerLipLoc+".translateY", self.lipMD+".input1Y", force=True)
cmds.connectAttr(self.cvLCornerLipLoc+".translateZ", self.lipMD+".input1Z", force=True)
cmds.connectAttr(self.lipMD+".outputX", self.cvRCornerLipLoc+".translateX", force=True)
cmds.connectAttr(self.lipMD+".outputY", self.cvRCornerLipLoc+".translateY", force=True)
cmds.connectAttr(self.lipMD+".outputZ", self.cvRCornerLipLoc+".translateZ", force=True)
cmds.setAttr(self.lipMD+".input2X", -1)
cmds.setAttr(self.cvRCornerLipLoc+".template", 1)
# make parenting between cvLocs:
cmds.parent(self.cvNeckLoc, self.moduleGrp)
cmds.parent(self.cvHeadLoc, self.cvNeckLoc)
cmds.parent(self.cvUpperJawLoc, self.cvJawLoc, self.cvHeadLoc)
cmds.parent(self.cvChinLoc, self.cvJawLoc)
cmds.parent(self.cvChewLoc, self.cvLowerLipLoc, self.cvChinLoc)
cmds.parent(self.cvLCornerLipLoc, self.cvJawLoc)
cmds.parent(self.cvRCornerLipLoc, self.cvJawLoc)
cmds.parent(self.cvUpperLipLoc, self.cvUpperHeadLoc, self.cvUpperJawLoc)
def changeJointNumber(self, enteredNJoints, *args):
""" Edit the number of joints in the guide.
"""
<|code_end|>
, determine the next line of code. You have imports:
from maya import cmds
from .Library import dpUtils
from . import dpBaseClass
from . import dpLayoutClass
and context (class names, function names, or code) available:
# Path: dpAutoRigSystem/Modules/Library/dpUtils.py
# def findEnv(key, path):
# def findPath(filename):
# def findAllFiles(path, dir, ext):
# def findAllModules(path, dir):
# def findAllModuleNames(path, dir):
# def findLastNumber(nameList, basename):
# def findModuleLastNumber(className, typeName):
# def normalizeText(enteredText="", prefixMax=4):
# def useDefaultRenderLayer():
# def zeroOut(transformList=[], offset=False):
# def originedFrom(objName="", attrString=""):
# def getOriginedFromDic():
# def addHook(objName="", hookType="staticHook"):
# def hook():
# def clearNodeGrp(nodeGrpName='dpAR_GuideMirror_Grp', attrFind='guideBaseMirror', unparent=False):
# def getGuideChildrenList(nodeName):
# def mirroredGuideFather(nodeName):
# def getParentsList(nodeName):
# def getModulesToBeRigged(instanceList):
# def getCtrlRadius(nodeName):
# def zeroOutJoints(jntList=None, displayBone=False):
# def clearDpArAttr(itemList):
# def deleteChildren(item):
# def setJointLabel(jointName, sideNumber, typeNumber, labelString):
# def deleteJointLabel(jointName):
# def extractSuffix(nodeName):
# def filterName(name, itemList, separator):
# def checkRawURLForUpdate(DPAR_VERSION, DPAR_RAWURL, *args):
# def visitWebSite(website, *args):
# def checkLoadedPlugin(pluginName, exceptName=None, message="Not loaded plugin", *args):
# def twistBoneMatrix(nodeA, nodeB, twistBoneName, twistBoneMD=None, axis='Z', inverse=True, *args):
# def validateName(nodeName, suffix=None, *args):
# def articulationJoint(fatherNode, brotherNode, corrNumber=0, dist=1, jarRadius=1.5, doScale=True, *args):
# def getNodeByMessage(grpAttrName, *args):
# def attachToMotionPath(nodeName, curveName, mopName, uValue):
# def profiler(func):
# def runProfile(*args, **kwargs):
# def extract_world_scale_from_matrix(obj):
# DPAR_PROFILE_MODE = False
. Output only the next line. | dpUtils.useDefaultRenderLayer() |
Given the code snippet: <|code_start|># importing libraries:
# global variables to this module:
CLASS_NAME = "ColorOverride"
TITLE = "m047_colorOver"
DESCRIPTION = "m048_coloOverDesc"
ICON = "/Icons/dp_colorOverride.png"
DPCO_VERSION = "2.1"
class ColorOverride(object):
def __init__(self, dpUIinst, presetDic, presetName, *args, **kwargs):
# defining variables
self.dpUIinst = dpUIinst
self.presetDic = presetDic
self.presetName = presetName
<|code_end|>
, generate the next line using the imports in this file:
from maya import cmds
from functools import partial
from ..Modules.Library import dpControls
and context (functions, classes, or occasionally code) from other files:
# Path: dpAutoRigSystem/Modules/Library/dpControls.py
# class ControlClass(object):
# def __init__(self, dpUIinst, presetDic, presetName, moduleGrp=None, *args):
# def colorShape(self, objList, color, rgb=False, *args):
# def renameShape(self, transformList, *args):
# def directConnect(self, fromObj, toObj, attrList=['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'], f=True, *args):
# def setLockHide(self, objList, attrList, l=True, k=False, *args):
# def setNonKeyable(self, objList, attrList, *args):
# def setNotRenderable(self, objList, *args):
# def distanceBet(self, a, b, name="temp_DistBet", keep=False, *args):
# def middlePoint(self, a, b, createLocator=False, *args):
# def createSimpleRibbon(self, name='ribbon', totalJoints=6, jointLabelNumber=0, jointLabelName="SimpleRibbon", *args):
# def getControlNodeById(self, ctrlType, *args):
# def getControlModuleById(self, ctrlType, *args):
# def getControlDegreeById(self, ctrlType, *args):
# def getControlInstance(self, instanceName, *args):
# def cvControl(self, ctrlType, ctrlName, r=1, d=1, dir='+Y', rot=(0, 0, 0), *args):
# def cvLocator(self, ctrlName, r=1, d=1, guide=False, *args):
# def cvJointLoc(self, ctrlName, r=0.3, d=1, rot=(0, 0, 0), guide=True, *args):
# def cvCharacter(self, ctrlType, ctrlName, r=1, d=1, dir="+Y", rot=(0, 0, 0), *args):
# def findHistory(self, objList, historyName, *args):
# def cvBaseGuide(self, ctrlName, r=1, *args):
# def setAndFreeze(nodeName="", tx=None, ty=None, tz=None, rx=None, ry=None, rz=None, sx=None, sy=None, sz=None, freeze=True):
# def copyAttr(self, sourceItem=False, attrList=False, verbose=False, *args):
# def pasteAttr(self, destinationList=False, verbose=False, *args):
# def copyAndPasteAttr(self, verbose=False, *args):
# def transferAttr(self, sourceItem, destinationList, attrList, *args):
# def transferShape(self, deleteSource=False, clearDestinationShapes=True, sourceItem=None, destinationList=None, applyColor=True, *args):
# def setSourceColorOverride(self, sourceItem, destinationList, *args):
# def resetCurve(self, changeDegree=False, transformList=False, *args):
# def dpCreatePreset(self, *args):
# def dpCheckLinearUnit(self, origRadius, defaultUnit="centimeter", *args):
# def shapeSizeSetup(self, transformNode, *args):
# def connectShapeSize(self, clusterHandle, *args):
# def addGuideAttrs(self, ctrlName, *args):
# def createPinGuide(self, ctrlName, *args):
# def setPinnedGuideColor(self, ctrlName, status, color, *args):
# def jobPinGuide(self, ctrlName, *args):
# def startPinGuide(self, guideBase, *args):
# def unPinGuide(self, guideBase, *args):
# def importCalibration(self, *args):
# def mirrorCalibration(self, nodeName=False, fromPrefix=False, toPrefix=False, *args):
# def transferCalibration(self, sourceItem=False, destinationList=False, attrList=False, verbose=True, *args):
# def setCalibrationAttr(self, nodeName, attrList, *args):
# def getCalibrationAttr(self, nodeName, *args):
. Output only the next line. | self.ctrls = dpControls.ControlClass(self.dpUIinst, self.presetDic, self.presetName) |
Continue the code snippet: <|code_start|> # get rigs names:
self.mirrorNames = cmds.getAttr(self.moduleGrp+".mirrorName")
# get first and last letters to use as side initials (prefix):
sideList = [self.mirrorNames[0]+'_', self.mirrorNames[len(self.mirrorNames) - 1]+'_']
for s, side in enumerate(sideList):
duplicated = cmds.duplicate(self.moduleGrp, name=side+self.userGuideName+'_Guide_Base')[0]
allGuideList = cmds.listRelatives(duplicated, allDescendents=True)
for item in allGuideList:
cmds.rename(item, side+self.userGuideName+"_"+item)
self.mirrorGrp = cmds.group(name="Guide_Base_Grp", empty=True)
cmds.parent(side+self.userGuideName+'_Guide_Base', self.mirrorGrp, absolute=True)
# re-rename grp:
cmds.rename(self.mirrorGrp, side+self.userGuideName+'_'+self.mirrorGrp)
# do a group mirror with negative scaling:
if s == 1:
for axis in self.mirrorAxis:
cmds.setAttr(side+self.userGuideName+'_'+self.mirrorGrp+'.scale'+axis, -1)
# joint labelling:
jointLabelAdd = 1
else: # if not mirror:
duplicated = cmds.duplicate(self.moduleGrp, name=self.userGuideName+'_Guide_Base')[0]
allGuideList = cmds.listRelatives(duplicated, allDescendents=True)
for item in allGuideList:
cmds.rename(item, self.userGuideName+"_"+item)
self.mirrorGrp = cmds.group(self.userGuideName+'_Guide_Base', name="Guide_Base_Grp", relative=True)
# re-rename grp:
cmds.rename(self.mirrorGrp, self.userGuideName+'_'+self.mirrorGrp)
# joint labelling:
jointLabelAdd = 0
# store the number of this guide by module type
<|code_end|>
. Use current file imports:
from maya import cmds
from .Library import dpUtils
from . import dpBaseClass
from . import dpLayoutClass
and context (classes, functions, or code) from other files:
# Path: dpAutoRigSystem/Modules/Library/dpUtils.py
# def findEnv(key, path):
# def findPath(filename):
# def findAllFiles(path, dir, ext):
# def findAllModules(path, dir):
# def findAllModuleNames(path, dir):
# def findLastNumber(nameList, basename):
# def findModuleLastNumber(className, typeName):
# def normalizeText(enteredText="", prefixMax=4):
# def useDefaultRenderLayer():
# def zeroOut(transformList=[], offset=False):
# def originedFrom(objName="", attrString=""):
# def getOriginedFromDic():
# def addHook(objName="", hookType="staticHook"):
# def hook():
# def clearNodeGrp(nodeGrpName='dpAR_GuideMirror_Grp', attrFind='guideBaseMirror', unparent=False):
# def getGuideChildrenList(nodeName):
# def mirroredGuideFather(nodeName):
# def getParentsList(nodeName):
# def getModulesToBeRigged(instanceList):
# def getCtrlRadius(nodeName):
# def zeroOutJoints(jntList=None, displayBone=False):
# def clearDpArAttr(itemList):
# def deleteChildren(item):
# def setJointLabel(jointName, sideNumber, typeNumber, labelString):
# def deleteJointLabel(jointName):
# def extractSuffix(nodeName):
# def filterName(name, itemList, separator):
# def checkRawURLForUpdate(DPAR_VERSION, DPAR_RAWURL, *args):
# def visitWebSite(website, *args):
# def checkLoadedPlugin(pluginName, exceptName=None, message="Not loaded plugin", *args):
# def twistBoneMatrix(nodeA, nodeB, twistBoneName, twistBoneMD=None, axis='Z', inverse=True, *args):
# def validateName(nodeName, suffix=None, *args):
# def articulationJoint(fatherNode, brotherNode, corrNumber=0, dist=1, jarRadius=1.5, doScale=True, *args):
# def getNodeByMessage(grpAttrName, *args):
# def attachToMotionPath(nodeName, curveName, mopName, uValue):
# def profiler(func):
# def runProfile(*args, **kwargs):
# def extract_world_scale_from_matrix(obj):
# DPAR_PROFILE_MODE = False
. Output only the next line. | dpAR_count = dpUtils.findModuleLastNumber(CLASS_NAME, "dpAR_type")+1 |
Predict the next line after this snippet: <|code_start|> self.ctrls.directConnect(self.cvJointLoc, self.jGuide, ['tx', 'ty', 'tz', 'rx', 'ry', 'rz'])
self.cvEndJoint = self.ctrls.cvLocator(ctrlName=self.guideName+"_JointEnd", r=0.2, d=1, guide=True)
cmds.parent(self.cvEndJoint, self.cvJointLoc)
cmds.setAttr(self.cvEndJoint+".tz", 1.3)
self.jGuideEnd = cmds.joint(name=self.guideName+"_JGuideEnd", radius=0.001)
cmds.setAttr(self.jGuideEnd+".template", 1)
cmds.transformLimits(self.cvEndJoint, tz=(0.01, 1), etz=(True, False))
self.ctrls.setLockHide([self.cvEndJoint], ['rx', 'ry', 'rz', 'sx', 'sy', 'sz'])
cmds.parent(self.cvJointLoc1, self.moduleGrp)
cmds.parent(self.jGuideEnd, self.jGuide1)
self.ctrls.directConnect(self.cvJointLoc1, self.jGuide1, ['tx', 'ty', 'tz', 'rx', 'ry', 'rz'])
self.ctrls.directConnect(self.cvEndJoint, self.jGuideEnd, ['tx', 'ty', 'tz', 'rx', 'ry', 'rz'])
# change the number of phalanges to 3:
self.changeJointNumber(3)
# create a base cvLoc to start the finger joints:
self.cvBaseJoint = self.ctrls.cvLocator(ctrlName=self.guideName+"_JointLoc0", r=0.2, d=1, guide=True)
cmds.setAttr(self.cvBaseJoint+".translateZ", -1)
cmds.parent(self.cvBaseJoint, self.moduleGrp)
# transform cvLocs in order to put as a good finger guide:
cmds.setAttr(self.moduleGrp+".rotateX", 90)
cmds.setAttr(self.moduleGrp+".rotateZ", 90)
def changeJointNumber(self, enteredNJoints, *args):
""" Edit the number of joints in the guide.
"""
<|code_end|>
using the current file's imports:
from maya import cmds
from .Library import dpUtils
from . import dpBaseClass
from . import dpLayoutClass
and any relevant context from other files:
# Path: dpAutoRigSystem/Modules/Library/dpUtils.py
# def findEnv(key, path):
# def findPath(filename):
# def findAllFiles(path, dir, ext):
# def findAllModules(path, dir):
# def findAllModuleNames(path, dir):
# def findLastNumber(nameList, basename):
# def findModuleLastNumber(className, typeName):
# def normalizeText(enteredText="", prefixMax=4):
# def useDefaultRenderLayer():
# def zeroOut(transformList=[], offset=False):
# def originedFrom(objName="", attrString=""):
# def getOriginedFromDic():
# def addHook(objName="", hookType="staticHook"):
# def hook():
# def clearNodeGrp(nodeGrpName='dpAR_GuideMirror_Grp', attrFind='guideBaseMirror', unparent=False):
# def getGuideChildrenList(nodeName):
# def mirroredGuideFather(nodeName):
# def getParentsList(nodeName):
# def getModulesToBeRigged(instanceList):
# def getCtrlRadius(nodeName):
# def zeroOutJoints(jntList=None, displayBone=False):
# def clearDpArAttr(itemList):
# def deleteChildren(item):
# def setJointLabel(jointName, sideNumber, typeNumber, labelString):
# def deleteJointLabel(jointName):
# def extractSuffix(nodeName):
# def filterName(name, itemList, separator):
# def checkRawURLForUpdate(DPAR_VERSION, DPAR_RAWURL, *args):
# def visitWebSite(website, *args):
# def checkLoadedPlugin(pluginName, exceptName=None, message="Not loaded plugin", *args):
# def twistBoneMatrix(nodeA, nodeB, twistBoneName, twistBoneMD=None, axis='Z', inverse=True, *args):
# def validateName(nodeName, suffix=None, *args):
# def articulationJoint(fatherNode, brotherNode, corrNumber=0, dist=1, jarRadius=1.5, doScale=True, *args):
# def getNodeByMessage(grpAttrName, *args):
# def attachToMotionPath(nodeName, curveName, mopName, uValue):
# def profiler(func):
# def runProfile(*args, **kwargs):
# def extract_world_scale_from_matrix(obj):
# DPAR_PROFILE_MODE = False
. Output only the next line. | dpUtils.useDefaultRenderLayer() |
Given the following code snippet before the placeholder: <|code_start|> for item in allGuideList:
cmds.rename(item, side+self.userGuideName+"_"+item)
self.mirrorGrp = cmds.group(name="Guide_Base_Grp", empty=True)
cmds.parent(side+self.userGuideName+'_Guide_Base', self.mirrorGrp, absolute=True)
# re-rename grp:
cmds.rename(self.mirrorGrp, side+self.userGuideName+'_'+self.mirrorGrp)
# do a group mirror with negative scaling:
if s == 1:
if cmds.getAttr(self.moduleGrp+".flip") == 0:
for axis in self.mirrorAxis:
gotValue = cmds.getAttr(side+self.userGuideName+"_Guide_Base.translate"+axis)
flipedValue = gotValue*(-2)
cmds.setAttr(side+self.userGuideName+'_'+self.mirrorGrp+'.translate'+axis, flipedValue)
else:
for axis in self.mirrorAxis:
cmds.setAttr(side+self.userGuideName+'_'+self.mirrorGrp+'.scale'+axis, -1)
# joint labelling:
jointLabelAdd = 1
else: # if not mirror:
duplicated = cmds.duplicate(self.moduleGrp, name=self.userGuideName+'_Guide_Base')[0]
allGuideList = cmds.listRelatives(duplicated, allDescendents=True)
for item in allGuideList:
cmds.rename(item, self.userGuideName+"_"+item)
self.mirrorGrp = cmds.group(self.userGuideName+'_Guide_Base', name="Guide_Base_Grp", relative=True)
#for Maya2012: self.userGuideName+'_'+self.moduleGrp+"_Grp"
# re-rename grp:
cmds.rename(self.mirrorGrp, self.userGuideName+'_'+self.mirrorGrp)
# joint labelling:
jointLabelAdd = 0
# store the number of this guide by module type
<|code_end|>
, predict the next line using imports from the current file:
from maya import cmds
from .Library import dpUtils
from . import dpBaseClass
from . import dpLayoutClass
and context including class names, function names, and sometimes code from other files:
# Path: dpAutoRigSystem/Modules/Library/dpUtils.py
# def findEnv(key, path):
# def findPath(filename):
# def findAllFiles(path, dir, ext):
# def findAllModules(path, dir):
# def findAllModuleNames(path, dir):
# def findLastNumber(nameList, basename):
# def findModuleLastNumber(className, typeName):
# def normalizeText(enteredText="", prefixMax=4):
# def useDefaultRenderLayer():
# def zeroOut(transformList=[], offset=False):
# def originedFrom(objName="", attrString=""):
# def getOriginedFromDic():
# def addHook(objName="", hookType="staticHook"):
# def hook():
# def clearNodeGrp(nodeGrpName='dpAR_GuideMirror_Grp', attrFind='guideBaseMirror', unparent=False):
# def getGuideChildrenList(nodeName):
# def mirroredGuideFather(nodeName):
# def getParentsList(nodeName):
# def getModulesToBeRigged(instanceList):
# def getCtrlRadius(nodeName):
# def zeroOutJoints(jntList=None, displayBone=False):
# def clearDpArAttr(itemList):
# def deleteChildren(item):
# def setJointLabel(jointName, sideNumber, typeNumber, labelString):
# def deleteJointLabel(jointName):
# def extractSuffix(nodeName):
# def filterName(name, itemList, separator):
# def checkRawURLForUpdate(DPAR_VERSION, DPAR_RAWURL, *args):
# def visitWebSite(website, *args):
# def checkLoadedPlugin(pluginName, exceptName=None, message="Not loaded plugin", *args):
# def twistBoneMatrix(nodeA, nodeB, twistBoneName, twistBoneMD=None, axis='Z', inverse=True, *args):
# def validateName(nodeName, suffix=None, *args):
# def articulationJoint(fatherNode, brotherNode, corrNumber=0, dist=1, jarRadius=1.5, doScale=True, *args):
# def getNodeByMessage(grpAttrName, *args):
# def attachToMotionPath(nodeName, curveName, mopName, uValue):
# def profiler(func):
# def runProfile(*args, **kwargs):
# def extract_world_scale_from_matrix(obj):
# DPAR_PROFILE_MODE = False
. Output only the next line. | dpAR_count = dpUtils.findModuleLastNumber(CLASS_NAME, "dpAR_type") + 1 |
Next line prediction: <|code_start|> # changing module aim guides:
cmds.setAttr(self.cvEndJointZero+".rotateX", 0)
cmds.setAttr(self.cvEndJointZero+".rotateY", 0)
if item[1] == "X":
if item[0] == "+":
cmds.setAttr(self.cvEndJointZero+".rotateY", 90)
else:
cmds.setAttr(self.cvEndJointZero+".rotateY", -90)
if item[1] == "Y":
if item[0] == "+":
cmds.setAttr(self.cvEndJointZero+".rotateX", -90)
else:
cmds.setAttr(self.cvEndJointZero+".rotateX", 90)
if item[1] == "Z":
if item[0] == "-":
cmds.setAttr(self.cvEndJointZero+".rotateY", 180)
def createEyelidJoints(self, side, lid, middle, cvEyelidLoc, jointLabelNumber, *args):
''' Create the eyelid joints to be used in the needed setup.
Returns EyelidBaseJxt and EyelidJnt created for rotate and skinning.
'''
# declating a concatenated name used for base to compose:
baseName = side+self.userGuideName+"_"+self.langDic[self.langName][lid]+"_"+self.langDic[self.langName]['c042_eyelid']+middle
# creating joints:
eyelidBaseZeroJxt = cmds.joint(name=baseName+"_Base_Zero_Jxt", rotationOrder="yzx", scaleCompensate=False)
eyelidBaseJxt = cmds.joint(name=baseName+"_Base_Jxt", rotationOrder="yzx", scaleCompensate=False)
eyelidZeroJxt = cmds.joint(name=baseName+"_Zero_Jxt", rotationOrder="yzx", scaleCompensate=False)
eyelidJnt = cmds.joint(name=baseName+"_Jnt", rotationOrder="yzx", scaleCompensate=False)
cmds.addAttr(eyelidJnt, longName='dpAR_joint', attributeType='float', keyable=False)
<|code_end|>
. Use current file imports:
(from maya import cmds
from .Library import dpUtils
from . import dpBaseClass
from . import dpLayoutClass)
and context including class names, function names, or small code snippets from other files:
# Path: dpAutoRigSystem/Modules/Library/dpUtils.py
# def findEnv(key, path):
# def findPath(filename):
# def findAllFiles(path, dir, ext):
# def findAllModules(path, dir):
# def findAllModuleNames(path, dir):
# def findLastNumber(nameList, basename):
# def findModuleLastNumber(className, typeName):
# def normalizeText(enteredText="", prefixMax=4):
# def useDefaultRenderLayer():
# def zeroOut(transformList=[], offset=False):
# def originedFrom(objName="", attrString=""):
# def getOriginedFromDic():
# def addHook(objName="", hookType="staticHook"):
# def hook():
# def clearNodeGrp(nodeGrpName='dpAR_GuideMirror_Grp', attrFind='guideBaseMirror', unparent=False):
# def getGuideChildrenList(nodeName):
# def mirroredGuideFather(nodeName):
# def getParentsList(nodeName):
# def getModulesToBeRigged(instanceList):
# def getCtrlRadius(nodeName):
# def zeroOutJoints(jntList=None, displayBone=False):
# def clearDpArAttr(itemList):
# def deleteChildren(item):
# def setJointLabel(jointName, sideNumber, typeNumber, labelString):
# def deleteJointLabel(jointName):
# def extractSuffix(nodeName):
# def filterName(name, itemList, separator):
# def checkRawURLForUpdate(DPAR_VERSION, DPAR_RAWURL, *args):
# def visitWebSite(website, *args):
# def checkLoadedPlugin(pluginName, exceptName=None, message="Not loaded plugin", *args):
# def twistBoneMatrix(nodeA, nodeB, twistBoneName, twistBoneMD=None, axis='Z', inverse=True, *args):
# def validateName(nodeName, suffix=None, *args):
# def articulationJoint(fatherNode, brotherNode, corrNumber=0, dist=1, jarRadius=1.5, doScale=True, *args):
# def getNodeByMessage(grpAttrName, *args):
# def attachToMotionPath(nodeName, curveName, mopName, uValue):
# def profiler(func):
# def runProfile(*args, **kwargs):
# def extract_world_scale_from_matrix(obj):
# DPAR_PROFILE_MODE = False
. Output only the next line. | dpUtils.setJointLabel(eyelidJnt, jointLabelNumber, 18, self.userGuideName+"_"+self.langDic[self.langName][lid]+"_"+self.langDic[self.langName]['c042_eyelid']+middle) |
Given the code snippet: <|code_start|> # get rigs names:
self.mirrorNames = cmds.getAttr(self.moduleGrp + ".mirrorName")
# get first and last letters to use as side initials (prefix):
sideList = [self.mirrorNames[0] + '_', self.mirrorNames[len(self.mirrorNames) - 1] + '_']
for s, side in enumerate(sideList):
duplicated = cmds.duplicate(self.moduleGrp, name=side + self.userGuideName + '_Guide_Base')[0]
allGuideList = cmds.listRelatives(duplicated, allDescendents=True)
for item in allGuideList:
cmds.rename(item, side + self.userGuideName + "_" + item)
self.mirrorGrp = cmds.group(name="Guide_Base_Grp", empty=True)
cmds.parent(side + self.userGuideName + '_Guide_Base', self.mirrorGrp, absolute=True)
# re-rename grp:
cmds.rename(self.mirrorGrp, side + self.userGuideName + '_' + self.mirrorGrp)
# do a group mirror with negative scaling:
if s == 1:
for axis in self.mirrorAxis:
cmds.setAttr(side + self.userGuideName + '_' + self.mirrorGrp+'.scale' + axis, -1)
# joint labelling:
jointLabelAdd = 1
else: # if not mirror:
duplicated = cmds.duplicate(self.moduleGrp, name=self.userGuideName + '_Guide_Base')[0]
allGuideList = cmds.listRelatives(duplicated, allDescendents=True)
for item in allGuideList:
cmds.rename(item, self.userGuideName + "_" + item)
self.mirrorGrp = cmds.group(self.userGuideName + '_Guide_Base', name="Guide_Base_Grp", relative=True)
# re-rename grp:
cmds.rename(self.mirrorGrp, self.userGuideName + '_' + self.mirrorGrp)
# joint labelling:
jointLabelAdd = 0
# store the number of this guide by module type
<|code_end|>
, generate the next line using the imports in this file:
from maya import cmds
from importlib import reload
from .Library import dpUtils
from . import dpBaseClass
from . import dpLayoutClass
from sstk.maya.animation import sqIkFkTools
from sstk.libs import libSerialization
from .Library import sqIkFkTools
from .Library import libSerialization
from .Library import jcRibbon
import math
and context (functions, classes, or occasionally code) from other files:
# Path: dpAutoRigSystem/Modules/Library/dpUtils.py
# def findEnv(key, path):
# def findPath(filename):
# def findAllFiles(path, dir, ext):
# def findAllModules(path, dir):
# def findAllModuleNames(path, dir):
# def findLastNumber(nameList, basename):
# def findModuleLastNumber(className, typeName):
# def normalizeText(enteredText="", prefixMax=4):
# def useDefaultRenderLayer():
# def zeroOut(transformList=[], offset=False):
# def originedFrom(objName="", attrString=""):
# def getOriginedFromDic():
# def addHook(objName="", hookType="staticHook"):
# def hook():
# def clearNodeGrp(nodeGrpName='dpAR_GuideMirror_Grp', attrFind='guideBaseMirror', unparent=False):
# def getGuideChildrenList(nodeName):
# def mirroredGuideFather(nodeName):
# def getParentsList(nodeName):
# def getModulesToBeRigged(instanceList):
# def getCtrlRadius(nodeName):
# def zeroOutJoints(jntList=None, displayBone=False):
# def clearDpArAttr(itemList):
# def deleteChildren(item):
# def setJointLabel(jointName, sideNumber, typeNumber, labelString):
# def deleteJointLabel(jointName):
# def extractSuffix(nodeName):
# def filterName(name, itemList, separator):
# def checkRawURLForUpdate(DPAR_VERSION, DPAR_RAWURL, *args):
# def visitWebSite(website, *args):
# def checkLoadedPlugin(pluginName, exceptName=None, message="Not loaded plugin", *args):
# def twistBoneMatrix(nodeA, nodeB, twistBoneName, twistBoneMD=None, axis='Z', inverse=True, *args):
# def validateName(nodeName, suffix=None, *args):
# def articulationJoint(fatherNode, brotherNode, corrNumber=0, dist=1, jarRadius=1.5, doScale=True, *args):
# def getNodeByMessage(grpAttrName, *args):
# def attachToMotionPath(nodeName, curveName, mopName, uValue):
# def profiler(func):
# def runProfile(*args, **kwargs):
# def extract_world_scale_from_matrix(obj):
# DPAR_PROFILE_MODE = False
. Output only the next line. | dpAR_count = dpUtils.findModuleLastNumber(CLASS_NAME, "dpAR_type") + 1 |
Given the following code snippet before the placeholder: <|code_start|> leftName = leftPrefix+item+offsetSuffix
rightName = rightPrefix+item+offsetSuffix
if cmds.objExists(centerName):
self.dpLoadJointTgtList(centerName)
if cmds.objExists(leftName):
self.dpLoadJointTgtList(leftName)
if cmds.objExists(rightName):
self.dpLoadJointTgtList(rightName)
def dpLoadJointTgtList(self, item, *args):
# get current list
currentList = cmds.textScrollList(self.jntTargetScrollList, query=True, allItems=True)
if currentList:
# clear current list
cmds.textScrollList(self.jntTargetScrollList, edit=True, removeAll=True)
# avoid repeated items
if not item in currentList:
currentList.append(item)
# refresh textScrollList
cmds.textScrollList(self.jntTargetScrollList, edit=True, append=currentList)
else:
# add selected items in the empyt target scroll list
cmds.textScrollList(self.jntTargetScrollList, edit=True, append=item)
self.jntTargetList = cmds.textScrollList(self.jntTargetScrollList, query=True, allItems=True)
def dpCreateRemapNode(self, fromNode, fromAttr, toNodeBaseName, toNode, toAttr, number, sizeFactor, oMin=0, oMax=1, iMin=0, iMax=1, *args):
""" Creates the nodes to remap values and connect it to final output (toNode) item.
"""
<|code_end|>
, predict the next line using imports from the current file:
from maya import cmds
from maya import mel
from functools import partial
from dpAutoRigSystem.Modules.Library import dpUtils
import os
import json
import dpAutoRigSystem.Modules.Library.dpControls as dpControls
and context including class names, function names, and sometimes code from other files:
# Path: dpAutoRigSystem/Modules/Library/dpUtils.py
# def findEnv(key, path):
# def findPath(filename):
# def findAllFiles(path, dir, ext):
# def findAllModules(path, dir):
# def findAllModuleNames(path, dir):
# def findLastNumber(nameList, basename):
# def findModuleLastNumber(className, typeName):
# def normalizeText(enteredText="", prefixMax=4):
# def useDefaultRenderLayer():
# def zeroOut(transformList=[], offset=False):
# def originedFrom(objName="", attrString=""):
# def getOriginedFromDic():
# def addHook(objName="", hookType="staticHook"):
# def hook():
# def clearNodeGrp(nodeGrpName='dpAR_GuideMirror_Grp', attrFind='guideBaseMirror', unparent=False):
# def getGuideChildrenList(nodeName):
# def mirroredGuideFather(nodeName):
# def getParentsList(nodeName):
# def getModulesToBeRigged(instanceList):
# def getCtrlRadius(nodeName):
# def zeroOutJoints(jntList=None, displayBone=False):
# def clearDpArAttr(itemList):
# def deleteChildren(item):
# def setJointLabel(jointName, sideNumber, typeNumber, labelString):
# def deleteJointLabel(jointName):
# def extractSuffix(nodeName):
# def filterName(name, itemList, separator):
# def checkRawURLForUpdate(DPAR_VERSION, DPAR_RAWURL, *args):
# def visitWebSite(website, *args):
# def checkLoadedPlugin(pluginName, exceptName=None, message="Not loaded plugin", *args):
# def twistBoneMatrix(nodeA, nodeB, twistBoneName, twistBoneMD=None, axis='Z', inverse=True, *args):
# def validateName(nodeName, suffix=None, *args):
# def articulationJoint(fatherNode, brotherNode, corrNumber=0, dist=1, jarRadius=1.5, doScale=True, *args):
# def getNodeByMessage(grpAttrName, *args):
# def attachToMotionPath(nodeName, curveName, mopName, uValue):
# def profiler(func):
# def runProfile(*args, **kwargs):
# def extract_world_scale_from_matrix(obj):
# DPAR_PROFILE_MODE = False
. Output only the next line. | fromNodeName = dpUtils.extractSuffix(fromNode) |
Given the following code snippet before the placeholder: <|code_start|> for item in allGuideList:
cmds.rename(item, side+self.userGuideName+"_"+item)
self.mirrorGrp = cmds.group(name="Guide_Base_Grp", empty=True)
cmds.parent(side+self.userGuideName+'_Guide_Base', self.mirrorGrp, absolute=True)
# re-rename grp:
cmds.rename(self.mirrorGrp, side+self.userGuideName+'_'+self.mirrorGrp)
# do a group mirror with negative scaling:
if s == 1:
if cmds.getAttr(self.moduleGrp+".flip") == 0:
for axis in self.mirrorAxis:
gotValue = cmds.getAttr(side+self.userGuideName+"_Guide_Base.translate"+axis)
flipedValue = gotValue*(-2)
cmds.setAttr(side+self.userGuideName+'_'+self.mirrorGrp+'.translate'+axis, flipedValue)
else:
for axis in self.mirrorAxis:
cmds.setAttr(side+self.userGuideName+'_'+self.mirrorGrp+'.scale'+axis, -1)
# joint labelling:
jointLabelAdd = 1
else: # if not mirror:
duplicated = cmds.duplicate(self.moduleGrp, name=self.userGuideName+'_Guide_Base')[0]
allGuideList = cmds.listRelatives(duplicated, allDescendents=True)
for item in allGuideList:
cmds.rename(item, self.userGuideName+"_"+item)
self.mirrorGrp = cmds.group(self.userGuideName+'_Guide_Base', name="Guide_Base_Grp", relative=True)
#for Maya2012: self.userGuideName+'_'+self.moduleGrp+"_Grp"
# re-rename grp:
cmds.rename(self.mirrorGrp, self.userGuideName+'_'+self.mirrorGrp)
# joint labelling:
jointLabelAdd = 0
# store the number of this guide by module type
<|code_end|>
, predict the next line using imports from the current file:
from maya import cmds
from maya import OpenMaya as om
from .Library import dpUtils
from . import dpBaseClass
from . import dpLayoutClass
and context including class names, function names, and sometimes code from other files:
# Path: dpAutoRigSystem/Modules/Library/dpUtils.py
# def findEnv(key, path):
# def findPath(filename):
# def findAllFiles(path, dir, ext):
# def findAllModules(path, dir):
# def findAllModuleNames(path, dir):
# def findLastNumber(nameList, basename):
# def findModuleLastNumber(className, typeName):
# def normalizeText(enteredText="", prefixMax=4):
# def useDefaultRenderLayer():
# def zeroOut(transformList=[], offset=False):
# def originedFrom(objName="", attrString=""):
# def getOriginedFromDic():
# def addHook(objName="", hookType="staticHook"):
# def hook():
# def clearNodeGrp(nodeGrpName='dpAR_GuideMirror_Grp', attrFind='guideBaseMirror', unparent=False):
# def getGuideChildrenList(nodeName):
# def mirroredGuideFather(nodeName):
# def getParentsList(nodeName):
# def getModulesToBeRigged(instanceList):
# def getCtrlRadius(nodeName):
# def zeroOutJoints(jntList=None, displayBone=False):
# def clearDpArAttr(itemList):
# def deleteChildren(item):
# def setJointLabel(jointName, sideNumber, typeNumber, labelString):
# def deleteJointLabel(jointName):
# def extractSuffix(nodeName):
# def filterName(name, itemList, separator):
# def checkRawURLForUpdate(DPAR_VERSION, DPAR_RAWURL, *args):
# def visitWebSite(website, *args):
# def checkLoadedPlugin(pluginName, exceptName=None, message="Not loaded plugin", *args):
# def twistBoneMatrix(nodeA, nodeB, twistBoneName, twistBoneMD=None, axis='Z', inverse=True, *args):
# def validateName(nodeName, suffix=None, *args):
# def articulationJoint(fatherNode, brotherNode, corrNumber=0, dist=1, jarRadius=1.5, doScale=True, *args):
# def getNodeByMessage(grpAttrName, *args):
# def attachToMotionPath(nodeName, curveName, mopName, uValue):
# def profiler(func):
# def runProfile(*args, **kwargs):
# def extract_world_scale_from_matrix(obj):
# DPAR_PROFILE_MODE = False
. Output only the next line. | dpAR_count = dpUtils.findModuleLastNumber(CLASS_NAME, "dpAR_type") + 1 |
Here is a snippet: <|code_start|> cmds.addAttr(self.moduleGrp, longName="flip", attributeType='bool')
cmds.setAttr(self.moduleGrp+".flip", 0)
cmds.setAttr(self.moduleGrp+".moduleNamespace", self.moduleGrp[:self.moduleGrp.rfind(":")], type='string')
cmds.addAttr(self.moduleGrp, longName="articulation", attributeType='bool')
cmds.setAttr(self.moduleGrp+".articulation", 0)
self.cvJointLoc = self.ctrls.cvJointLoc(ctrlName=self.guideName+"_JointLoc1", r=0.3, d=1, guide=True)
self.jGuide1 = cmds.joint(name=self.guideName+"_JGuide1", radius=0.001)
cmds.setAttr(self.jGuide1+".template", 1)
cmds.parent(self.jGuide1, self.moduleGrp, relative=True)
self.cvEndJoint = self.ctrls.cvLocator(ctrlName=self.guideName+"_JointEnd", r=0.1, d=1, guide=True)
cmds.parent(self.cvEndJoint, self.cvJointLoc)
cmds.setAttr(self.cvEndJoint+".tz", 1.3)
self.jGuideEnd = cmds.joint(name=self.guideName+"_JGuideEnd", radius=0.001)
cmds.setAttr(self.jGuideEnd+".template", 1)
cmds.transformLimits(self.cvEndJoint, tz=(0.01, 1), etz=(True, False))
self.ctrls.setLockHide([self.cvEndJoint], ['tx', 'ty', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'])
cmds.parent(self.cvJointLoc, self.moduleGrp)
cmds.parent(self.jGuideEnd, self.jGuide1)
cmds.parentConstraint(self.cvJointLoc, self.jGuide1, maintainOffset=False, name=self.jGuide1+"_PaC")
cmds.parentConstraint(self.cvEndJoint, self.jGuideEnd, maintainOffset=False, name=self.jGuideEnd+"_PaC")
def changeJointNumber(self, enteredNJoints, *args):
""" Edit the number of joints in the guide.
"""
<|code_end|>
. Write the next line using the current file imports:
from maya import cmds
from .Library import dpUtils
from . import dpBaseClass
from . import dpLayoutClass
and context from other files:
# Path: dpAutoRigSystem/Modules/Library/dpUtils.py
# def findEnv(key, path):
# def findPath(filename):
# def findAllFiles(path, dir, ext):
# def findAllModules(path, dir):
# def findAllModuleNames(path, dir):
# def findLastNumber(nameList, basename):
# def findModuleLastNumber(className, typeName):
# def normalizeText(enteredText="", prefixMax=4):
# def useDefaultRenderLayer():
# def zeroOut(transformList=[], offset=False):
# def originedFrom(objName="", attrString=""):
# def getOriginedFromDic():
# def addHook(objName="", hookType="staticHook"):
# def hook():
# def clearNodeGrp(nodeGrpName='dpAR_GuideMirror_Grp', attrFind='guideBaseMirror', unparent=False):
# def getGuideChildrenList(nodeName):
# def mirroredGuideFather(nodeName):
# def getParentsList(nodeName):
# def getModulesToBeRigged(instanceList):
# def getCtrlRadius(nodeName):
# def zeroOutJoints(jntList=None, displayBone=False):
# def clearDpArAttr(itemList):
# def deleteChildren(item):
# def setJointLabel(jointName, sideNumber, typeNumber, labelString):
# def deleteJointLabel(jointName):
# def extractSuffix(nodeName):
# def filterName(name, itemList, separator):
# def checkRawURLForUpdate(DPAR_VERSION, DPAR_RAWURL, *args):
# def visitWebSite(website, *args):
# def checkLoadedPlugin(pluginName, exceptName=None, message="Not loaded plugin", *args):
# def twistBoneMatrix(nodeA, nodeB, twistBoneName, twistBoneMD=None, axis='Z', inverse=True, *args):
# def validateName(nodeName, suffix=None, *args):
# def articulationJoint(fatherNode, brotherNode, corrNumber=0, dist=1, jarRadius=1.5, doScale=True, *args):
# def getNodeByMessage(grpAttrName, *args):
# def attachToMotionPath(nodeName, curveName, mopName, uValue):
# def profiler(func):
# def runProfile(*args, **kwargs):
# def extract_world_scale_from_matrix(obj):
# DPAR_PROFILE_MODE = False
, which may include functions, classes, or code. Output only the next line. | dpUtils.useDefaultRenderLayer() |
Based on the snippet: <|code_start|># importing libraries:
# global variables to this module:
CLASS_NAME = "CopyPasteAttr"
TITLE = "m135_copyPasteAttr"
DESCRIPTION = "m136_copyPasteAttrDesc"
ICON = "/Icons/dp_copyPasteAttr.png"
DPCP_VERSION = "2.1"
# import libraries
class CopyPasteAttr(object):
def __init__(self, dpUIinst, langDic, langName, presetDic, presetName, *args, **kwargs):
# defining variables
self.dpUIinst = dpUIinst
self.langDic = langDic
self.langName = langName
self.presetDic = presetDic
self.presetName = presetName
<|code_end|>
, predict the immediate next line with the help of imports:
from maya import cmds
from functools import partial
from ..Modules.Library import dpControls
from maya import cmds
and context (classes, functions, sometimes code) from other files:
# Path: dpAutoRigSystem/Modules/Library/dpControls.py
# class ControlClass(object):
# def __init__(self, dpUIinst, presetDic, presetName, moduleGrp=None, *args):
# def colorShape(self, objList, color, rgb=False, *args):
# def renameShape(self, transformList, *args):
# def directConnect(self, fromObj, toObj, attrList=['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'], f=True, *args):
# def setLockHide(self, objList, attrList, l=True, k=False, *args):
# def setNonKeyable(self, objList, attrList, *args):
# def setNotRenderable(self, objList, *args):
# def distanceBet(self, a, b, name="temp_DistBet", keep=False, *args):
# def middlePoint(self, a, b, createLocator=False, *args):
# def createSimpleRibbon(self, name='ribbon', totalJoints=6, jointLabelNumber=0, jointLabelName="SimpleRibbon", *args):
# def getControlNodeById(self, ctrlType, *args):
# def getControlModuleById(self, ctrlType, *args):
# def getControlDegreeById(self, ctrlType, *args):
# def getControlInstance(self, instanceName, *args):
# def cvControl(self, ctrlType, ctrlName, r=1, d=1, dir='+Y', rot=(0, 0, 0), *args):
# def cvLocator(self, ctrlName, r=1, d=1, guide=False, *args):
# def cvJointLoc(self, ctrlName, r=0.3, d=1, rot=(0, 0, 0), guide=True, *args):
# def cvCharacter(self, ctrlType, ctrlName, r=1, d=1, dir="+Y", rot=(0, 0, 0), *args):
# def findHistory(self, objList, historyName, *args):
# def cvBaseGuide(self, ctrlName, r=1, *args):
# def setAndFreeze(nodeName="", tx=None, ty=None, tz=None, rx=None, ry=None, rz=None, sx=None, sy=None, sz=None, freeze=True):
# def copyAttr(self, sourceItem=False, attrList=False, verbose=False, *args):
# def pasteAttr(self, destinationList=False, verbose=False, *args):
# def copyAndPasteAttr(self, verbose=False, *args):
# def transferAttr(self, sourceItem, destinationList, attrList, *args):
# def transferShape(self, deleteSource=False, clearDestinationShapes=True, sourceItem=None, destinationList=None, applyColor=True, *args):
# def setSourceColorOverride(self, sourceItem, destinationList, *args):
# def resetCurve(self, changeDegree=False, transformList=False, *args):
# def dpCreatePreset(self, *args):
# def dpCheckLinearUnit(self, origRadius, defaultUnit="centimeter", *args):
# def shapeSizeSetup(self, transformNode, *args):
# def connectShapeSize(self, clusterHandle, *args):
# def addGuideAttrs(self, ctrlName, *args):
# def createPinGuide(self, ctrlName, *args):
# def setPinnedGuideColor(self, ctrlName, status, color, *args):
# def jobPinGuide(self, ctrlName, *args):
# def startPinGuide(self, guideBase, *args):
# def unPinGuide(self, guideBase, *args):
# def importCalibration(self, *args):
# def mirrorCalibration(self, nodeName=False, fromPrefix=False, toPrefix=False, *args):
# def transferCalibration(self, sourceItem=False, destinationList=False, attrList=False, verbose=True, *args):
# def setCalibrationAttr(self, nodeName, attrList, *args):
# def getCalibrationAttr(self, nodeName, *args):
. Output only the next line. | self.ctrls = dpControls.ControlClass(self.dpUIinst, self.presetDic, self.presetName) |
Given the code snippet: <|code_start|> for item in allGuideList:
cmds.rename(item, side+self.userGuideName+"_"+item)
self.mirrorGrp = cmds.group(name="Guide_Base_Grp", empty=True)
cmds.parent(side+self.userGuideName+'_Guide_Base', self.mirrorGrp, absolute=True)
# re-rename grp:
cmds.rename(self.mirrorGrp, side+self.userGuideName+'_'+self.mirrorGrp)
# do a group mirror with negative scaling:
if s == 1:
if cmds.getAttr(self.moduleGrp+".flip") == 0:
for axis in self.mirrorAxis:
gotValue = cmds.getAttr(side+self.userGuideName+"_Guide_Base.translate"+axis)
flipedValue = gotValue*(-2)
cmds.setAttr(side+self.userGuideName+'_'+self.mirrorGrp+'.translate'+axis, flipedValue)
else:
for axis in self.mirrorAxis:
cmds.setAttr(side+self.userGuideName+'_'+self.mirrorGrp+'.scale'+axis, -1)
# joint labelling:
jointLabelAdd = 1
else: # if not mirror:
duplicated = cmds.duplicate(self.moduleGrp, name=self.userGuideName+'_Guide_Base')[0]
allGuideList = cmds.listRelatives(duplicated, allDescendents=True)
for item in allGuideList:
cmds.rename(item, self.userGuideName+"_"+item)
self.mirrorGrp = cmds.group(self.userGuideName+'_Guide_Base', name="Guide_Base_Grp", relative=True)
#for Maya2012: self.userGuideName+'_'+self.moduleGrp+"_Grp"
# re-rename grp:
cmds.rename(self.mirrorGrp, self.userGuideName+'_'+self.mirrorGrp)
# joint labelling:
jointLabelAdd = 0
# store the number of this guide by module type
<|code_end|>
, generate the next line using the imports in this file:
from maya import cmds
from .Library import dpUtils
from . import dpBaseClass
from . import dpLayoutClass
and context (functions, classes, or occasionally code) from other files:
# Path: dpAutoRigSystem/Modules/Library/dpUtils.py
# def findEnv(key, path):
# def findPath(filename):
# def findAllFiles(path, dir, ext):
# def findAllModules(path, dir):
# def findAllModuleNames(path, dir):
# def findLastNumber(nameList, basename):
# def findModuleLastNumber(className, typeName):
# def normalizeText(enteredText="", prefixMax=4):
# def useDefaultRenderLayer():
# def zeroOut(transformList=[], offset=False):
# def originedFrom(objName="", attrString=""):
# def getOriginedFromDic():
# def addHook(objName="", hookType="staticHook"):
# def hook():
# def clearNodeGrp(nodeGrpName='dpAR_GuideMirror_Grp', attrFind='guideBaseMirror', unparent=False):
# def getGuideChildrenList(nodeName):
# def mirroredGuideFather(nodeName):
# def getParentsList(nodeName):
# def getModulesToBeRigged(instanceList):
# def getCtrlRadius(nodeName):
# def zeroOutJoints(jntList=None, displayBone=False):
# def clearDpArAttr(itemList):
# def deleteChildren(item):
# def setJointLabel(jointName, sideNumber, typeNumber, labelString):
# def deleteJointLabel(jointName):
# def extractSuffix(nodeName):
# def filterName(name, itemList, separator):
# def checkRawURLForUpdate(DPAR_VERSION, DPAR_RAWURL, *args):
# def visitWebSite(website, *args):
# def checkLoadedPlugin(pluginName, exceptName=None, message="Not loaded plugin", *args):
# def twistBoneMatrix(nodeA, nodeB, twistBoneName, twistBoneMD=None, axis='Z', inverse=True, *args):
# def validateName(nodeName, suffix=None, *args):
# def articulationJoint(fatherNode, brotherNode, corrNumber=0, dist=1, jarRadius=1.5, doScale=True, *args):
# def getNodeByMessage(grpAttrName, *args):
# def attachToMotionPath(nodeName, curveName, mopName, uValue):
# def profiler(func):
# def runProfile(*args, **kwargs):
# def extract_world_scale_from_matrix(obj):
# DPAR_PROFILE_MODE = False
. Output only the next line. | dpAR_count = dpUtils.findModuleLastNumber(CLASS_NAME, "dpAR_type") + 1 |
Using the snippet: <|code_start|> for item in allGuideList:
cmds.rename(item, side+self.userGuideName+"_"+item)
self.mirrorGrp = cmds.group(name="Guide_Base_Grp", empty=True)
cmds.parent(side+self.userGuideName+'_Guide_Base', self.mirrorGrp, absolute=True)
# re-rename grp:
cmds.rename(self.mirrorGrp, side+self.userGuideName+'_'+self.mirrorGrp)
# do a group mirror with negative scaling:
if s == 1:
if cmds.getAttr(self.moduleGrp+".flip") == 0:
for axis in self.mirrorAxis:
gotValue = cmds.getAttr(side+self.userGuideName+"_Guide_Base.translate"+axis)
flipedValue = gotValue*(-2)
cmds.setAttr(side+self.userGuideName+'_'+self.mirrorGrp+'.translate'+axis, flipedValue)
else:
for axis in self.mirrorAxis:
cmds.setAttr(side+self.userGuideName+'_'+self.mirrorGrp+'.scale'+axis, -1)
# joint labelling:
jointLabelAdd = 1
else: # if not mirror:
duplicated = cmds.duplicate(self.moduleGrp, name=self.userGuideName+'_Guide_Base')[0]
allGuideList = cmds.listRelatives(duplicated, allDescendents=True)
for item in allGuideList:
cmds.rename(item, self.userGuideName+"_"+item)
self.mirrorGrp = cmds.group(self.userGuideName+'_Guide_Base', name="Guide_Base_Grp", relative=True)
#for Maya2012: self.userGuideName+'_'+self.moduleGrp+"_Grp"
# re-rename grp:
cmds.rename(self.mirrorGrp, self.userGuideName+'_'+self.mirrorGrp)
# joint labelling:
jointLabelAdd = 0
# store the number of this guide by module type
<|code_end|>
, determine the next line of code. You have imports:
from maya import cmds
from .Library import dpUtils
from . import dpBaseClass
from . import dpLayoutClass
and context (class names, function names, or code) available:
# Path: dpAutoRigSystem/Modules/Library/dpUtils.py
# def findEnv(key, path):
# def findPath(filename):
# def findAllFiles(path, dir, ext):
# def findAllModules(path, dir):
# def findAllModuleNames(path, dir):
# def findLastNumber(nameList, basename):
# def findModuleLastNumber(className, typeName):
# def normalizeText(enteredText="", prefixMax=4):
# def useDefaultRenderLayer():
# def zeroOut(transformList=[], offset=False):
# def originedFrom(objName="", attrString=""):
# def getOriginedFromDic():
# def addHook(objName="", hookType="staticHook"):
# def hook():
# def clearNodeGrp(nodeGrpName='dpAR_GuideMirror_Grp', attrFind='guideBaseMirror', unparent=False):
# def getGuideChildrenList(nodeName):
# def mirroredGuideFather(nodeName):
# def getParentsList(nodeName):
# def getModulesToBeRigged(instanceList):
# def getCtrlRadius(nodeName):
# def zeroOutJoints(jntList=None, displayBone=False):
# def clearDpArAttr(itemList):
# def deleteChildren(item):
# def setJointLabel(jointName, sideNumber, typeNumber, labelString):
# def deleteJointLabel(jointName):
# def extractSuffix(nodeName):
# def filterName(name, itemList, separator):
# def checkRawURLForUpdate(DPAR_VERSION, DPAR_RAWURL, *args):
# def visitWebSite(website, *args):
# def checkLoadedPlugin(pluginName, exceptName=None, message="Not loaded plugin", *args):
# def twistBoneMatrix(nodeA, nodeB, twistBoneName, twistBoneMD=None, axis='Z', inverse=True, *args):
# def validateName(nodeName, suffix=None, *args):
# def articulationJoint(fatherNode, brotherNode, corrNumber=0, dist=1, jarRadius=1.5, doScale=True, *args):
# def getNodeByMessage(grpAttrName, *args):
# def attachToMotionPath(nodeName, curveName, mopName, uValue):
# def profiler(func):
# def runProfile(*args, **kwargs):
# def extract_world_scale_from_matrix(obj):
# DPAR_PROFILE_MODE = False
. Output only the next line. | dpAR_count = dpUtils.findModuleLastNumber(CLASS_NAME, "dpAR_type") + 1 |
Next line prediction: <|code_start|> self.sideTMD = cmds.createNode("multiplyDivide", name=self.guideName+"_Side_Translate_MD")
self.sideRMD = cmds.createNode("multiplyDivide", name=self.guideName+"_Side_Rotate_MD")
self.nostrilMD = cmds.createNode("multiplyDivide", name=self.guideName+"_Nostril_MD")
cmds.connectAttr(self.cvLSideLoc+".translateX", self.sideTMD+".input1X", force=True)
cmds.connectAttr(self.cvLSideLoc+".translateY", self.sideTMD+".input1Y", force=True)
cmds.connectAttr(self.cvLSideLoc+".translateZ", self.sideTMD+".input1Z", force=True)
cmds.connectAttr(self.cvLSideLoc+".rotateX", self.sideRMD+".input1X", force=True)
cmds.connectAttr(self.cvLSideLoc+".rotateY", self.sideRMD+".input1Y", force=True)
cmds.connectAttr(self.cvLSideLoc+".rotateZ", self.sideRMD+".input1Z", force=True)
cmds.connectAttr(self.sideTMD+".outputX", self.cvRSideLoc+".translateX", force=True)
cmds.connectAttr(self.sideTMD+".outputY", self.cvRSideLoc+".translateY", force=True)
cmds.connectAttr(self.sideTMD+".outputZ", self.cvRSideLoc+".translateZ", force=True)
cmds.connectAttr(self.sideRMD+".outputX", self.cvRSideLoc+".rotateX", force=True)
cmds.connectAttr(self.sideRMD+".outputY", self.cvRSideLoc+".rotateY", force=True)
cmds.connectAttr(self.sideRMD+".outputZ", self.cvRSideLoc+".rotateZ", force=True)
cmds.connectAttr(self.cvLNostrilLoc+".translateX", self.nostrilMD+".input1X", force=True)
cmds.connectAttr(self.cvLNostrilLoc+".translateY", self.nostrilMD+".input1Y", force=True)
cmds.connectAttr(self.cvLNostrilLoc+".translateZ", self.nostrilMD+".input1Z", force=True)
cmds.connectAttr(self.nostrilMD+".outputX", self.cvRNostrilLoc+".translateX", force=True)
cmds.connectAttr(self.nostrilMD+".outputY", self.cvRNostrilLoc+".translateY", force=True)
cmds.connectAttr(self.nostrilMD+".outputZ", self.cvRNostrilLoc+".translateZ", force=True)
cmds.setAttr(self.sideTMD+".input2X", -1)
cmds.setAttr(self.sideRMD+".input2Y", -1)
cmds.setAttr(self.sideRMD+".input2Z", -1)
cmds.setAttr(self.nostrilMD+".input2X", -1)
def changeJointNumber(self, enteredNJoints, *args):
""" Edit the number of joints in the guide.
"""
<|code_end|>
. Use current file imports:
(from maya import cmds
from .Library import dpUtils
from . import dpBaseClass
from . import dpLayoutClass)
and context including class names, function names, or small code snippets from other files:
# Path: dpAutoRigSystem/Modules/Library/dpUtils.py
# def findEnv(key, path):
# def findPath(filename):
# def findAllFiles(path, dir, ext):
# def findAllModules(path, dir):
# def findAllModuleNames(path, dir):
# def findLastNumber(nameList, basename):
# def findModuleLastNumber(className, typeName):
# def normalizeText(enteredText="", prefixMax=4):
# def useDefaultRenderLayer():
# def zeroOut(transformList=[], offset=False):
# def originedFrom(objName="", attrString=""):
# def getOriginedFromDic():
# def addHook(objName="", hookType="staticHook"):
# def hook():
# def clearNodeGrp(nodeGrpName='dpAR_GuideMirror_Grp', attrFind='guideBaseMirror', unparent=False):
# def getGuideChildrenList(nodeName):
# def mirroredGuideFather(nodeName):
# def getParentsList(nodeName):
# def getModulesToBeRigged(instanceList):
# def getCtrlRadius(nodeName):
# def zeroOutJoints(jntList=None, displayBone=False):
# def clearDpArAttr(itemList):
# def deleteChildren(item):
# def setJointLabel(jointName, sideNumber, typeNumber, labelString):
# def deleteJointLabel(jointName):
# def extractSuffix(nodeName):
# def filterName(name, itemList, separator):
# def checkRawURLForUpdate(DPAR_VERSION, DPAR_RAWURL, *args):
# def visitWebSite(website, *args):
# def checkLoadedPlugin(pluginName, exceptName=None, message="Not loaded plugin", *args):
# def twistBoneMatrix(nodeA, nodeB, twistBoneName, twistBoneMD=None, axis='Z', inverse=True, *args):
# def validateName(nodeName, suffix=None, *args):
# def articulationJoint(fatherNode, brotherNode, corrNumber=0, dist=1, jarRadius=1.5, doScale=True, *args):
# def getNodeByMessage(grpAttrName, *args):
# def attachToMotionPath(nodeName, curveName, mopName, uValue):
# def profiler(func):
# def runProfile(*args, **kwargs):
# def extract_world_scale_from_matrix(obj):
# DPAR_PROFILE_MODE = False
. Output only the next line. | dpUtils.useDefaultRenderLayer() |
Given snippet: <|code_start|># Copyright (C) 2011-2017 Aratelia Limited - Juan A. Rubio
#
# 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 3 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, see <http://www.gnu.org/licenses/>.
class tag_OMX_BaseProfileAllocateBuffers(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
alias = element.get('alias')
name = context.cnames[alias]
portstr = element.get('port')
howmanystr = element.get('howmany')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import skema.tag
from skema.utils import log_api
from skema.utils import log_result
and context:
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
which might include code, classes, or functions. Output only the next line. | log_api ("%s %s:Port-%s' 'Howmany:%s'" \ |
Predict the next line for this snippet: <|code_start|># 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.
#
# 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, see <http://www.gnu.org/licenses/>.
class tag_OMX_BaseProfileAllocateBuffers(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
alias = element.get('alias')
name = context.cnames[alias]
portstr = element.get('port')
howmanystr = element.get('howmany')
log_api ("%s %s:Port-%s' 'Howmany:%s'" \
% (element.tag, name, portstr, howmanystr))
context.base_profile_mgr.allocate_buffers(alias, portstr, howmanystr)
<|code_end|>
with the help of current file imports:
import skema.tag
from skema.utils import log_api
from skema.utils import log_result
and context from other files:
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
, which may contain function names, class names, or code. Output only the next line. | log_result (element.tag, "OMX_ErrorNone") |
Given the following code snippet before the placeholder: <|code_start|># Copyright (C) 2011-2017 Aratelia Limited - Juan A. Rubio
#
# 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 3 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, see <http://www.gnu.org/licenses/>.
class tag_OMX_BaseProfileUseEGLImages(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
alias = element.get('alias')
name = context.cnames[alias]
portstr = element.get('port')
howmanystr = element.get('howmany')
<|code_end|>
, predict the next line using imports from the current file:
import skema.tag
from skema.utils import log_api
from skema.utils import log_result
and context including class names, function names, and sometimes code from other files:
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | log_api ("%s %s:Port-%s' 'Howmany:%s'" \ |
Given the following code snippet before the placeholder: <|code_start|># 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.
#
# 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, see <http://www.gnu.org/licenses/>.
class tag_OMX_BaseProfileUseEGLImages(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
alias = element.get('alias')
name = context.cnames[alias]
portstr = element.get('port')
howmanystr = element.get('howmany')
log_api ("%s %s:Port-%s' 'Howmany:%s'" \
% (element.tag, name, portstr, howmanystr))
context.base_profile_mgr.use_egl_images(alias, portstr, howmanystr)
<|code_end|>
, predict the next line using imports from the current file:
import skema.tag
from skema.utils import log_api
from skema.utils import log_result
and context including class names, function names, and sometimes code from other files:
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | log_result (element.tag, "OMX_ErrorNone") |
Here is a snippet: <|code_start|># 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, see <http://www.gnu.org/licenses/>.
class tag_OMX_SetContentURI(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
indexstr = "OMX_IndexParamContentURI"
uristr = element.get('uri')
alias = element.get('alias')
name = context.cnames[alias]
# Replace '$USER' and '$HOME' strings wih the actual representations
uristr = re.sub("\$USER", pwd.getpwuid(os.getuid())[0], uristr, 1)
uristr = re.sub("\$HOME", pwd.getpwuid(os.getuid())[5], uristr, 1)
log_api ("%s '%s' '%s' '%s'" \
% (element.tag, indexstr, name, uristr))
handle = context.handles[alias]
<|code_end|>
. Write the next line using the current file imports:
import os
import re
import pwd
import skema.tag
from skema.omxil12 import get_il_enum_from_string
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_PARAM_CONTENTURITYPE
from skema.omxil12 import OMX_GetParameter
from skema.omxil12 import OMX_SetParameter
from skema.utils import log_api
from skema.utils import log_line
from skema.utils import log_param
from skema.utils import log_result
from ctypes import sizeof
from ctypes import byref
from ctypes import CDLL
from ctypes import cast
from ctypes import c_char_p
and context from other files:
# Path: skema/omxil12.py
# def get_il_enum_from_string(string):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if name == string:
# return val
# raise AttributeError
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_PARAM_CONTENTURITYPE = struct_OMX_PARAM_CONTENTURITYPE # OMX_Component.h: 126
#
# Path: skema/omxil12.py
# def OMX_GetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/omxil12.py
# def OMX_SetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.SetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
, which may include functions, classes, or code. Output only the next line. | index = get_il_enum_from_string(indexstr) |
Continue the code snippet: <|code_start|>
class tag_OMX_SetContentURI(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
indexstr = "OMX_IndexParamContentURI"
uristr = element.get('uri')
alias = element.get('alias')
name = context.cnames[alias]
# Replace '$USER' and '$HOME' strings wih the actual representations
uristr = re.sub("\$USER", pwd.getpwuid(os.getuid())[0], uristr, 1)
uristr = re.sub("\$HOME", pwd.getpwuid(os.getuid())[5], uristr, 1)
log_api ("%s '%s' '%s' '%s'" \
% (element.tag, indexstr, name, uristr))
handle = context.handles[alias]
index = get_il_enum_from_string(indexstr)
param_type = OMX_PARAM_CONTENTURITYPE
param_struct = param_type()
param_struct.nSize = sizeof(param_type)
if (handle != None):
omxerror = OMX_GetParameter(handle, index, byref(param_struct))
interror = int(omxerror & 0xffffffff)
<|code_end|>
. Use current file imports:
import os
import re
import pwd
import skema.tag
from skema.omxil12 import get_il_enum_from_string
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_PARAM_CONTENTURITYPE
from skema.omxil12 import OMX_GetParameter
from skema.omxil12 import OMX_SetParameter
from skema.utils import log_api
from skema.utils import log_line
from skema.utils import log_param
from skema.utils import log_result
from ctypes import sizeof
from ctypes import byref
from ctypes import CDLL
from ctypes import cast
from ctypes import c_char_p
and context (classes, functions, or code) from other files:
# Path: skema/omxil12.py
# def get_il_enum_from_string(string):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if name == string:
# return val
# raise AttributeError
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_PARAM_CONTENTURITYPE = struct_OMX_PARAM_CONTENTURITYPE # OMX_Component.h: 126
#
# Path: skema/omxil12.py
# def OMX_GetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/omxil12.py
# def OMX_SetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.SetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | err = get_string_from_il_enum(interror, "OMX_Error") |
Continue the code 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, see <http://www.gnu.org/licenses/>.
class tag_OMX_SetContentURI(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
indexstr = "OMX_IndexParamContentURI"
uristr = element.get('uri')
alias = element.get('alias')
name = context.cnames[alias]
# Replace '$USER' and '$HOME' strings wih the actual representations
uristr = re.sub("\$USER", pwd.getpwuid(os.getuid())[0], uristr, 1)
uristr = re.sub("\$HOME", pwd.getpwuid(os.getuid())[5], uristr, 1)
log_api ("%s '%s' '%s' '%s'" \
% (element.tag, indexstr, name, uristr))
handle = context.handles[alias]
index = get_il_enum_from_string(indexstr)
<|code_end|>
. Use current file imports:
import os
import re
import pwd
import skema.tag
from skema.omxil12 import get_il_enum_from_string
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_PARAM_CONTENTURITYPE
from skema.omxil12 import OMX_GetParameter
from skema.omxil12 import OMX_SetParameter
from skema.utils import log_api
from skema.utils import log_line
from skema.utils import log_param
from skema.utils import log_result
from ctypes import sizeof
from ctypes import byref
from ctypes import CDLL
from ctypes import cast
from ctypes import c_char_p
and context (classes, functions, or code) from other files:
# Path: skema/omxil12.py
# def get_il_enum_from_string(string):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if name == string:
# return val
# raise AttributeError
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_PARAM_CONTENTURITYPE = struct_OMX_PARAM_CONTENTURITYPE # OMX_Component.h: 126
#
# Path: skema/omxil12.py
# def OMX_GetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/omxil12.py
# def OMX_SetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.SetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | param_type = OMX_PARAM_CONTENTURITYPE |
Predict the next line after this snippet: <|code_start|>
class tag_OMX_SetContentURI(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
indexstr = "OMX_IndexParamContentURI"
uristr = element.get('uri')
alias = element.get('alias')
name = context.cnames[alias]
# Replace '$USER' and '$HOME' strings wih the actual representations
uristr = re.sub("\$USER", pwd.getpwuid(os.getuid())[0], uristr, 1)
uristr = re.sub("\$HOME", pwd.getpwuid(os.getuid())[5], uristr, 1)
log_api ("%s '%s' '%s' '%s'" \
% (element.tag, indexstr, name, uristr))
handle = context.handles[alias]
index = get_il_enum_from_string(indexstr)
param_type = OMX_PARAM_CONTENTURITYPE
param_struct = param_type()
param_struct.nSize = sizeof(param_type)
if (handle != None):
<|code_end|>
using the current file's imports:
import os
import re
import pwd
import skema.tag
from skema.omxil12 import get_il_enum_from_string
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_PARAM_CONTENTURITYPE
from skema.omxil12 import OMX_GetParameter
from skema.omxil12 import OMX_SetParameter
from skema.utils import log_api
from skema.utils import log_line
from skema.utils import log_param
from skema.utils import log_result
from ctypes import sizeof
from ctypes import byref
from ctypes import CDLL
from ctypes import cast
from ctypes import c_char_p
and any relevant context from other files:
# Path: skema/omxil12.py
# def get_il_enum_from_string(string):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if name == string:
# return val
# raise AttributeError
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_PARAM_CONTENTURITYPE = struct_OMX_PARAM_CONTENTURITYPE # OMX_Component.h: 126
#
# Path: skema/omxil12.py
# def OMX_GetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/omxil12.py
# def OMX_SetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.SetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | omxerror = OMX_GetParameter(handle, index, byref(param_struct)) |
Given the following code snippet before the placeholder: <|code_start|> name = context.cnames[alias]
# Replace '$USER' and '$HOME' strings wih the actual representations
uristr = re.sub("\$USER", pwd.getpwuid(os.getuid())[0], uristr, 1)
uristr = re.sub("\$HOME", pwd.getpwuid(os.getuid())[5], uristr, 1)
log_api ("%s '%s' '%s' '%s'" \
% (element.tag, indexstr, name, uristr))
handle = context.handles[alias]
index = get_il_enum_from_string(indexstr)
param_type = OMX_PARAM_CONTENTURITYPE
param_struct = param_type()
param_struct.nSize = sizeof(param_type)
if (handle != None):
omxerror = OMX_GetParameter(handle, index, byref(param_struct))
interror = int(omxerror & 0xffffffff)
err = get_string_from_il_enum(interror, "OMX_Error")
for name, _ in param_type._fields_:
for name2, val2 in element.items():
if (name != "contentURI"):
if (name2 == name):
setattr(param_struct, name, int(val2))
else:
libc = CDLL('libc.so.6')
libc.strcpy(cast(param_struct.contentURI, c_char_p),
uristr)
<|code_end|>
, predict the next line using imports from the current file:
import os
import re
import pwd
import skema.tag
from skema.omxil12 import get_il_enum_from_string
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_PARAM_CONTENTURITYPE
from skema.omxil12 import OMX_GetParameter
from skema.omxil12 import OMX_SetParameter
from skema.utils import log_api
from skema.utils import log_line
from skema.utils import log_param
from skema.utils import log_result
from ctypes import sizeof
from ctypes import byref
from ctypes import CDLL
from ctypes import cast
from ctypes import c_char_p
and context including class names, function names, and sometimes code from other files:
# Path: skema/omxil12.py
# def get_il_enum_from_string(string):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if name == string:
# return val
# raise AttributeError
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_PARAM_CONTENTURITYPE = struct_OMX_PARAM_CONTENTURITYPE # OMX_Component.h: 126
#
# Path: skema/omxil12.py
# def OMX_GetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/omxil12.py
# def OMX_SetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.SetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | omxerror = OMX_SetParameter(handle, index, byref(param_struct)) |
Next line prediction: <|code_start|># the Free Software Foundation, either version 3 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, see <http://www.gnu.org/licenses/>.
class tag_OMX_SetContentURI(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
indexstr = "OMX_IndexParamContentURI"
uristr = element.get('uri')
alias = element.get('alias')
name = context.cnames[alias]
# Replace '$USER' and '$HOME' strings wih the actual representations
uristr = re.sub("\$USER", pwd.getpwuid(os.getuid())[0], uristr, 1)
uristr = re.sub("\$HOME", pwd.getpwuid(os.getuid())[5], uristr, 1)
<|code_end|>
. Use current file imports:
(import os
import re
import pwd
import skema.tag
from skema.omxil12 import get_il_enum_from_string
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_PARAM_CONTENTURITYPE
from skema.omxil12 import OMX_GetParameter
from skema.omxil12 import OMX_SetParameter
from skema.utils import log_api
from skema.utils import log_line
from skema.utils import log_param
from skema.utils import log_result
from ctypes import sizeof
from ctypes import byref
from ctypes import CDLL
from ctypes import cast
from ctypes import c_char_p)
and context including class names, function names, or small code snippets from other files:
# Path: skema/omxil12.py
# def get_il_enum_from_string(string):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if name == string:
# return val
# raise AttributeError
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_PARAM_CONTENTURITYPE = struct_OMX_PARAM_CONTENTURITYPE # OMX_Component.h: 126
#
# Path: skema/omxil12.py
# def OMX_GetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/omxil12.py
# def OMX_SetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.SetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | log_api ("%s '%s' '%s' '%s'" \ |
Given snippet: <|code_start|> % (element.tag, indexstr, name, uristr))
handle = context.handles[alias]
index = get_il_enum_from_string(indexstr)
param_type = OMX_PARAM_CONTENTURITYPE
param_struct = param_type()
param_struct.nSize = sizeof(param_type)
if (handle != None):
omxerror = OMX_GetParameter(handle, index, byref(param_struct))
interror = int(omxerror & 0xffffffff)
err = get_string_from_il_enum(interror, "OMX_Error")
for name, _ in param_type._fields_:
for name2, val2 in element.items():
if (name != "contentURI"):
if (name2 == name):
setattr(param_struct, name, int(val2))
else:
libc = CDLL('libc.so.6')
libc.strcpy(cast(param_struct.contentURI, c_char_p),
uristr)
omxerror = OMX_SetParameter(handle, index, byref(param_struct))
interror = int(omxerror & 0xffffffff)
err = get_string_from_il_enum(interror, "OMX_Error")
urifield = c_char_p()
urifield = cast(param_struct.contentURI, c_char_p)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import re
import pwd
import skema.tag
from skema.omxil12 import get_il_enum_from_string
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_PARAM_CONTENTURITYPE
from skema.omxil12 import OMX_GetParameter
from skema.omxil12 import OMX_SetParameter
from skema.utils import log_api
from skema.utils import log_line
from skema.utils import log_param
from skema.utils import log_result
from ctypes import sizeof
from ctypes import byref
from ctypes import CDLL
from ctypes import cast
from ctypes import c_char_p
and context:
# Path: skema/omxil12.py
# def get_il_enum_from_string(string):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if name == string:
# return val
# raise AttributeError
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_PARAM_CONTENTURITYPE = struct_OMX_PARAM_CONTENTURITYPE # OMX_Component.h: 126
#
# Path: skema/omxil12.py
# def OMX_GetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/omxil12.py
# def OMX_SetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.SetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
which might include code, classes, or functions. Output only the next line. | log_line () |
Given the code snippet: <|code_start|>
if (handle != None):
omxerror = OMX_GetParameter(handle, index, byref(param_struct))
interror = int(omxerror & 0xffffffff)
err = get_string_from_il_enum(interror, "OMX_Error")
for name, _ in param_type._fields_:
for name2, val2 in element.items():
if (name != "contentURI"):
if (name2 == name):
setattr(param_struct, name, int(val2))
else:
libc = CDLL('libc.so.6')
libc.strcpy(cast(param_struct.contentURI, c_char_p),
uristr)
omxerror = OMX_SetParameter(handle, index, byref(param_struct))
interror = int(omxerror & 0xffffffff)
err = get_string_from_il_enum(interror, "OMX_Error")
urifield = c_char_p()
urifield = cast(param_struct.contentURI, c_char_p)
log_line ()
log_line ("%s" % param_struct.__class__.__name__, 1)
for name, _ in param_type._fields_:
if (name == "nVersion"):
log_line ("%s -> '%08x'" \
% (name, param_struct.nVersion.nVersion), 1)
elif (name == "contentURI"):
<|code_end|>
, generate the next line using the imports in this file:
import os
import re
import pwd
import skema.tag
from skema.omxil12 import get_il_enum_from_string
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_PARAM_CONTENTURITYPE
from skema.omxil12 import OMX_GetParameter
from skema.omxil12 import OMX_SetParameter
from skema.utils import log_api
from skema.utils import log_line
from skema.utils import log_param
from skema.utils import log_result
from ctypes import sizeof
from ctypes import byref
from ctypes import CDLL
from ctypes import cast
from ctypes import c_char_p
and context (functions, classes, or occasionally code) from other files:
# Path: skema/omxil12.py
# def get_il_enum_from_string(string):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if name == string:
# return val
# raise AttributeError
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_PARAM_CONTENTURITYPE = struct_OMX_PARAM_CONTENTURITYPE # OMX_Component.h: 126
#
# Path: skema/omxil12.py
# def OMX_GetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/omxil12.py
# def OMX_SetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.SetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | log_param (name, urifield.value, 1) |
Predict the next line after this snippet: <|code_start|> err = get_string_from_il_enum(interror, "OMX_Error")
for name, _ in param_type._fields_:
for name2, val2 in element.items():
if (name != "contentURI"):
if (name2 == name):
setattr(param_struct, name, int(val2))
else:
libc = CDLL('libc.so.6')
libc.strcpy(cast(param_struct.contentURI, c_char_p),
uristr)
omxerror = OMX_SetParameter(handle, index, byref(param_struct))
interror = int(omxerror & 0xffffffff)
err = get_string_from_il_enum(interror, "OMX_Error")
urifield = c_char_p()
urifield = cast(param_struct.contentURI, c_char_p)
log_line ()
log_line ("%s" % param_struct.__class__.__name__, 1)
for name, _ in param_type._fields_:
if (name == "nVersion"):
log_line ("%s -> '%08x'" \
% (name, param_struct.nVersion.nVersion), 1)
elif (name == "contentURI"):
log_param (name, urifield.value, 1)
else:
log_param (name, str(getattr(param_struct, name)), 1)
<|code_end|>
using the current file's imports:
import os
import re
import pwd
import skema.tag
from skema.omxil12 import get_il_enum_from_string
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_PARAM_CONTENTURITYPE
from skema.omxil12 import OMX_GetParameter
from skema.omxil12 import OMX_SetParameter
from skema.utils import log_api
from skema.utils import log_line
from skema.utils import log_param
from skema.utils import log_result
from ctypes import sizeof
from ctypes import byref
from ctypes import CDLL
from ctypes import cast
from ctypes import c_char_p
and any relevant context from other files:
# Path: skema/omxil12.py
# def get_il_enum_from_string(string):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if name == string:
# return val
# raise AttributeError
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_PARAM_CONTENTURITYPE = struct_OMX_PARAM_CONTENTURITYPE # OMX_Component.h: 126
#
# Path: skema/omxil12.py
# def OMX_GetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/omxil12.py
# def OMX_SetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.SetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | log_result(element.tag, err) |
Predict the next line after this snippet: <|code_start|> self.quiet = kwargs.pop('quiet')
except KeyError:
self.quiet = False
super(Tee, self).__init__(*args, **kwargs)
def write(self, data):
super(Tee, self).write(data)
if self.quiet is False:
sys.stdout.write(data)
class bcolors:
BOLD = '\033[1m'
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
def disable(self):
self.HEADER = ''
self.OKBLUE = ''
self.OKGREEN = ''
self.WARNING = ''
self.FAIL = ''
self.ENDC = ''
def printit(line):
<|code_end|>
using the current file's imports:
import os
import shutil
import subprocess
import sys
import urllib2
import urlparse
import logging
from skema.config import get_config
and any relevant context from other files:
# Path: skema/config.py
# def get_config():
# global _config
# if _config is not None:
# return _config
# _config = SkemaConfig()
# return _config
. Output only the next line. | config = get_config () |
Predict the next line after this snippet: <|code_start|># Copyright (C) 2011-2017 Aratelia Limited - Juan A. Rubio
#
# 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 3 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, see <http://www.gnu.org/licenses/>.
class tag_OMX_BaseProfileFreeBuffers(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
alias = element.get('alias')
name = context.cnames[alias]
portstr = element.get('port')
howmanystr = element.get('howmany')
<|code_end|>
using the current file's imports:
import skema.tag
from skema.utils import log_api
from skema.utils import log_result
and any relevant context from other files:
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | log_api ("%s %s:Port-%s' 'Howmany:%s'" \ |
Given the code snippet: <|code_start|># 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.
#
# 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, see <http://www.gnu.org/licenses/>.
class tag_OMX_BaseProfileFreeBuffers(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
alias = element.get('alias')
name = context.cnames[alias]
portstr = element.get('port')
howmanystr = element.get('howmany')
log_api ("%s %s:Port-%s' 'Howmany:%s'" \
% (element.tag, name, portstr, howmanystr))
context.base_profile_mgr.free_buffers(alias, portstr, howmanystr)
<|code_end|>
, generate the next line using the imports in this file:
import skema.tag
from skema.utils import log_api
from skema.utils import log_result
and context (functions, classes, or occasionally code) from other files:
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | log_result (element.tag, "OMX_ErrorNone") |
Continue the code snippet: <|code_start|> This can be used by test definition files to create an object that contains
the building blocks for installing tests, running them, and parsing the
results.
suitename - name of the test suite
version - version of the test suite
installer - SkemaInstaller instance to use
runner - SkemaRunner instance to use
parser - SkemaParser instance to use
"""
def __init__(self, suitename, version="", installer=None, runner=None,
parser=None):
self.suitename = suitename
self.version = version
self.installer = installer
self.runner = runner
self.parser = parser
self.origdir = os.path.abspath(os.curdir)
def install(self):
"""Install the test suite.
This creates an install directory under the user's XDG_DATA_HOME
directory to mark that the test is installed. The installer's
install() method is then called from this directory to complete any
test specific install that may be needed.
"""
if not self.installer:
raise RuntimeError("no installer defined for '%s'" %
self.suitename)
<|code_end|>
. Use current file imports:
import os
import glob
import re
import shutil
import time
import logging
from commands import getstatusoutput
from datetime import datetime
from uuid import uuid1
from skema.api import SkemaSuiteIf
from skema.config import get_config
from skema.suiteutils import run_suite
from skema.utils import log_line
from skema.utils import log_result
from skema.omxil12 import get_string_from_il_enum
and context (classes, functions, or code) from other files:
# Path: skema/api.py
# class SkemaSuiteIf(object):
# """
# Skema test suite.
#
# Abstract class for skema test suite classes.
# """
#
# @abstractmethod
# def install(self):
# """
# Install the test suite.
#
# This creates an install directory under the user's XDG_DATA_HOME
# directory to mark that the suite is installed. The installer's
# install() method is then called from this directory to complete any
# test specific install that may be needed.
# """
#
# @abstractmethod
# def uninstall(self):
# """
# Uninstall the test suite.
#
# Uninstalling just recursively removes the test specific directory under
# the user's XDG_DATA_HOME directory. This will both mark the suite as
# removed, and clean up any files that were installed under that
# directory. Dependencies are intentionally not removed by this.
# """
#
# @abstractmethod
# def run(self, quiet=False, output=None):
# # TODO: Document me
# pass
#
# @abstractmethod
# def parse(self, resultname):
# # TODO: Document me
# pass
#
# Path: skema/config.py
# def get_config():
# global _config
# if _config is not None:
# return _config
# _config = SkemaConfig()
# return _config
#
# Path: skema/suiteutils.py
# def run_suite(scriptpath):
#
# tree = et()
# tree.parse(scriptpath)
# titer = tree.iter()
#
# config = get_config()
#
# suites = []
# cases = []
# errors = dict()
# last_tag = dict()
# case = ""
# for elem in titer:
#
# if elem.tag == "Suite":
# continue
#
# if elem.tag == "Case":
# case = elem.get('name')
# log_line ("Use Case : '%s'" % case)
# cases.append(case)
# errors[case] = 0
# result = 0
# continue
#
# if result == 0:
# tag_func = get_tag(elem.tag)
# if not tag_func:
# log_line ("Tag '%s' not found. Exiting." % elem.tag)
# sys.exit(1)
#
# result = tag_func.run(elem, config)
# if result != 0:
# log_result (elem.tag, get_string_from_il_enum(result, "OMX_Error"))
# errors[case] = result
# last_tag[case] = elem.tag
#
# if result != 0:
# config.base_profile_mgr.stop()
#
# log_line()
# log_line()
# log_line("-------------------------------------------------------------------")
# msg = "SUITE EXECUTION SUMMARY : " + str(len(cases)) + " test cases executed"
# log_result (msg, get_string_from_il_enum(result, "OMX_Error"))
# last_error = 0
# for case in cases:
# msg = "CASE : " + case + " (last tag was '" + last_tag[case] + "')"
# log_result (msg, get_string_from_il_enum(errors[case], "OMX_Error"))
# if errors[case] != 0:
# last_error = errors[case]
# log_line()
# log_line("-------------------------------------------------------------------")
# log_line()
#
# return last_error
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
. Output only the next line. | config = get_config() |
Given the following code snippet before the placeholder: <|code_start|> def install(self):
self._installscript()
class SkemaSuiteRunner(object):
"""Base class for defining an test runner object.
This class can be used as-is for simple execution with the expectation
that the run() method will be called from the directory where the test
was installed. Steps, if used, should handle changing directories from
there to the directory where the test was extracted if necessary.
This class can also be extended for more advanced funcionality.
"""
def __init__(self):
self.testoutput = []
def _runsteps(self, scriptpath, resultsdir, quiet=False):
outputlog = os.path.join(resultsdir, 'outputlog.txt')
outputlog2 = os.path.join(resultsdir, 'outputlog2.txt')
logging.basicConfig (filename=outputlog2, filemode='w', \
format='%(asctime)s - %(levelname)s : %(message)s', \
level=logging.DEBUG)
logging.info("log")
result = 0
with open(outputlog, 'a') as fd:
config = get_config()
config.quiet = quiet
temp = config.fd
config.fd = fd
<|code_end|>
, predict the next line using imports from the current file:
import os
import glob
import re
import shutil
import time
import logging
from commands import getstatusoutput
from datetime import datetime
from uuid import uuid1
from skema.api import SkemaSuiteIf
from skema.config import get_config
from skema.suiteutils import run_suite
from skema.utils import log_line
from skema.utils import log_result
from skema.omxil12 import get_string_from_il_enum
and context including class names, function names, and sometimes code from other files:
# Path: skema/api.py
# class SkemaSuiteIf(object):
# """
# Skema test suite.
#
# Abstract class for skema test suite classes.
# """
#
# @abstractmethod
# def install(self):
# """
# Install the test suite.
#
# This creates an install directory under the user's XDG_DATA_HOME
# directory to mark that the suite is installed. The installer's
# install() method is then called from this directory to complete any
# test specific install that may be needed.
# """
#
# @abstractmethod
# def uninstall(self):
# """
# Uninstall the test suite.
#
# Uninstalling just recursively removes the test specific directory under
# the user's XDG_DATA_HOME directory. This will both mark the suite as
# removed, and clean up any files that were installed under that
# directory. Dependencies are intentionally not removed by this.
# """
#
# @abstractmethod
# def run(self, quiet=False, output=None):
# # TODO: Document me
# pass
#
# @abstractmethod
# def parse(self, resultname):
# # TODO: Document me
# pass
#
# Path: skema/config.py
# def get_config():
# global _config
# if _config is not None:
# return _config
# _config = SkemaConfig()
# return _config
#
# Path: skema/suiteutils.py
# def run_suite(scriptpath):
#
# tree = et()
# tree.parse(scriptpath)
# titer = tree.iter()
#
# config = get_config()
#
# suites = []
# cases = []
# errors = dict()
# last_tag = dict()
# case = ""
# for elem in titer:
#
# if elem.tag == "Suite":
# continue
#
# if elem.tag == "Case":
# case = elem.get('name')
# log_line ("Use Case : '%s'" % case)
# cases.append(case)
# errors[case] = 0
# result = 0
# continue
#
# if result == 0:
# tag_func = get_tag(elem.tag)
# if not tag_func:
# log_line ("Tag '%s' not found. Exiting." % elem.tag)
# sys.exit(1)
#
# result = tag_func.run(elem, config)
# if result != 0:
# log_result (elem.tag, get_string_from_il_enum(result, "OMX_Error"))
# errors[case] = result
# last_tag[case] = elem.tag
#
# if result != 0:
# config.base_profile_mgr.stop()
#
# log_line()
# log_line()
# log_line("-------------------------------------------------------------------")
# msg = "SUITE EXECUTION SUMMARY : " + str(len(cases)) + " test cases executed"
# log_result (msg, get_string_from_il_enum(result, "OMX_Error"))
# last_error = 0
# for case in cases:
# msg = "CASE : " + case + " (last tag was '" + last_tag[case] + "')"
# log_result (msg, get_string_from_il_enum(errors[case], "OMX_Error"))
# if errors[case] != 0:
# last_error = errors[case]
# log_line()
# log_line("-------------------------------------------------------------------")
# log_line()
#
# return last_error
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
. Output only the next line. | result = run_suite(scriptpath) |
Predict the next line after this snippet: <|code_start|> self._installscript()
class SkemaSuiteRunner(object):
"""Base class for defining an test runner object.
This class can be used as-is for simple execution with the expectation
that the run() method will be called from the directory where the test
was installed. Steps, if used, should handle changing directories from
there to the directory where the test was extracted if necessary.
This class can also be extended for more advanced funcionality.
"""
def __init__(self):
self.testoutput = []
def _runsteps(self, scriptpath, resultsdir, quiet=False):
outputlog = os.path.join(resultsdir, 'outputlog.txt')
outputlog2 = os.path.join(resultsdir, 'outputlog2.txt')
logging.basicConfig (filename=outputlog2, filemode='w', \
format='%(asctime)s - %(levelname)s : %(message)s', \
level=logging.DEBUG)
logging.info("log")
result = 0
with open(outputlog, 'a') as fd:
config = get_config()
config.quiet = quiet
temp = config.fd
config.fd = fd
result = run_suite(scriptpath)
<|code_end|>
using the current file's imports:
import os
import glob
import re
import shutil
import time
import logging
from commands import getstatusoutput
from datetime import datetime
from uuid import uuid1
from skema.api import SkemaSuiteIf
from skema.config import get_config
from skema.suiteutils import run_suite
from skema.utils import log_line
from skema.utils import log_result
from skema.omxil12 import get_string_from_il_enum
and any relevant context from other files:
# Path: skema/api.py
# class SkemaSuiteIf(object):
# """
# Skema test suite.
#
# Abstract class for skema test suite classes.
# """
#
# @abstractmethod
# def install(self):
# """
# Install the test suite.
#
# This creates an install directory under the user's XDG_DATA_HOME
# directory to mark that the suite is installed. The installer's
# install() method is then called from this directory to complete any
# test specific install that may be needed.
# """
#
# @abstractmethod
# def uninstall(self):
# """
# Uninstall the test suite.
#
# Uninstalling just recursively removes the test specific directory under
# the user's XDG_DATA_HOME directory. This will both mark the suite as
# removed, and clean up any files that were installed under that
# directory. Dependencies are intentionally not removed by this.
# """
#
# @abstractmethod
# def run(self, quiet=False, output=None):
# # TODO: Document me
# pass
#
# @abstractmethod
# def parse(self, resultname):
# # TODO: Document me
# pass
#
# Path: skema/config.py
# def get_config():
# global _config
# if _config is not None:
# return _config
# _config = SkemaConfig()
# return _config
#
# Path: skema/suiteutils.py
# def run_suite(scriptpath):
#
# tree = et()
# tree.parse(scriptpath)
# titer = tree.iter()
#
# config = get_config()
#
# suites = []
# cases = []
# errors = dict()
# last_tag = dict()
# case = ""
# for elem in titer:
#
# if elem.tag == "Suite":
# continue
#
# if elem.tag == "Case":
# case = elem.get('name')
# log_line ("Use Case : '%s'" % case)
# cases.append(case)
# errors[case] = 0
# result = 0
# continue
#
# if result == 0:
# tag_func = get_tag(elem.tag)
# if not tag_func:
# log_line ("Tag '%s' not found. Exiting." % elem.tag)
# sys.exit(1)
#
# result = tag_func.run(elem, config)
# if result != 0:
# log_result (elem.tag, get_string_from_il_enum(result, "OMX_Error"))
# errors[case] = result
# last_tag[case] = elem.tag
#
# if result != 0:
# config.base_profile_mgr.stop()
#
# log_line()
# log_line()
# log_line("-------------------------------------------------------------------")
# msg = "SUITE EXECUTION SUMMARY : " + str(len(cases)) + " test cases executed"
# log_result (msg, get_string_from_il_enum(result, "OMX_Error"))
# last_error = 0
# for case in cases:
# msg = "CASE : " + case + " (last tag was '" + last_tag[case] + "')"
# log_result (msg, get_string_from_il_enum(errors[case], "OMX_Error"))
# if errors[case] != 0:
# last_error = errors[case]
# log_line()
# log_line("-------------------------------------------------------------------")
# log_line()
#
# return last_error
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
. Output only the next line. | log_line() |
Next line prediction: <|code_start|> titer = tree.iter()
config = get_config()
suites = []
cases = []
errors = dict()
last_tag = dict()
case = ""
for elem in titer:
if elem.tag == "Suite":
continue
if elem.tag == "Case":
case = elem.get('name')
log_line ("Use Case : '%s'" % case)
cases.append(case)
errors[case] = 0
result = 0
continue
if result == 0:
tag_func = get_tag(elem.tag)
if not tag_func:
log_line ("Tag '%s' not found. Exiting." % elem.tag)
sys.exit(1)
result = tag_func.run(elem, config)
if result != 0:
<|code_end|>
. Use current file imports:
(import os
import sys
import skema.command
from ctypes import *
from xml.etree.ElementTree import ElementTree as et
from optparse import make_option
from skema.omxil12 import get_string_from_il_enum
from skema.utils import log_line
from skema.utils import log_result
from skema.tagutils import get_tag
from skema.config import get_config)
and context including class names, function names, or small code snippets from other files:
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
#
# Path: skema/tagutils.py
# def get_tag(tag_name):
# tags = get_all_tags()
# return tags.get(tag_name)
#
# Path: skema/config.py
# def get_config():
# global _config
# if _config is not None:
# return _config
# _config = SkemaConfig()
# return _config
. Output only the next line. | log_result (elem.tag, get_string_from_il_enum(result, "OMX_Error")) |
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, see <http://www.gnu.org/licenses/>.
"""
Skema's suite-related utility functions
"""
def run_suite(scriptpath):
tree = et()
tree.parse(scriptpath)
titer = tree.iter()
config = get_config()
suites = []
cases = []
errors = dict()
last_tag = dict()
case = ""
for elem in titer:
if elem.tag == "Suite":
continue
if elem.tag == "Case":
case = elem.get('name')
<|code_end|>
with the help of current file imports:
import os
import sys
import skema.command
from ctypes import *
from xml.etree.ElementTree import ElementTree as et
from optparse import make_option
from skema.omxil12 import get_string_from_il_enum
from skema.utils import log_line
from skema.utils import log_result
from skema.tagutils import get_tag
from skema.config import get_config
and context from other files:
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
#
# Path: skema/tagutils.py
# def get_tag(tag_name):
# tags = get_all_tags()
# return tags.get(tag_name)
#
# Path: skema/config.py
# def get_config():
# global _config
# if _config is not None:
# return _config
# _config = SkemaConfig()
# return _config
, which may contain function names, class names, or code. Output only the next line. | log_line ("Use Case : '%s'" % case) |
Predict the next line after this snippet: <|code_start|> titer = tree.iter()
config = get_config()
suites = []
cases = []
errors = dict()
last_tag = dict()
case = ""
for elem in titer:
if elem.tag == "Suite":
continue
if elem.tag == "Case":
case = elem.get('name')
log_line ("Use Case : '%s'" % case)
cases.append(case)
errors[case] = 0
result = 0
continue
if result == 0:
tag_func = get_tag(elem.tag)
if not tag_func:
log_line ("Tag '%s' not found. Exiting." % elem.tag)
sys.exit(1)
result = tag_func.run(elem, config)
if result != 0:
<|code_end|>
using the current file's imports:
import os
import sys
import skema.command
from ctypes import *
from xml.etree.ElementTree import ElementTree as et
from optparse import make_option
from skema.omxil12 import get_string_from_il_enum
from skema.utils import log_line
from skema.utils import log_result
from skema.tagutils import get_tag
from skema.config import get_config
and any relevant context from other files:
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
#
# Path: skema/tagutils.py
# def get_tag(tag_name):
# tags = get_all_tags()
# return tags.get(tag_name)
#
# Path: skema/config.py
# def get_config():
# global _config
# if _config is not None:
# return _config
# _config = SkemaConfig()
# return _config
. Output only the next line. | log_result (elem.tag, get_string_from_il_enum(result, "OMX_Error")) |
Using the snippet: <|code_start|>
def run_suite(scriptpath):
tree = et()
tree.parse(scriptpath)
titer = tree.iter()
config = get_config()
suites = []
cases = []
errors = dict()
last_tag = dict()
case = ""
for elem in titer:
if elem.tag == "Suite":
continue
if elem.tag == "Case":
case = elem.get('name')
log_line ("Use Case : '%s'" % case)
cases.append(case)
errors[case] = 0
result = 0
continue
if result == 0:
<|code_end|>
, determine the next line of code. You have imports:
import os
import sys
import skema.command
from ctypes import *
from xml.etree.ElementTree import ElementTree as et
from optparse import make_option
from skema.omxil12 import get_string_from_il_enum
from skema.utils import log_line
from skema.utils import log_result
from skema.tagutils import get_tag
from skema.config import get_config
and context (class names, function names, or code) available:
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
#
# Path: skema/tagutils.py
# def get_tag(tag_name):
# tags = get_all_tags()
# return tags.get(tag_name)
#
# Path: skema/config.py
# def get_config():
# global _config
# if _config is not None:
# return _config
# _config = SkemaConfig()
# return _config
. Output only the next line. | tag_func = get_tag(elem.tag) |
Here is a snippet: <|code_start|># Copyright (C) 2011-2017 Aratelia Limited - Juan A. Rubio
#
# Portions Copyright (C) 2010 Linaro
#
# 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 3 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, see <http://www.gnu.org/licenses/>.
"""
Skema's suite-related utility functions
"""
def run_suite(scriptpath):
tree = et()
tree.parse(scriptpath)
titer = tree.iter()
<|code_end|>
. Write the next line using the current file imports:
import os
import sys
import skema.command
from ctypes import *
from xml.etree.ElementTree import ElementTree as et
from optparse import make_option
from skema.omxil12 import get_string_from_il_enum
from skema.utils import log_line
from skema.utils import log_result
from skema.tagutils import get_tag
from skema.config import get_config
and context from other files:
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
#
# Path: skema/tagutils.py
# def get_tag(tag_name):
# tags = get_all_tags()
# return tags.get(tag_name)
#
# Path: skema/config.py
# def get_config():
# global _config
# if _config is not None:
# return _config
# _config = SkemaConfig()
# return _config
, which may include functions, classes, or code. Output only the next line. | config = get_config() |
Next line prediction: <|code_start|>"""
class SkemaTag(SkemaTagIf):
"""Base class for defining skema's test tags.
This can be used by test definition files to create an object that contains
the building blocks for installing tests, running them, and parsing the
results.
tagsdir - name of the test tag
"""
def __init__(self, tagname):
self.tagsdir = tagname
self.origdir = os.path.abspath(os.curdir)
def install(self):
"""Install the test tag.
This creates an install directory under the user's XDG_DATA_HOME
directory to mark that the tag is installed. The installer's
install() method is then called from this directory to complete any
test specific install that may be needed.
"""
#if not self.installer:
# raise RuntimeError("no installer defined for '%s'" %
# self.tagsdir)
<|code_end|>
. Use current file imports:
(import os
import shutil
from skema.api import SkemaTagIf
from skema.config import get_config)
and context including class names, function names, or small code snippets from other files:
# Path: skema/api.py
# class SkemaTagIf(object):
# """
# Skema tag.
#
# Abstract class for skema tag classes.
# """
#
# @abstractmethod
# def install(self):
# """
# Install the tag.
#
# This creates an install directory under the user's XDG_DATA_HOME
# directory to mark that the tag is installed. The installer's
# install() method is then called from this directory to complete any
# test specific install that may be needed.
# """
#
# @abstractmethod
# def uninstall(self):
# """
# Uninstall the test tag.
#
# Uninstalling just recursively removes the test specific directory under
# the user's XDG_DATA_HOME directory. This will both mark the tag as
# removed, and clean up any files that were installed under that
# directory. Dependencies are intentionally not removed by this.
# """
#
# @abstractmethod
# def run(self, element, context):
# # TODO: Document me
# pass
#
# Path: skema/config.py
# def get_config():
# global _config
# if _config is not None:
# return _config
# _config = SkemaConfig()
# return _config
. Output only the next line. | config = get_config() |
Here is a 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 3 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, see <http://www.gnu.org/licenses/>.
class tag_OMX_StopSubProcess(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
alias = element.get('alias')
log_api ("%s '%s'" \
% (element.tag, alias))
pid = context.subprocesses[alias].pid
context.subprocesses[alias].terminate()
del context.subprocesses[alias]
<|code_end|>
. Write the next line using the current file imports:
from subprocess import Popen
from skema.utils import log_line
from skema.utils import log_result
from skema.utils import log_api
import skema.tag
and context from other files:
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
, which may include functions, classes, or code. Output only the next line. | log_line () |
Here is a snippet: <|code_start|># 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.
#
# 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, see <http://www.gnu.org/licenses/>.
class tag_OMX_StopSubProcess(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
alias = element.get('alias')
log_api ("%s '%s'" \
% (element.tag, alias))
pid = context.subprocesses[alias].pid
context.subprocesses[alias].terminate()
del context.subprocesses[alias]
log_line ()
msg = "Stopped sub-process '" + alias + "' with PID " + str(pid)
<|code_end|>
. Write the next line using the current file imports:
from subprocess import Popen
from skema.utils import log_line
from skema.utils import log_result
from skema.utils import log_api
import skema.tag
and context from other files:
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
, which may include functions, classes, or code. Output only the next line. | log_result (msg, "OMX_ErrorNone") |
Predict the next line for this snippet: <|code_start|># Copyright (C) 2011-2017 Aratelia Limited - Juan A. Rubio
#
# 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 3 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, see <http://www.gnu.org/licenses/>.
class tag_OMX_StopSubProcess(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
alias = element.get('alias')
<|code_end|>
with the help of current file imports:
from subprocess import Popen
from skema.utils import log_line
from skema.utils import log_result
from skema.utils import log_api
import skema.tag
and context from other files:
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
, which may contain function names, class names, or code. Output only the next line. | log_api ("%s '%s'" \ |
Here is a snippet: <|code_start|># (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, see <http://www.gnu.org/licenses/>.
#from types import *
class tag_OMX_SetComponentRole(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
indexstr = "OMX_IndexParamStandardComponentRole"
alias = element.get('alias')
name = context.cnames[alias]
rolestr = element.get('role')
log_api ("%s '%s' '%s'" \
% (element.tag, name, rolestr))
handle = context.handles[alias]
<|code_end|>
. Write the next line using the current file imports:
import skema.tag
from skema.omxil12 import get_il_enum_from_string
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_VERSION
from skema.omxil12 import OMX_PARAM_COMPONENTROLETYPE
from skema.omxil12 import OMX_GetParameter
from skema.omxil12 import OMX_SetParameter
from skema.utils import log_line
from skema.utils import log_api
from skema.utils import log_param
from skema.utils import log_result
from ctypes import c_char_p
from ctypes import sizeof
from ctypes import byref
from ctypes import CDLL
from ctypes import cast
and context from other files:
# Path: skema/omxil12.py
# def get_il_enum_from_string(string):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if name == string:
# return val
# raise AttributeError
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_VERSION = ((((OMX_VERSION_STEP << 24) | (OMX_VERSION_REVISION << 16)) | (OMX_VERSION_MINOR << 8)) | OMX_VERSION_MAJOR)
#
# Path: skema/omxil12.py
# OMX_PARAM_COMPONENTROLETYPE = struct_OMX_PARAM_COMPONENTROLETYPE # OMX_Core.h: 191
#
# Path: skema/omxil12.py
# def OMX_GetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/omxil12.py
# def OMX_SetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.SetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
, which may include functions, classes, or code. Output only the next line. | index = get_il_enum_from_string(indexstr) |
Given the following code snippet before the placeholder: <|code_start|>
#from types import *
class tag_OMX_SetComponentRole(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
indexstr = "OMX_IndexParamStandardComponentRole"
alias = element.get('alias')
name = context.cnames[alias]
rolestr = element.get('role')
log_api ("%s '%s' '%s'" \
% (element.tag, name, rolestr))
handle = context.handles[alias]
index = get_il_enum_from_string(indexstr)
param_type = OMX_PARAM_COMPONENTROLETYPE
param_struct = param_type()
param_struct.nVersion.nVersion = OMX_VERSION
param_struct.nSize = sizeof(param_type)
if (handle != None):
omxerror = OMX_GetParameter(handle, index, byref(param_struct))
interror = int(omxerror & 0xffffffff)
<|code_end|>
, predict the next line using imports from the current file:
import skema.tag
from skema.omxil12 import get_il_enum_from_string
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_VERSION
from skema.omxil12 import OMX_PARAM_COMPONENTROLETYPE
from skema.omxil12 import OMX_GetParameter
from skema.omxil12 import OMX_SetParameter
from skema.utils import log_line
from skema.utils import log_api
from skema.utils import log_param
from skema.utils import log_result
from ctypes import c_char_p
from ctypes import sizeof
from ctypes import byref
from ctypes import CDLL
from ctypes import cast
and context including class names, function names, and sometimes code from other files:
# Path: skema/omxil12.py
# def get_il_enum_from_string(string):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if name == string:
# return val
# raise AttributeError
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_VERSION = ((((OMX_VERSION_STEP << 24) | (OMX_VERSION_REVISION << 16)) | (OMX_VERSION_MINOR << 8)) | OMX_VERSION_MAJOR)
#
# Path: skema/omxil12.py
# OMX_PARAM_COMPONENTROLETYPE = struct_OMX_PARAM_COMPONENTROLETYPE # OMX_Core.h: 191
#
# Path: skema/omxil12.py
# def OMX_GetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/omxil12.py
# def OMX_SetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.SetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | err = get_string_from_il_enum(interror, "OMX_Error") |
Using the snippet: <|code_start|># 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, see <http://www.gnu.org/licenses/>.
#from types import *
class tag_OMX_SetComponentRole(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
indexstr = "OMX_IndexParamStandardComponentRole"
alias = element.get('alias')
name = context.cnames[alias]
rolestr = element.get('role')
log_api ("%s '%s' '%s'" \
% (element.tag, name, rolestr))
handle = context.handles[alias]
index = get_il_enum_from_string(indexstr)
param_type = OMX_PARAM_COMPONENTROLETYPE
param_struct = param_type()
<|code_end|>
, determine the next line of code. You have imports:
import skema.tag
from skema.omxil12 import get_il_enum_from_string
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_VERSION
from skema.omxil12 import OMX_PARAM_COMPONENTROLETYPE
from skema.omxil12 import OMX_GetParameter
from skema.omxil12 import OMX_SetParameter
from skema.utils import log_line
from skema.utils import log_api
from skema.utils import log_param
from skema.utils import log_result
from ctypes import c_char_p
from ctypes import sizeof
from ctypes import byref
from ctypes import CDLL
from ctypes import cast
and context (class names, function names, or code) available:
# Path: skema/omxil12.py
# def get_il_enum_from_string(string):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if name == string:
# return val
# raise AttributeError
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_VERSION = ((((OMX_VERSION_STEP << 24) | (OMX_VERSION_REVISION << 16)) | (OMX_VERSION_MINOR << 8)) | OMX_VERSION_MAJOR)
#
# Path: skema/omxil12.py
# OMX_PARAM_COMPONENTROLETYPE = struct_OMX_PARAM_COMPONENTROLETYPE # OMX_Core.h: 191
#
# Path: skema/omxil12.py
# def OMX_GetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/omxil12.py
# def OMX_SetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.SetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | param_struct.nVersion.nVersion = OMX_VERSION |
Predict the next line after this snippet: <|code_start|>#
# 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, see <http://www.gnu.org/licenses/>.
#from types import *
class tag_OMX_SetComponentRole(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
indexstr = "OMX_IndexParamStandardComponentRole"
alias = element.get('alias')
name = context.cnames[alias]
rolestr = element.get('role')
log_api ("%s '%s' '%s'" \
% (element.tag, name, rolestr))
handle = context.handles[alias]
index = get_il_enum_from_string(indexstr)
<|code_end|>
using the current file's imports:
import skema.tag
from skema.omxil12 import get_il_enum_from_string
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_VERSION
from skema.omxil12 import OMX_PARAM_COMPONENTROLETYPE
from skema.omxil12 import OMX_GetParameter
from skema.omxil12 import OMX_SetParameter
from skema.utils import log_line
from skema.utils import log_api
from skema.utils import log_param
from skema.utils import log_result
from ctypes import c_char_p
from ctypes import sizeof
from ctypes import byref
from ctypes import CDLL
from ctypes import cast
and any relevant context from other files:
# Path: skema/omxil12.py
# def get_il_enum_from_string(string):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if name == string:
# return val
# raise AttributeError
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_VERSION = ((((OMX_VERSION_STEP << 24) | (OMX_VERSION_REVISION << 16)) | (OMX_VERSION_MINOR << 8)) | OMX_VERSION_MAJOR)
#
# Path: skema/omxil12.py
# OMX_PARAM_COMPONENTROLETYPE = struct_OMX_PARAM_COMPONENTROLETYPE # OMX_Core.h: 191
#
# Path: skema/omxil12.py
# def OMX_GetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/omxil12.py
# def OMX_SetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.SetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | param_type = OMX_PARAM_COMPONENTROLETYPE |
Using the snippet: <|code_start|># You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#from types import *
class tag_OMX_SetComponentRole(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
indexstr = "OMX_IndexParamStandardComponentRole"
alias = element.get('alias')
name = context.cnames[alias]
rolestr = element.get('role')
log_api ("%s '%s' '%s'" \
% (element.tag, name, rolestr))
handle = context.handles[alias]
index = get_il_enum_from_string(indexstr)
param_type = OMX_PARAM_COMPONENTROLETYPE
param_struct = param_type()
param_struct.nVersion.nVersion = OMX_VERSION
param_struct.nSize = sizeof(param_type)
if (handle != None):
<|code_end|>
, determine the next line of code. You have imports:
import skema.tag
from skema.omxil12 import get_il_enum_from_string
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_VERSION
from skema.omxil12 import OMX_PARAM_COMPONENTROLETYPE
from skema.omxil12 import OMX_GetParameter
from skema.omxil12 import OMX_SetParameter
from skema.utils import log_line
from skema.utils import log_api
from skema.utils import log_param
from skema.utils import log_result
from ctypes import c_char_p
from ctypes import sizeof
from ctypes import byref
from ctypes import CDLL
from ctypes import cast
and context (class names, function names, or code) available:
# Path: skema/omxil12.py
# def get_il_enum_from_string(string):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if name == string:
# return val
# raise AttributeError
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_VERSION = ((((OMX_VERSION_STEP << 24) | (OMX_VERSION_REVISION << 16)) | (OMX_VERSION_MINOR << 8)) | OMX_VERSION_MAJOR)
#
# Path: skema/omxil12.py
# OMX_PARAM_COMPONENTROLETYPE = struct_OMX_PARAM_COMPONENTROLETYPE # OMX_Core.h: 191
#
# Path: skema/omxil12.py
# def OMX_GetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/omxil12.py
# def OMX_SetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.SetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | omxerror = OMX_GetParameter(handle, index, byref(param_struct)) |
Given the following code snippet before the placeholder: <|code_start|> indexstr = "OMX_IndexParamStandardComponentRole"
alias = element.get('alias')
name = context.cnames[alias]
rolestr = element.get('role')
log_api ("%s '%s' '%s'" \
% (element.tag, name, rolestr))
handle = context.handles[alias]
index = get_il_enum_from_string(indexstr)
param_type = OMX_PARAM_COMPONENTROLETYPE
param_struct = param_type()
param_struct.nVersion.nVersion = OMX_VERSION
param_struct.nSize = sizeof(param_type)
if (handle != None):
omxerror = OMX_GetParameter(handle, index, byref(param_struct))
interror = int(omxerror & 0xffffffff)
err = get_string_from_il_enum(interror, "OMX_Error")
for name, _ in param_type._fields_:
for name2, val2 in element.items():
if (name != "cRole"):
if (name2 == name):
setattr(param_struct, name, int(val2))
else:
libc = CDLL('libc.so.6')
libc.strcpy(cast(param_struct.cRole, c_char_p),
rolestr)
<|code_end|>
, predict the next line using imports from the current file:
import skema.tag
from skema.omxil12 import get_il_enum_from_string
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_VERSION
from skema.omxil12 import OMX_PARAM_COMPONENTROLETYPE
from skema.omxil12 import OMX_GetParameter
from skema.omxil12 import OMX_SetParameter
from skema.utils import log_line
from skema.utils import log_api
from skema.utils import log_param
from skema.utils import log_result
from ctypes import c_char_p
from ctypes import sizeof
from ctypes import byref
from ctypes import CDLL
from ctypes import cast
and context including class names, function names, and sometimes code from other files:
# Path: skema/omxil12.py
# def get_il_enum_from_string(string):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if name == string:
# return val
# raise AttributeError
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_VERSION = ((((OMX_VERSION_STEP << 24) | (OMX_VERSION_REVISION << 16)) | (OMX_VERSION_MINOR << 8)) | OMX_VERSION_MAJOR)
#
# Path: skema/omxil12.py
# OMX_PARAM_COMPONENTROLETYPE = struct_OMX_PARAM_COMPONENTROLETYPE # OMX_Core.h: 191
#
# Path: skema/omxil12.py
# def OMX_GetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/omxil12.py
# def OMX_SetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.SetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | omxerror = OMX_SetParameter(handle, index, byref(param_struct)) |
Given the code snippet: <|code_start|>
handle = context.handles[alias]
index = get_il_enum_from_string(indexstr)
param_type = OMX_PARAM_COMPONENTROLETYPE
param_struct = param_type()
param_struct.nVersion.nVersion = OMX_VERSION
param_struct.nSize = sizeof(param_type)
if (handle != None):
omxerror = OMX_GetParameter(handle, index, byref(param_struct))
interror = int(omxerror & 0xffffffff)
err = get_string_from_il_enum(interror, "OMX_Error")
for name, _ in param_type._fields_:
for name2, val2 in element.items():
if (name != "cRole"):
if (name2 == name):
setattr(param_struct, name, int(val2))
else:
libc = CDLL('libc.so.6')
libc.strcpy(cast(param_struct.cRole, c_char_p),
rolestr)
omxerror = OMX_SetParameter(handle, index, byref(param_struct))
interror = int(omxerror & 0xffffffff)
err = get_string_from_il_enum(interror, "OMX_Error")
rolefield = c_char_p()
rolefield = cast(param_struct.cRole, c_char_p)
<|code_end|>
, generate the next line using the imports in this file:
import skema.tag
from skema.omxil12 import get_il_enum_from_string
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_VERSION
from skema.omxil12 import OMX_PARAM_COMPONENTROLETYPE
from skema.omxil12 import OMX_GetParameter
from skema.omxil12 import OMX_SetParameter
from skema.utils import log_line
from skema.utils import log_api
from skema.utils import log_param
from skema.utils import log_result
from ctypes import c_char_p
from ctypes import sizeof
from ctypes import byref
from ctypes import CDLL
from ctypes import cast
and context (functions, classes, or occasionally code) from other files:
# Path: skema/omxil12.py
# def get_il_enum_from_string(string):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if name == string:
# return val
# raise AttributeError
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_VERSION = ((((OMX_VERSION_STEP << 24) | (OMX_VERSION_REVISION << 16)) | (OMX_VERSION_MINOR << 8)) | OMX_VERSION_MAJOR)
#
# Path: skema/omxil12.py
# OMX_PARAM_COMPONENTROLETYPE = struct_OMX_PARAM_COMPONENTROLETYPE # OMX_Core.h: 191
#
# Path: skema/omxil12.py
# def OMX_GetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/omxil12.py
# def OMX_SetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.SetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | log_line () |
Using the 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 3 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, see <http://www.gnu.org/licenses/>.
#from types import *
class tag_OMX_SetComponentRole(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
indexstr = "OMX_IndexParamStandardComponentRole"
alias = element.get('alias')
name = context.cnames[alias]
rolestr = element.get('role')
<|code_end|>
, determine the next line of code. You have imports:
import skema.tag
from skema.omxil12 import get_il_enum_from_string
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_VERSION
from skema.omxil12 import OMX_PARAM_COMPONENTROLETYPE
from skema.omxil12 import OMX_GetParameter
from skema.omxil12 import OMX_SetParameter
from skema.utils import log_line
from skema.utils import log_api
from skema.utils import log_param
from skema.utils import log_result
from ctypes import c_char_p
from ctypes import sizeof
from ctypes import byref
from ctypes import CDLL
from ctypes import cast
and context (class names, function names, or code) available:
# Path: skema/omxil12.py
# def get_il_enum_from_string(string):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if name == string:
# return val
# raise AttributeError
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_VERSION = ((((OMX_VERSION_STEP << 24) | (OMX_VERSION_REVISION << 16)) | (OMX_VERSION_MINOR << 8)) | OMX_VERSION_MAJOR)
#
# Path: skema/omxil12.py
# OMX_PARAM_COMPONENTROLETYPE = struct_OMX_PARAM_COMPONENTROLETYPE # OMX_Core.h: 191
#
# Path: skema/omxil12.py
# def OMX_GetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/omxil12.py
# def OMX_SetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.SetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | log_api ("%s '%s' '%s'" \ |
Given the code snippet: <|code_start|>
if (handle != None):
omxerror = OMX_GetParameter(handle, index, byref(param_struct))
interror = int(omxerror & 0xffffffff)
err = get_string_from_il_enum(interror, "OMX_Error")
for name, _ in param_type._fields_:
for name2, val2 in element.items():
if (name != "cRole"):
if (name2 == name):
setattr(param_struct, name, int(val2))
else:
libc = CDLL('libc.so.6')
libc.strcpy(cast(param_struct.cRole, c_char_p),
rolestr)
omxerror = OMX_SetParameter(handle, index, byref(param_struct))
interror = int(omxerror & 0xffffffff)
err = get_string_from_il_enum(interror, "OMX_Error")
rolefield = c_char_p()
rolefield = cast(param_struct.cRole, c_char_p)
log_line ()
log_line ("%s" % param_struct.__class__.__name__, 1)
for name, _ in param_type._fields_:
if (name == "nVersion"):
log_line ("%s -> '%08x'" \
% (name, param_struct.nVersion.nVersion), 1)
elif (name == "cRole"):
<|code_end|>
, generate the next line using the imports in this file:
import skema.tag
from skema.omxil12 import get_il_enum_from_string
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_VERSION
from skema.omxil12 import OMX_PARAM_COMPONENTROLETYPE
from skema.omxil12 import OMX_GetParameter
from skema.omxil12 import OMX_SetParameter
from skema.utils import log_line
from skema.utils import log_api
from skema.utils import log_param
from skema.utils import log_result
from ctypes import c_char_p
from ctypes import sizeof
from ctypes import byref
from ctypes import CDLL
from ctypes import cast
and context (functions, classes, or occasionally code) from other files:
# Path: skema/omxil12.py
# def get_il_enum_from_string(string):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if name == string:
# return val
# raise AttributeError
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_VERSION = ((((OMX_VERSION_STEP << 24) | (OMX_VERSION_REVISION << 16)) | (OMX_VERSION_MINOR << 8)) | OMX_VERSION_MAJOR)
#
# Path: skema/omxil12.py
# OMX_PARAM_COMPONENTROLETYPE = struct_OMX_PARAM_COMPONENTROLETYPE # OMX_Core.h: 191
#
# Path: skema/omxil12.py
# def OMX_GetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/omxil12.py
# def OMX_SetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.SetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | log_param (name, rolefield.value, 1) |
Next line prediction: <|code_start|> err = get_string_from_il_enum(interror, "OMX_Error")
for name, _ in param_type._fields_:
for name2, val2 in element.items():
if (name != "cRole"):
if (name2 == name):
setattr(param_struct, name, int(val2))
else:
libc = CDLL('libc.so.6')
libc.strcpy(cast(param_struct.cRole, c_char_p),
rolestr)
omxerror = OMX_SetParameter(handle, index, byref(param_struct))
interror = int(omxerror & 0xffffffff)
err = get_string_from_il_enum(interror, "OMX_Error")
rolefield = c_char_p()
rolefield = cast(param_struct.cRole, c_char_p)
log_line ()
log_line ("%s" % param_struct.__class__.__name__, 1)
for name, _ in param_type._fields_:
if (name == "nVersion"):
log_line ("%s -> '%08x'" \
% (name, param_struct.nVersion.nVersion), 1)
elif (name == "cRole"):
log_param (name, rolefield.value, 1)
else:
log_param (name, str(getattr(param_struct, name)), 1)
<|code_end|>
. Use current file imports:
(import skema.tag
from skema.omxil12 import get_il_enum_from_string
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_VERSION
from skema.omxil12 import OMX_PARAM_COMPONENTROLETYPE
from skema.omxil12 import OMX_GetParameter
from skema.omxil12 import OMX_SetParameter
from skema.utils import log_line
from skema.utils import log_api
from skema.utils import log_param
from skema.utils import log_result
from ctypes import c_char_p
from ctypes import sizeof
from ctypes import byref
from ctypes import CDLL
from ctypes import cast)
and context including class names, function names, or small code snippets from other files:
# Path: skema/omxil12.py
# def get_il_enum_from_string(string):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if name == string:
# return val
# raise AttributeError
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_VERSION = ((((OMX_VERSION_STEP << 24) | (OMX_VERSION_REVISION << 16)) | (OMX_VERSION_MINOR << 8)) | OMX_VERSION_MAJOR)
#
# Path: skema/omxil12.py
# OMX_PARAM_COMPONENTROLETYPE = struct_OMX_PARAM_COMPONENTROLETYPE # OMX_Core.h: 191
#
# Path: skema/omxil12.py
# def OMX_GetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/omxil12.py
# def OMX_SetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.SetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | log_result(element.tag, err) |
Predict the next line after this snippet: <|code_start|># Copyright (C) 2011-2017 Aratelia Limited - Juan A. Rubio
#
# 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 3 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, see <http://www.gnu.org/licenses/>.
class tag_OMX_GetComponentVersion(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
alias = element.get('alias')
name = context.cnames[alias]
log_api ("%s '%s'" % (element.tag, name))
handle = context.handles[alias]
cname = (c_ubyte * OMX_MAX_STRINGNAME_SIZE)()
<|code_end|>
using the current file's imports:
import skema.tag
from skema.omxil12 import OMX_STRING
from skema.omxil12 import OMX_VERSIONTYPE
from skema.omxil12 import OMX_UUIDTYPE
from skema.omxil12 import struct_anon_1
from skema.omxil12 import OMX_GetComponentVersion
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_MAX_STRINGNAME_SIZE
from skema.utils import log_api
from skema.utils import log_line
from skema.utils import log_param
from skema.utils import log_result
from ctypes import byref
from ctypes import create_string_buffer
from ctypes import c_ubyte
from ctypes import c_char
from ctypes import c_char_p
from ctypes import POINTER
from ctypes import cast
and any relevant context from other files:
# Path: skema/omxil12.py
# OMX_STRING = String # OMX_Types.h: 124
#
# Path: skema/omxil12.py
# OMX_VERSIONTYPE = union_OMX_VERSIONTYPE # OMX_Types.h: 236
#
# Path: skema/omxil12.py
# OMX_UUIDTYPE = c_ubyte * 128 # OMX_Types.h: 126
#
# Path: skema/omxil12.py
# class struct_anon_1(Structure):
# pass
#
# Path: skema/omxil12.py
# def OMX_GetComponentVersion(hComponent, pComponentName, pComponentVersion, pSpecVersion, pComponentUUID):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetComponentVersion) (hComponent, pComponentName, pComponentVersion, pSpecVersion, pComponentUUID))
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_MAX_STRINGNAME_SIZE = 128
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | cversion = OMX_VERSIONTYPE() |
Based on the 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 3 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, see <http://www.gnu.org/licenses/>.
class tag_OMX_GetComponentVersion(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
alias = element.get('alias')
name = context.cnames[alias]
log_api ("%s '%s'" % (element.tag, name))
handle = context.handles[alias]
cname = (c_ubyte * OMX_MAX_STRINGNAME_SIZE)()
cversion = OMX_VERSIONTYPE()
specversion = OMX_VERSIONTYPE()
<|code_end|>
, predict the immediate next line with the help of imports:
import skema.tag
from skema.omxil12 import OMX_STRING
from skema.omxil12 import OMX_VERSIONTYPE
from skema.omxil12 import OMX_UUIDTYPE
from skema.omxil12 import struct_anon_1
from skema.omxil12 import OMX_GetComponentVersion
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_MAX_STRINGNAME_SIZE
from skema.utils import log_api
from skema.utils import log_line
from skema.utils import log_param
from skema.utils import log_result
from ctypes import byref
from ctypes import create_string_buffer
from ctypes import c_ubyte
from ctypes import c_char
from ctypes import c_char_p
from ctypes import POINTER
from ctypes import cast
and context (classes, functions, sometimes code) from other files:
# Path: skema/omxil12.py
# OMX_STRING = String # OMX_Types.h: 124
#
# Path: skema/omxil12.py
# OMX_VERSIONTYPE = union_OMX_VERSIONTYPE # OMX_Types.h: 236
#
# Path: skema/omxil12.py
# OMX_UUIDTYPE = c_ubyte * 128 # OMX_Types.h: 126
#
# Path: skema/omxil12.py
# class struct_anon_1(Structure):
# pass
#
# Path: skema/omxil12.py
# def OMX_GetComponentVersion(hComponent, pComponentName, pComponentVersion, pSpecVersion, pComponentUUID):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetComponentVersion) (hComponent, pComponentName, pComponentVersion, pSpecVersion, pComponentUUID))
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_MAX_STRINGNAME_SIZE = 128
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | cuuid = OMX_UUIDTYPE() |
Based on the snippet: <|code_start|>
class tag_OMX_GetComponentVersion(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
alias = element.get('alias')
name = context.cnames[alias]
log_api ("%s '%s'" % (element.tag, name))
handle = context.handles[alias]
cname = (c_ubyte * OMX_MAX_STRINGNAME_SIZE)()
cversion = OMX_VERSIONTYPE()
specversion = OMX_VERSIONTYPE()
cuuid = OMX_UUIDTYPE()
if (handle != None):
omxerror = OMX_GetComponentVersion(handle, cast(cname, POINTER(c_char)),
byref(cversion),
byref(specversion),
byref(cuuid))
interror = int(omxerror & 0xffffffff)
err = get_string_from_il_enum(interror, "OMX_Error")
log_line ()
msg = "Component Name : " + cast(cname, c_char_p).value
log_line (msg, 1)
log_line ()
log_line ("Component Version", 1)
<|code_end|>
, predict the immediate next line with the help of imports:
import skema.tag
from skema.omxil12 import OMX_STRING
from skema.omxil12 import OMX_VERSIONTYPE
from skema.omxil12 import OMX_UUIDTYPE
from skema.omxil12 import struct_anon_1
from skema.omxil12 import OMX_GetComponentVersion
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_MAX_STRINGNAME_SIZE
from skema.utils import log_api
from skema.utils import log_line
from skema.utils import log_param
from skema.utils import log_result
from ctypes import byref
from ctypes import create_string_buffer
from ctypes import c_ubyte
from ctypes import c_char
from ctypes import c_char_p
from ctypes import POINTER
from ctypes import cast
and context (classes, functions, sometimes code) from other files:
# Path: skema/omxil12.py
# OMX_STRING = String # OMX_Types.h: 124
#
# Path: skema/omxil12.py
# OMX_VERSIONTYPE = union_OMX_VERSIONTYPE # OMX_Types.h: 236
#
# Path: skema/omxil12.py
# OMX_UUIDTYPE = c_ubyte * 128 # OMX_Types.h: 126
#
# Path: skema/omxil12.py
# class struct_anon_1(Structure):
# pass
#
# Path: skema/omxil12.py
# def OMX_GetComponentVersion(hComponent, pComponentName, pComponentVersion, pSpecVersion, pComponentUUID):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetComponentVersion) (hComponent, pComponentName, pComponentVersion, pSpecVersion, pComponentUUID))
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_MAX_STRINGNAME_SIZE = 128
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | for name, _ in struct_anon_1._fields_: |
Given the code snippet: <|code_start|># the Free Software Foundation, either version 3 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, see <http://www.gnu.org/licenses/>.
class tag_OMX_GetComponentVersion(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
alias = element.get('alias')
name = context.cnames[alias]
log_api ("%s '%s'" % (element.tag, name))
handle = context.handles[alias]
cname = (c_ubyte * OMX_MAX_STRINGNAME_SIZE)()
cversion = OMX_VERSIONTYPE()
specversion = OMX_VERSIONTYPE()
cuuid = OMX_UUIDTYPE()
if (handle != None):
<|code_end|>
, generate the next line using the imports in this file:
import skema.tag
from skema.omxil12 import OMX_STRING
from skema.omxil12 import OMX_VERSIONTYPE
from skema.omxil12 import OMX_UUIDTYPE
from skema.omxil12 import struct_anon_1
from skema.omxil12 import OMX_GetComponentVersion
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_MAX_STRINGNAME_SIZE
from skema.utils import log_api
from skema.utils import log_line
from skema.utils import log_param
from skema.utils import log_result
from ctypes import byref
from ctypes import create_string_buffer
from ctypes import c_ubyte
from ctypes import c_char
from ctypes import c_char_p
from ctypes import POINTER
from ctypes import cast
and context (functions, classes, or occasionally code) from other files:
# Path: skema/omxil12.py
# OMX_STRING = String # OMX_Types.h: 124
#
# Path: skema/omxil12.py
# OMX_VERSIONTYPE = union_OMX_VERSIONTYPE # OMX_Types.h: 236
#
# Path: skema/omxil12.py
# OMX_UUIDTYPE = c_ubyte * 128 # OMX_Types.h: 126
#
# Path: skema/omxil12.py
# class struct_anon_1(Structure):
# pass
#
# Path: skema/omxil12.py
# def OMX_GetComponentVersion(hComponent, pComponentName, pComponentVersion, pSpecVersion, pComponentUUID):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetComponentVersion) (hComponent, pComponentName, pComponentVersion, pSpecVersion, pComponentUUID))
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_MAX_STRINGNAME_SIZE = 128
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | omxerror = OMX_GetComponentVersion(handle, cast(cname, POINTER(c_char)), |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.