Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line after this snippet: <|code_start|>
objects = BakeryUserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['password']
class Meta:
verbose_name = _('User')
verbose_name_plural = _('Users')
def __str__(self):
return self.username
def get_absolute_url(self):
return reverse_lazy('auth:profile', kwargs={'username': self.username})
def get_full_name(self):
return self.name
def get_short_name(self):
"Returns the short name for the user."
return self.name
def get_display_name(self):
return self.name or self.username
def get_gravatar(self):
return get_gravatar(self.email)
def vote_for_cookie(self, cookie):
<|code_end|>
using the current file's imports:
from django.core.urlresolvers import reverse_lazy
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from django.contrib.auth.models import AbstractBaseUser
from bakery.auth.managers import BakeryUserManager
from bakery.socialize.models import do_vote, CANDIES
from bakery.utils.gravatar import get_gravatar
and any relevant context from other files:
# Path: bakery/auth/managers.py
# class BakeryUserManager(UserManager):
# pass
#
# Path: bakery/socialize/models.py
# def do_vote(user, cookie):
# assert user and cookie
# if not Vote.objects.has_voted(user, cookie):
# with transaction.commit_on_success():
# vote = Vote.objects.create(cookie=cookie, user=user)
# candy_type = random.choice(CANDIES)
# Candy.objects.create(candy_type=candy_type[0], user=user, vote=vote)
#
# CANDIES = (
# ('rice-cracker', _('Rice Cracker'), '🍘'),
# ('candy', _('Candy'), '🍬'),
# ('lollipop', _('Lollipop'), '🍭'),
# ('chocolate-bar', _('Chocolate Bar'), '🍫'),
# ('doughnut', _('Doughnut'), '🍩'),
# ('cookie', _('Cookie'), '🍪'),
# )
#
# Path: bakery/utils/gravatar.py
# def get_gravatar(email, secure=False, rating='g', size=80, default='mm'):
# """Generate a link to the users' Gravatar."""
# assert rating.lower() in RATINGS
# assert MIN_SIZE <= size <= MAX_SIZE
#
# url = SECURE_BASE_URL if secure else BASE_URL
#
# options = {'s': size, 'r': rating, 'd': default}
# url += email_hash(email) + '?' + urlencode(options)
# return url
. Output only the next line. | do_vote(self, cookie) |
Predict the next line for this snippet: <|code_start|> verbose_name = _('User')
verbose_name_plural = _('Users')
def __str__(self):
return self.username
def get_absolute_url(self):
return reverse_lazy('auth:profile', kwargs={'username': self.username})
def get_full_name(self):
return self.name
def get_short_name(self):
"Returns the short name for the user."
return self.name
def get_display_name(self):
return self.name or self.username
def get_gravatar(self):
return get_gravatar(self.email)
def vote_for_cookie(self, cookie):
do_vote(self, cookie)
@property
def candies_list(self):
candies_list = getattr(self, '_candies_list', [])
if not candies_list:
candies = self.candies.order_by('candy_type')
<|code_end|>
with the help of current file imports:
from django.core.urlresolvers import reverse_lazy
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from django.contrib.auth.models import AbstractBaseUser
from bakery.auth.managers import BakeryUserManager
from bakery.socialize.models import do_vote, CANDIES
from bakery.utils.gravatar import get_gravatar
and context from other files:
# Path: bakery/auth/managers.py
# class BakeryUserManager(UserManager):
# pass
#
# Path: bakery/socialize/models.py
# def do_vote(user, cookie):
# assert user and cookie
# if not Vote.objects.has_voted(user, cookie):
# with transaction.commit_on_success():
# vote = Vote.objects.create(cookie=cookie, user=user)
# candy_type = random.choice(CANDIES)
# Candy.objects.create(candy_type=candy_type[0], user=user, vote=vote)
#
# CANDIES = (
# ('rice-cracker', _('Rice Cracker'), '🍘'),
# ('candy', _('Candy'), '🍬'),
# ('lollipop', _('Lollipop'), '🍭'),
# ('chocolate-bar', _('Chocolate Bar'), '🍫'),
# ('doughnut', _('Doughnut'), '🍩'),
# ('cookie', _('Cookie'), '🍪'),
# )
#
# Path: bakery/utils/gravatar.py
# def get_gravatar(email, secure=False, rating='g', size=80, default='mm'):
# """Generate a link to the users' Gravatar."""
# assert rating.lower() in RATINGS
# assert MIN_SIZE <= size <= MAX_SIZE
#
# url = SECURE_BASE_URL if secure else BASE_URL
#
# options = {'s': size, 'r': rating, 'd': default}
# url += email_hash(email) + '?' + urlencode(options)
# return url
, which may contain function names, class names, or code. Output only the next line. | for candy in CANDIES: |
Here is a snippet: <|code_start|> is_active = models.BooleanField(_('Active'), default=True)
is_organization = models.BooleanField(_('Organization'))
profile_url = models.URLField(_('Profile'), blank=True, null=True)
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
objects = BakeryUserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['password']
class Meta:
verbose_name = _('User')
verbose_name_plural = _('Users')
def __str__(self):
return self.username
def get_absolute_url(self):
return reverse_lazy('auth:profile', kwargs={'username': self.username})
def get_full_name(self):
return self.name
def get_short_name(self):
"Returns the short name for the user."
return self.name
def get_display_name(self):
return self.name or self.username
<|code_end|>
. Write the next line using the current file imports:
from django.core.urlresolvers import reverse_lazy
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from django.contrib.auth.models import AbstractBaseUser
from bakery.auth.managers import BakeryUserManager
from bakery.socialize.models import do_vote, CANDIES
from bakery.utils.gravatar import get_gravatar
and context from other files:
# Path: bakery/auth/managers.py
# class BakeryUserManager(UserManager):
# pass
#
# Path: bakery/socialize/models.py
# def do_vote(user, cookie):
# assert user and cookie
# if not Vote.objects.has_voted(user, cookie):
# with transaction.commit_on_success():
# vote = Vote.objects.create(cookie=cookie, user=user)
# candy_type = random.choice(CANDIES)
# Candy.objects.create(candy_type=candy_type[0], user=user, vote=vote)
#
# CANDIES = (
# ('rice-cracker', _('Rice Cracker'), '🍘'),
# ('candy', _('Candy'), '🍬'),
# ('lollipop', _('Lollipop'), '🍭'),
# ('chocolate-bar', _('Chocolate Bar'), '🍫'),
# ('doughnut', _('Doughnut'), '🍩'),
# ('cookie', _('Cookie'), '🍪'),
# )
#
# Path: bakery/utils/gravatar.py
# def get_gravatar(email, secure=False, rating='g', size=80, default='mm'):
# """Generate a link to the users' Gravatar."""
# assert rating.lower() in RATINGS
# assert MIN_SIZE <= size <= MAX_SIZE
#
# url = SECURE_BASE_URL if secure else BASE_URL
#
# options = {'s': size, 'r': rating, 'd': default}
# url += email_hash(email) + '?' + urlencode(options)
# return url
, which may include functions, classes, or code. Output only the next line. | def get_gravatar(self): |
Based on the snippet: <|code_start|>
try:
except ValueError: # Celery doesn't work under Python 3.3 - when it does it'll test again
Celery = None
def prefix(name):
return '%s.%s' % (__name__, name)
<|code_end|>
, predict the immediate next line with the help of imports:
import mock
from unittest import TestCase
from .utils import skipIf
from emit.router.celery import CeleryRouter
from celery import Celery, Task
and context (classes, functions, sometimes code) from other files:
# Path: tests/utils.py
# def skipIf(condition, message):
# try:
# from unittest import skipIf
# return skipIf(condition, message)
# except ImportError: # skipIf/skip not implemented
# if condition:
# return lambda x: None
# else:
# return lambda x: x
#
# Path: emit/router/celery.py
# class CeleryRouter(Router):
# 'Router specifically for Celery routing'
# def __init__(self, celery_task, *args, **kwargs):
# '''\
# Specifically route when celery is needed
#
# :param celery_task: celery task to apply to all nodes (can be
# overridden in :py:meth:`Router.node`.)
# :type celery_task: A celery task decorator, in any form
# '''
# super(CeleryRouter, self).__init__(*args, **kwargs)
# self.celery_task = celery_task
# self.logger.debug('Initialized Celery Router')
#
# def dispatch(self, origin, destination, message):
# '''\
# enqueue a message with Celery
#
# :param destination: destination to dispatch to
# :type destination: :py:class:`str`
# :param message: message to dispatch
# :type message: :py:class:`emit.message.Message` or subclass
# '''
# func = self.functions[destination]
# self.logger.debug('delaying %r', func)
# return func.delay(_origin=origin, **message)
#
# def wrap_node(self, node, options):
# '''\
# celery registers tasks by decorating them, and so do we, so the user
# can pass a celery task and we'll wrap our code with theirs in a nice
# package celery can execute.
# '''
# if 'celery_task' in options:
# return options['celery_task'](node)
#
# return self.celery_task(node)
. Output only the next line. | @skipIf(Celery is None, 'Celery did not import correctly') |
Given the code snippet: <|code_start|>
try:
except ValueError: # Celery doesn't work under Python 3.3 - when it does it'll test again
Celery = None
def prefix(name):
return '%s.%s' % (__name__, name)
@skipIf(Celery is None, 'Celery did not import correctly')
class CeleryRouterTests(TestCase):
'tests for using celery to route nodes'
def setUp(self):
self.celery = self.get_test_celery()
<|code_end|>
, generate the next line using the imports in this file:
import mock
from unittest import TestCase
from .utils import skipIf
from emit.router.celery import CeleryRouter
from celery import Celery, Task
and context (functions, classes, or occasionally code) from other files:
# Path: tests/utils.py
# def skipIf(condition, message):
# try:
# from unittest import skipIf
# return skipIf(condition, message)
# except ImportError: # skipIf/skip not implemented
# if condition:
# return lambda x: None
# else:
# return lambda x: x
#
# Path: emit/router/celery.py
# class CeleryRouter(Router):
# 'Router specifically for Celery routing'
# def __init__(self, celery_task, *args, **kwargs):
# '''\
# Specifically route when celery is needed
#
# :param celery_task: celery task to apply to all nodes (can be
# overridden in :py:meth:`Router.node`.)
# :type celery_task: A celery task decorator, in any form
# '''
# super(CeleryRouter, self).__init__(*args, **kwargs)
# self.celery_task = celery_task
# self.logger.debug('Initialized Celery Router')
#
# def dispatch(self, origin, destination, message):
# '''\
# enqueue a message with Celery
#
# :param destination: destination to dispatch to
# :type destination: :py:class:`str`
# :param message: message to dispatch
# :type message: :py:class:`emit.message.Message` or subclass
# '''
# func = self.functions[destination]
# self.logger.debug('delaying %r', func)
# return func.delay(_origin=origin, **message)
#
# def wrap_node(self, node, options):
# '''\
# celery registers tasks by decorating them, and so do we, so the user
# can pass a celery task and we'll wrap our code with theirs in a nice
# package celery can execute.
# '''
# if 'celery_task' in options:
# return options['celery_task'](node)
#
# return self.celery_task(node)
. Output only the next line. | self.router = CeleryRouter(self.celery.task) |
Predict the next line for this snippet: <|code_start|>'router for emit'
class Router(object):
'A router object. Holds routes and references to functions for dispatch'
def __init__(self, message_class=None, node_modules=None, node_package=None):
'''\
Create a new router object. All parameters are optional.
:param message_class: wrapper class for messages passed to nodes
:type message_class: :py:class:`emit.message.Message` or subclass
:param node_modules: a list of modules that contain nodes
:type node_modules: a list of :py:class:`str`, or ``None``.
:param node_package: if any node_modules are relative, the path to base
off of.
:type node_package: :py:class:`str`, or ``None``.
:exceptions: None
:returns: None
'''
self.routes = {}
self.names = set()
self.regexes = {}
self.ignore_regexes = {}
self.fields = {}
self.functions = {}
<|code_end|>
with the help of current file imports:
from functools import wraps
from types import GeneratorType
from emit.messages import Message, NoResult
import importlib
import logging
import re
and context from other files:
# Path: emit/messages.py
# class Message(object):
# 'Convenient wrapper around a dictionary to provide attribute access'
# def __init__(self, *args, **kwargs):
# self.bundle = dict(*args, **kwargs)
#
# def __getattr__(self, attr):
# try:
# return self.bundle[attr]
# except KeyError:
# raise AttributeError(
# '"%s" is not included in this message' % attr
# )
#
# def __dir__(self):
# 'get directory of attributes. include bundle.'
# return sorted(list(['bundle'] + list(self.bundle.keys())))
#
# def __repr__(self):
# 'representation of this message'
# return 'Message(%s)' % (
# ', '.join('%s=%s' % pair for pair in self.bundle.items())
# )
#
# def __eq__(self, other):
# 'test equality of two messages'
# return self.bundle == other.bundle
#
# def as_dict(self):
# '''\
# representation of this message as a dictionary
#
# :returns: dict
# '''
# return self.bundle
#
# def as_json(self):
# '''
# representation of this message as a json object
#
# :returns: str
# '''
# return json.dumps(self.as_dict())
#
# class NoResult(object):
# 'single value to return from a node to stop further processing'
# pass
, which may contain function names, class names, or code. Output only the next line. | self.message_class = message_class or Message |
Using the snippet: <|code_start|> .. note::
This function does not optionally accept a single argument
(dictionary) as other points in this API do - it must be expanded to
keyword arguments in this case.
'''
self.logger.info('Calling entry point with %r', kwargs)
self.route('__entry_point', kwargs)
def wrap_as_node(self, func):
'wrap a function as a node'
name = self.get_name(func)
@wraps(func)
def wrapped(*args, **kwargs):
'wrapped version of func'
message = self.get_message_from_call(*args, **kwargs)
self.logger.info('calling "%s" with %r', name, message)
result = func(message)
# functions can return multiple values ("emit" multiple times)
# by yielding instead of returning. Handle this case by making
# a list of the results and processing them all after the
# generator successfully exits. If we were to process them as
# they came out of the generator, we might get a partially
# processed input sent down the graph. This may be possible in
# the future via a flag.
if isinstance(result, GeneratorType):
results = [
self.wrap_result(name, item)
for item in result
<|code_end|>
, determine the next line of code. You have imports:
from functools import wraps
from types import GeneratorType
from emit.messages import Message, NoResult
import importlib
import logging
import re
and context (class names, function names, or code) available:
# Path: emit/messages.py
# class Message(object):
# 'Convenient wrapper around a dictionary to provide attribute access'
# def __init__(self, *args, **kwargs):
# self.bundle = dict(*args, **kwargs)
#
# def __getattr__(self, attr):
# try:
# return self.bundle[attr]
# except KeyError:
# raise AttributeError(
# '"%s" is not included in this message' % attr
# )
#
# def __dir__(self):
# 'get directory of attributes. include bundle.'
# return sorted(list(['bundle'] + list(self.bundle.keys())))
#
# def __repr__(self):
# 'representation of this message'
# return 'Message(%s)' % (
# ', '.join('%s=%s' % pair for pair in self.bundle.items())
# )
#
# def __eq__(self, other):
# 'test equality of two messages'
# return self.bundle == other.bundle
#
# def as_dict(self):
# '''\
# representation of this message as a dictionary
#
# :returns: dict
# '''
# return self.bundle
#
# def as_json(self):
# '''
# representation of this message as a json object
#
# :returns: str
# '''
# return json.dumps(self.as_dict())
#
# class NoResult(object):
# 'single value to return from a node to stop further processing'
# pass
. Output only the next line. | if item is not NoResult |
Using the snippet: <|code_start|>
try:
except ImportError:
RQRouter = None
<|code_end|>
, determine the next line of code. You have imports:
import mock
import rq
from redis import Redis
from unittest import TestCase
from .utils import skipIf
from emit.router.rq import RQRouter
and context (class names, function names, or code) available:
# Path: tests/utils.py
# def skipIf(condition, message):
# try:
# from unittest import skipIf
# return skipIf(condition, message)
# except ImportError: # skipIf/skip not implemented
# if condition:
# return lambda x: None
# else:
# return lambda x: x
. Output only the next line. | @skipIf(RQRouter is None, 'RQ did not import correctly') |
Based on the snippet: <|code_start|>'tests for message'
class MessageTests(TestCase):
'tests for Message'
def test_dot_access(self):
'accessing attributes'
<|code_end|>
, predict the immediate next line with the help of imports:
import json
from unittest import TestCase
from emit.messages import Message
and context (classes, functions, sometimes code) from other files:
# Path: emit/messages.py
# class Message(object):
# 'Convenient wrapper around a dictionary to provide attribute access'
# def __init__(self, *args, **kwargs):
# self.bundle = dict(*args, **kwargs)
#
# def __getattr__(self, attr):
# try:
# return self.bundle[attr]
# except KeyError:
# raise AttributeError(
# '"%s" is not included in this message' % attr
# )
#
# def __dir__(self):
# 'get directory of attributes. include bundle.'
# return sorted(list(['bundle'] + list(self.bundle.keys())))
#
# def __repr__(self):
# 'representation of this message'
# return 'Message(%s)' % (
# ', '.join('%s=%s' % pair for pair in self.bundle.items())
# )
#
# def __eq__(self, other):
# 'test equality of two messages'
# return self.bundle == other.bundle
#
# def as_dict(self):
# '''\
# representation of this message as a dictionary
#
# :returns: dict
# '''
# return self.bundle
#
# def as_json(self):
# '''
# representation of this message as a json object
#
# :returns: str
# '''
# return json.dumps(self.as_dict())
. Output only the next line. | x = Message(x=1) |
Predict the next line after this snippet: <|code_start|>'simple celery app'
app = Celery(
'celery_emit_example',
broker='redis://'
)
app.conf.update(
CELERY_IMPORTS=('tasks',)
)
<|code_end|>
using the current file's imports:
from celery import Celery
from emit.router.celery import CeleryRouter
import logging
and any relevant context from other files:
# Path: emit/router/celery.py
# class CeleryRouter(Router):
# 'Router specifically for Celery routing'
# def __init__(self, celery_task, *args, **kwargs):
# '''\
# Specifically route when celery is needed
#
# :param celery_task: celery task to apply to all nodes (can be
# overridden in :py:meth:`Router.node`.)
# :type celery_task: A celery task decorator, in any form
# '''
# super(CeleryRouter, self).__init__(*args, **kwargs)
# self.celery_task = celery_task
# self.logger.debug('Initialized Celery Router')
#
# def dispatch(self, origin, destination, message):
# '''\
# enqueue a message with Celery
#
# :param destination: destination to dispatch to
# :type destination: :py:class:`str`
# :param message: message to dispatch
# :type message: :py:class:`emit.message.Message` or subclass
# '''
# func = self.functions[destination]
# self.logger.debug('delaying %r', func)
# return func.delay(_origin=origin, **message)
#
# def wrap_node(self, node, options):
# '''\
# celery registers tasks by decorating them, and so do we, so the user
# can pass a celery task and we'll wrap our code with theirs in a nice
# package celery can execute.
# '''
# if 'celery_task' in options:
# return options['celery_task'](node)
#
# return self.celery_task(node)
. Output only the next line. | router = CeleryRouter(celery_task=app.task, node_modules=['tasks']) |
Next line prediction: <|code_start|>'simple celery app'
app = Celery(
'celery_emit_example',
broker='redis://'
)
app.conf.update(
CELERY_IMPORTS=('tasks',)
)
<|code_end|>
. Use current file imports:
(from celery import Celery
from emit.router.celery import CeleryRouter)
and context including class names, function names, or small code snippets from other files:
# Path: emit/router/celery.py
# class CeleryRouter(Router):
# 'Router specifically for Celery routing'
# def __init__(self, celery_task, *args, **kwargs):
# '''\
# Specifically route when celery is needed
#
# :param celery_task: celery task to apply to all nodes (can be
# overridden in :py:meth:`Router.node`.)
# :type celery_task: A celery task decorator, in any form
# '''
# super(CeleryRouter, self).__init__(*args, **kwargs)
# self.celery_task = celery_task
# self.logger.debug('Initialized Celery Router')
#
# def dispatch(self, origin, destination, message):
# '''\
# enqueue a message with Celery
#
# :param destination: destination to dispatch to
# :type destination: :py:class:`str`
# :param message: message to dispatch
# :type message: :py:class:`emit.message.Message` or subclass
# '''
# func = self.functions[destination]
# self.logger.debug('delaying %r', func)
# return func.delay(_origin=origin, **message)
#
# def wrap_node(self, node, options):
# '''\
# celery registers tasks by decorating them, and so do we, so the user
# can pass a celery task and we'll wrap our code with theirs in a nice
# package celery can execute.
# '''
# if 'celery_task' in options:
# return options['celery_task'](node)
#
# return self.celery_task(node)
. Output only the next line. | router = CeleryRouter(celery_task=app.task, node_modules=['tasks']) |
Given snippet: <|code_start|>
# This code is mostly duplicated from the `gitlint.shell` module. We consciously duplicate this code as to not depend
# on gitlint internals for our integration testing framework.
if USE_SH_LIB:
gitlint = gitlint.bake(_unify_ttys=True, _tty_in=True) # pylint: disable=invalid-name
# import exceptions separately, this makes it a little easier to mock them out in the unit tests
else:
class CommandNotFound(Exception):
""" Exception indicating a command was not found during execution """
pass
class RunningCommand:
pass
class ShResult(RunningCommand):
""" Result wrapper class. We use this to more easily migrate from using https://amoffat.github.io/sh/ to using
the builtin subprocess module. """
def __init__(self, full_cmd, stdout, stderr='', exitcode=0):
self.full_cmd = full_cmd
# TODO(jorisroovers): The 'sh' library by default will merge stdout and stderr. We mimic this behavior
# for now until we fully remove the 'sh' library.
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import subprocess
from qa.utils import USE_SH_LIB, DEFAULT_ENCODING
from sh import git, echo, gitlint # pylint: disable=unused-import,no-name-in-module,import-error
from sh import CommandNotFound, ErrorReturnCode, RunningCommand # pylint: disable=import-error
and context:
# Path: qa/utils.py
# USE_SH_LIB = use_sh_library()
#
# DEFAULT_ENCODING = getpreferredencoding()
which might include code, classes, or functions. Output only the next line. | self.stdout = stdout + stderr.decode(DEFAULT_ENCODING) |
Continue the code snippet: <|code_start|>
def setUp(self):
""" Sets up the integration tests by creating a new temporary git repository """
self.tmpfiles = []
self.tmp_git_repos = []
self.tmp_git_repo = self.create_tmp_git_repo()
def tearDown(self):
# Clean up temporary files and repos
for tmpfile in self.tmpfiles:
os.remove(tmpfile)
for repo in self.tmp_git_repos:
shutil.rmtree(repo)
def assertEqualStdout(self, output, expected): # pylint: disable=invalid-name
self.assertIsInstance(output, RunningCommand)
output = output.stdout.decode(DEFAULT_ENCODING)
output = output.replace('\r', '')
self.assertMultiLineEqual(output, expected)
@staticmethod
def generate_temp_path():
timestamp = datetime.now().strftime("%Y%m%d-%H%M%S-%f")
return os.path.realpath(f"/tmp/gitlint-test-{timestamp}")
def create_tmp_git_repo(self):
""" Creates a temporary git repository and returns its directory path """
tmp_git_repo = self.generate_temp_path()
self.tmp_git_repos.append(tmp_git_repo)
<|code_end|>
. Use current file imports:
import io
import os
import platform
import shutil
import sys
import tempfile
import arrow
from datetime import datetime
from uuid import uuid4
from unittest import TestCase
from qa.shell import git, gitlint, RunningCommand
from qa.utils import DEFAULT_ENCODING
and context (classes, functions, or code) from other files:
# Path: qa/shell.py
# def git(*command_parts, **kwargs):
# return run_command("git", *command_parts, **kwargs)
#
# def gitlint(*command_parts, **kwargs):
# return run_command("gitlint", *command_parts, **kwargs)
#
# class RunningCommand:
# pass
#
# Path: qa/utils.py
# DEFAULT_ENCODING = getpreferredencoding()
. Output only the next line. | git("init", tmp_git_repo) |
Given snippet: <|code_start|>
@staticmethod
def get_sample_path(filename=""):
samples_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "samples")
return os.path.join(samples_dir, filename)
def get_last_commit_short_hash(self, git_repo=None):
git_repo = self.tmp_git_repo if git_repo is None else git_repo
return git("rev-parse", "--short", "HEAD", _cwd=git_repo, _err_to_out=True).replace("\n", "")
def get_last_commit_hash(self, git_repo=None):
git_repo = self.tmp_git_repo if git_repo is None else git_repo
return git("rev-parse", "HEAD", _cwd=git_repo, _err_to_out=True).replace("\n", "")
@staticmethod
def get_expected(filename="", variable_dict=None):
""" Utility method to read an 'expected' file and return it as a string. Optionally replace template variables
specified by variable_dict. """
expected_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "expected")
expected_path = os.path.join(expected_dir, filename)
with io.open(expected_path, encoding=DEFAULT_ENCODING) as file:
expected = file.read()
if variable_dict:
expected = expected.format(**variable_dict)
return expected
@staticmethod
def get_system_info_dict():
""" Returns a dict with items related to system values logged by `gitlint --debug` """
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import io
import os
import platform
import shutil
import sys
import tempfile
import arrow
from datetime import datetime
from uuid import uuid4
from unittest import TestCase
from qa.shell import git, gitlint, RunningCommand
from qa.utils import DEFAULT_ENCODING
and context:
# Path: qa/shell.py
# def git(*command_parts, **kwargs):
# return run_command("git", *command_parts, **kwargs)
#
# def gitlint(*command_parts, **kwargs):
# return run_command("gitlint", *command_parts, **kwargs)
#
# class RunningCommand:
# pass
#
# Path: qa/utils.py
# DEFAULT_ENCODING = getpreferredencoding()
which might include code, classes, or functions. Output only the next line. | expected_gitlint_version = gitlint("--version").replace("gitlint, version ", "").strip() |
Continue the code snippet: <|code_start|>
class BaseTestCase(TestCase):
""" Base class of which all gitlint integration test classes are derived.
Provides a number of convenience methods. """
# In case of assert failures, print the full error message
maxDiff = None
tmp_git_repo = None
GITLINT_USE_SH_LIB = os.environ.get("GITLINT_USE_SH_LIB", "[NOT SET]")
GIT_CONTEXT_ERROR_CODE = 254
GITLINT_USAGE_ERROR = 253
def setUp(self):
""" Sets up the integration tests by creating a new temporary git repository """
self.tmpfiles = []
self.tmp_git_repos = []
self.tmp_git_repo = self.create_tmp_git_repo()
def tearDown(self):
# Clean up temporary files and repos
for tmpfile in self.tmpfiles:
os.remove(tmpfile)
for repo in self.tmp_git_repos:
shutil.rmtree(repo)
def assertEqualStdout(self, output, expected): # pylint: disable=invalid-name
<|code_end|>
. Use current file imports:
import io
import os
import platform
import shutil
import sys
import tempfile
import arrow
from datetime import datetime
from uuid import uuid4
from unittest import TestCase
from qa.shell import git, gitlint, RunningCommand
from qa.utils import DEFAULT_ENCODING
and context (classes, functions, or code) from other files:
# Path: qa/shell.py
# def git(*command_parts, **kwargs):
# return run_command("git", *command_parts, **kwargs)
#
# def gitlint(*command_parts, **kwargs):
# return run_command("gitlint", *command_parts, **kwargs)
#
# class RunningCommand:
# pass
#
# Path: qa/utils.py
# DEFAULT_ENCODING = getpreferredencoding()
. Output only the next line. | self.assertIsInstance(output, RunningCommand) |
Given the code snippet: <|code_start|>
class BaseTestCase(TestCase):
""" Base class of which all gitlint integration test classes are derived.
Provides a number of convenience methods. """
# In case of assert failures, print the full error message
maxDiff = None
tmp_git_repo = None
GITLINT_USE_SH_LIB = os.environ.get("GITLINT_USE_SH_LIB", "[NOT SET]")
GIT_CONTEXT_ERROR_CODE = 254
GITLINT_USAGE_ERROR = 253
def setUp(self):
""" Sets up the integration tests by creating a new temporary git repository """
self.tmpfiles = []
self.tmp_git_repos = []
self.tmp_git_repo = self.create_tmp_git_repo()
def tearDown(self):
# Clean up temporary files and repos
for tmpfile in self.tmpfiles:
os.remove(tmpfile)
for repo in self.tmp_git_repos:
shutil.rmtree(repo)
def assertEqualStdout(self, output, expected): # pylint: disable=invalid-name
self.assertIsInstance(output, RunningCommand)
<|code_end|>
, generate the next line using the imports in this file:
import io
import os
import platform
import shutil
import sys
import tempfile
import arrow
from datetime import datetime
from uuid import uuid4
from unittest import TestCase
from qa.shell import git, gitlint, RunningCommand
from qa.utils import DEFAULT_ENCODING
and context (functions, classes, or occasionally code) from other files:
# Path: qa/shell.py
# def git(*command_parts, **kwargs):
# return run_command("git", *command_parts, **kwargs)
#
# def gitlint(*command_parts, **kwargs):
# return run_command("gitlint", *command_parts, **kwargs)
#
# class RunningCommand:
# pass
#
# Path: qa/utils.py
# DEFAULT_ENCODING = getpreferredencoding()
. Output only the next line. | output = output.stdout.decode(DEFAULT_ENCODING) |
Given snippet: <|code_start|> # self.assertGreaterEqual(srv.getbalance(address), 50000000000)
# self.assertEqual(srv.getutxos(address)[0]['txid'], txid)
# self.assertEqual(srv.gettransactions(address)[0].txid, txid)
def test_service_getblock_id(self):
srv = ServiceTest(min_providers=3, timeout=TIMEOUT_TEST, cache_uri='')
srv.getblock('0000000000000a3290f20e75860d505ce0e948a1d1d846bec7e39015d242884b', parse_transactions=False)
for provider in srv.results:
blk = srv.results[provider]
if blk['bits']:
self.assertEqual(blk['bits'], 436956491)
self.assertEqual(blk['height'], 150000)
self.assertEqual(blk['merkle_root'], 'be0b136f2f3db38d4f55f1963f0acac506d637b3c27a4c42f3504836a4ec52b1')
if blk['nonce']:
self.assertEqual(blk['nonce'], 1796110725)
if blk['prev_block']:
self.assertEqual(blk['prev_block'], '00000000000008df4269884f1d3bfc2aed3ea747292abb89be3dc3faa8c5d26f')
self.assertEqual(blk['time'], 1319118291)
self.assertEqual(blk['tx_count'], 10)
self.assertEqual(len(blk['txs']), 10)
if blk['version']:
self.assertEqual(blk['version'], 1)
self.assertEqual(blk['txs'][9],
'13e3167d46334600b59a5aa286dd02147ac33e64bfc2e188e1f0c0a442182584')
def test_service_getblock_height(self):
srv = ServiceTest(timeout=TIMEOUT_TEST, exclude_providers=['chainso'], cache_uri='')
b = srv.getblock(599999, parse_transactions=True, limit=3)
print("Test getblock using provider %s" % list(srv.results.keys())[0])
self.assertEqual(b.height, 599999)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
import logging
import mysql.connector
import psycopg2
from parameterized import parameterized_class
from psycopg2 import sql
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
from bitcoinlib.services.services import *
from bitcoinlib.encoding import to_hexstring
from tests.test_custom import CustomAssertions
and context:
# Path: bitcoinlib/encoding.py
# def to_hexstring(string):
# """
# Convert bytes, string to a hexadecimal string. Use instead of built-in hex() method if format
# of input string is not known.
#
# >>> to_hexstring(b'\\x12\\xaa\\xdd')
# '12aadd'
#
# :param string: Variable to convert to hex string
# :type string: bytes, str
#
# :return: hexstring
# """
# if not string:
# return ''
# try:
# bytes.fromhex(string)
# return string
# except (ValueError, TypeError):
# pass
#
# if not isinstance(string, bytes):
# string = bytes(string, 'utf8')
# return string.hex()
#
# Path: tests/test_custom.py
# class CustomAssertions:
#
# def assertDictEqualExt(self, result_dict, expected_dict, none_allowed=None):
# """
# Compare dictionaries, skip items not found in expected dictionary.
#
# Lists and recursion's in dictionaries are allowed.
#
# :param result_dict: First dictionary with results
# :type result_dict: dict
# :param expected_dict: Second dictionary with expected values
# :type expected_dict: dict
# :param none_allowed: List of fields for which None value in result_dict is allowed
# :type none_allowed: list
#
# :return bool: Dictionaries are identical?
# """
# if none_allowed is None:
# none_allowed = []
# if not isinstance(expected_dict, dict):
# if expected_dict == result_dict:
# return True
# else:
# raise AssertionError("Different value for %s != %s" % (result_dict, expected_dict))
# expected_keys = expected_dict.keys()
# for k in result_dict:
# if k not in expected_keys:
# continue
# if isinstance(result_dict[k], dict):
# self.assertDictEqualExt(result_dict[k], expected_dict[k], none_allowed)
# elif isinstance(result_dict[k], list):
# for i in range(len(result_dict[k])):
# if not isinstance(expected_dict[k], list):
# raise AssertionError("No list expected for %s attribute, expected '%s' but received: '%s'" %
# (k, expected_dict[k], result_dict[k]))
# self.assertDictEqualExt(result_dict[k][i], expected_dict[k][i], none_allowed)
# elif result_dict[k] != expected_dict[k]:
# if isinstance(result_dict[k], datetime):
# if result_dict[k].date() == expected_dict[k].date():
# continue
# if result_dict[k] is not None or k not in none_allowed:
# raise AssertionError("Different value for '%s': %s != %s" % (k, result_dict[k], expected_dict[k]))
which might include code, classes, or functions. Output only the next line. | self.assertEqual(to_hexstring(b.block_hash), '00000000000000000003ecd827f336c6971f6f77a0b9fba362398dd867975645') |
Based on the snippet: <|code_start|>MAXIMUM_ESTIMATED_FEE_DIFFERENCE = 3.00 # Maximum difference from average estimated fee before test_estimatefee fails.
# Use value above >0, and 1 for 100%
DATABASEFILE_CACHE_UNITTESTS = os.path.join(str(BCL_DATABASE_DIR), 'bitcoinlibcache.unittest.sqlite')
DATABASEFILE_CACHE_UNITTESTS2 = os.path.join(str(BCL_DATABASE_DIR), 'bitcoinlibcache2.unittest.sqlite')
DATABASE_CACHE_POSTGRESQL = 'postgresql://postgres:postgres@localhost:5432/bitcoinlibcache.unittest'
# FIXME: MySQL databases are not supported. Not allowed to create indexes/primary keys on binary fields
DATABASE_CACHE_MYSQL = 'mysql://root:root@localhost:3306/bitcoinlibcache.unittest'
DATABASES_CACHE = [
DATABASEFILE_CACHE_UNITTESTS2,
]
if UNITTESTS_FULL_DATABASE_TEST:
DATABASES_CACHE += [
DATABASE_CACHE_POSTGRESQL,
DATABASE_CACHE_MYSQL
]
TIMEOUT_TEST = 2
# Wrapper class for the Service client: Set cache_uri, timeout and ignore provider priority
class ServiceTest(Service):
def __init__(self, network=DEFAULT_NETWORK, min_providers=1, max_providers=1, providers=None,
timeout=TIMEOUT_TEST, cache_uri=DATABASEFILE_CACHE_UNITTESTS, ignore_priority=True,
exclude_providers=None, max_errors=SERVICE_MAX_ERRORS, strict=True):
super(self.__class__, self).__init__(network, min_providers, max_providers, providers, timeout, cache_uri,
ignore_priority, exclude_providers, max_errors, strict)
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
import logging
import mysql.connector
import psycopg2
from parameterized import parameterized_class
from psycopg2 import sql
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
from bitcoinlib.services.services import *
from bitcoinlib.encoding import to_hexstring
from tests.test_custom import CustomAssertions
and context (classes, functions, sometimes code) from other files:
# Path: bitcoinlib/encoding.py
# def to_hexstring(string):
# """
# Convert bytes, string to a hexadecimal string. Use instead of built-in hex() method if format
# of input string is not known.
#
# >>> to_hexstring(b'\\x12\\xaa\\xdd')
# '12aadd'
#
# :param string: Variable to convert to hex string
# :type string: bytes, str
#
# :return: hexstring
# """
# if not string:
# return ''
# try:
# bytes.fromhex(string)
# return string
# except (ValueError, TypeError):
# pass
#
# if not isinstance(string, bytes):
# string = bytes(string, 'utf8')
# return string.hex()
#
# Path: tests/test_custom.py
# class CustomAssertions:
#
# def assertDictEqualExt(self, result_dict, expected_dict, none_allowed=None):
# """
# Compare dictionaries, skip items not found in expected dictionary.
#
# Lists and recursion's in dictionaries are allowed.
#
# :param result_dict: First dictionary with results
# :type result_dict: dict
# :param expected_dict: Second dictionary with expected values
# :type expected_dict: dict
# :param none_allowed: List of fields for which None value in result_dict is allowed
# :type none_allowed: list
#
# :return bool: Dictionaries are identical?
# """
# if none_allowed is None:
# none_allowed = []
# if not isinstance(expected_dict, dict):
# if expected_dict == result_dict:
# return True
# else:
# raise AssertionError("Different value for %s != %s" % (result_dict, expected_dict))
# expected_keys = expected_dict.keys()
# for k in result_dict:
# if k not in expected_keys:
# continue
# if isinstance(result_dict[k], dict):
# self.assertDictEqualExt(result_dict[k], expected_dict[k], none_allowed)
# elif isinstance(result_dict[k], list):
# for i in range(len(result_dict[k])):
# if not isinstance(expected_dict[k], list):
# raise AssertionError("No list expected for %s attribute, expected '%s' but received: '%s'" %
# (k, expected_dict[k], result_dict[k]))
# self.assertDictEqualExt(result_dict[k][i], expected_dict[k][i], none_allowed)
# elif result_dict[k] != expected_dict[k]:
# if isinstance(result_dict[k], datetime):
# if result_dict[k].date() == expected_dict[k].date():
# continue
# if result_dict[k] is not None or k not in none_allowed:
# raise AssertionError("Different value for '%s': %s != %s" % (k, result_dict[k], expected_dict[k]))
. Output only the next line. | class TestService(unittest.TestCase, CustomAssertions): |
Based on the snippet: <|code_start|> self.assertEqual(s.raw, b'')
def test_script_deserialize_sig_pk(self):
scr = '493046022100cf4d7571dd47a4d47f5cb767d54d6702530a3555726b27b6ac56117f5e7808fe0221008cbb42233bb04d7f28a' \
'715cf7c938e238afde90207e9d103dd9018e12cb7180e0141042daa93315eebbe2cb9b5c3505df4c6fb6caca8b75678609856' \
'7550d4820c09db988fe9997d049d687292f815ccd6e7fb5c1b1a91137999818d17c73d0f80aef9'
s = Script.parse_hex(scr)
self.assertEqual(['sig_pubkey'], s.script_types)
self.assertEqual(s.signatures[0].as_der_encoded(),
bytearray(b"0F\x02!\x00\xcfMuq\xddG\xa4\xd4\x7f\\\xb7g\xd5Mg\x02S\n5Urk\'\xb6\xacV"
b"\x11\x7f^x\x08\xfe\x02!\x00\x8c\xbbB#;\xb0M\x7f(\xa7\x15\xcf|\x93\x8e#"
b"\x8a\xfd\xe9\x02\x07\xe9\xd1\x03\xdd\x90\x18\xe1,\xb7\x18\x0e\x01"))
self.assertEqual(s.keys[0].public_byte,
bytearray(b'\x04-\xaa\x931^\xeb\xbe,\xb9\xb5\xc3P]\xf4\xc6\xfbl\xac\xa8\xb7Vx`\x98'
b'VuP\xd4\x82\x0c\t\xdb\x98\x8f\xe9\x99}\x04\x9dhr\x92\xf8\x15\xcc\xd6'
b'\xe7\xfb\\\x1b\x1a\x91\x13y\x99\x81\x8d\x17\xc7=\x0f\x80\xae\xf9'))
def test_script_deserialize_sig_hashtype(self):
scr = '493046022100cf4d7571dd47a4d47f5cb767d54d6702530a3555726b27b6ac56117f5e7808fe0221008cbb42233bb04d7f28a' \
'715cf7c938e238afde90207e9d103dd9018e12cb7180e03'
s = Script.parse_hex(scr)
self.assertEqual(3, s.signatures[0].hash_type)
self.assertEqual(3, s.hash_type)
self.assertEqual(s.keys, [])
self.assertEqual(s.signatures[0].as_der_encoded(),
b"0F\x02!\x00\xcfMuq\xddG\xa4\xd4\x7f\\\xb7g\xd5Mg\x02S\n5Urk'\xb6\xacV\x11\x7f^x\x08\xfe"
b"\x02!\x00\x8c\xbbB#;\xb0M\x7f(\xa7\x15\xcf|\x93\x8e#"
b'\x8a\xfd\xe9\x02\x07\xe9\xd1\x03\xdd\x90\x18\xe1,\xb7\x18\x0e\x03')
<|code_end|>
, predict the immediate next line with the help of imports:
from bitcoinlib.scripts import *
from tests.test_custom import CustomAssertions
import unittest
and context (classes, functions, sometimes code) from other files:
# Path: tests/test_custom.py
# class CustomAssertions:
#
# def assertDictEqualExt(self, result_dict, expected_dict, none_allowed=None):
# """
# Compare dictionaries, skip items not found in expected dictionary.
#
# Lists and recursion's in dictionaries are allowed.
#
# :param result_dict: First dictionary with results
# :type result_dict: dict
# :param expected_dict: Second dictionary with expected values
# :type expected_dict: dict
# :param none_allowed: List of fields for which None value in result_dict is allowed
# :type none_allowed: list
#
# :return bool: Dictionaries are identical?
# """
# if none_allowed is None:
# none_allowed = []
# if not isinstance(expected_dict, dict):
# if expected_dict == result_dict:
# return True
# else:
# raise AssertionError("Different value for %s != %s" % (result_dict, expected_dict))
# expected_keys = expected_dict.keys()
# for k in result_dict:
# if k not in expected_keys:
# continue
# if isinstance(result_dict[k], dict):
# self.assertDictEqualExt(result_dict[k], expected_dict[k], none_allowed)
# elif isinstance(result_dict[k], list):
# for i in range(len(result_dict[k])):
# if not isinstance(expected_dict[k], list):
# raise AssertionError("No list expected for %s attribute, expected '%s' but received: '%s'" %
# (k, expected_dict[k], result_dict[k]))
# self.assertDictEqualExt(result_dict[k][i], expected_dict[k][i], none_allowed)
# elif result_dict[k] != expected_dict[k]:
# if isinstance(result_dict[k], datetime):
# if result_dict[k].date() == expected_dict[k].date():
# continue
# if result_dict[k] is not None or k not in none_allowed:
# raise AssertionError("Different value for '%s': %s != %s" % (k, result_dict[k], expected_dict[k]))
. Output only the next line. | class TestScript(unittest.TestCase, CustomAssertions): |
Continue the code snippet: <|code_start|>
def test_hdkey_testnet_random(self):
self.k = HDKey(network='testnet')
self.assertEqual('tprv', self.k.wif(is_private=True)[:4])
self.assertEqual('tpub', self.k.wif_public()[:4])
self.assertIn(self.k.address()[:1], ['m', 'n'])
def test_hdkey_testnet_import(self):
self.k = HDKey('tprv8ZgxMBicQKsPf2S18qpSypHPZBK7mdiwvXHPh5TSjGjm2pLacP4tEqVjLVyagTLLgSZK4YyBNb4eytBykE755Kc'
'L9YXAqPtfERNRfwRt54M')
self.assertEqual('cPSokRrLueavzAmVBmAXwgALkumRNMN9pErvRLAXvx58NBJAkEYJ', self.k.wif_key())
self.assertEqual('tpubD6NzVbkrYhZ4YVTo2VV3PDwW8Cq3vxurVptAybVk9YY9sJbMEmtURL7bWgKxXSWSahXu6HbHkdpjBGzwYYkJm'
'u2VmoeHuiTmzHZpJo8Cdpb', self.k.wif_public())
self.assertEqual('n4c8TKkqUmj3b8VJrTioiZuciyaCDRd6iE', self.k.address())
def test_hdkey_uncompressed_key_conversion(self):
key = Key('5JGSWMSfKiXVDvXzUeod8HeSsGRpHWQgrETithYjZKcxWNpexVK')
hdkey = HDKey(key)
hdkey_uncompressed = HDKey(hdkey.wif(is_private=True), compressed=False)
hdkey_compressed = HDKey(hdkey.wif(is_private=True))
self.assertFalse(key.compressed)
self.assertFalse(hdkey.compressed)
self.assertEqual(hdkey_uncompressed.private_hex, hdkey_compressed.private_hex)
self.assertEqual(hdkey_uncompressed.wif(), hdkey.wif())
self.assertEqual(hdkey_compressed.wif_key(), 'KyD9aZEG9cHZa3Hnh3rnTAUHAs6XhroYtJQwuBy4qfBhzHGEApgv')
def test_hdkey_wif_prefixes(self):
<|code_end|>
. Use current file imports:
import os
import unittest
import json
from bitcoinlib.networks import NETWORK_DEFINITIONS
from bitcoinlib.keys import *
and context (classes, functions, or code) from other files:
# Path: bitcoinlib/networks.py
# NETWORK_DEFINITIONS = _read_network_definitions()
. Output only the next line. | for network in list(NETWORK_DEFINITIONS.keys()): |
Continue the code snippet: <|code_start|>def init_sqlite(_):
if os.path.isfile(SQLITE_DATABASE_FILE):
os.remove(SQLITE_DATABASE_FILE)
def init_postgresql(_):
con = psycopg2.connect(user='postgres', host='localhost', password='postgres')
con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cur = con.cursor()
cur.execute(sql.SQL("DROP DATABASE IF EXISTS {}").format(
sql.Identifier(DATABASE_NAME))
)
cur.execute(sql.SQL("CREATE DATABASE {}").format(
sql.Identifier(DATABASE_NAME))
)
cur.close()
con.close()
def init_mysql(_):
con = mysql.connector.connect(user='root', host='localhost')
cur = con.cursor()
cur.execute("DROP DATABASE IF EXISTS {}".format(DATABASE_NAME))
cur.execute("CREATE DATABASE {}".format(DATABASE_NAME))
con.commit()
cur.close()
con.close()
db_uris = (('sqlite:///' + SQLITE_DATABASE_FILE, init_sqlite),)
<|code_end|>
. Use current file imports:
import os
import sys
import unittest
import mysql.connector
import psycopg2
from subprocess import Popen, PIPE
from parameterized import parameterized_class
from psycopg2 import sql
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
from bitcoinlib.main import UNITTESTS_FULL_DATABASE_TEST
from bitcoinlib.db import BCL_DATABASE_DIR
from bitcoinlib.encoding import normalize_string
and context (classes, functions, or code) from other files:
# Path: bitcoinlib/main.py
# def script_type_default(witness_type=None, multisig=False, locking_script=False):
# def get_encoding_from_witness(witness_type=None):
# def deprecated(func):
# def new_func(*args, **kwargs):
#
# Path: bitcoinlib/db.py
# def compile_largebinary_mysql(type_, compiler, **kwargs):
# def __init__(self, db_uri=None, password=None):
# def drop_db(self, yes_i_am_sure=False):
# def _import_config_data(ses):
# def add_column(engine, table_name, column):
# def __repr__(self):
# def __repr__(self):
# def __repr__(self):
# def __repr__(self):
# def db_update_version_id(db, version):
# def db_update(db, version_db, code_version=BITCOINLIB_VERSION):
# class Db:
# class DbConfig(Base):
# class DbWallet(Base):
# class DbKeyMultisigChildren(Base):
# class DbKey(Base):
# class DbNetwork(Base):
# class DbTransaction(Base):
# class DbTransactionInput(Base):
# class DbTransactionOutput(Base):
#
# Path: bitcoinlib/encoding.py
# def normalize_string(string):
# """
# Normalize a string to the default NFKD unicode format
# See https://en.wikipedia.org/wiki/Unicode_equivalence#Normalization
#
# :param string: string value
# :type string: bytes, str
#
# :return: string
# """
# if isinstance(string, bytes):
# utxt = string.decode('utf8')
# elif isinstance(string, TYPE_TEXT):
# utxt = string
# else:
# raise TypeError("String value expected")
#
# return unicodedata.normalize('NFKD', utxt)
. Output only the next line. | if UNITTESTS_FULL_DATABASE_TEST: |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# BitcoinLib - Python Cryptocurrency Library
# Unit Tests for Bitcoinlib Tools
# © 2018 May - 1200 Web Development <http://1200wd.com/>
#
try:
except ImportError:
pass # Only necessary when mysql or postgres is used
<|code_end|>
, determine the next line of code. You have imports:
import os
import sys
import unittest
import mysql.connector
import psycopg2
from subprocess import Popen, PIPE
from parameterized import parameterized_class
from psycopg2 import sql
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
from bitcoinlib.main import UNITTESTS_FULL_DATABASE_TEST
from bitcoinlib.db import BCL_DATABASE_DIR
from bitcoinlib.encoding import normalize_string
and context (class names, function names, or code) available:
# Path: bitcoinlib/main.py
# def script_type_default(witness_type=None, multisig=False, locking_script=False):
# def get_encoding_from_witness(witness_type=None):
# def deprecated(func):
# def new_func(*args, **kwargs):
#
# Path: bitcoinlib/db.py
# def compile_largebinary_mysql(type_, compiler, **kwargs):
# def __init__(self, db_uri=None, password=None):
# def drop_db(self, yes_i_am_sure=False):
# def _import_config_data(ses):
# def add_column(engine, table_name, column):
# def __repr__(self):
# def __repr__(self):
# def __repr__(self):
# def __repr__(self):
# def db_update_version_id(db, version):
# def db_update(db, version_db, code_version=BITCOINLIB_VERSION):
# class Db:
# class DbConfig(Base):
# class DbWallet(Base):
# class DbKeyMultisigChildren(Base):
# class DbKey(Base):
# class DbNetwork(Base):
# class DbTransaction(Base):
# class DbTransactionInput(Base):
# class DbTransactionOutput(Base):
#
# Path: bitcoinlib/encoding.py
# def normalize_string(string):
# """
# Normalize a string to the default NFKD unicode format
# See https://en.wikipedia.org/wiki/Unicode_equivalence#Normalization
#
# :param string: string value
# :type string: bytes, str
#
# :return: string
# """
# if isinstance(string, bytes):
# utxt = string.decode('utf8')
# elif isinstance(string, TYPE_TEXT):
# utxt = string
# else:
# raise TypeError("String value expected")
#
# return unicodedata.normalize('NFKD', utxt)
. Output only the next line. | SQLITE_DATABASE_FILE = os.path.join(str(BCL_DATABASE_DIR), 'bitcoinlib.unittest.sqlite') |
Given snippet: <|code_start|>
db_uris = (('sqlite:///' + SQLITE_DATABASE_FILE, init_sqlite),)
if UNITTESTS_FULL_DATABASE_TEST:
db_uris += (
# ('mysql://root@localhost:3306/' + DATABASE_NAME, init_mysql),
('postgresql://postgres:postgres@localhost:5432/' + DATABASE_NAME, init_postgresql),
)
@parameterized_class(('DATABASE_URI', 'init_fn'), db_uris)
class TestToolsCommandLineWallet(unittest.TestCase):
def setUp(self):
self.init_fn()
self.python_executable = sys.executable
self.clw_executable = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)),
'../bitcoinlib/tools/clw.py'))
def test_tools_clw_create_wallet(self):
cmd_wlt_create = '%s %s test --passphrase "emotion camp sponsor curious bacon squeeze bean world ' \
'actual chicken obscure spray" -r -d %s' % \
(self.python_executable, self.clw_executable, self.DATABASE_URI)
cmd_wlt_delete = "%s %s test --wallet-remove -d %s" % \
(self.python_executable, self.clw_executable, self.DATABASE_URI)
output_wlt_create = "14guS7uQpEbgf1e8TDo1zTEURJW3NGPc9E"
output_wlt_delete = "Wallet test has been removed"
process = Popen(cmd_wlt_create, stdin=PIPE, stdout=PIPE, shell=True)
poutput = process.communicate(input=b'y')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import sys
import unittest
import mysql.connector
import psycopg2
from subprocess import Popen, PIPE
from parameterized import parameterized_class
from psycopg2 import sql
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
from bitcoinlib.main import UNITTESTS_FULL_DATABASE_TEST
from bitcoinlib.db import BCL_DATABASE_DIR
from bitcoinlib.encoding import normalize_string
and context:
# Path: bitcoinlib/main.py
# def script_type_default(witness_type=None, multisig=False, locking_script=False):
# def get_encoding_from_witness(witness_type=None):
# def deprecated(func):
# def new_func(*args, **kwargs):
#
# Path: bitcoinlib/db.py
# def compile_largebinary_mysql(type_, compiler, **kwargs):
# def __init__(self, db_uri=None, password=None):
# def drop_db(self, yes_i_am_sure=False):
# def _import_config_data(ses):
# def add_column(engine, table_name, column):
# def __repr__(self):
# def __repr__(self):
# def __repr__(self):
# def __repr__(self):
# def db_update_version_id(db, version):
# def db_update(db, version_db, code_version=BITCOINLIB_VERSION):
# class Db:
# class DbConfig(Base):
# class DbWallet(Base):
# class DbKeyMultisigChildren(Base):
# class DbKey(Base):
# class DbNetwork(Base):
# class DbTransaction(Base):
# class DbTransactionInput(Base):
# class DbTransactionOutput(Base):
#
# Path: bitcoinlib/encoding.py
# def normalize_string(string):
# """
# Normalize a string to the default NFKD unicode format
# See https://en.wikipedia.org/wiki/Unicode_equivalence#Normalization
#
# :param string: string value
# :type string: bytes, str
#
# :return: string
# """
# if isinstance(string, bytes):
# utxt = string.decode('utf8')
# elif isinstance(string, TYPE_TEXT):
# utxt = string
# else:
# raise TypeError("String value expected")
#
# return unicodedata.normalize('NFKD', utxt)
which might include code, classes, or functions. Output only the next line. | self.assertIn(output_wlt_create, normalize_string(poutput[0])) |
Using the snippet: <|code_start|> :param strength: Key strength in number of bits as multiply of 32, default is 128 bits. It advised to specify 128 bits or more, i.e.: 128, 256, 512 or 1024
:type strength: int
:param add_checksum: Included a checksum? Default is True
:type add_checksum: bool
:return str: Mnemonic passphrase consisting of a space seperated list of words
"""
if strength % 32 > 0:
raise ValueError("Strength should be divisible by 32")
data = os.urandom(strength // 8)
return self.to_mnemonic(data, add_checksum=add_checksum)
def to_mnemonic(self, data, add_checksum=True, check_on_curve=True):
"""
Convert key data entropy to Mnemonic sentence
>>> Mnemonic().to_mnemonic('28acfc94465fd2f6774759d6897ec122')
'chunk gun celery million wood kite tackle twenty story episode raccoon dutch'
:param data: Key data entropy
:type data: bytes, hexstring
:param add_checksum: Included a checksum? Default is True
:type add_checksum: bool
:param check_on_curve: Check if data integer value is on secp256k1 curve. Should be enabled when not testing and working with crypto
:type check_on_curve: bool
:return str: Mnemonic passphrase consisting of a space seperated list of words
"""
data = to_bytes(data)
data_int = int.from_bytes(data, 'big')
<|code_end|>
, determine the next line of code. You have imports:
from bitcoinlib.encoding import *
from bitcoinlib.config.secp256k1 import secp256k1_n
and context (class names, function names, or code) available:
# Path: bitcoinlib/config/secp256k1.py
. Output only the next line. | if check_on_curve and not 0 < data_int < secp256k1_n: |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
#
# BitcoinLib - Python Cryptocurrency Library
# Update database
# © 2017 November - 1200 Web Development <http://1200wd.com/>
#
# This script creates a database with latest structure and copies only wallets and keys from old database
# Transactions, UTXO's and values are not copied, but can be recreated with utxos_update and transaction_update
# methods of the Wallet class.
#
print("Database should update automatically when using BitcoinLib. If automatic update fails you can run this script. "
"!!! After everything is backuped !!!")
def parse_args():
parser = argparse.ArgumentParser(description='BitcoinLib Database update script')
<|code_end|>
using the current file's imports:
import os
import sys
import argparse
from copy import deepcopy
from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from shutil import move
from bitcoinlib.main import DEFAULT_DATABASE, BCL_DATABASE_DIR, BITCOINLIB_VERSION
from bitcoinlib.db import Base, DbWallet, DbKey, DbKeyMultisigChildren, DbConfig
and any relevant context from other files:
# Path: bitcoinlib/main.py
# def script_type_default(witness_type=None, multisig=False, locking_script=False):
# def get_encoding_from_witness(witness_type=None):
# def deprecated(func):
# def new_func(*args, **kwargs):
#
# Path: bitcoinlib/db.py
# def compile_largebinary_mysql(type_, compiler, **kwargs):
# def __init__(self, db_uri=None, password=None):
# def drop_db(self, yes_i_am_sure=False):
# def _import_config_data(ses):
# def add_column(engine, table_name, column):
# def __repr__(self):
# def __repr__(self):
# def __repr__(self):
# def __repr__(self):
# def db_update_version_id(db, version):
# def db_update(db, version_db, code_version=BITCOINLIB_VERSION):
# class Db:
# class DbConfig(Base):
# class DbWallet(Base):
# class DbKeyMultisigChildren(Base):
# class DbKey(Base):
# class DbNetwork(Base):
# class DbTransaction(Base):
# class DbTransactionInput(Base):
# class DbTransactionOutput(Base):
. Output only the next line. | parser.add_argument('--database', '-d', default='sqlite:///' + DEFAULT_DATABASE, |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# BitcoinLib - Python Cryptocurrency Library
# Update database
# © 2017 November - 1200 Web Development <http://1200wd.com/>
#
# This script creates a database with latest structure and copies only wallets and keys from old database
# Transactions, UTXO's and values are not copied, but can be recreated with utxos_update and transaction_update
# methods of the Wallet class.
#
print("Database should update automatically when using BitcoinLib. If automatic update fails you can run this script. "
"!!! After everything is backuped !!!")
def parse_args():
parser = argparse.ArgumentParser(description='BitcoinLib Database update script')
parser.add_argument('--database', '-d', default='sqlite:///' + DEFAULT_DATABASE,
help="Name of specific database file to use",)
pa = parser.parse_args()
return pa
args = parse_args()
database_file = args.database
if not os.path.isfile(database_file):
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import sys
import argparse
from copy import deepcopy
from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from shutil import move
from bitcoinlib.main import DEFAULT_DATABASE, BCL_DATABASE_DIR, BITCOINLIB_VERSION
from bitcoinlib.db import Base, DbWallet, DbKey, DbKeyMultisigChildren, DbConfig
and context (classes, functions, sometimes code) from other files:
# Path: bitcoinlib/main.py
# def script_type_default(witness_type=None, multisig=False, locking_script=False):
# def get_encoding_from_witness(witness_type=None):
# def deprecated(func):
# def new_func(*args, **kwargs):
#
# Path: bitcoinlib/db.py
# def compile_largebinary_mysql(type_, compiler, **kwargs):
# def __init__(self, db_uri=None, password=None):
# def drop_db(self, yes_i_am_sure=False):
# def _import_config_data(ses):
# def add_column(engine, table_name, column):
# def __repr__(self):
# def __repr__(self):
# def __repr__(self):
# def __repr__(self):
# def db_update_version_id(db, version):
# def db_update(db, version_db, code_version=BITCOINLIB_VERSION):
# class Db:
# class DbConfig(Base):
# class DbWallet(Base):
# class DbKeyMultisigChildren(Base):
# class DbKey(Base):
# class DbNetwork(Base):
# class DbTransaction(Base):
# class DbTransactionInput(Base):
# class DbTransactionOutput(Base):
. Output only the next line. | database_file = os.path.join(BCL_DATABASE_DIR, database_file) |
Continue the code snippet: <|code_start|>
keys = session_backup.execute("SELECT * FROM keys")
for key in keys:
fields = dict(key)
# Update for 'key' field
if 'key' in fields:
if fields['is_private']:
fields['private'] = fields['key']
else:
fields['public'] = fields['key']
del(fields['key'])
# Remove unused fields
db_field_names = [field[0] for field in DbKey.__table__.columns.items()]
fields_copy = deepcopy(fields)
for f in fields_copy:
if f not in db_field_names:
del(fields[f])
fields['used'] = False # To force rescan of all keys
session.add(DbKey(**fields))
session.commit()
keysubs = session_backup.execute("SELECT * FROM key_multisig_children")
for keysub in keysubs:
fields = dict(keysub)
session.add(DbKeyMultisigChildren(**fields))
session.commit()
<|code_end|>
. Use current file imports:
import os
import sys
import argparse
from copy import deepcopy
from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from shutil import move
from bitcoinlib.main import DEFAULT_DATABASE, BCL_DATABASE_DIR, BITCOINLIB_VERSION
from bitcoinlib.db import Base, DbWallet, DbKey, DbKeyMultisigChildren, DbConfig
and context (classes, functions, or code) from other files:
# Path: bitcoinlib/main.py
# def script_type_default(witness_type=None, multisig=False, locking_script=False):
# def get_encoding_from_witness(witness_type=None):
# def deprecated(func):
# def new_func(*args, **kwargs):
#
# Path: bitcoinlib/db.py
# def compile_largebinary_mysql(type_, compiler, **kwargs):
# def __init__(self, db_uri=None, password=None):
# def drop_db(self, yes_i_am_sure=False):
# def _import_config_data(ses):
# def add_column(engine, table_name, column):
# def __repr__(self):
# def __repr__(self):
# def __repr__(self):
# def __repr__(self):
# def db_update_version_id(db, version):
# def db_update(db, version_db, code_version=BITCOINLIB_VERSION):
# class Db:
# class DbConfig(Base):
# class DbWallet(Base):
# class DbKeyMultisigChildren(Base):
# class DbKey(Base):
# class DbNetwork(Base):
# class DbTransaction(Base):
# class DbTransactionInput(Base):
# class DbTransactionOutput(Base):
. Output only the next line. | session.query(DbConfig).filter(DbConfig.variable == 'version').update({DbConfig.value: BITCOINLIB_VERSION}) |
Next line prediction: <|code_start|>def parse_args():
parser = argparse.ArgumentParser(description='BitcoinLib Database update script')
parser.add_argument('--database', '-d', default='sqlite:///' + DEFAULT_DATABASE,
help="Name of specific database file to use",)
pa = parser.parse_args()
return pa
args = parse_args()
database_file = args.database
if not os.path.isfile(database_file):
database_file = os.path.join(BCL_DATABASE_DIR, database_file)
database_backup_file = os.path.join(BCL_DATABASE_DIR, "%s.backup-%s" %
(database_file, datetime.now().strftime("%Y%m%d-%I:%M")))
print("\nWallet and Key data will be copied to new database. Transaction data will NOT be copied")
print("Updating database file: %s" % database_file)
print("Old database will be backed up to %s" % database_backup_file)
if input("Type 'y' or 'Y' to continue or any other key to cancel: ") not in ['y', 'Y']:
print("Aborted by user")
sys.exit()
# Move old database to temporary database
move(database_file, database_backup_file)
try:
# Create new database
engine = create_engine('sqlite:///%s' % database_file)
<|code_end|>
. Use current file imports:
(import os
import sys
import argparse
from copy import deepcopy
from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from shutil import move
from bitcoinlib.main import DEFAULT_DATABASE, BCL_DATABASE_DIR, BITCOINLIB_VERSION
from bitcoinlib.db import Base, DbWallet, DbKey, DbKeyMultisigChildren, DbConfig)
and context including class names, function names, or small code snippets from other files:
# Path: bitcoinlib/main.py
# def script_type_default(witness_type=None, multisig=False, locking_script=False):
# def get_encoding_from_witness(witness_type=None):
# def deprecated(func):
# def new_func(*args, **kwargs):
#
# Path: bitcoinlib/db.py
# def compile_largebinary_mysql(type_, compiler, **kwargs):
# def __init__(self, db_uri=None, password=None):
# def drop_db(self, yes_i_am_sure=False):
# def _import_config_data(ses):
# def add_column(engine, table_name, column):
# def __repr__(self):
# def __repr__(self):
# def __repr__(self):
# def __repr__(self):
# def db_update_version_id(db, version):
# def db_update(db, version_db, code_version=BITCOINLIB_VERSION):
# class Db:
# class DbConfig(Base):
# class DbWallet(Base):
# class DbKeyMultisigChildren(Base):
# class DbKey(Base):
# class DbNetwork(Base):
# class DbTransaction(Base):
# class DbTransactionInput(Base):
# class DbTransactionOutput(Base):
. Output only the next line. | Base.metadata.create_all(engine) |
Here is a snippet: <|code_start|>
try:
# Create new database
engine = create_engine('sqlite:///%s' % database_file)
Base.metadata.create_all(engine)
# Copy wallets and keys to new database
Session = sessionmaker(bind=engine)
session = Session()
engine_backup = create_engine('sqlite:///%s' % database_backup_file)
Session_backup = sessionmaker(bind=engine_backup)
session_backup = Session_backup()
wallets = session_backup.execute("SELECT * FROM wallets")
for wallet in wallets:
fields = dict(wallet)
# Update, rename
try:
del(fields['balance'])
except:
pass
if fields['scheme'] == 'bip44':
fields['scheme'] = 'bip32'
elif fields['scheme'] == 'multisig':
fields['scheme'] = 'bip32'
fields['multisig'] = True
# Remove unused fields
<|code_end|>
. Write the next line using the current file imports:
import os
import sys
import argparse
from copy import deepcopy
from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from shutil import move
from bitcoinlib.main import DEFAULT_DATABASE, BCL_DATABASE_DIR, BITCOINLIB_VERSION
from bitcoinlib.db import Base, DbWallet, DbKey, DbKeyMultisigChildren, DbConfig
and context from other files:
# Path: bitcoinlib/main.py
# def script_type_default(witness_type=None, multisig=False, locking_script=False):
# def get_encoding_from_witness(witness_type=None):
# def deprecated(func):
# def new_func(*args, **kwargs):
#
# Path: bitcoinlib/db.py
# def compile_largebinary_mysql(type_, compiler, **kwargs):
# def __init__(self, db_uri=None, password=None):
# def drop_db(self, yes_i_am_sure=False):
# def _import_config_data(ses):
# def add_column(engine, table_name, column):
# def __repr__(self):
# def __repr__(self):
# def __repr__(self):
# def __repr__(self):
# def db_update_version_id(db, version):
# def db_update(db, version_db, code_version=BITCOINLIB_VERSION):
# class Db:
# class DbConfig(Base):
# class DbWallet(Base):
# class DbKeyMultisigChildren(Base):
# class DbKey(Base):
# class DbNetwork(Base):
# class DbTransaction(Base):
# class DbTransactionInput(Base):
# class DbTransactionOutput(Base):
, which may include functions, classes, or code. Output only the next line. | db_field_names = [field[0] for field in DbWallet.__table__.columns.items()] |
Given the following code snippet before the placeholder: <|code_start|> pass
if fields['scheme'] == 'bip44':
fields['scheme'] = 'bip32'
elif fields['scheme'] == 'multisig':
fields['scheme'] = 'bip32'
fields['multisig'] = True
# Remove unused fields
db_field_names = [field[0] for field in DbWallet.__table__.columns.items()]
fields_copy = deepcopy(fields)
for f in fields_copy:
if f not in db_field_names:
del(fields[f])
session.add(DbWallet(**fields))
session.commit()
keys = session_backup.execute("SELECT * FROM keys")
for key in keys:
fields = dict(key)
# Update for 'key' field
if 'key' in fields:
if fields['is_private']:
fields['private'] = fields['key']
else:
fields['public'] = fields['key']
del(fields['key'])
# Remove unused fields
<|code_end|>
, predict the next line using imports from the current file:
import os
import sys
import argparse
from copy import deepcopy
from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from shutil import move
from bitcoinlib.main import DEFAULT_DATABASE, BCL_DATABASE_DIR, BITCOINLIB_VERSION
from bitcoinlib.db import Base, DbWallet, DbKey, DbKeyMultisigChildren, DbConfig
and context including class names, function names, and sometimes code from other files:
# Path: bitcoinlib/main.py
# def script_type_default(witness_type=None, multisig=False, locking_script=False):
# def get_encoding_from_witness(witness_type=None):
# def deprecated(func):
# def new_func(*args, **kwargs):
#
# Path: bitcoinlib/db.py
# def compile_largebinary_mysql(type_, compiler, **kwargs):
# def __init__(self, db_uri=None, password=None):
# def drop_db(self, yes_i_am_sure=False):
# def _import_config_data(ses):
# def add_column(engine, table_name, column):
# def __repr__(self):
# def __repr__(self):
# def __repr__(self):
# def __repr__(self):
# def db_update_version_id(db, version):
# def db_update(db, version_db, code_version=BITCOINLIB_VERSION):
# class Db:
# class DbConfig(Base):
# class DbWallet(Base):
# class DbKeyMultisigChildren(Base):
# class DbKey(Base):
# class DbNetwork(Base):
# class DbTransaction(Base):
# class DbTransactionInput(Base):
# class DbTransactionOutput(Base):
. Output only the next line. | db_field_names = [field[0] for field in DbKey.__table__.columns.items()] |
Here is a snippet: <|code_start|>
session.add(DbWallet(**fields))
session.commit()
keys = session_backup.execute("SELECT * FROM keys")
for key in keys:
fields = dict(key)
# Update for 'key' field
if 'key' in fields:
if fields['is_private']:
fields['private'] = fields['key']
else:
fields['public'] = fields['key']
del(fields['key'])
# Remove unused fields
db_field_names = [field[0] for field in DbKey.__table__.columns.items()]
fields_copy = deepcopy(fields)
for f in fields_copy:
if f not in db_field_names:
del(fields[f])
fields['used'] = False # To force rescan of all keys
session.add(DbKey(**fields))
session.commit()
keysubs = session_backup.execute("SELECT * FROM key_multisig_children")
for keysub in keysubs:
fields = dict(keysub)
<|code_end|>
. Write the next line using the current file imports:
import os
import sys
import argparse
from copy import deepcopy
from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from shutil import move
from bitcoinlib.main import DEFAULT_DATABASE, BCL_DATABASE_DIR, BITCOINLIB_VERSION
from bitcoinlib.db import Base, DbWallet, DbKey, DbKeyMultisigChildren, DbConfig
and context from other files:
# Path: bitcoinlib/main.py
# def script_type_default(witness_type=None, multisig=False, locking_script=False):
# def get_encoding_from_witness(witness_type=None):
# def deprecated(func):
# def new_func(*args, **kwargs):
#
# Path: bitcoinlib/db.py
# def compile_largebinary_mysql(type_, compiler, **kwargs):
# def __init__(self, db_uri=None, password=None):
# def drop_db(self, yes_i_am_sure=False):
# def _import_config_data(ses):
# def add_column(engine, table_name, column):
# def __repr__(self):
# def __repr__(self):
# def __repr__(self):
# def __repr__(self):
# def db_update_version_id(db, version):
# def db_update(db, version_db, code_version=BITCOINLIB_VERSION):
# class Db:
# class DbConfig(Base):
# class DbWallet(Base):
# class DbKeyMultisigChildren(Base):
# class DbKey(Base):
# class DbNetwork(Base):
# class DbTransaction(Base):
# class DbTransactionInput(Base):
# class DbTransactionOutput(Base):
, which may include functions, classes, or code. Output only the next line. | session.add(DbKeyMultisigChildren(**fields)) |
Given the following code snippet before the placeholder: <|code_start|>
keys = session_backup.execute("SELECT * FROM keys")
for key in keys:
fields = dict(key)
# Update for 'key' field
if 'key' in fields:
if fields['is_private']:
fields['private'] = fields['key']
else:
fields['public'] = fields['key']
del(fields['key'])
# Remove unused fields
db_field_names = [field[0] for field in DbKey.__table__.columns.items()]
fields_copy = deepcopy(fields)
for f in fields_copy:
if f not in db_field_names:
del(fields[f])
fields['used'] = False # To force rescan of all keys
session.add(DbKey(**fields))
session.commit()
keysubs = session_backup.execute("SELECT * FROM key_multisig_children")
for keysub in keysubs:
fields = dict(keysub)
session.add(DbKeyMultisigChildren(**fields))
session.commit()
<|code_end|>
, predict the next line using imports from the current file:
import os
import sys
import argparse
from copy import deepcopy
from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from shutil import move
from bitcoinlib.main import DEFAULT_DATABASE, BCL_DATABASE_DIR, BITCOINLIB_VERSION
from bitcoinlib.db import Base, DbWallet, DbKey, DbKeyMultisigChildren, DbConfig
and context including class names, function names, and sometimes code from other files:
# Path: bitcoinlib/main.py
# def script_type_default(witness_type=None, multisig=False, locking_script=False):
# def get_encoding_from_witness(witness_type=None):
# def deprecated(func):
# def new_func(*args, **kwargs):
#
# Path: bitcoinlib/db.py
# def compile_largebinary_mysql(type_, compiler, **kwargs):
# def __init__(self, db_uri=None, password=None):
# def drop_db(self, yes_i_am_sure=False):
# def _import_config_data(ses):
# def add_column(engine, table_name, column):
# def __repr__(self):
# def __repr__(self):
# def __repr__(self):
# def __repr__(self):
# def db_update_version_id(db, version):
# def db_update(db, version_db, code_version=BITCOINLIB_VERSION):
# class Db:
# class DbConfig(Base):
# class DbWallet(Base):
# class DbKeyMultisigChildren(Base):
# class DbKey(Base):
# class DbNetwork(Base):
# class DbTransaction(Base):
# class DbTransactionInput(Base):
# class DbTransactionOutput(Base):
. Output only the next line. | session.query(DbConfig).filter(DbConfig.variable == 'version').update({DbConfig.value: BITCOINLIB_VERSION}) |
Given the code snippet: <|code_start|> raise ValueError("Value uses different network (%s) then supplied network: %s" % (value.network.name, network))
value = value.value_sat
return value
class Value:
"""
Class to represent and convert cryptocurrency values
"""
@classmethod
def from_satoshi(cls, value, denominator=None, network=DEFAULT_NETWORK):
"""
Initialize Value class with smallest denominator as input. Such as represented in script and transactions cryptocurrency values.
:param value: Amount of Satoshi's / smallest denominator for this network
:type value: int
:param denominator: Denominator as integer or string. Such as 0.001 or m for milli, 1000 or k for kilo, etc. See NETWORK_DENOMINATORS for list of available denominator symbols.
:type denominator: int, float, str
:param network: Specify network if not supplied already in the value string
:type network: str, Network
:return Value:
"""
if not isinstance(network, Network):
network = Network(network)
if denominator is None:
denominator = network.denominator
else:
if isinstance(denominator, str):
<|code_end|>
, generate the next line using the imports in this file:
from bitcoinlib.networks import *
from bitcoinlib.config.config import NETWORK_DENOMINATORS
and context (functions, classes, or occasionally code) from other files:
# Path: bitcoinlib/config/config.py
# NETWORK_DENOMINATORS = { # source: https://en.bitcoin.it/wiki/Units, https://en.wikipedia.org/wiki/Metric_prefix
# 0.00000000000001: 'µsat',
# 0.00000000001: 'msat',
# 0.000000001: 'n',
# 0.00000001: 'sat',
# 0.0000001: 'fin',
# 0.000001: 'µ',
# 0.001: 'm',
# 0.01: 'c',
# 0.1: 'd',
# 1: '',
# 10: 'da',
# 100: 'h',
# 1000: 'k',
# 1000000: 'M',
# 1000000000: 'G',
# 1000000000000: 'T',
# 1000000000000000: 'P',
# 1000000000000000000: 'E',
# 1000000000000000000000: 'Z',
# 1000000000000000000000000: 'Y',
# }
. Output only the next line. | dens = [den for den, symb in NETWORK_DENOMINATORS.items() if symb == denominator] |
Here is a snippet: <|code_start|> self.assertEqual(str(Quantity(121608561109507200000, 'H/s', precision=10)), '121.6085611095 EH/s')
self.assertEqual(str(Quantity(1 / 121608561109507200000, 'ots', precision=10)), '8.2231052722 zots')
self.assertEqual(str(Quantity(0.0000000001, 'm', precision=2)), '100.00 pm')
self.assertEqual(str(Quantity(121608561109507200000000000000000)), '121608561.110 Y')
self.assertEqual(str(Quantity(1/1216085611095072000000000000000)), '0.000 y')
self.assertEqual(str(Quantity(1/1216085611095072000000000000000, precision=10)), '0.0000008223 y')
self.assertEqual(str(Quantity(10, 'pound', precision=0)), '10 pound')
self.assertEqual(str(Quantity(0)), '0.000')
# Source: https://github.com/bitcoin/bips/blob/master/bip-0350.mediawiki
def test_bech32m_valid(self):
for addr, pubkeyhash in BECH32M_VALID:
assert(pubkeyhash == addr_bech32_to_pubkeyhash(addr, include_witver=True).hex())
prefix = addr.split('1')[0].lower()
witver = change_base(addr.split('1')[1][0], 'bech32', 10)
checksum_xor = addr_bech32_checksum(addr)
addrc = pubkeyhash_to_addr_bech32(pubkeyhash, prefix, witver, checksum_xor=checksum_xor)
assert(addr.lower() == addrc)
def test_bech32_invalid(self):
for addr, err in BECH32M_INVALID:
try:
addr_bech32_to_pubkeyhash(addr)
except (EncodingError, TypeError) as e:
assert (str(e) == err)
class TestEncodingConfig(unittest.TestCase):
def test_config_opcodes(self):
<|code_end|>
. Write the next line using the current file imports:
import unittest
from bitcoinlib.config.opcodes import op
from bitcoinlib.encoding import *
from bitcoinlib.encoding import _bech32_polymod, _codestring_to_array
and context from other files:
# Path: bitcoinlib/config/opcodes.py
# def op():
# pass
#
# Path: bitcoinlib/encoding.py
# def _bech32_polymod(values):
# """
# Internal function that computes the Bech32 checksum
# """
# generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]
# chk = 1
# for value in values:
# top = chk >> 25
# chk = (chk & 0x1ffffff) << 5 ^ value
# for i in range(5):
# chk ^= generator[i] if ((top >> i) & 1) else 0
# return chk
#
# def _codestring_to_array(codestring, base):
# codestring = bytes(codestring, 'utf8')
# codebase = code_strings[base]
# array = []
# for s in codestring:
# try:
# array.append(codebase.index(s))
# except ValueError:
# raise EncodingError("Character '%s' not found in codebase" % s)
# return array
, which may include functions, classes, or code. Output only the next line. | self.assertEqual(op.op_checklocktimeverify, 177) |
Here is a snippet: <|code_start|> ('bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kemeawh', 'Invalid checksum (Bech32m instead of Bech32)'),
('tb1q0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vq24jc47', 'Invalid checksum (Bech32m instead of Bech32)'),
('bc1p38j9r5y49hruaue7wxjce0updqjuyyx0kh56v8s25huc6995vvpql3jow4', "Character '111' not found in codebase"),
('BC130XLXVLHEMJA6C4DQV22UAPCTQUPFHLXM9H8Z3K2E72Q4K9HCZ7VQ7ZWS8R', 'Invalid decoded data length'),
('bc1pw5dgrnzv', 'Invalid decoded data length, must be between 2 and 40'),
('bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7v8n0nx0muaewav253zgeav',
'Invalid decoded data length, must be between 2 and 40'),
('BC1QR508D6QEJXTDG4Y5R3ZARVARYV98GJ9P', 'Invalid decoded data length, must be 20 or 32 bytes'),
('bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7v07qwwzcrf', "cannot convert 'NoneType' object to bytes"),
('tb1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vpggkg4j', "cannot convert 'NoneType' object to bytes"),
('bc1gmk9yu', 'Invalid checksum (Bech32 instead of Bech32m)'),
]
class TestEncodingBech32SegwitAddresses(unittest.TestCase):
"""
Reference tests for bech32 segwit adresses
Copyright (c) 2017 Pieter Wuille
Source: https://github.com/sipa/bech32/tree/master/ref/python
"""
def test_valid_checksum(self):
"""Test checksum creation and validation."""
for test in VALID_CHECKSUM:
pos = test.rfind('1')
test = test.lower()
hrp = test[:pos]
data = _codestring_to_array(test[pos + 1:], 'bech32')
hrp_expanded = [ord(x) >> 5 for x in hrp] + [0] + [ord(x) & 31 for x in hrp]
<|code_end|>
. Write the next line using the current file imports:
import unittest
from bitcoinlib.config.opcodes import op
from bitcoinlib.encoding import *
from bitcoinlib.encoding import _bech32_polymod, _codestring_to_array
and context from other files:
# Path: bitcoinlib/config/opcodes.py
# def op():
# pass
#
# Path: bitcoinlib/encoding.py
# def _bech32_polymod(values):
# """
# Internal function that computes the Bech32 checksum
# """
# generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]
# chk = 1
# for value in values:
# top = chk >> 25
# chk = (chk & 0x1ffffff) << 5 ^ value
# for i in range(5):
# chk ^= generator[i] if ((top >> i) & 1) else 0
# return chk
#
# def _codestring_to_array(codestring, base):
# codestring = bytes(codestring, 'utf8')
# codebase = code_strings[base]
# array = []
# for s in codestring:
# try:
# array.append(codebase.index(s))
# except ValueError:
# raise EncodingError("Character '%s' not found in codebase" % s)
# return array
, which may include functions, classes, or code. Output only the next line. | self.assertEqual(_bech32_polymod(hrp_expanded + data), 1, msg="Invalid checksum for address %s" % test) |
Using the snippet: <|code_start|> ('tb1z0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqglt7rf', 'Invalid checksum (Bech32 instead of Bech32m)'),
('BC1S0XLXVLHEMJA6C4DQV22UAPCTQUPFHLXM9H8Z3K2E72Q4K9HCZ7VQ54WELL', 'Invalid checksum (Bech32 instead of Bech32m)'),
('bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kemeawh', 'Invalid checksum (Bech32m instead of Bech32)'),
('tb1q0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vq24jc47', 'Invalid checksum (Bech32m instead of Bech32)'),
('bc1p38j9r5y49hruaue7wxjce0updqjuyyx0kh56v8s25huc6995vvpql3jow4', "Character '111' not found in codebase"),
('BC130XLXVLHEMJA6C4DQV22UAPCTQUPFHLXM9H8Z3K2E72Q4K9HCZ7VQ7ZWS8R', 'Invalid decoded data length'),
('bc1pw5dgrnzv', 'Invalid decoded data length, must be between 2 and 40'),
('bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7v8n0nx0muaewav253zgeav',
'Invalid decoded data length, must be between 2 and 40'),
('BC1QR508D6QEJXTDG4Y5R3ZARVARYV98GJ9P', 'Invalid decoded data length, must be 20 or 32 bytes'),
('bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7v07qwwzcrf', "cannot convert 'NoneType' object to bytes"),
('tb1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vpggkg4j', "cannot convert 'NoneType' object to bytes"),
('bc1gmk9yu', 'Invalid checksum (Bech32 instead of Bech32m)'),
]
class TestEncodingBech32SegwitAddresses(unittest.TestCase):
"""
Reference tests for bech32 segwit adresses
Copyright (c) 2017 Pieter Wuille
Source: https://github.com/sipa/bech32/tree/master/ref/python
"""
def test_valid_checksum(self):
"""Test checksum creation and validation."""
for test in VALID_CHECKSUM:
pos = test.rfind('1')
test = test.lower()
hrp = test[:pos]
<|code_end|>
, determine the next line of code. You have imports:
import unittest
from bitcoinlib.config.opcodes import op
from bitcoinlib.encoding import *
from bitcoinlib.encoding import _bech32_polymod, _codestring_to_array
and context (class names, function names, or code) available:
# Path: bitcoinlib/config/opcodes.py
# def op():
# pass
#
# Path: bitcoinlib/encoding.py
# def _bech32_polymod(values):
# """
# Internal function that computes the Bech32 checksum
# """
# generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]
# chk = 1
# for value in values:
# top = chk >> 25
# chk = (chk & 0x1ffffff) << 5 ^ value
# for i in range(5):
# chk ^= generator[i] if ((top >> i) & 1) else 0
# return chk
#
# def _codestring_to_array(codestring, base):
# codestring = bytes(codestring, 'utf8')
# codebase = code_strings[base]
# array = []
# for s in codestring:
# try:
# array.append(codebase.index(s))
# except ValueError:
# raise EncodingError("Character '%s' not found in codebase" % s)
# return array
. Output only the next line. | data = _codestring_to_array(test[pos + 1:], 'bech32') |
Next line prediction: <|code_start|>
def test_formatter():
"""Test if logs are being colored"""
logging.config.dictConfig(DEFAULT_LOGGING)
with LogCapture(names='bottery') as logs:
logger = logging.getLogger('bottery')
logger.debug('DEBUG')
logger.info('INFO')
logger.warning('WARN')
logger.error('ERROR')
logger.critical('CRITICAL')
records = [record for record in logs.records]
# Create a list of all records formated with ColoredFormatter
<|code_end|>
. Use current file imports:
(import logging
import pytest
from unittest import mock
from testfixtures import LogCapture
from bottery.log import DEFAULT_LOGGING, ColoredFormatter, Spinner)
and context including class names, function names, or small code snippets from other files:
# Path: bottery/log.py
# DEFAULT_LOGGING = {
# 'version': 1,
# 'disable_existing_loggers': False,
# 'handlers': {
# 'console': {
# 'class': 'logging.StreamHandler',
# 'level': 'DEBUG',
# 'formatter': 'bottery.server',
# }
# },
# 'formatters': {
# 'bottery.server': {
# 'class': 'bottery.log.ColoredFormatter',
# 'format': '%(asctime)s %(message)s',
# 'datefmt': '%H:%M:%S',
# }
# },
# 'loggers': {
# 'bottery': {
# 'handlers': ['console'],
# 'level': 'INFO',
# 'propagate': False,
# },
# },
# }
#
# class ColoredFormatter(logging.Formatter):
# def format(self, record):
# options = DEFAULT_COLORS.get(record.levelno, {})
#
# if options:
# record.msg = click.style(record.msg, **options)
#
# return super().format(record)
#
# class Spinner:
# def __init__(self, message):
# self.halo = Halo(text=message, spinner='dot', color='green')
#
# def __enter__(self):
# self.halo.__enter__()
#
# def __exit__(self, exc_type, exc_val, exc_tb):
# self.halo.__exit__(exc_tb, exc_val, exc_tb)
. Output only the next line. | colored_formatter = ColoredFormatter() |
Predict the next line after this snippet: <|code_start|>
logging.config.dictConfig(DEFAULT_LOGGING)
with LogCapture(names='bottery') as logs:
logger = logging.getLogger('bottery')
logger.debug('DEBUG')
logger.info('INFO')
logger.warning('WARN')
logger.error('ERROR')
logger.critical('CRITICAL')
records = [record for record in logs.records]
# Create a list of all records formated with ColoredFormatter
colored_formatter = ColoredFormatter()
formatted_records = [colored_formatter.format(record)
for record in records]
expected_records = [
'DEBUG',
'INFO',
'\x1b[33mWARN\x1b[0m',
'\x1b[31mERROR\x1b[0m',
'\x1b[30m\x1b[41mCRITICAL\x1b[0m'
]
assert formatted_records == expected_records
@mock.patch('bottery.log.Halo')
def test_spinner_instance(mocked_halo):
<|code_end|>
using the current file's imports:
import logging
import pytest
from unittest import mock
from testfixtures import LogCapture
from bottery.log import DEFAULT_LOGGING, ColoredFormatter, Spinner
and any relevant context from other files:
# Path: bottery/log.py
# DEFAULT_LOGGING = {
# 'version': 1,
# 'disable_existing_loggers': False,
# 'handlers': {
# 'console': {
# 'class': 'logging.StreamHandler',
# 'level': 'DEBUG',
# 'formatter': 'bottery.server',
# }
# },
# 'formatters': {
# 'bottery.server': {
# 'class': 'bottery.log.ColoredFormatter',
# 'format': '%(asctime)s %(message)s',
# 'datefmt': '%H:%M:%S',
# }
# },
# 'loggers': {
# 'bottery': {
# 'handlers': ['console'],
# 'level': 'INFO',
# 'propagate': False,
# },
# },
# }
#
# class ColoredFormatter(logging.Formatter):
# def format(self, record):
# options = DEFAULT_COLORS.get(record.levelno, {})
#
# if options:
# record.msg = click.style(record.msg, **options)
#
# return super().format(record)
#
# class Spinner:
# def __init__(self, message):
# self.halo = Halo(text=message, spinner='dot', color='green')
#
# def __enter__(self):
# self.halo.__enter__()
#
# def __exit__(self, exc_type, exc_val, exc_tb):
# self.halo.__exit__(exc_tb, exc_val, exc_tb)
. Output only the next line. | Spinner('message') |
Given the code snippet: <|code_start|>
class CaseSensitiveOptionMixin:
def clean_case_senstive(self):
if not self.kwargs.get('case_sensitive'):
self.message.text = self.message.text.lower()
class PlatformsOptionMixin:
def clean_platforms(self):
platforms = self.kwargs.get('platforms')
if platforms is None:
return
if not isinstance(platforms, (list, tuple,)):
raise Exception('platforms option must be a list or a tuple')
if self.message.platform not in platforms:
<|code_end|>
, generate the next line using the imports in this file:
import re
from bottery.exceptions import ValidationError
and context (functions, classes, or occasionally code) from other files:
# Path: bottery/exceptions.py
# class ValidationError(Exception):
# pass
. Output only the next line. | raise ValidationError('message not from {}'.format(platforms)) |
Here is a snippet: <|code_start|> if inspect.iscoroutinefunction(method):
await method()
else:
method()
def sync_view(message):
return 'pong'
async def async_view(message):
return 'pong'
@pytest.mark.asyncio
@pytest.mark.parametrize('view', [sync_view, async_view], ids=['sync', 'async']) # noqa
async def test_get_response_from_views(view, settings):
"""
Test if get_response can call an async/sync view and get its response.
"""
engine = BaseEngine()
engine.discovery_view = mock.Mock(return_value=view)
response = await engine.get_response('ping')
assert response.text == 'pong'
def test_prepare_response():
engine = BaseEngine()
response = engine.prepare_response('response', 'message')
<|code_end|>
. Write the next line using the current file imports:
import inspect
import sys
import pytest
from unittest import mock
from bottery.message import Response
from bottery.platforms import BaseEngine
from utils import AsyncMock
and context from other files:
# Path: bottery/message.py
# class Response:
# source = attr.ib()
# text = attr.ib()
#
# Path: bottery/platforms.py
# class BaseEngine:
# # Should we use ABC for required attributes and methods?
#
# def __init__(self, **kwargs):
# self.tasks = []
#
# kwargs['engine_name'] = kwargs.get('engine_name', '')
# # For each named parameters received, set it as an instance
# # attribute
# for item, value in kwargs.items():
# setattr(self, item, value)
#
# @property
# def platform(self):
# """Platform name"""
# raise NotImplementedError('platform attribute not implemented')
#
# def build_message(self):
# """
# Build Message instance according to the data received from the
# platform API.
# """
# raise NotImplementedError('build_message not implemented')
#
# async def configure(self):
# """Called by App instance to configure the platform"""
# raise NotImplementedError('configure not implemented')
#
# async def _get_response(self, message):
# """
# Get response running the view with await syntax if it is a
# coroutine function, otherwise just run it the normal way.
# """
#
# view = self.discovery_view(message)
# if not view:
# return
#
# if inspect.iscoroutinefunction(view):
# response = await view(message)
# else:
# response = view(message)
#
# return self.prepare_response(response, message)
#
# def prepare_response(self, response, message):
# if isinstance(response, Response):
# return response
#
# if isinstance(response, str):
# return Response(source=message, text=response)
#
# if response is not None:
# logger.error(
# '[%s] View should only return str or Response',
# self.engine_name,
# )
#
# return None
#
# async def prepare_get_response(self):
# get_response = self._get_response
# for middleware in reversed(settings.MIDDLEWARES):
# get_response = await middleware(get_response)
#
# return get_response
#
# async def get_response(self, message):
# f = await self.prepare_get_response()
# return await f(message)
#
# def discovery_view(self, message):
# """
# Use the new message to search for a registered view according
# to its pattern.
# """
# for handler in self.registered_handlers:
# if handler.check(message):
# return handler.view
#
# return None
#
# async def message_handler(self, data):
# """
# For each new message, build its platform specific message
# object and get a response.
# """
#
# message = self.build_message(data)
# if not message:
# logger.error(
# '[%s] Unable to build Message with data, data=%s, error',
# self.engine_name,
# data
# )
# return
#
# logger.info('[%s] New message from %s: %s', self.engine_name,
# message.user, message.text)
#
# response = await self.get_response(message)
# if response:
# await self.send_response(response)
, which may include functions, classes, or code. Output only the next line. | assert isinstance(response, Response) |
Predict the next line after this snippet: <|code_start|>
@pytest.fixture
def settings():
settings = mock.Mock()
sys.modules['settings'] = settings
yield settings
del sys.modules['settings']
def test_baseengine_platform_name_not_implemented():
"""Check if attributes from the public API raise NotImplementedError"""
<|code_end|>
using the current file's imports:
import inspect
import sys
import pytest
from unittest import mock
from bottery.message import Response
from bottery.platforms import BaseEngine
from utils import AsyncMock
and any relevant context from other files:
# Path: bottery/message.py
# class Response:
# source = attr.ib()
# text = attr.ib()
#
# Path: bottery/platforms.py
# class BaseEngine:
# # Should we use ABC for required attributes and methods?
#
# def __init__(self, **kwargs):
# self.tasks = []
#
# kwargs['engine_name'] = kwargs.get('engine_name', '')
# # For each named parameters received, set it as an instance
# # attribute
# for item, value in kwargs.items():
# setattr(self, item, value)
#
# @property
# def platform(self):
# """Platform name"""
# raise NotImplementedError('platform attribute not implemented')
#
# def build_message(self):
# """
# Build Message instance according to the data received from the
# platform API.
# """
# raise NotImplementedError('build_message not implemented')
#
# async def configure(self):
# """Called by App instance to configure the platform"""
# raise NotImplementedError('configure not implemented')
#
# async def _get_response(self, message):
# """
# Get response running the view with await syntax if it is a
# coroutine function, otherwise just run it the normal way.
# """
#
# view = self.discovery_view(message)
# if not view:
# return
#
# if inspect.iscoroutinefunction(view):
# response = await view(message)
# else:
# response = view(message)
#
# return self.prepare_response(response, message)
#
# def prepare_response(self, response, message):
# if isinstance(response, Response):
# return response
#
# if isinstance(response, str):
# return Response(source=message, text=response)
#
# if response is not None:
# logger.error(
# '[%s] View should only return str or Response',
# self.engine_name,
# )
#
# return None
#
# async def prepare_get_response(self):
# get_response = self._get_response
# for middleware in reversed(settings.MIDDLEWARES):
# get_response = await middleware(get_response)
#
# return get_response
#
# async def get_response(self, message):
# f = await self.prepare_get_response()
# return await f(message)
#
# def discovery_view(self, message):
# """
# Use the new message to search for a registered view according
# to its pattern.
# """
# for handler in self.registered_handlers:
# if handler.check(message):
# return handler.view
#
# return None
#
# async def message_handler(self, data):
# """
# For each new message, build its platform specific message
# object and get a response.
# """
#
# message = self.build_message(data)
# if not message:
# logger.error(
# '[%s] Unable to build Message with data, data=%s, error',
# self.engine_name,
# data
# )
# return
#
# logger.info('[%s] New message from %s: %s', self.engine_name,
# message.user, message.text)
#
# response = await self.get_response(message)
# if response:
# await self.send_response(response)
. Output only the next line. | engine = BaseEngine() |
Predict the next line after this snippet: <|code_start|>
@pytest.fixture
def api():
session = AsyncMock()
<|code_end|>
using the current file's imports:
import pytest
from bottery.messenger import MessengerAPI
from utils import AsyncMock
and any relevant context from other files:
# Path: bottery/messenger/api.py
# class MessengerAPI:
# url = 'https://graph.facebook.com/{0}{1}?access_token={2}'
#
# def __init__(self, token, session, version='v2.6'):
# self.token = token
# self.session = session
# self.version = version
#
# def make_url(self, method):
# return self.url.format(self.version, method, self.token)
#
# async def messages(self, user_id, text, type='RESPONSE'):
# request = {
# 'messaging_type': type,
# 'recipient': {
# 'id': user_id,
# },
# 'message': {
# 'text': text,
# },
# }
# url = self.make_url('/me/messages')
# return await self.session.post(url, json=request)
. Output only the next line. | return MessengerAPI('token', session) |
Next line prediction: <|code_start|>
def test_startproject():
runner = CliRunner()
with runner.isolated_filesystem():
project_name = 'librarybot'
project_files = {
'handlers.py',
'settings.py',
'views.py',
'wsgi.py'
}
<|code_end|>
. Use current file imports:
(import os
import bottery
from click.testing import CliRunner
from bottery.cli import cli)
and context including class names, function names, or small code snippets from other files:
# Path: bottery/cli.py
# @click.group(invoke_without_command=True)
# @click.option('--version', '-v', is_flag=True, default=False)
# @click.pass_context
# def cli(ctx, version):
# """Bottery"""
#
# # If no subcommand was given and the version flag is true, shows
# # Bottery version
# if not ctx.invoked_subcommand and version:
# click.echo(bottery.__version__)
# ctx.exit()
#
# # If no subcommand but neither the version flag, shows help message
# elif not ctx.invoked_subcommand:
# click.echo(ctx.get_help())
# ctx.exit()
. Output only the next line. | result = runner.invoke(cli, ['startproject', project_name]) |
Given the following code snippet before the placeholder: <|code_start|>
@pytest.fixture
def message():
return type('Message', (), {'text': 'ping'})
@pytest.fixture
def handler():
<|code_end|>
, predict the next line using imports from the current file:
from unittest import mock
from bottery import handlers
import pytest
and context including class names, function names, and sometimes code from other files:
# Path: bottery/handlers.py
# class CaseSensitiveOptionMixin:
# class PlatformsOptionMixin:
# class BaseHandler(PlatformsOptionMixin):
# class RegexHandler(BaseHandler):
# class MessageHandler(CaseSensitiveOptionMixin, BaseHandler):
# class StartswithHandler(CaseSensitiveOptionMixin, BaseHandler):
# class DefaultHandler(BaseHandler):
# def clean_case_senstive(self):
# def clean_platforms(self):
# def __init__(self, pattern=None, view=None, *args, **kwargs):
# def check(self, message):
# def full_clean(self):
# def match(self, message):
# def __init__(self, *args, **kwargs):
# def match(self, message):
# def match(self, message):
# def match(self, message):
# def __init__(self, view, *args, **kwargs):
# def check(self, message):
# def _handle_msg(pattern, view=None, Handler=None, *args, **kwargs):
. Output only the next line. | handler = type('TestHandler', (handlers.BaseHandler,), {}) |
Using the snippet: <|code_start|>
TEST_SETTINGS = {
"ARMSTRONG_HATBAND_RICHTEXTEDITOR": "django.forms.widgets.Textarea",
}
<|code_end|>
, determine the next line of code. You have imports:
from django.forms.widgets import Textarea
from .._utils import HatbandTestCase
from armstrong.hatband.widgets import CKEditorWidget, RichTextWidget
and context (class names, function names, or code) available:
# Path: tests/_utils.py
# class HatbandTestCase(ArmstrongTestCase):
# pass
#
# Path: armstrong/hatband/widgets/base.py
# class RichTextWidget(object):
# def __new__(cls, *args, **kwargs):
# return RICH_TEXT_BACKEND.get_backend(*args, **kwargs)
#
# Path: armstrong/hatband/widgets/ckeditor.py
# class CKEditorWidget(widgets.Textarea):
# class Media:
# js = (static("ckeditor/ckeditor.js"),)
#
# def __init__(self, attrs=None):
# final_attrs = {'class': 'ckeditor'}
# if attrs is not None:
# final_attrs.update(attrs)
# if 'class' in attrs:
# final_attrs['class'] = ' '.join((attrs['class'], 'ckeditor'))
# super(CKEditorWidget, self).__init__(attrs=final_attrs)
. Output only the next line. | class RichTextFieldTestCase(HatbandTestCase): |
Given the code snippet: <|code_start|>
TEST_SETTINGS = {
"ARMSTRONG_HATBAND_RICHTEXTEDITOR": "django.forms.widgets.Textarea",
}
class RichTextFieldTestCase(HatbandTestCase):
def test_default(self):
ckeditor = CKEditorWidget()
<|code_end|>
, generate the next line using the imports in this file:
from django.forms.widgets import Textarea
from .._utils import HatbandTestCase
from armstrong.hatband.widgets import CKEditorWidget, RichTextWidget
and context (functions, classes, or occasionally code) from other files:
# Path: tests/_utils.py
# class HatbandTestCase(ArmstrongTestCase):
# pass
#
# Path: armstrong/hatband/widgets/base.py
# class RichTextWidget(object):
# def __new__(cls, *args, **kwargs):
# return RICH_TEXT_BACKEND.get_backend(*args, **kwargs)
#
# Path: armstrong/hatband/widgets/ckeditor.py
# class CKEditorWidget(widgets.Textarea):
# class Media:
# js = (static("ckeditor/ckeditor.js"),)
#
# def __init__(self, attrs=None):
# final_attrs = {'class': 'ckeditor'}
# if attrs is not None:
# final_attrs.update(attrs)
# if 'class' in attrs:
# final_attrs['class'] = ' '.join((attrs['class'], 'ckeditor'))
# super(CKEditorWidget, self).__init__(attrs=final_attrs)
. Output only the next line. | widget = RichTextWidget() |
Based on the snippet: <|code_start|>
TEST_SETTINGS = {
"ARMSTRONG_HATBAND_RICHTEXTEDITOR": "django.forms.widgets.Textarea",
}
class RichTextFieldTestCase(HatbandTestCase):
def test_default(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from django.forms.widgets import Textarea
from .._utils import HatbandTestCase
from armstrong.hatband.widgets import CKEditorWidget, RichTextWidget
and context (classes, functions, sometimes code) from other files:
# Path: tests/_utils.py
# class HatbandTestCase(ArmstrongTestCase):
# pass
#
# Path: armstrong/hatband/widgets/base.py
# class RichTextWidget(object):
# def __new__(cls, *args, **kwargs):
# return RICH_TEXT_BACKEND.get_backend(*args, **kwargs)
#
# Path: armstrong/hatband/widgets/ckeditor.py
# class CKEditorWidget(widgets.Textarea):
# class Media:
# js = (static("ckeditor/ckeditor.js"),)
#
# def __init__(self, attrs=None):
# final_attrs = {'class': 'ckeditor'}
# if attrs is not None:
# final_attrs.update(attrs)
# if 'class' in attrs:
# final_attrs['class'] = ' '.join((attrs['class'], 'ckeditor'))
# super(CKEditorWidget, self).__init__(attrs=final_attrs)
. Output only the next line. | ckeditor = CKEditorWidget() |
Given the following code snippet before the placeholder: <|code_start|> ])
class ArmstrongBaseMixin(object):
url_prefix = "armstrong"
class GenericKeyFacetsMixin(ArmstrongBaseMixin):
url = "search/generickey/facets/"
def get_urls(self):
urlpatterns = patterns('',
url(r"^%s/%s$" % (self.url_prefix, self.url),
self.admin_view(self.generic_key_facets),
name="generic_key_facets",
)
)
return urlpatterns + super(GenericKeyFacetsMixin, self).get_urls()
def generic_key_facets(self, request):
"""Find all available facets/Models for VisualSearch"""
excluded_apps = Q(app_label__in=EXCLUDED_APPS_FROM_FACETS)
excluded_models = Q()
for app_label, model in EXCLUDED_MODELS_FROM_FACETS:
excluded_models = excluded_models | Q(app_label=app_label,
model=model)
values = "model", "app_label", "id"
content_types = ContentType.objects.values_list(*values) \
.exclude(excluded_apps | excluded_models)
<|code_end|>
, predict the next line using imports from the current file:
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.db.models import Q
from django.http import HttpResponse
from django.http import HttpResponseBadRequest, HttpResponseNotFound
from django.core.exceptions import ObjectDoesNotExist
from django.conf.urls import patterns, url
from django.conf.urls.defaults import patterns, url
from armstrong.core.arm_layout.utils import render_model
from ..http import JsonResponse
and context including class names, function names, and sometimes code from other files:
# Path: armstrong/hatband/http.py
# class JsonResponse(HttpResponse):
# """
# Simple HttpResponse object that takes a JSON value as it's parameter
#
# TODO: Find a proper home for this.
# """
# def __init__(self, data, *args, **kwargs):
# super(JsonResponse, self).__init__(json.dumps(data), *args, **kwargs)
. Output only the next line. | return JsonResponse(dict([(str(a), {"app_label": str(b), "id": str(c)}) |
Given the following code snippet before the placeholder: <|code_start|>
class JsonResponseTestCase(HatbandTestCase):
def test_turns_body_into_json(self):
data = {
"foo": "bar",
"random": random.randint(1000, 2000),
}
<|code_end|>
, predict the next line using imports from the current file:
import json
import random
from ._utils import HatbandTestCase
from armstrong.hatband.http import JsonResponse
and context including class names, function names, and sometimes code from other files:
# Path: tests/_utils.py
# class HatbandTestCase(ArmstrongTestCase):
# pass
#
# Path: armstrong/hatband/http.py
# class JsonResponse(HttpResponse):
# """
# Simple HttpResponse object that takes a JSON value as it's parameter
#
# TODO: Find a proper home for this.
# """
# def __init__(self, data, *args, **kwargs):
# super(JsonResponse, self).__init__(json.dumps(data), *args, **kwargs)
. Output only the next line. | response = JsonResponse(data) |
Next line prediction: <|code_start|> float
Expected value of the metric from random ordering of targets.
"""
targets = np.copy(targets)
scores = []
for _ in range(100):
np.random.shuffle(targets)
scores.append(self.evaluate(qid, targets))
return np.mean(scores)
def calc_mean(self, qids, targets, preds):
"""Calculates the mean of the metric among the provided predictions.
Parameters
----------
qids : array_like of shape = [n_targets]
List of query ids. They must be grouped contiguously
(i.e. ``pyltr.util.group.check_qids`` must pass).
targets : array_like of shape = [n_targets]
List of targets.
preds : array_like of shape = [n_targets]
List of predicted scores corresponding to the targets.
Returns
-------
float
Mean of the metric over provided query groups.
"""
<|code_end|>
. Use current file imports:
(import numpy as np
from six.moves import range
from ..util.group import check_qids, get_groups
from ..util.sort import get_sorted_y)
and context including class names, function names, or small code snippets from other files:
# Path: pyltr/util/group.py
# def check_qids(qids):
# """Asserts that query ids are grouped into contiguous blocks.
#
# Note that query ids do not have to be sorted.
#
# Parameters
# ----------
# qids : array_like of shape = [n_samples]
# List of query ids.
#
# Returns
# -------
# int
# Number of unique query ids in `qids`.
#
# Raises
# ------
# ValueError
# If any two query ids are not in the same contiguous block.
# e.g. ``[1, 1, 3, 3, 2, 2, 3]``
#
# """
# seen_qids = set()
# prev_qid = None
#
# for qid in qids:
# assert qid is not None
# if qid != prev_qid:
# if qid in seen_qids:
# raise ValueError('Samples must be grouped by qid.')
# seen_qids.add(qid)
# prev_qid = qid
#
# return len(seen_qids)
#
# def get_groups(qids):
# """Makes an iterator of query groups on the provided list of query ids.
#
# Parameters
# ----------
# qids : array_like of shape = [n_samples]
# List of query ids.
#
# Yields
# ------
# row : (qid, int, int)
# Tuple of query id, from, to.
# ``[i for i, q in enumerate(qids) if q == qid] == range(from, to)``
#
# """
# prev_qid = None
# prev_limit = 0
# total = 0
#
# for i, qid in enumerate(qids):
# total += 1
# if qid != prev_qid:
# if i != prev_limit:
# yield (prev_qid, prev_limit, i)
# prev_qid = qid
# prev_limit = i
#
# if prev_limit != total:
# yield (prev_qid, prev_limit, total)
#
# Path: pyltr/util/sort.py
# def get_sorted_y(y, y_pred, check=True):
# """Returns a copy of `y` sorted by position in `y_pred`.
#
# Parameters
# ----------
# y : array_like of shape = [n_samples_in_query]
# List of sample scores for a query.
# y_pred : array_like of shape = [n_samples_in_query]
# List of predicted scores for a query.
#
# Returns
# -------
# y_sorted : array_like of shape = [n_samples_in_query]
# Copy of `y` sorted by descending order of `y_pred`.
# Ties are broken in ascending order of `y`.
#
# """
# return y[get_sorted_y_positions(y, y_pred, check=check)]
. Output only the next line. | check_qids(qids) |
Given snippet: <|code_start|> Expected value of the metric from random ordering of targets.
"""
targets = np.copy(targets)
scores = []
for _ in range(100):
np.random.shuffle(targets)
scores.append(self.evaluate(qid, targets))
return np.mean(scores)
def calc_mean(self, qids, targets, preds):
"""Calculates the mean of the metric among the provided predictions.
Parameters
----------
qids : array_like of shape = [n_targets]
List of query ids. They must be grouped contiguously
(i.e. ``pyltr.util.group.check_qids`` must pass).
targets : array_like of shape = [n_targets]
List of targets.
preds : array_like of shape = [n_targets]
List of predicted scores corresponding to the targets.
Returns
-------
float
Mean of the metric over provided query groups.
"""
check_qids(qids)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
from six.moves import range
from ..util.group import check_qids, get_groups
from ..util.sort import get_sorted_y
and context:
# Path: pyltr/util/group.py
# def check_qids(qids):
# """Asserts that query ids are grouped into contiguous blocks.
#
# Note that query ids do not have to be sorted.
#
# Parameters
# ----------
# qids : array_like of shape = [n_samples]
# List of query ids.
#
# Returns
# -------
# int
# Number of unique query ids in `qids`.
#
# Raises
# ------
# ValueError
# If any two query ids are not in the same contiguous block.
# e.g. ``[1, 1, 3, 3, 2, 2, 3]``
#
# """
# seen_qids = set()
# prev_qid = None
#
# for qid in qids:
# assert qid is not None
# if qid != prev_qid:
# if qid in seen_qids:
# raise ValueError('Samples must be grouped by qid.')
# seen_qids.add(qid)
# prev_qid = qid
#
# return len(seen_qids)
#
# def get_groups(qids):
# """Makes an iterator of query groups on the provided list of query ids.
#
# Parameters
# ----------
# qids : array_like of shape = [n_samples]
# List of query ids.
#
# Yields
# ------
# row : (qid, int, int)
# Tuple of query id, from, to.
# ``[i for i, q in enumerate(qids) if q == qid] == range(from, to)``
#
# """
# prev_qid = None
# prev_limit = 0
# total = 0
#
# for i, qid in enumerate(qids):
# total += 1
# if qid != prev_qid:
# if i != prev_limit:
# yield (prev_qid, prev_limit, i)
# prev_qid = qid
# prev_limit = i
#
# if prev_limit != total:
# yield (prev_qid, prev_limit, total)
#
# Path: pyltr/util/sort.py
# def get_sorted_y(y, y_pred, check=True):
# """Returns a copy of `y` sorted by position in `y_pred`.
#
# Parameters
# ----------
# y : array_like of shape = [n_samples_in_query]
# List of sample scores for a query.
# y_pred : array_like of shape = [n_samples_in_query]
# List of predicted scores for a query.
#
# Returns
# -------
# y_sorted : array_like of shape = [n_samples_in_query]
# Copy of `y` sorted by descending order of `y_pred`.
# Ties are broken in ascending order of `y`.
#
# """
# return y[get_sorted_y_positions(y, y_pred, check=check)]
which might include code, classes, or functions. Output only the next line. | query_groups = get_groups(qids) |
Given snippet: <|code_start|> Returns
-------
k : int or None
Value for which ``swap_delta()[i, j] == 0 for all i, j >= k``.
None if no such value.
"""
return None
def evaluate_preds(self, qid, targets, preds):
"""Evaluates the metric on a ranked list of targets.
Parameters
----------
qid : object
See `evaluate`.
targets : array_like of shape = [n_targets]
See `evaluate`.
preds : array_like of shape = [n_targets]
List of predicted scores corresponding to the targets. The
`targets` array will be sorted by these predictions before
evaluation.
Returns
-------
float
Value of the metric on the provided list of targets and
predictions.
"""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
from six.moves import range
from ..util.group import check_qids, get_groups
from ..util.sort import get_sorted_y
and context:
# Path: pyltr/util/group.py
# def check_qids(qids):
# """Asserts that query ids are grouped into contiguous blocks.
#
# Note that query ids do not have to be sorted.
#
# Parameters
# ----------
# qids : array_like of shape = [n_samples]
# List of query ids.
#
# Returns
# -------
# int
# Number of unique query ids in `qids`.
#
# Raises
# ------
# ValueError
# If any two query ids are not in the same contiguous block.
# e.g. ``[1, 1, 3, 3, 2, 2, 3]``
#
# """
# seen_qids = set()
# prev_qid = None
#
# for qid in qids:
# assert qid is not None
# if qid != prev_qid:
# if qid in seen_qids:
# raise ValueError('Samples must be grouped by qid.')
# seen_qids.add(qid)
# prev_qid = qid
#
# return len(seen_qids)
#
# def get_groups(qids):
# """Makes an iterator of query groups on the provided list of query ids.
#
# Parameters
# ----------
# qids : array_like of shape = [n_samples]
# List of query ids.
#
# Yields
# ------
# row : (qid, int, int)
# Tuple of query id, from, to.
# ``[i for i, q in enumerate(qids) if q == qid] == range(from, to)``
#
# """
# prev_qid = None
# prev_limit = 0
# total = 0
#
# for i, qid in enumerate(qids):
# total += 1
# if qid != prev_qid:
# if i != prev_limit:
# yield (prev_qid, prev_limit, i)
# prev_qid = qid
# prev_limit = i
#
# if prev_limit != total:
# yield (prev_qid, prev_limit, total)
#
# Path: pyltr/util/sort.py
# def get_sorted_y(y, y_pred, check=True):
# """Returns a copy of `y` sorted by position in `y_pred`.
#
# Parameters
# ----------
# y : array_like of shape = [n_samples_in_query]
# List of sample scores for a query.
# y_pred : array_like of shape = [n_samples_in_query]
# List of predicted scores for a query.
#
# Returns
# -------
# y_sorted : array_like of shape = [n_samples_in_query]
# Copy of `y` sorted by descending order of `y_pred`.
# Ties are broken in ascending order of `y`.
#
# """
# return y[get_sorted_y_positions(y, y_pred, check=check)]
which might include code, classes, or functions. Output only the next line. | return self.evaluate(qid, get_sorted_y(targets, preds)) |
Given snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
def main():
if not len(sys.argv) > 1:
sys.stderr.write("Missing arguments\n")
sys.exit(0)
try:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
from .reader import FileReader
and context:
# Path: quickavro/reader.py
# class FileReader(BinaryEncoder):
# """
# The :class:`FileReader` object implements :class:`quickavro.BinaryEncoder`
# and provides and interface to read Avro files.
#
# :param f: File-like object or path of file that :class:`FileReader`
# will read from.
#
# Example:
#
# .. code-block:: python
#
# with quickavro.FileReader("test.avro") as reader:
# for record in reader.records():
# print(record)
# """
#
# def __init__(self, f, header_size=INITIAL_HEADER_SIZE):
# super(FileReader, self).__init__()
# if isinstance(f, basestring):
# self.f = open(f, 'rb')
# else:
# self.f = f
# header = self.read_header(header_size)
# metadata = header.get('meta')
# self.schema = json.loads(ensure_str(metadata.get('avro.schema')))
# self.codec = ensure_str(metadata.get('avro.codec', 'null'))
# self.sync_marker = header.get('sync')
#
# def close(self):
# self.f.close()
#
# def peek(self, size):
# cur = self.f.tell()
# data = self.f.read(size)
# self.f.seek(cur)
# return data
#
# def read_block(self):
# block_count = self.read_long()
# block_length = self.read_long()
# data = self.f.read(block_length)
# if not data:
# return None
# if self.codec == "deflate":
# data = zlib.decompress(data, -15)
# elif self.codec == "snappy":
# crc = data[-4:]
# data = snappy_uncompress(data[:-4])
# if crc != crc32(data):
# raise SnappyChecksumError("Snappy CRC32 check has failed.")
# self.block_count += 1
# return data
#
# def read_blocks(self):
# while True:
# block = self.read_block()
# if not block:
# break
# for record in self.read(block):
# yield record
# sync_marker = self.f.read(16)
# if sync_marker != self.sync_marker:
# break
#
# def read_header(self, size=INITIAL_HEADER_SIZE):
# b = b""
# while True:
# data = self.f.read(size)
# if len(data) == 0:
# raise InvalidSchemaError("end of file, unable to find avro header")
# b += data
# try:
# header, offset = read_header(b)
# except _quickavro.ReadError as error:
# continue
# self.f.seek(offset)
# return header
#
# def read_long(self):
# data = self.peek(MAX_VARINT_SIZE)
# l, offset = super(FileReader, self).read_long(data)
# cur = self.f.tell()
# self.f.seek(cur+offset)
# return l
#
# def records(self):
# return self.read_blocks()
which might include code, classes, or functions. Output only the next line. | with FileReader(sys.argv[1]) as reader: |
Predict the next line for this snippet: <|code_start|>system is used to register implementations of each individual `OperationDef`.
The `OperationDef`s defined by the user in their preprocessing_fn are all
subclasses of `AnayzerDef` (except `TensorSource`, which gets converted to
`ExtractFromDict` in `tensorflow_transform.beam.analysis_graph_builder.build`).
The subclasses of `AnalyzerDef` are defined in
`tensorflow_transform.analyzer_nodes` and are implemented in
`tensorflow_transform.beam.analyzer_impls`.
This module contains the nodes that are created by
`tensorflow_transform.beam.analysis_graph_builder.build`. These nodes define
the parts of the beam graph that run a TensorFlow graph in a `beam.ParDo`,
extract `PCollections` containing tuples of tensors required by analyzers,
run the analyzers, and then create a new (deferred) TensorFlow graph where
the results of analyzers are replaced by constant tensors. This happens in a
number of phases, since an analyzer might depend on a tensor that in turn
depends on the result of another analyzer.
The `OperationDef` subclasses defined here are implemented in
`tensorflow_transform.beam.impl`.
"""
# TODO(https://issues.apache.org/jira/browse/SPARK-22674): Switch to
# `collections.namedtuple` or `typing.NamedTuple` once the Spark issue is
# resolved.
class CreateTensorBinding(
tfx_namedtuple.namedtuple(
'CreateTensorBinding',
['tensor_name', 'dtype_enum', 'is_asset_filepath', 'label']),
<|code_end|>
with the help of current file imports:
import tensorflow as tf
from tensorflow_transform import nodes
from tfx_bsl.types import tfx_namedtuple
and context from other files:
# Path: tensorflow_transform/nodes.py
# class ValueNode(
# tfx_namedtuple.namedtuple('ValueNode',
# ['parent_operation', 'value_index'])):
# class OperationDef(metaclass=abc.ABCMeta):
# class OperationNode:
# class Visitor(metaclass=abc.ABCMeta):
# class Traverser:
# class _PrintGraphVisitor(Visitor):
# def __init__(self, parent_operation, value_index: int):
# def __iter__(self):
# def num_outputs(self) -> int:
# def label(self) -> str:
# def get_field_str(self, field_name: str) -> str:
# def is_partitionable(self) -> bool:
# def cache_coder(self) -> Optional[object]:
# def __init__(self, operation_def, inputs):
# def __repr__(self):
# def operation_def(self):
# def inputs(self):
# def outputs(self):
# def apply_operation(operation_def_cls, *args, **kwargs):
# def apply_multi_output_operation(operation_def_cls, *args, **kwargs):
# def validate_value(self, value):
# def visit(self, operation_def, input_values):
# def __init__(self, visitor: Visitor):
# def visit_value_node(self, value_node: ValueNode):
# def _maybe_visit_value_node(self, value_node: ValueNode):
# def _visit_operation(self, operation: OperationNode):
# def _escape(line: str) -> str:
# def __init__(self):
# def get_dot_graph(self) -> pydot.Dot:
# def visit(self, operation_def, input_nodes) -> Tuple[pydot.Node, ...]:
# def validate_value(self, value: pydot.Node):
# def get_dot_graph(leaf_nodes: Collection[ValueNode]) -> pydot.Dot:
, which may contain function names, class names, or code. Output only the next line. | nodes.OperationDef): |
Continue the code snippet: <|code_start|># 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.
"""Common data and utilities for tf_metadata tests."""
test_feature_spec = {
# FixedLenFeatures
'fixed_categorical_int_with_range':
tf.io.FixedLenFeature(shape=[], dtype=tf.int64),
'fixed_int':
tf.io.FixedLenFeature(shape=[5], dtype=tf.int64),
'fixed_float':
tf.io.FixedLenFeature(shape=[5], dtype=tf.float32),
'fixed_string':
tf.io.FixedLenFeature(shape=[5], dtype=tf.string),
# VarLenFeatures
'var_int':
tf.io.VarLenFeature(dtype=tf.int64),
'var_float':
tf.io.VarLenFeature(dtype=tf.float32),
'var_string':
tf.io.VarLenFeature(dtype=tf.string),
}
def get_test_schema():
<|code_end|>
. Use current file imports:
import tensorflow as tf
from tensorflow_transform.tf_metadata import schema_utils
and context (classes, functions, or code) from other files:
# Path: tensorflow_transform/tf_metadata/schema_utils.py
# TENSOR_REPRESENTATION_GROUP = ''
# RAGGED_TENSOR_TAG = 'ragged_tensor'
# _DEPRECATED_LIFECYCLE_STAGES = [
# schema_pb2.DEPRECATED, schema_pb2.DISABLED, schema_pb2.PLANNED,
# schema_pb2.ALPHA, schema_pb2.DEBUG_ONLY
# ]
# _LEGACY_DEFAULT_VALUE_FOR_DTYPE = {tf.string: '', tf.int64: -1, tf.float32: -1}
# def schema_from_feature_spec(
# feature_spec: Mapping[str, common_types.FeatureSpecType],
# domains: Optional[Mapping[str, common_types.DomainType]] = None
# ) -> schema_pb2.Schema:
# def _ragged_tensor_representation_from_feature_spec(
# spec: common_types.RaggedFeature, name: str,
# domains: Dict[str, common_types.DomainType]
# ) -> Tuple[schema_pb2.Feature, List[schema_pb2.Feature],
# def _sparse_feature_from_feature_spec(spec, name, domains):
# def _feature_from_feature_spec(spec, name, domains):
# def _set_type(name, feature, dtype):
# def _set_domain(name, feature, domain):
# def schema_as_feature_spec(
# schema_proto: schema_pb2.Schema) -> SchemaAsFeatureSpecResult:
# def _get_string_domains(schema):
# def _get_domain(feature, string_domains):
# def pop_ragged_source_columns(
# name: str, tensor_representation: schema_pb2.TensorRepresentation,
# feature_by_name: Dict[str, schema_pb2.Feature]) -> schema_pb2.Feature:
# def _ragged_tensor_representation_as_feature_spec(
# name: str, tensor_representation: schema_pb2.TensorRepresentation,
# feature_by_name: Dict[str, schema_pb2.Feature],
# string_domains: Dict[str, common_types.DomainType]
# ) -> Tuple[common_types.RaggedFeature, Optional[common_types.DomainType]]:
# def _sparse_feature_as_feature_spec(feature, feature_by_name, string_domains):
# def _feature_as_feature_spec(feature, string_domains):
# def _feature_dtype(feature):
# def _fixed_shape_as_tf_shape(fixed_shape):
# def _include_in_parsing_spec(feature):
# def _legacy_schema_from_feature_spec(feature_spec, domains=None):
# def _legacy_schema_as_feature_spec(schema_proto):
# def _legacy_feature_as_feature_spec(feature):
# def _legacy_infer_default_value(feature_proto, dtype):
. Output only the next line. | return schema_utils.schema_from_feature_spec(test_feature_spec) |
Given snippet: <|code_start|>
def schema_from_feature_spec(
feature_spec: Mapping[str, common_types.FeatureSpecType],
domains: Optional[Mapping[str, common_types.DomainType]] = None
) -> schema_pb2.Schema:
"""Convert a feature spec to a Schema proto.
Args:
feature_spec: A TensorFlow feature spec
domains: (optional) a dict whose keys are feature names and values are one
of schema_pb2.IntDomain, schema_pb2.StringDomain or
schema_pb2.FloatDomain.
Returns:
A Schema proto
Raises:
ValueError: If the feature spec cannot be converted to a Schema proto.
"""
if domains is None:
domains = {}
result = schema_pb2.Schema()
# Some feature specs can only be represented with the legacy schema, in
# particular feature specs where any FixedLenFeature has default_value set.
# We represent these (and only these) using a schema with
# generate_legacy_feature_spec=True. Note the generate_legacy_feature_spec
# field is not part of the open source codebase.
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import typing
import tensorflow as tf
from typing import Dict, List, Mapping, Optional, Tuple
from tensorflow_transform import common_types
from tensorflow_transform.tf_metadata import schema_utils_legacy
from tfx_bsl.tfxio import tensor_representation_util
from tfx_bsl.types import tfx_namedtuple
from tensorflow_metadata.proto.v0 import path_pb2
from tensorflow_metadata.proto.v0 import schema_pb2
and context:
# Path: tensorflow_transform/common_types.py
# def is_ragged_feature_available() -> bool:
# def is_ragged_feature(spec: FeatureSpecType) -> bool:
#
# Path: tensorflow_transform/tf_metadata/schema_utils_legacy.py
# def should_set_generate_legacy_feature_spec(feature_spec):
# def set_generate_legacy_feature_spec(schema_proto, value):
# def get_generate_legacy_feature_spec(schema_proto):
# def check_for_unsupported_features(schema_proto):
# def get_deprecated(feature):
which might include code, classes, or functions. Output only the next line. | if schema_utils_legacy.should_set_generate_legacy_feature_spec(feature_spec): |
Using the snippet: <|code_start|># Copyright 2021 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for tensorflow_transform.annotators."""
class AnnotatorsTest(test_case.TransformTestCase):
@test_case.named_parameters(
dict(testcase_name='tf_compat_v1', use_tf_compat_v1=True),
dict(testcase_name='tf2', use_tf_compat_v1=False))
def test_annotate_asset(self, use_tf_compat_v1):
if not use_tf_compat_v1:
test_case.skip_if_not_tf2('Tensorflow 2.x required')
def foo():
<|code_end|>
, determine the next line of code. You have imports:
import tensorflow as tf
from tensorflow_transform import annotators
from tensorflow_transform import test_case
from tensorflow.python.training.tracking import base # pylint: disable=g-direct-tensorflow-import
and context (class names, function names, or code) available:
# Path: tensorflow_transform/annotators.py
# _ASSET_KEY_COLLECTION = 'tft_asset_key_collection'
# _ASSET_FILENAME_COLLECTION = 'tft_asset_filename_collection'
# _OBJECT_TRACKER = None
# VOCABULARY_SIZE_BY_NAME_COLLECTION = 'tft_vocabulary_size_by_name_collection'
# _OBJECT_TRACKER = object_tracker
# _OBJECT_TRACKER = None
# class ObjectTracker:
# def __init__(self):
# def trackable_objects(self) -> List[base.Trackable]:
# def add_trackable_object(self, trackable_object: base.Trackable,
# name: Optional[str]):
# def object_tracker_scope(object_tracker: ObjectTracker):
# def _get_object(name: str) -> Optional[base.Trackable]:
# def track_object(trackable: base.Trackable, name: Optional[str]):
# def make_and_track_object(trackable_factory_callable: Callable[[],
# base.Trackable],
# name: Optional[str] = None) -> base.Trackable:
# def get_asset_annotations(graph: tf.Graph):
# def clear_asset_annotations(graph: tf.Graph):
# def annotate_asset(asset_key: str, asset_filename: str):
# def annotate_vocab_size(vocab_filename: str, vocab_size: tf.Tensor):
#
# Path: tensorflow_transform/test_case.py
# def is_tf_api_version_1():
# def cross_named_parameters(*args):
# def _cross_test_cases(parameters_list):
# def parameters(*testcases):
# def wrapper(fn):
# def to_arg_dict(testcase):
# def cross_parameters(*args):
# def _make_placeholder(tensor_spec):
# def _graph_function_handler(input_signature):
# def wrapper(fn):
# def _run_graph(*inputs):
# def _ragged_value_as_constant(value, dtype):
# def _wrap_as_constant(value, tensor_spec):
# def _eager_function_handler(input_signature):
# def wrapper(fn):
# def _run_eagerly(*inputs): # pylint: disable=missing-docstring
# def _tf_function_function_handler(input_signature):
# def wrapper(fn):
# def is_external_environment():
# def skip_if_external_environment(reason):
# def skip_if_not_tf2(reason):
# def cross_with_function_handlers(parameters_list):
# def assertDataCloseOrEqual(self, a_data, b_data):
# def _assertValuesCloseOrEqual(self, a_value, b_value, msg=None):
# def AssertVocabularyContents(self, vocab_file_path, file_contents):
# def WriteRenderedDotFile(self, dot_string, output_file=None):
# def _NumpyArraysToLists(self, maybe_arrays):
# def _SortedDicts(self, list_of_dicts):
# def _SortedData(self, list_of_dicts_of_arrays):
# FUNCTION_HANDLERS = [
# dict(testcase_name='graph',
# function_handler=_graph_function_handler),
# dict(testcase_name='eager',
# function_handler=_eager_function_handler),
# dict(testcase_name='tf_function',
# function_handler=_tf_function_function_handler)
# ]
# class TransformTestCase(parameterized.TestCase, tf.test.TestCase):
. Output only the next line. | annotators.annotate_asset('scope/my_key', 'scope/my_value') |
Predict the next line for this snippet: <|code_start|># 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.
"""Example of sentiment analysis using IMDB movie review dataset."""
# pylint: disable=g-bad-import-order
VOCAB_SIZE = 20000
TRAIN_BATCH_SIZE = 128
TRAIN_NUM_EPOCHS = 200
NUM_TRAIN_INSTANCES = 25000
NUM_TEST_INSTANCES = 25000
REVIEW_KEY = 'review'
REVIEW_WEIGHT_KEY = 'review_weight'
LABEL_KEY = 'label'
RAW_DATA_FEATURE_SPEC = {
REVIEW_KEY: tf.io.FixedLenFeature([], tf.string),
LABEL_KEY: tf.io.FixedLenFeature([], tf.int64)
}
<|code_end|>
with the help of current file imports:
import argparse
import os
import pprint
import tempfile
import apache_beam as beam
import tensorflow as tf
import tensorflow_transform as tft
import tensorflow_transform.beam as tft_beam
from tensorflow_transform.tf_metadata import dataset_metadata
from tfx_bsl.coders.example_coder import RecordBatchToExamples
from tfx_bsl.public import tfxio
and context from other files:
# Path: tensorflow_transform/tf_metadata/dataset_metadata.py
# class DatasetMetadata:
# def __init__(self, schema: schema_pb2.Schema):
# def from_feature_spec(
# cls: Type[_DatasetMetadataType],
# feature_spec: Mapping[str, common_types.FeatureSpecType],
# domains: Optional[Mapping[str, common_types.DomainType]] = None
# ) -> _DatasetMetadataType:
# def schema(self) -> schema_pb2.Schema:
# def __eq__(self, other):
# def __ne__(self, other):
# def __repr__(self):
, which may contain function names, class names, or code. Output only the next line. | SCHEMA = dataset_metadata.DatasetMetadata.from_feature_spec( |
Given the following code snippet before the placeholder: <|code_start|># Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test metadata for tft_beam_io tests."""
_FEATURE_SPEC = {
'fixed_column': tf.io.FixedLenFeature([3], tf.string),
'list_columm': tf.io.VarLenFeature(tf.int64),
}
<|code_end|>
, predict the next line using imports from the current file:
import tensorflow as tf
from tensorflow_transform.tf_metadata import dataset_metadata
from tensorflow_metadata.proto.v0 import schema_pb2
and context including class names, function names, and sometimes code from other files:
# Path: tensorflow_transform/tf_metadata/dataset_metadata.py
# class DatasetMetadata:
# def __init__(self, schema: schema_pb2.Schema):
# def from_feature_spec(
# cls: Type[_DatasetMetadataType],
# feature_spec: Mapping[str, common_types.FeatureSpecType],
# domains: Optional[Mapping[str, common_types.DomainType]] = None
# ) -> _DatasetMetadataType:
# def schema(self) -> schema_pb2.Schema:
# def __eq__(self, other):
# def __ne__(self, other):
# def __repr__(self):
. Output only the next line. | COMPLETE_METADATA = dataset_metadata.DatasetMetadata.from_feature_spec( |
Given snippet: <|code_start|> 'native-country',
]
NUMERIC_FEATURE_KEYS = [
'age',
'capital-gain',
'capital-loss',
'hours-per-week',
]
OPTIONAL_NUMERIC_FEATURE_KEYS = [
'education-num',
]
LABEL_KEY = 'label'
ORDERED_CSV_COLUMNS = [
'age', 'workclass', 'fnlwgt', 'education', 'education-num',
'marital-status', 'occupation', 'relationship', 'race', 'sex',
'capital-gain', 'capital-loss', 'hours-per-week', 'native-country', 'label'
]
RAW_DATA_FEATURE_SPEC = dict([(name, tf.io.FixedLenFeature([], tf.string))
for name in CATEGORICAL_FEATURE_KEYS] +
[(name, tf.io.FixedLenFeature([], tf.float32))
for name in NUMERIC_FEATURE_KEYS] +
[(name, tf.io.VarLenFeature(tf.float32))
for name in OPTIONAL_NUMERIC_FEATURE_KEYS] +
[(LABEL_KEY,
tf.io.FixedLenFeature([], tf.string))])
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import argparse
import os
import tempfile
import apache_beam as beam
import tensorflow.compat.v2 as tf
import tensorflow_transform as tft
import tensorflow_transform.beam as tft_beam
from tensorflow_transform.tf_metadata import dataset_metadata
from tfx_bsl.coders.example_coder import RecordBatchToExamples
from tfx_bsl.public import tfxio
and context:
# Path: tensorflow_transform/tf_metadata/dataset_metadata.py
# class DatasetMetadata:
# def __init__(self, schema: schema_pb2.Schema):
# def from_feature_spec(
# cls: Type[_DatasetMetadataType],
# feature_spec: Mapping[str, common_types.FeatureSpecType],
# domains: Optional[Mapping[str, common_types.DomainType]] = None
# ) -> _DatasetMetadataType:
# def schema(self) -> schema_pb2.Schema:
# def __eq__(self, other):
# def __ne__(self, other):
# def __repr__(self):
which might include code, classes, or functions. Output only the next line. | _SCHEMA = dataset_metadata.DatasetMetadata.from_feature_spec( |
Given the code snippet: <|code_start|>class TF2UtilsTest(test_case.TransformTestCase):
def test_strip_and_get_tensors_and_control_dependencies(self):
@tf.function(input_signature=[tf.TensorSpec([], dtype=tf.int64)])
def func(x):
with tf.init_scope():
initializer_1 = tf.lookup.KeyValueTensorInitializer(
[0, 1, 2], ['a', 'b', 'c'],
key_dtype=tf.int64,
value_dtype=tf.string)
table_1 = tf.lookup.StaticHashTable(initializer_1, default_value='NAN')
size = table_1.size()
initializer_2 = tf.lookup.KeyValueTensorInitializer(
['a', 'b', 'c'], [-1, 0, 1],
key_dtype=tf.string,
value_dtype=tf.int64)
table_2 = tf.lookup.StaticHashTable(initializer_2, default_value=-777)
y = table_1.lookup(x)
_ = table_2.lookup(y)
z = x + size
return {'x': x, 'z': z}
concrete_function = func.get_concrete_function()
flat_outputs = tf.nest.flatten(
concrete_function.structured_outputs, expand_composites=True)
expected_flat_outputs = [t.op.inputs[0] for t in flat_outputs]
expected_control_dependencies = itertools.chain(
*[t.op.control_inputs for t in flat_outputs])
new_flat_outputs, control_dependencies = (
<|code_end|>
, generate the next line using the imports in this file:
import itertools
import tensorflow as tf
from tensorflow_transform import tf2_utils
from tensorflow_transform import test_case
and context (functions, classes, or occasionally code) from other files:
# Path: tensorflow_transform/tf2_utils.py
# def use_tf_compat_v1(force_tf_compat_v1: bool) -> bool:
# def strip_and_get_tensors_and_control_dependencies(
# flat_tensor_list: Iterable[tf.Tensor]
# ) -> Tuple[Iterable[tf.Tensor], Iterable[tf.Operation]]:
# def supply_missing_tensor(batch_size: int, tensor_shape: tf.TensorShape,
# tensor_dtype: tf.DType) -> tf.Tensor:
# def supply_missing_inputs(
# structured_inputs: Mapping[str, common_types.TensorType],
# batch_size: int,
# missing_keys: Optional[Collection[str]] = None
# ) -> Mapping[str, common_types.TensorType]:
# def get_structured_inputs_from_func_graph(
# func_graph: FuncGraph) -> Mapping[str, common_types.TensorType]:
#
# Path: tensorflow_transform/test_case.py
# def is_tf_api_version_1():
# def cross_named_parameters(*args):
# def _cross_test_cases(parameters_list):
# def parameters(*testcases):
# def wrapper(fn):
# def to_arg_dict(testcase):
# def cross_parameters(*args):
# def _make_placeholder(tensor_spec):
# def _graph_function_handler(input_signature):
# def wrapper(fn):
# def _run_graph(*inputs):
# def _ragged_value_as_constant(value, dtype):
# def _wrap_as_constant(value, tensor_spec):
# def _eager_function_handler(input_signature):
# def wrapper(fn):
# def _run_eagerly(*inputs): # pylint: disable=missing-docstring
# def _tf_function_function_handler(input_signature):
# def wrapper(fn):
# def is_external_environment():
# def skip_if_external_environment(reason):
# def skip_if_not_tf2(reason):
# def cross_with_function_handlers(parameters_list):
# def assertDataCloseOrEqual(self, a_data, b_data):
# def _assertValuesCloseOrEqual(self, a_value, b_value, msg=None):
# def AssertVocabularyContents(self, vocab_file_path, file_contents):
# def WriteRenderedDotFile(self, dot_string, output_file=None):
# def _NumpyArraysToLists(self, maybe_arrays):
# def _SortedDicts(self, list_of_dicts):
# def _SortedData(self, list_of_dicts_of_arrays):
# FUNCTION_HANDLERS = [
# dict(testcase_name='graph',
# function_handler=_graph_function_handler),
# dict(testcase_name='eager',
# function_handler=_eager_function_handler),
# dict(testcase_name='tf_function',
# function_handler=_tf_function_function_handler)
# ]
# class TransformTestCase(parameterized.TestCase, tf.test.TestCase):
. Output only the next line. | tf2_utils.strip_and_get_tensors_and_control_dependencies(flat_outputs)) |
Predict the next line for this snippet: <|code_start|># See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for tensorflow_transform.tf2_utils."""
_TEST_BATCH_SIZES = [1, 10]
_TEST_DTYPES = [
tf.int16,
tf.int32,
tf.int64,
tf.float32,
tf.float64,
tf.string,
]
_TEST_TENSORS_TYPES = [
(lambda dtype: tf.TensorSpec([None], dtype=dtype), tf.Tensor, []),
(lambda dtype: tf.TensorSpec([None, 2], dtype=dtype), tf.Tensor, [2]),
(lambda dtype: tf.RaggedTensorSpec([None, None], dtype=dtype),
tf.RaggedTensor, [None]),
(
lambda dtype: tf.RaggedTensorSpec( # pylint: disable=g-long-lambda
[None, None, 2],
dtype=dtype,
ragged_rank=1),
tf.RaggedTensor,
[None, 2]),
]
<|code_end|>
with the help of current file imports:
import itertools
import tensorflow as tf
from tensorflow_transform import tf2_utils
from tensorflow_transform import test_case
and context from other files:
# Path: tensorflow_transform/tf2_utils.py
# def use_tf_compat_v1(force_tf_compat_v1: bool) -> bool:
# def strip_and_get_tensors_and_control_dependencies(
# flat_tensor_list: Iterable[tf.Tensor]
# ) -> Tuple[Iterable[tf.Tensor], Iterable[tf.Operation]]:
# def supply_missing_tensor(batch_size: int, tensor_shape: tf.TensorShape,
# tensor_dtype: tf.DType) -> tf.Tensor:
# def supply_missing_inputs(
# structured_inputs: Mapping[str, common_types.TensorType],
# batch_size: int,
# missing_keys: Optional[Collection[str]] = None
# ) -> Mapping[str, common_types.TensorType]:
# def get_structured_inputs_from_func_graph(
# func_graph: FuncGraph) -> Mapping[str, common_types.TensorType]:
#
# Path: tensorflow_transform/test_case.py
# def is_tf_api_version_1():
# def cross_named_parameters(*args):
# def _cross_test_cases(parameters_list):
# def parameters(*testcases):
# def wrapper(fn):
# def to_arg_dict(testcase):
# def cross_parameters(*args):
# def _make_placeholder(tensor_spec):
# def _graph_function_handler(input_signature):
# def wrapper(fn):
# def _run_graph(*inputs):
# def _ragged_value_as_constant(value, dtype):
# def _wrap_as_constant(value, tensor_spec):
# def _eager_function_handler(input_signature):
# def wrapper(fn):
# def _run_eagerly(*inputs): # pylint: disable=missing-docstring
# def _tf_function_function_handler(input_signature):
# def wrapper(fn):
# def is_external_environment():
# def skip_if_external_environment(reason):
# def skip_if_not_tf2(reason):
# def cross_with_function_handlers(parameters_list):
# def assertDataCloseOrEqual(self, a_data, b_data):
# def _assertValuesCloseOrEqual(self, a_value, b_value, msg=None):
# def AssertVocabularyContents(self, vocab_file_path, file_contents):
# def WriteRenderedDotFile(self, dot_string, output_file=None):
# def _NumpyArraysToLists(self, maybe_arrays):
# def _SortedDicts(self, list_of_dicts):
# def _SortedData(self, list_of_dicts_of_arrays):
# FUNCTION_HANDLERS = [
# dict(testcase_name='graph',
# function_handler=_graph_function_handler),
# dict(testcase_name='eager',
# function_handler=_eager_function_handler),
# dict(testcase_name='tf_function',
# function_handler=_tf_function_function_handler)
# ]
# class TransformTestCase(parameterized.TestCase, tf.test.TestCase):
, which may contain function names, class names, or code. Output only the next line. | class TF2UtilsTest(test_case.TransformTestCase): |
Based on the 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.
"""In-memory representation of all metadata associated with a dataset."""
_DatasetMetadataType = TypeVar('_DatasetMetadataType', bound='DatasetMetadata')
class DatasetMetadata:
"""A collection of metadata about a dataset.
This is an in-memory representation that may be serialized and deserialized to
and from a variety of disk representations.
"""
def __init__(self, schema: schema_pb2.Schema):
self._schema = schema
@classmethod
def from_feature_spec(
cls: Type[_DatasetMetadataType],
<|code_end|>
, predict the immediate next line with the help of imports:
from typing import Mapping, Optional, Type, TypeVar
from tensorflow_transform import common_types
from tensorflow_transform.tf_metadata import schema_utils
from tensorflow_metadata.proto.v0 import schema_pb2
and context (classes, functions, sometimes code) from other files:
# Path: tensorflow_transform/common_types.py
# def is_ragged_feature_available() -> bool:
# def is_ragged_feature(spec: FeatureSpecType) -> bool:
#
# Path: tensorflow_transform/tf_metadata/schema_utils.py
# TENSOR_REPRESENTATION_GROUP = ''
# RAGGED_TENSOR_TAG = 'ragged_tensor'
# _DEPRECATED_LIFECYCLE_STAGES = [
# schema_pb2.DEPRECATED, schema_pb2.DISABLED, schema_pb2.PLANNED,
# schema_pb2.ALPHA, schema_pb2.DEBUG_ONLY
# ]
# _LEGACY_DEFAULT_VALUE_FOR_DTYPE = {tf.string: '', tf.int64: -1, tf.float32: -1}
# def schema_from_feature_spec(
# feature_spec: Mapping[str, common_types.FeatureSpecType],
# domains: Optional[Mapping[str, common_types.DomainType]] = None
# ) -> schema_pb2.Schema:
# def _ragged_tensor_representation_from_feature_spec(
# spec: common_types.RaggedFeature, name: str,
# domains: Dict[str, common_types.DomainType]
# ) -> Tuple[schema_pb2.Feature, List[schema_pb2.Feature],
# def _sparse_feature_from_feature_spec(spec, name, domains):
# def _feature_from_feature_spec(spec, name, domains):
# def _set_type(name, feature, dtype):
# def _set_domain(name, feature, domain):
# def schema_as_feature_spec(
# schema_proto: schema_pb2.Schema) -> SchemaAsFeatureSpecResult:
# def _get_string_domains(schema):
# def _get_domain(feature, string_domains):
# def pop_ragged_source_columns(
# name: str, tensor_representation: schema_pb2.TensorRepresentation,
# feature_by_name: Dict[str, schema_pb2.Feature]) -> schema_pb2.Feature:
# def _ragged_tensor_representation_as_feature_spec(
# name: str, tensor_representation: schema_pb2.TensorRepresentation,
# feature_by_name: Dict[str, schema_pb2.Feature],
# string_domains: Dict[str, common_types.DomainType]
# ) -> Tuple[common_types.RaggedFeature, Optional[common_types.DomainType]]:
# def _sparse_feature_as_feature_spec(feature, feature_by_name, string_domains):
# def _feature_as_feature_spec(feature, string_domains):
# def _feature_dtype(feature):
# def _fixed_shape_as_tf_shape(fixed_shape):
# def _include_in_parsing_spec(feature):
# def _legacy_schema_from_feature_spec(feature_spec, domains=None):
# def _legacy_schema_as_feature_spec(schema_proto):
# def _legacy_feature_as_feature_spec(feature):
# def _legacy_infer_default_value(feature_proto, dtype):
. Output only the next line. | feature_spec: Mapping[str, common_types.FeatureSpecType], |
Given the code snippet: <|code_start|>#
# 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.
"""In-memory representation of all metadata associated with a dataset."""
_DatasetMetadataType = TypeVar('_DatasetMetadataType', bound='DatasetMetadata')
class DatasetMetadata:
"""A collection of metadata about a dataset.
This is an in-memory representation that may be serialized and deserialized to
and from a variety of disk representations.
"""
def __init__(self, schema: schema_pb2.Schema):
self._schema = schema
@classmethod
def from_feature_spec(
cls: Type[_DatasetMetadataType],
feature_spec: Mapping[str, common_types.FeatureSpecType],
domains: Optional[Mapping[str, common_types.DomainType]] = None
) -> _DatasetMetadataType:
"""Creates a DatasetMetadata from a TF feature spec dict."""
<|code_end|>
, generate the next line using the imports in this file:
from typing import Mapping, Optional, Type, TypeVar
from tensorflow_transform import common_types
from tensorflow_transform.tf_metadata import schema_utils
from tensorflow_metadata.proto.v0 import schema_pb2
and context (functions, classes, or occasionally code) from other files:
# Path: tensorflow_transform/common_types.py
# def is_ragged_feature_available() -> bool:
# def is_ragged_feature(spec: FeatureSpecType) -> bool:
#
# Path: tensorflow_transform/tf_metadata/schema_utils.py
# TENSOR_REPRESENTATION_GROUP = ''
# RAGGED_TENSOR_TAG = 'ragged_tensor'
# _DEPRECATED_LIFECYCLE_STAGES = [
# schema_pb2.DEPRECATED, schema_pb2.DISABLED, schema_pb2.PLANNED,
# schema_pb2.ALPHA, schema_pb2.DEBUG_ONLY
# ]
# _LEGACY_DEFAULT_VALUE_FOR_DTYPE = {tf.string: '', tf.int64: -1, tf.float32: -1}
# def schema_from_feature_spec(
# feature_spec: Mapping[str, common_types.FeatureSpecType],
# domains: Optional[Mapping[str, common_types.DomainType]] = None
# ) -> schema_pb2.Schema:
# def _ragged_tensor_representation_from_feature_spec(
# spec: common_types.RaggedFeature, name: str,
# domains: Dict[str, common_types.DomainType]
# ) -> Tuple[schema_pb2.Feature, List[schema_pb2.Feature],
# def _sparse_feature_from_feature_spec(spec, name, domains):
# def _feature_from_feature_spec(spec, name, domains):
# def _set_type(name, feature, dtype):
# def _set_domain(name, feature, domain):
# def schema_as_feature_spec(
# schema_proto: schema_pb2.Schema) -> SchemaAsFeatureSpecResult:
# def _get_string_domains(schema):
# def _get_domain(feature, string_domains):
# def pop_ragged_source_columns(
# name: str, tensor_representation: schema_pb2.TensorRepresentation,
# feature_by_name: Dict[str, schema_pb2.Feature]) -> schema_pb2.Feature:
# def _ragged_tensor_representation_as_feature_spec(
# name: str, tensor_representation: schema_pb2.TensorRepresentation,
# feature_by_name: Dict[str, schema_pb2.Feature],
# string_domains: Dict[str, common_types.DomainType]
# ) -> Tuple[common_types.RaggedFeature, Optional[common_types.DomainType]]:
# def _sparse_feature_as_feature_spec(feature, feature_by_name, string_domains):
# def _feature_as_feature_spec(feature, string_domains):
# def _feature_dtype(feature):
# def _fixed_shape_as_tf_shape(fixed_shape):
# def _include_in_parsing_spec(feature):
# def _legacy_schema_from_feature_spec(feature_spec, domains=None):
# def _legacy_schema_as_feature_spec(schema_proto):
# def _legacy_feature_as_feature_spec(feature):
# def _legacy_infer_default_value(feature_proto, dtype):
. Output only the next line. | return cls(schema_utils.schema_from_feature_spec(feature_spec, domains)) |
Given the following code snippet before the placeholder: <|code_start|>#
# 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.
"""Utilities to read and write metadata in standardized versioned formats."""
def read_metadata(path):
"""Load metadata in JSON format from a path into a new DatasetMetadata."""
schema_file = os.path.join(path, 'schema.pbtxt')
legacy_schema_file = os.path.join(path, 'v1-json', 'schema.json')
if file_io.file_exists(schema_file):
text_proto = file_io.FileIO(schema_file, 'r').read()
schema_proto = text_format.Parse(text_proto, schema_pb2.Schema(),
allow_unknown_extension=True)
elif file_io.file_exists(legacy_schema_file):
schema_json = file_io.FileIO(legacy_schema_file, 'r').read()
schema_proto = _parse_schema_json(schema_json)
else:
raise IOError(
'Schema file {} does not exist and neither did legacy format file '
'{}'.format(schema_file, legacy_schema_file))
<|code_end|>
, predict the next line using imports from the current file:
import json
import os
import tensorflow as tf
from tensorflow_transform.tf_metadata import dataset_metadata
from tensorflow_transform.tf_metadata import schema_utils
from google.protobuf import text_format
from tensorflow.python.lib.io import file_io # pylint: disable=g-direct-tensorflow-import
from tensorflow_metadata.proto.v0 import schema_pb2
and context including class names, function names, and sometimes code from other files:
# Path: tensorflow_transform/tf_metadata/dataset_metadata.py
# class DatasetMetadata:
# def __init__(self, schema: schema_pb2.Schema):
# def from_feature_spec(
# cls: Type[_DatasetMetadataType],
# feature_spec: Mapping[str, common_types.FeatureSpecType],
# domains: Optional[Mapping[str, common_types.DomainType]] = None
# ) -> _DatasetMetadataType:
# def schema(self) -> schema_pb2.Schema:
# def __eq__(self, other):
# def __ne__(self, other):
# def __repr__(self):
#
# Path: tensorflow_transform/tf_metadata/schema_utils.py
# TENSOR_REPRESENTATION_GROUP = ''
# RAGGED_TENSOR_TAG = 'ragged_tensor'
# _DEPRECATED_LIFECYCLE_STAGES = [
# schema_pb2.DEPRECATED, schema_pb2.DISABLED, schema_pb2.PLANNED,
# schema_pb2.ALPHA, schema_pb2.DEBUG_ONLY
# ]
# _LEGACY_DEFAULT_VALUE_FOR_DTYPE = {tf.string: '', tf.int64: -1, tf.float32: -1}
# def schema_from_feature_spec(
# feature_spec: Mapping[str, common_types.FeatureSpecType],
# domains: Optional[Mapping[str, common_types.DomainType]] = None
# ) -> schema_pb2.Schema:
# def _ragged_tensor_representation_from_feature_spec(
# spec: common_types.RaggedFeature, name: str,
# domains: Dict[str, common_types.DomainType]
# ) -> Tuple[schema_pb2.Feature, List[schema_pb2.Feature],
# def _sparse_feature_from_feature_spec(spec, name, domains):
# def _feature_from_feature_spec(spec, name, domains):
# def _set_type(name, feature, dtype):
# def _set_domain(name, feature, domain):
# def schema_as_feature_spec(
# schema_proto: schema_pb2.Schema) -> SchemaAsFeatureSpecResult:
# def _get_string_domains(schema):
# def _get_domain(feature, string_domains):
# def pop_ragged_source_columns(
# name: str, tensor_representation: schema_pb2.TensorRepresentation,
# feature_by_name: Dict[str, schema_pb2.Feature]) -> schema_pb2.Feature:
# def _ragged_tensor_representation_as_feature_spec(
# name: str, tensor_representation: schema_pb2.TensorRepresentation,
# feature_by_name: Dict[str, schema_pb2.Feature],
# string_domains: Dict[str, common_types.DomainType]
# ) -> Tuple[common_types.RaggedFeature, Optional[common_types.DomainType]]:
# def _sparse_feature_as_feature_spec(feature, feature_by_name, string_domains):
# def _feature_as_feature_spec(feature, string_domains):
# def _feature_dtype(feature):
# def _fixed_shape_as_tf_shape(fixed_shape):
# def _include_in_parsing_spec(feature):
# def _legacy_schema_from_feature_spec(feature_spec, domains=None):
# def _legacy_schema_as_feature_spec(schema_proto):
# def _legacy_feature_as_feature_spec(feature):
# def _legacy_infer_default_value(feature_proto, dtype):
. Output only the next line. | return dataset_metadata.DatasetMetadata(schema_proto) |
Continue the code snippet: <|code_start|>
def read_metadata(path):
"""Load metadata in JSON format from a path into a new DatasetMetadata."""
schema_file = os.path.join(path, 'schema.pbtxt')
legacy_schema_file = os.path.join(path, 'v1-json', 'schema.json')
if file_io.file_exists(schema_file):
text_proto = file_io.FileIO(schema_file, 'r').read()
schema_proto = text_format.Parse(text_proto, schema_pb2.Schema(),
allow_unknown_extension=True)
elif file_io.file_exists(legacy_schema_file):
schema_json = file_io.FileIO(legacy_schema_file, 'r').read()
schema_proto = _parse_schema_json(schema_json)
else:
raise IOError(
'Schema file {} does not exist and neither did legacy format file '
'{}'.format(schema_file, legacy_schema_file))
return dataset_metadata.DatasetMetadata(schema_proto)
def _parse_schema_json(schema_json):
"""Translate a JSON schema into a Schema proto."""
schema_dict = json.loads(schema_json)
feature_spec = {
feature_dict['name']: _column_schema_from_json(feature_dict)
for feature_dict in schema_dict.get('feature', [])
}
domains = {
feature_dict['name']: _domain_from_json(feature_dict['domain'])
for feature_dict in schema_dict.get('feature', [])
}
<|code_end|>
. Use current file imports:
import json
import os
import tensorflow as tf
from tensorflow_transform.tf_metadata import dataset_metadata
from tensorflow_transform.tf_metadata import schema_utils
from google.protobuf import text_format
from tensorflow.python.lib.io import file_io # pylint: disable=g-direct-tensorflow-import
from tensorflow_metadata.proto.v0 import schema_pb2
and context (classes, functions, or code) from other files:
# Path: tensorflow_transform/tf_metadata/dataset_metadata.py
# class DatasetMetadata:
# def __init__(self, schema: schema_pb2.Schema):
# def from_feature_spec(
# cls: Type[_DatasetMetadataType],
# feature_spec: Mapping[str, common_types.FeatureSpecType],
# domains: Optional[Mapping[str, common_types.DomainType]] = None
# ) -> _DatasetMetadataType:
# def schema(self) -> schema_pb2.Schema:
# def __eq__(self, other):
# def __ne__(self, other):
# def __repr__(self):
#
# Path: tensorflow_transform/tf_metadata/schema_utils.py
# TENSOR_REPRESENTATION_GROUP = ''
# RAGGED_TENSOR_TAG = 'ragged_tensor'
# _DEPRECATED_LIFECYCLE_STAGES = [
# schema_pb2.DEPRECATED, schema_pb2.DISABLED, schema_pb2.PLANNED,
# schema_pb2.ALPHA, schema_pb2.DEBUG_ONLY
# ]
# _LEGACY_DEFAULT_VALUE_FOR_DTYPE = {tf.string: '', tf.int64: -1, tf.float32: -1}
# def schema_from_feature_spec(
# feature_spec: Mapping[str, common_types.FeatureSpecType],
# domains: Optional[Mapping[str, common_types.DomainType]] = None
# ) -> schema_pb2.Schema:
# def _ragged_tensor_representation_from_feature_spec(
# spec: common_types.RaggedFeature, name: str,
# domains: Dict[str, common_types.DomainType]
# ) -> Tuple[schema_pb2.Feature, List[schema_pb2.Feature],
# def _sparse_feature_from_feature_spec(spec, name, domains):
# def _feature_from_feature_spec(spec, name, domains):
# def _set_type(name, feature, dtype):
# def _set_domain(name, feature, domain):
# def schema_as_feature_spec(
# schema_proto: schema_pb2.Schema) -> SchemaAsFeatureSpecResult:
# def _get_string_domains(schema):
# def _get_domain(feature, string_domains):
# def pop_ragged_source_columns(
# name: str, tensor_representation: schema_pb2.TensorRepresentation,
# feature_by_name: Dict[str, schema_pb2.Feature]) -> schema_pb2.Feature:
# def _ragged_tensor_representation_as_feature_spec(
# name: str, tensor_representation: schema_pb2.TensorRepresentation,
# feature_by_name: Dict[str, schema_pb2.Feature],
# string_domains: Dict[str, common_types.DomainType]
# ) -> Tuple[common_types.RaggedFeature, Optional[common_types.DomainType]]:
# def _sparse_feature_as_feature_spec(feature, feature_by_name, string_domains):
# def _feature_as_feature_spec(feature, string_domains):
# def _feature_dtype(feature):
# def _fixed_shape_as_tf_shape(fixed_shape):
# def _include_in_parsing_spec(feature):
# def _legacy_schema_from_feature_spec(feature_spec, domains=None):
# def _legacy_schema_as_feature_spec(schema_proto):
# def _legacy_feature_as_feature_spec(feature):
# def _legacy_infer_default_value(feature_proto, dtype):
. Output only the next line. | return schema_utils.schema_from_feature_spec(feature_spec, domains) |
Here is a snippet: <|code_start|> x * np.exp(0.5 * hr * np.square(x)),
x * np.exp(0.5 * hl * np.square(x)))
_INVERSE_TUKEY_HH_ND_TESTS = [dict(
testcase_name='inverse_tukey_1D',
samples=np.array(
_tukey_hh(np.linspace(-5.0, 5.0, 20), 1.0, 2.0), np.float32),
hl=np.float32(1.0),
hr=np.float32(2.0),
expected_output=np.linspace(-5.0, 5.0, 20, dtype=np.float32)
), dict(
testcase_name='inverse_tukey_3D',
samples=np.array(
_tukey_hh(np.linspace(-5.0, 5.0, 100).reshape((10, 5, 2)),
np.linspace(1.0, 1.5, 10).reshape((1, 5, 2)),
np.linspace(2.0, 2.5, 10).reshape((1, 5, 2))), np.float32),
hl=np.linspace(1.0, 1.5, 10, dtype=np.float32).reshape((1, 5, 2)),
hr=np.linspace(2.0, 2.5, 10, dtype=np.float32).reshape((1, 5, 2)),
expected_output=np.linspace(
-5.0, 5.0, 100, dtype=np.float32).reshape((10, 5, 2))
)]
class GaussianizationTest(test_case.TransformTestCase):
@test_case.named_parameters(
_MEAN_SCALE_SCALAR_TEST,
_MEAN_SCALE_ND_TEST
)
def test_tukey_hh_l_mean_and_scale(self, h_params, expected_outputs):
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
from tensorflow_transform import gaussianization
from tensorflow_transform import test_case
and context from other files:
# Path: tensorflow_transform/gaussianization.py
# def tukey_hh_l_mean_and_scale(h_params):
# def _tukey_hh_l_skewness_and_kurtosis(h_params):
# def skewness_num(h1, h2):
# def skewness_den(h):
# def kurtosis_den_part(h):
# def _binary_search(error_fn, low_value, high_value):
# def _params_to_errors(h, delta_h, l_skewness_and_kurtosis):
# def compute_tukey_hh_params(l_skewness_and_kurtosis):
# def lambert_w(x):
# def newton_update(count, w):
# def inverse_tukey_hh(x, hl, hr):
# def one_side(x, h):
#
# Path: tensorflow_transform/test_case.py
# def is_tf_api_version_1():
# def cross_named_parameters(*args):
# def _cross_test_cases(parameters_list):
# def parameters(*testcases):
# def wrapper(fn):
# def to_arg_dict(testcase):
# def cross_parameters(*args):
# def _make_placeholder(tensor_spec):
# def _graph_function_handler(input_signature):
# def wrapper(fn):
# def _run_graph(*inputs):
# def _ragged_value_as_constant(value, dtype):
# def _wrap_as_constant(value, tensor_spec):
# def _eager_function_handler(input_signature):
# def wrapper(fn):
# def _run_eagerly(*inputs): # pylint: disable=missing-docstring
# def _tf_function_function_handler(input_signature):
# def wrapper(fn):
# def is_external_environment():
# def skip_if_external_environment(reason):
# def skip_if_not_tf2(reason):
# def cross_with_function_handlers(parameters_list):
# def assertDataCloseOrEqual(self, a_data, b_data):
# def _assertValuesCloseOrEqual(self, a_value, b_value, msg=None):
# def AssertVocabularyContents(self, vocab_file_path, file_contents):
# def WriteRenderedDotFile(self, dot_string, output_file=None):
# def _NumpyArraysToLists(self, maybe_arrays):
# def _SortedDicts(self, list_of_dicts):
# def _SortedData(self, list_of_dicts_of_arrays):
# FUNCTION_HANDLERS = [
# dict(testcase_name='graph',
# function_handler=_graph_function_handler),
# dict(testcase_name='eager',
# function_handler=_eager_function_handler),
# dict(testcase_name='tf_function',
# function_handler=_tf_function_function_handler)
# ]
# class TransformTestCase(parameterized.TestCase, tf.test.TestCase):
, which may include functions, classes, or code. Output only the next line. | outputs = gaussianization.tukey_hh_l_mean_and_scale(h_params) |
Based on the snippet: <|code_start|> expected_output=np.float32(-5.0)
)]
def _tukey_hh(x, hl, hr):
return np.where(
x > 0.0,
x * np.exp(0.5 * hr * np.square(x)),
x * np.exp(0.5 * hl * np.square(x)))
_INVERSE_TUKEY_HH_ND_TESTS = [dict(
testcase_name='inverse_tukey_1D',
samples=np.array(
_tukey_hh(np.linspace(-5.0, 5.0, 20), 1.0, 2.0), np.float32),
hl=np.float32(1.0),
hr=np.float32(2.0),
expected_output=np.linspace(-5.0, 5.0, 20, dtype=np.float32)
), dict(
testcase_name='inverse_tukey_3D',
samples=np.array(
_tukey_hh(np.linspace(-5.0, 5.0, 100).reshape((10, 5, 2)),
np.linspace(1.0, 1.5, 10).reshape((1, 5, 2)),
np.linspace(2.0, 2.5, 10).reshape((1, 5, 2))), np.float32),
hl=np.linspace(1.0, 1.5, 10, dtype=np.float32).reshape((1, 5, 2)),
hr=np.linspace(2.0, 2.5, 10, dtype=np.float32).reshape((1, 5, 2)),
expected_output=np.linspace(
-5.0, 5.0, 100, dtype=np.float32).reshape((10, 5, 2))
)]
<|code_end|>
, predict the immediate next line with the help of imports:
import numpy as np
from tensorflow_transform import gaussianization
from tensorflow_transform import test_case
and context (classes, functions, sometimes code) from other files:
# Path: tensorflow_transform/gaussianization.py
# def tukey_hh_l_mean_and_scale(h_params):
# def _tukey_hh_l_skewness_and_kurtosis(h_params):
# def skewness_num(h1, h2):
# def skewness_den(h):
# def kurtosis_den_part(h):
# def _binary_search(error_fn, low_value, high_value):
# def _params_to_errors(h, delta_h, l_skewness_and_kurtosis):
# def compute_tukey_hh_params(l_skewness_and_kurtosis):
# def lambert_w(x):
# def newton_update(count, w):
# def inverse_tukey_hh(x, hl, hr):
# def one_side(x, h):
#
# Path: tensorflow_transform/test_case.py
# def is_tf_api_version_1():
# def cross_named_parameters(*args):
# def _cross_test_cases(parameters_list):
# def parameters(*testcases):
# def wrapper(fn):
# def to_arg_dict(testcase):
# def cross_parameters(*args):
# def _make_placeholder(tensor_spec):
# def _graph_function_handler(input_signature):
# def wrapper(fn):
# def _run_graph(*inputs):
# def _ragged_value_as_constant(value, dtype):
# def _wrap_as_constant(value, tensor_spec):
# def _eager_function_handler(input_signature):
# def wrapper(fn):
# def _run_eagerly(*inputs): # pylint: disable=missing-docstring
# def _tf_function_function_handler(input_signature):
# def wrapper(fn):
# def is_external_environment():
# def skip_if_external_environment(reason):
# def skip_if_not_tf2(reason):
# def cross_with_function_handlers(parameters_list):
# def assertDataCloseOrEqual(self, a_data, b_data):
# def _assertValuesCloseOrEqual(self, a_value, b_value, msg=None):
# def AssertVocabularyContents(self, vocab_file_path, file_contents):
# def WriteRenderedDotFile(self, dot_string, output_file=None):
# def _NumpyArraysToLists(self, maybe_arrays):
# def _SortedDicts(self, list_of_dicts):
# def _SortedData(self, list_of_dicts_of_arrays):
# FUNCTION_HANDLERS = [
# dict(testcase_name='graph',
# function_handler=_graph_function_handler),
# dict(testcase_name='eager',
# function_handler=_eager_function_handler),
# dict(testcase_name='tf_function',
# function_handler=_tf_function_function_handler)
# ]
# class TransformTestCase(parameterized.TestCase, tf.test.TestCase):
. Output only the next line. | class GaussianizationTest(test_case.TransformTestCase): |
Continue the code snippet: <|code_start|># 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.
"""Tests for simple_example."""
_EXPECTED_TRANSFORMED_OUTPUT = [
{
'x_centered': 1.0,
'y_normalized': 1.0,
'x_centered_times_y_normalized': 1.0,
's_integerized': 0,
},
{
'x_centered': 0.0,
'y_normalized': 0.5,
'x_centered_times_y_normalized': 0.0,
's_integerized': 1,
},
{
'x_centered': -1.0,
'y_normalized': 0.0,
'x_centered_times_y_normalized': -0.0,
's_integerized': 0,
},
]
<|code_end|>
. Use current file imports:
import tensorflow as tf
import simple_example
from tensorflow_transform.beam import tft_unit
and context (classes, functions, or code) from other files:
# Path: tensorflow_transform/beam/tft_unit.py
# def metadata_from_feature_spec(feature_spec, domains=None):
# def canonical_numeric_dtype(dtype):
# def make_feature_spec_wrapper(make_feature_spec, *args):
# def _format_example_as_numpy_dict(example, feature_shape_dict):
# def has_ran(self):
# def metrics(self):
# def __exit__(self, exc_type, exc_val, exc_tb):
# def _makeTestPipeline(self):
# def assertMetricsCounterEqual(self, metrics, name, expected_count,
# namespaces_list=None):
# def assertAnalyzerOutputs(self,
# input_data,
# input_metadata,
# analyzer_fn,
# expected_outputs,
# test_data=None,
# desired_batch_size=None,
# beam_pipeline=None,
# force_tf_compat_v1=False,
# output_record_batches=False):
# def preprocessing_fn(inputs):
# def assertAnalyzeAndTransformResults(self,
# input_data,
# input_metadata,
# preprocessing_fn,
# expected_data=None,
# expected_metadata=None,
# expected_vocab_file_contents=None,
# test_data=None,
# desired_batch_size=None,
# beam_pipeline=None,
# temp_dir=None,
# force_tf_compat_v1=False,
# output_record_batches=False):
# class TransformTestCase(test_case.TransformTestCase):
# class _TestPipeline(beam.Pipeline):
. Output only the next line. | class SimpleExampleTest(tft_unit.TransformTestCase): |
Based on the snippet: <|code_start|># Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for saved_model_loader."""
def _create_test_saved_model_dir():
export_path = os.path.join(tempfile.mkdtemp(), 'export')
with tf.compat.v1.Graph().as_default():
with tf.compat.v1.Session().as_default() as session:
input_float = tf.compat.v1.placeholder(tf.float32, shape=[1])
output = (input_float - 2.0) / 5.0
inputs = {'x': input_float}
outputs = {'x_scaled': output}
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import tempfile
import tensorflow as tf
import unittest
from tensorflow_transform.saved import saved_transform_io
and context (classes, functions, sometimes code) from other files:
# Path: tensorflow_transform/saved/saved_transform_io.py
# _MANGLED_TENSOR_NAME_RE = re.compile(
# r'(.*)\$(indices|values|dense_shape|dense_tensor)$')
# _PARTITIONED_VARIABLE_NAME_RE = re.compile(r'^(.*)/part_(\d*)$')
# def _update_legacy_signature(signature):
# def _load_transform_saved_model(transform_savedmodel_dir):
# def _expand_input_map(logical_input_map, input_signature):
# def _maybe_register_addon_ops():
# def _try_import(name):
# def _partially_apply_saved_transform_impl(saved_model_dir,
# logical_input_map,
# tensor_replacement_map=None):
# def lookup_remapped_tensor(tensor_name):
# def lookup_tensor_or_sparse_or_composite_tensor(tensor_info):
# def partially_apply_saved_transform_internal(saved_model_dir,
# logical_input_map,
# tensor_replacement_map=None):
# def write_saved_transform_from_session(
# session, inputs, outputs, export_path, as_text=False):
# def exported_as_v1(transform_savedmodel_dir):
. Output only the next line. | saved_transform_io.write_saved_transform_from_session( |
Continue the code snippet: <|code_start|> # Check for inputs that were not part of the input signature.
unexpected_inputs = (
set(logical_input_map.keys()) - set(input_signature.keys()))
if unexpected_inputs:
raise ValueError('Unexpected inputs '
'to transform: {}'.format(unexpected_inputs))
# Create a map from tensor names in the graph to be imported, to the tensors
# specified in `input_tensors`.
input_map = _expand_input_map(logical_input_map, input_signature)
input_map.update(asset_tensor_dict)
if tensor_replacement_map:
input_map.update(tensor_replacement_map)
# unique_name may produce e.g. transform_5. The result has no trailing slash.
scope = graph.unique_name('transform', mark_as_used=False)
# unique_name returns an "absolute" name while we want a name relative to the
# current scope. Therefore, we check if the current name stack is non-empty,
# and if so, strip out the existing name scope.
if graph.get_name_scope():
current_name_scope = graph.get_name_scope() + '/'
assert scope.startswith(current_name_scope)
import_scope = scope[len(current_name_scope):]
else:
import_scope = scope
# If the saved_model contained py_funcs, will reinsert them in the graph
# here and update their associated token in the model.
<|code_end|>
. Use current file imports:
import importlib
import os
import re
import tensorflow as tf
from tensorflow_transform.py_func import pyfunc_helper
from tensorflow_transform.saved import constants
from tensorflow_transform.saved import saved_model_loader
from tensorflow.core.protobuf import struct_pb2
from tensorflow.python.framework import ops
from tensorflow.python.saved_model import nested_structure_coder
from tensorflow.python.training import saver as tf_saver
and context (classes, functions, or code) from other files:
# Path: tensorflow_transform/py_func/pyfunc_helper.py
# _PYFUNC_COLLECTION_KEY = 'pyfuncs'
# class _PyFuncDef(tfx_namedtuple.namedtuple('_PyFuncDef', ['token', 'func'])):
# def from_proto(attr_value, import_scope=None):
# def from_proto_string(proto_str, import_scope=None):
# def to_proto(self, export_scope=None):
# def insert_pyfunc(func, Tout, stateful, name, *args): # pylint: disable=invalid-name
# def register_pyfuncs_from_saved_transform(graph, meta_graph, loaded_in_tf2):
#
# Path: tensorflow_transform/saved/constants.py
# TRANSFORM_TAG = 'transform'
# TRANSFORM_SIGNATURE = 'transform_signature'
#
# Path: tensorflow_transform/saved/saved_model_loader.py
# def parse_saved_model(saved_model_dir):
# def _choose_meta_graph_def_internal(saved_model, tags):
# def choose_meta_graph_def(saved_model):
# def choose_meta_graph_def_and_raise(saved_model):
# def get_asset_tensors(saved_model_dir, meta_graph_def_to_load):
. Output only the next line. | _ = pyfunc_helper.register_pyfuncs_from_saved_transform( |
Given the code snippet: <|code_start|> new_tensor_info.coo_sparse.indices_tensor_name = (
original_tensor_info.name)
elif original_tensor_type == 'values':
new_tensor_info.dtype = original_tensor_info.dtype
new_tensor_info.coo_sparse.values_tensor_name = (
original_tensor_info.name)
elif original_tensor_type == 'dense_shape':
new_tensor_info.coo_sparse.dense_shape_tensor_name = (
original_tensor_info.name)
else:
new_tensor_info.CopyFrom(tensor_info_map[original_name])
del tensor_info_map[original_name]
def _load_transform_saved_model(transform_savedmodel_dir):
"""Load a SavedModel representing a transform function from disk.
Args:
transform_savedmodel_dir: a SavedModel directory.
Returns:
A tuple with a `MetaGraphDef` proto, the input and outputs of a
`SignatureDef` proto, and a dict from tensor names to absolute paths for
asset filepaths.
"""
saved_model = saved_model_loader.parse_saved_model(
transform_savedmodel_dir)
meta_graph_def = saved_model_loader.choose_meta_graph_def_and_raise(
saved_model)
<|code_end|>
, generate the next line using the imports in this file:
import importlib
import os
import re
import tensorflow as tf
from tensorflow_transform.py_func import pyfunc_helper
from tensorflow_transform.saved import constants
from tensorflow_transform.saved import saved_model_loader
from tensorflow.core.protobuf import struct_pb2
from tensorflow.python.framework import ops
from tensorflow.python.saved_model import nested_structure_coder
from tensorflow.python.training import saver as tf_saver
and context (functions, classes, or occasionally code) from other files:
# Path: tensorflow_transform/py_func/pyfunc_helper.py
# _PYFUNC_COLLECTION_KEY = 'pyfuncs'
# class _PyFuncDef(tfx_namedtuple.namedtuple('_PyFuncDef', ['token', 'func'])):
# def from_proto(attr_value, import_scope=None):
# def from_proto_string(proto_str, import_scope=None):
# def to_proto(self, export_scope=None):
# def insert_pyfunc(func, Tout, stateful, name, *args): # pylint: disable=invalid-name
# def register_pyfuncs_from_saved_transform(graph, meta_graph, loaded_in_tf2):
#
# Path: tensorflow_transform/saved/constants.py
# TRANSFORM_TAG = 'transform'
# TRANSFORM_SIGNATURE = 'transform_signature'
#
# Path: tensorflow_transform/saved/saved_model_loader.py
# def parse_saved_model(saved_model_dir):
# def _choose_meta_graph_def_internal(saved_model, tags):
# def choose_meta_graph_def(saved_model):
# def choose_meta_graph_def_and_raise(saved_model):
# def get_asset_tensors(saved_model_dir, meta_graph_def_to_load):
. Output only the next line. | signature = meta_graph_def.signature_def[constants.TRANSFORM_SIGNATURE] |
Predict the next line for this snippet: <|code_start|> assert (name not in tensor_info_map or
tensor_info_map[name].WhichOneof('encoding') == 'coo_sparse')
new_tensor_info = tensor_info_map[name]
original_tensor_type = match.group(2)
if original_tensor_type == 'indices':
new_tensor_info.coo_sparse.indices_tensor_name = (
original_tensor_info.name)
elif original_tensor_type == 'values':
new_tensor_info.dtype = original_tensor_info.dtype
new_tensor_info.coo_sparse.values_tensor_name = (
original_tensor_info.name)
elif original_tensor_type == 'dense_shape':
new_tensor_info.coo_sparse.dense_shape_tensor_name = (
original_tensor_info.name)
else:
new_tensor_info.CopyFrom(tensor_info_map[original_name])
del tensor_info_map[original_name]
def _load_transform_saved_model(transform_savedmodel_dir):
"""Load a SavedModel representing a transform function from disk.
Args:
transform_savedmodel_dir: a SavedModel directory.
Returns:
A tuple with a `MetaGraphDef` proto, the input and outputs of a
`SignatureDef` proto, and a dict from tensor names to absolute paths for
asset filepaths.
"""
<|code_end|>
with the help of current file imports:
import importlib
import os
import re
import tensorflow as tf
from tensorflow_transform.py_func import pyfunc_helper
from tensorflow_transform.saved import constants
from tensorflow_transform.saved import saved_model_loader
from tensorflow.core.protobuf import struct_pb2
from tensorflow.python.framework import ops
from tensorflow.python.saved_model import nested_structure_coder
from tensorflow.python.training import saver as tf_saver
and context from other files:
# Path: tensorflow_transform/py_func/pyfunc_helper.py
# _PYFUNC_COLLECTION_KEY = 'pyfuncs'
# class _PyFuncDef(tfx_namedtuple.namedtuple('_PyFuncDef', ['token', 'func'])):
# def from_proto(attr_value, import_scope=None):
# def from_proto_string(proto_str, import_scope=None):
# def to_proto(self, export_scope=None):
# def insert_pyfunc(func, Tout, stateful, name, *args): # pylint: disable=invalid-name
# def register_pyfuncs_from_saved_transform(graph, meta_graph, loaded_in_tf2):
#
# Path: tensorflow_transform/saved/constants.py
# TRANSFORM_TAG = 'transform'
# TRANSFORM_SIGNATURE = 'transform_signature'
#
# Path: tensorflow_transform/saved/saved_model_loader.py
# def parse_saved_model(saved_model_dir):
# def _choose_meta_graph_def_internal(saved_model, tags):
# def choose_meta_graph_def(saved_model):
# def choose_meta_graph_def_and_raise(saved_model):
# def get_asset_tensors(saved_model_dir, meta_graph_def_to_load):
, which may contain function names, class names, or code. Output only the next line. | saved_model = saved_model_loader.parse_saved_model( |
Using the snippet: <|code_start|># Copyright 2022 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for dataset_metadata."""
class DatasetSchemaTest(unittest.TestCase):
def test_sanity(self):
metadata = dataset_metadata.DatasetMetadata.from_feature_spec(
<|code_end|>
, determine the next line of code. You have imports:
from tensorflow_transform.tf_metadata import test_common
from tensorflow_transform.tf_metadata import dataset_metadata
import unittest
and context (class names, function names, or code) available:
# Path: tensorflow_transform/tf_metadata/test_common.py
# def get_test_schema():
#
# Path: tensorflow_transform/tf_metadata/dataset_metadata.py
# class DatasetMetadata:
# def __init__(self, schema: schema_pb2.Schema):
# def from_feature_spec(
# cls: Type[_DatasetMetadataType],
# feature_spec: Mapping[str, common_types.FeatureSpecType],
# domains: Optional[Mapping[str, common_types.DomainType]] = None
# ) -> _DatasetMetadataType:
# def schema(self) -> schema_pb2.Schema:
# def __eq__(self, other):
# def __ne__(self, other):
# def __repr__(self):
. Output only the next line. | test_common.test_feature_spec) |
Given the code snippet: <|code_start|> value being registered may also be a function. The registered function will
be invoked as follows:
outputs = my_function(inputs, operation, extra_args)
where inputs, operation, extra_args and outputs are the same as for the
PTransform case.
Args:
operation_def_subclass: The class of attributes that is being registered.
Should be a subclass of `tensorflow_transform.nodes.OperationDef`.
tags: A set of string tags belonging to `EnvironmentTags`. If
provided, the PTransform will be registered against all of them.
Returns:
A class decorator that registers a PTransform or function as an
implementation of the OperationDef subclass.
"""
def register(ptransform_class):
assert isinstance(ptransform_class, type)
assert issubclass(ptransform_class, beam.PTransform)
assert tags is None or (tag in _ALLOWED_PTRANSFORM_TAGS for tag in tags)
_PTRANSFORM_BY_OPERATION_DEF_SUBCLASS[
operation_def_subclass].add_ptransform(ptransform_class, tags)
return ptransform_class
return register
<|code_end|>
, generate the next line using the imports in this file:
import collections
import enum
import os
import uuid
import apache_beam as beam
from apache_beam.typehints import Union
from tensorflow_transform import nodes
from tfx_bsl.telemetry import util
from tfx_bsl.types import tfx_namedtuple
and context (functions, classes, or occasionally code) from other files:
# Path: tensorflow_transform/nodes.py
# class ValueNode(
# tfx_namedtuple.namedtuple('ValueNode',
# ['parent_operation', 'value_index'])):
# class OperationDef(metaclass=abc.ABCMeta):
# class OperationNode:
# class Visitor(metaclass=abc.ABCMeta):
# class Traverser:
# class _PrintGraphVisitor(Visitor):
# def __init__(self, parent_operation, value_index: int):
# def __iter__(self):
# def num_outputs(self) -> int:
# def label(self) -> str:
# def get_field_str(self, field_name: str) -> str:
# def is_partitionable(self) -> bool:
# def cache_coder(self) -> Optional[object]:
# def __init__(self, operation_def, inputs):
# def __repr__(self):
# def operation_def(self):
# def inputs(self):
# def outputs(self):
# def apply_operation(operation_def_cls, *args, **kwargs):
# def apply_multi_output_operation(operation_def_cls, *args, **kwargs):
# def validate_value(self, value):
# def visit(self, operation_def, input_values):
# def __init__(self, visitor: Visitor):
# def visit_value_node(self, value_node: ValueNode):
# def _maybe_visit_value_node(self, value_node: ValueNode):
# def _visit_operation(self, operation: OperationNode):
# def _escape(line: str) -> str:
# def __init__(self):
# def get_dot_graph(self) -> pydot.Dot:
# def visit(self, operation_def, input_nodes) -> Tuple[pydot.Node, ...]:
# def validate_value(self, value: pydot.Node):
# def get_dot_graph(leaf_nodes: Collection[ValueNode]) -> pydot.Dot:
. Output only the next line. | class ConstructBeamPipelineVisitor(nodes.Visitor): |
Predict the next line after this snippet: <|code_start|> return None
@classmethod
def get_passthrough_keys(cls) -> Iterable[str]:
"""Retrieves a user set passthrough_keys, None if not set."""
state = cls._get_topmost_state_frame()
if state.passthrough_keys is not None:
return state.passthrough_keys
return set()
@classmethod
def get_use_deep_copy_optimization(cls) -> bool:
"""Retrieves a user set use_deep_copy_optimization, None if not set."""
state = cls._get_topmost_state_frame()
if state.use_deep_copy_optimization is not None:
return state.use_deep_copy_optimization
return False
@classmethod
def _get_force_tf_compat_v1(cls) -> bool:
"""Retrieves flag force_tf_compat_v1."""
state = cls._get_topmost_state_frame()
if state.force_tf_compat_v1 is not None:
return state.force_tf_compat_v1
return False
@classmethod
def get_use_tf_compat_v1(cls) -> bool:
"""Computes use_tf_compat_v1 from TF environment and force_tf_compat_v1."""
force_tf_compat_v1 = cls._get_force_tf_compat_v1()
<|code_end|>
using the current file's imports:
import os
import threading
import tensorflow as tf
from typing import Iterable, Optional
from tensorflow_transform import tf2_utils
from tfx_bsl.types import tfx_namedtuple
and any relevant context from other files:
# Path: tensorflow_transform/tf2_utils.py
# def use_tf_compat_v1(force_tf_compat_v1: bool) -> bool:
# def strip_and_get_tensors_and_control_dependencies(
# flat_tensor_list: Iterable[tf.Tensor]
# ) -> Tuple[Iterable[tf.Tensor], Iterable[tf.Operation]]:
# def supply_missing_tensor(batch_size: int, tensor_shape: tf.TensorShape,
# tensor_dtype: tf.DType) -> tf.Tensor:
# def supply_missing_inputs(
# structured_inputs: Mapping[str, common_types.TensorType],
# batch_size: int,
# missing_keys: Optional[Collection[str]] = None
# ) -> Mapping[str, common_types.TensorType]:
# def get_structured_inputs_from_func_graph(
# func_graph: FuncGraph) -> Mapping[str, common_types.TensorType]:
. Output only the next line. | return tf2_utils.use_tf_compat_v1(force_tf_compat_v1) |
Here is a snippet: <|code_start|> 'x': _FEATURE_BY_NAME['x'],
'ragged$row_lengths_1': _FEATURE_BY_NAME['ragged$row_lengths_1'],
'ragged$row_lengths_2': _FEATURE_BY_NAME['ragged$row_lengths_2'],
},
},
{
'testcase_name':
'uniform_3d',
'name':
'ragged_uniform_3d',
'tensor_representation':
text_format.Parse(
"""
ragged_tensor {
feature_path { step: "ragged$value" }
partition { row_length: "ragged$row_lengths_1" }
partition { uniform_row_length: 3 }
}
""", schema_pb2.TensorRepresentation()),
'feature_by_name':
_FEATURE_BY_NAME.copy(),
'expected_value_feature':
_FEATURE_BY_NAME['ragged$value'],
'truncated_feature_by_name': {
'x': _FEATURE_BY_NAME['x'],
'ragged$row_lengths_2': _FEATURE_BY_NAME['ragged$row_lengths_2'],
},
},
]
<|code_end|>
. Write the next line using the current file imports:
import tensorflow as tf
from tensorflow_transform import common_types
from google.protobuf import text_format
from tensorflow_metadata.proto.v0 import schema_pb2
and context from other files:
# Path: tensorflow_transform/common_types.py
# def is_ragged_feature_available() -> bool:
# def is_ragged_feature(spec: FeatureSpecType) -> bool:
, which may include functions, classes, or code. Output only the next line. | if common_types.is_ragged_feature_available(): |
Given the code snippet: <|code_start|> key: "capital-gain"
value { float_list: { value: 0 } }
}
feature {
key: "capital-loss"
value { float_list: { value: 0 } }
}
feature {
key: "hours-per-week"
value { float_list: { value: 40 } }
}
feature {
key: "native-country"
value { bytes_list: { value: "United-States" } }
}
}
"""
_MODEL_NAME = 'my_model'
_CLASSIFICATION_REQUEST_TEXT_PB = """model_spec { name: "%s" }
input {
example_list {
examples {
%s
}
}
}""" % (_MODEL_NAME, _PREDICT_TF_EXAMPLE_TEXT_PB)
<|code_end|>
, generate the next line using the imports in this file:
import os
import shutil
import tensorflow.compat.v2 as tf
import census_example_common
import census_example_v2
import local_model_server
from tensorflow_transform import test_case as tft_test_case
from google.protobuf import text_format
from tensorflow.python import tf2 # pylint: disable=g-direct-tensorflow-import
and context (functions, classes, or occasionally code) from other files:
# Path: tensorflow_transform/test_case.py
# def is_tf_api_version_1():
# def cross_named_parameters(*args):
# def _cross_test_cases(parameters_list):
# def parameters(*testcases):
# def wrapper(fn):
# def to_arg_dict(testcase):
# def cross_parameters(*args):
# def _make_placeholder(tensor_spec):
# def _graph_function_handler(input_signature):
# def wrapper(fn):
# def _run_graph(*inputs):
# def _ragged_value_as_constant(value, dtype):
# def _wrap_as_constant(value, tensor_spec):
# def _eager_function_handler(input_signature):
# def wrapper(fn):
# def _run_eagerly(*inputs): # pylint: disable=missing-docstring
# def _tf_function_function_handler(input_signature):
# def wrapper(fn):
# def is_external_environment():
# def skip_if_external_environment(reason):
# def skip_if_not_tf2(reason):
# def cross_with_function_handlers(parameters_list):
# def assertDataCloseOrEqual(self, a_data, b_data):
# def _assertValuesCloseOrEqual(self, a_value, b_value, msg=None):
# def AssertVocabularyContents(self, vocab_file_path, file_contents):
# def WriteRenderedDotFile(self, dot_string, output_file=None):
# def _NumpyArraysToLists(self, maybe_arrays):
# def _SortedDicts(self, list_of_dicts):
# def _SortedData(self, list_of_dicts_of_arrays):
# FUNCTION_HANDLERS = [
# dict(testcase_name='graph',
# function_handler=_graph_function_handler),
# dict(testcase_name='eager',
# function_handler=_eager_function_handler),
# dict(testcase_name='tf_function',
# function_handler=_tf_function_function_handler)
# ]
# class TransformTestCase(parameterized.TestCase, tf.test.TestCase):
. Output only the next line. | class CensusExampleV2Test(tft_test_case.TransformTestCase): |
Based on the snippet: <|code_start|> # ReadTransformFn never inspects this directory.
transform_fn_dir = os.path.join(
path, tft.TFTransformOutput.TRANSFORM_FN_DIR)
transformed_metadata_dir = os.path.join(
path, tft.TFTransformOutput.TRANSFORMED_METADATA_DIR)
metadata_io.write_metadata(test_metadata.COMPLETE_METADATA,
transformed_metadata_dir)
with beam.Pipeline() as pipeline:
saved_model_dir_pcoll, metadata = (
pipeline | transform_fn_io.ReadTransformFn(path))
beam_test_util.assert_that(
saved_model_dir_pcoll,
beam_test_util.equal_to([transform_fn_dir]),
label='AssertSavedModelDir')
# NOTE: metadata is currently read in a non-deferred manner.
self.assertEqual(metadata, test_metadata.COMPLETE_METADATA)
def testWriteTransformFn(self):
transform_output_dir = os.path.join(self.get_temp_dir(), 'output')
with beam.Pipeline() as pipeline:
# Create an empty directory for the source saved model dir.
saved_model_dir = os.path.join(self.get_temp_dir(), 'source')
file_io.recursive_create_dir(saved_model_dir)
saved_model_dir_pcoll = (
pipeline | 'CreateSavedModelDir' >> beam.Create([saved_model_dir]))
# Combine test metadata with a dict of PCollections resolving futures.
deferred_metadata = pipeline | 'CreateDeferredMetadata' >> beam.Create(
[test_metadata.COMPLETE_METADATA])
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import apache_beam as beam
import tensorflow as tf
import tensorflow_transform as tft
from apache_beam.testing import util as beam_test_util
from tensorflow_transform.beam import tft_unit
from tensorflow_transform.beam.tft_beam_io import beam_metadata_io
from tensorflow_transform.beam.tft_beam_io import transform_fn_io
from tensorflow_transform.beam.tft_beam_io import test_metadata
from tensorflow_transform.tf_metadata import metadata_io
from tensorflow.python.lib.io import file_io # pylint: disable=g-direct-tensorflow-import
and context (classes, functions, sometimes code) from other files:
# Path: tensorflow_transform/beam/tft_unit.py
# def metadata_from_feature_spec(feature_spec, domains=None):
# def canonical_numeric_dtype(dtype):
# def make_feature_spec_wrapper(make_feature_spec, *args):
# def _format_example_as_numpy_dict(example, feature_shape_dict):
# def has_ran(self):
# def metrics(self):
# def __exit__(self, exc_type, exc_val, exc_tb):
# def _makeTestPipeline(self):
# def assertMetricsCounterEqual(self, metrics, name, expected_count,
# namespaces_list=None):
# def assertAnalyzerOutputs(self,
# input_data,
# input_metadata,
# analyzer_fn,
# expected_outputs,
# test_data=None,
# desired_batch_size=None,
# beam_pipeline=None,
# force_tf_compat_v1=False,
# output_record_batches=False):
# def preprocessing_fn(inputs):
# def assertAnalyzeAndTransformResults(self,
# input_data,
# input_metadata,
# preprocessing_fn,
# expected_data=None,
# expected_metadata=None,
# expected_vocab_file_contents=None,
# test_data=None,
# desired_batch_size=None,
# beam_pipeline=None,
# temp_dir=None,
# force_tf_compat_v1=False,
# output_record_batches=False):
# class TransformTestCase(test_case.TransformTestCase):
# class _TestPipeline(beam.Pipeline):
#
# Path: tensorflow_transform/beam/tft_beam_io/beam_metadata_io.py
# class BeamDatasetMetadata(
# tfx_namedtuple.namedtuple(
# 'BeamDatasetMetadata',
# ['dataset_metadata', 'deferred_metadata', 'asset_map'])):
# class WriteMetadata(beam.PTransform):
# def schema(self):
# def __init__(self, path, pipeline, write_to_unique_subdirectory=False):
# def _extract_input_pvalues(self, metadata):
# def expand(self, metadata):
# def write_metadata_output(metadata):
#
# Path: tensorflow_transform/beam/tft_beam_io/transform_fn_io.py
# TRANSFORMED_METADATA_DIR = tft.TFTransformOutput.TRANSFORMED_METADATA_DIR
# TRANSFORM_FN_DIR = tft.TFTransformOutput.TRANSFORM_FN_DIR
# def _copy_tree_to_unique_temp_dir(source, base_temp_dir_path):
# def _copy_tree(source, destination):
# def __init__(self, path):
# def _extract_input_pvalues(self, transform_fn):
# def expand(self, transform_fn):
# def publish_outputs(unused_element, metadata_source_path,
# transform_fn_source_path):
# def __init__(self, path):
# def expand(self, pvalue):
# class WriteTransformFn(beam.PTransform):
# class ReadTransformFn(beam.PTransform):
#
# Path: tensorflow_transform/beam/tft_beam_io/test_metadata.py
# _FEATURE_SPEC = {
# 'fixed_column': tf.io.FixedLenFeature([3], tf.string),
# 'list_columm': tf.io.VarLenFeature(tf.int64),
# }
# COMPLETE_METADATA = dataset_metadata.DatasetMetadata.from_feature_spec(
# _FEATURE_SPEC, domains={'list_columm': schema_pb2.IntDomain(min=-1, max=5)})
# INCOMPLETE_METADATA = dataset_metadata.DatasetMetadata.from_feature_spec(
# _FEATURE_SPEC,
# # Values will be overridden by those in COMPLETE_METADATA
# domains={'list_columm': schema_pb2.IntDomain(min=0, max=0)})
#
# Path: tensorflow_transform/tf_metadata/metadata_io.py
# def read_metadata(path):
# def _parse_schema_json(schema_json):
# def _column_schema_from_json(feature_dict):
# def _domain_from_json(domain):
# def maybe_to_int(s):
# def _dtype_from_json(domain):
# def write_metadata(metadata, path):
# def _convert_scalar_or_list(fn, scalar_or_list):
. Output only the next line. | metadata = beam_metadata_io.BeamDatasetMetadata( |
Continue the code snippet: <|code_start|># 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.
"""Tests for transform_fn_io."""
mock = tf.compat.v1.test.mock
# TODO(varshaan): Remove global variable and use a class attribute.
_COPY_TREE_TO_UNIQUE_TEMP_DIR_CALLED = False
class TransformFnIoTest(tft_unit.TransformTestCase):
def testReadTransformFn(self):
path = self.get_temp_dir()
# NOTE: we don't need to create or write to the transform_fn directory since
# ReadTransformFn never inspects this directory.
transform_fn_dir = os.path.join(
path, tft.TFTransformOutput.TRANSFORM_FN_DIR)
transformed_metadata_dir = os.path.join(
path, tft.TFTransformOutput.TRANSFORMED_METADATA_DIR)
metadata_io.write_metadata(test_metadata.COMPLETE_METADATA,
transformed_metadata_dir)
with beam.Pipeline() as pipeline:
saved_model_dir_pcoll, metadata = (
<|code_end|>
. Use current file imports:
import os
import apache_beam as beam
import tensorflow as tf
import tensorflow_transform as tft
from apache_beam.testing import util as beam_test_util
from tensorflow_transform.beam import tft_unit
from tensorflow_transform.beam.tft_beam_io import beam_metadata_io
from tensorflow_transform.beam.tft_beam_io import transform_fn_io
from tensorflow_transform.beam.tft_beam_io import test_metadata
from tensorflow_transform.tf_metadata import metadata_io
from tensorflow.python.lib.io import file_io # pylint: disable=g-direct-tensorflow-import
and context (classes, functions, or code) from other files:
# Path: tensorflow_transform/beam/tft_unit.py
# def metadata_from_feature_spec(feature_spec, domains=None):
# def canonical_numeric_dtype(dtype):
# def make_feature_spec_wrapper(make_feature_spec, *args):
# def _format_example_as_numpy_dict(example, feature_shape_dict):
# def has_ran(self):
# def metrics(self):
# def __exit__(self, exc_type, exc_val, exc_tb):
# def _makeTestPipeline(self):
# def assertMetricsCounterEqual(self, metrics, name, expected_count,
# namespaces_list=None):
# def assertAnalyzerOutputs(self,
# input_data,
# input_metadata,
# analyzer_fn,
# expected_outputs,
# test_data=None,
# desired_batch_size=None,
# beam_pipeline=None,
# force_tf_compat_v1=False,
# output_record_batches=False):
# def preprocessing_fn(inputs):
# def assertAnalyzeAndTransformResults(self,
# input_data,
# input_metadata,
# preprocessing_fn,
# expected_data=None,
# expected_metadata=None,
# expected_vocab_file_contents=None,
# test_data=None,
# desired_batch_size=None,
# beam_pipeline=None,
# temp_dir=None,
# force_tf_compat_v1=False,
# output_record_batches=False):
# class TransformTestCase(test_case.TransformTestCase):
# class _TestPipeline(beam.Pipeline):
#
# Path: tensorflow_transform/beam/tft_beam_io/beam_metadata_io.py
# class BeamDatasetMetadata(
# tfx_namedtuple.namedtuple(
# 'BeamDatasetMetadata',
# ['dataset_metadata', 'deferred_metadata', 'asset_map'])):
# class WriteMetadata(beam.PTransform):
# def schema(self):
# def __init__(self, path, pipeline, write_to_unique_subdirectory=False):
# def _extract_input_pvalues(self, metadata):
# def expand(self, metadata):
# def write_metadata_output(metadata):
#
# Path: tensorflow_transform/beam/tft_beam_io/transform_fn_io.py
# TRANSFORMED_METADATA_DIR = tft.TFTransformOutput.TRANSFORMED_METADATA_DIR
# TRANSFORM_FN_DIR = tft.TFTransformOutput.TRANSFORM_FN_DIR
# def _copy_tree_to_unique_temp_dir(source, base_temp_dir_path):
# def _copy_tree(source, destination):
# def __init__(self, path):
# def _extract_input_pvalues(self, transform_fn):
# def expand(self, transform_fn):
# def publish_outputs(unused_element, metadata_source_path,
# transform_fn_source_path):
# def __init__(self, path):
# def expand(self, pvalue):
# class WriteTransformFn(beam.PTransform):
# class ReadTransformFn(beam.PTransform):
#
# Path: tensorflow_transform/beam/tft_beam_io/test_metadata.py
# _FEATURE_SPEC = {
# 'fixed_column': tf.io.FixedLenFeature([3], tf.string),
# 'list_columm': tf.io.VarLenFeature(tf.int64),
# }
# COMPLETE_METADATA = dataset_metadata.DatasetMetadata.from_feature_spec(
# _FEATURE_SPEC, domains={'list_columm': schema_pb2.IntDomain(min=-1, max=5)})
# INCOMPLETE_METADATA = dataset_metadata.DatasetMetadata.from_feature_spec(
# _FEATURE_SPEC,
# # Values will be overridden by those in COMPLETE_METADATA
# domains={'list_columm': schema_pb2.IntDomain(min=0, max=0)})
#
# Path: tensorflow_transform/tf_metadata/metadata_io.py
# def read_metadata(path):
# def _parse_schema_json(schema_json):
# def _column_schema_from_json(feature_dict):
# def _domain_from_json(domain):
# def maybe_to_int(s):
# def _dtype_from_json(domain):
# def write_metadata(metadata, path):
# def _convert_scalar_or_list(fn, scalar_or_list):
. Output only the next line. | pipeline | transform_fn_io.ReadTransformFn(path)) |
Using the snippet: <|code_start|># 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.
"""Tests for transform_fn_io."""
mock = tf.compat.v1.test.mock
# TODO(varshaan): Remove global variable and use a class attribute.
_COPY_TREE_TO_UNIQUE_TEMP_DIR_CALLED = False
class TransformFnIoTest(tft_unit.TransformTestCase):
def testReadTransformFn(self):
path = self.get_temp_dir()
# NOTE: we don't need to create or write to the transform_fn directory since
# ReadTransformFn never inspects this directory.
transform_fn_dir = os.path.join(
path, tft.TFTransformOutput.TRANSFORM_FN_DIR)
transformed_metadata_dir = os.path.join(
path, tft.TFTransformOutput.TRANSFORMED_METADATA_DIR)
<|code_end|>
, determine the next line of code. You have imports:
import os
import apache_beam as beam
import tensorflow as tf
import tensorflow_transform as tft
from apache_beam.testing import util as beam_test_util
from tensorflow_transform.beam import tft_unit
from tensorflow_transform.beam.tft_beam_io import beam_metadata_io
from tensorflow_transform.beam.tft_beam_io import transform_fn_io
from tensorflow_transform.beam.tft_beam_io import test_metadata
from tensorflow_transform.tf_metadata import metadata_io
from tensorflow.python.lib.io import file_io # pylint: disable=g-direct-tensorflow-import
and context (class names, function names, or code) available:
# Path: tensorflow_transform/beam/tft_unit.py
# def metadata_from_feature_spec(feature_spec, domains=None):
# def canonical_numeric_dtype(dtype):
# def make_feature_spec_wrapper(make_feature_spec, *args):
# def _format_example_as_numpy_dict(example, feature_shape_dict):
# def has_ran(self):
# def metrics(self):
# def __exit__(self, exc_type, exc_val, exc_tb):
# def _makeTestPipeline(self):
# def assertMetricsCounterEqual(self, metrics, name, expected_count,
# namespaces_list=None):
# def assertAnalyzerOutputs(self,
# input_data,
# input_metadata,
# analyzer_fn,
# expected_outputs,
# test_data=None,
# desired_batch_size=None,
# beam_pipeline=None,
# force_tf_compat_v1=False,
# output_record_batches=False):
# def preprocessing_fn(inputs):
# def assertAnalyzeAndTransformResults(self,
# input_data,
# input_metadata,
# preprocessing_fn,
# expected_data=None,
# expected_metadata=None,
# expected_vocab_file_contents=None,
# test_data=None,
# desired_batch_size=None,
# beam_pipeline=None,
# temp_dir=None,
# force_tf_compat_v1=False,
# output_record_batches=False):
# class TransformTestCase(test_case.TransformTestCase):
# class _TestPipeline(beam.Pipeline):
#
# Path: tensorflow_transform/beam/tft_beam_io/beam_metadata_io.py
# class BeamDatasetMetadata(
# tfx_namedtuple.namedtuple(
# 'BeamDatasetMetadata',
# ['dataset_metadata', 'deferred_metadata', 'asset_map'])):
# class WriteMetadata(beam.PTransform):
# def schema(self):
# def __init__(self, path, pipeline, write_to_unique_subdirectory=False):
# def _extract_input_pvalues(self, metadata):
# def expand(self, metadata):
# def write_metadata_output(metadata):
#
# Path: tensorflow_transform/beam/tft_beam_io/transform_fn_io.py
# TRANSFORMED_METADATA_DIR = tft.TFTransformOutput.TRANSFORMED_METADATA_DIR
# TRANSFORM_FN_DIR = tft.TFTransformOutput.TRANSFORM_FN_DIR
# def _copy_tree_to_unique_temp_dir(source, base_temp_dir_path):
# def _copy_tree(source, destination):
# def __init__(self, path):
# def _extract_input_pvalues(self, transform_fn):
# def expand(self, transform_fn):
# def publish_outputs(unused_element, metadata_source_path,
# transform_fn_source_path):
# def __init__(self, path):
# def expand(self, pvalue):
# class WriteTransformFn(beam.PTransform):
# class ReadTransformFn(beam.PTransform):
#
# Path: tensorflow_transform/beam/tft_beam_io/test_metadata.py
# _FEATURE_SPEC = {
# 'fixed_column': tf.io.FixedLenFeature([3], tf.string),
# 'list_columm': tf.io.VarLenFeature(tf.int64),
# }
# COMPLETE_METADATA = dataset_metadata.DatasetMetadata.from_feature_spec(
# _FEATURE_SPEC, domains={'list_columm': schema_pb2.IntDomain(min=-1, max=5)})
# INCOMPLETE_METADATA = dataset_metadata.DatasetMetadata.from_feature_spec(
# _FEATURE_SPEC,
# # Values will be overridden by those in COMPLETE_METADATA
# domains={'list_columm': schema_pb2.IntDomain(min=0, max=0)})
#
# Path: tensorflow_transform/tf_metadata/metadata_io.py
# def read_metadata(path):
# def _parse_schema_json(schema_json):
# def _column_schema_from_json(feature_dict):
# def _domain_from_json(domain):
# def maybe_to_int(s):
# def _dtype_from_json(domain):
# def write_metadata(metadata, path):
# def _convert_scalar_or_list(fn, scalar_or_list):
. Output only the next line. | metadata_io.write_metadata(test_metadata.COMPLETE_METADATA, |
Using the snippet: <|code_start|># 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.
"""Tests for transform_fn_io."""
mock = tf.compat.v1.test.mock
# TODO(varshaan): Remove global variable and use a class attribute.
_COPY_TREE_TO_UNIQUE_TEMP_DIR_CALLED = False
class TransformFnIoTest(tft_unit.TransformTestCase):
def testReadTransformFn(self):
path = self.get_temp_dir()
# NOTE: we don't need to create or write to the transform_fn directory since
# ReadTransformFn never inspects this directory.
transform_fn_dir = os.path.join(
path, tft.TFTransformOutput.TRANSFORM_FN_DIR)
transformed_metadata_dir = os.path.join(
path, tft.TFTransformOutput.TRANSFORMED_METADATA_DIR)
<|code_end|>
, determine the next line of code. You have imports:
import os
import apache_beam as beam
import tensorflow as tf
import tensorflow_transform as tft
from apache_beam.testing import util as beam_test_util
from tensorflow_transform.beam import tft_unit
from tensorflow_transform.beam.tft_beam_io import beam_metadata_io
from tensorflow_transform.beam.tft_beam_io import transform_fn_io
from tensorflow_transform.beam.tft_beam_io import test_metadata
from tensorflow_transform.tf_metadata import metadata_io
from tensorflow.python.lib.io import file_io # pylint: disable=g-direct-tensorflow-import
and context (class names, function names, or code) available:
# Path: tensorflow_transform/beam/tft_unit.py
# def metadata_from_feature_spec(feature_spec, domains=None):
# def canonical_numeric_dtype(dtype):
# def make_feature_spec_wrapper(make_feature_spec, *args):
# def _format_example_as_numpy_dict(example, feature_shape_dict):
# def has_ran(self):
# def metrics(self):
# def __exit__(self, exc_type, exc_val, exc_tb):
# def _makeTestPipeline(self):
# def assertMetricsCounterEqual(self, metrics, name, expected_count,
# namespaces_list=None):
# def assertAnalyzerOutputs(self,
# input_data,
# input_metadata,
# analyzer_fn,
# expected_outputs,
# test_data=None,
# desired_batch_size=None,
# beam_pipeline=None,
# force_tf_compat_v1=False,
# output_record_batches=False):
# def preprocessing_fn(inputs):
# def assertAnalyzeAndTransformResults(self,
# input_data,
# input_metadata,
# preprocessing_fn,
# expected_data=None,
# expected_metadata=None,
# expected_vocab_file_contents=None,
# test_data=None,
# desired_batch_size=None,
# beam_pipeline=None,
# temp_dir=None,
# force_tf_compat_v1=False,
# output_record_batches=False):
# class TransformTestCase(test_case.TransformTestCase):
# class _TestPipeline(beam.Pipeline):
#
# Path: tensorflow_transform/beam/tft_beam_io/beam_metadata_io.py
# class BeamDatasetMetadata(
# tfx_namedtuple.namedtuple(
# 'BeamDatasetMetadata',
# ['dataset_metadata', 'deferred_metadata', 'asset_map'])):
# class WriteMetadata(beam.PTransform):
# def schema(self):
# def __init__(self, path, pipeline, write_to_unique_subdirectory=False):
# def _extract_input_pvalues(self, metadata):
# def expand(self, metadata):
# def write_metadata_output(metadata):
#
# Path: tensorflow_transform/beam/tft_beam_io/transform_fn_io.py
# TRANSFORMED_METADATA_DIR = tft.TFTransformOutput.TRANSFORMED_METADATA_DIR
# TRANSFORM_FN_DIR = tft.TFTransformOutput.TRANSFORM_FN_DIR
# def _copy_tree_to_unique_temp_dir(source, base_temp_dir_path):
# def _copy_tree(source, destination):
# def __init__(self, path):
# def _extract_input_pvalues(self, transform_fn):
# def expand(self, transform_fn):
# def publish_outputs(unused_element, metadata_source_path,
# transform_fn_source_path):
# def __init__(self, path):
# def expand(self, pvalue):
# class WriteTransformFn(beam.PTransform):
# class ReadTransformFn(beam.PTransform):
#
# Path: tensorflow_transform/beam/tft_beam_io/test_metadata.py
# _FEATURE_SPEC = {
# 'fixed_column': tf.io.FixedLenFeature([3], tf.string),
# 'list_columm': tf.io.VarLenFeature(tf.int64),
# }
# COMPLETE_METADATA = dataset_metadata.DatasetMetadata.from_feature_spec(
# _FEATURE_SPEC, domains={'list_columm': schema_pb2.IntDomain(min=-1, max=5)})
# INCOMPLETE_METADATA = dataset_metadata.DatasetMetadata.from_feature_spec(
# _FEATURE_SPEC,
# # Values will be overridden by those in COMPLETE_METADATA
# domains={'list_columm': schema_pb2.IntDomain(min=0, max=0)})
#
# Path: tensorflow_transform/tf_metadata/metadata_io.py
# def read_metadata(path):
# def _parse_schema_json(schema_json):
# def _column_schema_from_json(feature_dict):
# def _domain_from_json(domain):
# def maybe_to_int(s):
# def _dtype_from_json(domain):
# def write_metadata(metadata, path):
# def _convert_scalar_or_list(fn, scalar_or_list):
. Output only the next line. | metadata_io.write_metadata(test_metadata.COMPLETE_METADATA, |
Next line prediction: <|code_start|> @staticmethod
def _MakeAdd1CountingIdentityFn(label):
def Add1CountingIdentityFn(x_y):
(x, y) = x_y
return DeepCopyTest._CountingIdentityFn(label, (x + 1, y))
return Add1CountingIdentityFn
@staticmethod
def _InitializeCounts():
DeepCopyTest._counts = collections.defaultdict(int)
def setUp(self):
DeepCopyTest._InitializeCounts()
def testBasicDeepCopy(self):
with DeepCopyTest._MakeBeamPipeline() as p:
grouped = (p
| beam.Create([(1, 'a'), (2, 'b'), (3, 'c')])
| beam.Map(
lambda x: DeepCopyTest._CountingIdentityFn(
'PreGroup', x))
| beam.GroupByKey())
modified = (
grouped
|
'Add1' >> beam.Map(DeepCopyTest._MakeAdd1CountingIdentityFn('Add1'))
|
'Add2' >> beam.Map(DeepCopyTest._MakeAdd1CountingIdentityFn('Add2')))
<|code_end|>
. Use current file imports:
(import collections
import apache_beam as beam
import unittest
from apache_beam import pvalue
from apache_beam.transforms import resources
from tensorflow_transform.beam import deep_copy
from tensorflow_transform.beam import test_helpers)
and context including class names, function names, or small code snippets from other files:
# Path: tensorflow_transform/beam/deep_copy.py
# def deep_copy(pcollection):
# """Create a deep copy of a PCollection up to materialization boundaries."""
# if not isinstance(pcollection, pvalue.PCollection):
# raise ValueError('Input to deep_copy must be a PCollection.')
#
# # AppliedPTransform.update_input_refcounts() is a vestigial method that
# # uses an incorrect heuristic; it will be removed in a future version of
# # Beam, since its results aren't used anyway. Until then, we work around
# # this (see https://issues.apache.org/jira/browse/BEAM-4593).
# if getattr(beam_pipeline.AppliedPTransform,
# 'update_input_refcounts', None) is not None:
# beam_pipeline.AppliedPTransform.update_input_refcounts = lambda _: None
#
# to_clone = _get_items_to_clone(pcollection)
# pcollection_replacements = _clone_items(pcollection.pipeline, to_clone)
#
# return pcollection_replacements[pcollection]
#
# Path: tensorflow_transform/beam/test_helpers.py
# def make_test_beam_pipeline_kwargs():
. Output only the next line. | copied = deep_copy.deep_copy(modified) |
Using the snippet: <|code_start|># Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Unit tests for tensorflow_transform.beam.deep_copy."""
# pylint: disable=g-long-lambda
class DeepCopyTest(unittest.TestCase):
@staticmethod
def _MakeBeamPipeline():
<|code_end|>
, determine the next line of code. You have imports:
import collections
import apache_beam as beam
import unittest
from apache_beam import pvalue
from apache_beam.transforms import resources
from tensorflow_transform.beam import deep_copy
from tensorflow_transform.beam import test_helpers
and context (class names, function names, or code) available:
# Path: tensorflow_transform/beam/deep_copy.py
# def deep_copy(pcollection):
# """Create a deep copy of a PCollection up to materialization boundaries."""
# if not isinstance(pcollection, pvalue.PCollection):
# raise ValueError('Input to deep_copy must be a PCollection.')
#
# # AppliedPTransform.update_input_refcounts() is a vestigial method that
# # uses an incorrect heuristic; it will be removed in a future version of
# # Beam, since its results aren't used anyway. Until then, we work around
# # this (see https://issues.apache.org/jira/browse/BEAM-4593).
# if getattr(beam_pipeline.AppliedPTransform,
# 'update_input_refcounts', None) is not None:
# beam_pipeline.AppliedPTransform.update_input_refcounts = lambda _: None
#
# to_clone = _get_items_to_clone(pcollection)
# pcollection_replacements = _clone_items(pcollection.pipeline, to_clone)
#
# return pcollection_replacements[pcollection]
#
# Path: tensorflow_transform/beam/test_helpers.py
# def make_test_beam_pipeline_kwargs():
. Output only the next line. | return beam.Pipeline(**test_helpers.make_test_beam_pipeline_kwargs()) |
Using the snippet: <|code_start|> def tensor_fn(input1, input2):
initializer = tf.compat.v1.initializers.constant([1, 2, 3])
with tf.compat.v1.variable_scope(
'Model', reuse=None, initializer=initializer):
v1 = tf.compat.v1.get_variable('v1', [3], dtype=tf.int64)
o1 = tf.add(v1, input1, name='myadda1')
o = tf.subtract(o1, input2, name='myadda2')
return o
return tensor_fn
def save_checkpoint_with_two_inputs(self, checkpoint_path):
test_tensor_fn = self.make_tensor_fn_two_inputs()
with tf.compat.v1.Graph().as_default() as graph:
with self.test_session(graph=graph) as sess:
input1 = tf.compat.v1.placeholder(
dtype=tf.int64, shape=[3], name='myinputa')
input2 = tf.compat.v1.placeholder(
dtype=tf.int64, shape=[3], name='myinputb')
test_tensor_fn(input1, input2)
saver = tf.compat.v1.train.Saver()
sess.run(tf.compat.v1.global_variables_initializer())
saver.save(sess, checkpoint_path)
def testApplySavedModelSingleInput(self):
export_dir = os.path.join(self.get_temp_dir(), 'single_input')
self.save_model_with_single_input(export_dir)
with tf.compat.v1.Graph().as_default() as graph:
with self.test_session(graph=graph) as sess:
input_tensor = tf.compat.v1.placeholder(
dtype=tf.int32, shape=[5], name='input_tensor')
<|code_end|>
, determine the next line of code. You have imports:
import os
import tensorflow as tf
from tensorflow_transform import pretrained_models
and context (class names, function names, or code) available:
# Path: tensorflow_transform/pretrained_models.py
# def _get_variables(scope=None,
# suffix=None,
# collection=tf.compat.v1.GraphKeys.GLOBAL_VARIABLES):
# def _get_variables_to_restore(include=None, exclude=None):
# def apply_saved_model(model_dir, inputs, tags, signature_name=None,
# output_keys_in_signature=None):
# def apply_function_with_checkpoint(fn, inputs, checkpoint, include=None,
# exclude=None):
. Output only the next line. | output_tensor = pretrained_models.apply_saved_model( |
Based on the snippet: <|code_start|># `collections.namedtuple` or `typing.NamedTuple` once the Spark issue is
# resolved.
mock = tf.compat.v1.test.mock
class _Concat(
tfx_namedtuple.namedtuple('_Concat', ['label']), nodes.OperationDef):
__slots__ = ()
class _Swap(tfx_namedtuple.namedtuple('_Swap', ['label']), nodes.OperationDef):
__slots__ = ()
@property
def num_outputs(self):
return 2
class _Constant(
tfx_namedtuple.namedtuple('_Constant', ['value', 'label']),
nodes.OperationDef):
__slots__ = ()
class _Identity(
tfx_namedtuple.namedtuple('_Identity', ['label']), nodes.OperationDef):
__slots__ = ()
<|code_end|>
, predict the immediate next line with the help of imports:
import tensorflow as tf
from tensorflow_transform import nodes
from tensorflow_transform import test_case
from tfx_bsl.types import tfx_namedtuple
and context (classes, functions, sometimes code) from other files:
# Path: tensorflow_transform/nodes.py
# class ValueNode(
# tfx_namedtuple.namedtuple('ValueNode',
# ['parent_operation', 'value_index'])):
# class OperationDef(metaclass=abc.ABCMeta):
# class OperationNode:
# class Visitor(metaclass=abc.ABCMeta):
# class Traverser:
# class _PrintGraphVisitor(Visitor):
# def __init__(self, parent_operation, value_index: int):
# def __iter__(self):
# def num_outputs(self) -> int:
# def label(self) -> str:
# def get_field_str(self, field_name: str) -> str:
# def is_partitionable(self) -> bool:
# def cache_coder(self) -> Optional[object]:
# def __init__(self, operation_def, inputs):
# def __repr__(self):
# def operation_def(self):
# def inputs(self):
# def outputs(self):
# def apply_operation(operation_def_cls, *args, **kwargs):
# def apply_multi_output_operation(operation_def_cls, *args, **kwargs):
# def validate_value(self, value):
# def visit(self, operation_def, input_values):
# def __init__(self, visitor: Visitor):
# def visit_value_node(self, value_node: ValueNode):
# def _maybe_visit_value_node(self, value_node: ValueNode):
# def _visit_operation(self, operation: OperationNode):
# def _escape(line: str) -> str:
# def __init__(self):
# def get_dot_graph(self) -> pydot.Dot:
# def visit(self, operation_def, input_nodes) -> Tuple[pydot.Node, ...]:
# def validate_value(self, value: pydot.Node):
# def get_dot_graph(leaf_nodes: Collection[ValueNode]) -> pydot.Dot:
#
# Path: tensorflow_transform/test_case.py
# def is_tf_api_version_1():
# def cross_named_parameters(*args):
# def _cross_test_cases(parameters_list):
# def parameters(*testcases):
# def wrapper(fn):
# def to_arg_dict(testcase):
# def cross_parameters(*args):
# def _make_placeholder(tensor_spec):
# def _graph_function_handler(input_signature):
# def wrapper(fn):
# def _run_graph(*inputs):
# def _ragged_value_as_constant(value, dtype):
# def _wrap_as_constant(value, tensor_spec):
# def _eager_function_handler(input_signature):
# def wrapper(fn):
# def _run_eagerly(*inputs): # pylint: disable=missing-docstring
# def _tf_function_function_handler(input_signature):
# def wrapper(fn):
# def is_external_environment():
# def skip_if_external_environment(reason):
# def skip_if_not_tf2(reason):
# def cross_with_function_handlers(parameters_list):
# def assertDataCloseOrEqual(self, a_data, b_data):
# def _assertValuesCloseOrEqual(self, a_value, b_value, msg=None):
# def AssertVocabularyContents(self, vocab_file_path, file_contents):
# def WriteRenderedDotFile(self, dot_string, output_file=None):
# def _NumpyArraysToLists(self, maybe_arrays):
# def _SortedDicts(self, list_of_dicts):
# def _SortedData(self, list_of_dicts_of_arrays):
# FUNCTION_HANDLERS = [
# dict(testcase_name='graph',
# function_handler=_graph_function_handler),
# dict(testcase_name='eager',
# function_handler=_eager_function_handler),
# dict(testcase_name='tf_function',
# function_handler=_tf_function_function_handler)
# ]
# class TransformTestCase(parameterized.TestCase, tf.test.TestCase):
. Output only the next line. | class NodesTest(test_case.TransformTestCase): |
Next line prediction: <|code_start|># 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.
"""Tests for saved_transform_io."""
# pylint: disable=g-direct-tensorflow-import
# pylint: enable=g-direct-tensorflow-import
# TODO(b/123241798): Find an open-source compatible way to access
# FLAGS.test_tmpdir.
def _create_test_saved_model():
export_path = os.path.join(tempfile.mkdtemp(), 'export')
with tf.compat.v1.Graph().as_default():
with tf.compat.v1.Session().as_default() as session:
input_float = tf.compat.v1.placeholder(tf.float32, shape=[1])
output = (input_float - 2.0) / 5.0
inputs = {'x': input_float}
outputs = {'x_scaled': output}
<|code_end|>
. Use current file imports:
(import os
import tempfile
import numpy as np
import tensorflow as tf
from tensorflow_transform.saved import saved_transform_io
from tensorflow.core.protobuf import meta_graph_pb2
from tensorflow.python.lib.io import file_io
from tensorflow.python.ops import lookup_ops)
and context including class names, function names, or small code snippets from other files:
# Path: tensorflow_transform/saved/saved_transform_io.py
# _MANGLED_TENSOR_NAME_RE = re.compile(
# r'(.*)\$(indices|values|dense_shape|dense_tensor)$')
# _PARTITIONED_VARIABLE_NAME_RE = re.compile(r'^(.*)/part_(\d*)$')
# def _update_legacy_signature(signature):
# def _load_transform_saved_model(transform_savedmodel_dir):
# def _expand_input_map(logical_input_map, input_signature):
# def _maybe_register_addon_ops():
# def _try_import(name):
# def _partially_apply_saved_transform_impl(saved_model_dir,
# logical_input_map,
# tensor_replacement_map=None):
# def lookup_remapped_tensor(tensor_name):
# def lookup_tensor_or_sparse_or_composite_tensor(tensor_info):
# def partially_apply_saved_transform_internal(saved_model_dir,
# logical_input_map,
# tensor_replacement_map=None):
# def write_saved_transform_from_session(
# session, inputs, outputs, export_path, as_text=False):
# def exported_as_v1(transform_savedmodel_dir):
. Output only the next line. | saved_transform_io.write_saved_transform_from_session( |
Using the snippet: <|code_start|> def convert_dtype_and_swap(v, k):
return key_dtype_fn(k), tf.cast(v, value_dtype)
return dataset.enumerate().map(convert_dtype_and_swap)
def make_tfrecord_vocabulary_lookup_initializer(filename_tensor,
key_dtype=tf.string,
value_dtype=tf.int64,
return_indicator_as_value=False,
has_indicator=False):
"""Makes a lookup table initializer from a compressed tfrecord file."""
graph = ops.get_default_graph()
with contextlib.ExitStack() as stack:
# TODO(b/165884902): Use tf.inside_function after dropping TF 2.3 support.
# If filename_tensor is a graph tensor (e.g. temporary analyzer output), the
# following operation cannot be lifted to init scope. Hence, check it is an
# eager tensor or a string constant.
if isinstance(graph, func_graph.FuncGraph) and isinstance(
filename_tensor, (ops.EagerTensor, str)):
# Lift the dataset creation out of graph construction to avoid
# repeated initialization in TF2.
stack.enter_context(tf.init_scope())
dataset = _make_tfrecord_vocabulary_dataset(filename_tensor, key_dtype,
value_dtype,
return_indicator_as_value,
has_indicator)
# TODO(b/165884902): Use tf.inside_function after dropping TF 2.3 support.
if isinstance(graph, func_graph.FuncGraph):
<|code_end|>
, determine the next line of code. You have imports:
import contextlib
import enum
import tensorflow as tf
from typing import Callable, Optional, Tuple, Union
from tensorflow_transform import annotators
from tensorflow_transform import common_types
from tfx_bsl.types import tfx_namedtuple
from tensorflow.python.framework import composite_tensor
from tensorflow.python.framework import func_graph
from tensorflow.python.framework import ops
from tensorflow.python.ops import lookup_ops
from tensorflow.python.util import object_identity
and context (class names, function names, or code) available:
# Path: tensorflow_transform/annotators.py
# _ASSET_KEY_COLLECTION = 'tft_asset_key_collection'
# _ASSET_FILENAME_COLLECTION = 'tft_asset_filename_collection'
# _OBJECT_TRACKER = None
# VOCABULARY_SIZE_BY_NAME_COLLECTION = 'tft_vocabulary_size_by_name_collection'
# _OBJECT_TRACKER = object_tracker
# _OBJECT_TRACKER = None
# class ObjectTracker:
# def __init__(self):
# def trackable_objects(self) -> List[base.Trackable]:
# def add_trackable_object(self, trackable_object: base.Trackable,
# name: Optional[str]):
# def object_tracker_scope(object_tracker: ObjectTracker):
# def _get_object(name: str) -> Optional[base.Trackable]:
# def track_object(trackable: base.Trackable, name: Optional[str]):
# def make_and_track_object(trackable_factory_callable: Callable[[],
# base.Trackable],
# name: Optional[str] = None) -> base.Trackable:
# def get_asset_annotations(graph: tf.Graph):
# def clear_asset_annotations(graph: tf.Graph):
# def annotate_asset(asset_key: str, asset_filename: str):
# def annotate_vocab_size(vocab_filename: str, vocab_size: tf.Tensor):
#
# Path: tensorflow_transform/common_types.py
# def is_ragged_feature_available() -> bool:
# def is_ragged_feature(spec: FeatureSpecType) -> bool:
. Output only the next line. | annotators.track_object(dataset, name=None) |
Using the snippet: <|code_start|>
# TODO(https://issues.apache.org/jira/browse/SPARK-22674): Switch to
# `collections.namedtuple` or `typing.NamedTuple` once the Spark issue is
# resolved.
# pylint: disable=g-direct-tensorflow-import
# pylint: enable=g-direct-tensorflow-import
_AssetFileType = Union[tf.Tensor, str]
_FLOATING_NAN = float('nan')
# Global sentinels used to keep track of the total counts of y
GLOBAL_Y_COUNT_SENTINEL_STRING = b'global_y_count_sentinel'
GLOBAL_Y_COUNT_SENTINEL_INT = tf.int64.limits[1]
# Key for graph collection containing tuple of a key to the eager tensor
# representing asset path and the graph tensor tracking the analyzer in
# `analyzer_nodes.TENSOR_REPLACEMENTS`.
_ASSET_REPLACEMENTS = 'tft_asset_replacements'
ReducedBatchWeightedCounts = tfx_namedtuple.namedtuple('ReducedBatchCounts', [
'unique_x', 'summed_weights_per_x', 'summed_positive_per_x_and_y',
'counts_per_x'
])
_CompositeTensorRef = tfx_namedtuple.namedtuple('_CompositeTensorRef',
['type_spec', 'list_of_refs'])
<|code_end|>
, determine the next line of code. You have imports:
import contextlib
import enum
import tensorflow as tf
from typing import Callable, Optional, Tuple, Union
from tensorflow_transform import annotators
from tensorflow_transform import common_types
from tfx_bsl.types import tfx_namedtuple
from tensorflow.python.framework import composite_tensor
from tensorflow.python.framework import func_graph
from tensorflow.python.framework import ops
from tensorflow.python.ops import lookup_ops
from tensorflow.python.util import object_identity
and context (class names, function names, or code) available:
# Path: tensorflow_transform/annotators.py
# _ASSET_KEY_COLLECTION = 'tft_asset_key_collection'
# _ASSET_FILENAME_COLLECTION = 'tft_asset_filename_collection'
# _OBJECT_TRACKER = None
# VOCABULARY_SIZE_BY_NAME_COLLECTION = 'tft_vocabulary_size_by_name_collection'
# _OBJECT_TRACKER = object_tracker
# _OBJECT_TRACKER = None
# class ObjectTracker:
# def __init__(self):
# def trackable_objects(self) -> List[base.Trackable]:
# def add_trackable_object(self, trackable_object: base.Trackable,
# name: Optional[str]):
# def object_tracker_scope(object_tracker: ObjectTracker):
# def _get_object(name: str) -> Optional[base.Trackable]:
# def track_object(trackable: base.Trackable, name: Optional[str]):
# def make_and_track_object(trackable_factory_callable: Callable[[],
# base.Trackable],
# name: Optional[str] = None) -> base.Trackable:
# def get_asset_annotations(graph: tf.Graph):
# def clear_asset_annotations(graph: tf.Graph):
# def annotate_asset(asset_key: str, asset_filename: str):
# def annotate_vocab_size(vocab_filename: str, vocab_size: tf.Tensor):
#
# Path: tensorflow_transform/common_types.py
# def is_ragged_feature_available() -> bool:
# def is_ragged_feature(spec: FeatureSpecType) -> bool:
. Output only the next line. | def get_values(x: common_types.TensorType) -> tf.Tensor: |
Using the snippet: <|code_start|>"""Tests for tensorflow_transform.info_theory."""
EPSILON = 1e-4
def _make_hypergeometric_pmf_sum_up_to_one_parameters():
start = 1000
end = 10000
range_length = end - start
num_chunks = 15
assert range_length % num_chunks == 0
chunk_size = int(range_length / num_chunks)
sub_ranges = [(x, x + chunk_size) for x in range(start, end, chunk_size)]
return [ # pylint: disable=g-complex-comprehension
dict(
testcase_name='{}_to_{}'.format(a, b),
test_range=range(a, b),
n=end,
y_j=start) for a, b in sub_ranges
]
class InfoTheoryTest(test_case.TransformTestCase):
def testHypergeometricPmf(self):
expected_results = [(0, 0.75), (1, 0.25)]
<|code_end|>
, determine the next line of code. You have imports:
from tensorflow_transform import info_theory
from tensorflow_transform import test_case
import unittest
and context (class names, function names, or code) available:
# Path: tensorflow_transform/info_theory.py
# def calculate_partial_expected_mutual_information(n, x_i, y_j):
# def calculate_partial_mutual_information(n_ij, x_i, y_j, n):
# def _hypergeometric_pmf(n, x_i, y_j):
# def _logfactorial(n):
#
# Path: tensorflow_transform/test_case.py
# def is_tf_api_version_1():
# def cross_named_parameters(*args):
# def _cross_test_cases(parameters_list):
# def parameters(*testcases):
# def wrapper(fn):
# def to_arg_dict(testcase):
# def cross_parameters(*args):
# def _make_placeholder(tensor_spec):
# def _graph_function_handler(input_signature):
# def wrapper(fn):
# def _run_graph(*inputs):
# def _ragged_value_as_constant(value, dtype):
# def _wrap_as_constant(value, tensor_spec):
# def _eager_function_handler(input_signature):
# def wrapper(fn):
# def _run_eagerly(*inputs): # pylint: disable=missing-docstring
# def _tf_function_function_handler(input_signature):
# def wrapper(fn):
# def is_external_environment():
# def skip_if_external_environment(reason):
# def skip_if_not_tf2(reason):
# def cross_with_function_handlers(parameters_list):
# def assertDataCloseOrEqual(self, a_data, b_data):
# def _assertValuesCloseOrEqual(self, a_value, b_value, msg=None):
# def AssertVocabularyContents(self, vocab_file_path, file_contents):
# def WriteRenderedDotFile(self, dot_string, output_file=None):
# def _NumpyArraysToLists(self, maybe_arrays):
# def _SortedDicts(self, list_of_dicts):
# def _SortedData(self, list_of_dicts_of_arrays):
# FUNCTION_HANDLERS = [
# dict(testcase_name='graph',
# function_handler=_graph_function_handler),
# dict(testcase_name='eager',
# function_handler=_eager_function_handler),
# dict(testcase_name='tf_function',
# function_handler=_tf_function_function_handler)
# ]
# class TransformTestCase(parameterized.TestCase, tf.test.TestCase):
. Output only the next line. | results = list(info_theory._hypergeometric_pmf(4, 1, 1)) |
Predict the next line for this snippet: <|code_start|># 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.
"""Tests for tensorflow_transform.info_theory."""
EPSILON = 1e-4
def _make_hypergeometric_pmf_sum_up_to_one_parameters():
start = 1000
end = 10000
range_length = end - start
num_chunks = 15
assert range_length % num_chunks == 0
chunk_size = int(range_length / num_chunks)
sub_ranges = [(x, x + chunk_size) for x in range(start, end, chunk_size)]
return [ # pylint: disable=g-complex-comprehension
dict(
testcase_name='{}_to_{}'.format(a, b),
test_range=range(a, b),
n=end,
y_j=start) for a, b in sub_ranges
]
<|code_end|>
with the help of current file imports:
from tensorflow_transform import info_theory
from tensorflow_transform import test_case
import unittest
and context from other files:
# Path: tensorflow_transform/info_theory.py
# def calculate_partial_expected_mutual_information(n, x_i, y_j):
# def calculate_partial_mutual_information(n_ij, x_i, y_j, n):
# def _hypergeometric_pmf(n, x_i, y_j):
# def _logfactorial(n):
#
# Path: tensorflow_transform/test_case.py
# def is_tf_api_version_1():
# def cross_named_parameters(*args):
# def _cross_test_cases(parameters_list):
# def parameters(*testcases):
# def wrapper(fn):
# def to_arg_dict(testcase):
# def cross_parameters(*args):
# def _make_placeholder(tensor_spec):
# def _graph_function_handler(input_signature):
# def wrapper(fn):
# def _run_graph(*inputs):
# def _ragged_value_as_constant(value, dtype):
# def _wrap_as_constant(value, tensor_spec):
# def _eager_function_handler(input_signature):
# def wrapper(fn):
# def _run_eagerly(*inputs): # pylint: disable=missing-docstring
# def _tf_function_function_handler(input_signature):
# def wrapper(fn):
# def is_external_environment():
# def skip_if_external_environment(reason):
# def skip_if_not_tf2(reason):
# def cross_with_function_handlers(parameters_list):
# def assertDataCloseOrEqual(self, a_data, b_data):
# def _assertValuesCloseOrEqual(self, a_value, b_value, msg=None):
# def AssertVocabularyContents(self, vocab_file_path, file_contents):
# def WriteRenderedDotFile(self, dot_string, output_file=None):
# def _NumpyArraysToLists(self, maybe_arrays):
# def _SortedDicts(self, list_of_dicts):
# def _SortedData(self, list_of_dicts_of_arrays):
# FUNCTION_HANDLERS = [
# dict(testcase_name='graph',
# function_handler=_graph_function_handler),
# dict(testcase_name='eager',
# function_handler=_eager_function_handler),
# dict(testcase_name='tf_function',
# function_handler=_tf_function_function_handler)
# ]
# class TransformTestCase(parameterized.TestCase, tf.test.TestCase):
, which may contain function names, class names, or code. Output only the next line. | class InfoTheoryTest(test_case.TransformTestCase): |
Based on the snippet: <|code_start|> self._schema = schema
self._delimiter = delimiter
self._secondary_delimiter = secondary_delimiter
self._encoder = self._WriterWrapper(delimiter)
if multivalent_columns is None:
multivalent_columns = []
self._multivalent_columns = multivalent_columns
if secondary_delimiter:
secondary_encoder = self._WriterWrapper(secondary_delimiter)
elif multivalent_columns:
raise ValueError(
'secondary_delimiter unspecified for multivalent columns "{}"'.format(
multivalent_columns))
secondary_encoder_by_name = {
name: secondary_encoder for name in multivalent_columns
}
indices_by_name = {
name: index for index, name in enumerate(self._column_names)
}
def index(name):
index = indices_by_name.get(name)
if index is None:
raise ValueError('Column not found: "{}"'.format(name))
else:
return index
self._feature_handlers = []
<|code_end|>
, predict the immediate next line with the help of imports:
import csv
import io
import numpy as np
import tensorflow as tf
from tensorflow_transform.tf_metadata import schema_utils
and context (classes, functions, sometimes code) from other files:
# Path: tensorflow_transform/tf_metadata/schema_utils.py
# TENSOR_REPRESENTATION_GROUP = ''
# RAGGED_TENSOR_TAG = 'ragged_tensor'
# _DEPRECATED_LIFECYCLE_STAGES = [
# schema_pb2.DEPRECATED, schema_pb2.DISABLED, schema_pb2.PLANNED,
# schema_pb2.ALPHA, schema_pb2.DEBUG_ONLY
# ]
# _LEGACY_DEFAULT_VALUE_FOR_DTYPE = {tf.string: '', tf.int64: -1, tf.float32: -1}
# def schema_from_feature_spec(
# feature_spec: Mapping[str, common_types.FeatureSpecType],
# domains: Optional[Mapping[str, common_types.DomainType]] = None
# ) -> schema_pb2.Schema:
# def _ragged_tensor_representation_from_feature_spec(
# spec: common_types.RaggedFeature, name: str,
# domains: Dict[str, common_types.DomainType]
# ) -> Tuple[schema_pb2.Feature, List[schema_pb2.Feature],
# def _sparse_feature_from_feature_spec(spec, name, domains):
# def _feature_from_feature_spec(spec, name, domains):
# def _set_type(name, feature, dtype):
# def _set_domain(name, feature, domain):
# def schema_as_feature_spec(
# schema_proto: schema_pb2.Schema) -> SchemaAsFeatureSpecResult:
# def _get_string_domains(schema):
# def _get_domain(feature, string_domains):
# def pop_ragged_source_columns(
# name: str, tensor_representation: schema_pb2.TensorRepresentation,
# feature_by_name: Dict[str, schema_pb2.Feature]) -> schema_pb2.Feature:
# def _ragged_tensor_representation_as_feature_spec(
# name: str, tensor_representation: schema_pb2.TensorRepresentation,
# feature_by_name: Dict[str, schema_pb2.Feature],
# string_domains: Dict[str, common_types.DomainType]
# ) -> Tuple[common_types.RaggedFeature, Optional[common_types.DomainType]]:
# def _sparse_feature_as_feature_spec(feature, feature_by_name, string_domains):
# def _feature_as_feature_spec(feature, string_domains):
# def _feature_dtype(feature):
# def _fixed_shape_as_tf_shape(fixed_shape):
# def _include_in_parsing_spec(feature):
# def _legacy_schema_from_feature_spec(feature_spec, domains=None):
# def _legacy_schema_as_feature_spec(schema_proto):
# def _legacy_feature_as_feature_spec(feature):
# def _legacy_infer_default_value(feature_proto, dtype):
. Output only the next line. | for name, feature_spec in schema_utils.schema_as_feature_spec( |
Given snippet: <|code_start|> Args:
saved_model: A `SavedModel` protocol buffer.
tags: Set of string tags to identify the required MetaGraphDef. These should
correspond to the tags used when saving the variables using the
SavedModel `save()` API.
Returns:
The chosen `MetaGraphDef` protocol buffer. This can be used to further
extract signature-defs, collection-defs, etc. If tags cannot be found,
returns None.
"""
result = None
for meta_graph_def in saved_model.meta_graphs:
if set(meta_graph_def.meta_info_def.tags) == set(tags):
result = meta_graph_def
break
return result
def choose_meta_graph_def(saved_model):
"""Find a MetaGraphDef in the SavedModel with tag `constants.TRANSFORM_TAG`.
Args:
saved_model: A `SavedModel` protocol buffer.
Returns:
The chosen `MetaGraphDef` protocol buffer. This can be used to further
extract signature-defs, collection-defs, etc. If tags cannot be found,
returns None.
"""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from tensorflow_transform.saved import constants
from tensorflow.python.saved_model import loader_impl # pylint: disable=g-direct-tensorflow-import
and context:
# Path: tensorflow_transform/saved/constants.py
# TRANSFORM_TAG = 'transform'
# TRANSFORM_SIGNATURE = 'transform_signature'
which might include code, classes, or functions. Output only the next line. | return _choose_meta_graph_def_internal(saved_model, [constants.TRANSFORM_TAG]) |
Using the snippet: <|code_start|>
The underlying reason for this limited support is that `tf.py_func` ops were
not designed to be serialized since they contain a reference to arbitrary
Python functions. This function pickles those functions and including them in
the graph, and `transform_raw_features` similarly unpickles the functions.
But unpickling requires a Python environment, so there it's not possible to
provide support in non-Python languages for loading such ops. Therefore
loading these ops in libraries such as TensorFlow Serving is not supported.
Note: This API can only be used when TF2 is disabled or
`tft_beam.Context.force_tf_compat_v1=True`.
Args:
func: A Python function, which accepts a list of NumPy `ndarray` objects
having element types that match the corresponding `tf.Tensor` objects
in `*args`, and returns a list of `ndarray` objects (or a single
`ndarray`) having element types that match the corresponding values
in `Tout`.
Tout: A list or tuple of tensorflow data types or a single tensorflow data
type if there is only one, indicating what `func` returns.
stateful: (Boolean.) If True, the function should be considered stateful.
If a function is stateless, when given the same input it will return the
same output and have no observable side effects. Optimizations such as
common subexpression elimination are only performed on stateless
operations.
name: A name for the operation (optional).
*args: The list of `Tensor`s to apply the arguments to.
Returns:
A `Tensor` representing the application of the function.
"""
<|code_end|>
, determine the next line of code. You have imports:
from tensorflow_transform.py_func import pyfunc_helper
and context (class names, function names, or code) available:
# Path: tensorflow_transform/py_func/pyfunc_helper.py
# _PYFUNC_COLLECTION_KEY = 'pyfuncs'
# class _PyFuncDef(tfx_namedtuple.namedtuple('_PyFuncDef', ['token', 'func'])):
# def from_proto(attr_value, import_scope=None):
# def from_proto_string(proto_str, import_scope=None):
# def to_proto(self, export_scope=None):
# def insert_pyfunc(func, Tout, stateful, name, *args): # pylint: disable=invalid-name
# def register_pyfuncs_from_saved_transform(graph, meta_graph, loaded_in_tf2):
. Output only the next line. | return pyfunc_helper.insert_pyfunc(func, Tout, stateful, name, *args) |
Given snippet: <|code_start|> # TODO(b/123241798): use TEST_TMPDIR
basedir = tempfile.mkdtemp()
schema_no_sparse_features = """
{
"feature": [{
"name": "my_key",
"fixedShape": {
"axis": [{
"size": 2
}]
},
"type": "INT",
"domain": {
"ints": {}
},
"parsingOptions": {
"tfOptions": {
"fixedLenFeature": {}
}
}
}]
}
"""
self._write_schema_to_disk(basedir, schema_no_sparse_features)
_ = metadata_io.read_metadata(basedir)
def test_write_and_read(self):
# TODO(b/123241798): use TEST_TMPDIR
basedir = tempfile.mkdtemp()
original = dataset_metadata.DatasetMetadata(
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import tempfile
import unittest
from tensorflow_transform.tf_metadata import test_common
from tensorflow_transform.tf_metadata import dataset_metadata
from tensorflow_transform.tf_metadata import metadata_io
from tensorflow.python.lib.io import file_io # pylint: disable=g-direct-tensorflow-import
and context:
# Path: tensorflow_transform/tf_metadata/test_common.py
# def get_test_schema():
#
# Path: tensorflow_transform/tf_metadata/dataset_metadata.py
# class DatasetMetadata:
# def __init__(self, schema: schema_pb2.Schema):
# def from_feature_spec(
# cls: Type[_DatasetMetadataType],
# feature_spec: Mapping[str, common_types.FeatureSpecType],
# domains: Optional[Mapping[str, common_types.DomainType]] = None
# ) -> _DatasetMetadataType:
# def schema(self) -> schema_pb2.Schema:
# def __eq__(self, other):
# def __ne__(self, other):
# def __repr__(self):
#
# Path: tensorflow_transform/tf_metadata/metadata_io.py
# def read_metadata(path):
# def _parse_schema_json(schema_json):
# def _column_schema_from_json(feature_dict):
# def _domain_from_json(domain):
# def maybe_to_int(s):
# def _dtype_from_json(domain):
# def write_metadata(metadata, path):
# def _convert_scalar_or_list(fn, scalar_or_list):
which might include code, classes, or functions. Output only the next line. | schema=test_common.get_test_schema()) |
Given the following code snippet before the placeholder: <|code_start|> def test_read_features(self):
# TODO(b/123241798): use TEST_TMPDIR
basedir = tempfile.mkdtemp()
schema_no_sparse_features = """
{
"feature": [{
"name": "my_key",
"fixedShape": {
"axis": [{
"size": 2
}]
},
"type": "INT",
"domain": {
"ints": {}
},
"parsingOptions": {
"tfOptions": {
"fixedLenFeature": {}
}
}
}]
}
"""
self._write_schema_to_disk(basedir, schema_no_sparse_features)
_ = metadata_io.read_metadata(basedir)
def test_write_and_read(self):
# TODO(b/123241798): use TEST_TMPDIR
basedir = tempfile.mkdtemp()
<|code_end|>
, predict the next line using imports from the current file:
import os
import tempfile
import unittest
from tensorflow_transform.tf_metadata import test_common
from tensorflow_transform.tf_metadata import dataset_metadata
from tensorflow_transform.tf_metadata import metadata_io
from tensorflow.python.lib.io import file_io # pylint: disable=g-direct-tensorflow-import
and context including class names, function names, and sometimes code from other files:
# Path: tensorflow_transform/tf_metadata/test_common.py
# def get_test_schema():
#
# Path: tensorflow_transform/tf_metadata/dataset_metadata.py
# class DatasetMetadata:
# def __init__(self, schema: schema_pb2.Schema):
# def from_feature_spec(
# cls: Type[_DatasetMetadataType],
# feature_spec: Mapping[str, common_types.FeatureSpecType],
# domains: Optional[Mapping[str, common_types.DomainType]] = None
# ) -> _DatasetMetadataType:
# def schema(self) -> schema_pb2.Schema:
# def __eq__(self, other):
# def __ne__(self, other):
# def __repr__(self):
#
# Path: tensorflow_transform/tf_metadata/metadata_io.py
# def read_metadata(path):
# def _parse_schema_json(schema_json):
# def _column_schema_from_json(feature_dict):
# def _domain_from_json(domain):
# def maybe_to_int(s):
# def _dtype_from_json(domain):
# def write_metadata(metadata, path):
# def _convert_scalar_or_list(fn, scalar_or_list):
. Output only the next line. | original = dataset_metadata.DatasetMetadata( |
Continue the code snippet: <|code_start|> file_io.recursive_create_dir(version_basedir)
file_io.write_string_to_file(os.path.join(version_basedir, 'schema.json'),
schema_string)
def test_read_with_invalid_keys(self):
# TODO(b/123241798): use TEST_TMPDIR
basedir = tempfile.mkdtemp()
self._write_schema_to_disk(basedir, _SCHEMA_WITH_INVALID_KEYS)
def test_read_features_default_axis(self):
# TODO(b/123241798): use TEST_TMPDIR
basedir = tempfile.mkdtemp()
schema_no_sparse_features = """
{
"feature": [{
"name": "my_key",
"fixedShape": {},
"type": "INT",
"domain": {
"ints": {}
},
"parsingOptions": {
"tfOptions": {
"fixedLenFeature": {}
}
}
}]
}
"""
self._write_schema_to_disk(basedir, schema_no_sparse_features)
<|code_end|>
. Use current file imports:
import os
import tempfile
import unittest
from tensorflow_transform.tf_metadata import test_common
from tensorflow_transform.tf_metadata import dataset_metadata
from tensorflow_transform.tf_metadata import metadata_io
from tensorflow.python.lib.io import file_io # pylint: disable=g-direct-tensorflow-import
and context (classes, functions, or code) from other files:
# Path: tensorflow_transform/tf_metadata/test_common.py
# def get_test_schema():
#
# Path: tensorflow_transform/tf_metadata/dataset_metadata.py
# class DatasetMetadata:
# def __init__(self, schema: schema_pb2.Schema):
# def from_feature_spec(
# cls: Type[_DatasetMetadataType],
# feature_spec: Mapping[str, common_types.FeatureSpecType],
# domains: Optional[Mapping[str, common_types.DomainType]] = None
# ) -> _DatasetMetadataType:
# def schema(self) -> schema_pb2.Schema:
# def __eq__(self, other):
# def __ne__(self, other):
# def __repr__(self):
#
# Path: tensorflow_transform/tf_metadata/metadata_io.py
# def read_metadata(path):
# def _parse_schema_json(schema_json):
# def _column_schema_from_json(feature_dict):
# def _domain_from_json(domain):
# def maybe_to_int(s):
# def _dtype_from_json(domain):
# def write_metadata(metadata, path):
# def _convert_scalar_or_list(fn, scalar_or_list):
. Output only the next line. | _ = metadata_io.read_metadata(basedir) |
Next line prediction: <|code_start|>def supply_missing_tensor(batch_size: int, tensor_shape: tf.TensorShape,
tensor_dtype: tf.DType) -> tf.Tensor:
"""Supplies a `tf.Tensor` compatible with `tensor`.
Supports only string and numeric dtypes.
Args:
batch_size: an integer representing the size of the batch returned.
tensor_shape: a `tf.TensorShape`. The returned tensor will have shape
compatible with this.
tensor_dtype: The dtype of the returned tensors.
Returns:
A batch of `tf.Tensor` tensors.
"""
# If tensor rank is 0 or unknown, return a scalar.
if tensor_shape.ndims is None or tensor_shape.ndims == 0:
return tf.zeros([], dtype=tensor_dtype)
input_shape = tensor_shape.as_list()
result_shape = [input_shape[0] or batch_size]
for shape in input_shape[1:]:
if shape is None:
result_shape = result_shape + [1]
else:
result_shape = result_shape + [shape]
return tf.zeros(result_shape, dtype=tensor_dtype)
def supply_missing_inputs(
<|code_end|>
. Use current file imports:
(import copy
import itertools
import tensorflow as tf
from typing import Collection, Iterable, Mapping, Optional, Tuple
from tensorflow_transform import common_types
from tensorflow.python import tf2
from tensorflow.python.framework import ops
from tensorflow.python.framework.func_graph import FuncGraph)
and context including class names, function names, or small code snippets from other files:
# Path: tensorflow_transform/common_types.py
# def is_ragged_feature_available() -> bool:
# def is_ragged_feature(spec: FeatureSpecType) -> bool:
. Output only the next line. | structured_inputs: Mapping[str, common_types.TensorType], |
Next line prediction: <|code_start|> """
self._schema = schema
self._serialized = serialized
# Using pre-allocated tf.train.Example and FeatureHandler objects for
# performance reasons.
#
# Since the output of "encode" is deep as opposed to shallow
# transformations, and since the schema always fully defines the Example's
# FeatureMap (ie all fields are always cleared/assigned or copied), the
# optimization and implementation are correct and thread-compatible.
self._encode_example_cache = tf.train.Example()
self._feature_handlers = []
for name, feature_spec in schema_utils.schema_as_feature_spec(
schema).feature_spec.items():
if isinstance(feature_spec, tf.io.FixedLenFeature):
self._feature_handlers.append(
_FixedLenFeatureHandler(name, feature_spec))
elif isinstance(feature_spec, tf.io.VarLenFeature):
self._feature_handlers.append(
_VarLenFeatureHandler(name, feature_spec.dtype))
elif isinstance(feature_spec, tf.io.SparseFeature):
index_keys = (
feature_spec.index_key if isinstance(feature_spec.index_key, list)
else [feature_spec.index_key])
for index_key in index_keys:
self._feature_handlers.append(
_VarLenFeatureHandler(index_key, tf.int64))
self._feature_handlers.append(
_VarLenFeatureHandler(feature_spec.value_key, feature_spec.dtype))
<|code_end|>
. Use current file imports:
(import numpy as np
import tensorflow as tf
from tensorflow_transform import common_types
from tensorflow_transform.tf_metadata import schema_utils)
and context including class names, function names, or small code snippets from other files:
# Path: tensorflow_transform/common_types.py
# def is_ragged_feature_available() -> bool:
# def is_ragged_feature(spec: FeatureSpecType) -> bool:
#
# Path: tensorflow_transform/tf_metadata/schema_utils.py
# TENSOR_REPRESENTATION_GROUP = ''
# RAGGED_TENSOR_TAG = 'ragged_tensor'
# _DEPRECATED_LIFECYCLE_STAGES = [
# schema_pb2.DEPRECATED, schema_pb2.DISABLED, schema_pb2.PLANNED,
# schema_pb2.ALPHA, schema_pb2.DEBUG_ONLY
# ]
# _LEGACY_DEFAULT_VALUE_FOR_DTYPE = {tf.string: '', tf.int64: -1, tf.float32: -1}
# def schema_from_feature_spec(
# feature_spec: Mapping[str, common_types.FeatureSpecType],
# domains: Optional[Mapping[str, common_types.DomainType]] = None
# ) -> schema_pb2.Schema:
# def _ragged_tensor_representation_from_feature_spec(
# spec: common_types.RaggedFeature, name: str,
# domains: Dict[str, common_types.DomainType]
# ) -> Tuple[schema_pb2.Feature, List[schema_pb2.Feature],
# def _sparse_feature_from_feature_spec(spec, name, domains):
# def _feature_from_feature_spec(spec, name, domains):
# def _set_type(name, feature, dtype):
# def _set_domain(name, feature, domain):
# def schema_as_feature_spec(
# schema_proto: schema_pb2.Schema) -> SchemaAsFeatureSpecResult:
# def _get_string_domains(schema):
# def _get_domain(feature, string_domains):
# def pop_ragged_source_columns(
# name: str, tensor_representation: schema_pb2.TensorRepresentation,
# feature_by_name: Dict[str, schema_pb2.Feature]) -> schema_pb2.Feature:
# def _ragged_tensor_representation_as_feature_spec(
# name: str, tensor_representation: schema_pb2.TensorRepresentation,
# feature_by_name: Dict[str, schema_pb2.Feature],
# string_domains: Dict[str, common_types.DomainType]
# ) -> Tuple[common_types.RaggedFeature, Optional[common_types.DomainType]]:
# def _sparse_feature_as_feature_spec(feature, feature_by_name, string_domains):
# def _feature_as_feature_spec(feature, string_domains):
# def _feature_dtype(feature):
# def _fixed_shape_as_tf_shape(fixed_shape):
# def _include_in_parsing_spec(feature):
# def _legacy_schema_from_feature_spec(feature_spec, domains=None):
# def _legacy_schema_as_feature_spec(schema_proto):
# def _legacy_feature_as_feature_spec(feature):
# def _legacy_infer_default_value(feature_proto, dtype):
. Output only the next line. | elif common_types.is_ragged_feature(feature_spec): |
Next line prediction: <|code_start|> casted = self._cast_fn(values)
self._value.extend(casted)
class ExampleProtoCoder:
"""A coder between maybe-serialized TF Examples and tf.Transform datasets."""
def __init__(self, schema, serialized=True):
"""Build an ExampleProtoCoder.
Args:
schema: A `Schema` proto.
serialized: Whether to encode serialized Example protos (as opposed to
in-memory Example protos).
Raises:
ValueError: If `schema` is invalid.
"""
self._schema = schema
self._serialized = serialized
# Using pre-allocated tf.train.Example and FeatureHandler objects for
# performance reasons.
#
# Since the output of "encode" is deep as opposed to shallow
# transformations, and since the schema always fully defines the Example's
# FeatureMap (ie all fields are always cleared/assigned or copied), the
# optimization and implementation are correct and thread-compatible.
self._encode_example_cache = tf.train.Example()
self._feature_handlers = []
<|code_end|>
. Use current file imports:
(import numpy as np
import tensorflow as tf
from tensorflow_transform import common_types
from tensorflow_transform.tf_metadata import schema_utils)
and context including class names, function names, or small code snippets from other files:
# Path: tensorflow_transform/common_types.py
# def is_ragged_feature_available() -> bool:
# def is_ragged_feature(spec: FeatureSpecType) -> bool:
#
# Path: tensorflow_transform/tf_metadata/schema_utils.py
# TENSOR_REPRESENTATION_GROUP = ''
# RAGGED_TENSOR_TAG = 'ragged_tensor'
# _DEPRECATED_LIFECYCLE_STAGES = [
# schema_pb2.DEPRECATED, schema_pb2.DISABLED, schema_pb2.PLANNED,
# schema_pb2.ALPHA, schema_pb2.DEBUG_ONLY
# ]
# _LEGACY_DEFAULT_VALUE_FOR_DTYPE = {tf.string: '', tf.int64: -1, tf.float32: -1}
# def schema_from_feature_spec(
# feature_spec: Mapping[str, common_types.FeatureSpecType],
# domains: Optional[Mapping[str, common_types.DomainType]] = None
# ) -> schema_pb2.Schema:
# def _ragged_tensor_representation_from_feature_spec(
# spec: common_types.RaggedFeature, name: str,
# domains: Dict[str, common_types.DomainType]
# ) -> Tuple[schema_pb2.Feature, List[schema_pb2.Feature],
# def _sparse_feature_from_feature_spec(spec, name, domains):
# def _feature_from_feature_spec(spec, name, domains):
# def _set_type(name, feature, dtype):
# def _set_domain(name, feature, domain):
# def schema_as_feature_spec(
# schema_proto: schema_pb2.Schema) -> SchemaAsFeatureSpecResult:
# def _get_string_domains(schema):
# def _get_domain(feature, string_domains):
# def pop_ragged_source_columns(
# name: str, tensor_representation: schema_pb2.TensorRepresentation,
# feature_by_name: Dict[str, schema_pb2.Feature]) -> schema_pb2.Feature:
# def _ragged_tensor_representation_as_feature_spec(
# name: str, tensor_representation: schema_pb2.TensorRepresentation,
# feature_by_name: Dict[str, schema_pb2.Feature],
# string_domains: Dict[str, common_types.DomainType]
# ) -> Tuple[common_types.RaggedFeature, Optional[common_types.DomainType]]:
# def _sparse_feature_as_feature_spec(feature, feature_by_name, string_domains):
# def _feature_as_feature_spec(feature, string_domains):
# def _feature_dtype(feature):
# def _fixed_shape_as_tf_shape(fixed_shape):
# def _include_in_parsing_spec(feature):
# def _legacy_schema_from_feature_spec(feature_spec, domains=None):
# def _legacy_schema_as_feature_spec(schema_proto):
# def _legacy_feature_as_feature_spec(feature):
# def _legacy_infer_default_value(feature_proto, dtype):
. Output only the next line. | for name, feature_spec in schema_utils.schema_as_feature_spec( |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.