Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line after this snippet: <|code_start|>
random_config = {
'discount': get_discount()
, 'N0': get_N0()
, 'min_eps': get_min_eps()
, 'initial_q_value': get_initial_q_value()
}
random_config.update(fixed_params)
return random... | self.actions_t, self.probs_t = capacities.tabular_UCB( |
Given snippet: <|code_start|> 'lr': get_lr()
, 'lr_decay_steps': get_lr_decay_steps()
, 'discount': get_discount()
, 'N0': get_N0()
, 'min_eps': get_min_eps()
, 'initial_q_value': get_initial_q_value()
}
random_config.update(fixed_pa... | self.actions_t, self.probs_t = capacities.tabular_UCB( |
Given the following code snippet before the placeholder: <|code_start|> 'lr': get_lr()
, 'lr_decay_steps': get_lr_decay_steps()
, 'discount': get_discount()
, 'N0': get_N0()
, 'min_eps': get_min_eps()
, 'initial_q_value': get_initial_q_value()
... | self.actions_t, self.probs_t = capacities.tabular_UCB( |
Predict the next line after this snippet: <|code_start|> game.created_by = game.modified_by = self.request.user
game.save()
self._save_team_score(game, Team.RED, form.forms['team1'])
self._save_team_score(game, Team.BLUE, form.forms['team2'])
return redirect(self.get_success_url... | stats_func = getattr(stats, "stats_%s" % statistic, None) |
Given snippet: <|code_start|>
class GameListView(LoginRequiredMixin, ListView):
model = Game
paginate_by = 10
template_name = "games/game_list.jinja"
class GameDetailView(LoginRequiredMixin, DetailView):
model = Game
template_name = "games/game_detail.jinja"
class GameCreateView(LoginRequired... | form_class = GameForm |
Predict the next line for this snippet: <|code_start|>
class GameDetailView(LoginRequiredMixin, DetailView):
model = Game
template_name = "games/game_detail.jinja"
class GameCreateView(LoginRequiredMixin, FormView):
template_name = "games/game_new.jinja"
form_class = GameForm
success_url = revers... | update_player_stats(team) |
Continue the code snippet: <|code_start|>
class GameListView(LoginRequiredMixin, ListView):
model = Game
paginate_by = 10
template_name = "games/game_list.jinja"
class GameDetailView(LoginRequiredMixin, DetailView):
model = Game
template_name = "games/game_detail.jinja"
class GameCreateView(L... | self._save_team_score(game, Team.RED, form.forms['team1']) |
Here is a snippet: <|code_start|> for user in instance.players.all():
totals = {1: 0, 2: 0}
wins = {1: 0, 2: 0}
teams = Team.objects.filter(players__id=user.id).prefetch_related("players")
for team in teams:
player_count = len(team.players.all())
totals[player_... | red_wins = Game.objects.filter(teams__side=Team.RED, teams__score=10).count() |
Next line prediction: <|code_start|>
def update_player_stats(instance):
"""
Update player win and played counts for players of a Team.
:param instance: Team that will be used to update players.
:type instance: Team
"""
for user in instance.players.all():
totals = {1: 0, 2: 0}
w... | teams = Team.objects.filter(players__id=user.id).prefetch_related("players") |
Here is a snippet: <|code_start|>
def update_player_stats(instance):
"""
Update player win and played counts for players of a Team.
:param instance: Team that will be used to update players.
:type instance: Team
"""
for user in instance.players.all():
totals = {1: 0, 2: 0}
wins... | player, _created = Player.objects.get_or_create(user=user) |
Based on the snippet: <|code_start|> model = Team
def has_changed(self):
# force Teams to be saved also when they aren't modified,
# prevents Games with less than two Teams
return True
class TeamInlineFormSet(forms.models.BaseInlineFormSet):
def clean(self):
clean_team_form... | @admin.register(Game) |
Given the following code snippet before the placeholder: <|code_start|>class TeamInline(admin.TabularInline):
model = Team
form = TeamForm
formset = TeamInlineFormSet
extra = 2
max_num = 2
class Media:
css = {
'all': ('css/admin_hide_team_str.css',)
}
def has_de... | @admin.register(Table) |
Predict the next line after this snippet: <|code_start|>
class TeamForm(forms.ModelForm):
model = Team
def has_changed(self):
# force Teams to be saved also when they aren't modified,
# prevents Games with less than two Teams
return True
class TeamInlineFormSet(forms.models.BaseInl... | clean_team_forms(self.forms[0], self.forms[1]) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
@pytest.fixture
def four_users(user_factory):
return user_factory.create_batch(4)
@pytest.fixture
def game_form_data():
return {
'form-game-played_at': '2016-03-03 12:00:00',
'form-team1-players': [1, 2],
'form-team2-players':... | form = GameForm(data=game_form_data) |
Using the snippet: <|code_start|>
def handle_login(client):
"""
Create user and log the user in.
"""
user = UserFactory(username="foobar")
client.force_login(user)
def create_game(winner_loser=("RED", "BLUE"), players=(None, None)):
"""
Create a game and teams.
Optionally with given ... | game = Game.objects.create() |
Using the snippet: <|code_start|>
def handle_login(client):
"""
Create user and log the user in.
"""
user = UserFactory(username="foobar")
client.force_login(user)
def create_game(winner_loser=("RED", "BLUE"), players=(None, None)):
"""
Create a game and teams.
Optionally with given ... | winners = TeamFactory(score=10, game=game, side=getattr(Team, winner_loser[0]), players=players[0]) |
Based on the snippet: <|code_start|>
def handle_login(client):
"""
Create user and log the user in.
"""
user = UserFactory(username="foobar")
client.force_login(user)
def create_game(winner_loser=("RED", "BLUE"), players=(None, None)):
"""
Create a game and teams.
Optionally with giv... | update_player_stats(winners) |
Continue the code snippet: <|code_start|>
def handle_login(client):
"""
Create user and log the user in.
"""
user = UserFactory(username="foobar")
client.force_login(user)
def create_game(winner_loser=("RED", "BLUE"), players=(None, None)):
"""
Create a game and teams.
Optionally wit... | winners = TeamFactory(score=10, game=game, side=getattr(Team, winner_loser[0]), players=players[0]) |
Using the snippet: <|code_start|>
@pytest.mark.django_db
def test_stats_red_or_blue():
for i in range(3):
create_game()
create_game(("BLUE", "RED"))
<|code_end|>
, determine the next line of code. You have imports:
from decimal import Decimal
from foosball.games.stats import stats_red_or_blue, stats... | stats = stats_red_or_blue(None) |
Next line prediction: <|code_start|>
@pytest.mark.django_db
def test_stats_red_or_blue():
for i in range(3):
create_game()
create_game(("BLUE", "RED"))
stats = stats_red_or_blue(None)
assert stats["data"]["datasets"][0]["data"] == [3, 1]
@pytest.mark.django_db
def test_stats_players():
... | stats = stats_players(None) |
Using the snippet: <|code_start|>
@pytest.mark.django_db
def test_stats_red_or_blue():
for i in range(3):
<|code_end|>
, determine the next line of code. You have imports:
from decimal import Decimal
from foosball.games.stats import stats_red_or_blue, stats_players
from foosball.games.tests.utils import create_... | create_game() |
Given the following code snippet before the placeholder: <|code_start|>
@pytest.mark.django_db
@pytest.mark.client
def test_game_list_view_renders(client):
handle_login(client)
response = client.get(reverse("games:index"))
assert response.status_code == 200
@pytest.mark.django_db
@pytest.mark.client
def... | game = GameFactory() |
Predict the next line after this snippet: <|code_start|>
@pytest.mark.django_db
@pytest.mark.client
def test_game_list_view_renders(client):
<|code_end|>
using the current file's imports:
import pytest
from django.core.urlresolvers import reverse
from foosball.games.tests.factories import GameFactory
from foosball.... | handle_login(client) |
Continue the code snippet: <|code_start|> )
total_played = models.PositiveIntegerField(
verbose_name=_("total played"),
help_text=_("Total games played in"),
default=0
)
singles_played = models.PositiveIntegerField(
verbose_name=_("singles played"),
help_text=_("To... | self.colour = random_colour() |
Predict the next line after this snippet: <|code_start|>
class MultiPlayerWidget(ModelSelect2MultipleWidget):
model = User
search_fields = [
'username__icontains',
'first_name__icontains',
'last_name__icontains',
'email__icontains',
]
def build_attrs(self, extra_attrs=... | model = Team |
Predict the next line after this snippet: <|code_start|> 'last_name__icontains',
'email__icontains',
]
def build_attrs(self, extra_attrs=None, **kwargs):
attrs = super().build_attrs(extra_attrs=extra_attrs, **kwargs)
attrs['data-maximum-selection-length'] = 2
return attrs... | model = Game |
Continue the code snippet: <|code_start|> return " - ".join(filter(None, [obj.username, obj.name]))
class TeamModelForm(forms.ModelForm):
class Meta:
model = Team
fields = ('score', 'players')
widgets = {
'players': MultiPlayerWidget,
'score': forms.Select(ch... | return super().is_valid() & clean_team_forms(self.forms['team1'], self.forms['team2']) |
Predict the next line after this snippet: <|code_start|>
def build_deployment_from_config(config_txt):
config = json.loads(config_txt)
if not 'metroId' in config:
return "no metroId provided"
if 'metro' in config:
metro_name = config['metro']
else:
metro_name = "N/A"
... | man_dep = ManagedDeployment.objects.get(source=source) |
Predict the next line after this snippet: <|code_start|> #html = html + 'published build_managed message<br>'
return response
def deploy_build_to_host(build, host):
exchange = Exchange("amq.direct", type="direct", durable=True)
conn = DjangoBrokerConnection()
publisher = conn.Producer(routing_key=... | for host in DeploymentHost.objects.all(): |
Using the snippet: <|code_start|>
def build_deployment_from_config(config_txt):
config = json.loads(config_txt)
if not 'metroId' in config:
return "no metroId provided"
if 'metro' in config:
metro_name = config['metro']
else:
metro_name = "N/A"
response = 'Metro #%s... | group = DeploymentGroup.objects.get(name="otpna") |
Given snippet: <|code_start|>
def build_deployment_from_config(config_txt):
config = json.loads(config_txt)
if not 'metroId' in config:
return "no metroId provided"
if 'metro' in config:
metro_name = config['metro']
else:
metro_name = "N/A"
response = 'Metro #%s (%s... | build = GraphBuild(deployment=man_dep, osm_key=man_dep.last_osm_key, config=config_txt) |
Predict the next line for this snippet: <|code_start|>
@permission_required('admin')
def index(request):
conn = connect_ec2(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_KEY)
reservations = conn.get_all_instances()
running_instances = []
for reservation in reservations:
for instance in... | image = AmazonMachineImage.objects.get(ami_id=instance.image_id) |
Continue the code snippet: <|code_start|>
## Global register for db commands that must be performed if
## processes are aborted
class database(sqlite3.Connection):
db_name = None
json_data = None
_mem_db = False
_db_com_register = {}
_lock = th.Lock()
@classmethod
def setup(cls, json_d... | raise CommandException("Can not register duplicate key") |
Here is a snippet: <|code_start|> if ack:
six.print_('Successful', typstr, 'open of',
lockopt['option'] +
'-locked concatenated tables',
tabname, ':', self.ncols(), 'column... | return (_add_prefix(self.name()) + "\n%d rows" % self.nrows() + |
Continue the code snippet: <|code_start|> in use in another process
`permanentwait`
as above, but wait until the lock is acquired.
`default`
this is the default option.
If the given table is already open, the locking option
in use is not changed. Otherwise it reverts to `auto`.
... | tabname = _remove_prefix(tablename) |
Using the snippet: <|code_start|> return int(self._nrows())
def __getattr__(self, name):
"""Get the tablecolumn object or keyword value.
| A tablecolumn object is returned if it names a column.
| The value of a keyword is returned if it names a keyword.
If the keyword is a... | if val != _do_remove_prefix(val): |
Predict the next line after this snippet: <|code_start|> if wait:
six.print_(" finished viewing")
tabledelete(tempname)
else:
six.print_(" after viewing use tabledelete('" +
... | rowout = _format_row(row, self.colnames(), self) |
Based on the snippet: <|code_start|># However, a mutual dependency is created when doing that for the tablerow
# object inside the table object.
# Therefore an intermediate _tablerow exists to be used in class table.
class _tablerow(TableRow):
def __init__(self, table, columnnames, exclude=False):
TableRow... | sei = _check_key_slice(key, nrows, 'tablerow') |
Next line prediction: <|code_start|>
| See `func:`tables.table.haslock` for more information.
| Locks are only used for images in casacore format. For other formats
(un)locking is a no-op, so this method always returns True.
"""
return self._unlock()
def subimage(self, bl... | return coordinatesystem(self._coordinates()) |
Given the following code snippet before the placeholder: <|code_start|># Convert Python value type to a glish-like type string
# as expected by the table code.
def _value_type_name(value):
if isinstance(value, bool):
return 'boolean'
if isinstance(value, integer_types):
return 'integer'
if i... | return quantity(val, unit).formatted('YMD_ONLY') |
Continue the code snippet: <|code_start|>
class ClusterKeysCommandMixin(KeysCommandMixin):
NODES_FLAGS = dict_merge(
{
'MOVE': NodeFlag.BLOCKED,
'RANDOMKEY': NodeFlag.RANDOM,
'SCAN': NodeFlag.ALL_MASTERS,
},
list_keys_to_dict(
['KEYS'],
NodeFl... | raise ResponseError("source and destination objects are the same") |
Using the snippet: <|code_start|> return await self.execute_command('RESTORE', *params)
async def sort(self, name, start=None, num=None, by=None, get=None,
desc=False, alpha=False, store=None, groups=False):
"""
Sorts and returns a list, set or sorted set at ``name``.
`... | raise RedisError("``start`` and ``num`` must both be specified") |
Predict the next line after this snippet: <|code_start|> pieces = [name]
if by is not None:
pieces.append(b('BY'))
pieces.append(by)
if start is not None and num is not None:
pieces.append(b('LIMIT'))
pieces.append(start)
pieces.append(n... | raise DataError('when using "groups" the "get" argument ' |
Predict the next line for this snippet: <|code_start|> Incrementally return lists of key names. Also return a cursor
indicating the scan position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
"""
pieces = [cur... | 'KEYS': merge_result, |
Given the following code snippet before the placeholder: <|code_start|> async def wait(self, num_replicas, timeout):
"""
Redis synchronous replication
That returns the number of replicas that processed the query when
we finally have at least ``num_replicas``, or when the ``timeout`` w... | 'MOVE': NodeFlag.BLOCKED, |
Next line prediction: <|code_start|> indicating the scan position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
"""
pieces = [cursor]
if match is not None:
pieces.extend([b('MATCH'), match])
... | 'RANDOMKEY': first_key, |
Based on the snippet: <|code_start|> """
Sorts and returns a list, set or sorted set at ``name``.
``start`` and ``num`` are for paginating sorted data
``by`` allows using an external key to weight and sort the items.
Use an "*" to indicate where in the key the item value is ... | pieces.append(b('BY')) |
Continue the code snippet: <|code_start|>
def sort_return_tuples(response, **options):
"""
If ``groups`` is specified, return the response as a list of
n-element tuples with n being the value found in options['groups']
"""
if not response or not options['groups']:
return response
n = op... | RESPONSE_CALLBACKS = dict_merge( |
Predict the next line after this snippet: <|code_start|>
def sort_return_tuples(response, **options):
"""
If ``groups`` is specified, return the response as a list of
n-element tuples with n being the value found in options['groups']
"""
if not response or not options['groups']:
return resp... | return int_or_none(response) |
Using the snippet: <|code_start|> return response
n = options['groups']
return list(zip(*[response[i::n] for i in range(n)]))
def parse_object(response, infotype):
"""Parse the results of an OBJECT command"""
if infotype in ('idletime', 'refcount'):
return int_or_none(response)
retu... | 'RENAME': bool_ok, |
Using the snippet: <|code_start|>
def sort_return_tuples(response, **options):
"""
If ``groups`` is specified, return the response as a list of
n-element tuples with n being the value found in options['groups']
"""
if not response or not options['groups']:
return response
n = options['g... | string_keys_to_dict( |
Given snippet: <|code_start|> we finally have at least ``num_replicas``, or when the ``timeout`` was
reached.
"""
return await self.execute_command('WAIT', num_replicas, timeout)
async def scan(self, cursor=0, match=None, count=None):
"""
Incrementally return lists of... | list_keys_to_dict( |
Continue the code snippet: <|code_start|> # the properly native Python value.
f = [nativestr]
f += [cast[o] for o in ['withdist', 'withhash', 'withcoord'] if options[o]]
return [
list(map(lambda fv: fv[0](fv[1]), zip(f, r))) for r in response_list
]
class GeoCommandMixin:
RESPONSE_CALL... | raise RedisError("GEOADD requires places with lon, lat and name" |
Predict the next line after this snippet: <|code_start|> count=count, sort=sort, store=store,
store_dist=store_dist)
async def georadiusbymember(self, name, member, radius, unit=None,
withdist=Fal... | pieces.append(b(token.upper())) |
Given the code snippet: <|code_start|>
def parse_georadius_generic(response, **options):
if options['store'] or options['store_dist']:
# `store` and `store_diff` cant be combined
# with other command arguments.
return response
if type(response) != list:
response_list = [respons... | return [nativestr(r) for r in response_list] |
Predict the next line after this snippet: <|code_start|> return await self.execute_command('HINCRBYFLOAT', name, key, amount)
async def hkeys(self, name):
"""Returns the list of keys within hash ``name``"""
return await self.execute_command('HKEYS', name)
async def hlen(self, name):
... | raise DataError("'hmset' with 'mapping' of length 0") |
Predict the next line after this snippet: <|code_start|> Sets key to value within hash ``name`` for each corresponding
key and value from the ``mapping`` dict.
"""
if not mapping:
raise DataError("'hmset' with 'mapping' of length 0")
items = []
for pair in iter... | pieces.extend([b('MATCH'), match]) |
Based on the snippet: <|code_start|>
def parse_hscan(response, **options):
cursor, r = response
return int(cursor), r and pairs_to_dict(r) or {}
class HashCommandMixin:
<|code_end|>
, predict the immediate next line with the help of imports:
from aredis.exceptions import DataError
from aredis.utils import ... | RESPONSE_CALLBACKS = dict_merge( |
Continue the code snippet: <|code_start|> async def hkeys(self, name):
"""Returns the list of keys within hash ``name``"""
return await self.execute_command('HKEYS', name)
async def hlen(self, name):
"""Returns the number of elements in hash ``name``"""
return await self.execute_... | for pair in iteritems(mapping): |
Next line prediction: <|code_start|> return await self.execute_command('HVALS', name)
async def hscan(self, name, cursor=0, match=None, count=None):
"""
Incrementallys return key/value slices in a hash. Also returns a
cursor pointing to the scan position.
``match`` allows fo... | 'HSCAN': first_key |
Predict the next line after this snippet: <|code_start|>
def parse_hscan(response, **options):
cursor, r = response
return int(cursor), r and pairs_to_dict(r) or {}
class HashCommandMixin:
RESPONSE_CALLBACKS = dict_merge(
<|code_end|>
using the current file's imports:
from aredis.exceptions import Dat... | string_keys_to_dict('HDEL HLEN', int), |
Here is a snippet: <|code_start|> return await self.execute_command('HLEN', name)
async def hset(self, name, key, value):
"""
Sets ``key`` to ``value`` within hash ``name``
Returns 1 if HSET created a new field, otherwise 0
"""
return await self.execute_command('HSET'... | args = list_or_args(keys, args) |
Predict the next line after this snippet: <|code_start|> await lock.release()
@pytest.mark.asyncio()
async def test_float_timeout(self, r):
lock = self.get_lock(r, 'foo', timeout=9.5)
assert await lock.acquire(blocking=False)
assert 8 < await r.pttl('foo') <= 9500
await l... | with pytest.raises(LockError): |
Predict the next line for this snippet: <|code_start|>
class TransactionCommandMixin:
RESPONSE_CALLBACKS = string_keys_to_dict(
'WATCH UNWATCH',
bool_ok
)
async def transaction(self, func, *watches, **kwargs):
"""
Convenience method for executing the callable `... | except WatchError: |
Predict the next line after this snippet: <|code_start|>
class TransactionCommandMixin:
RESPONSE_CALLBACKS = string_keys_to_dict(
'WATCH UNWATCH',
<|code_end|>
using the current file's imports:
import asyncio
import warnings
from aredis.exceptions import (RedisClusterException,
... | bool_ok |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
class TestStreams:
@skip_if_server_version_lt('4.9.103')
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_xadd_with_wrong_id(self, r):
<|code_end|>
with the help of current file imports:
import... | with pytest.raises(RedisError): |
Continue the code snippet: <|code_start|> await r.xadd('test_stream', {'k1': 'v1', 'k2': 1}, stream_id=idx,
max_len=10, approximate=False)
entries = await r.xrevrange('test_stream', count=5)
assert len(entries) == 5 and isinstance(entries, list) and isinstance(entries... | with pytest.raises(ResponseError) as exc: |
Given the following code snippet before the placeholder: <|code_start|>
The section option is not supported by older versions of Redis Server,
and will generate ResponseError
"""
if section is None:
return await self.execute_command('INFO')
else:
return aw... | raise RedisError("SHUTDOWN seems to have failed.") |
Here is a snippet: <|code_start|>
def parse_slowlog_get(response, **options):
return [{
'id': item[0],
'start_time': int(item[1]),
'duration': int(item[2]),
<|code_end|>
. Write the next line using the current file imports:
import datetime
from aredis.exceptions imp... | 'command': b(' ').join(item[3]) |
Next line prediction: <|code_start|> return res
def _parse_slave(response):
host, port, status, offset = response[1:]
return {
'role': role,
'host': host,
'port': port,
'status': status,
'offset': offset
}
def _parse_se... | 'SHUTDOWN SLAVEOF', bool_ok |
Given the code snippet: <|code_start|>
def parse_slowlog_get(response, **options):
return [{
'id': item[0],
'start_time': int(item[1]),
'duration': int(item[2]),
'command': b(' ').join(item[3])
} for item in response]
def parse_client_li... | for c in nativestr(response).splitlines(): |
Here is a snippet: <|code_start|> 'host': host,
'port': int(port),
'offset': int(offset)
})
return res
def _parse_slave(response):
host, port, status, offset = response[1:]
return {
'role': role,
'host': host... | RESPONSE_CALLBACKS = dict_merge( |
Predict the next line after this snippet: <|code_start|> 'port': int(port),
'offset': int(offset)
})
return res
def _parse_slave(response):
host, port, status, offset = response[1:]
return {
'role': role,
'host': host,
... | string_keys_to_dict('BGREWRITEAOF BGSAVE', lambda r: True), |
Given snippet: <|code_start|>
async def slowlog_len(self):
"""Gets the number of items in the slowlog"""
return await self.execute_command('SLOWLOG LEN')
async def slowlog_reset(self):
"""Removes all items in the slowlog"""
return await self.execute_command('SLOWLOG RESET')
... | list_keys_to_dict( |
Based on the snippet: <|code_start|>
def parse_slowlog_get(response, **options):
return [{
'id': item[0],
'start_time': int(item[1]),
'duration': int(item[2]),
'command': b(' ').join(item[3])
} for item in response]
def parse_client_list... | return response and pairs_to_dict(response) or {} |
Next line prediction: <|code_start|> """Gets the number of items in the slowlog"""
return await self.execute_command('SLOWLOG LEN')
async def slowlog_reset(self):
"""Removes all items in the slowlog"""
return await self.execute_command('SLOWLOG RESET')
async def time(self):
... | NodeFlag.BLOCKED |
Given snippet: <|code_start|> assert await r.zrevrangebylex('a', '(c', '-') == [b('b'), b('a')]
assert await r.zrevrangebylex('a', '(g', '[aaa') == \
[b('f'), b('e'), b('d'), b('c'), b('b')]
assert await r.zrevrangebylex('a', '+', '[f') == [b('g'), b('f')]
assert await r.zrevr... | with pytest.raises(RedisClusterException): |
Using the snippet: <|code_start|>
pytestmark = skip_if_server_version_lt('2.9.0')
async def redis_server_time(client):
t = await client.time()
seconds, milliseconds = list(t.values())[0]
timestamp = float('{0}.{1}'.format(seconds, milliseconds))
return datetime.datetime.fromtimestamp(timestamp)
clas... | with pytest.raises(ResponseError): |
Predict the next line for this snippet: <|code_start|> await r.rpush('a', '2', '3', '1')
assert await r.sort('a', get='user:*') == [b('u1'), b('u2'), b('u3')]
@pytest.mark.asyncio
async def test_sort_get_multi(self, r):
await r.flushdb()
await r.set('user:1', 'u1')
await ... | with pytest.raises(DataError): |
Here is a snippet: <|code_start|> @skip_if_redis_py_version_lt("2.10.2")
async def test_bitpos(self, r):
"""
Bitpos was added in redis-py in version 2.10.2
# TODO: Added b() around keys but i think they should not have to be
there for this command to work properly.
... | with pytest.raises(RedisError): |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
# python std lib
from __future__ import with_statement
# rediscluster imports
pytestmark = skip_if_server_version_lt('2.9.0')
async def redis_server_time(client):
t = await client.time()
seconds, milliseconds = list(t.values())[0]
timestamp = fl... | await r.zadd('a', a=0, b=0, c=0, d=0, e=0, f=0, g=0) |
Here is a snippet: <|code_start|> assert await r.get('a') == b('1')
assert await r.incrbyfloat('a', 1.1) == 2.1
assert float(await r.get('a')) == float(2.1)
@pytest.mark.asyncio
async def test_keys(self, r):
await r.flushdb()
keys = await r.keys()
assert keys == [... | for k, v in iteritems(d): |
Using the snippet: <|code_start|> await r.hmset('a', {'1': 1, '2': 2, '3': 3})
assert await r.hexists('a', '1')
assert not await r.hexists('a', '4')
@pytest.mark.asyncio
async def test_hgetall(self, r):
await r.flushdb()
h = {b('a1'): b('1'), b('a2'): b('2'), b('a3'): b('... | local_keys = list(iterkeys(h)) |
Here is a snippet: <|code_start|> await r.hmset('a', {'1': 1, '2': 2, '3': 3})
assert await r.hlen('a') == 3
@pytest.mark.asyncio
async def test_hmget(self, r):
await r.flushdb()
assert await r.hmset('a', {'a': 1, 'b': 2, 'c': 3})
assert await r.hmget('a', 'a', 'b', 'c') ... | local_vals = list(itervalues(h)) |
Predict the next line for this snippet: <|code_start|> @pytest.mark.asyncio
async def test_22_info(self):
"""
Older Redis versions contained 'allocation_stats' in INFO that
was the cause of a number of bugs when parsing.
"""
info = b"allocation_stats:6=1,7=1,8=7141,9=180,1... | parsed = parse_info(info) |
Next line prediction: <|code_start|>
@pytest.mark.asyncio
async def test_bitcount(self, r):
await r.flushdb()
await r.setbit('a', 5, True)
assert await r.bitcount('a') == 1
await r.setbit('a', 6, True)
assert await r.bitcount('a') == 2
await r.setbit('a', 5, False... | @skip_if_redis_py_version_lt("2.10.2") |
Given the code snippet: <|code_start|>
class ConnectionCommandMixin:
RESPONSE_CALLBACKS = {
'AUTH': bool,
'PING': lambda r: nativestr(r) == 'PONG',
'SELECT': bool_ok,
}
async def echo(self, value):
"Echo the string back from the server"
return await self.execute_co... | 'PING': NodeFlag.ALL_NODES, |
Given the code snippet: <|code_start|>
class ConnectionCommandMixin:
RESPONSE_CALLBACKS = {
'AUTH': bool,
'PING': lambda r: nativestr(r) == 'PONG',
<|code_end|>
, generate the next line using the imports in this file:
from aredis.utils import (NodeFlag,
bool_ok,
... | 'SELECT': bool_ok, |
Given snippet: <|code_start|>
class ConnectionCommandMixin:
RESPONSE_CALLBACKS = {
'AUTH': bool,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from aredis.utils import (NodeFlag,
bool_ok,
nativestr)
and context:
#... | 'PING': lambda r: nativestr(r) == 'PONG', |
Next line prediction: <|code_start|>
:start: and :num:
are for paging through the sorted data
:by:
allows using an external key to weight and sort the items.
Use an "*" to indicate where in the key the item value is located
:get:
is for returning... | data_type = b(await self.type(name)) |
Given snippet: <|code_start|>
class ListsCommandMixin:
RESPONSE_CALLBACKS = dict_merge(
string_keys_to_dict(
'BLPOP BRPOP',
lambda r: r and tuple(r) or None
),
string_keys_to_dict(
# these return OK, or int if redis-server is >=1.3.4
'LPUSH R... | string_keys_to_dict('LSET LTRIM', bool_ok), |
Continue the code snippet: <|code_start|>
class ListsCommandMixin:
RESPONSE_CALLBACKS = dict_merge(
string_keys_to_dict(
'BLPOP BRPOP',
lambda r: r and tuple(r) or None
),
string_keys_to_dict(
# these return OK, or int if redis-server is >=1.3.4
... | lambda r: isinstance(r, int) and r or nativestr(r) == 'OK' |
Given the following code snippet before the placeholder: <|code_start|> if by is not None:
# _sort_using_by_arg mutates data so we don't
# need need a return value.
data = await self._sort_using_by_arg(data, by, alpha)
elif not alpha:
... | raise DataError('when using "groups" the "get" argument ' |
Predict the next line for this snippet: <|code_start|> is for returning items from external keys rather than the
sorted data itself. Use an "*" to indicate where int he key
the item value is located
:desc:
is for reversing the sort
:alpha:
is... | raise RedisClusterException("Unable to sort data type : {0}".format(data_type)) |
Here is a snippet: <|code_start|> async def sort(self, name, start=None, num=None, by=None, get=None, desc=False, alpha=False, store=None, groups=None):
"""Sorts and returns a list, set or sorted set at ``name``.
:start: and :num:
are for paging through the sorted data
:by:
... | raise RedisError("RedisError: ``start`` and ``num`` must both be specified") |
Here is a snippet: <|code_start|> Check if a script exists in the script cache by specifying the SHAs of
each script as ``args``. Returns a list of boolean values indicating if
if each already script exists in the cache.
"""
return await self.execute_command('SCRIPT EXISTS', *args... | NODES_FLAGS = dict_merge( |
Given snippet: <|code_start|>
class ScriptingCommandMixin:
RESPONSE_CALLBACKS = {
'SCRIPT EXISTS': lambda r: list(map(bool, r)),
'SCRIPT FLUSH': bool_ok,
'SCRIPT KILL': bool_ok,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from aredis.utils import (d... | 'SCRIPT LOAD': nativestr, |
Given snippet: <|code_start|> return await self.execute_command('SCRIPT EXISTS', *args)
async def script_flush(self):
"""Flushes all scripts from the script cache"""
return await self.execute_command('SCRIPT FLUSH')
async def script_kill(self):
"""Kills the currently executing L... | list_keys_to_dict( |
Continue the code snippet: <|code_start|> if each already script exists in the cache.
"""
return await self.execute_command('SCRIPT EXISTS', *args)
async def script_flush(self):
"""Flushes all scripts from the script cache"""
return await self.execute_command('SCRIPT FLUSH')
... | 'SCRIPT KILL': NodeFlag.BLOCKED |
Here is a snippet: <|code_start|>
class ScriptingCommandMixin:
RESPONSE_CALLBACKS = {
'SCRIPT EXISTS': lambda r: list(map(bool, r)),
<|code_end|>
. Write the next line using the current file imports:
from aredis.utils import (dict_merge, nativestr,
list_keys_to_dict,
... | 'SCRIPT FLUSH': bool_ok, |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.