Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Continue the code snippet: <|code_start|>def tree(request, repo, sha, path=None):
try:
commit = repo.get_commit(sha)
except KeyError:
raise Http404
if not path or path[-1] == '/':
if request.is_ajax() and 'commits' in request.GET:
tree = commit.get_tree(path, commits=True).tree
tree_elements = []
for entry in tree:
tree_elements.append({
'tree_id': entry['sha'],
'id': entry['commit'].id,
'author': entry['commit'].author,
'commit_date': entry['commit'].commit_date,
'since': timesince(entry['commit'].commit_date),
})
return HttpResponse(simplejson.dumps(tree_elements,
cls=DjangoJSONEncoder), mimetype='application/json')
try:
tree = commit.get_tree(path)
except KeyError:
raise Http404
return render(request, 'trees/tree.html', {
'repository': repo,
'commit': commit,
'tree': tree,
<|code_end|>
. Use current file imports:
from django.core.serializers.json import DjangoJSONEncoder
from django.http import Http404, HttpResponse
from django.shortcuts import render
from django.template.defaultfilters import timesince
from django.utils import simplejson
from brigitte.repositories.decorators import repository_view
from brigitte.trees.utils import build_path_breadcrumb
from brigitte.utils.highlight import pygmentize
and context (classes, functions, or code) from other files:
# Path: brigitte/repositories/decorators.py
# def repository_view(can_admin=False):
# def inner_repository_view(f):
# def wrapped(request, user, slug, *args, **kwargs):
# qs = Repository.objects.none()
#
# if request.user.is_authenticated():
# if can_admin:
# qs = Repository.objects.manageable_repositories(request.user)
# else:
# qs = Repository.objects.available_repositories(request.user)
# else:
# if not can_admin:
# qs = Repository.objects.public_repositories()
#
# repository = get_object_or_404(qs, user__username=user, slug=slug)
#
# return f(request, repository, *args, **kwargs)
# return wraps(f)(wrapped)
# return inner_repository_view
#
# Path: brigitte/trees/utils.py
# def build_path_breadcrumb(path):
# if not path:
# return []
#
# links = []
# cur_path = None
#
# for part in path.split('/'):
# if cur_path:
# cur_path += '/' + part
# else:
# cur_path = part
#
# links.append({
# 'path': cur_path,
# 'name': part,
# })
#
# return links
#
# Path: brigitte/utils/highlight.py
# def pygmentize(mime, blob):
# try:
# lexer = lexers.get_lexer_for_mimetype(mime)
# except ClassNotFound:
# try:
# lexer = lexers.get_lexer_by_name(mime)
# except:
# lexer = lexers.get_lexer_by_name('text')
#
# pygmented_string = pygments.highlight(blob, lexer, NakedHtmlFormatter())
# pygmented_string = unescape_amp(pygmented_string)
#
# return mark_safe(pygmented_string)
. Output only the next line. | 'breadcrumb': build_path_breadcrumb(path) |
Given the code snippet: <|code_start|> tree_elements = []
for entry in tree:
tree_elements.append({
'tree_id': entry['sha'],
'id': entry['commit'].id,
'author': entry['commit'].author,
'commit_date': entry['commit'].commit_date,
'since': timesince(entry['commit'].commit_date),
})
return HttpResponse(simplejson.dumps(tree_elements,
cls=DjangoJSONEncoder), mimetype='application/json')
try:
tree = commit.get_tree(path)
except KeyError:
raise Http404
return render(request, 'trees/tree.html', {
'repository': repo,
'commit': commit,
'tree': tree,
'breadcrumb': build_path_breadcrumb(path)
})
else:
try:
file_obj = commit.get_file(path)
except KeyError:
raise Http404
<|code_end|>
, generate the next line using the imports in this file:
from django.core.serializers.json import DjangoJSONEncoder
from django.http import Http404, HttpResponse
from django.shortcuts import render
from django.template.defaultfilters import timesince
from django.utils import simplejson
from brigitte.repositories.decorators import repository_view
from brigitte.trees.utils import build_path_breadcrumb
from brigitte.utils.highlight import pygmentize
and context (functions, classes, or occasionally code) from other files:
# Path: brigitte/repositories/decorators.py
# def repository_view(can_admin=False):
# def inner_repository_view(f):
# def wrapped(request, user, slug, *args, **kwargs):
# qs = Repository.objects.none()
#
# if request.user.is_authenticated():
# if can_admin:
# qs = Repository.objects.manageable_repositories(request.user)
# else:
# qs = Repository.objects.available_repositories(request.user)
# else:
# if not can_admin:
# qs = Repository.objects.public_repositories()
#
# repository = get_object_or_404(qs, user__username=user, slug=slug)
#
# return f(request, repository, *args, **kwargs)
# return wraps(f)(wrapped)
# return inner_repository_view
#
# Path: brigitte/trees/utils.py
# def build_path_breadcrumb(path):
# if not path:
# return []
#
# links = []
# cur_path = None
#
# for part in path.split('/'):
# if cur_path:
# cur_path += '/' + part
# else:
# cur_path = part
#
# links.append({
# 'path': cur_path,
# 'name': part,
# })
#
# return links
#
# Path: brigitte/utils/highlight.py
# def pygmentize(mime, blob):
# try:
# lexer = lexers.get_lexer_for_mimetype(mime)
# except ClassNotFound:
# try:
# lexer = lexers.get_lexer_by_name(mime)
# except:
# lexer = lexers.get_lexer_by_name('text')
#
# pygmented_string = pygments.highlight(blob, lexer, NakedHtmlFormatter())
# pygmented_string = unescape_amp(pygmented_string)
#
# return mark_safe(pygmented_string)
. Output only the next line. | file_blob_pygmentized = pygmentize( |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
register = template.Library()
@register.filter
def pygmentize_diff(blob):
try:
<|code_end|>
. Use current file imports:
from django import template
from brigitte.utils.highlight import pygmentize
and context (classes, functions, or code) from other files:
# Path: brigitte/utils/highlight.py
# def pygmentize(mime, blob):
# try:
# lexer = lexers.get_lexer_for_mimetype(mime)
# except ClassNotFound:
# try:
# lexer = lexers.get_lexer_by_name(mime)
# except:
# lexer = lexers.get_lexer_by_name('text')
#
# pygmented_string = pygments.highlight(blob, lexer, NakedHtmlFormatter())
# pygmented_string = unescape_amp(pygmented_string)
#
# return mark_safe(pygmented_string)
. Output only the next line. | return pygmentize('diff', blob) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
class ProfileRegistrationForm(RegistrationForm):
short_info = forms.CharField(widget=forms.Textarea, required=False)
def save_profile(self, new_user, *args, **kwargs):
<|code_end|>
. Use current file imports:
(import base64
import struct
from django import forms
from django.utils.translation import ugettext_lazy as _
from userprofiles.forms import RegistrationForm
from brigitte.accounts.models import Profile, SshPublicKey)
and context including class names, function names, or small code snippets from other files:
# Path: brigitte/accounts/models.py
# class Profile(models.Model):
# user = models.OneToOneField(User, unique=True)
# short_info = models.TextField(_('Short info'), blank=True)
#
# def __unicode__(self):
# return '%s %s' % (self.user.first_name, self.user.last_name)
#
# @property
# def first_name(self):
# return self.user.first_name
#
# @property
# def last_name(self):
# return self.user.last_name
#
# class Meta:
# verbose_name = _('Profile')
# verbose_name_plural = _('Profiles')
#
# class SshPublicKey(models.Model):
# user = models.ForeignKey(User, verbose_name=_('User'), blank=False)
# description = models.CharField(_('Description'), max_length=250, blank=True)
# can_read = models.BooleanField(_('Can read'), default=True)
# can_write = models.BooleanField(_('Can write'), default=False)
# key = models.TextField(_('Key'), blank=False, unique=True)
# key_parsed = models.TextField(_('Key (parsed)'), blank=True, unique=True, editable=False)
#
# def __unicode__(self):
# if self.description:
# return self.description
# else:
# return self.short_key
#
# def save(self, *args, **kwargs):
# self.key_parsed = self.key.split()[1]
# super(SshPublicKey, self).save(*args, **kwargs)
#
# @property
# def short_key(self):
# return self.key[:32] + '...'
#
# @property
# def can_read_html(self):
# if self.can_read:
# return mark_safe('✔')
# else:
# return mark_safe('✘')
#
# @property
# def can_write_html(self):
# if self.can_write:
# return mark_safe('✔')
# else:
# return mark_safe('✘')
#
# class Meta:
# verbose_name = _('SSH Public Key')
# verbose_name_plural = _('SSH Public Keys')
. Output only the next line. | Profile.objects.create( |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
class ProfileRegistrationForm(RegistrationForm):
short_info = forms.CharField(widget=forms.Textarea, required=False)
def save_profile(self, new_user, *args, **kwargs):
Profile.objects.create(
user=new_user,
short_info=self.cleaned_data['short_info']
)
class SshPublicKeyForm(forms.ModelForm):
class Meta:
<|code_end|>
, generate the next line using the imports in this file:
import base64
import struct
from django import forms
from django.utils.translation import ugettext_lazy as _
from userprofiles.forms import RegistrationForm
from brigitte.accounts.models import Profile, SshPublicKey
and context (functions, classes, or occasionally code) from other files:
# Path: brigitte/accounts/models.py
# class Profile(models.Model):
# user = models.OneToOneField(User, unique=True)
# short_info = models.TextField(_('Short info'), blank=True)
#
# def __unicode__(self):
# return '%s %s' % (self.user.first_name, self.user.last_name)
#
# @property
# def first_name(self):
# return self.user.first_name
#
# @property
# def last_name(self):
# return self.user.last_name
#
# class Meta:
# verbose_name = _('Profile')
# verbose_name_plural = _('Profiles')
#
# class SshPublicKey(models.Model):
# user = models.ForeignKey(User, verbose_name=_('User'), blank=False)
# description = models.CharField(_('Description'), max_length=250, blank=True)
# can_read = models.BooleanField(_('Can read'), default=True)
# can_write = models.BooleanField(_('Can write'), default=False)
# key = models.TextField(_('Key'), blank=False, unique=True)
# key_parsed = models.TextField(_('Key (parsed)'), blank=True, unique=True, editable=False)
#
# def __unicode__(self):
# if self.description:
# return self.description
# else:
# return self.short_key
#
# def save(self, *args, **kwargs):
# self.key_parsed = self.key.split()[1]
# super(SshPublicKey, self).save(*args, **kwargs)
#
# @property
# def short_key(self):
# return self.key[:32] + '...'
#
# @property
# def can_read_html(self):
# if self.can_read:
# return mark_safe('✔')
# else:
# return mark_safe('✘')
#
# @property
# def can_write_html(self):
# if self.can_write:
# return mark_safe('✔')
# else:
# return mark_safe('✘')
#
# class Meta:
# verbose_name = _('SSH Public Key')
# verbose_name_plural = _('SSH Public Keys')
. Output only the next line. | model = SshPublicKey |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
class RepositoryUserInline(admin.TabularInline):
model = RepositoryUser
extra = 2
class RepositoryAdmin(admin.ModelAdmin):
list_display = ('title', 'path', 'user')
inlines = [RepositoryUserInline]
<|code_end|>
. Use current file imports:
from django.contrib import admin
from brigitte.repositories.models import Repository, RepositoryUser
and context (classes, functions, or code) from other files:
# Path: brigitte/repositories/models.py
# class Repository(models.Model):
# user = models.ForeignKey(User, verbose_name=_('User'))
# slug = models.SlugField(_('Slug'), max_length=80, blank=False)
# title = models.CharField(_('Title'), max_length=80)
# description = models.TextField(_('Description'), blank=True)
# private = models.BooleanField(_('Private'), default=False)
# repo_type = models.CharField(_('Type'), max_length=4, choices=REPO_TYPES,
# default='git')
# last_commit_date = models.DateTimeField(blank=True, null=True)
#
# objects = RepositoryManager()
#
# def __unicode__(self):
# return self.title
#
# def get_last_commit(self):
# # TODO: cache self.last_commit with git hook ...
# last_commit = self.last_commit
# if not self.last_commit_date and last_commit:
# self.last_commit_date = last_commit.commit_date
# self.save()
# elif self.last_commit_date and last_commit and self.last_commit_date != last_commit.commit_date:
# self.last_commit_date = self.last_commit.commit_date
# self.save()
# return last_commit
#
# @property
# def private_html(self):
# if self.private:
# return mark_safe('✔')
# else:
# return mark_safe('✘')
#
# @property
# def path(self):
# if self.repo_type == 'git':
# return os.path.join(BRIGITTE_GIT_BASE_PATH, self.user.username,
# '%s.git' % self.slug)
#
# return None
#
# @property
# def short_path(self):
# if self.repo_type == 'git':
# return '%s/%s.git' % (self.user.username, self.slug)
#
# return None
#
# @property
# def _repo(self):
# if not hasattr(self, '_repo_obj'):
# self._repo_obj = get_backend(self.repo_type)(self)
# return self._repo_obj
#
# def recent_commits(self, count=10):
# return self._repo.get_commits(count=count)
#
# @property
# def last_commit(self):
# if not hasattr(self, '_last_commit'):
# self._last_commit = self._repo.last_commit
# return self._last_commit
#
# @property
# def tags(self):
# if not hasattr(self, '_tags'):
# self._tags = self._repo.tags
# return self._tags
#
# @property
# def branches(self):
# if not hasattr(self, '_branches'):
# self._branches = self._repo.branches
# return self._branches
#
# @property
# def rw_url(self):
# if self.repo_type == 'git':
# return 'git@%s:%s' % (
# Site.objects.get_current(), self.short_path)
#
# return None
#
# @property
# def ro_url(self):
# if self.repo_type == 'git':
# return 'git://%s/%s' % (Site.objects.get_current(), self.short_path)
#
# return None
#
# def get_commit(self, sha):
# return self._repo.get_commit(sha)
#
# def get_commits(self, count=10, skip=0, head=None):
# return self._repo.get_commits(count=count, skip=skip, head=head)
#
# @property
# def alterable_users(self):
# return self.repositoryuser_set.exclude(user=self.user)
#
# def save(self, *args, **kwargs):
# if not self.pk:
# self._repo.init_repo()
# self._repo.repo_settings_changed()
# super(Repository, self).save(*args, **kwargs)
#
# def delete(self, *args, **kwargs):
# self._repo.delete_repo(self.slug)
# super(Repository, self).delete(*args, **kwargs)
#
# class Meta:
# unique_together = ('user', 'slug')
# verbose_name = _('Repository')
# verbose_name_plural = _('Repositories')
#
# class RepositoryUser(models.Model):
# repo = models.ForeignKey(Repository, verbose_name=_('Repository'))
# user = models.ForeignKey(User, verbose_name=_('User'))
#
# can_read = models.BooleanField(_('Can read'), default=True)
# can_write = models.BooleanField(_('Can write'), default=False)
# can_admin = models.BooleanField(_('Can admin'), default=False)
#
# def __unicode__(self):
# return '%s/%s (%s, %s, %s)' % (
# self.repo,
# self.user,
# self.can_read,
# self.can_write,
# self.can_admin
# )
#
# def save(self, *args, **kwargs):
# if self.can_admin:
# self.can_write = True
# self.can_read = True
# elif self.can_write:
# self.can_read = True
#
# super(RepositoryUser, self).save(*args, **kwargs)
#
# class Meta:
# unique_together = ('repo', 'user')
# verbose_name = _('Repository user')
# verbose_name_plural = _('Repository users')
. Output only the next line. | admin.site.register(Repository, RepositoryAdmin) |
Given the code snippet: <|code_start|>
class MinPQUnitTest(unittest.TestCase):
def test_min(self):
pq = MinPQ.create()
pq.enqueue(10)
pq.enqueue(5)
pq.enqueue(12)
pq.enqueue(14)
pq.enqueue(2)
self.assertFalse(pq.is_empty())
self.assertEqual(5, pq.size())
print([i for i in pq.iterate()])
self.assertEqual(2, pq.del_min())
self.assertEqual(5, pq.del_min())
self.assertEqual(10, pq.del_min())
self.assertEqual(12, pq.del_min())
self.assertEqual(14, pq.del_min())
self.assertTrue(pq.is_empty())
self.assertEqual(0, pq.size())
class MaxPQUnitTest(unittest.TestCase):
def test_min(self):
<|code_end|>
, generate the next line using the imports in this file:
import unittest
from pyalgs.data_structures.commons.priority_queue import MinPQ, MaxPQ
and context (functions, classes, or occasionally code) from other files:
# Path: pyalgs/data_structures/commons/priority_queue.py
# class MinPQ(object):
# pq = None
# N = 0
#
# def __init__(self, capacity=None):
# if capacity is None:
# capacity = 10
# self.pq = [0] * capacity
#
# def enqueue(self, key):
# self.N += 1
# if self.N == len(self.pq):
# self.resize(len(self.pq) * 2)
#
# self.pq[self.N] = key
# self.swim(self.N)
#
# def swim(self, k):
# while k > 1:
# parent = k // 2
# if less(self.pq[k], self.pq[parent]):
# exchange(self.pq, k, parent)
# k = parent
# else:
# break
#
# def del_min(self):
# if self.is_empty():
# return None
#
# key = self.pq[1]
# exchange(self.pq, 1, self.N)
# self.N -= 1
# if self.N == len(self.pq) // 4:
# self.resize(len(self.pq) // 2)
#
# self.sink(self.pq, 1, self.N)
# return key
#
# @staticmethod
# def sink(tmp, k, n):
#
# while k * 2 <= n:
# child = k * 2
# if child < n and less(tmp[child + 1], tmp[child]):
# child = child + 1
# if less(tmp[child], tmp[k]):
# exchange(tmp, child, k)
# k = child
# else:
# break
#
# def resize(self, new_size):
# tmp = [0] * new_size
# for k in range(min(new_size, len(self.pq))):
# tmp[k] = self.pq[k]
# self.pq = tmp
#
# def is_empty(self):
# return self.N == 0
#
# def size(self):
# return self.N
#
# def iterate(self):
# tmp = [0] * (self.N + 1)
# for k in range(self.N + 1):
# tmp[k] = self.pq[k]
#
# n = self.N
# while n >= 1:
# key = tmp[1]
# exchange(tmp, 1, n)
# n -= 1
# self.sink(tmp, 1, n)
# yield key
#
# @staticmethod
# def create():
# return MinPQ()
#
# class MaxPQ(object):
# pq = None
# N = 0
#
# def __init__(self, capacity=None):
# if capacity is None:
# capacity = 10
# self.pq = [0] * capacity
#
# def enqueue(self, key):
# if self.N == len(self.pq):
# self.resize(len(self.pq) * 2)
# self.N += 1
# self.pq[self.N] = key
# self.swim(self.N)
#
# def swim(self, k):
# while k > 1:
# parent = k // 2
# if greater(self.pq[k], self.pq[parent]):
# exchange(self.pq, k, parent)
# k = parent
# else:
# break
#
# def del_max(self):
# if self.is_empty():
# return None
#
# key = self.pq[1]
# exchange(self.pq, 1, self.N)
# self.N -= 1
# if self.N == len(self.pq) // 4:
# self.resize(len(self.pq) // 2)
#
# self.sink(self.pq, 1, self.N)
# return key
#
# @staticmethod
# def sink(tmp, k, n):
#
# while k * 2 <= n:
# child = k * 2
# if child < n and greater(tmp[child + 1], tmp[child]):
# child = child + 1
# if greater(tmp[child], tmp[k]):
# exchange(tmp, child, k)
# k = child
# else:
# break
#
# def resize(self, new_size):
# tmp = [0] * new_size
# for k in range(min(new_size, len(self.pq))):
# tmp[k] = self.pq[k]
# self.pq = tmp
#
# def is_empty(self):
# return self.N == 0
#
# def size(self):
# return self.N
#
# def iterate(self):
# tmp = [0] * (self.N + 1)
# for k in range(self.N + 1):
# tmp[k] = self.pq[k]
#
# n = self.N
# while n >= 1:
# key = tmp[1]
# exchange(tmp, 1, n)
# n -= 1
# self.sink(tmp, 1, n)
# yield key
#
# @staticmethod
# def create():
# return MaxPQ()
. Output only the next line. | pq = MaxPQ.create() |
Here is a snippet: <|code_start|>
class DirectedCycleUnitTest(unittest.TestCase):
def test_cycle(self):
dag = create_dag()
<|code_end|>
. Write the next line using the current file imports:
import unittest
from pyalgs.algorithms.graphs.directed_cycle import DirectedCycle
from tests.algorithms.graphs.util import create_dag
and context from other files:
# Path: pyalgs/algorithms/graphs/directed_cycle.py
# class DirectedCycle(object):
#
# marked = None
# onStack = None
# cycle = None
# edgeTo = None
#
# def __init__(self, G):
# if isinstance(G, DirectedEdgeWeightedGraph):
# G = G.to_digraph()
#
# if not isinstance(G, Digraph):
# raise ValueError('Graph must be unweighted digraph')
#
# vertex_count = G.vertex_count()
# self.marked = [False] * vertex_count
# self.onStack = [False] * vertex_count
# self.edgeTo = [-1] * vertex_count
#
# for v in range(vertex_count):
# if not self.marked[v]:
# self.dfs(G, v)
#
# def dfs(self, G, v):
# self.marked[v] = True
# self.onStack[v] = True
#
# for w in G.adj(v):
# if not self.marked[w]:
# self.edgeTo[w] = v
# self.dfs(G, w)
# elif self.cycle is not None:
# break
# elif self.onStack[w]:
# self.cycle = Stack.create()
# x = v
# while x != w:
# self.cycle.push(x)
# x = self.edgeTo[x]
# self.cycle.push(w)
# self.cycle.push(v)
# break
#
# self.onStack[v] = False
#
# def hasCycle(self):
# return self.cycle is not None
#
# def get_cycle(self):
# return self.cycle.iterate()
#
# Path: tests/algorithms/graphs/util.py
# def create_dag():
# dag = Digraph(7)
#
# dag.add_edge(0, 5)
# dag.add_edge(0, 2)
# dag.add_edge(0, 1)
# dag.add_edge(3, 6)
# dag.add_edge(3, 5)
# dag.add_edge(3, 4)
# dag.add_edge(5, 4)
# dag.add_edge(6, 4)
# dag.add_edge(6, 0)
# dag.add_edge(3, 2)
# dag.add_edge(1, 4)
#
# return dag
, which may include functions, classes, or code. Output only the next line. | dc = DirectedCycle(dag) |
Given snippet: <|code_start|>
class FordFulkersonMaxFlowUnitTest(unittest.TestCase):
def test_max_flow(self):
network = create_flow_network()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
from pyalgs.algorithms.graphs.max_flow import FordFulkersonMaxFlow
from tests.algorithms.graphs.util import create_flow_network
and context:
# Path: pyalgs/algorithms/graphs/max_flow.py
# class FordFulkersonMaxFlow(object):
# edgeTo = None
# marked = None
# s = None
# t = None
# value = 0.0
# network = None
#
# def __init__(self, network, s, t):
# self.s = s
# self.t = t
# self.network = network
# self.value = 0.0
# while self.has_augmenting_path():
# x = self.t
# bottle = float('inf')
# while x != self.s:
# bottle = min(bottle, self.edgeTo[x].residual_capacity_to(x))
# x = self.edgeTo[x].other(x)
#
# x = self.t
# while x != self.s:
# self.edgeTo[x].add_residual_flow_to(x, bottle)
# x = self.edgeTo[x].other(x)
#
# self.value += bottle
#
# def has_augmenting_path(self):
# vertex_count = self.network.vertex_count()
# self.edgeTo = [None] * vertex_count
# self.marked = [False] * vertex_count
#
# queue = Queue.create()
#
# queue.enqueue(self.s)
# self.marked[self.s] = True
#
# while not queue.is_empty():
# x = queue.dequeue()
# for e in self.network.adj(x):
# w = e.other(x)
# if e.residual_capacity_to(w) > 0:
# if not self.marked[w]:
# self.marked[w] = True
# self.edgeTo[w] = e
# queue.enqueue(w)
#
# return self.marked[self.t]
#
# def max_flow_value(self):
# return self.value
#
# def min_cut(self):
# queue = Queue.create()
# for edge in self.network.edges():
# if edge.residual_capacity_to(edge.end()) == 0:
# queue.enqueue(edge)
#
# return queue.iterate()
#
# Path: tests/algorithms/graphs/util.py
# def create_flow_network():
# g = FlowNetwork(8)
# g.add_edge(FlowEdge(0, 1, 10))
# g.add_edge(FlowEdge(0, 2, 5))
# g.add_edge(FlowEdge(0, 3, 15))
# g.add_edge(FlowEdge(1, 4, 9))
# g.add_edge(FlowEdge(1, 5, 15))
# g.add_edge(FlowEdge(1, 2, 4))
# g.add_edge(FlowEdge(2, 5, 8))
# g.add_edge(FlowEdge(2, 3, 4))
# g.add_edge(FlowEdge(3, 6, 16))
# g.add_edge(FlowEdge(4, 5, 15))
# g.add_edge(FlowEdge(4, 7, 10))
# g.add_edge(FlowEdge(5, 7, 10))
# g.add_edge(FlowEdge(5, 6, 15))
# g.add_edge(FlowEdge(6, 2, 6))
# g.add_edge(FlowEdge(6, 7, 10))
#
# return g
which might include code, classes, or functions. Output only the next line. | ff = FordFulkersonMaxFlow(network, 0, 7) |
Given the code snippet: <|code_start|>
class QueueUnitTest(unittest.TestCase):
def test_Queue(self):
queue = Queue.create()
queue.enqueue(10)
self.assertEqual(1, queue.size())
self.assertFalse(queue.is_empty())
queue.enqueue(20)
self.assertEqual(2, queue.size())
queue.enqueue(30)
print([i for i in queue.iterate()])
self.assertEqual(3, queue.size())
self.assertEqual(10, queue.dequeue())
self.assertEqual(2, queue.size())
self.assertEqual(20, queue.dequeue())
self.assertEqual(1, queue.size())
self.assertEqual(30, queue.dequeue())
self.assertTrue(queue.is_empty())
def test_LinkedListQueue(self):
<|code_end|>
, generate the next line using the imports in this file:
import unittest
from pyalgs.data_structures.commons.queue import LinkedListQueue, Queue, ArrayQueue
and context (functions, classes, or occasionally code) from other files:
# Path: pyalgs/data_structures/commons/queue.py
# class LinkedListQueue(Queue):
#
# first = None
# last = None
# N = 0
#
# def size(self):
# return self.N
#
# def iterate(self):
# x = self.first
# while x is not None:
# value = x.value
# x = x.nextNode
# yield value
#
# def enqueue(self, item):
# old_last = self.last
# self.last = Node(item)
# if old_last is not None:
# old_last.nextNode = self.last
# if self.first is None:
# self.first = self.last
# self.N += 1
#
# def is_empty(self):
# return self.N == 0
#
# def dequeue(self):
# if self.is_empty():
# return None
# old_first = self.first
# self.first = old_first.nextNode
# if old_first == self.last:
# self.last = None
# self.N -= 1
# return old_first.value
#
# class Queue(object):
# """ Queue interface
#
# """
#
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def enqueue(self, item):
# pass
#
# @abstractmethod
# def dequeue(self):
# pass
#
# @abstractmethod
# def is_empty(self):
# pass
#
# @abstractmethod
# def size(self):
# pass
#
# @staticmethod
# def create():
# return LinkedListQueue()
#
# @abstractmethod
# def iterate(self):
# pass
#
# class ArrayQueue(Queue):
#
# head = 0
# tail = 0
# s = []
#
# def __init__(self, capacity=None):
# if capacity is None:
# capacity = 10
# self.s = [0] * capacity
#
# def iterate(self):
# if self.is_empty():
# return
# for i in range(self.head, self.tail):
# yield self.s[i]
#
# def enqueue(self, item):
# self.s[self.tail] = item
# self.tail += 1
# if self.tail == len(self.s):
# self.resize(len(self.s) * 2)
#
# def resize(self, new_size):
# tmp = [0] * new_size
# for i in range(self.head, self.tail):
# tmp[i-self.head] = self.s[i]
# self.s = tmp
# self.tail = self.tail - self.head
# self.head = 0
#
# def size(self):
# return self.tail - self.head
#
# def is_empty(self):
# return self.size() == 0
#
# def dequeue(self):
# if self.is_empty():
# return None
#
# deleted = self.s[self.head]
# self.head += 1
# if self.size() == len(self.s) // 4:
# self.resize(len(self.s) // 2)
# return deleted
. Output only the next line. | queue = LinkedListQueue() |
Next line prediction: <|code_start|> print([i for i in queue.iterate()])
self.assertEqual(3, queue.size())
self.assertEqual(10, queue.dequeue())
self.assertEqual(2, queue.size())
self.assertEqual(20, queue.dequeue())
self.assertEqual(1, queue.size())
self.assertEqual(30, queue.dequeue())
self.assertTrue(queue.is_empty())
def test_LinkedListQueue(self):
queue = LinkedListQueue()
queue.enqueue(10)
self.assertEqual(1, queue.size())
self.assertFalse(queue.is_empty())
queue.enqueue(20)
self.assertEqual(2, queue.size())
queue.enqueue(30)
print([i for i in queue.iterate()])
self.assertEqual(3, queue.size())
self.assertEqual(10, queue.dequeue())
self.assertEqual(2, queue.size())
self.assertEqual(20, queue.dequeue())
self.assertEqual(1, queue.size())
self.assertEqual(30, queue.dequeue())
self.assertTrue(queue.is_empty())
def test_ArrayQueue(self):
<|code_end|>
. Use current file imports:
(import unittest
from pyalgs.data_structures.commons.queue import LinkedListQueue, Queue, ArrayQueue)
and context including class names, function names, or small code snippets from other files:
# Path: pyalgs/data_structures/commons/queue.py
# class LinkedListQueue(Queue):
#
# first = None
# last = None
# N = 0
#
# def size(self):
# return self.N
#
# def iterate(self):
# x = self.first
# while x is not None:
# value = x.value
# x = x.nextNode
# yield value
#
# def enqueue(self, item):
# old_last = self.last
# self.last = Node(item)
# if old_last is not None:
# old_last.nextNode = self.last
# if self.first is None:
# self.first = self.last
# self.N += 1
#
# def is_empty(self):
# return self.N == 0
#
# def dequeue(self):
# if self.is_empty():
# return None
# old_first = self.first
# self.first = old_first.nextNode
# if old_first == self.last:
# self.last = None
# self.N -= 1
# return old_first.value
#
# class Queue(object):
# """ Queue interface
#
# """
#
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def enqueue(self, item):
# pass
#
# @abstractmethod
# def dequeue(self):
# pass
#
# @abstractmethod
# def is_empty(self):
# pass
#
# @abstractmethod
# def size(self):
# pass
#
# @staticmethod
# def create():
# return LinkedListQueue()
#
# @abstractmethod
# def iterate(self):
# pass
#
# class ArrayQueue(Queue):
#
# head = 0
# tail = 0
# s = []
#
# def __init__(self, capacity=None):
# if capacity is None:
# capacity = 10
# self.s = [0] * capacity
#
# def iterate(self):
# if self.is_empty():
# return
# for i in range(self.head, self.tail):
# yield self.s[i]
#
# def enqueue(self, item):
# self.s[self.tail] = item
# self.tail += 1
# if self.tail == len(self.s):
# self.resize(len(self.s) * 2)
#
# def resize(self, new_size):
# tmp = [0] * new_size
# for i in range(self.head, self.tail):
# tmp[i-self.head] = self.s[i]
# self.s = tmp
# self.tail = self.tail - self.head
# self.head = 0
#
# def size(self):
# return self.tail - self.head
#
# def is_empty(self):
# return self.size() == 0
#
# def dequeue(self):
# if self.is_empty():
# return None
#
# deleted = self.s[self.head]
# self.head += 1
# if self.size() == len(self.s) // 4:
# self.resize(len(self.s) // 2)
# return deleted
. Output only the next line. | queue = ArrayQueue() |
Given the following code snippet before the placeholder: <|code_start|> def __init__(self, m=None):
if m is None:
m = 97
self.M = m
self.id = [None] * self.M
def hash(self, key):
return (hash(key) & 0x7fffffff) % self.M
def is_empty(self):
return self.N == 0
def contains_key(self, key):
return self.get(key) is not None
def keys(self):
for i in range(self.M):
x = self.id[i]
while x is not None:
key = x.key
x = x.next_node
yield key
def size(self):
return self.N
def get(self, key):
i = self.hash(key)
x = self.id[i]
while x is not None:
<|code_end|>
, predict the next line using imports from the current file:
from abc import ABCMeta, abstractmethod
from pyalgs.algorithms.commons import util
and context including class names, function names, and sometimes code from other files:
# Path: pyalgs/algorithms/commons/util.py
# def less(a, b):
# def greater(a, b):
# def cmp(a, b):
# def exchange(a, i, j):
# def is_sorted(a):
. Output only the next line. | if util.cmp(x.key, key) == 0: |
Using the snippet: <|code_start|>
class DepthFirstSearchUnitTest(unittest.TestCase):
def test_dfs(self):
g = create_graph() # or create_digraph
s = 0
<|code_end|>
, determine the next line of code. You have imports:
import unittest
from pyalgs.algorithms.graphs.search import DepthFirstSearch, BreadthFirstSearch
from tests.algorithms.graphs.util import create_graph, create_digraph
and context (class names, function names, or code) available:
# Path: pyalgs/algorithms/graphs/search.py
# class DepthFirstSearch(Paths):
# marked = None
# edgesTo = None
# s = None
#
# def __init__(self, G, s):
# if isinstance(G, EdgeWeightedGraph):
# G = G.to_graph()
# self.s = s
# vertex_count = G.vertex_count()
# self.marked = [False] * vertex_count
# self.edgesTo = [-1] * vertex_count
# self.dfs(G, s)
#
# def dfs(self, G, v):
# self.marked[v] = True
# for w in G.adj(v):
# if not self.marked[w]:
# self.edgesTo[w] = v
# self.dfs(G, w)
#
# def hasPathTo(self, v):
# return self.marked[v]
#
# def pathTo(self, v):
# x = v
# path = Stack.create()
# while x != self.s:
# path.push(x)
# x = self.edgesTo[x]
# path.push(self.s)
# return path.iterate()
#
# class BreadthFirstSearch(Paths):
#
# marked = None
# s = None
# edgeTo = None
#
# def __init__(self, G, s):
# if isinstance(G, EdgeWeightedGraph):
# G = G.to_graph()
# self.s = s
# vertex_count = G.vertex_count()
# self.marked = [False] * vertex_count
# self.edgeTo = [-1] * vertex_count
#
# queue = Queue.create()
#
# queue.enqueue(s)
# while not queue.is_empty():
# v = queue.dequeue()
# self.marked[v] = True
# for w in G.adj(v):
# if not self.marked[w]:
# self.edgeTo[w] = v
# queue.enqueue(w)
#
# def hasPathTo(self, v):
# return self.marked[v]
#
# def pathTo(self, v):
# x = v
# path = Stack.create()
# while x != self.s:
# path.push(x)
# x = self.edgeTo[x]
# path.push(self.s)
# return path.iterate()
#
# Path: tests/algorithms/graphs/util.py
# def create_graph():
# g = Graph(6)
# g.add_edge(0, 5)
# g.add_edge(2, 4)
# g.add_edge(2, 3)
# g.add_edge(1, 2)
# g.add_edge(0, 1)
# g.add_edge(3, 4)
# g.add_edge(3, 5)
# g.add_edge(0, 2)
#
# return g
#
# def create_digraph():
# g = Digraph(13)
# g.add_edge(4, 2)
# g.add_edge(2, 3)
# g.add_edge(3, 2)
# g.add_edge(6, 0)
# g.add_edge(0, 1)
# g.add_edge(2, 0)
# g.add_edge(11, 12)
# g.add_edge(12, 9)
# g.add_edge(9, 10)
# g.add_edge(9, 11)
# g.add_edge(7, 9)
# g.add_edge(10, 12)
# g.add_edge(11, 4)
# g.add_edge(4, 3)
# g.add_edge(3, 5)
# g.add_edge(6, 8)
# g.add_edge(8, 6)
# g.add_edge(5, 4)
# g.add_edge(0, 5)
# g.add_edge(6, 4)
# g.add_edge(6, 9)
# g.add_edge(7, 6)
#
# return g
. Output only the next line. | dfs = DepthFirstSearch(g, s) |
Based on the snippet: <|code_start|>
class DepthFirstSearchUnitTest(unittest.TestCase):
def test_dfs(self):
g = create_graph() # or create_digraph
s = 0
dfs = DepthFirstSearch(g, s)
for v in range(1, g.vertex_count()):
if dfs.hasPathTo(v):
print(str(s) + ' is connected to ' + str(v))
print('path is ' + ' => '.join([str(i) for i in dfs.pathTo(v)]))
def test_dfs_digraph(self):
g = create_digraph()
s = 0
dfs = DepthFirstSearch(g, s)
for v in range(1, g.vertex_count()):
if dfs.hasPathTo(v):
print(str(s) + ' is connected to ' + str(v))
print('path is ' + ' => '.join([str(i) for i in dfs.pathTo(v)]))
class BreadthFirstSearchUnitTest(unittest.TestCase):
def test_dfs(self):
g = create_graph() # or create_digraph
s = 0
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
from pyalgs.algorithms.graphs.search import DepthFirstSearch, BreadthFirstSearch
from tests.algorithms.graphs.util import create_graph, create_digraph
and context (classes, functions, sometimes code) from other files:
# Path: pyalgs/algorithms/graphs/search.py
# class DepthFirstSearch(Paths):
# marked = None
# edgesTo = None
# s = None
#
# def __init__(self, G, s):
# if isinstance(G, EdgeWeightedGraph):
# G = G.to_graph()
# self.s = s
# vertex_count = G.vertex_count()
# self.marked = [False] * vertex_count
# self.edgesTo = [-1] * vertex_count
# self.dfs(G, s)
#
# def dfs(self, G, v):
# self.marked[v] = True
# for w in G.adj(v):
# if not self.marked[w]:
# self.edgesTo[w] = v
# self.dfs(G, w)
#
# def hasPathTo(self, v):
# return self.marked[v]
#
# def pathTo(self, v):
# x = v
# path = Stack.create()
# while x != self.s:
# path.push(x)
# x = self.edgesTo[x]
# path.push(self.s)
# return path.iterate()
#
# class BreadthFirstSearch(Paths):
#
# marked = None
# s = None
# edgeTo = None
#
# def __init__(self, G, s):
# if isinstance(G, EdgeWeightedGraph):
# G = G.to_graph()
# self.s = s
# vertex_count = G.vertex_count()
# self.marked = [False] * vertex_count
# self.edgeTo = [-1] * vertex_count
#
# queue = Queue.create()
#
# queue.enqueue(s)
# while not queue.is_empty():
# v = queue.dequeue()
# self.marked[v] = True
# for w in G.adj(v):
# if not self.marked[w]:
# self.edgeTo[w] = v
# queue.enqueue(w)
#
# def hasPathTo(self, v):
# return self.marked[v]
#
# def pathTo(self, v):
# x = v
# path = Stack.create()
# while x != self.s:
# path.push(x)
# x = self.edgeTo[x]
# path.push(self.s)
# return path.iterate()
#
# Path: tests/algorithms/graphs/util.py
# def create_graph():
# g = Graph(6)
# g.add_edge(0, 5)
# g.add_edge(2, 4)
# g.add_edge(2, 3)
# g.add_edge(1, 2)
# g.add_edge(0, 1)
# g.add_edge(3, 4)
# g.add_edge(3, 5)
# g.add_edge(0, 2)
#
# return g
#
# def create_digraph():
# g = Digraph(13)
# g.add_edge(4, 2)
# g.add_edge(2, 3)
# g.add_edge(3, 2)
# g.add_edge(6, 0)
# g.add_edge(0, 1)
# g.add_edge(2, 0)
# g.add_edge(11, 12)
# g.add_edge(12, 9)
# g.add_edge(9, 10)
# g.add_edge(9, 11)
# g.add_edge(7, 9)
# g.add_edge(10, 12)
# g.add_edge(11, 4)
# g.add_edge(4, 3)
# g.add_edge(3, 5)
# g.add_edge(6, 8)
# g.add_edge(8, 6)
# g.add_edge(5, 4)
# g.add_edge(0, 5)
# g.add_edge(6, 4)
# g.add_edge(6, 9)
# g.add_edge(7, 6)
#
# return g
. Output only the next line. | dfs = BreadthFirstSearch(g, s) |
Given the following code snippet before the placeholder: <|code_start|>
class DepthFirstSearchUnitTest(unittest.TestCase):
def test_dfs(self):
g = create_graph() # or create_digraph
s = 0
dfs = DepthFirstSearch(g, s)
for v in range(1, g.vertex_count()):
if dfs.hasPathTo(v):
print(str(s) + ' is connected to ' + str(v))
print('path is ' + ' => '.join([str(i) for i in dfs.pathTo(v)]))
def test_dfs_digraph(self):
<|code_end|>
, predict the next line using imports from the current file:
import unittest
from pyalgs.algorithms.graphs.search import DepthFirstSearch, BreadthFirstSearch
from tests.algorithms.graphs.util import create_graph, create_digraph
and context including class names, function names, and sometimes code from other files:
# Path: pyalgs/algorithms/graphs/search.py
# class DepthFirstSearch(Paths):
# marked = None
# edgesTo = None
# s = None
#
# def __init__(self, G, s):
# if isinstance(G, EdgeWeightedGraph):
# G = G.to_graph()
# self.s = s
# vertex_count = G.vertex_count()
# self.marked = [False] * vertex_count
# self.edgesTo = [-1] * vertex_count
# self.dfs(G, s)
#
# def dfs(self, G, v):
# self.marked[v] = True
# for w in G.adj(v):
# if not self.marked[w]:
# self.edgesTo[w] = v
# self.dfs(G, w)
#
# def hasPathTo(self, v):
# return self.marked[v]
#
# def pathTo(self, v):
# x = v
# path = Stack.create()
# while x != self.s:
# path.push(x)
# x = self.edgesTo[x]
# path.push(self.s)
# return path.iterate()
#
# class BreadthFirstSearch(Paths):
#
# marked = None
# s = None
# edgeTo = None
#
# def __init__(self, G, s):
# if isinstance(G, EdgeWeightedGraph):
# G = G.to_graph()
# self.s = s
# vertex_count = G.vertex_count()
# self.marked = [False] * vertex_count
# self.edgeTo = [-1] * vertex_count
#
# queue = Queue.create()
#
# queue.enqueue(s)
# while not queue.is_empty():
# v = queue.dequeue()
# self.marked[v] = True
# for w in G.adj(v):
# if not self.marked[w]:
# self.edgeTo[w] = v
# queue.enqueue(w)
#
# def hasPathTo(self, v):
# return self.marked[v]
#
# def pathTo(self, v):
# x = v
# path = Stack.create()
# while x != self.s:
# path.push(x)
# x = self.edgeTo[x]
# path.push(self.s)
# return path.iterate()
#
# Path: tests/algorithms/graphs/util.py
# def create_graph():
# g = Graph(6)
# g.add_edge(0, 5)
# g.add_edge(2, 4)
# g.add_edge(2, 3)
# g.add_edge(1, 2)
# g.add_edge(0, 1)
# g.add_edge(3, 4)
# g.add_edge(3, 5)
# g.add_edge(0, 2)
#
# return g
#
# def create_digraph():
# g = Digraph(13)
# g.add_edge(4, 2)
# g.add_edge(2, 3)
# g.add_edge(3, 2)
# g.add_edge(6, 0)
# g.add_edge(0, 1)
# g.add_edge(2, 0)
# g.add_edge(11, 12)
# g.add_edge(12, 9)
# g.add_edge(9, 10)
# g.add_edge(9, 11)
# g.add_edge(7, 9)
# g.add_edge(10, 12)
# g.add_edge(11, 4)
# g.add_edge(4, 3)
# g.add_edge(3, 5)
# g.add_edge(6, 8)
# g.add_edge(8, 6)
# g.add_edge(5, 4)
# g.add_edge(0, 5)
# g.add_edge(6, 4)
# g.add_edge(6, 9)
# g.add_edge(7, 6)
#
# return g
. Output only the next line. | g = create_digraph() |
Predict the next line after this snippet: <|code_start|>
class LSDUnitTest(unittest.TestCase):
def test_lsd(self):
words = words3()
print(words)
<|code_end|>
using the current file's imports:
import unittest
from pyalgs.algorithms.strings.sorting import LSD, MSD, String3WayQuickSort
from tests.algorithms.strings.util import words3
and any relevant context from other files:
# Path: pyalgs/algorithms/strings/sorting.py
# class LSD(object):
# R = 256
#
# @staticmethod
# def sort(a):
# W = len(a[0])
# aux = [None] * len(a)
#
# for d in range(W - 1, -1, -1):
# count = [0] * (LSD.R + 1)
#
# for i in range(len(a)):
# count[ord(a[i][d]) + 1] += 1
#
# for r in range(0, LSD.R):
# count[r + 1] += count[r]
#
# for i in range(len(a)):
# aux[count[ord(a[i][d])]] = a[i]
# count[ord(a[i][d])] += 1
#
# for i in range(len(a)):
# a[i] = aux[i]
#
# class MSD(object):
# R = 256
#
# @staticmethod
# def sort(a):
# MSD._sort(a, 0, len(a) - 1, 0)
#
# @staticmethod
# def _sort(a, lo, hi, d):
# if hi - lo <= 0:
# return
#
# count = [0] * (MSD.R + 2)
# aux = [None] * (hi - lo + 1)
#
# for i in range(lo, hi + 1):
# count[MSD.char_at(a[i], d) + 2] += 1
#
# for r in range(0, MSD.R):
# count[r + 1] += count[r]
#
# for i in range(lo, hi + 1):
# aux[count[MSD.char_at(a[i], d) + 1]] = a[i]
# count[MSD.char_at(a[i], d) + 1] += 1
#
# for i in range(lo, hi + 1):
# a[i] = aux[i - lo]
#
# for r in range(MSD.R):
# MSD._sort(a, lo + count[r], lo + count[r + 1] - 1, d + 1)
#
# @staticmethod
# def char_at(text, d):
# if len(text) <= d + 1:
# return -1
# return ord(text[d])
#
# class String3WayQuickSort(object):
# @staticmethod
# def sort(a):
# String3WayQuickSort._sort(a, 0, len(a) - 1, 0)
#
# @staticmethod
# def _sort(a, lo, hi, d):
# if lo >= hi:
# return
#
# lt = lo
# i = lo
# gt = hi
#
# c = String3WayQuickSort.char_at(a[lo], d)
#
# while i < gt:
# cmp = c - String3WayQuickSort.char_at(a[i], d)
# if cmp > 0:
# util.exchange(a, i, lt)
# i += 1
# lt += 1
# elif cmp < 0:
# util.exchange(a, i, gt)
# gt -= 1
# else:
# i += 1
#
# String3WayQuickSort._sort(a, lo, lt-1, d)
# if c >= 0:
# String3WayQuickSort._sort(a, lt, gt, d+1)
# String3WayQuickSort._sort(a, gt+1, hi, d)
#
# @staticmethod
# def char_at(text, d):
# if len(text) <= d + 1:
# return -1
# return ord(text[d])
#
# Path: tests/algorithms/strings/util.py
# def words3():
# words = some_text().split(' ')
# return words
. Output only the next line. | LSD.sort(words) |
Predict the next line for this snippet: <|code_start|>
class LSDUnitTest(unittest.TestCase):
def test_lsd(self):
words = words3()
print(words)
LSD.sort(words)
print(words)
class MSDUnitTest(unittest.TestCase):
def test_msd(self):
words = 'more details are provided in the docs for implementation, complexities and further info'.split(' ')
print(words)
<|code_end|>
with the help of current file imports:
import unittest
from pyalgs.algorithms.strings.sorting import LSD, MSD, String3WayQuickSort
from tests.algorithms.strings.util import words3
and context from other files:
# Path: pyalgs/algorithms/strings/sorting.py
# class LSD(object):
# R = 256
#
# @staticmethod
# def sort(a):
# W = len(a[0])
# aux = [None] * len(a)
#
# for d in range(W - 1, -1, -1):
# count = [0] * (LSD.R + 1)
#
# for i in range(len(a)):
# count[ord(a[i][d]) + 1] += 1
#
# for r in range(0, LSD.R):
# count[r + 1] += count[r]
#
# for i in range(len(a)):
# aux[count[ord(a[i][d])]] = a[i]
# count[ord(a[i][d])] += 1
#
# for i in range(len(a)):
# a[i] = aux[i]
#
# class MSD(object):
# R = 256
#
# @staticmethod
# def sort(a):
# MSD._sort(a, 0, len(a) - 1, 0)
#
# @staticmethod
# def _sort(a, lo, hi, d):
# if hi - lo <= 0:
# return
#
# count = [0] * (MSD.R + 2)
# aux = [None] * (hi - lo + 1)
#
# for i in range(lo, hi + 1):
# count[MSD.char_at(a[i], d) + 2] += 1
#
# for r in range(0, MSD.R):
# count[r + 1] += count[r]
#
# for i in range(lo, hi + 1):
# aux[count[MSD.char_at(a[i], d) + 1]] = a[i]
# count[MSD.char_at(a[i], d) + 1] += 1
#
# for i in range(lo, hi + 1):
# a[i] = aux[i - lo]
#
# for r in range(MSD.R):
# MSD._sort(a, lo + count[r], lo + count[r + 1] - 1, d + 1)
#
# @staticmethod
# def char_at(text, d):
# if len(text) <= d + 1:
# return -1
# return ord(text[d])
#
# class String3WayQuickSort(object):
# @staticmethod
# def sort(a):
# String3WayQuickSort._sort(a, 0, len(a) - 1, 0)
#
# @staticmethod
# def _sort(a, lo, hi, d):
# if lo >= hi:
# return
#
# lt = lo
# i = lo
# gt = hi
#
# c = String3WayQuickSort.char_at(a[lo], d)
#
# while i < gt:
# cmp = c - String3WayQuickSort.char_at(a[i], d)
# if cmp > 0:
# util.exchange(a, i, lt)
# i += 1
# lt += 1
# elif cmp < 0:
# util.exchange(a, i, gt)
# gt -= 1
# else:
# i += 1
#
# String3WayQuickSort._sort(a, lo, lt-1, d)
# if c >= 0:
# String3WayQuickSort._sort(a, lt, gt, d+1)
# String3WayQuickSort._sort(a, gt+1, hi, d)
#
# @staticmethod
# def char_at(text, d):
# if len(text) <= d + 1:
# return -1
# return ord(text[d])
#
# Path: tests/algorithms/strings/util.py
# def words3():
# words = some_text().split(' ')
# return words
, which may contain function names, class names, or code. Output only the next line. | MSD.sort(words) |
Next line prediction: <|code_start|>
class LSDUnitTest(unittest.TestCase):
def test_lsd(self):
words = words3()
print(words)
LSD.sort(words)
print(words)
class MSDUnitTest(unittest.TestCase):
def test_msd(self):
words = 'more details are provided in the docs for implementation, complexities and further info'.split(' ')
print(words)
MSD.sort(words)
print(words)
class String3WayQuickSortUnitTest(unittest.TestCase):
def test_msd(self):
words = 'more details are provided in the docs for implementation, complexities and further info'.split(' ')
print(words)
<|code_end|>
. Use current file imports:
(import unittest
from pyalgs.algorithms.strings.sorting import LSD, MSD, String3WayQuickSort
from tests.algorithms.strings.util import words3)
and context including class names, function names, or small code snippets from other files:
# Path: pyalgs/algorithms/strings/sorting.py
# class LSD(object):
# R = 256
#
# @staticmethod
# def sort(a):
# W = len(a[0])
# aux = [None] * len(a)
#
# for d in range(W - 1, -1, -1):
# count = [0] * (LSD.R + 1)
#
# for i in range(len(a)):
# count[ord(a[i][d]) + 1] += 1
#
# for r in range(0, LSD.R):
# count[r + 1] += count[r]
#
# for i in range(len(a)):
# aux[count[ord(a[i][d])]] = a[i]
# count[ord(a[i][d])] += 1
#
# for i in range(len(a)):
# a[i] = aux[i]
#
# class MSD(object):
# R = 256
#
# @staticmethod
# def sort(a):
# MSD._sort(a, 0, len(a) - 1, 0)
#
# @staticmethod
# def _sort(a, lo, hi, d):
# if hi - lo <= 0:
# return
#
# count = [0] * (MSD.R + 2)
# aux = [None] * (hi - lo + 1)
#
# for i in range(lo, hi + 1):
# count[MSD.char_at(a[i], d) + 2] += 1
#
# for r in range(0, MSD.R):
# count[r + 1] += count[r]
#
# for i in range(lo, hi + 1):
# aux[count[MSD.char_at(a[i], d) + 1]] = a[i]
# count[MSD.char_at(a[i], d) + 1] += 1
#
# for i in range(lo, hi + 1):
# a[i] = aux[i - lo]
#
# for r in range(MSD.R):
# MSD._sort(a, lo + count[r], lo + count[r + 1] - 1, d + 1)
#
# @staticmethod
# def char_at(text, d):
# if len(text) <= d + 1:
# return -1
# return ord(text[d])
#
# class String3WayQuickSort(object):
# @staticmethod
# def sort(a):
# String3WayQuickSort._sort(a, 0, len(a) - 1, 0)
#
# @staticmethod
# def _sort(a, lo, hi, d):
# if lo >= hi:
# return
#
# lt = lo
# i = lo
# gt = hi
#
# c = String3WayQuickSort.char_at(a[lo], d)
#
# while i < gt:
# cmp = c - String3WayQuickSort.char_at(a[i], d)
# if cmp > 0:
# util.exchange(a, i, lt)
# i += 1
# lt += 1
# elif cmp < 0:
# util.exchange(a, i, gt)
# gt -= 1
# else:
# i += 1
#
# String3WayQuickSort._sort(a, lo, lt-1, d)
# if c >= 0:
# String3WayQuickSort._sort(a, lt, gt, d+1)
# String3WayQuickSort._sort(a, gt+1, hi, d)
#
# @staticmethod
# def char_at(text, d):
# if len(text) <= d + 1:
# return -1
# return ord(text[d])
#
# Path: tests/algorithms/strings/util.py
# def words3():
# words = some_text().split(' ')
# return words
. Output only the next line. | String3WayQuickSort.sort(words) |
Given snippet: <|code_start|>
class KruskalMSTUnitTest(unittest.TestCase):
def test_mst(self):
g = create_edge_weighted_graph()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
from pyalgs.algorithms.graphs.minimum_spanning_trees import KruskalMST, LazyPrimMST, EagerPrimMST
from tests.algorithms.graphs.util import create_edge_weighted_graph
and context:
# Path: pyalgs/algorithms/graphs/minimum_spanning_trees.py
# class KruskalMST(MST):
# tree = None
#
# def __init__(self, G):
# if not isinstance(G, EdgeWeightedGraph):
# raise ValueError('Graph must be edge weighted and undirected to run MST')
# minpq = MinPQ.create()
# self.tree = Bag()
# for e in G.edges():
# minpq.enqueue(e)
#
# uf = UnionFind.create(G.vertex_count())
#
# while not minpq.is_empty() and self.tree.size() < G.vertex_count() - 1:
# e = minpq.del_min()
# v = e.either()
# w = e.other(v)
# if not uf.connected(v, w):
# uf.union(v, w)
# self.tree.add(e)
#
# def spanning_tree(self):
# return self.tree.iterate()
#
# class LazyPrimMST(MST):
# tree = None
# marked = None
# minpq = None
#
# def __init__(self, G):
# if not isinstance(G, EdgeWeightedGraph):
# raise ValueError('Graph must be edge weighted and undirected to run MST')
# self.minpq = MinPQ.create()
# self.tree = Bag()
# vertex_count = G.vertex_count()
# self.marked = [False] * vertex_count
# self.visit(G, 0)
#
# while not self.minpq.is_empty() and self.tree.size() < vertex_count - 1:
# edge = self.minpq.del_min()
# v = edge.either()
# w = edge.other(v)
# if self.marked[v] and self.marked[w]:
# continue
# self.tree.add(edge)
# if not self.marked[v]:
# self.visit(G, v)
# if not self.marked[w]:
# self.visit(G, w)
#
# def visit(self, G, v):
# self.marked[v] = True
# for e in G.adj(v):
# w = e.other(v)
# if not self.marked[w]:
# self.minpq.enqueue(e)
#
# def spanning_tree(self):
# return self.tree.iterate()
#
# class EagerPrimMST(MST):
# path = None
# pq = None
# marked = None
#
# def __init__(self, G):
# if not isinstance(G, EdgeWeightedGraph):
# raise ValueError('Graph must be edge weighted and undirected to run MST')
# vertex_count = G.vertex_count()
# self.pq = IndexMinPQ(vertex_count)
# self.path = Bag()
# self.marked = [False] * vertex_count
#
# self.visit(G, 0)
#
# while not self.pq.is_empty() and self.path.size() < vertex_count - 1:
# e = self.pq.min_key()
# w = self.pq.del_min()
# self.path.add(e)
# if not self.marked[w]:
# self.visit(G, w)
#
# def visit(self, G, v):
# self.marked[v] = True
# for e in G.adj(v):
# w = e.other(v)
# if not self.marked[w]:
# if self.pq.contains_index(w):
# old_e = self.pq.get(w)
# if less(e, old_e):
# self.pq.decrease_key(w, e)
# else:
# self.pq.insert(w, e)
#
# def spanning_tree(self):
# return self.path.iterate()
#
# Path: tests/algorithms/graphs/util.py
# def create_edge_weighted_graph():
# g = EdgeWeightedGraph(8)
# g.add_edge(Edge(0, 7, 0.16))
# g.add_edge(Edge(2, 3, 0.17))
# g.add_edge(Edge(1, 7, 0.19))
# g.add_edge(Edge(0, 2, 0.26))
# g.add_edge(Edge(5, 7, 0.28))
# g.add_edge(Edge(1, 3, 0.29))
# g.add_edge(Edge(1, 5, 0.32))
# g.add_edge(Edge(2, 7, 0.34))
# g.add_edge(Edge(4, 5, 0.35))
# g.add_edge(Edge(1, 2, 0.36))
# g.add_edge(Edge(4, 7, 0.37))
# g.add_edge(Edge(0, 4, 0.38))
# g.add_edge(Edge(6, 2, 0.4))
# g.add_edge(Edge(3, 6, 0.52))
# g.add_edge(Edge(6, 0, 0.58))
# g.add_edge(Edge(6, 4, 0.93))
#
# return g
which might include code, classes, or functions. Output only the next line. | mst = KruskalMST(g) |
Given the following code snippet before the placeholder: <|code_start|>
class KruskalMSTUnitTest(unittest.TestCase):
def test_mst(self):
g = create_edge_weighted_graph()
mst = KruskalMST(g)
tree = mst.spanning_tree()
for e in tree:
print(e)
class LazyPrimMSTUnitTest(unittest.TestCase):
def test_mst(self):
g = create_edge_weighted_graph()
<|code_end|>
, predict the next line using imports from the current file:
import unittest
from pyalgs.algorithms.graphs.minimum_spanning_trees import KruskalMST, LazyPrimMST, EagerPrimMST
from tests.algorithms.graphs.util import create_edge_weighted_graph
and context including class names, function names, and sometimes code from other files:
# Path: pyalgs/algorithms/graphs/minimum_spanning_trees.py
# class KruskalMST(MST):
# tree = None
#
# def __init__(self, G):
# if not isinstance(G, EdgeWeightedGraph):
# raise ValueError('Graph must be edge weighted and undirected to run MST')
# minpq = MinPQ.create()
# self.tree = Bag()
# for e in G.edges():
# minpq.enqueue(e)
#
# uf = UnionFind.create(G.vertex_count())
#
# while not minpq.is_empty() and self.tree.size() < G.vertex_count() - 1:
# e = minpq.del_min()
# v = e.either()
# w = e.other(v)
# if not uf.connected(v, w):
# uf.union(v, w)
# self.tree.add(e)
#
# def spanning_tree(self):
# return self.tree.iterate()
#
# class LazyPrimMST(MST):
# tree = None
# marked = None
# minpq = None
#
# def __init__(self, G):
# if not isinstance(G, EdgeWeightedGraph):
# raise ValueError('Graph must be edge weighted and undirected to run MST')
# self.minpq = MinPQ.create()
# self.tree = Bag()
# vertex_count = G.vertex_count()
# self.marked = [False] * vertex_count
# self.visit(G, 0)
#
# while not self.minpq.is_empty() and self.tree.size() < vertex_count - 1:
# edge = self.minpq.del_min()
# v = edge.either()
# w = edge.other(v)
# if self.marked[v] and self.marked[w]:
# continue
# self.tree.add(edge)
# if not self.marked[v]:
# self.visit(G, v)
# if not self.marked[w]:
# self.visit(G, w)
#
# def visit(self, G, v):
# self.marked[v] = True
# for e in G.adj(v):
# w = e.other(v)
# if not self.marked[w]:
# self.minpq.enqueue(e)
#
# def spanning_tree(self):
# return self.tree.iterate()
#
# class EagerPrimMST(MST):
# path = None
# pq = None
# marked = None
#
# def __init__(self, G):
# if not isinstance(G, EdgeWeightedGraph):
# raise ValueError('Graph must be edge weighted and undirected to run MST')
# vertex_count = G.vertex_count()
# self.pq = IndexMinPQ(vertex_count)
# self.path = Bag()
# self.marked = [False] * vertex_count
#
# self.visit(G, 0)
#
# while not self.pq.is_empty() and self.path.size() < vertex_count - 1:
# e = self.pq.min_key()
# w = self.pq.del_min()
# self.path.add(e)
# if not self.marked[w]:
# self.visit(G, w)
#
# def visit(self, G, v):
# self.marked[v] = True
# for e in G.adj(v):
# w = e.other(v)
# if not self.marked[w]:
# if self.pq.contains_index(w):
# old_e = self.pq.get(w)
# if less(e, old_e):
# self.pq.decrease_key(w, e)
# else:
# self.pq.insert(w, e)
#
# def spanning_tree(self):
# return self.path.iterate()
#
# Path: tests/algorithms/graphs/util.py
# def create_edge_weighted_graph():
# g = EdgeWeightedGraph(8)
# g.add_edge(Edge(0, 7, 0.16))
# g.add_edge(Edge(2, 3, 0.17))
# g.add_edge(Edge(1, 7, 0.19))
# g.add_edge(Edge(0, 2, 0.26))
# g.add_edge(Edge(5, 7, 0.28))
# g.add_edge(Edge(1, 3, 0.29))
# g.add_edge(Edge(1, 5, 0.32))
# g.add_edge(Edge(2, 7, 0.34))
# g.add_edge(Edge(4, 5, 0.35))
# g.add_edge(Edge(1, 2, 0.36))
# g.add_edge(Edge(4, 7, 0.37))
# g.add_edge(Edge(0, 4, 0.38))
# g.add_edge(Edge(6, 2, 0.4))
# g.add_edge(Edge(3, 6, 0.52))
# g.add_edge(Edge(6, 0, 0.58))
# g.add_edge(Edge(6, 4, 0.93))
#
# return g
. Output only the next line. | mst = LazyPrimMST(g) |
Using the snippet: <|code_start|>
class KruskalMSTUnitTest(unittest.TestCase):
def test_mst(self):
g = create_edge_weighted_graph()
mst = KruskalMST(g)
tree = mst.spanning_tree()
for e in tree:
print(e)
class LazyPrimMSTUnitTest(unittest.TestCase):
def test_mst(self):
g = create_edge_weighted_graph()
mst = LazyPrimMST(g)
tree = mst.spanning_tree()
for e in tree:
print(e)
class EagerPrimMSTUnitTest(unittest.TestCase):
def test_mst(self):
g = create_edge_weighted_graph()
<|code_end|>
, determine the next line of code. You have imports:
import unittest
from pyalgs.algorithms.graphs.minimum_spanning_trees import KruskalMST, LazyPrimMST, EagerPrimMST
from tests.algorithms.graphs.util import create_edge_weighted_graph
and context (class names, function names, or code) available:
# Path: pyalgs/algorithms/graphs/minimum_spanning_trees.py
# class KruskalMST(MST):
# tree = None
#
# def __init__(self, G):
# if not isinstance(G, EdgeWeightedGraph):
# raise ValueError('Graph must be edge weighted and undirected to run MST')
# minpq = MinPQ.create()
# self.tree = Bag()
# for e in G.edges():
# minpq.enqueue(e)
#
# uf = UnionFind.create(G.vertex_count())
#
# while not minpq.is_empty() and self.tree.size() < G.vertex_count() - 1:
# e = minpq.del_min()
# v = e.either()
# w = e.other(v)
# if not uf.connected(v, w):
# uf.union(v, w)
# self.tree.add(e)
#
# def spanning_tree(self):
# return self.tree.iterate()
#
# class LazyPrimMST(MST):
# tree = None
# marked = None
# minpq = None
#
# def __init__(self, G):
# if not isinstance(G, EdgeWeightedGraph):
# raise ValueError('Graph must be edge weighted and undirected to run MST')
# self.minpq = MinPQ.create()
# self.tree = Bag()
# vertex_count = G.vertex_count()
# self.marked = [False] * vertex_count
# self.visit(G, 0)
#
# while not self.minpq.is_empty() and self.tree.size() < vertex_count - 1:
# edge = self.minpq.del_min()
# v = edge.either()
# w = edge.other(v)
# if self.marked[v] and self.marked[w]:
# continue
# self.tree.add(edge)
# if not self.marked[v]:
# self.visit(G, v)
# if not self.marked[w]:
# self.visit(G, w)
#
# def visit(self, G, v):
# self.marked[v] = True
# for e in G.adj(v):
# w = e.other(v)
# if not self.marked[w]:
# self.minpq.enqueue(e)
#
# def spanning_tree(self):
# return self.tree.iterate()
#
# class EagerPrimMST(MST):
# path = None
# pq = None
# marked = None
#
# def __init__(self, G):
# if not isinstance(G, EdgeWeightedGraph):
# raise ValueError('Graph must be edge weighted and undirected to run MST')
# vertex_count = G.vertex_count()
# self.pq = IndexMinPQ(vertex_count)
# self.path = Bag()
# self.marked = [False] * vertex_count
#
# self.visit(G, 0)
#
# while not self.pq.is_empty() and self.path.size() < vertex_count - 1:
# e = self.pq.min_key()
# w = self.pq.del_min()
# self.path.add(e)
# if not self.marked[w]:
# self.visit(G, w)
#
# def visit(self, G, v):
# self.marked[v] = True
# for e in G.adj(v):
# w = e.other(v)
# if not self.marked[w]:
# if self.pq.contains_index(w):
# old_e = self.pq.get(w)
# if less(e, old_e):
# self.pq.decrease_key(w, e)
# else:
# self.pq.insert(w, e)
#
# def spanning_tree(self):
# return self.path.iterate()
#
# Path: tests/algorithms/graphs/util.py
# def create_edge_weighted_graph():
# g = EdgeWeightedGraph(8)
# g.add_edge(Edge(0, 7, 0.16))
# g.add_edge(Edge(2, 3, 0.17))
# g.add_edge(Edge(1, 7, 0.19))
# g.add_edge(Edge(0, 2, 0.26))
# g.add_edge(Edge(5, 7, 0.28))
# g.add_edge(Edge(1, 3, 0.29))
# g.add_edge(Edge(1, 5, 0.32))
# g.add_edge(Edge(2, 7, 0.34))
# g.add_edge(Edge(4, 5, 0.35))
# g.add_edge(Edge(1, 2, 0.36))
# g.add_edge(Edge(4, 7, 0.37))
# g.add_edge(Edge(0, 4, 0.38))
# g.add_edge(Edge(6, 2, 0.4))
# g.add_edge(Edge(3, 6, 0.52))
# g.add_edge(Edge(6, 0, 0.58))
# g.add_edge(Edge(6, 4, 0.93))
#
# return g
. Output only the next line. | mst = EagerPrimMST(g) |
Here is a snippet: <|code_start|> return x is not None and x.value is not None
def size(self):
return self.N
def keys(self):
queue = Queue.create()
self.collect(self.root, '', queue)
return queue.iterate()
def collect(self, x, prefix, queue):
if x is None:
return
if x.value is not None:
queue.enqueue(prefix)
c = chr(x.key)
self.collect(x.left, prefix, queue)
self.collect(x.mid, prefix + str(c), queue)
self.collect(x.right, prefix, queue)
def get(self, key):
x = self._get(self.root, key, 0)
if x is None:
return None
return x.value
def _get(self, x, key, d):
if x is None:
return None
c = char_at(key, d)
<|code_end|>
. Write the next line using the current file imports:
from abc import ABCMeta, abstractmethod
from pyalgs.algorithms.commons import util
from pyalgs.data_structures.commons.queue import Queue
and context from other files:
# Path: pyalgs/algorithms/commons/util.py
# def less(a, b):
# def greater(a, b):
# def cmp(a, b):
# def exchange(a, i, j):
# def is_sorted(a):
#
# Path: pyalgs/data_structures/commons/queue.py
# class Queue(object):
# """ Queue interface
#
# """
#
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def enqueue(self, item):
# pass
#
# @abstractmethod
# def dequeue(self):
# pass
#
# @abstractmethod
# def is_empty(self):
# pass
#
# @abstractmethod
# def size(self):
# pass
#
# @staticmethod
# def create():
# return LinkedListQueue()
#
# @abstractmethod
# def iterate(self):
# pass
, which may include functions, classes, or code. Output only the next line. | compared = util.cmp(c, x.key) |
Predict the next line after this snippet: <|code_start|>
def char_at(key, d):
return ord(key[d])
class RwayNode(object):
nodes = None
value = None
R = 256
def __init__(self):
self.nodes = [None] * RwayNode.R
class RWaySearchTries(SearchTries):
root = None
N = 0
def contains_key(self, key):
x = self._get(self.root, key, 0)
if x is None:
return None
return x.value
def keys_with_prefix(self, prefix):
x = self._get(self.root, prefix, 0)
if x is None:
return None
<|code_end|>
using the current file's imports:
from abc import ABCMeta, abstractmethod
from pyalgs.algorithms.commons import util
from pyalgs.data_structures.commons.queue import Queue
and any relevant context from other files:
# Path: pyalgs/algorithms/commons/util.py
# def less(a, b):
# def greater(a, b):
# def cmp(a, b):
# def exchange(a, i, j):
# def is_sorted(a):
#
# Path: pyalgs/data_structures/commons/queue.py
# class Queue(object):
# """ Queue interface
#
# """
#
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def enqueue(self, item):
# pass
#
# @abstractmethod
# def dequeue(self):
# pass
#
# @abstractmethod
# def is_empty(self):
# pass
#
# @abstractmethod
# def size(self):
# pass
#
# @staticmethod
# def create():
# return LinkedListQueue()
#
# @abstractmethod
# def iterate(self):
# pass
. Output only the next line. | queue = Queue.create() |
Given snippet: <|code_start|>
class KnuthShuffle(object):
@staticmethod
def shuffle(a):
for i in range(1, len(a)):
r = randint(0, i)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from random import randint
from pyalgs.algorithms.commons.util import exchange
and context:
# Path: pyalgs/algorithms/commons/util.py
# def exchange(a, i, j):
# tmp = a[j]
# a[j] = a[i]
# a[i] = tmp
which might include code, classes, or functions. Output only the next line. | exchange(a, r, i) |
Here is a snippet: <|code_start|>
class StackTest(unittest.TestCase):
def test_push(self):
stack = Stack.create()
stack.push(10)
stack.push(1)
print([i for i in stack.iterate()])
self.assertFalse(stack.is_empty())
self.assertEqual(2, stack.size())
self.assertEqual(1, stack.pop())
self.assertFalse(stack.is_empty())
self.assertEqual(1, stack.size())
self.assertEqual(10, stack.pop())
self.assertTrue(stack.is_empty())
for i in range(100):
stack.push(i)
class LinkedListStackTest(unittest.TestCase):
def test_push(self):
<|code_end|>
. Write the next line using the current file imports:
import unittest
from pyalgs.data_structures.commons.stack import LinkedListStack
from pyalgs.data_structures.commons.stack import ArrayStack
from pyalgs.data_structures.commons.stack import Stack
and context from other files:
# Path: pyalgs/data_structures/commons/stack.py
# class LinkedListStack(Stack):
# """ Linked list implementation of stack
# """
# first = None
# N = 0
#
# def push(self, item):
# node = StackNode(item)
# old_first = self.first
# node.nextNode = old_first
# self.first = node
# self.N += 1
#
# def pop(self):
# if self.is_empty():
# return None
# old_first = self.first
# if old_first.nextNode is None:
# self.first = None
# self.first = old_first.nextNode
# self.N -= 1
# return old_first.item
#
# def is_empty(self):
# return self.N == 0
#
# def size(self):
# return self.N
#
# def iterate(self):
# x = self.first
# while x is not None:
# value = x.item
# x = x.nextNode
# yield value
#
# Path: pyalgs/data_structures/commons/stack.py
# class ArrayStack(Stack):
# """ Array implementation of stack
# """
#
# def __init__(self, capacity=None):
# if capacity is None:
# capacity = 10
# self.s = [0] * capacity
# self.N = 0
#
# def push(self, item):
# self.s[self.N] = item
# self.N += 1
# if self.N == len(self.s):
# self.resize(len(self.s) * 2)
#
# def resize(self, new_size):
# tmp = [0] * new_size
# for i in range(min(new_size, len(self.s))):
# tmp[i] = self.s[i]
# self.s = tmp
#
# def pop(self):
# value = self.s[self.N-1]
# self.N -= 1
# if self.N == len(self.s) // 4:
# self.resize(len(self.s) // 2)
# return value
#
# def is_empty(self):
# return self.N == 0
#
# def size(self):
# return self.N
#
# def iterate(self):
# if self.is_empty():
# return
# for i in reversed(range(self.N)):
# yield self.s[i]
#
# Path: pyalgs/data_structures/commons/stack.py
# class Stack(object):
# """ Stack interface which provides the API for stack data structure
# """
#
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def push(self, item):
# pass
#
# @abstractmethod
# def pop(self):
# pass
#
# @abstractmethod
# def is_empty(self):
# pass
#
# @abstractmethod
# def size(self):
# pass
#
# @abstractmethod
# def iterate(self):
# pass
#
# @staticmethod
# def create():
# return LinkedListStack()
, which may include functions, classes, or code. Output only the next line. | stack = LinkedListStack() |
Given the code snippet: <|code_start|> self.assertEqual(1, stack.size())
self.assertEqual(10, stack.pop())
self.assertTrue(stack.is_empty())
for i in range(100):
stack.push(i)
class LinkedListStackTest(unittest.TestCase):
def test_push(self):
stack = LinkedListStack()
stack.push(10)
stack.push(1)
print([i for i in stack.iterate()])
self.assertFalse(stack.is_empty())
self.assertEqual(2, stack.size())
self.assertEqual(1, stack.pop())
self.assertFalse(stack.is_empty())
self.assertEqual(1, stack.size())
self.assertEqual(10, stack.pop())
self.assertTrue(stack.is_empty())
for i in range(100):
stack.push(i)
class ArrayStackTest(unittest.TestCase):
def test_push(self):
<|code_end|>
, generate the next line using the imports in this file:
import unittest
from pyalgs.data_structures.commons.stack import LinkedListStack
from pyalgs.data_structures.commons.stack import ArrayStack
from pyalgs.data_structures.commons.stack import Stack
and context (functions, classes, or occasionally code) from other files:
# Path: pyalgs/data_structures/commons/stack.py
# class LinkedListStack(Stack):
# """ Linked list implementation of stack
# """
# first = None
# N = 0
#
# def push(self, item):
# node = StackNode(item)
# old_first = self.first
# node.nextNode = old_first
# self.first = node
# self.N += 1
#
# def pop(self):
# if self.is_empty():
# return None
# old_first = self.first
# if old_first.nextNode is None:
# self.first = None
# self.first = old_first.nextNode
# self.N -= 1
# return old_first.item
#
# def is_empty(self):
# return self.N == 0
#
# def size(self):
# return self.N
#
# def iterate(self):
# x = self.first
# while x is not None:
# value = x.item
# x = x.nextNode
# yield value
#
# Path: pyalgs/data_structures/commons/stack.py
# class ArrayStack(Stack):
# """ Array implementation of stack
# """
#
# def __init__(self, capacity=None):
# if capacity is None:
# capacity = 10
# self.s = [0] * capacity
# self.N = 0
#
# def push(self, item):
# self.s[self.N] = item
# self.N += 1
# if self.N == len(self.s):
# self.resize(len(self.s) * 2)
#
# def resize(self, new_size):
# tmp = [0] * new_size
# for i in range(min(new_size, len(self.s))):
# tmp[i] = self.s[i]
# self.s = tmp
#
# def pop(self):
# value = self.s[self.N-1]
# self.N -= 1
# if self.N == len(self.s) // 4:
# self.resize(len(self.s) // 2)
# return value
#
# def is_empty(self):
# return self.N == 0
#
# def size(self):
# return self.N
#
# def iterate(self):
# if self.is_empty():
# return
# for i in reversed(range(self.N)):
# yield self.s[i]
#
# Path: pyalgs/data_structures/commons/stack.py
# class Stack(object):
# """ Stack interface which provides the API for stack data structure
# """
#
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def push(self, item):
# pass
#
# @abstractmethod
# def pop(self):
# pass
#
# @abstractmethod
# def is_empty(self):
# pass
#
# @abstractmethod
# def size(self):
# pass
#
# @abstractmethod
# def iterate(self):
# pass
#
# @staticmethod
# def create():
# return LinkedListStack()
. Output only the next line. | stack = ArrayStack() |
Continue the code snippet: <|code_start|>
class BinarySelectionUnitTest(unittest.TestCase):
def test_select(self):
a = [1, 2, 13, 22, 123]
assert is_sorted(a)
<|code_end|>
. Use current file imports:
import unittest
from pyalgs.algorithms.commons.selecting import BinarySelection
from pyalgs.algorithms.commons.util import is_sorted
and context (classes, functions, or code) from other files:
# Path: pyalgs/algorithms/commons/selecting.py
# class BinarySelection(object):
# @staticmethod
# def index_of(a, x, lo=None, hi=None):
# if not is_sorted(a):
# raise ValueError('array must be sorted before running selection')
#
# if lo is None:
# lo = 0
# if hi is None:
# hi = len(a) - 1
#
# while lo <= hi:
# mid = lo + (hi - lo) // 2
# if less(x, a[mid]):
# hi = mid - 1
# elif less(a[mid], x):
# lo = mid + 1
# else:
# return mid
#
# return -1
#
# Path: pyalgs/algorithms/commons/util.py
# def is_sorted(a):
# if len(a) <= 1:
# return True
# for i in range(1, len(a)):
# if less(a[i], a[i - 1]):
# return False
# return True
. Output only the next line. | print(BinarySelection.index_of(a, 13)) |
Based on the snippet: <|code_start|>
class BinarySelectionUnitTest(unittest.TestCase):
def test_select(self):
a = [1, 2, 13, 22, 123]
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
from pyalgs.algorithms.commons.selecting import BinarySelection
from pyalgs.algorithms.commons.util import is_sorted
and context (classes, functions, sometimes code) from other files:
# Path: pyalgs/algorithms/commons/selecting.py
# class BinarySelection(object):
# @staticmethod
# def index_of(a, x, lo=None, hi=None):
# if not is_sorted(a):
# raise ValueError('array must be sorted before running selection')
#
# if lo is None:
# lo = 0
# if hi is None:
# hi = len(a) - 1
#
# while lo <= hi:
# mid = lo + (hi - lo) // 2
# if less(x, a[mid]):
# hi = mid - 1
# elif less(a[mid], x):
# lo = mid + 1
# else:
# return mid
#
# return -1
#
# Path: pyalgs/algorithms/commons/util.py
# def is_sorted(a):
# if len(a) <= 1:
# return True
# for i in range(1, len(a)):
# if less(a[i], a[i - 1]):
# return False
# return True
. Output only the next line. | assert is_sorted(a) |
Predict the next line for this snippet: <|code_start|>
class GraphUnitTest(unittest.TestCase):
def test_graph(self):
G = Graph(100)
G.add_edge(1, 2)
G.add_edge(1, 3)
print([i for i in G.adj(1)])
self.assertEqual(100, G.vertex_count())
class DigraphUnitTest(unittest.TestCase):
def test_digraph(self):
<|code_end|>
with the help of current file imports:
import unittest
from pyalgs.data_structures.graphs.graph import Graph, Digraph
and context from other files:
# Path: pyalgs/data_structures/graphs/graph.py
# class Graph(object):
# V = 0
# adjList = None
#
# def __init__(self, V):
# self.V = V
# self.adjList = [None] * V
# for v in range(V):
# self.adjList[v] = Bag()
#
# def vertex_count(self):
# return self.V
#
# def adj(self, v):
# return self.adjList[v].iterate()
#
# def add_edge(self, v, w):
# self.adjList[v].add(w)
# self.adjList[w].add(v)
#
# class Digraph(object):
# V = 0
# adjList = None
#
# def __init__(self, V):
# self.V = V
# self.adjList = [None] * V
# for v in range(V):
# self.adjList[v] = Bag()
#
# def vertex_count(self):
# return self.V
#
# def adj(self, v):
# return self.adjList[v].iterate()
#
# def add_edge(self, v, w):
# self.adjList[v].add(w)
#
# def reverse(self):
# g = Digraph(self.V)
# for v in range(self.V):
# for w in self.adjList[v].iterate():
# g.add_edge(w, v)
#
# return g
, which may contain function names, class names, or code. Output only the next line. | G = Digraph(100) |
Given snippet: <|code_start|>
class BinarySelection(object):
@staticmethod
def index_of(a, x, lo=None, hi=None):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pyalgs.algorithms.commons.util import is_sorted, less
and context:
# Path: pyalgs/algorithms/commons/util.py
# def is_sorted(a):
# if len(a) <= 1:
# return True
# for i in range(1, len(a)):
# if less(a[i], a[i - 1]):
# return False
# return True
#
# def less(a, b):
# return cmp(a, b) < 0
which might include code, classes, or functions. Output only the next line. | if not is_sorted(a): |
Continue the code snippet: <|code_start|>
class BinarySelection(object):
@staticmethod
def index_of(a, x, lo=None, hi=None):
if not is_sorted(a):
raise ValueError('array must be sorted before running selection')
if lo is None:
lo = 0
if hi is None:
hi = len(a) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
<|code_end|>
. Use current file imports:
from pyalgs.algorithms.commons.util import is_sorted, less
and context (classes, functions, or code) from other files:
# Path: pyalgs/algorithms/commons/util.py
# def is_sorted(a):
# if len(a) <= 1:
# return True
# for i in range(1, len(a)):
# if less(a[i], a[i - 1]):
# return False
# return True
#
# def less(a, b):
# return cmp(a, b) < 0
. Output only the next line. | if less(x, a[mid]): |
Continue the code snippet: <|code_start|>
def __init__(self, key, value, red=None):
self.key = key
self.value = value
self.count = 1
if red is not None:
self.red = red
else:
self.red = 0
def _count(x):
if x is None:
return 0
return x.count
class BinarySearchTree(object):
__metaclass__ = ABCMeta
root = None
def put(self, key, value):
self.root = self._put(self.root, key, value)
def _put(self, x, key, value):
if x is None:
return Node(key, value)
<|code_end|>
. Use current file imports:
from abc import ABCMeta
from pyalgs.algorithms.commons.util import cmp
from pyalgs.data_structures.commons.queue import Queue
and context (classes, functions, or code) from other files:
# Path: pyalgs/algorithms/commons/util.py
# def cmp(a, b):
# if a is None:
# return -1
# if b is None:
# return -1
# return (a > b) - (a < b)
#
# Path: pyalgs/data_structures/commons/queue.py
# class Queue(object):
# """ Queue interface
#
# """
#
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def enqueue(self, item):
# pass
#
# @abstractmethod
# def dequeue(self):
# pass
#
# @abstractmethod
# def is_empty(self):
# pass
#
# @abstractmethod
# def size(self):
# pass
#
# @staticmethod
# def create():
# return LinkedListQueue()
#
# @abstractmethod
# def iterate(self):
# pass
. Output only the next line. | compared = cmp(key, x.key) |
Continue the code snippet: <|code_start|> else:
if x.left is None:
return x.right
elif x.right is None:
return x.left
else:
m = self.min(x.right)
m.right = self.del_min(x.right)
m.left = x.left
x = m
x.count = 1 + _count(x.left) + _count(x.right)
return x
def min(self, x):
if x.left is None:
return x
return self.min(x.left)
def del_min(self, x):
if x.left is None:
return x.right
x.left = self.del_min(x.left)
return x
def contains_key(self, x):
return self.get(x) is not None
def keys(self):
<|code_end|>
. Use current file imports:
from abc import ABCMeta
from pyalgs.algorithms.commons.util import cmp
from pyalgs.data_structures.commons.queue import Queue
and context (classes, functions, or code) from other files:
# Path: pyalgs/algorithms/commons/util.py
# def cmp(a, b):
# if a is None:
# return -1
# if b is None:
# return -1
# return (a > b) - (a < b)
#
# Path: pyalgs/data_structures/commons/queue.py
# class Queue(object):
# """ Queue interface
#
# """
#
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def enqueue(self, item):
# pass
#
# @abstractmethod
# def dequeue(self):
# pass
#
# @abstractmethod
# def is_empty(self):
# pass
#
# @abstractmethod
# def size(self):
# pass
#
# @staticmethod
# def create():
# return LinkedListQueue()
#
# @abstractmethod
# def iterate(self):
# pass
. Output only the next line. | queue = Queue.create() |
Predict the next line after this snippet: <|code_start|> cycle = None
edgeTo = None
def __init__(self, G):
if isinstance(G, DirectedEdgeWeightedGraph):
G = G.to_digraph()
if not isinstance(G, Digraph):
raise ValueError('Graph must be unweighted digraph')
vertex_count = G.vertex_count()
self.marked = [False] * vertex_count
self.onStack = [False] * vertex_count
self.edgeTo = [-1] * vertex_count
for v in range(vertex_count):
if not self.marked[v]:
self.dfs(G, v)
def dfs(self, G, v):
self.marked[v] = True
self.onStack[v] = True
for w in G.adj(v):
if not self.marked[w]:
self.edgeTo[w] = v
self.dfs(G, w)
elif self.cycle is not None:
break
elif self.onStack[w]:
<|code_end|>
using the current file's imports:
from pyalgs.data_structures.commons.stack import Stack
from pyalgs.data_structures.graphs.graph import DirectedEdgeWeightedGraph, Digraph
and any relevant context from other files:
# Path: pyalgs/data_structures/commons/stack.py
# class Stack(object):
# """ Stack interface which provides the API for stack data structure
# """
#
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def push(self, item):
# pass
#
# @abstractmethod
# def pop(self):
# pass
#
# @abstractmethod
# def is_empty(self):
# pass
#
# @abstractmethod
# def size(self):
# pass
#
# @abstractmethod
# def iterate(self):
# pass
#
# @staticmethod
# def create():
# return LinkedListStack()
#
# Path: pyalgs/data_structures/graphs/graph.py
# class DirectedEdgeWeightedGraph(object):
# adjList = None
# V = 0
#
# def __init__(self, vertex_count):
# self.V = vertex_count
# self.adjList = [None] * vertex_count
# for v in range(vertex_count):
# self.adjList[v] = Bag()
#
# def add_edge(self, edge):
# v = edge.start()
# self.adjList[v].add(edge)
#
# def adj(self, v):
# return self.adjList[v].iterate()
#
# def vertex_count(self):
# return self.V
#
# def edges(self):
# for v in range(self.V):
# for e in self.adj(v):
# yield e
#
# def to_graph(self):
# g = Graph()
#
# for e in self.edges():
# g.add_edge(e.start(), e.end())
# return g
#
# def to_digraph(self):
# g = Digraph(self.V)
#
# for e in self.edges():
# g.add_edge(e.start(), e.end())
#
# return g
#
# class Digraph(object):
# V = 0
# adjList = None
#
# def __init__(self, V):
# self.V = V
# self.adjList = [None] * V
# for v in range(V):
# self.adjList[v] = Bag()
#
# def vertex_count(self):
# return self.V
#
# def adj(self, v):
# return self.adjList[v].iterate()
#
# def add_edge(self, v, w):
# self.adjList[v].add(w)
#
# def reverse(self):
# g = Digraph(self.V)
# for v in range(self.V):
# for w in self.adjList[v].iterate():
# g.add_edge(w, v)
#
# return g
. Output only the next line. | self.cycle = Stack.create() |
Based on the snippet: <|code_start|>
class DirectedCycle(object):
marked = None
onStack = None
cycle = None
edgeTo = None
def __init__(self, G):
<|code_end|>
, predict the immediate next line with the help of imports:
from pyalgs.data_structures.commons.stack import Stack
from pyalgs.data_structures.graphs.graph import DirectedEdgeWeightedGraph, Digraph
and context (classes, functions, sometimes code) from other files:
# Path: pyalgs/data_structures/commons/stack.py
# class Stack(object):
# """ Stack interface which provides the API for stack data structure
# """
#
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def push(self, item):
# pass
#
# @abstractmethod
# def pop(self):
# pass
#
# @abstractmethod
# def is_empty(self):
# pass
#
# @abstractmethod
# def size(self):
# pass
#
# @abstractmethod
# def iterate(self):
# pass
#
# @staticmethod
# def create():
# return LinkedListStack()
#
# Path: pyalgs/data_structures/graphs/graph.py
# class DirectedEdgeWeightedGraph(object):
# adjList = None
# V = 0
#
# def __init__(self, vertex_count):
# self.V = vertex_count
# self.adjList = [None] * vertex_count
# for v in range(vertex_count):
# self.adjList[v] = Bag()
#
# def add_edge(self, edge):
# v = edge.start()
# self.adjList[v].add(edge)
#
# def adj(self, v):
# return self.adjList[v].iterate()
#
# def vertex_count(self):
# return self.V
#
# def edges(self):
# for v in range(self.V):
# for e in self.adj(v):
# yield e
#
# def to_graph(self):
# g = Graph()
#
# for e in self.edges():
# g.add_edge(e.start(), e.end())
# return g
#
# def to_digraph(self):
# g = Digraph(self.V)
#
# for e in self.edges():
# g.add_edge(e.start(), e.end())
#
# return g
#
# class Digraph(object):
# V = 0
# adjList = None
#
# def __init__(self, V):
# self.V = V
# self.adjList = [None] * V
# for v in range(V):
# self.adjList[v] = Bag()
#
# def vertex_count(self):
# return self.V
#
# def adj(self, v):
# return self.adjList[v].iterate()
#
# def add_edge(self, v, w):
# self.adjList[v].add(w)
#
# def reverse(self):
# g = Digraph(self.V)
# for v in range(self.V):
# for w in self.adjList[v].iterate():
# g.add_edge(w, v)
#
# return g
. Output only the next line. | if isinstance(G, DirectedEdgeWeightedGraph): |
Continue the code snippet: <|code_start|>
class DirectedCycle(object):
marked = None
onStack = None
cycle = None
edgeTo = None
def __init__(self, G):
if isinstance(G, DirectedEdgeWeightedGraph):
G = G.to_digraph()
<|code_end|>
. Use current file imports:
from pyalgs.data_structures.commons.stack import Stack
from pyalgs.data_structures.graphs.graph import DirectedEdgeWeightedGraph, Digraph
and context (classes, functions, or code) from other files:
# Path: pyalgs/data_structures/commons/stack.py
# class Stack(object):
# """ Stack interface which provides the API for stack data structure
# """
#
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def push(self, item):
# pass
#
# @abstractmethod
# def pop(self):
# pass
#
# @abstractmethod
# def is_empty(self):
# pass
#
# @abstractmethod
# def size(self):
# pass
#
# @abstractmethod
# def iterate(self):
# pass
#
# @staticmethod
# def create():
# return LinkedListStack()
#
# Path: pyalgs/data_structures/graphs/graph.py
# class DirectedEdgeWeightedGraph(object):
# adjList = None
# V = 0
#
# def __init__(self, vertex_count):
# self.V = vertex_count
# self.adjList = [None] * vertex_count
# for v in range(vertex_count):
# self.adjList[v] = Bag()
#
# def add_edge(self, edge):
# v = edge.start()
# self.adjList[v].add(edge)
#
# def adj(self, v):
# return self.adjList[v].iterate()
#
# def vertex_count(self):
# return self.V
#
# def edges(self):
# for v in range(self.V):
# for e in self.adj(v):
# yield e
#
# def to_graph(self):
# g = Graph()
#
# for e in self.edges():
# g.add_edge(e.start(), e.end())
# return g
#
# def to_digraph(self):
# g = Digraph(self.V)
#
# for e in self.edges():
# g.add_edge(e.start(), e.end())
#
# return g
#
# class Digraph(object):
# V = 0
# adjList = None
#
# def __init__(self, V):
# self.V = V
# self.adjList = [None] * V
# for v in range(V):
# self.adjList[v] = Bag()
#
# def vertex_count(self):
# return self.V
#
# def adj(self, v):
# return self.adjList[v].iterate()
#
# def add_edge(self, v, w):
# self.adjList[v].add(w)
#
# def reverse(self):
# g = Digraph(self.V)
# for v in range(self.V):
# for w in self.adjList[v].iterate():
# g.add_edge(w, v)
#
# return g
. Output only the next line. | if not isinstance(G, Digraph): |
Given snippet: <|code_start|> id = None
N = 0
def __init__(self, m=None):
if m is None:
m = 97
self.M = m
self.id = [None] * self.M
def hash(self, key):
return (hash(key) & 0x7fffffff) % self.M
def is_empty(self):
return self.N == 0
def iterate(self):
for i in range(self.M):
x = self.id[i]
while x is not None:
key = x.key
x = x.next_node
yield key
def size(self):
return self.N
def contains(self, key):
i = self.hash(key)
x = self.id[i]
while x is not None:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from abc import ABCMeta, abstractmethod
from pyalgs.algorithms.commons import util
from pyalgs.data_structures.commons.queue import Queue
and context:
# Path: pyalgs/algorithms/commons/util.py
# def less(a, b):
# def greater(a, b):
# def cmp(a, b):
# def exchange(a, i, j):
# def is_sorted(a):
#
# Path: pyalgs/data_structures/commons/queue.py
# class Queue(object):
# """ Queue interface
#
# """
#
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def enqueue(self, item):
# pass
#
# @abstractmethod
# def dequeue(self):
# pass
#
# @abstractmethod
# def is_empty(self):
# pass
#
# @abstractmethod
# def size(self):
# pass
#
# @staticmethod
# def create():
# return LinkedListQueue()
#
# @abstractmethod
# def iterate(self):
# pass
which might include code, classes, or functions. Output only the next line. | if util.cmp(x.key, key) == 0: |
Given the code snippet: <|code_start|>
for r in range(MSD.R):
MSD._sort(a, lo + count[r], lo + count[r + 1] - 1, d + 1)
@staticmethod
def char_at(text, d):
if len(text) <= d + 1:
return -1
return ord(text[d])
class String3WayQuickSort(object):
@staticmethod
def sort(a):
String3WayQuickSort._sort(a, 0, len(a) - 1, 0)
@staticmethod
def _sort(a, lo, hi, d):
if lo >= hi:
return
lt = lo
i = lo
gt = hi
c = String3WayQuickSort.char_at(a[lo], d)
while i < gt:
cmp = c - String3WayQuickSort.char_at(a[i], d)
if cmp > 0:
<|code_end|>
, generate the next line using the imports in this file:
from pyalgs.algorithms.commons import util
and context (functions, classes, or occasionally code) from other files:
# Path: pyalgs/algorithms/commons/util.py
# def less(a, b):
# def greater(a, b):
# def cmp(a, b):
# def exchange(a, i, j):
# def is_sorted(a):
. Output only the next line. | util.exchange(a, i, lt) |
Given the following code snippet before the placeholder: <|code_start|>
class UnionFindUnitTest(unittest.TestCase):
def test_find(self):
uf = UnionFind.create(10)
uf.union(1, 3)
uf.union(2, 4)
uf.union(1, 5)
self.assertTrue(uf.connected(1, 3))
self.assertTrue(uf.connected(3, 5))
self.assertFalse(uf.connected(1, 2))
self.assertFalse(uf.connected(1, 4))
class QuickFindUnitTest(unittest.TestCase):
def test_find(self):
<|code_end|>
, predict the next line using imports from the current file:
import unittest
from pyalgs.algorithms.commons.union_find import UnionFind, QuickFind, QuickUnion
and context including class names, function names, and sometimes code from other files:
# Path: pyalgs/algorithms/commons/union_find.py
# class UnionFind(object):
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def union(self, v, w):
# pass
#
# @abstractmethod
# def connected(self, v, w):
# pass
#
# @staticmethod
# def create(size):
# return QuickUnion(size)
#
# class QuickFind(UnionFind):
# id = None
#
# def __init__(self, capacity):
# self.id = [i for i in range(capacity)]
#
# def connected(self, v, w):
# return self.id[v] == self.id[w]
#
# def union(self, v, w):
# p = self.id[v]
# q = self.id[w]
#
# if p != q:
# for i in range(len(self.id)):
# if self.id[i] == p:
# self.id[i] = q
#
# class QuickUnion(UnionFind):
# id = None
# sizes = None
#
# def __init__(self, capacity):
# self.id = [i for i in range(capacity)]
# self.sizes = [1] * capacity
#
# def root(self, v):
# while v != self.id[v]:
# self.id[v] = self.id[self.id[v]] # path compression
# v = self.id[v]
# return v
#
# def connected(self, v, w):
# return self.root(v) == self.root(w)
#
# def union(self, v, w):
# vroot = self.root(v)
# wroot = self.root(w)
#
# if self.sizes[vroot] > self.sizes[wroot]:
# self.id[wroot] = vroot
# self.sizes[vroot] += self.sizes[wroot]
# else:
# self.id[vroot] = wroot
# self.sizes[wroot] += self.sizes[vroot]
. Output only the next line. | uf = QuickFind(10) |
Predict the next line for this snippet: <|code_start|>class UnionFindUnitTest(unittest.TestCase):
def test_find(self):
uf = UnionFind.create(10)
uf.union(1, 3)
uf.union(2, 4)
uf.union(1, 5)
self.assertTrue(uf.connected(1, 3))
self.assertTrue(uf.connected(3, 5))
self.assertFalse(uf.connected(1, 2))
self.assertFalse(uf.connected(1, 4))
class QuickFindUnitTest(unittest.TestCase):
def test_find(self):
uf = QuickFind(10)
uf.union(1, 3)
uf.union(2, 4)
uf.union(1, 5)
self.assertTrue(uf.connected(1, 3))
self.assertTrue(uf.connected(3, 5))
self.assertFalse(uf.connected(1, 2))
self.assertFalse(uf.connected(1, 4))
class QuickUnionUnitTest(unittest.TestCase):
def test_find(self):
<|code_end|>
with the help of current file imports:
import unittest
from pyalgs.algorithms.commons.union_find import UnionFind, QuickFind, QuickUnion
and context from other files:
# Path: pyalgs/algorithms/commons/union_find.py
# class UnionFind(object):
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def union(self, v, w):
# pass
#
# @abstractmethod
# def connected(self, v, w):
# pass
#
# @staticmethod
# def create(size):
# return QuickUnion(size)
#
# class QuickFind(UnionFind):
# id = None
#
# def __init__(self, capacity):
# self.id = [i for i in range(capacity)]
#
# def connected(self, v, w):
# return self.id[v] == self.id[w]
#
# def union(self, v, w):
# p = self.id[v]
# q = self.id[w]
#
# if p != q:
# for i in range(len(self.id)):
# if self.id[i] == p:
# self.id[i] = q
#
# class QuickUnion(UnionFind):
# id = None
# sizes = None
#
# def __init__(self, capacity):
# self.id = [i for i in range(capacity)]
# self.sizes = [1] * capacity
#
# def root(self, v):
# while v != self.id[v]:
# self.id[v] = self.id[self.id[v]] # path compression
# v = self.id[v]
# return v
#
# def connected(self, v, w):
# return self.root(v) == self.root(w)
#
# def union(self, v, w):
# vroot = self.root(v)
# wroot = self.root(w)
#
# if self.sizes[vroot] > self.sizes[wroot]:
# self.id[wroot] = vroot
# self.sizes[vroot] += self.sizes[wroot]
# else:
# self.id[vroot] = wroot
# self.sizes[wroot] += self.sizes[vroot]
, which may contain function names, class names, or code. Output only the next line. | uf = QuickUnion(10) |
Here is a snippet: <|code_start|>
class UtilTest(unittest.TestCase):
def test_less(self):
self.assertTrue(less(4, 5))
self.assertFalse(less(4, 4))
def test_exchange(self):
a = [2, 4, 5]
<|code_end|>
. Write the next line using the current file imports:
import unittest
from pyalgs.algorithms.commons.util import less, exchange
and context from other files:
# Path: pyalgs/algorithms/commons/util.py
# def less(a, b):
# return cmp(a, b) < 0
#
# def exchange(a, i, j):
# tmp = a[j]
# a[j] = a[i]
# a[i] = tmp
, which may include functions, classes, or code. Output only the next line. | exchange(a, 0, 1) |
Using the snippet: <|code_start|>
self.assertEqual(5, set.size())
self.assertFalse(set.is_empty())
set.delete("one")
self.assertFalse(set.contains("one"))
self.assertEqual(4, set.size())
set.delete("ten")
self.assertFalse(set.contains("ten"))
self.assertEqual(3, set.size())
set.delete("three")
self.assertFalse(set.contains("three"))
self.assertEqual(2, set.size())
for i in range(100):
set.add(str(i))
self.assertTrue(set.contains(str(i)))
for key in set.iterate():
print(key)
for i in range(100):
set.delete(str(i))
self.assertFalse(set.contains(str(i)))
class HashedSetWithSeparateChainingUnitTest(unittest.TestCase):
def test_binarySearchTree(self):
<|code_end|>
, determine the next line of code. You have imports:
import unittest
from pyalgs.data_structures.commons.hashed_set import HashedSetWithSeparateChaining, HashedSet, \
HashedSetWithLinearProbing
and context (class names, function names, or code) available:
# Path: pyalgs/data_structures/commons/hashed_set.py
# class HashedSetWithSeparateChaining(HashedSet):
# M = 97
# id = None
# N = 0
#
# def __init__(self, m=None):
# if m is None:
# m = 97
# self.M = m
# self.id = [None] * self.M
#
# def hash(self, key):
# return (hash(key) & 0x7fffffff) % self.M
#
# def is_empty(self):
# return self.N == 0
#
# def iterate(self):
# for i in range(self.M):
# x = self.id[i]
# while x is not None:
# key = x.key
# x = x.next_node
# yield key
#
# def size(self):
# return self.N
#
# def contains(self, key):
# i = self.hash(key)
# x = self.id[i]
# while x is not None:
# if util.cmp(x.key, key) == 0:
# return True
# x = x.next_node
# return False
#
# def delete(self, key):
# i = self.hash(key)
# x = self.id[i]
# prev_node = None
# while x is not None:
# if util.cmp(x.key, key) == 0:
# next_node = x.next_node
# self.N -= 1
# if prev_node is not None:
# prev_node.next_node = next_node
# if self.id[i] == x:
# self.id[i] = None
# return True
# prev_node = x
# x = x.next_node
# return False
#
# def add(self, key):
# if key is None:
# raise ValueError('key cannot be None')
#
# i = self.hash(key)
# x = self.id[i]
# while x is not None:
# if util.cmp(x.key, key) == 0:
# return
# x = x.next_node
# old_first = self.id[i]
# self.id[i] = Node(key)
# self.id[i].next_node = old_first
# self.N += 1
#
# class HashedSet(object):
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def add(self, key):
# pass
#
# @abstractmethod
# def delete(self, key):
# pass
#
# @abstractmethod
# def size(self):
# pass
#
# @abstractmethod
# def is_empty(self):
# pass
#
# @abstractmethod
# def iterate(self):
# pass
#
# @abstractmethod
# def contains(self, key):
# pass
#
# @staticmethod
# def create():
# return HashedSetWithSeparateChaining()
#
# class HashedSetWithLinearProbing(HashedSet):
#
# M = 97
# id = None
# N = 0
#
# def __init__(self, m=None):
# if m is None:
# m = 97
# self.M = m
# self.id = [None] * self.M
#
# def hash(self, key):
# return (hash(key) & 0x7fffffff) % self.M
#
# def is_empty(self):
# return self.N == 0
#
# def iterate(self):
# for i in range(self.M):
# x = self.id[i]
# if x is not None:
# yield x.key
#
# def size(self):
# return self.N
#
# def contains(self, key):
# i = self.hash(key)
# for j in range(self.M):
# k = (i + j) % self.M
# x = self.id[k]
# if x is None:
# return False
# if util.cmp(key, x.key) == 0:
# return True
#
# def delete(self, key):
# i = self.hash(key)
# for j in range(self.M):
# k = (i + j) % self.M
# x = self.id[k]
# if x is None:
# return False
# if util.cmp(key, x.key) == 0:
# self.id[k] = None
# self.N -= 1
# if self.N == self.M // 4:
# self.resize(self.M // 2)
# return True
#
# def add(self, key):
# i = self.hash(key)
# for j in range(self.M):
# k = (i + j) % self.M
# x = self.id[k]
# if x is None:
# self.id[k] = Node(key)
# self.N += 1
# if self.N == self.M // 2:
# self.resize(self.M * 2)
# break
# if util.cmp(x.key, key) == 0:
# break
#
# def resize(self, new_size):
# clone = HashedSetWithLinearProbing(new_size)
# for i in range(self.M):
# x = self.id[i]
# if x is not None:
# clone.add(x.key)
# self.M = clone.M
# self.id = clone.id
. Output only the next line. | set = HashedSetWithSeparateChaining() |
Next line prediction: <|code_start|>
self.assertEqual(5, set.size())
self.assertFalse(set.is_empty())
set.delete("one")
self.assertFalse(set.contains("one"))
self.assertEqual(4, set.size())
set.delete("ten")
self.assertFalse(set.contains("ten"))
self.assertEqual(3, set.size())
set.delete("three")
self.assertFalse(set.contains("three"))
self.assertEqual(2, set.size())
for i in range(100):
set.add(str(i))
self.assertTrue(set.contains(str(i)))
for key in set.iterate():
print(key)
for i in range(100):
set.delete(str(i))
self.assertFalse(set.contains(str(i)))
class HashedSetWithLinearProbingUnitTest(unittest.TestCase):
def test_binarySearchTree(self):
<|code_end|>
. Use current file imports:
(import unittest
from pyalgs.data_structures.commons.hashed_set import HashedSetWithSeparateChaining, HashedSet, \
HashedSetWithLinearProbing)
and context including class names, function names, or small code snippets from other files:
# Path: pyalgs/data_structures/commons/hashed_set.py
# class HashedSetWithSeparateChaining(HashedSet):
# M = 97
# id = None
# N = 0
#
# def __init__(self, m=None):
# if m is None:
# m = 97
# self.M = m
# self.id = [None] * self.M
#
# def hash(self, key):
# return (hash(key) & 0x7fffffff) % self.M
#
# def is_empty(self):
# return self.N == 0
#
# def iterate(self):
# for i in range(self.M):
# x = self.id[i]
# while x is not None:
# key = x.key
# x = x.next_node
# yield key
#
# def size(self):
# return self.N
#
# def contains(self, key):
# i = self.hash(key)
# x = self.id[i]
# while x is not None:
# if util.cmp(x.key, key) == 0:
# return True
# x = x.next_node
# return False
#
# def delete(self, key):
# i = self.hash(key)
# x = self.id[i]
# prev_node = None
# while x is not None:
# if util.cmp(x.key, key) == 0:
# next_node = x.next_node
# self.N -= 1
# if prev_node is not None:
# prev_node.next_node = next_node
# if self.id[i] == x:
# self.id[i] = None
# return True
# prev_node = x
# x = x.next_node
# return False
#
# def add(self, key):
# if key is None:
# raise ValueError('key cannot be None')
#
# i = self.hash(key)
# x = self.id[i]
# while x is not None:
# if util.cmp(x.key, key) == 0:
# return
# x = x.next_node
# old_first = self.id[i]
# self.id[i] = Node(key)
# self.id[i].next_node = old_first
# self.N += 1
#
# class HashedSet(object):
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def add(self, key):
# pass
#
# @abstractmethod
# def delete(self, key):
# pass
#
# @abstractmethod
# def size(self):
# pass
#
# @abstractmethod
# def is_empty(self):
# pass
#
# @abstractmethod
# def iterate(self):
# pass
#
# @abstractmethod
# def contains(self, key):
# pass
#
# @staticmethod
# def create():
# return HashedSetWithSeparateChaining()
#
# class HashedSetWithLinearProbing(HashedSet):
#
# M = 97
# id = None
# N = 0
#
# def __init__(self, m=None):
# if m is None:
# m = 97
# self.M = m
# self.id = [None] * self.M
#
# def hash(self, key):
# return (hash(key) & 0x7fffffff) % self.M
#
# def is_empty(self):
# return self.N == 0
#
# def iterate(self):
# for i in range(self.M):
# x = self.id[i]
# if x is not None:
# yield x.key
#
# def size(self):
# return self.N
#
# def contains(self, key):
# i = self.hash(key)
# for j in range(self.M):
# k = (i + j) % self.M
# x = self.id[k]
# if x is None:
# return False
# if util.cmp(key, x.key) == 0:
# return True
#
# def delete(self, key):
# i = self.hash(key)
# for j in range(self.M):
# k = (i + j) % self.M
# x = self.id[k]
# if x is None:
# return False
# if util.cmp(key, x.key) == 0:
# self.id[k] = None
# self.N -= 1
# if self.N == self.M // 4:
# self.resize(self.M // 2)
# return True
#
# def add(self, key):
# i = self.hash(key)
# for j in range(self.M):
# k = (i + j) % self.M
# x = self.id[k]
# if x is None:
# self.id[k] = Node(key)
# self.N += 1
# if self.N == self.M // 2:
# self.resize(self.M * 2)
# break
# if util.cmp(x.key, key) == 0:
# break
#
# def resize(self, new_size):
# clone = HashedSetWithLinearProbing(new_size)
# for i in range(self.M):
# x = self.id[i]
# if x is not None:
# clone.add(x.key)
# self.M = clone.M
# self.id = clone.id
. Output only the next line. | set = HashedSetWithLinearProbing() |
Given snippet: <|code_start|> self.edgesTo[w] = v
self.dfs(G, w)
def hasPathTo(self, v):
return self.marked[v]
def pathTo(self, v):
x = v
path = Stack.create()
while x != self.s:
path.push(x)
x = self.edgesTo[x]
path.push(self.s)
return path.iterate()
class BreadthFirstSearch(Paths):
marked = None
s = None
edgeTo = None
def __init__(self, G, s):
if isinstance(G, EdgeWeightedGraph):
G = G.to_graph()
self.s = s
vertex_count = G.vertex_count()
self.marked = [False] * vertex_count
self.edgeTo = [-1] * vertex_count
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from abc import ABCMeta, abstractmethod
from pyalgs.data_structures.commons.queue import Queue
from pyalgs.data_structures.commons.stack import Stack
from pyalgs.data_structures.graphs.graph import EdgeWeightedGraph
and context:
# Path: pyalgs/data_structures/commons/queue.py
# class Queue(object):
# """ Queue interface
#
# """
#
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def enqueue(self, item):
# pass
#
# @abstractmethod
# def dequeue(self):
# pass
#
# @abstractmethod
# def is_empty(self):
# pass
#
# @abstractmethod
# def size(self):
# pass
#
# @staticmethod
# def create():
# return LinkedListQueue()
#
# @abstractmethod
# def iterate(self):
# pass
#
# Path: pyalgs/data_structures/commons/stack.py
# class Stack(object):
# """ Stack interface which provides the API for stack data structure
# """
#
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def push(self, item):
# pass
#
# @abstractmethod
# def pop(self):
# pass
#
# @abstractmethod
# def is_empty(self):
# pass
#
# @abstractmethod
# def size(self):
# pass
#
# @abstractmethod
# def iterate(self):
# pass
#
# @staticmethod
# def create():
# return LinkedListStack()
#
# Path: pyalgs/data_structures/graphs/graph.py
# class EdgeWeightedGraph(object):
# adjList = None
# V = 0
#
# def __init__(self, vertex_count):
# self.V = vertex_count
# self.adjList = [None] * vertex_count
# for v in range(vertex_count):
# self.adjList[v] = Bag()
#
# def add_edge(self, edge):
# v = edge.either()
# w = edge.other(v)
# self.adjList[v].add(edge)
# self.adjList[w].add(edge)
#
# def adj(self, v):
# return self.adjList[v].iterate()
#
# def vertex_count(self):
# return self.V
#
# def edges(self):
# for v in range(self.V):
# for e in self.adj(v):
# if e.either() == v:
# yield e
#
# def to_graph(self):
# g = Graph()
#
# for e in self.edges():
# g.add_edge(e.start(), e.end())
# return g
#
# def to_edge_weighted_digraph(self):
# g = DirectedEdgeWeightedGraph(self.V)
#
# for e in self.edges():
# g.add_edge(e)
# g.add_edge(e.reverse())
# return g
which might include code, classes, or functions. Output only the next line. | queue = Queue.create() |
Given the code snippet: <|code_start|> def hasPathTo(self, v):
pass
class DepthFirstSearch(Paths):
marked = None
edgesTo = None
s = None
def __init__(self, G, s):
if isinstance(G, EdgeWeightedGraph):
G = G.to_graph()
self.s = s
vertex_count = G.vertex_count()
self.marked = [False] * vertex_count
self.edgesTo = [-1] * vertex_count
self.dfs(G, s)
def dfs(self, G, v):
self.marked[v] = True
for w in G.adj(v):
if not self.marked[w]:
self.edgesTo[w] = v
self.dfs(G, w)
def hasPathTo(self, v):
return self.marked[v]
def pathTo(self, v):
x = v
<|code_end|>
, generate the next line using the imports in this file:
from abc import ABCMeta, abstractmethod
from pyalgs.data_structures.commons.queue import Queue
from pyalgs.data_structures.commons.stack import Stack
from pyalgs.data_structures.graphs.graph import EdgeWeightedGraph
and context (functions, classes, or occasionally code) from other files:
# Path: pyalgs/data_structures/commons/queue.py
# class Queue(object):
# """ Queue interface
#
# """
#
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def enqueue(self, item):
# pass
#
# @abstractmethod
# def dequeue(self):
# pass
#
# @abstractmethod
# def is_empty(self):
# pass
#
# @abstractmethod
# def size(self):
# pass
#
# @staticmethod
# def create():
# return LinkedListQueue()
#
# @abstractmethod
# def iterate(self):
# pass
#
# Path: pyalgs/data_structures/commons/stack.py
# class Stack(object):
# """ Stack interface which provides the API for stack data structure
# """
#
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def push(self, item):
# pass
#
# @abstractmethod
# def pop(self):
# pass
#
# @abstractmethod
# def is_empty(self):
# pass
#
# @abstractmethod
# def size(self):
# pass
#
# @abstractmethod
# def iterate(self):
# pass
#
# @staticmethod
# def create():
# return LinkedListStack()
#
# Path: pyalgs/data_structures/graphs/graph.py
# class EdgeWeightedGraph(object):
# adjList = None
# V = 0
#
# def __init__(self, vertex_count):
# self.V = vertex_count
# self.adjList = [None] * vertex_count
# for v in range(vertex_count):
# self.adjList[v] = Bag()
#
# def add_edge(self, edge):
# v = edge.either()
# w = edge.other(v)
# self.adjList[v].add(edge)
# self.adjList[w].add(edge)
#
# def adj(self, v):
# return self.adjList[v].iterate()
#
# def vertex_count(self):
# return self.V
#
# def edges(self):
# for v in range(self.V):
# for e in self.adj(v):
# if e.either() == v:
# yield e
#
# def to_graph(self):
# g = Graph()
#
# for e in self.edges():
# g.add_edge(e.start(), e.end())
# return g
#
# def to_edge_weighted_digraph(self):
# g = DirectedEdgeWeightedGraph(self.V)
#
# for e in self.edges():
# g.add_edge(e)
# g.add_edge(e.reverse())
# return g
. Output only the next line. | path = Stack.create() |
Given the following code snippet before the placeholder: <|code_start|>
class Paths(object):
__metaclass__ = ABCMeta
@abstractmethod
def pathTo(self, v):
pass
@abstractmethod
def hasPathTo(self, v):
pass
class DepthFirstSearch(Paths):
marked = None
edgesTo = None
s = None
def __init__(self, G, s):
<|code_end|>
, predict the next line using imports from the current file:
from abc import ABCMeta, abstractmethod
from pyalgs.data_structures.commons.queue import Queue
from pyalgs.data_structures.commons.stack import Stack
from pyalgs.data_structures.graphs.graph import EdgeWeightedGraph
and context including class names, function names, and sometimes code from other files:
# Path: pyalgs/data_structures/commons/queue.py
# class Queue(object):
# """ Queue interface
#
# """
#
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def enqueue(self, item):
# pass
#
# @abstractmethod
# def dequeue(self):
# pass
#
# @abstractmethod
# def is_empty(self):
# pass
#
# @abstractmethod
# def size(self):
# pass
#
# @staticmethod
# def create():
# return LinkedListQueue()
#
# @abstractmethod
# def iterate(self):
# pass
#
# Path: pyalgs/data_structures/commons/stack.py
# class Stack(object):
# """ Stack interface which provides the API for stack data structure
# """
#
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def push(self, item):
# pass
#
# @abstractmethod
# def pop(self):
# pass
#
# @abstractmethod
# def is_empty(self):
# pass
#
# @abstractmethod
# def size(self):
# pass
#
# @abstractmethod
# def iterate(self):
# pass
#
# @staticmethod
# def create():
# return LinkedListStack()
#
# Path: pyalgs/data_structures/graphs/graph.py
# class EdgeWeightedGraph(object):
# adjList = None
# V = 0
#
# def __init__(self, vertex_count):
# self.V = vertex_count
# self.adjList = [None] * vertex_count
# for v in range(vertex_count):
# self.adjList[v] = Bag()
#
# def add_edge(self, edge):
# v = edge.either()
# w = edge.other(v)
# self.adjList[v].add(edge)
# self.adjList[w].add(edge)
#
# def adj(self, v):
# return self.adjList[v].iterate()
#
# def vertex_count(self):
# return self.V
#
# def edges(self):
# for v in range(self.V):
# for e in self.adj(v):
# if e.either() == v:
# yield e
#
# def to_graph(self):
# g = Graph()
#
# for e in self.edges():
# g.add_edge(e.start(), e.end())
# return g
#
# def to_edge_weighted_digraph(self):
# g = DirectedEdgeWeightedGraph(self.V)
#
# for e in self.edges():
# g.add_edge(e)
# g.add_edge(e.reverse())
# return g
. Output only the next line. | if isinstance(G, EdgeWeightedGraph): |
Given the following code snippet before the placeholder: <|code_start|>
class BruteForceSubstringSearchUnitTest(unittest.TestCase):
def test_search(self):
t = some_text()
<|code_end|>
, predict the next line using imports from the current file:
import unittest
from pyalgs.algorithms.strings.substring_search import BruteForceSubstringSearch, RabinKarp, BoyerMoore, \
KnuthMorrisPratt
from tests.algorithms.strings.util import some_text
and context including class names, function names, and sometimes code from other files:
# Path: pyalgs/algorithms/strings/substring_search.py
# class BruteForceSubstringSearch(SubstringSearch):
# def __init__(self, pattern):
# self.pattern = pattern
#
# def search_in(self, text):
# n = len(text)
#
# for i in range(n - len(self.pattern)):
# J = i
# for j in range(len(self.pattern)):
# k = i + j
# if text[k] != self.pattern[j]:
# J = -1
# break
# if J != -1:
# return J
#
# return -1
#
# class RabinKarp(SubstringSearch):
# patHash = None
# Q = 1573773197
# R = 256
# M = None
# RM = None
#
# def __init__(self, pat):
# h = 1
# self.M = len(pat)
# for i in range(1, self.M):
# h = (h * RabinKarp.R) % RabinKarp.Q
#
# self.RM = h
#
# self.patHash = self.hash(pat, self.M)
#
# def hash(self, text, M):
# h = 0
# for d in range(M):
# h = (h * RabinKarp.R + char_at(text, d)) % RabinKarp.Q
# return h
#
# def search_in(self, text):
# text_hash = self.hash(text, self.M)
# if text_hash == self.patHash:
# return 0
# for i in range(self.M, len(text)):
# text_hash = (text_hash + RabinKarp.Q - self.RM * char_at(text, i - self.M) % RabinKarp.Q) % RabinKarp.Q
# text_hash = (text_hash * RabinKarp.R + char_at(text, i)) % RabinKarp.Q
# if text_hash == self.patHash:
# return i - self.M + 1
# return -1
#
# class BoyerMoore(SubstringSearch):
# right = None
# R = 256
# pattern = None
#
# def __init__(self, pattern):
# self.pattern = pattern
# self.right = [0] * BoyerMoore.R
# for i in range(len(pattern)):
# self.right[char_at(pattern, i)] = i
#
# def search_in(self, text):
# n = len(text)
# m = len(self.pattern)
#
# skip = 1
# i = 0
# while i <= n - m:
# for j in range(m-1, -1, -1):
# if char_at(text, i+j) != char_at(self.pattern, j):
# skip = max(1, j - self.right[char_at(text, i+j)])
# break
# if j == 0:
# return i
# i += skip
#
# return -1
#
# class KnuthMorrisPratt(SubstringSearch):
#
# dfs = None
# M = None
# R = 256
#
# def __init__(self, pattern):
# self.M = len(pattern)
#
# self.dfs = [None] * self.R
# for i in range(self.R):
# self.dfs[i] = [0] * self.M
# self.dfs[0][0] = 1
#
# X = 0
# for j in range(self.M):
# for i in range(self.R):
# self.dfs[i][j] = self.dfs[i][X]
# self.dfs[char_at(pattern, j)][j] = j+1
# X = self.dfs[char_at(pattern, j)][X]
#
# def search_in(self, text):
#
# n = len(text)
#
# j = 0
# for i in range(n):
# j = self.dfs[char_at(text, i)][j]
# if j == self.M:
# return i - self.M
#
# return -1
#
# Path: tests/algorithms/strings/util.py
# def some_text():
# return "bed bug dad yes zoo now for tip ilk dim tag jot sob nob sky hut men egg few jay owl joy rap gig wee was wad fee tap tar dug jam all bad yet"
. Output only the next line. | ss = BruteForceSubstringSearch('men') |
Here is a snippet: <|code_start|>
class BruteForceSubstringSearchUnitTest(unittest.TestCase):
def test_search(self):
t = some_text()
ss = BruteForceSubstringSearch('men')
self.assertNotEqual(-1, ss.search_in(t))
self.assertEqual(-1, ss.search_in('Hello World'))
class RabinKarpUnitTest(unittest.TestCase):
def test_search(self):
t = some_text()
<|code_end|>
. Write the next line using the current file imports:
import unittest
from pyalgs.algorithms.strings.substring_search import BruteForceSubstringSearch, RabinKarp, BoyerMoore, \
KnuthMorrisPratt
from tests.algorithms.strings.util import some_text
and context from other files:
# Path: pyalgs/algorithms/strings/substring_search.py
# class BruteForceSubstringSearch(SubstringSearch):
# def __init__(self, pattern):
# self.pattern = pattern
#
# def search_in(self, text):
# n = len(text)
#
# for i in range(n - len(self.pattern)):
# J = i
# for j in range(len(self.pattern)):
# k = i + j
# if text[k] != self.pattern[j]:
# J = -1
# break
# if J != -1:
# return J
#
# return -1
#
# class RabinKarp(SubstringSearch):
# patHash = None
# Q = 1573773197
# R = 256
# M = None
# RM = None
#
# def __init__(self, pat):
# h = 1
# self.M = len(pat)
# for i in range(1, self.M):
# h = (h * RabinKarp.R) % RabinKarp.Q
#
# self.RM = h
#
# self.patHash = self.hash(pat, self.M)
#
# def hash(self, text, M):
# h = 0
# for d in range(M):
# h = (h * RabinKarp.R + char_at(text, d)) % RabinKarp.Q
# return h
#
# def search_in(self, text):
# text_hash = self.hash(text, self.M)
# if text_hash == self.patHash:
# return 0
# for i in range(self.M, len(text)):
# text_hash = (text_hash + RabinKarp.Q - self.RM * char_at(text, i - self.M) % RabinKarp.Q) % RabinKarp.Q
# text_hash = (text_hash * RabinKarp.R + char_at(text, i)) % RabinKarp.Q
# if text_hash == self.patHash:
# return i - self.M + 1
# return -1
#
# class BoyerMoore(SubstringSearch):
# right = None
# R = 256
# pattern = None
#
# def __init__(self, pattern):
# self.pattern = pattern
# self.right = [0] * BoyerMoore.R
# for i in range(len(pattern)):
# self.right[char_at(pattern, i)] = i
#
# def search_in(self, text):
# n = len(text)
# m = len(self.pattern)
#
# skip = 1
# i = 0
# while i <= n - m:
# for j in range(m-1, -1, -1):
# if char_at(text, i+j) != char_at(self.pattern, j):
# skip = max(1, j - self.right[char_at(text, i+j)])
# break
# if j == 0:
# return i
# i += skip
#
# return -1
#
# class KnuthMorrisPratt(SubstringSearch):
#
# dfs = None
# M = None
# R = 256
#
# def __init__(self, pattern):
# self.M = len(pattern)
#
# self.dfs = [None] * self.R
# for i in range(self.R):
# self.dfs[i] = [0] * self.M
# self.dfs[0][0] = 1
#
# X = 0
# for j in range(self.M):
# for i in range(self.R):
# self.dfs[i][j] = self.dfs[i][X]
# self.dfs[char_at(pattern, j)][j] = j+1
# X = self.dfs[char_at(pattern, j)][X]
#
# def search_in(self, text):
#
# n = len(text)
#
# j = 0
# for i in range(n):
# j = self.dfs[char_at(text, i)][j]
# if j == self.M:
# return i - self.M
#
# return -1
#
# Path: tests/algorithms/strings/util.py
# def some_text():
# return "bed bug dad yes zoo now for tip ilk dim tag jot sob nob sky hut men egg few jay owl joy rap gig wee was wad fee tap tar dug jam all bad yet"
, which may include functions, classes, or code. Output only the next line. | ss = RabinKarp('men') |
Next line prediction: <|code_start|>
class BruteForceSubstringSearchUnitTest(unittest.TestCase):
def test_search(self):
t = some_text()
ss = BruteForceSubstringSearch('men')
self.assertNotEqual(-1, ss.search_in(t))
self.assertEqual(-1, ss.search_in('Hello World'))
class RabinKarpUnitTest(unittest.TestCase):
def test_search(self):
t = some_text()
ss = RabinKarp('men')
self.assertNotEqual(-1, ss.search_in(t))
self.assertEqual(-1, ss.search_in('Hello World'))
class BoyerMooreUnitTest(unittest.TestCase):
def test_search(self):
t = some_text()
<|code_end|>
. Use current file imports:
(import unittest
from pyalgs.algorithms.strings.substring_search import BruteForceSubstringSearch, RabinKarp, BoyerMoore, \
KnuthMorrisPratt
from tests.algorithms.strings.util import some_text)
and context including class names, function names, or small code snippets from other files:
# Path: pyalgs/algorithms/strings/substring_search.py
# class BruteForceSubstringSearch(SubstringSearch):
# def __init__(self, pattern):
# self.pattern = pattern
#
# def search_in(self, text):
# n = len(text)
#
# for i in range(n - len(self.pattern)):
# J = i
# for j in range(len(self.pattern)):
# k = i + j
# if text[k] != self.pattern[j]:
# J = -1
# break
# if J != -1:
# return J
#
# return -1
#
# class RabinKarp(SubstringSearch):
# patHash = None
# Q = 1573773197
# R = 256
# M = None
# RM = None
#
# def __init__(self, pat):
# h = 1
# self.M = len(pat)
# for i in range(1, self.M):
# h = (h * RabinKarp.R) % RabinKarp.Q
#
# self.RM = h
#
# self.patHash = self.hash(pat, self.M)
#
# def hash(self, text, M):
# h = 0
# for d in range(M):
# h = (h * RabinKarp.R + char_at(text, d)) % RabinKarp.Q
# return h
#
# def search_in(self, text):
# text_hash = self.hash(text, self.M)
# if text_hash == self.patHash:
# return 0
# for i in range(self.M, len(text)):
# text_hash = (text_hash + RabinKarp.Q - self.RM * char_at(text, i - self.M) % RabinKarp.Q) % RabinKarp.Q
# text_hash = (text_hash * RabinKarp.R + char_at(text, i)) % RabinKarp.Q
# if text_hash == self.patHash:
# return i - self.M + 1
# return -1
#
# class BoyerMoore(SubstringSearch):
# right = None
# R = 256
# pattern = None
#
# def __init__(self, pattern):
# self.pattern = pattern
# self.right = [0] * BoyerMoore.R
# for i in range(len(pattern)):
# self.right[char_at(pattern, i)] = i
#
# def search_in(self, text):
# n = len(text)
# m = len(self.pattern)
#
# skip = 1
# i = 0
# while i <= n - m:
# for j in range(m-1, -1, -1):
# if char_at(text, i+j) != char_at(self.pattern, j):
# skip = max(1, j - self.right[char_at(text, i+j)])
# break
# if j == 0:
# return i
# i += skip
#
# return -1
#
# class KnuthMorrisPratt(SubstringSearch):
#
# dfs = None
# M = None
# R = 256
#
# def __init__(self, pattern):
# self.M = len(pattern)
#
# self.dfs = [None] * self.R
# for i in range(self.R):
# self.dfs[i] = [0] * self.M
# self.dfs[0][0] = 1
#
# X = 0
# for j in range(self.M):
# for i in range(self.R):
# self.dfs[i][j] = self.dfs[i][X]
# self.dfs[char_at(pattern, j)][j] = j+1
# X = self.dfs[char_at(pattern, j)][X]
#
# def search_in(self, text):
#
# n = len(text)
#
# j = 0
# for i in range(n):
# j = self.dfs[char_at(text, i)][j]
# if j == self.M:
# return i - self.M
#
# return -1
#
# Path: tests/algorithms/strings/util.py
# def some_text():
# return "bed bug dad yes zoo now for tip ilk dim tag jot sob nob sky hut men egg few jay owl joy rap gig wee was wad fee tap tar dug jam all bad yet"
. Output only the next line. | ss = BoyerMoore('men') |
Predict the next line for this snippet: <|code_start|>
def test_search(self):
t = some_text()
ss = BruteForceSubstringSearch('men')
self.assertNotEqual(-1, ss.search_in(t))
self.assertEqual(-1, ss.search_in('Hello World'))
class RabinKarpUnitTest(unittest.TestCase):
def test_search(self):
t = some_text()
ss = RabinKarp('men')
self.assertNotEqual(-1, ss.search_in(t))
self.assertEqual(-1, ss.search_in('Hello World'))
class BoyerMooreUnitTest(unittest.TestCase):
def test_search(self):
t = some_text()
ss = BoyerMoore('men')
self.assertNotEqual(-1, ss.search_in(t))
self.assertEqual(-1, ss.search_in('Hello World'))
class KnuthMorrisPrattUnitTest(unittest.TestCase):
def test_search(self):
t = some_text()
<|code_end|>
with the help of current file imports:
import unittest
from pyalgs.algorithms.strings.substring_search import BruteForceSubstringSearch, RabinKarp, BoyerMoore, \
KnuthMorrisPratt
from tests.algorithms.strings.util import some_text
and context from other files:
# Path: pyalgs/algorithms/strings/substring_search.py
# class BruteForceSubstringSearch(SubstringSearch):
# def __init__(self, pattern):
# self.pattern = pattern
#
# def search_in(self, text):
# n = len(text)
#
# for i in range(n - len(self.pattern)):
# J = i
# for j in range(len(self.pattern)):
# k = i + j
# if text[k] != self.pattern[j]:
# J = -1
# break
# if J != -1:
# return J
#
# return -1
#
# class RabinKarp(SubstringSearch):
# patHash = None
# Q = 1573773197
# R = 256
# M = None
# RM = None
#
# def __init__(self, pat):
# h = 1
# self.M = len(pat)
# for i in range(1, self.M):
# h = (h * RabinKarp.R) % RabinKarp.Q
#
# self.RM = h
#
# self.patHash = self.hash(pat, self.M)
#
# def hash(self, text, M):
# h = 0
# for d in range(M):
# h = (h * RabinKarp.R + char_at(text, d)) % RabinKarp.Q
# return h
#
# def search_in(self, text):
# text_hash = self.hash(text, self.M)
# if text_hash == self.patHash:
# return 0
# for i in range(self.M, len(text)):
# text_hash = (text_hash + RabinKarp.Q - self.RM * char_at(text, i - self.M) % RabinKarp.Q) % RabinKarp.Q
# text_hash = (text_hash * RabinKarp.R + char_at(text, i)) % RabinKarp.Q
# if text_hash == self.patHash:
# return i - self.M + 1
# return -1
#
# class BoyerMoore(SubstringSearch):
# right = None
# R = 256
# pattern = None
#
# def __init__(self, pattern):
# self.pattern = pattern
# self.right = [0] * BoyerMoore.R
# for i in range(len(pattern)):
# self.right[char_at(pattern, i)] = i
#
# def search_in(self, text):
# n = len(text)
# m = len(self.pattern)
#
# skip = 1
# i = 0
# while i <= n - m:
# for j in range(m-1, -1, -1):
# if char_at(text, i+j) != char_at(self.pattern, j):
# skip = max(1, j - self.right[char_at(text, i+j)])
# break
# if j == 0:
# return i
# i += skip
#
# return -1
#
# class KnuthMorrisPratt(SubstringSearch):
#
# dfs = None
# M = None
# R = 256
#
# def __init__(self, pattern):
# self.M = len(pattern)
#
# self.dfs = [None] * self.R
# for i in range(self.R):
# self.dfs[i] = [0] * self.M
# self.dfs[0][0] = 1
#
# X = 0
# for j in range(self.M):
# for i in range(self.R):
# self.dfs[i][j] = self.dfs[i][X]
# self.dfs[char_at(pattern, j)][j] = j+1
# X = self.dfs[char_at(pattern, j)][X]
#
# def search_in(self, text):
#
# n = len(text)
#
# j = 0
# for i in range(n):
# j = self.dfs[char_at(text, i)][j]
# if j == self.M:
# return i - self.M
#
# return -1
#
# Path: tests/algorithms/strings/util.py
# def some_text():
# return "bed bug dad yes zoo now for tip ilk dim tag jot sob nob sky hut men egg few jay owl joy rap gig wee was wad fee tap tar dug jam all bad yet"
, which may contain function names, class names, or code. Output only the next line. | ss = KnuthMorrisPratt('men') |
Using the snippet: <|code_start|>
class MinPQ(object):
pq = None
N = 0
def __init__(self, capacity=None):
if capacity is None:
capacity = 10
self.pq = [0] * capacity
def enqueue(self, key):
self.N += 1
if self.N == len(self.pq):
self.resize(len(self.pq) * 2)
self.pq[self.N] = key
self.swim(self.N)
def swim(self, k):
while k > 1:
parent = k // 2
<|code_end|>
, determine the next line of code. You have imports:
from pyalgs.algorithms.commons.util import less, exchange, greater
and context (class names, function names, or code) available:
# Path: pyalgs/algorithms/commons/util.py
# def less(a, b):
# return cmp(a, b) < 0
#
# def exchange(a, i, j):
# tmp = a[j]
# a[j] = a[i]
# a[i] = tmp
#
# def greater(a, b):
# return cmp(a, b) > 0
. Output only the next line. | if less(self.pq[k], self.pq[parent]): |
Predict the next line for this snippet: <|code_start|>
class MinPQ(object):
pq = None
N = 0
def __init__(self, capacity=None):
if capacity is None:
capacity = 10
self.pq = [0] * capacity
def enqueue(self, key):
self.N += 1
if self.N == len(self.pq):
self.resize(len(self.pq) * 2)
self.pq[self.N] = key
self.swim(self.N)
def swim(self, k):
while k > 1:
parent = k // 2
if less(self.pq[k], self.pq[parent]):
<|code_end|>
with the help of current file imports:
from pyalgs.algorithms.commons.util import less, exchange, greater
and context from other files:
# Path: pyalgs/algorithms/commons/util.py
# def less(a, b):
# return cmp(a, b) < 0
#
# def exchange(a, i, j):
# tmp = a[j]
# a[j] = a[i]
# a[i] = tmp
#
# def greater(a, b):
# return cmp(a, b) > 0
, which may contain function names, class names, or code. Output only the next line. | exchange(self.pq, k, parent) |
Next line prediction: <|code_start|> key = tmp[1]
exchange(tmp, 1, n)
n -= 1
self.sink(tmp, 1, n)
yield key
@staticmethod
def create():
return MinPQ()
class MaxPQ(object):
pq = None
N = 0
def __init__(self, capacity=None):
if capacity is None:
capacity = 10
self.pq = [0] * capacity
def enqueue(self, key):
if self.N == len(self.pq):
self.resize(len(self.pq) * 2)
self.N += 1
self.pq[self.N] = key
self.swim(self.N)
def swim(self, k):
while k > 1:
parent = k // 2
<|code_end|>
. Use current file imports:
(from pyalgs.algorithms.commons.util import less, exchange, greater)
and context including class names, function names, or small code snippets from other files:
# Path: pyalgs/algorithms/commons/util.py
# def less(a, b):
# return cmp(a, b) < 0
#
# def exchange(a, i, j):
# tmp = a[j]
# a[j] = a[i]
# a[i] = tmp
#
# def greater(a, b):
# return cmp(a, b) > 0
. Output only the next line. | if greater(self.pq[k], self.pq[parent]): |
Here is a snippet: <|code_start|> if not self.marked[w]:
self.dfs(G, w)
def connected(self, v, w):
return self._id[v] == self._id[w]
def count(self):
return self._count
def id(self, v):
return self._id[v]
class StronglyConnectedComponents(object):
marked = None
_id = None
_count = 0
def __init__(self, G):
if isinstance(G, EdgeWeightedGraph):
raise ValueError('Graph must be directed graph for strongly connected components')
if isinstance(G, DirectedEdgeWeightedGraph):
G = G.to_digrah()
if not isinstance(G, Digraph):
raise ValueError('Graph must be directed graph for strongly connected components')
vertex_count = G.vertex_count()
self.marked = [False] * vertex_count
self._id = [-1] * vertex_count
<|code_end|>
. Write the next line using the current file imports:
from abc import ABCMeta, abstractmethod
from pyalgs.algorithms.graphs.topological_sort import DepthFirstOrder
from pyalgs.data_structures.graphs.graph import EdgeWeightedGraph, Digraph, DirectedEdgeWeightedGraph
and context from other files:
# Path: pyalgs/algorithms/graphs/topological_sort.py
# class DepthFirstOrder(object):
#
# marked = None
# reversePostOrder = None
#
# def __init__(self, G):
# if isinstance(G, DirectedEdgeWeightedGraph):
# G = G.to_digraph()
#
# self.reversePostOrder = Stack.create()
# vertex_count = G.vertex_count()
# self.marked = [False] * vertex_count
#
# for v in range(vertex_count):
# if not self.marked[v]:
# self.dfs(G, v)
#
# def dfs(self, G, v):
# self.marked[v] = True
# for w in G.adj(v):
# if not self.marked[w]:
# self.dfs(G, w)
# self.reversePostOrder.push(v)
#
# def postOrder(self):
# return self.reversePostOrder.iterate()
#
# Path: pyalgs/data_structures/graphs/graph.py
# class EdgeWeightedGraph(object):
# adjList = None
# V = 0
#
# def __init__(self, vertex_count):
# self.V = vertex_count
# self.adjList = [None] * vertex_count
# for v in range(vertex_count):
# self.adjList[v] = Bag()
#
# def add_edge(self, edge):
# v = edge.either()
# w = edge.other(v)
# self.adjList[v].add(edge)
# self.adjList[w].add(edge)
#
# def adj(self, v):
# return self.adjList[v].iterate()
#
# def vertex_count(self):
# return self.V
#
# def edges(self):
# for v in range(self.V):
# for e in self.adj(v):
# if e.either() == v:
# yield e
#
# def to_graph(self):
# g = Graph()
#
# for e in self.edges():
# g.add_edge(e.start(), e.end())
# return g
#
# def to_edge_weighted_digraph(self):
# g = DirectedEdgeWeightedGraph(self.V)
#
# for e in self.edges():
# g.add_edge(e)
# g.add_edge(e.reverse())
# return g
#
# class Digraph(object):
# V = 0
# adjList = None
#
# def __init__(self, V):
# self.V = V
# self.adjList = [None] * V
# for v in range(V):
# self.adjList[v] = Bag()
#
# def vertex_count(self):
# return self.V
#
# def adj(self, v):
# return self.adjList[v].iterate()
#
# def add_edge(self, v, w):
# self.adjList[v].add(w)
#
# def reverse(self):
# g = Digraph(self.V)
# for v in range(self.V):
# for w in self.adjList[v].iterate():
# g.add_edge(w, v)
#
# return g
#
# class DirectedEdgeWeightedGraph(object):
# adjList = None
# V = 0
#
# def __init__(self, vertex_count):
# self.V = vertex_count
# self.adjList = [None] * vertex_count
# for v in range(vertex_count):
# self.adjList[v] = Bag()
#
# def add_edge(self, edge):
# v = edge.start()
# self.adjList[v].add(edge)
#
# def adj(self, v):
# return self.adjList[v].iterate()
#
# def vertex_count(self):
# return self.V
#
# def edges(self):
# for v in range(self.V):
# for e in self.adj(v):
# yield e
#
# def to_graph(self):
# g = Graph()
#
# for e in self.edges():
# g.add_edge(e.start(), e.end())
# return g
#
# def to_digraph(self):
# g = Digraph(self.V)
#
# for e in self.edges():
# g.add_edge(e.start(), e.end())
#
# return g
, which may include functions, classes, or code. Output only the next line. | dfo = DepthFirstOrder(G.reverse()) |
Using the snippet: <|code_start|>
class ConnectedComponents(object):
marked = None
_id = None
_count = 0
def __init__(self, G):
<|code_end|>
, determine the next line of code. You have imports:
from abc import ABCMeta, abstractmethod
from pyalgs.algorithms.graphs.topological_sort import DepthFirstOrder
from pyalgs.data_structures.graphs.graph import EdgeWeightedGraph, Digraph, DirectedEdgeWeightedGraph
and context (class names, function names, or code) available:
# Path: pyalgs/algorithms/graphs/topological_sort.py
# class DepthFirstOrder(object):
#
# marked = None
# reversePostOrder = None
#
# def __init__(self, G):
# if isinstance(G, DirectedEdgeWeightedGraph):
# G = G.to_digraph()
#
# self.reversePostOrder = Stack.create()
# vertex_count = G.vertex_count()
# self.marked = [False] * vertex_count
#
# for v in range(vertex_count):
# if not self.marked[v]:
# self.dfs(G, v)
#
# def dfs(self, G, v):
# self.marked[v] = True
# for w in G.adj(v):
# if not self.marked[w]:
# self.dfs(G, w)
# self.reversePostOrder.push(v)
#
# def postOrder(self):
# return self.reversePostOrder.iterate()
#
# Path: pyalgs/data_structures/graphs/graph.py
# class EdgeWeightedGraph(object):
# adjList = None
# V = 0
#
# def __init__(self, vertex_count):
# self.V = vertex_count
# self.adjList = [None] * vertex_count
# for v in range(vertex_count):
# self.adjList[v] = Bag()
#
# def add_edge(self, edge):
# v = edge.either()
# w = edge.other(v)
# self.adjList[v].add(edge)
# self.adjList[w].add(edge)
#
# def adj(self, v):
# return self.adjList[v].iterate()
#
# def vertex_count(self):
# return self.V
#
# def edges(self):
# for v in range(self.V):
# for e in self.adj(v):
# if e.either() == v:
# yield e
#
# def to_graph(self):
# g = Graph()
#
# for e in self.edges():
# g.add_edge(e.start(), e.end())
# return g
#
# def to_edge_weighted_digraph(self):
# g = DirectedEdgeWeightedGraph(self.V)
#
# for e in self.edges():
# g.add_edge(e)
# g.add_edge(e.reverse())
# return g
#
# class Digraph(object):
# V = 0
# adjList = None
#
# def __init__(self, V):
# self.V = V
# self.adjList = [None] * V
# for v in range(V):
# self.adjList[v] = Bag()
#
# def vertex_count(self):
# return self.V
#
# def adj(self, v):
# return self.adjList[v].iterate()
#
# def add_edge(self, v, w):
# self.adjList[v].add(w)
#
# def reverse(self):
# g = Digraph(self.V)
# for v in range(self.V):
# for w in self.adjList[v].iterate():
# g.add_edge(w, v)
#
# return g
#
# class DirectedEdgeWeightedGraph(object):
# adjList = None
# V = 0
#
# def __init__(self, vertex_count):
# self.V = vertex_count
# self.adjList = [None] * vertex_count
# for v in range(vertex_count):
# self.adjList[v] = Bag()
#
# def add_edge(self, edge):
# v = edge.start()
# self.adjList[v].add(edge)
#
# def adj(self, v):
# return self.adjList[v].iterate()
#
# def vertex_count(self):
# return self.V
#
# def edges(self):
# for v in range(self.V):
# for e in self.adj(v):
# yield e
#
# def to_graph(self):
# g = Graph()
#
# for e in self.edges():
# g.add_edge(e.start(), e.end())
# return g
#
# def to_digraph(self):
# g = Digraph(self.V)
#
# for e in self.edges():
# g.add_edge(e.start(), e.end())
#
# return g
. Output only the next line. | if isinstance(G, EdgeWeightedGraph): |
Using the snippet: <|code_start|> self.dfs(G, v)
self._count += 1
def dfs(self, G, v):
self.marked[v] = True
self._id[v] = self._count
for w in G.adj(v):
if not self.marked[w]:
self.dfs(G, w)
def connected(self, v, w):
return self._id[v] == self._id[w]
def count(self):
return self._count
def id(self, v):
return self._id[v]
class StronglyConnectedComponents(object):
marked = None
_id = None
_count = 0
def __init__(self, G):
if isinstance(G, EdgeWeightedGraph):
raise ValueError('Graph must be directed graph for strongly connected components')
if isinstance(G, DirectedEdgeWeightedGraph):
G = G.to_digrah()
<|code_end|>
, determine the next line of code. You have imports:
from abc import ABCMeta, abstractmethod
from pyalgs.algorithms.graphs.topological_sort import DepthFirstOrder
from pyalgs.data_structures.graphs.graph import EdgeWeightedGraph, Digraph, DirectedEdgeWeightedGraph
and context (class names, function names, or code) available:
# Path: pyalgs/algorithms/graphs/topological_sort.py
# class DepthFirstOrder(object):
#
# marked = None
# reversePostOrder = None
#
# def __init__(self, G):
# if isinstance(G, DirectedEdgeWeightedGraph):
# G = G.to_digraph()
#
# self.reversePostOrder = Stack.create()
# vertex_count = G.vertex_count()
# self.marked = [False] * vertex_count
#
# for v in range(vertex_count):
# if not self.marked[v]:
# self.dfs(G, v)
#
# def dfs(self, G, v):
# self.marked[v] = True
# for w in G.adj(v):
# if not self.marked[w]:
# self.dfs(G, w)
# self.reversePostOrder.push(v)
#
# def postOrder(self):
# return self.reversePostOrder.iterate()
#
# Path: pyalgs/data_structures/graphs/graph.py
# class EdgeWeightedGraph(object):
# adjList = None
# V = 0
#
# def __init__(self, vertex_count):
# self.V = vertex_count
# self.adjList = [None] * vertex_count
# for v in range(vertex_count):
# self.adjList[v] = Bag()
#
# def add_edge(self, edge):
# v = edge.either()
# w = edge.other(v)
# self.adjList[v].add(edge)
# self.adjList[w].add(edge)
#
# def adj(self, v):
# return self.adjList[v].iterate()
#
# def vertex_count(self):
# return self.V
#
# def edges(self):
# for v in range(self.V):
# for e in self.adj(v):
# if e.either() == v:
# yield e
#
# def to_graph(self):
# g = Graph()
#
# for e in self.edges():
# g.add_edge(e.start(), e.end())
# return g
#
# def to_edge_weighted_digraph(self):
# g = DirectedEdgeWeightedGraph(self.V)
#
# for e in self.edges():
# g.add_edge(e)
# g.add_edge(e.reverse())
# return g
#
# class Digraph(object):
# V = 0
# adjList = None
#
# def __init__(self, V):
# self.V = V
# self.adjList = [None] * V
# for v in range(V):
# self.adjList[v] = Bag()
#
# def vertex_count(self):
# return self.V
#
# def adj(self, v):
# return self.adjList[v].iterate()
#
# def add_edge(self, v, w):
# self.adjList[v].add(w)
#
# def reverse(self):
# g = Digraph(self.V)
# for v in range(self.V):
# for w in self.adjList[v].iterate():
# g.add_edge(w, v)
#
# return g
#
# class DirectedEdgeWeightedGraph(object):
# adjList = None
# V = 0
#
# def __init__(self, vertex_count):
# self.V = vertex_count
# self.adjList = [None] * vertex_count
# for v in range(vertex_count):
# self.adjList[v] = Bag()
#
# def add_edge(self, edge):
# v = edge.start()
# self.adjList[v].add(edge)
#
# def adj(self, v):
# return self.adjList[v].iterate()
#
# def vertex_count(self):
# return self.V
#
# def edges(self):
# for v in range(self.V):
# for e in self.adj(v):
# yield e
#
# def to_graph(self):
# g = Graph()
#
# for e in self.edges():
# g.add_edge(e.start(), e.end())
# return g
#
# def to_digraph(self):
# g = Digraph(self.V)
#
# for e in self.edges():
# g.add_edge(e.start(), e.end())
#
# return g
. Output only the next line. | if not isinstance(G, Digraph): |
Here is a snippet: <|code_start|> for v in range(vertex_count):
if not self.marked[v]:
self.dfs(G, v)
self._count += 1
def dfs(self, G, v):
self.marked[v] = True
self._id[v] = self._count
for w in G.adj(v):
if not self.marked[w]:
self.dfs(G, w)
def connected(self, v, w):
return self._id[v] == self._id[w]
def count(self):
return self._count
def id(self, v):
return self._id[v]
class StronglyConnectedComponents(object):
marked = None
_id = None
_count = 0
def __init__(self, G):
if isinstance(G, EdgeWeightedGraph):
raise ValueError('Graph must be directed graph for strongly connected components')
<|code_end|>
. Write the next line using the current file imports:
from abc import ABCMeta, abstractmethod
from pyalgs.algorithms.graphs.topological_sort import DepthFirstOrder
from pyalgs.data_structures.graphs.graph import EdgeWeightedGraph, Digraph, DirectedEdgeWeightedGraph
and context from other files:
# Path: pyalgs/algorithms/graphs/topological_sort.py
# class DepthFirstOrder(object):
#
# marked = None
# reversePostOrder = None
#
# def __init__(self, G):
# if isinstance(G, DirectedEdgeWeightedGraph):
# G = G.to_digraph()
#
# self.reversePostOrder = Stack.create()
# vertex_count = G.vertex_count()
# self.marked = [False] * vertex_count
#
# for v in range(vertex_count):
# if not self.marked[v]:
# self.dfs(G, v)
#
# def dfs(self, G, v):
# self.marked[v] = True
# for w in G.adj(v):
# if not self.marked[w]:
# self.dfs(G, w)
# self.reversePostOrder.push(v)
#
# def postOrder(self):
# return self.reversePostOrder.iterate()
#
# Path: pyalgs/data_structures/graphs/graph.py
# class EdgeWeightedGraph(object):
# adjList = None
# V = 0
#
# def __init__(self, vertex_count):
# self.V = vertex_count
# self.adjList = [None] * vertex_count
# for v in range(vertex_count):
# self.adjList[v] = Bag()
#
# def add_edge(self, edge):
# v = edge.either()
# w = edge.other(v)
# self.adjList[v].add(edge)
# self.adjList[w].add(edge)
#
# def adj(self, v):
# return self.adjList[v].iterate()
#
# def vertex_count(self):
# return self.V
#
# def edges(self):
# for v in range(self.V):
# for e in self.adj(v):
# if e.either() == v:
# yield e
#
# def to_graph(self):
# g = Graph()
#
# for e in self.edges():
# g.add_edge(e.start(), e.end())
# return g
#
# def to_edge_weighted_digraph(self):
# g = DirectedEdgeWeightedGraph(self.V)
#
# for e in self.edges():
# g.add_edge(e)
# g.add_edge(e.reverse())
# return g
#
# class Digraph(object):
# V = 0
# adjList = None
#
# def __init__(self, V):
# self.V = V
# self.adjList = [None] * V
# for v in range(V):
# self.adjList[v] = Bag()
#
# def vertex_count(self):
# return self.V
#
# def adj(self, v):
# return self.adjList[v].iterate()
#
# def add_edge(self, v, w):
# self.adjList[v].add(w)
#
# def reverse(self):
# g = Digraph(self.V)
# for v in range(self.V):
# for w in self.adjList[v].iterate():
# g.add_edge(w, v)
#
# return g
#
# class DirectedEdgeWeightedGraph(object):
# adjList = None
# V = 0
#
# def __init__(self, vertex_count):
# self.V = vertex_count
# self.adjList = [None] * vertex_count
# for v in range(vertex_count):
# self.adjList[v] = Bag()
#
# def add_edge(self, edge):
# v = edge.start()
# self.adjList[v].add(edge)
#
# def adj(self, v):
# return self.adjList[v].iterate()
#
# def vertex_count(self):
# return self.V
#
# def edges(self):
# for v in range(self.V):
# for e in self.adj(v):
# yield e
#
# def to_graph(self):
# g = Graph()
#
# for e in self.edges():
# g.add_edge(e.start(), e.end())
# return g
#
# def to_digraph(self):
# g = Digraph(self.V)
#
# for e in self.edges():
# g.add_edge(e.start(), e.end())
#
# return g
, which may include functions, classes, or code. Output only the next line. | if isinstance(G, DirectedEdgeWeightedGraph): |
Predict the next line after this snippet: <|code_start|>
class DepthFirstOrder(object):
marked = None
reversePostOrder = None
def __init__(self, G):
if isinstance(G, DirectedEdgeWeightedGraph):
G = G.to_digraph()
<|code_end|>
using the current file's imports:
from pyalgs.data_structures.commons.stack import Stack
from pyalgs.data_structures.graphs.graph import EdgeWeightedGraph, DirectedEdgeWeightedGraph
and any relevant context from other files:
# Path: pyalgs/data_structures/commons/stack.py
# class Stack(object):
# """ Stack interface which provides the API for stack data structure
# """
#
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def push(self, item):
# pass
#
# @abstractmethod
# def pop(self):
# pass
#
# @abstractmethod
# def is_empty(self):
# pass
#
# @abstractmethod
# def size(self):
# pass
#
# @abstractmethod
# def iterate(self):
# pass
#
# @staticmethod
# def create():
# return LinkedListStack()
#
# Path: pyalgs/data_structures/graphs/graph.py
# class EdgeWeightedGraph(object):
# adjList = None
# V = 0
#
# def __init__(self, vertex_count):
# self.V = vertex_count
# self.adjList = [None] * vertex_count
# for v in range(vertex_count):
# self.adjList[v] = Bag()
#
# def add_edge(self, edge):
# v = edge.either()
# w = edge.other(v)
# self.adjList[v].add(edge)
# self.adjList[w].add(edge)
#
# def adj(self, v):
# return self.adjList[v].iterate()
#
# def vertex_count(self):
# return self.V
#
# def edges(self):
# for v in range(self.V):
# for e in self.adj(v):
# if e.either() == v:
# yield e
#
# def to_graph(self):
# g = Graph()
#
# for e in self.edges():
# g.add_edge(e.start(), e.end())
# return g
#
# def to_edge_weighted_digraph(self):
# g = DirectedEdgeWeightedGraph(self.V)
#
# for e in self.edges():
# g.add_edge(e)
# g.add_edge(e.reverse())
# return g
#
# class DirectedEdgeWeightedGraph(object):
# adjList = None
# V = 0
#
# def __init__(self, vertex_count):
# self.V = vertex_count
# self.adjList = [None] * vertex_count
# for v in range(vertex_count):
# self.adjList[v] = Bag()
#
# def add_edge(self, edge):
# v = edge.start()
# self.adjList[v].add(edge)
#
# def adj(self, v):
# return self.adjList[v].iterate()
#
# def vertex_count(self):
# return self.V
#
# def edges(self):
# for v in range(self.V):
# for e in self.adj(v):
# yield e
#
# def to_graph(self):
# g = Graph()
#
# for e in self.edges():
# g.add_edge(e.start(), e.end())
# return g
#
# def to_digraph(self):
# g = Digraph(self.V)
#
# for e in self.edges():
# g.add_edge(e.start(), e.end())
#
# return g
. Output only the next line. | self.reversePostOrder = Stack.create() |
Given snippet: <|code_start|>
class DepthFirstOrder(object):
marked = None
reversePostOrder = None
def __init__(self, G):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pyalgs.data_structures.commons.stack import Stack
from pyalgs.data_structures.graphs.graph import EdgeWeightedGraph, DirectedEdgeWeightedGraph
and context:
# Path: pyalgs/data_structures/commons/stack.py
# class Stack(object):
# """ Stack interface which provides the API for stack data structure
# """
#
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def push(self, item):
# pass
#
# @abstractmethod
# def pop(self):
# pass
#
# @abstractmethod
# def is_empty(self):
# pass
#
# @abstractmethod
# def size(self):
# pass
#
# @abstractmethod
# def iterate(self):
# pass
#
# @staticmethod
# def create():
# return LinkedListStack()
#
# Path: pyalgs/data_structures/graphs/graph.py
# class EdgeWeightedGraph(object):
# adjList = None
# V = 0
#
# def __init__(self, vertex_count):
# self.V = vertex_count
# self.adjList = [None] * vertex_count
# for v in range(vertex_count):
# self.adjList[v] = Bag()
#
# def add_edge(self, edge):
# v = edge.either()
# w = edge.other(v)
# self.adjList[v].add(edge)
# self.adjList[w].add(edge)
#
# def adj(self, v):
# return self.adjList[v].iterate()
#
# def vertex_count(self):
# return self.V
#
# def edges(self):
# for v in range(self.V):
# for e in self.adj(v):
# if e.either() == v:
# yield e
#
# def to_graph(self):
# g = Graph()
#
# for e in self.edges():
# g.add_edge(e.start(), e.end())
# return g
#
# def to_edge_weighted_digraph(self):
# g = DirectedEdgeWeightedGraph(self.V)
#
# for e in self.edges():
# g.add_edge(e)
# g.add_edge(e.reverse())
# return g
#
# class DirectedEdgeWeightedGraph(object):
# adjList = None
# V = 0
#
# def __init__(self, vertex_count):
# self.V = vertex_count
# self.adjList = [None] * vertex_count
# for v in range(vertex_count):
# self.adjList[v] = Bag()
#
# def add_edge(self, edge):
# v = edge.start()
# self.adjList[v].add(edge)
#
# def adj(self, v):
# return self.adjList[v].iterate()
#
# def vertex_count(self):
# return self.V
#
# def edges(self):
# for v in range(self.V):
# for e in self.adj(v):
# yield e
#
# def to_graph(self):
# g = Graph()
#
# for e in self.edges():
# g.add_edge(e.start(), e.end())
# return g
#
# def to_digraph(self):
# g = Digraph(self.V)
#
# for e in self.edges():
# g.add_edge(e.start(), e.end())
#
# return g
which might include code, classes, or functions. Output only the next line. | if isinstance(G, DirectedEdgeWeightedGraph): |
Predict the next line for this snippet: <|code_start|>
class KnuthShuffleUnitTest(unittest.TestCase):
def test_shuffle(self):
a = [1, 2, 13, 22, 123]
<|code_end|>
with the help of current file imports:
import unittest
from pyalgs.algorithms.commons.shuffling import KnuthShuffle
and context from other files:
# Path: pyalgs/algorithms/commons/shuffling.py
# class KnuthShuffle(object):
# @staticmethod
# def shuffle(a):
# for i in range(1, len(a)):
# r = randint(0, i)
# exchange(a, r, i)
, which may contain function names, class names, or code. Output only the next line. | KnuthShuffle.shuffle(a) |
Next line prediction: <|code_start|>
def __init__(self, v=None, w=None, weight=None):
if weight is None:
weight = 0
self.v = v
self.w = w
self.weight = weight
def start(self):
return self.v
def end(self):
return self.w
def reverse(self):
return Edge(self.w, self.v, self.weight)
def either(self):
return self.v
def other(self, v):
if self.v == v:
return self.w
elif self.w == v:
return self.v
else:
raise ValueError('mismatched vertex detected')
# use for python 2 comparison
def __cmp__(self, other):
<|code_end|>
. Use current file imports:
(from pyalgs.algorithms.commons import util
from pyalgs.data_structures.commons.bag import Bag)
and context including class names, function names, or small code snippets from other files:
# Path: pyalgs/algorithms/commons/util.py
# def less(a, b):
# def greater(a, b):
# def cmp(a, b):
# def exchange(a, i, j):
# def is_sorted(a):
#
# Path: pyalgs/data_structures/commons/bag.py
# class Bag(object):
# def __init__(self):
# self.stack = Stack.create()
#
# def add(self, item):
# self.stack.push(item)
#
# def size(self):
# return self.stack.size()
#
# def is_empty(self):
# return self.stack.is_empty()
#
# def iterate(self):
# return self.stack.iterate()
#
# @staticmethod
# def create():
# return Bag()
. Output only the next line. | return util.cmp(self.weight, other.weight) |
Given snippet: <|code_start|>
class Graph(object):
V = 0
adjList = None
def __init__(self, V):
self.V = V
self.adjList = [None] * V
for v in range(V):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pyalgs.algorithms.commons import util
from pyalgs.data_structures.commons.bag import Bag
and context:
# Path: pyalgs/algorithms/commons/util.py
# def less(a, b):
# def greater(a, b):
# def cmp(a, b):
# def exchange(a, i, j):
# def is_sorted(a):
#
# Path: pyalgs/data_structures/commons/bag.py
# class Bag(object):
# def __init__(self):
# self.stack = Stack.create()
#
# def add(self, item):
# self.stack.push(item)
#
# def size(self):
# return self.stack.size()
#
# def is_empty(self):
# return self.stack.is_empty()
#
# def iterate(self):
# return self.stack.iterate()
#
# @staticmethod
# def create():
# return Bag()
which might include code, classes, or functions. Output only the next line. | self.adjList[v] = Bag() |
Given the following code snippet before the placeholder: <|code_start|>
class ConnectedComponentsUnitTest(unittest.TestCase):
def test_cc(self):
G = create_graph_4_connected_components()
<|code_end|>
, predict the next line using imports from the current file:
import unittest
from random import randint
from pyalgs.algorithms.graphs.connectivity import ConnectedComponents, StronglyConnectedComponents
from tests.algorithms.graphs.util import create_graph_4_connected_components, \
create_digraph_4_strongly_connected_components
and context including class names, function names, and sometimes code from other files:
# Path: pyalgs/algorithms/graphs/connectivity.py
# class ConnectedComponents(object):
# marked = None
# _id = None
# _count = 0
#
# def __init__(self, G):
# if isinstance(G, EdgeWeightedGraph):
# G = G.to_graph()
#
# vertex_count = G.vertex_count()
# self.marked = [False] * vertex_count
# self._id = [-1] * vertex_count
# for v in range(vertex_count):
# if not self.marked[v]:
# self.dfs(G, v)
# self._count += 1
#
# def dfs(self, G, v):
# self.marked[v] = True
# self._id[v] = self._count
# for w in G.adj(v):
# if not self.marked[w]:
# self.dfs(G, w)
#
# def connected(self, v, w):
# return self._id[v] == self._id[w]
#
# def count(self):
# return self._count
#
# def id(self, v):
# return self._id[v]
#
# class StronglyConnectedComponents(object):
# marked = None
# _id = None
# _count = 0
#
# def __init__(self, G):
# if isinstance(G, EdgeWeightedGraph):
# raise ValueError('Graph must be directed graph for strongly connected components')
# if isinstance(G, DirectedEdgeWeightedGraph):
# G = G.to_digrah()
# if not isinstance(G, Digraph):
# raise ValueError('Graph must be directed graph for strongly connected components')
#
# vertex_count = G.vertex_count()
# self.marked = [False] * vertex_count
# self._id = [-1] * vertex_count
#
# dfo = DepthFirstOrder(G.reverse())
# orders = dfo.postOrder()
#
# for v in orders:
# if not self.marked[v]:
# self.dfs(G, v)
# self._count += 1
#
# def dfs(self, G, v):
# self.marked[v] = True
# self._id[v] = self._count
# for w in G.adj(v):
# if not self.marked[w]:
# self.dfs(G, w)
#
# def connected(self, v, w):
# return self._id[v] == self._id[w]
#
# def count(self):
# return self._count
#
# def id(self, v):
# return self._id[v]
#
# Path: tests/algorithms/graphs/util.py
# def create_graph_4_connected_components():
# g = Graph(13)
# g.add_edge(0, 5)
# g.add_edge(4, 3)
# g.add_edge(0, 1)
# g.add_edge(9, 12)
# g.add_edge(6, 4)
# g.add_edge(5, 4)
# g.add_edge(0, 2)
# g.add_edge(11, 12)
# g.add_edge(9, 10)
# g.add_edge(0, 6)
# g.add_edge(7, 8)
# g.add_edge(9, 11)
# g.add_edge(5, 3)
# return g
#
# def create_digraph_4_strongly_connected_components():
# graph = Digraph(13)
# graph.add_edge(4, 2)
# graph.add_edge(2, 3)
# graph.add_edge(3, 2)
# graph.add_edge(6, 0)
# graph.add_edge(0, 1)
# graph.add_edge(2, 0)
# graph.add_edge(11, 12)
# graph.add_edge(12, 9)
# graph.add_edge(9, 10)
# graph.add_edge(9, 11)
# graph.add_edge(8, 9)
# graph.add_edge(10, 12)
# graph.add_edge(11, 4)
# graph.add_edge(4, 3)
# graph.add_edge(3, 5)
# graph.add_edge(7, 8)
# graph.add_edge(8, 7)
# graph.add_edge(5, 4)
# graph.add_edge(0, 5)
# graph.add_edge(6, 4)
# graph.add_edge(6, 9)
# graph.add_edge(7, 6)
#
# return graph
. Output only the next line. | cc = ConnectedComponents(G) |
Using the snippet: <|code_start|>
class ConnectedComponentsUnitTest(unittest.TestCase):
def test_cc(self):
G = create_graph_4_connected_components()
cc = ConnectedComponents(G)
print('connected component count: ' + str(cc.count()))
self.assertEqual(3, cc.count())
for v in range(G.vertex_count()):
print('id[' + str(v) + ']: ' + str(cc.id(v)))
for v in range(G.vertex_count()):
r = randint(0, G.vertex_count() - 1)
if cc.connected(v, r):
print(str(v) + ' is connected to ' + str(r))
class StronglyConnectedComponentsUnitTest(unittest.TestCase):
def test_cc(self):
G = create_digraph_4_strongly_connected_components()
<|code_end|>
, determine the next line of code. You have imports:
import unittest
from random import randint
from pyalgs.algorithms.graphs.connectivity import ConnectedComponents, StronglyConnectedComponents
from tests.algorithms.graphs.util import create_graph_4_connected_components, \
create_digraph_4_strongly_connected_components
and context (class names, function names, or code) available:
# Path: pyalgs/algorithms/graphs/connectivity.py
# class ConnectedComponents(object):
# marked = None
# _id = None
# _count = 0
#
# def __init__(self, G):
# if isinstance(G, EdgeWeightedGraph):
# G = G.to_graph()
#
# vertex_count = G.vertex_count()
# self.marked = [False] * vertex_count
# self._id = [-1] * vertex_count
# for v in range(vertex_count):
# if not self.marked[v]:
# self.dfs(G, v)
# self._count += 1
#
# def dfs(self, G, v):
# self.marked[v] = True
# self._id[v] = self._count
# for w in G.adj(v):
# if not self.marked[w]:
# self.dfs(G, w)
#
# def connected(self, v, w):
# return self._id[v] == self._id[w]
#
# def count(self):
# return self._count
#
# def id(self, v):
# return self._id[v]
#
# class StronglyConnectedComponents(object):
# marked = None
# _id = None
# _count = 0
#
# def __init__(self, G):
# if isinstance(G, EdgeWeightedGraph):
# raise ValueError('Graph must be directed graph for strongly connected components')
# if isinstance(G, DirectedEdgeWeightedGraph):
# G = G.to_digrah()
# if not isinstance(G, Digraph):
# raise ValueError('Graph must be directed graph for strongly connected components')
#
# vertex_count = G.vertex_count()
# self.marked = [False] * vertex_count
# self._id = [-1] * vertex_count
#
# dfo = DepthFirstOrder(G.reverse())
# orders = dfo.postOrder()
#
# for v in orders:
# if not self.marked[v]:
# self.dfs(G, v)
# self._count += 1
#
# def dfs(self, G, v):
# self.marked[v] = True
# self._id[v] = self._count
# for w in G.adj(v):
# if not self.marked[w]:
# self.dfs(G, w)
#
# def connected(self, v, w):
# return self._id[v] == self._id[w]
#
# def count(self):
# return self._count
#
# def id(self, v):
# return self._id[v]
#
# Path: tests/algorithms/graphs/util.py
# def create_graph_4_connected_components():
# g = Graph(13)
# g.add_edge(0, 5)
# g.add_edge(4, 3)
# g.add_edge(0, 1)
# g.add_edge(9, 12)
# g.add_edge(6, 4)
# g.add_edge(5, 4)
# g.add_edge(0, 2)
# g.add_edge(11, 12)
# g.add_edge(9, 10)
# g.add_edge(0, 6)
# g.add_edge(7, 8)
# g.add_edge(9, 11)
# g.add_edge(5, 3)
# return g
#
# def create_digraph_4_strongly_connected_components():
# graph = Digraph(13)
# graph.add_edge(4, 2)
# graph.add_edge(2, 3)
# graph.add_edge(3, 2)
# graph.add_edge(6, 0)
# graph.add_edge(0, 1)
# graph.add_edge(2, 0)
# graph.add_edge(11, 12)
# graph.add_edge(12, 9)
# graph.add_edge(9, 10)
# graph.add_edge(9, 11)
# graph.add_edge(8, 9)
# graph.add_edge(10, 12)
# graph.add_edge(11, 4)
# graph.add_edge(4, 3)
# graph.add_edge(3, 5)
# graph.add_edge(7, 8)
# graph.add_edge(8, 7)
# graph.add_edge(5, 4)
# graph.add_edge(0, 5)
# graph.add_edge(6, 4)
# graph.add_edge(6, 9)
# graph.add_edge(7, 6)
#
# return graph
. Output only the next line. | cc = StronglyConnectedComponents(G) |
Predict the next line for this snippet: <|code_start|>
class ConnectedComponentsUnitTest(unittest.TestCase):
def test_cc(self):
G = create_graph_4_connected_components()
cc = ConnectedComponents(G)
print('connected component count: ' + str(cc.count()))
self.assertEqual(3, cc.count())
for v in range(G.vertex_count()):
print('id[' + str(v) + ']: ' + str(cc.id(v)))
for v in range(G.vertex_count()):
r = randint(0, G.vertex_count() - 1)
if cc.connected(v, r):
print(str(v) + ' is connected to ' + str(r))
class StronglyConnectedComponentsUnitTest(unittest.TestCase):
def test_cc(self):
<|code_end|>
with the help of current file imports:
import unittest
from random import randint
from pyalgs.algorithms.graphs.connectivity import ConnectedComponents, StronglyConnectedComponents
from tests.algorithms.graphs.util import create_graph_4_connected_components, \
create_digraph_4_strongly_connected_components
and context from other files:
# Path: pyalgs/algorithms/graphs/connectivity.py
# class ConnectedComponents(object):
# marked = None
# _id = None
# _count = 0
#
# def __init__(self, G):
# if isinstance(G, EdgeWeightedGraph):
# G = G.to_graph()
#
# vertex_count = G.vertex_count()
# self.marked = [False] * vertex_count
# self._id = [-1] * vertex_count
# for v in range(vertex_count):
# if not self.marked[v]:
# self.dfs(G, v)
# self._count += 1
#
# def dfs(self, G, v):
# self.marked[v] = True
# self._id[v] = self._count
# for w in G.adj(v):
# if not self.marked[w]:
# self.dfs(G, w)
#
# def connected(self, v, w):
# return self._id[v] == self._id[w]
#
# def count(self):
# return self._count
#
# def id(self, v):
# return self._id[v]
#
# class StronglyConnectedComponents(object):
# marked = None
# _id = None
# _count = 0
#
# def __init__(self, G):
# if isinstance(G, EdgeWeightedGraph):
# raise ValueError('Graph must be directed graph for strongly connected components')
# if isinstance(G, DirectedEdgeWeightedGraph):
# G = G.to_digrah()
# if not isinstance(G, Digraph):
# raise ValueError('Graph must be directed graph for strongly connected components')
#
# vertex_count = G.vertex_count()
# self.marked = [False] * vertex_count
# self._id = [-1] * vertex_count
#
# dfo = DepthFirstOrder(G.reverse())
# orders = dfo.postOrder()
#
# for v in orders:
# if not self.marked[v]:
# self.dfs(G, v)
# self._count += 1
#
# def dfs(self, G, v):
# self.marked[v] = True
# self._id[v] = self._count
# for w in G.adj(v):
# if not self.marked[w]:
# self.dfs(G, w)
#
# def connected(self, v, w):
# return self._id[v] == self._id[w]
#
# def count(self):
# return self._count
#
# def id(self, v):
# return self._id[v]
#
# Path: tests/algorithms/graphs/util.py
# def create_graph_4_connected_components():
# g = Graph(13)
# g.add_edge(0, 5)
# g.add_edge(4, 3)
# g.add_edge(0, 1)
# g.add_edge(9, 12)
# g.add_edge(6, 4)
# g.add_edge(5, 4)
# g.add_edge(0, 2)
# g.add_edge(11, 12)
# g.add_edge(9, 10)
# g.add_edge(0, 6)
# g.add_edge(7, 8)
# g.add_edge(9, 11)
# g.add_edge(5, 3)
# return g
#
# def create_digraph_4_strongly_connected_components():
# graph = Digraph(13)
# graph.add_edge(4, 2)
# graph.add_edge(2, 3)
# graph.add_edge(3, 2)
# graph.add_edge(6, 0)
# graph.add_edge(0, 1)
# graph.add_edge(2, 0)
# graph.add_edge(11, 12)
# graph.add_edge(12, 9)
# graph.add_edge(9, 10)
# graph.add_edge(9, 11)
# graph.add_edge(8, 9)
# graph.add_edge(10, 12)
# graph.add_edge(11, 4)
# graph.add_edge(4, 3)
# graph.add_edge(3, 5)
# graph.add_edge(7, 8)
# graph.add_edge(8, 7)
# graph.add_edge(5, 4)
# graph.add_edge(0, 5)
# graph.add_edge(6, 4)
# graph.add_edge(6, 9)
# graph.add_edge(7, 6)
#
# return graph
, which may contain function names, class names, or code. Output only the next line. | G = create_digraph_4_strongly_connected_components() |
Here is a snippet: <|code_start|>
class DepthFirstOrderUnitTest(unittest.TestCase):
def test_topological_sort(self):
G = create_dag()
<|code_end|>
. Write the next line using the current file imports:
import unittest
from pyalgs.algorithms.graphs.topological_sort import DepthFirstOrder
from tests.algorithms.graphs.util import create_dag
and context from other files:
# Path: pyalgs/algorithms/graphs/topological_sort.py
# class DepthFirstOrder(object):
#
# marked = None
# reversePostOrder = None
#
# def __init__(self, G):
# if isinstance(G, DirectedEdgeWeightedGraph):
# G = G.to_digraph()
#
# self.reversePostOrder = Stack.create()
# vertex_count = G.vertex_count()
# self.marked = [False] * vertex_count
#
# for v in range(vertex_count):
# if not self.marked[v]:
# self.dfs(G, v)
#
# def dfs(self, G, v):
# self.marked[v] = True
# for w in G.adj(v):
# if not self.marked[w]:
# self.dfs(G, w)
# self.reversePostOrder.push(v)
#
# def postOrder(self):
# return self.reversePostOrder.iterate()
#
# Path: tests/algorithms/graphs/util.py
# def create_dag():
# dag = Digraph(7)
#
# dag.add_edge(0, 5)
# dag.add_edge(0, 2)
# dag.add_edge(0, 1)
# dag.add_edge(3, 6)
# dag.add_edge(3, 5)
# dag.add_edge(3, 4)
# dag.add_edge(5, 4)
# dag.add_edge(6, 4)
# dag.add_edge(6, 0)
# dag.add_edge(3, 2)
# dag.add_edge(1, 4)
#
# return dag
, which may include functions, classes, or code. Output only the next line. | topological_sort = DepthFirstOrder(G) |
Given snippet: <|code_start|> marked = None
s = None
t = None
value = 0.0
network = None
def __init__(self, network, s, t):
self.s = s
self.t = t
self.network = network
self.value = 0.0
while self.has_augmenting_path():
x = self.t
bottle = float('inf')
while x != self.s:
bottle = min(bottle, self.edgeTo[x].residual_capacity_to(x))
x = self.edgeTo[x].other(x)
x = self.t
while x != self.s:
self.edgeTo[x].add_residual_flow_to(x, bottle)
x = self.edgeTo[x].other(x)
self.value += bottle
def has_augmenting_path(self):
vertex_count = self.network.vertex_count()
self.edgeTo = [None] * vertex_count
self.marked = [False] * vertex_count
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pyalgs.data_structures.commons.queue import Queue
and context:
# Path: pyalgs/data_structures/commons/queue.py
# class Queue(object):
# """ Queue interface
#
# """
#
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def enqueue(self, item):
# pass
#
# @abstractmethod
# def dequeue(self):
# pass
#
# @abstractmethod
# def is_empty(self):
# pass
#
# @abstractmethod
# def size(self):
# pass
#
# @staticmethod
# def create():
# return LinkedListQueue()
#
# @abstractmethod
# def iterate(self):
# pass
which might include code, classes, or functions. Output only the next line. | queue = Queue.create() |
Given the code snippet: <|code_start|> """
Get all events by trigger
:param trigger: Trigger trigger
:param limit: int limit
:return: list of dicts
:raises: ValueError
:raises: ResponseStructureError
"""
if not trigger.id:
raise ValueError('Trigger id is None')
params = {
'p': 0,
'size': limit
}
result = self._client.get(self._full_path(trigger.id), params=params)
if 'list' not in result:
raise ResponseStructureError("list doesn't exist in response", result)
return result['list']
def delete_all(self):
"""
Remove all events
:return: True on success, False otherwise
"""
try:
result = self._client.delete(self._full_path("all"))
return False
<|code_end|>
, generate the next line using the imports in this file:
from ..client import InvalidJSONError
from ..client import ResponseStructureError
and context (functions, classes, or occasionally code) from other files:
# Path: moira_client/client.py
# class InvalidJSONError(Exception):
# def __init__(self, content):
# """
#
# :param content: bytes response content
# """
# self.content = content
#
# Path: moira_client/client.py
# class ResponseStructureError(Exception):
# def __init__(self, msg, content):
# """
#
# :param msg: str error message
# :param content: dict response content
# """
# self.msg = msg
# self.content = content
. Output only the next line. | except InvalidJSONError as e: |
Given the following code snippet before the placeholder: <|code_start|>
MAX_FETCH_LIMIT = 1000
class EventManager:
def __init__(self, client):
self._client = client
def fetch_by_trigger(self, trigger, limit=MAX_FETCH_LIMIT):
"""
Get all events by trigger
:param trigger: Trigger trigger
:param limit: int limit
:return: list of dicts
:raises: ValueError
:raises: ResponseStructureError
"""
if not trigger.id:
raise ValueError('Trigger id is None')
params = {
'p': 0,
'size': limit
}
result = self._client.get(self._full_path(trigger.id), params=params)
if 'list' not in result:
<|code_end|>
, predict the next line using imports from the current file:
from ..client import InvalidJSONError
from ..client import ResponseStructureError
and context including class names, function names, and sometimes code from other files:
# Path: moira_client/client.py
# class InvalidJSONError(Exception):
# def __init__(self, content):
# """
#
# :param content: bytes response content
# """
# self.content = content
#
# Path: moira_client/client.py
# class ResponseStructureError(Exception):
# def __init__(self, msg, content):
# """
#
# :param msg: str error message
# :param content: dict response content
# """
# self.msg = msg
# self.content = content
. Output only the next line. | raise ResponseStructureError("list doesn't exist in response", result) |
Predict the next line after this snippet: <|code_start|> :param ignore_recoverings: bool ignore recoverings
:param kwargs: additional parameters
:param plotting: dict plotting settings
:param any_tags: bool any tags
:return: Subscription
"""
return Subscription(
self._client,
tags,
contacts,
enabled,
throttling,
sched,
ignore_warnings,
ignore_recoverings,
plotting,
any_tags,
**kwargs
)
def delete(self, subscription_id):
"""
Remove subscription by given id
:return: True on success, False otherwise
"""
try:
self._client.delete(self._full_path(subscription_id))
return False
<|code_end|>
using the current file's imports:
from ..client import InvalidJSONError
from ..client import ResponseStructureError
from .base import Base
from .common import MINUTES_IN_HOUR, get_schedule
and any relevant context from other files:
# Path: moira_client/client.py
# class InvalidJSONError(Exception):
# def __init__(self, content):
# """
#
# :param content: bytes response content
# """
# self.content = content
#
# Path: moira_client/client.py
# class ResponseStructureError(Exception):
# def __init__(self, msg, content):
# """
#
# :param msg: str error message
# :param content: dict response content
# """
# self.msg = msg
# self.content = content
#
# Path: moira_client/models/base.py
# class Base:
# @property
# def id(self):
# return self._id
#
# def __repr__(self):
# return '({} {})'.format(self.__class__.__name__, self.id)
#
# def __unicode__(self):
# return u'({} {})'.format(self.__class__.__name__, self.id)
#
# def __eq__(self, other):
# return self.id == other.id
#
# def __ne__(self, other):
# return self.id != other.id
#
# Path: moira_client/models/common.py
# MINUTES_IN_HOUR = 60
#
# def get_schedule(start_hour, start_minute, end_hour, end_minute, disabled_days):
# days = []
# for day in DAYS_OF_WEEK:
# day_info = {
# 'enabled': True if day not in disabled_days else False,
# 'name': day
# }
# days.append(day_info)
# return {
# 'days': days,
# 'startOffset': start_hour * MINUTES_IN_HOUR + start_minute,
# 'endOffset': end_hour * MINUTES_IN_HOUR + end_minute,
# }
. Output only the next line. | except InvalidJSONError as e: |
Based on the snippet: <|code_start|> self.ignore_recoverings = ignore_recoverings
if not plotting:
plotting = {'enabled': False, 'theme': 'light'}
self.plotting = plotting
def _send_request(self, subscription_id=None):
data = {
'contacts': self.contacts,
'tags': self.tags,
'enabled': self.enabled,
'any_tags': self.any_tags,
'throttling': self.throttling,
'sched': self.sched,
'ignore_warnings': self.ignore_warnings,
'ignore_recoverings': self.ignore_recoverings,
'plotting': self.plotting
}
if subscription_id:
data['id'] = subscription_id
data['sched'] = get_schedule(self._start_hour, self._start_minute, self._end_hour, self._end_minute,
self.disabled_days)
if subscription_id:
result = self._client.put('subscription/{id}'.format(id=subscription_id), json=data)
else:
result = self._client.put('subscription', json=data)
if 'id' not in result:
<|code_end|>
, predict the immediate next line with the help of imports:
from ..client import InvalidJSONError
from ..client import ResponseStructureError
from .base import Base
from .common import MINUTES_IN_HOUR, get_schedule
and context (classes, functions, sometimes code) from other files:
# Path: moira_client/client.py
# class InvalidJSONError(Exception):
# def __init__(self, content):
# """
#
# :param content: bytes response content
# """
# self.content = content
#
# Path: moira_client/client.py
# class ResponseStructureError(Exception):
# def __init__(self, msg, content):
# """
#
# :param msg: str error message
# :param content: dict response content
# """
# self.msg = msg
# self.content = content
#
# Path: moira_client/models/base.py
# class Base:
# @property
# def id(self):
# return self._id
#
# def __repr__(self):
# return '({} {})'.format(self.__class__.__name__, self.id)
#
# def __unicode__(self):
# return u'({} {})'.format(self.__class__.__name__, self.id)
#
# def __eq__(self, other):
# return self.id == other.id
#
# def __ne__(self, other):
# return self.id != other.id
#
# Path: moira_client/models/common.py
# MINUTES_IN_HOUR = 60
#
# def get_schedule(start_hour, start_minute, end_hour, end_minute, disabled_days):
# days = []
# for day in DAYS_OF_WEEK:
# day_info = {
# 'enabled': True if day not in disabled_days else False,
# 'name': day
# }
# days.append(day_info)
# return {
# 'days': days,
# 'startOffset': start_hour * MINUTES_IN_HOUR + start_minute,
# 'endOffset': end_hour * MINUTES_IN_HOUR + end_minute,
# }
. Output only the next line. | raise ResponseStructureError("id doesn't exist in response", result) |
Continue the code snippet: <|code_start|> :param ignore_warnings: bool ignore warnings
:param ignore_recoverings: bool ignore recoverings
:param plotting: dict plotting settings
:param any_tags: bool any tags
:param kwargs: additional parameters
"""
self._client = client
self._id = kwargs.get('id', None)
self.tags = tags if not any_tags else []
if not contacts:
contacts = []
self.contacts = contacts
self.enabled = enabled
self.any_tags = any_tags
self.throttling = throttling
default_sched = {
'startOffset': 0,
'endOffset': 1439,
'tzOffset': 0
}
if not sched:
sched = default_sched
self.disabled_days = set()
else:
if 'days' in sched and sched['days'] is not None:
self.disabled_days = {day['name'] for day in sched['days'] if not day['enabled']}
self.sched = sched
# compute time range
<|code_end|>
. Use current file imports:
from ..client import InvalidJSONError
from ..client import ResponseStructureError
from .base import Base
from .common import MINUTES_IN_HOUR, get_schedule
and context (classes, functions, or code) from other files:
# Path: moira_client/client.py
# class InvalidJSONError(Exception):
# def __init__(self, content):
# """
#
# :param content: bytes response content
# """
# self.content = content
#
# Path: moira_client/client.py
# class ResponseStructureError(Exception):
# def __init__(self, msg, content):
# """
#
# :param msg: str error message
# :param content: dict response content
# """
# self.msg = msg
# self.content = content
#
# Path: moira_client/models/base.py
# class Base:
# @property
# def id(self):
# return self._id
#
# def __repr__(self):
# return '({} {})'.format(self.__class__.__name__, self.id)
#
# def __unicode__(self):
# return u'({} {})'.format(self.__class__.__name__, self.id)
#
# def __eq__(self, other):
# return self.id == other.id
#
# def __ne__(self, other):
# return self.id != other.id
#
# Path: moira_client/models/common.py
# MINUTES_IN_HOUR = 60
#
# def get_schedule(start_hour, start_minute, end_hour, end_minute, disabled_days):
# days = []
# for day in DAYS_OF_WEEK:
# day_info = {
# 'enabled': True if day not in disabled_days else False,
# 'name': day
# }
# days.append(day_info)
# return {
# 'days': days,
# 'startOffset': start_hour * MINUTES_IN_HOUR + start_minute,
# 'endOffset': end_hour * MINUTES_IN_HOUR + end_minute,
# }
. Output only the next line. | self._start_hour = self.sched['startOffset'] // MINUTES_IN_HOUR |
Continue the code snippet: <|code_start|>
# compute time range
self._start_hour = self.sched['startOffset'] // MINUTES_IN_HOUR
self._start_minute = self.sched['startOffset'] - self._start_hour * MINUTES_IN_HOUR
self._end_hour = self.sched['endOffset'] // MINUTES_IN_HOUR
self._end_minute = self.sched['endOffset'] - self._end_hour * MINUTES_IN_HOUR
self.ignore_warnings = ignore_warnings
self.ignore_recoverings = ignore_recoverings
if not plotting:
plotting = {'enabled': False, 'theme': 'light'}
self.plotting = plotting
def _send_request(self, subscription_id=None):
data = {
'contacts': self.contacts,
'tags': self.tags,
'enabled': self.enabled,
'any_tags': self.any_tags,
'throttling': self.throttling,
'sched': self.sched,
'ignore_warnings': self.ignore_warnings,
'ignore_recoverings': self.ignore_recoverings,
'plotting': self.plotting
}
if subscription_id:
data['id'] = subscription_id
<|code_end|>
. Use current file imports:
from ..client import InvalidJSONError
from ..client import ResponseStructureError
from .base import Base
from .common import MINUTES_IN_HOUR, get_schedule
and context (classes, functions, or code) from other files:
# Path: moira_client/client.py
# class InvalidJSONError(Exception):
# def __init__(self, content):
# """
#
# :param content: bytes response content
# """
# self.content = content
#
# Path: moira_client/client.py
# class ResponseStructureError(Exception):
# def __init__(self, msg, content):
# """
#
# :param msg: str error message
# :param content: dict response content
# """
# self.msg = msg
# self.content = content
#
# Path: moira_client/models/base.py
# class Base:
# @property
# def id(self):
# return self._id
#
# def __repr__(self):
# return '({} {})'.format(self.__class__.__name__, self.id)
#
# def __unicode__(self):
# return u'({} {})'.format(self.__class__.__name__, self.id)
#
# def __eq__(self, other):
# return self.id == other.id
#
# def __ne__(self, other):
# return self.id != other.id
#
# Path: moira_client/models/common.py
# MINUTES_IN_HOUR = 60
#
# def get_schedule(start_hour, start_minute, end_hour, end_minute, disabled_days):
# days = []
# for day in DAYS_OF_WEEK:
# day_info = {
# 'enabled': True if day not in disabled_days else False,
# 'name': day
# }
# days.append(day_info)
# return {
# 'days': days,
# 'startOffset': start_hour * MINUTES_IN_HOUR + start_minute,
# 'endOffset': end_hour * MINUTES_IN_HOUR + end_minute,
# }
. Output only the next line. | data['sched'] = get_schedule(self._start_hour, self._start_minute, self._end_hour, self._end_minute, |
Based on the snippet: <|code_start|>
def fetch(self, start, end):
"""
Gets a paginated list of notifications
:return: list of dict
:param start
:param end
:raises: ResponseStructureError
"""
params = {
'start': start,
'end': end
}
result = self._client.get(self._full_path(), params=params)
if 'list' not in result:
raise ResponseStructureError("list doesn't exist in response", result)
return result['list']
def delete_all(self):
"""
Remove all notifications
:return: True on success, False otherwise
"""
try:
result = self._client.delete(self._full_path("all"))
return False
<|code_end|>
, predict the immediate next line with the help of imports:
from ..client import InvalidJSONError
from ..client import ResponseStructureError
and context (classes, functions, sometimes code) from other files:
# Path: moira_client/client.py
# class InvalidJSONError(Exception):
# def __init__(self, content):
# """
#
# :param content: bytes response content
# """
# self.content = content
#
# Path: moira_client/client.py
# class ResponseStructureError(Exception):
# def __init__(self, msg, content):
# """
#
# :param msg: str error message
# :param content: dict response content
# """
# self.msg = msg
# self.content = content
. Output only the next line. | except InvalidJSONError as e: |
Next line prediction: <|code_start|>class NotificationManager:
def __init__(self, client):
self._client = client
def fetch_all(self):
"""
Returns all notifications
:return: list of dict
:raises: ResponseStructureError
"""
result = self.fetch(start=0, end=-1)
return result
def fetch(self, start, end):
"""
Gets a paginated list of notifications
:return: list of dict
:param start
:param end
:raises: ResponseStructureError
"""
params = {
'start': start,
'end': end
}
result = self._client.get(self._full_path(), params=params)
if 'list' not in result:
<|code_end|>
. Use current file imports:
(from ..client import InvalidJSONError
from ..client import ResponseStructureError)
and context including class names, function names, or small code snippets from other files:
# Path: moira_client/client.py
# class InvalidJSONError(Exception):
# def __init__(self, content):
# """
#
# :param content: bytes response content
# """
# self.content = content
#
# Path: moira_client/client.py
# class ResponseStructureError(Exception):
# def __init__(self, msg, content):
# """
#
# :param msg: str error message
# :param content: dict response content
# """
# self.msg = msg
# self.content = content
. Output only the next line. | raise ResponseStructureError("list doesn't exist in response", result) |
Continue the code snippet: <|code_start|>try:
except ImportError:
class PatternTest(ModelTest):
def test_fetch_all(self):
<|code_end|>
. Use current file imports:
from unittest.mock import Mock
from unittest.mock import patch
from mock import Mock
from mock import patch
from moira_client.client import Client
from moira_client.client import InvalidJSONError
from moira_client.client import ResponseStructureError
from moira_client.models.pattern import PatternManager
from .test_model import ModelTest
and context (classes, functions, or code) from other files:
# Path: moira_client/client.py
# class Client:
# def __init__(self, api_url, auth_custom=None, auth_user=None, auth_pass=None, login=None):
# """
#
# :param api_url: str Moira API URL
# :param auth_custom: dict auth custom headers
# :param auth_user: str auth user
# :param auth_pass: str auth password
# :param login: str auth login
# """
# if not api_url.endswith('/'):
# self.api_url = api_url + '/'
# else:
# self.api_url = api_url
#
# if not login and auth_user:
# login = auth_user
#
# self.auth = None
# self.headers = {
# 'X-Webauth-User': login,
# 'Content-Type': 'application/json',
# 'User-Agent': 'Python Moira Client'
# }
#
# if auth_user and auth_pass:
# self.auth = HTTPBasicAuth(auth_user, auth_pass)
#
# if auth_custom:
# self.headers.update(auth_custom)
#
# def get(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.get(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def delete(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.delete(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def put(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.put(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def post(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.post(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def _path_join(self, *args):
# path = self.api_url
# for part in args:
# path += part
# return path
#
# Path: moira_client/client.py
# class InvalidJSONError(Exception):
# def __init__(self, content):
# """
#
# :param content: bytes response content
# """
# self.content = content
#
# Path: moira_client/client.py
# class ResponseStructureError(Exception):
# def __init__(self, msg, content):
# """
#
# :param msg: str error message
# :param content: dict response content
# """
# self.msg = msg
# self.content = content
#
# Path: moira_client/models/pattern.py
# class PatternManager:
# """
# A Graphite pattern is a single dot-separated metric name, possibly containing one or more wildcards.
# """
# def __init__(self, client):
# self._client = client
#
# def fetch_all(self):
# """
# Returns all existing patterns in all triggers
#
# :return: list of Pattern
#
# :raises: ResponseStructureError
# """
# result = self._client.get(self._full_path())
# if 'list' in result:
# patterns = []
# for pattern in result['list']:
# if 'triggers' in pattern:
# pattern['triggers'] = [Trigger(self._client, **trigger) for trigger in pattern['triggers']]
# patterns.append(Pattern(**pattern))
# return patterns
# else:
# raise ResponseStructureError("list doesn't exist in response", result)
#
# def delete(self, pattern):
# """
# Delete pattern
# Returns True even if pattern doesn't exist
#
# :param pattern: str pattern
# :return: True if deleted, False otherwise
#
# :raises: ResponseStructureError
# """
# try:
# self._client.delete(self._full_path(pattern))
# return False
# except InvalidJSONError:
# return True
#
# def _full_path(self, path=''):
# if path:
# return 'pattern/{}'.format(path)
# return 'pattern'
#
# Path: tests/models/test_model.py
# class ModelTest(unittest.TestCase):
# TEST_API_URL = 'http://test/url'
#
# @property
# def api_url(self):
# return self.TEST_API_URL
. Output only the next line. | client = Client(self.api_url) |
Given snippet: <|code_start|>try:
except ImportError:
class PatternTest(ModelTest):
def test_fetch_all(self):
client = Client(self.api_url)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from unittest.mock import Mock
from unittest.mock import patch
from mock import Mock
from mock import patch
from moira_client.client import Client
from moira_client.client import InvalidJSONError
from moira_client.client import ResponseStructureError
from moira_client.models.pattern import PatternManager
from .test_model import ModelTest
and context:
# Path: moira_client/client.py
# class Client:
# def __init__(self, api_url, auth_custom=None, auth_user=None, auth_pass=None, login=None):
# """
#
# :param api_url: str Moira API URL
# :param auth_custom: dict auth custom headers
# :param auth_user: str auth user
# :param auth_pass: str auth password
# :param login: str auth login
# """
# if not api_url.endswith('/'):
# self.api_url = api_url + '/'
# else:
# self.api_url = api_url
#
# if not login and auth_user:
# login = auth_user
#
# self.auth = None
# self.headers = {
# 'X-Webauth-User': login,
# 'Content-Type': 'application/json',
# 'User-Agent': 'Python Moira Client'
# }
#
# if auth_user and auth_pass:
# self.auth = HTTPBasicAuth(auth_user, auth_pass)
#
# if auth_custom:
# self.headers.update(auth_custom)
#
# def get(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.get(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def delete(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.delete(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def put(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.put(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def post(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.post(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def _path_join(self, *args):
# path = self.api_url
# for part in args:
# path += part
# return path
#
# Path: moira_client/client.py
# class InvalidJSONError(Exception):
# def __init__(self, content):
# """
#
# :param content: bytes response content
# """
# self.content = content
#
# Path: moira_client/client.py
# class ResponseStructureError(Exception):
# def __init__(self, msg, content):
# """
#
# :param msg: str error message
# :param content: dict response content
# """
# self.msg = msg
# self.content = content
#
# Path: moira_client/models/pattern.py
# class PatternManager:
# """
# A Graphite pattern is a single dot-separated metric name, possibly containing one or more wildcards.
# """
# def __init__(self, client):
# self._client = client
#
# def fetch_all(self):
# """
# Returns all existing patterns in all triggers
#
# :return: list of Pattern
#
# :raises: ResponseStructureError
# """
# result = self._client.get(self._full_path())
# if 'list' in result:
# patterns = []
# for pattern in result['list']:
# if 'triggers' in pattern:
# pattern['triggers'] = [Trigger(self._client, **trigger) for trigger in pattern['triggers']]
# patterns.append(Pattern(**pattern))
# return patterns
# else:
# raise ResponseStructureError("list doesn't exist in response", result)
#
# def delete(self, pattern):
# """
# Delete pattern
# Returns True even if pattern doesn't exist
#
# :param pattern: str pattern
# :return: True if deleted, False otherwise
#
# :raises: ResponseStructureError
# """
# try:
# self._client.delete(self._full_path(pattern))
# return False
# except InvalidJSONError:
# return True
#
# def _full_path(self, path=''):
# if path:
# return 'pattern/{}'.format(path)
# return 'pattern'
#
# Path: tests/models/test_model.py
# class ModelTest(unittest.TestCase):
# TEST_API_URL = 'http://test/url'
#
# @property
# def api_url(self):
# return self.TEST_API_URL
which might include code, classes, or functions. Output only the next line. | pattern_manager = PatternManager(client) |
Predict the next line for this snippet: <|code_start|> data = {
'name': self.name,
'tags': self.tags,
'targets': self.targets,
'warn_value': self.warn_value,
'error_value': self.error_value,
'desc': self.desc,
'ttl': self.ttl,
'ttl_state': self.ttl_state,
'sched': self.sched,
'expression': self.expression,
'is_remote': self.is_remote,
'trigger_type': self.trigger_type,
'mute_new_metrics': self.mute_new_metrics,
'alone_metrics': self.alone_metrics,
}
if trigger_id:
data['id'] = trigger_id
api_response = TriggerManager(
self._client).fetch_by_id(trigger_id)
data['sched'] = get_schedule(self._start_hour, self._start_minute, self._end_hour, self._end_minute,
self.disabled_days)
if trigger_id and api_response:
res = self._client.put('trigger/{id}'.format(id=trigger_id), json=data)
else:
res = self._client.put('trigger', json=data)
if 'id' not in res:
<|code_end|>
with the help of current file imports:
from ..client import ResponseStructureError
from ..client import InvalidJSONError
from .base import Base
from .common import MINUTES_IN_HOUR, get_schedule
and context from other files:
# Path: moira_client/client.py
# class ResponseStructureError(Exception):
# def __init__(self, msg, content):
# """
#
# :param msg: str error message
# :param content: dict response content
# """
# self.msg = msg
# self.content = content
#
# Path: moira_client/client.py
# class InvalidJSONError(Exception):
# def __init__(self, content):
# """
#
# :param content: bytes response content
# """
# self.content = content
#
# Path: moira_client/models/base.py
# class Base:
# @property
# def id(self):
# return self._id
#
# def __repr__(self):
# return '({} {})'.format(self.__class__.__name__, self.id)
#
# def __unicode__(self):
# return u'({} {})'.format(self.__class__.__name__, self.id)
#
# def __eq__(self, other):
# return self.id == other.id
#
# def __ne__(self, other):
# return self.id != other.id
#
# Path: moira_client/models/common.py
# MINUTES_IN_HOUR = 60
#
# def get_schedule(start_hour, start_minute, end_hour, end_minute, disabled_days):
# days = []
# for day in DAYS_OF_WEEK:
# day_info = {
# 'enabled': True if day not in disabled_days else False,
# 'name': day
# }
# days.append(day_info)
# return {
# 'days': days,
# 'startOffset': start_hour * MINUTES_IN_HOUR + start_minute,
# 'endOffset': end_hour * MINUTES_IN_HOUR + end_minute,
# }
, which may contain function names, class names, or code. Output only the next line. | raise ResponseStructureError('id not in response', res) |
Given snippet: <|code_start|>
def check_exists(self):
"""
Check if current trigger exists
:return: trigger id if exists, None otherwise
"""
trigger_manager = TriggerManager(self._client)
for trigger in trigger_manager.fetch_all():
if self.name == trigger.name and \
set(self.targets) == set(trigger.targets) and \
set(self.tags) == set(trigger.tags):
return trigger
def get_metrics(self, start, end):
"""
Get metrics associated with certain trigger
:param start: The start period of metrics to get. Example : -1hour
:param end: The end period of metrics to get. Example : now
:return: Metrics for trigger
"""
try:
params = {
'from': start,
'to': end,
}
result = self._client.get('trigger/{id}/metrics'.format(id=self.id), params=params)
return result
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from ..client import ResponseStructureError
from ..client import InvalidJSONError
from .base import Base
from .common import MINUTES_IN_HOUR, get_schedule
and context:
# Path: moira_client/client.py
# class ResponseStructureError(Exception):
# def __init__(self, msg, content):
# """
#
# :param msg: str error message
# :param content: dict response content
# """
# self.msg = msg
# self.content = content
#
# Path: moira_client/client.py
# class InvalidJSONError(Exception):
# def __init__(self, content):
# """
#
# :param content: bytes response content
# """
# self.content = content
#
# Path: moira_client/models/base.py
# class Base:
# @property
# def id(self):
# return self._id
#
# def __repr__(self):
# return '({} {})'.format(self.__class__.__name__, self.id)
#
# def __unicode__(self):
# return u'({} {})'.format(self.__class__.__name__, self.id)
#
# def __eq__(self, other):
# return self.id == other.id
#
# def __ne__(self, other):
# return self.id != other.id
#
# Path: moira_client/models/common.py
# MINUTES_IN_HOUR = 60
#
# def get_schedule(start_hour, start_minute, end_hour, end_minute, disabled_days):
# days = []
# for day in DAYS_OF_WEEK:
# day_info = {
# 'enabled': True if day not in disabled_days else False,
# 'name': day
# }
# days.append(day_info)
# return {
# 'days': days,
# 'startOffset': start_hour * MINUTES_IN_HOUR + start_minute,
# 'endOffset': end_hour * MINUTES_IN_HOUR + end_minute,
# }
which might include code, classes, or functions. Output only the next line. | except InvalidJSONError: |
Given the following code snippet before the placeholder: <|code_start|>
STATE_OK = 'OK'
STATE_WARN = 'WARN'
STATE_ERROR = 'ERROR'
STATE_NODATA = 'NODATA'
STATE_EXCEPTION = 'EXCEPTION'
RISING_TRIGGER = 'rising'
FALLING_TRIGGER = 'falling'
EXPRESSION_TRIGGER = 'expression'
<|code_end|>
, predict the next line using imports from the current file:
from ..client import ResponseStructureError
from ..client import InvalidJSONError
from .base import Base
from .common import MINUTES_IN_HOUR, get_schedule
and context including class names, function names, and sometimes code from other files:
# Path: moira_client/client.py
# class ResponseStructureError(Exception):
# def __init__(self, msg, content):
# """
#
# :param msg: str error message
# :param content: dict response content
# """
# self.msg = msg
# self.content = content
#
# Path: moira_client/client.py
# class InvalidJSONError(Exception):
# def __init__(self, content):
# """
#
# :param content: bytes response content
# """
# self.content = content
#
# Path: moira_client/models/base.py
# class Base:
# @property
# def id(self):
# return self._id
#
# def __repr__(self):
# return '({} {})'.format(self.__class__.__name__, self.id)
#
# def __unicode__(self):
# return u'({} {})'.format(self.__class__.__name__, self.id)
#
# def __eq__(self, other):
# return self.id == other.id
#
# def __ne__(self, other):
# return self.id != other.id
#
# Path: moira_client/models/common.py
# MINUTES_IN_HOUR = 60
#
# def get_schedule(start_hour, start_minute, end_hour, end_minute, disabled_days):
# days = []
# for day in DAYS_OF_WEEK:
# day_info = {
# 'enabled': True if day not in disabled_days else False,
# 'name': day
# }
# days.append(day_info)
# return {
# 'days': days,
# 'startOffset': start_hour * MINUTES_IN_HOUR + start_minute,
# 'endOffset': end_hour * MINUTES_IN_HOUR + end_minute,
# }
. Output only the next line. | class Trigger(Base): |
Using the snippet: <|code_start|> :param kwargs: additional parameters
"""
self._client = client
self._id = kwargs.get('id', None)
self.name = name
self.tags = tags
self.targets = targets
self.warn_value = warn_value
self.error_value = error_value
self.desc = desc
self.ttl = ttl
self.ttl_state = ttl_state
default_sched = {
'startOffset': 0,
'endOffset': 1439,
'tzOffset': 0
}
if not sched:
sched = default_sched
self.disabled_days = set()
else:
if 'days' in sched:
self.disabled_days = {day['name'] for day in sched['days'] if not day['enabled']}
self.sched = sched
self.expression = expression
self.trigger_type = self.resolve_type(trigger_type)
# compute time range
<|code_end|>
, determine the next line of code. You have imports:
from ..client import ResponseStructureError
from ..client import InvalidJSONError
from .base import Base
from .common import MINUTES_IN_HOUR, get_schedule
and context (class names, function names, or code) available:
# Path: moira_client/client.py
# class ResponseStructureError(Exception):
# def __init__(self, msg, content):
# """
#
# :param msg: str error message
# :param content: dict response content
# """
# self.msg = msg
# self.content = content
#
# Path: moira_client/client.py
# class InvalidJSONError(Exception):
# def __init__(self, content):
# """
#
# :param content: bytes response content
# """
# self.content = content
#
# Path: moira_client/models/base.py
# class Base:
# @property
# def id(self):
# return self._id
#
# def __repr__(self):
# return '({} {})'.format(self.__class__.__name__, self.id)
#
# def __unicode__(self):
# return u'({} {})'.format(self.__class__.__name__, self.id)
#
# def __eq__(self, other):
# return self.id == other.id
#
# def __ne__(self, other):
# return self.id != other.id
#
# Path: moira_client/models/common.py
# MINUTES_IN_HOUR = 60
#
# def get_schedule(start_hour, start_minute, end_hour, end_minute, disabled_days):
# days = []
# for day in DAYS_OF_WEEK:
# day_info = {
# 'enabled': True if day not in disabled_days else False,
# 'name': day
# }
# days.append(day_info)
# return {
# 'days': days,
# 'startOffset': start_hour * MINUTES_IN_HOUR + start_minute,
# 'endOffset': end_hour * MINUTES_IN_HOUR + end_minute,
# }
. Output only the next line. | self._start_hour = self.sched['startOffset'] // MINUTES_IN_HOUR |
Using the snippet: <|code_start|> """
self.disabled_days.remove(day)
@property
def id(self):
return self._id
def _send_request(self, trigger_id=None):
data = {
'name': self.name,
'tags': self.tags,
'targets': self.targets,
'warn_value': self.warn_value,
'error_value': self.error_value,
'desc': self.desc,
'ttl': self.ttl,
'ttl_state': self.ttl_state,
'sched': self.sched,
'expression': self.expression,
'is_remote': self.is_remote,
'trigger_type': self.trigger_type,
'mute_new_metrics': self.mute_new_metrics,
'alone_metrics': self.alone_metrics,
}
if trigger_id:
data['id'] = trigger_id
api_response = TriggerManager(
self._client).fetch_by_id(trigger_id)
<|code_end|>
, determine the next line of code. You have imports:
from ..client import ResponseStructureError
from ..client import InvalidJSONError
from .base import Base
from .common import MINUTES_IN_HOUR, get_schedule
and context (class names, function names, or code) available:
# Path: moira_client/client.py
# class ResponseStructureError(Exception):
# def __init__(self, msg, content):
# """
#
# :param msg: str error message
# :param content: dict response content
# """
# self.msg = msg
# self.content = content
#
# Path: moira_client/client.py
# class InvalidJSONError(Exception):
# def __init__(self, content):
# """
#
# :param content: bytes response content
# """
# self.content = content
#
# Path: moira_client/models/base.py
# class Base:
# @property
# def id(self):
# return self._id
#
# def __repr__(self):
# return '({} {})'.format(self.__class__.__name__, self.id)
#
# def __unicode__(self):
# return u'({} {})'.format(self.__class__.__name__, self.id)
#
# def __eq__(self, other):
# return self.id == other.id
#
# def __ne__(self, other):
# return self.id != other.id
#
# Path: moira_client/models/common.py
# MINUTES_IN_HOUR = 60
#
# def get_schedule(start_hour, start_minute, end_hour, end_minute, disabled_days):
# days = []
# for day in DAYS_OF_WEEK:
# day_info = {
# 'enabled': True if day not in disabled_days else False,
# 'name': day
# }
# days.append(day_info)
# return {
# 'days': days,
# 'startOffset': start_hour * MINUTES_IN_HOUR + start_minute,
# 'endOffset': end_hour * MINUTES_IN_HOUR + end_minute,
# }
. Output only the next line. | data['sched'] = get_schedule(self._start_hour, self._start_minute, self._end_hour, self._end_minute, |
Here is a snippet: <|code_start|>TEST_HEADERS = {
'X-Webauth-User': 'login',
'Content-Type': 'application/json',
'User-Agent': 'Python Moira Client'
}
class FakeResponse:
@property
def content(self):
return 'not json'
def raise_for_status(self):
pass
def json(self):
raise ValueError('invalid json')
class ClientTest(unittest.TestCase):
def test_get(self):
def get(url, params, **kwargs):
pass
with patch.object(requests, 'get', side_effects=get) as mock_get:
test_path = 'test_path'
<|code_end|>
. Write the next line using the current file imports:
import unittest
import requests
from unittest.mock import patch
from mock import patch
from moira_client.client import Client
from moira_client.client import InvalidJSONError
and context from other files:
# Path: moira_client/client.py
# class Client:
# def __init__(self, api_url, auth_custom=None, auth_user=None, auth_pass=None, login=None):
# """
#
# :param api_url: str Moira API URL
# :param auth_custom: dict auth custom headers
# :param auth_user: str auth user
# :param auth_pass: str auth password
# :param login: str auth login
# """
# if not api_url.endswith('/'):
# self.api_url = api_url + '/'
# else:
# self.api_url = api_url
#
# if not login and auth_user:
# login = auth_user
#
# self.auth = None
# self.headers = {
# 'X-Webauth-User': login,
# 'Content-Type': 'application/json',
# 'User-Agent': 'Python Moira Client'
# }
#
# if auth_user and auth_pass:
# self.auth = HTTPBasicAuth(auth_user, auth_pass)
#
# if auth_custom:
# self.headers.update(auth_custom)
#
# def get(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.get(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def delete(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.delete(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def put(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.put(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def post(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.post(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def _path_join(self, *args):
# path = self.api_url
# for part in args:
# path += part
# return path
#
# Path: moira_client/client.py
# class InvalidJSONError(Exception):
# def __init__(self, content):
# """
#
# :param content: bytes response content
# """
# self.content = content
, which may include functions, classes, or code. Output only the next line. | client = Client(TEST_API_URL, TEST_HEADERS) |
Given snippet: <|code_start|> self.assertTrue(mock_post.called)
expected_url_call = TEST_API_URL + '/' + test_path
mock_post.assert_called_with(expected_url_call, data=test_data, headers=TEST_HEADERS, auth=None)
def test_delete(self):
def delete(url, **kwargs):
pass
with patch.object(requests, 'delete', side_effects=delete) as mock_delete:
test_path = 'test_path'
client = Client(TEST_API_URL, TEST_HEADERS)
client.delete(test_path)
self.assertTrue(mock_delete.called)
expected_url_call = TEST_API_URL + '/' + test_path
mock_delete.assert_called_with(expected_url_call, headers=TEST_HEADERS, auth=None)
def test_get_invalid_response(self):
def get(url, params, **kwargs):
return FakeResponse()
response = FakeResponse()
with patch.object(requests, 'get', side_effects=get, return_value=response) as mock_get:
test_path = 'test_path'
client = Client(TEST_API_URL, TEST_HEADERS)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
import requests
from unittest.mock import patch
from mock import patch
from moira_client.client import Client
from moira_client.client import InvalidJSONError
and context:
# Path: moira_client/client.py
# class Client:
# def __init__(self, api_url, auth_custom=None, auth_user=None, auth_pass=None, login=None):
# """
#
# :param api_url: str Moira API URL
# :param auth_custom: dict auth custom headers
# :param auth_user: str auth user
# :param auth_pass: str auth password
# :param login: str auth login
# """
# if not api_url.endswith('/'):
# self.api_url = api_url + '/'
# else:
# self.api_url = api_url
#
# if not login and auth_user:
# login = auth_user
#
# self.auth = None
# self.headers = {
# 'X-Webauth-User': login,
# 'Content-Type': 'application/json',
# 'User-Agent': 'Python Moira Client'
# }
#
# if auth_user and auth_pass:
# self.auth = HTTPBasicAuth(auth_user, auth_pass)
#
# if auth_custom:
# self.headers.update(auth_custom)
#
# def get(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.get(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def delete(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.delete(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def put(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.put(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def post(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.post(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def _path_join(self, *args):
# path = self.api_url
# for part in args:
# path += part
# return path
#
# Path: moira_client/client.py
# class InvalidJSONError(Exception):
# def __init__(self, content):
# """
#
# :param content: bytes response content
# """
# self.content = content
which might include code, classes, or functions. Output only the next line. | with self.assertRaises(InvalidJSONError): |
Given snippet: <|code_start|>try:
except ImportError:
class ConfigTest(ModelTest):
def test_fetch(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from unittest.mock import Mock
from unittest.mock import patch
from mock import Mock
from mock import patch
from moira_client.client import Client
from moira_client.client import ResponseStructureError
from .test_model import ModelTest
from moira_client.models.config import ConfigManager
and context:
# Path: moira_client/client.py
# class Client:
# def __init__(self, api_url, auth_custom=None, auth_user=None, auth_pass=None, login=None):
# """
#
# :param api_url: str Moira API URL
# :param auth_custom: dict auth custom headers
# :param auth_user: str auth user
# :param auth_pass: str auth password
# :param login: str auth login
# """
# if not api_url.endswith('/'):
# self.api_url = api_url + '/'
# else:
# self.api_url = api_url
#
# if not login and auth_user:
# login = auth_user
#
# self.auth = None
# self.headers = {
# 'X-Webauth-User': login,
# 'Content-Type': 'application/json',
# 'User-Agent': 'Python Moira Client'
# }
#
# if auth_user and auth_pass:
# self.auth = HTTPBasicAuth(auth_user, auth_pass)
#
# if auth_custom:
# self.headers.update(auth_custom)
#
# def get(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.get(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def delete(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.delete(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def put(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.put(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def post(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.post(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def _path_join(self, *args):
# path = self.api_url
# for part in args:
# path += part
# return path
#
# Path: moira_client/client.py
# class ResponseStructureError(Exception):
# def __init__(self, msg, content):
# """
#
# :param msg: str error message
# :param content: dict response content
# """
# self.msg = msg
# self.content = content
#
# Path: tests/models/test_model.py
# class ModelTest(unittest.TestCase):
# TEST_API_URL = 'http://test/url'
#
# @property
# def api_url(self):
# return self.TEST_API_URL
#
# Path: moira_client/models/config.py
# class ConfigManager:
# def __init__(self, client):
# self._client = client
#
# def fetch(self):
# """
# Returns config, see https://moira.readthedocs.io/en/latest/installation/configuration.html
#
# :return: config
#
# :raises: ResponseStructureError
# """
# result = self._client.get(self._full_path())
#
# if 'contacts' not in result:
# raise ResponseStructureError("'contacts' field doesn't exist in response", result)
# if 'remoteAllowed' not in result:
# raise ResponseStructureError("'remoteAllowed' field doesn't exist in response", result)
#
# contacts = []
# for contact in result['contacts']:
# if self._validate_contact(contact):
# _help = contact['help'] if 'help' in contact else None
# validation = contact['validation'] if 'validation' in contact else None
# placeholder = contact['placeholder'] if 'placeholder' in contact else None
# contacts.append(WebContact(_type=contact['type'], label=contact['label'], validation=validation,
# placeholder=placeholder, _help=_help))
# support = result['supportEmail'] if 'supportEmail' in result else None
# return Config(remote_allowed=result['remoteAllowed'], contacts=contacts, support_email=support)
#
# def _validate_contact(self, contact):
# if 'type' not in contact:
# return False
# if 'label' not in contact:
# return False
# return True
#
# def _full_path(self, path=''):
# if path:
# return 'config/{}'.format(path)
# return 'config'
which might include code, classes, or functions. Output only the next line. | client = Client(self.api_url) |
Based on the snippet: <|code_start|>try:
except ImportError:
class ConfigTest(ModelTest):
def test_fetch(self):
client = Client(self.api_url)
<|code_end|>
, predict the immediate next line with the help of imports:
from unittest.mock import Mock
from unittest.mock import patch
from mock import Mock
from mock import patch
from moira_client.client import Client
from moira_client.client import ResponseStructureError
from .test_model import ModelTest
from moira_client.models.config import ConfigManager
and context (classes, functions, sometimes code) from other files:
# Path: moira_client/client.py
# class Client:
# def __init__(self, api_url, auth_custom=None, auth_user=None, auth_pass=None, login=None):
# """
#
# :param api_url: str Moira API URL
# :param auth_custom: dict auth custom headers
# :param auth_user: str auth user
# :param auth_pass: str auth password
# :param login: str auth login
# """
# if not api_url.endswith('/'):
# self.api_url = api_url + '/'
# else:
# self.api_url = api_url
#
# if not login and auth_user:
# login = auth_user
#
# self.auth = None
# self.headers = {
# 'X-Webauth-User': login,
# 'Content-Type': 'application/json',
# 'User-Agent': 'Python Moira Client'
# }
#
# if auth_user and auth_pass:
# self.auth = HTTPBasicAuth(auth_user, auth_pass)
#
# if auth_custom:
# self.headers.update(auth_custom)
#
# def get(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.get(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def delete(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.delete(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def put(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.put(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def post(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.post(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def _path_join(self, *args):
# path = self.api_url
# for part in args:
# path += part
# return path
#
# Path: moira_client/client.py
# class ResponseStructureError(Exception):
# def __init__(self, msg, content):
# """
#
# :param msg: str error message
# :param content: dict response content
# """
# self.msg = msg
# self.content = content
#
# Path: tests/models/test_model.py
# class ModelTest(unittest.TestCase):
# TEST_API_URL = 'http://test/url'
#
# @property
# def api_url(self):
# return self.TEST_API_URL
#
# Path: moira_client/models/config.py
# class ConfigManager:
# def __init__(self, client):
# self._client = client
#
# def fetch(self):
# """
# Returns config, see https://moira.readthedocs.io/en/latest/installation/configuration.html
#
# :return: config
#
# :raises: ResponseStructureError
# """
# result = self._client.get(self._full_path())
#
# if 'contacts' not in result:
# raise ResponseStructureError("'contacts' field doesn't exist in response", result)
# if 'remoteAllowed' not in result:
# raise ResponseStructureError("'remoteAllowed' field doesn't exist in response", result)
#
# contacts = []
# for contact in result['contacts']:
# if self._validate_contact(contact):
# _help = contact['help'] if 'help' in contact else None
# validation = contact['validation'] if 'validation' in contact else None
# placeholder = contact['placeholder'] if 'placeholder' in contact else None
# contacts.append(WebContact(_type=contact['type'], label=contact['label'], validation=validation,
# placeholder=placeholder, _help=_help))
# support = result['supportEmail'] if 'supportEmail' in result else None
# return Config(remote_allowed=result['remoteAllowed'], contacts=contacts, support_email=support)
#
# def _validate_contact(self, contact):
# if 'type' not in contact:
# return False
# if 'label' not in contact:
# return False
# return True
#
# def _full_path(self, path=''):
# if path:
# return 'config/{}'.format(path)
# return 'config'
. Output only the next line. | config_manager = ConfigManager(client) |
Given snippet: <|code_start|>try:
except ImportError:
class HealthTest(ModelTest):
def test_get_notifier_state(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from unittest.mock import patch
from mock import patch
from moira_client.client import Client
from moira_client.client import ResponseStructureError
from moira_client.models.health import HealthManager
from .test_model import ModelTest
and context:
# Path: moira_client/client.py
# class Client:
# def __init__(self, api_url, auth_custom=None, auth_user=None, auth_pass=None, login=None):
# """
#
# :param api_url: str Moira API URL
# :param auth_custom: dict auth custom headers
# :param auth_user: str auth user
# :param auth_pass: str auth password
# :param login: str auth login
# """
# if not api_url.endswith('/'):
# self.api_url = api_url + '/'
# else:
# self.api_url = api_url
#
# if not login and auth_user:
# login = auth_user
#
# self.auth = None
# self.headers = {
# 'X-Webauth-User': login,
# 'Content-Type': 'application/json',
# 'User-Agent': 'Python Moira Client'
# }
#
# if auth_user and auth_pass:
# self.auth = HTTPBasicAuth(auth_user, auth_pass)
#
# if auth_custom:
# self.headers.update(auth_custom)
#
# def get(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.get(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def delete(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.delete(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def put(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.put(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def post(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.post(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def _path_join(self, *args):
# path = self.api_url
# for part in args:
# path += part
# return path
#
# Path: moira_client/client.py
# class ResponseStructureError(Exception):
# def __init__(self, msg, content):
# """
#
# :param msg: str error message
# :param content: dict response content
# """
# self.msg = msg
# self.content = content
#
# Path: moira_client/models/health.py
# class HealthManager:
# def __init__(self, client):
# self._client = client
#
# def get_notifier_state(self):
# """
# Returns current Moira Notifier state
# :return: str
#
# :raises: ResponseStructureError
# """
# result = self._client.get(self._full_path("notifier"))
# if 'state' not in result:
# raise ResponseStructureError("state doesn't exist in response", result)
#
# return result['state']
#
# def disable_notifications(self):
# """
# Manage Moira Notifier to stop sending notifications
# Returns current Moira Notifier state
# :return: str
#
# :raises: ResponseStructureError
# """
# data = {
# 'state': STATE_DISABLED
# }
# result = self._client.put(self._full_path("notifier"), json=data)
# if 'state' not in result:
# raise ResponseStructureError("state doesn't exist in response", result)
#
# return result['state']
#
# def enable_notifications(self):
# """
# Manage Moira Notifier to start sending notifications
# Returns current Moira Notifier state
# :return: str
#
# :raises: ResponseStructureError
# """
# data = {
# 'state': STATE_ENABLED
# }
# result = self._client.put(self._full_path("notifier"), json=data)
# if 'state' not in result:
# raise ResponseStructureError("state doesn't exist in response", result)
#
# return result['state']
#
# def _full_path(self, path=''):
# if path:
# return 'health/{}'.format(path)
# return 'health'
#
# Path: tests/models/test_model.py
# class ModelTest(unittest.TestCase):
# TEST_API_URL = 'http://test/url'
#
# @property
# def api_url(self):
# return self.TEST_API_URL
which might include code, classes, or functions. Output only the next line. | client = Client(self.api_url) |
Continue the code snippet: <|code_start|>try:
except ImportError:
class HealthTest(ModelTest):
def test_get_notifier_state(self):
client = Client(self.api_url)
<|code_end|>
. Use current file imports:
from unittest.mock import patch
from mock import patch
from moira_client.client import Client
from moira_client.client import ResponseStructureError
from moira_client.models.health import HealthManager
from .test_model import ModelTest
and context (classes, functions, or code) from other files:
# Path: moira_client/client.py
# class Client:
# def __init__(self, api_url, auth_custom=None, auth_user=None, auth_pass=None, login=None):
# """
#
# :param api_url: str Moira API URL
# :param auth_custom: dict auth custom headers
# :param auth_user: str auth user
# :param auth_pass: str auth password
# :param login: str auth login
# """
# if not api_url.endswith('/'):
# self.api_url = api_url + '/'
# else:
# self.api_url = api_url
#
# if not login and auth_user:
# login = auth_user
#
# self.auth = None
# self.headers = {
# 'X-Webauth-User': login,
# 'Content-Type': 'application/json',
# 'User-Agent': 'Python Moira Client'
# }
#
# if auth_user and auth_pass:
# self.auth = HTTPBasicAuth(auth_user, auth_pass)
#
# if auth_custom:
# self.headers.update(auth_custom)
#
# def get(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.get(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def delete(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.delete(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def put(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.put(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def post(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.post(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def _path_join(self, *args):
# path = self.api_url
# for part in args:
# path += part
# return path
#
# Path: moira_client/client.py
# class ResponseStructureError(Exception):
# def __init__(self, msg, content):
# """
#
# :param msg: str error message
# :param content: dict response content
# """
# self.msg = msg
# self.content = content
#
# Path: moira_client/models/health.py
# class HealthManager:
# def __init__(self, client):
# self._client = client
#
# def get_notifier_state(self):
# """
# Returns current Moira Notifier state
# :return: str
#
# :raises: ResponseStructureError
# """
# result = self._client.get(self._full_path("notifier"))
# if 'state' not in result:
# raise ResponseStructureError("state doesn't exist in response", result)
#
# return result['state']
#
# def disable_notifications(self):
# """
# Manage Moira Notifier to stop sending notifications
# Returns current Moira Notifier state
# :return: str
#
# :raises: ResponseStructureError
# """
# data = {
# 'state': STATE_DISABLED
# }
# result = self._client.put(self._full_path("notifier"), json=data)
# if 'state' not in result:
# raise ResponseStructureError("state doesn't exist in response", result)
#
# return result['state']
#
# def enable_notifications(self):
# """
# Manage Moira Notifier to start sending notifications
# Returns current Moira Notifier state
# :return: str
#
# :raises: ResponseStructureError
# """
# data = {
# 'state': STATE_ENABLED
# }
# result = self._client.put(self._full_path("notifier"), json=data)
# if 'state' not in result:
# raise ResponseStructureError("state doesn't exist in response", result)
#
# return result['state']
#
# def _full_path(self, path=''):
# if path:
# return 'health/{}'.format(path)
# return 'health'
#
# Path: tests/models/test_model.py
# class ModelTest(unittest.TestCase):
# TEST_API_URL = 'http://test/url'
#
# @property
# def api_url(self):
# return self.TEST_API_URL
. Output only the next line. | health_manager = HealthManager(client) |
Predict the next line for this snippet: <|code_start|> def __init__(self, _type, label, validation=None, placeholder=None, _help=None):
self.type = _type
self.label = label
self.validation = validation
self.placeholder = placeholder
self.help = _help
class Config:
def __init__(self, remote_allowed, contacts, support_email=None):
self.remoteAllowed = remote_allowed
self.contacts = contacts
self.supportEmail = support_email
class ConfigManager:
def __init__(self, client):
self._client = client
def fetch(self):
"""
Returns config, see https://moira.readthedocs.io/en/latest/installation/configuration.html
:return: config
:raises: ResponseStructureError
"""
result = self._client.get(self._full_path())
if 'contacts' not in result:
<|code_end|>
with the help of current file imports:
from ..client import ResponseStructureError
and context from other files:
# Path: moira_client/client.py
# class ResponseStructureError(Exception):
# def __init__(self, msg, content):
# """
#
# :param msg: str error message
# :param content: dict response content
# """
# self.msg = msg
# self.content = content
, which may contain function names, class names, or code. Output only the next line. | raise ResponseStructureError("'contacts' field doesn't exist in response", result) |
Predict the next line after this snippet: <|code_start|>
STATE_ENABLED = 'OK'
STATE_DISABLED = 'ERROR'
class HealthManager:
def __init__(self, client):
self._client = client
def get_notifier_state(self):
"""
Returns current Moira Notifier state
:return: str
:raises: ResponseStructureError
"""
result = self._client.get(self._full_path("notifier"))
if 'state' not in result:
<|code_end|>
using the current file's imports:
from ..client import ResponseStructureError
and any relevant context from other files:
# Path: moira_client/client.py
# class ResponseStructureError(Exception):
# def __init__(self, msg, content):
# """
#
# :param msg: str error message
# :param content: dict response content
# """
# self.msg = msg
# self.content = content
. Output only the next line. | raise ResponseStructureError("state doesn't exist in response", result) |
Predict the next line for this snippet: <|code_start|>try:
except ImportError:
class UserTest(ModelTest):
def test_get_settings(self):
<|code_end|>
with the help of current file imports:
from unittest.mock import Mock
from unittest.mock import patch
from mock import Mock
from mock import patch
from moira_client.client import Client
from moira_client.models.user import UserManager
from .test_model import ModelTest
and context from other files:
# Path: moira_client/client.py
# class Client:
# def __init__(self, api_url, auth_custom=None, auth_user=None, auth_pass=None, login=None):
# """
#
# :param api_url: str Moira API URL
# :param auth_custom: dict auth custom headers
# :param auth_user: str auth user
# :param auth_pass: str auth password
# :param login: str auth login
# """
# if not api_url.endswith('/'):
# self.api_url = api_url + '/'
# else:
# self.api_url = api_url
#
# if not login and auth_user:
# login = auth_user
#
# self.auth = None
# self.headers = {
# 'X-Webauth-User': login,
# 'Content-Type': 'application/json',
# 'User-Agent': 'Python Moira Client'
# }
#
# if auth_user and auth_pass:
# self.auth = HTTPBasicAuth(auth_user, auth_pass)
#
# if auth_custom:
# self.headers.update(auth_custom)
#
# def get(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.get(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def delete(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.delete(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def put(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.put(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def post(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.post(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def _path_join(self, *args):
# path = self.api_url
# for part in args:
# path += part
# return path
#
# Path: moira_client/models/user.py
# class UserManager:
# def __init__(self, client):
# self._client = client
#
# def get_username(self):
# """
# Gets the username of the authenticated user if it is available.
#
# :return: login
#
# :raises: ResponseStructureError
# """
# result = self._client.get(self._full_path())
# if 'login' not in result:
# raise ResponseStructureError("'login' field doesn't exist in response", result)
# return result['login']
#
# def get_user_settings(self):
# """
# Get the user's contacts and subscriptions.
#
# :return: user settings
#
# :raises: ResponseStructureError
# """
# result = self._client.get(self._full_path('settings'))
# required = ['login', 'contacts', 'subscriptions']
# for field in required:
# if field not in result:
# raise ResponseStructureError("'{}' field doesn't exist in response".format(field), result)
#
# contacts = []
# for contact in result['contacts']:
# contacts.append(Contact(**contact))
# result['contacts'] = contacts
#
# subscriptions = []
# for subscription in result['subscriptions']:
# subscriptions.append(Subscription(self._client, **subscription))
# result['subscriptions'] = subscriptions
#
# return UserSettings(**result)
#
# def _full_path(self, path=''):
# if path:
# return 'user/{}'.format(path)
# return 'user'
#
# Path: tests/models/test_model.py
# class ModelTest(unittest.TestCase):
# TEST_API_URL = 'http://test/url'
#
# @property
# def api_url(self):
# return self.TEST_API_URL
, which may contain function names, class names, or code. Output only the next line. | client = Client(self.api_url) |
Based on the snippet: <|code_start|>try:
except ImportError:
class UserTest(ModelTest):
def test_get_settings(self):
client = Client(self.api_url)
<|code_end|>
, predict the immediate next line with the help of imports:
from unittest.mock import Mock
from unittest.mock import patch
from mock import Mock
from mock import patch
from moira_client.client import Client
from moira_client.models.user import UserManager
from .test_model import ModelTest
and context (classes, functions, sometimes code) from other files:
# Path: moira_client/client.py
# class Client:
# def __init__(self, api_url, auth_custom=None, auth_user=None, auth_pass=None, login=None):
# """
#
# :param api_url: str Moira API URL
# :param auth_custom: dict auth custom headers
# :param auth_user: str auth user
# :param auth_pass: str auth password
# :param login: str auth login
# """
# if not api_url.endswith('/'):
# self.api_url = api_url + '/'
# else:
# self.api_url = api_url
#
# if not login and auth_user:
# login = auth_user
#
# self.auth = None
# self.headers = {
# 'X-Webauth-User': login,
# 'Content-Type': 'application/json',
# 'User-Agent': 'Python Moira Client'
# }
#
# if auth_user and auth_pass:
# self.auth = HTTPBasicAuth(auth_user, auth_pass)
#
# if auth_custom:
# self.headers.update(auth_custom)
#
# def get(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.get(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def delete(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.delete(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def put(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.put(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def post(self, path='', **kwargs):
# """
#
# :param path: str api path
# :param kwargs: additional parameters for request
# :return: dict response
#
# :raises: HTTPError
# :raises: InvalidJSONError
# """
# r = requests.post(self._path_join(path), headers=self.headers, auth=self.auth, **kwargs)
# r.raise_for_status()
# try:
# return r.json()
# except ValueError:
# raise InvalidJSONError(r.content)
#
# def _path_join(self, *args):
# path = self.api_url
# for part in args:
# path += part
# return path
#
# Path: moira_client/models/user.py
# class UserManager:
# def __init__(self, client):
# self._client = client
#
# def get_username(self):
# """
# Gets the username of the authenticated user if it is available.
#
# :return: login
#
# :raises: ResponseStructureError
# """
# result = self._client.get(self._full_path())
# if 'login' not in result:
# raise ResponseStructureError("'login' field doesn't exist in response", result)
# return result['login']
#
# def get_user_settings(self):
# """
# Get the user's contacts and subscriptions.
#
# :return: user settings
#
# :raises: ResponseStructureError
# """
# result = self._client.get(self._full_path('settings'))
# required = ['login', 'contacts', 'subscriptions']
# for field in required:
# if field not in result:
# raise ResponseStructureError("'{}' field doesn't exist in response".format(field), result)
#
# contacts = []
# for contact in result['contacts']:
# contacts.append(Contact(**contact))
# result['contacts'] = contacts
#
# subscriptions = []
# for subscription in result['subscriptions']:
# subscriptions.append(Subscription(self._client, **subscription))
# result['subscriptions'] = subscriptions
#
# return UserSettings(**result)
#
# def _full_path(self, path=''):
# if path:
# return 'user/{}'.format(path)
# return 'user'
#
# Path: tests/models/test_model.py
# class ModelTest(unittest.TestCase):
# TEST_API_URL = 'http://test/url'
#
# @property
# def api_url(self):
# return self.TEST_API_URL
. Output only the next line. | user_manager = UserManager(client) |
Using the snippet: <|code_start|> contacts.append(Contact(**contact))
return contacts
def get_id(self, type, value):
"""
Returns contact id by type and value
Returns None if contact doesn't exist
:param type: str contact type
:param value: str contact value
:return: str contact id
"""
for contact in self.fetch_all():
if contact.type == type and contact.value == value:
return contact.id
def delete(self, contact_id):
"""
Delete contact by contact id
If contact id doesn't exist returns True
:param contact_id: str contact id
:return: True if ok, False otherwise
:raises: ResponseStructureError
"""
try:
self._client.delete(self._full_path(contact_id))
return False
<|code_end|>
, determine the next line of code. You have imports:
from ..client import InvalidJSONError
from ..client import ResponseStructureError
from .base import Base
and context (class names, function names, or code) available:
# Path: moira_client/client.py
# class InvalidJSONError(Exception):
# def __init__(self, content):
# """
#
# :param content: bytes response content
# """
# self.content = content
#
# Path: moira_client/client.py
# class ResponseStructureError(Exception):
# def __init__(self, msg, content):
# """
#
# :param msg: str error message
# :param content: dict response content
# """
# self.msg = msg
# self.content = content
#
# Path: moira_client/models/base.py
# class Base:
# @property
# def id(self):
# return self._id
#
# def __repr__(self):
# return '({} {})'.format(self.__class__.__name__, self.id)
#
# def __unicode__(self):
# return u'({} {})'.format(self.__class__.__name__, self.id)
#
# def __eq__(self, other):
# return self.id == other.id
#
# def __ne__(self, other):
# return self.id != other.id
. Output only the next line. | except InvalidJSONError as e: |
Given the following code snippet before the placeholder: <|code_start|> self.user = kwargs.get('user', None)
self._id = kwargs.get('id', None)
class ContactManager:
def __init__(self, client):
self._client = client
def add(self, value, contact_type):
"""
Add new contact
:param value: str contact value
:param contact_type: str contact type (one of CONTACT_* constants)
:return: Contact
:raises: ResponseStructureError
"""
data = {
'value': value,
'type': contact_type
}
contacts = self.fetch_by_current_user()
for contact in contacts:
if contact.value == value and contact.type == contact_type:
return contact
result = self._client.put(self._full_path(), json=data)
if 'id' not in result:
<|code_end|>
, predict the next line using imports from the current file:
from ..client import InvalidJSONError
from ..client import ResponseStructureError
from .base import Base
and context including class names, function names, and sometimes code from other files:
# Path: moira_client/client.py
# class InvalidJSONError(Exception):
# def __init__(self, content):
# """
#
# :param content: bytes response content
# """
# self.content = content
#
# Path: moira_client/client.py
# class ResponseStructureError(Exception):
# def __init__(self, msg, content):
# """
#
# :param msg: str error message
# :param content: dict response content
# """
# self.msg = msg
# self.content = content
#
# Path: moira_client/models/base.py
# class Base:
# @property
# def id(self):
# return self._id
#
# def __repr__(self):
# return '({} {})'.format(self.__class__.__name__, self.id)
#
# def __unicode__(self):
# return u'({} {})'.format(self.__class__.__name__, self.id)
#
# def __eq__(self, other):
# return self.id == other.id
#
# def __ne__(self, other):
# return self.id != other.id
. Output only the next line. | raise ResponseStructureError('No id in response', result) |
Predict the next line after this snippet: <|code_start|>
CONTACT_EMAIL = 'mail'
CONTACT_PUSHOVER = 'pushover'
CONTACT_SLACK = 'slack'
CONTACT_TELEGRAM = 'telegram'
CONTACT_TWILIO_SMS = 'twilio sms'
CONTACT_TWILIO_VOICE = 'twilio voice'
<|code_end|>
using the current file's imports:
from ..client import InvalidJSONError
from ..client import ResponseStructureError
from .base import Base
and any relevant context from other files:
# Path: moira_client/client.py
# class InvalidJSONError(Exception):
# def __init__(self, content):
# """
#
# :param content: bytes response content
# """
# self.content = content
#
# Path: moira_client/client.py
# class ResponseStructureError(Exception):
# def __init__(self, msg, content):
# """
#
# :param msg: str error message
# :param content: dict response content
# """
# self.msg = msg
# self.content = content
#
# Path: moira_client/models/base.py
# class Base:
# @property
# def id(self):
# return self._id
#
# def __repr__(self):
# return '({} {})'.format(self.__class__.__name__, self.id)
#
# def __unicode__(self):
# return u'({} {})'.format(self.__class__.__name__, self.id)
#
# def __eq__(self, other):
# return self.id == other.id
#
# def __ne__(self, other):
# return self.id != other.id
. Output only the next line. | class Contact(Base): |
Here is a snippet: <|code_start|> return None
def change(self, email=None):
if email != None and email != self.email:
with transact:
self.update(
email=email,
email_verified=False
)
self.generateEmailVerification()
def generateEmailVerification(self):
code = ''.join('%02X' % random.randrange(256) for i in range(20))
with transact:
self.update(email_verification=code)
email(self.email, 'verify', code=code)
def addGold(self, amount, price):
with transact:
self.update(gold=self.gold+amount)
GoldHistory.create(
user=self,
date=datetime.now(),
amount=amount,
balance=self.gold,
dollars=price,
job=None,
desc=u'Bought %i gold for $%.2f' % (amount, price / 100.0)
)
<|code_end|>
. Write the next line using the current file imports:
import math, json, os, random
import sqlalchemy as sa
import hashlib
import markdown2
from datetime import datetime
from sqlalchemy.orm import relationship
from sqlalchemy.types import *
from sms import sms
from metamodel import *
from handler import handler
from handler import handler
from handler import email
and context from other files:
# Path: sms.py
# def sms(number, message):
# client = TwilioRestClient(account, token)
# if number[0] != '+':
# if number[0] == '1':
# number = '+' + number
# else:
# assert len(number) == 10
# number = '+1' + number
# client.sms.messages.create(to=number, from_=from_number, body=message)
, which may include functions, classes, or code. Output only the next line. | def sms(self, message): |
Given snippet: <|code_start|>
def refresh(self, *fields):
for field in fields:
self._fields.add(field)
self._populate_data(self.connection.get_character(self.region, self._data['realm'],
self.name, raw=True, fields=self._fields))
self._delete_property_fields()
def get_realm_name(self):
return normalize(self._data['realm'])
def get_class_name(self):
return CLASS.get(self.class_, 'Unknown')
def get_spec_name(self):
for talent in self.talents:
if talent.selected:
return talent.name
return ''
def get_full_class_name(self):
spec_name = self.get_spec_name()
class_name = self.get_class_name()
return ('%s %s' % (spec_name, class_name)).strip()
def get_race_name(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import operator
import collections
import datetime
import simplejson as json
import json
from .enums import RACE, CLASS, QUALITY, RACE_TO_FACTION
from .utils import make_icon_url, normalize, make_connection
and context:
# Path: battlenet/enums.py
# RACE = {
# 1: 'Human',
# 2: 'Orc',
# 3: 'Dwarf',
# 4: 'Night Elf',
# 5: 'Undead',
# 6: 'Tauren',
# 7: 'Gnome',
# 8: 'Troll',
# 9: 'Goblin',
# 10: 'Blood Elf',
# 11: 'Draenei',
# 22: 'Worgen',
# }
#
# CLASS = {
# 1: 'Warrior',
# 2: 'Paladin',
# 3: 'Hunter',
# 4: 'Rogue',
# 5: 'Priest',
# 7: 'Shaman',
# 8: 'Mage',
# 9: 'Warlock',
# 11: 'Druid',
# 6: 'Death Knight',
# }
#
# QUALITY = {
# 1: 'Common',
# 2: 'Uncommon',
# 3: 'Rare',
# 4: 'Epic',
# 5: 'Legendary',
# }
#
# RACE_TO_FACTION = {
# 1: 'Alliance',
# 2: 'Horde',
# 3: 'Alliance',
# 4: 'Alliance',
# 5: 'Horde',
# 6: 'Horde',
# 7: 'Alliance',
# 8: 'Horde',
# 9: 'Horde',
# 10: 'Horde',
# 11: 'Alliance',
# 22: 'Alliance',
# }
#
# Path: battlenet/utils.py
# def make_icon_url(region, icon, size='large'):
# if not icon:
# return ''
#
# if size == 'small':
# size = 18
# else:
# size = 56
#
# return 'http://%s.media.blizzard.com/wow/icons/%d/%s.jpg' % (region, size, icon)
#
# def normalize(name):
# if not isinstance(name, unicode):
# name = name.decode('utf8')
#
# return unicodedata.normalize('NFKC', name).encode('utf8')
#
# def make_connection():
# if not hasattr(make_connection, 'Connection'):
# from .connection import Connection
# make_connection.Connection = Connection
#
# return make_connection.Connection()
which might include code, classes, or functions. Output only the next line. | return RACE.get(self.race, 'Unknown') |
Next line prediction: <|code_start|> self._stats = Stats(self, self._data[Character.STATS])
return self._stats
@property
def achievements(self):
if self._refresh_if_not_present(Character.ACHIEVEMENTS):
self._achievements = {}
achievements_completed = self._data['achievements']['achievementsCompleted']
achievements_completed_ts = self._data['achievements']['achievementsCompletedTimestamp']
for id_, timestamp in zip(achievements_completed, achievements_completed_ts):
self._achievements[id_] = datetime.datetime.fromtimestamp(timestamp / 1000)
return self._achievements
def refresh(self, *fields):
for field in fields:
self._fields.add(field)
self._populate_data(self.connection.get_character(self.region, self._data['realm'],
self.name, raw=True, fields=self._fields))
self._delete_property_fields()
def get_realm_name(self):
return normalize(self._data['realm'])
def get_class_name(self):
<|code_end|>
. Use current file imports:
(import operator
import collections
import datetime
import simplejson as json
import json
from .enums import RACE, CLASS, QUALITY, RACE_TO_FACTION
from .utils import make_icon_url, normalize, make_connection)
and context including class names, function names, or small code snippets from other files:
# Path: battlenet/enums.py
# RACE = {
# 1: 'Human',
# 2: 'Orc',
# 3: 'Dwarf',
# 4: 'Night Elf',
# 5: 'Undead',
# 6: 'Tauren',
# 7: 'Gnome',
# 8: 'Troll',
# 9: 'Goblin',
# 10: 'Blood Elf',
# 11: 'Draenei',
# 22: 'Worgen',
# }
#
# CLASS = {
# 1: 'Warrior',
# 2: 'Paladin',
# 3: 'Hunter',
# 4: 'Rogue',
# 5: 'Priest',
# 7: 'Shaman',
# 8: 'Mage',
# 9: 'Warlock',
# 11: 'Druid',
# 6: 'Death Knight',
# }
#
# QUALITY = {
# 1: 'Common',
# 2: 'Uncommon',
# 3: 'Rare',
# 4: 'Epic',
# 5: 'Legendary',
# }
#
# RACE_TO_FACTION = {
# 1: 'Alliance',
# 2: 'Horde',
# 3: 'Alliance',
# 4: 'Alliance',
# 5: 'Horde',
# 6: 'Horde',
# 7: 'Alliance',
# 8: 'Horde',
# 9: 'Horde',
# 10: 'Horde',
# 11: 'Alliance',
# 22: 'Alliance',
# }
#
# Path: battlenet/utils.py
# def make_icon_url(region, icon, size='large'):
# if not icon:
# return ''
#
# if size == 'small':
# size = 18
# else:
# size = 56
#
# return 'http://%s.media.blizzard.com/wow/icons/%d/%s.jpg' % (region, size, icon)
#
# def normalize(name):
# if not isinstance(name, unicode):
# name = name.decode('utf8')
#
# return unicodedata.normalize('NFKC', name).encode('utf8')
#
# def make_connection():
# if not hasattr(make_connection, 'Connection'):
# from .connection import Connection
# make_connection.Connection = Connection
#
# return make_connection.Connection()
. Output only the next line. | return CLASS.get(self.class_, 'Unknown') |
Given the code snippet: <|code_start|>
class EquippedItem(Thing):
def __init__(self, region, data):
self._region = region
self._data = data
self.id = data['id']
self.name = data['name']
self.quality = data['quality']
self.icon = data['icon']
self.reforge = data['tooltipParams'].get('reforge')
self.set = data['tooltipParams'].get('set')
self.enchant = data['tooltipParams'].get('enchant')
self.extra_socket = data['tooltipParams'].get('extraSocket', False)
self.gems = collections.defaultdict(lambda: None)
for key, value in data['tooltipParams'].items():
if key.startswith('gem'):
self.gems[int(key[3:])] = value
def __str__(self):
return self.name
def __repr__(self):
return '<%s: %s>' % (self.__class__.__name__, self.name)
def get_quality_name(self):
<|code_end|>
, generate the next line using the imports in this file:
import operator
import collections
import datetime
import simplejson as json
import json
from .enums import RACE, CLASS, QUALITY, RACE_TO_FACTION
from .utils import make_icon_url, normalize, make_connection
and context (functions, classes, or occasionally code) from other files:
# Path: battlenet/enums.py
# RACE = {
# 1: 'Human',
# 2: 'Orc',
# 3: 'Dwarf',
# 4: 'Night Elf',
# 5: 'Undead',
# 6: 'Tauren',
# 7: 'Gnome',
# 8: 'Troll',
# 9: 'Goblin',
# 10: 'Blood Elf',
# 11: 'Draenei',
# 22: 'Worgen',
# }
#
# CLASS = {
# 1: 'Warrior',
# 2: 'Paladin',
# 3: 'Hunter',
# 4: 'Rogue',
# 5: 'Priest',
# 7: 'Shaman',
# 8: 'Mage',
# 9: 'Warlock',
# 11: 'Druid',
# 6: 'Death Knight',
# }
#
# QUALITY = {
# 1: 'Common',
# 2: 'Uncommon',
# 3: 'Rare',
# 4: 'Epic',
# 5: 'Legendary',
# }
#
# RACE_TO_FACTION = {
# 1: 'Alliance',
# 2: 'Horde',
# 3: 'Alliance',
# 4: 'Alliance',
# 5: 'Horde',
# 6: 'Horde',
# 7: 'Alliance',
# 8: 'Horde',
# 9: 'Horde',
# 10: 'Horde',
# 11: 'Alliance',
# 22: 'Alliance',
# }
#
# Path: battlenet/utils.py
# def make_icon_url(region, icon, size='large'):
# if not icon:
# return ''
#
# if size == 'small':
# size = 18
# else:
# size = 56
#
# return 'http://%s.media.blizzard.com/wow/icons/%d/%s.jpg' % (region, size, icon)
#
# def normalize(name):
# if not isinstance(name, unicode):
# name = name.decode('utf8')
#
# return unicodedata.normalize('NFKC', name).encode('utf8')
#
# def make_connection():
# if not hasattr(make_connection, 'Connection'):
# from .connection import Connection
# make_connection.Connection = Connection
#
# return make_connection.Connection()
. Output only the next line. | return QUALITY.get(self.quality, 'Unknown') |
Given snippet: <|code_start|>
if realm and name and not data:
data = self.connection.get_character(region, realm, name, raw=True, fields=self._fields)
self._populate_data(data)
def __str__(self):
return self.name
def __repr__(self):
return '<%s: %s@%s>' % (self.__class__.__name__, self.name, self._data['realm'])
def __eq__(self, other):
if not isinstance(other, Character):
return False
return self.connection == other.connection \
and self.name == other.name \
and self.get_realm_name() == other.get_realm_name()
def _populate_data(self, data):
self._data = data
self.name = normalize(data['name'])
self.level = data['level']
self.class_ = data['class']
self.race = data['race']
self.thumbnail = data['thumbnail']
self.gender = data['gender']
self.achievement_points = data['achievementPoints']
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import operator
import collections
import datetime
import simplejson as json
import json
from .enums import RACE, CLASS, QUALITY, RACE_TO_FACTION
from .utils import make_icon_url, normalize, make_connection
and context:
# Path: battlenet/enums.py
# RACE = {
# 1: 'Human',
# 2: 'Orc',
# 3: 'Dwarf',
# 4: 'Night Elf',
# 5: 'Undead',
# 6: 'Tauren',
# 7: 'Gnome',
# 8: 'Troll',
# 9: 'Goblin',
# 10: 'Blood Elf',
# 11: 'Draenei',
# 22: 'Worgen',
# }
#
# CLASS = {
# 1: 'Warrior',
# 2: 'Paladin',
# 3: 'Hunter',
# 4: 'Rogue',
# 5: 'Priest',
# 7: 'Shaman',
# 8: 'Mage',
# 9: 'Warlock',
# 11: 'Druid',
# 6: 'Death Knight',
# }
#
# QUALITY = {
# 1: 'Common',
# 2: 'Uncommon',
# 3: 'Rare',
# 4: 'Epic',
# 5: 'Legendary',
# }
#
# RACE_TO_FACTION = {
# 1: 'Alliance',
# 2: 'Horde',
# 3: 'Alliance',
# 4: 'Alliance',
# 5: 'Horde',
# 6: 'Horde',
# 7: 'Alliance',
# 8: 'Horde',
# 9: 'Horde',
# 10: 'Horde',
# 11: 'Alliance',
# 22: 'Alliance',
# }
#
# Path: battlenet/utils.py
# def make_icon_url(region, icon, size='large'):
# if not icon:
# return ''
#
# if size == 'small':
# size = 18
# else:
# size = 56
#
# return 'http://%s.media.blizzard.com/wow/icons/%d/%s.jpg' % (region, size, icon)
#
# def normalize(name):
# if not isinstance(name, unicode):
# name = name.decode('utf8')
#
# return unicodedata.normalize('NFKC', name).encode('utf8')
#
# def make_connection():
# if not hasattr(make_connection, 'Connection'):
# from .connection import Connection
# make_connection.Connection = Connection
#
# return make_connection.Connection()
which might include code, classes, or functions. Output only the next line. | self.faction = RACE_TO_FACTION[self.race] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.