Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Here is a snippet: <|code_start|>
def isBeatmap(fileName=None, content=None):
if fileName is not None:
with open(fileName, "rb") as f:
firstLine = f.readline().decode("utf-8-sig").strip()
elif content is not None:
try:
<|code_end|>
. Write the next line using the current file impor... | firstLine = content.decode("utf-8-sig").split("\n")[0].strip() |
Based on the snippet: <|code_start|>
MODULE_NAME = "ez"
stats = {
"latency": {
gameModes.STD: {
"classic": glob.stats["pp_calc_latency_seconds"].labels(game_mode="std", relax="0"),
"relax": glob.stats["pp_calc_latency_seconds"].labels(game_mode="std", relax="1")
},
gameModes.TAIKO: {
"classic": glob.... | "failures": { |
Given the following code snippet before the placeholder: <|code_start|>
MODULE_NAME = "ez"
stats = {
"latency": {
gameModes.STD: {
"classic": glob.stats["pp_calc_latency_seconds"].labels(game_mode="std", relax="0"),
"relax": glob.stats["pp_calc_latency_seconds"].labels(game_mode="std", relax="1")
},
gam... | } |
Given the code snippet: <|code_start|>
MODULE_NAME = "ez"
stats = {
"latency": {
gameModes.STD: {
"classic": glob.stats["pp_calc_latency_seconds"].labels(game_mode="std", relax="0"),
"relax": glob.stats["pp_calc_latency_seconds"].labels(game_mode="std", relax="1")
},
<|code_end|>
, generate the next line ... | gameModes.TAIKO: { |
Predict the next line for this snippet: <|code_start|>
stats = {
"latency": {
"classic":glob.stats["pp_calc_latency_seconds"].labels(game_mode="ctb", relax="0"),
"relax": glob.stats["pp_calc_latency_seconds"].labels(game_mode="ctb", relax="1")
},
"failures": {
"classic": glob.stats... | } |
Predict the next line for this snippet: <|code_start|> mapFile = mapsHelper.cachedMapPath(self.beatmap.beatmapID)
mapsHelper.cacheMap(mapFile, self.beatmap)
# TODO: Sanizite mods
# Gamemode check
if self.score is not None and self.score.gameMode != gameModes.... | diff=difficulty, |
Next line prediction: <|code_start|>stats = {
"latency": {
"classic":glob.stats["pp_calc_latency_seconds"].labels(game_mode="ctb", relax="0"),
"relax": glob.stats["pp_calc_latency_seconds"].labels(game_mode="ctb", relax="1")
},
"failures": {
"classic": glob.stats["pp_calc_failures"].... | if self.combo is None or self.combo < 0: |
Given snippet: <|code_start|>
class Data():
pass
def _resolveRefs(symdict, arg):
gens = _flatten(arg)
data = Data()
data.symdict = symdict
v = _AttrRefTransformer(data)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import ast
import itertools
from types imp... | for gen in gens: |
Given the following code snippet before the placeholder: <|code_start|>
def test_auc_for_one_positive():
assert auc_for_one_positive(1, [0, 2]) == 0.5
assert auc_for_one_positive(1, [1]) == 0.5
assert auc_for_one_positive(3, [0]) == 1.0
assert auc_for_one_positive(0, [3]) == 0.0
<|code_end|>
, predi... | @given(st.lists(st.floats(allow_nan=False, allow_infinity=False), min_size=1), st.floats(allow_nan=False, allow_infinity=False)) |
Given snippet: <|code_start|>from __future__ import print_function, division, absolute_import, unicode_literals
def sample_batch_fixations(log_density, fixations_per_image, batch_size, rst=None):
xs, ys = sample_from_logdensity(log_density, fixations_per_image * batch_size, rst=rst)
<|code_end|>
, continue by ... | ns = np.repeat(np.arange(batch_size, dtype=int), repeats=fixations_per_image) |
Given the code snippet: <|code_start|>
assert skew(fixations_val.x) == approx(0.11714467225615313)
assert skew(fixations_val.y) == approx(0.12631245881037118)
assert skew(fixations_val.t) == approx(1.8301317514860862)
assert skew(fixations_val.lengths) == approx(0.0)
assert entropy(fixations_val.n)... | assert np.std(fixations_train.y) == approx(93.55417139372516) |
Here is a snippet: <|code_start|>
class TestPatchFile(TestWithData):
def test_parsing(self):
p = open('tests/test_quilt/patches/add_numbers.diff').read()
patch = PatchFile(p)
self.assertEqual(len(patch.diffs), 1)
diff = patch.diffs[0]
self.assertEqual(len(diff.hunks), 1)
... | shallow=False)) |
Predict the next line after this snippet: <|code_start|> diff = patch.diffs[0]
self.assertEqual(len(diff.hunks), 1)
self.assertEqual(diff.source_filename, 'source.txt')
self.assertEqual(diff.target_filename, 'source.txt')
hunk = diff.hunks[0]
self.assertEqual(hunk.source_... | location = os.path.join(self.data_path, 'patching') |
Predict the next line after this snippet: <|code_start|>class ConstantSaliencyModel(pysaliency.Model):
def _log_density(self, stimulus):
return np.zeros((stimulus.shape[0], stimulus.shape[1])) - np.log(stimulus.shape[0]) - np.log(stimulus.shape[1])
class GaussianSaliencyModel(pysaliency.Model):
def _l... | [0, 200, 600], |
Next line prediction: <|code_start|> [False, False, False, False, False, True, True, True, False]),
([True, True, True, True, True, True, True, True, False],
[False, False, False, False, False, False, False, False, True])
]
X = fixations_to_scikit_learn(fixation_trains, normalize=stimu... | X, |
Using the snippet: <|code_start|> [True, True, True, True, True, False, False, False, False]),
([True, True, True, True, True, False, False, False, True],
[False, False, False, False, False, True, True, True, False]),
([True, True, True, True, True, True, True, True, False],
[F... | assert cross_val_score( |
Predict the next line for this snippet: <|code_start|>from __future__ import absolute_import, division, print_function, unicode_literals
class ConstantSaliencyModel(pysaliency.Model):
def _log_density(self, stimulus):
return np.zeros((stimulus.shape[0], stimulus.shape[1])) - np.log(stimulus.shape[0]) -... | [2, 2], |
Predict the next line for this snippet: <|code_start|> ts_trains = [
[0, 200, 600],
[100, 400],
[50, 500, 900]]
ns = [0, 0, 1]
subjects = [0, 1, 1]
return pysaliency.FixationTrains.from_fixation_trains(xs_trains, ys_trains, ts_trains, ns, subjects)
@pytest.fixture
def stimuli():... | [0, 1, 0]])) |
Next line prediction: <|code_start|> [22, 5, 18]]
ts_trains = [
[0, 200, 600],
[100, 400],
[50, 500, 900]]
ns = [0, 0, 1]
subjects = [0, 1, 1]
return pysaliency.FixationTrains.from_fixation_trains(xs_trains, ys_trains, ts_trains, ns, subjects)
@pytest.fixture
def stimuli... | [0, 2, 2], |
Here is a snippet: <|code_start|> train_ts = np.vstack(train_ts)
train_ns = np.hstack(train_ns)
train_subjects = np.hstack(train_subjects)
full_nonfixations = type(self)(train_xs, train_ys, train_ts, train_ns, train_subjects)
self.full_nonfixations = full_nonfixations
retu... | train_ts[train_index][i] = self.t[new_fix_index] |
Using the snippet: <|code_start|> """Return dictionary of optimization parameters from vector x.
The non-optimization parameters will be taken from the initial values.
if return_list==True, return a list instead of an dictionary"""
params = self.param_values.copy()
index = 0... | def get_length(self, param_name): |
Using the snippet: <|code_start|> rst = np.random.RandomState(42)
inds = []
k_fold = StratifiedKFold(n_splits=split_count, shuffle=random, random_state=rst)
for i, (train_index, test_index) in enumerate(k_fold.split(X, labels)):
if i in included_splits:
inds.extend(test_index)
s... | else: |
Continue the code snippet: <|code_start|>
def sample_batch_fixations(log_density, fixations_per_image, batch_size, rst=None):
xs, ys = sample_from_logdensity(log_density, fixations_per_image * batch_size, rst=rst)
ns = np.repeat(np.arange(batch_size, dtype=int), repeats=fixations_per_image)
return xs, ys... | def step(self, closure=None): |
Given the code snippet: <|code_start|>
def sample_batch_fixations(log_density, fixations_per_image, batch_size, rst=None):
xs, ys = sample_from_logdensity(log_density, fixations_per_image * batch_size, rst=rst)
ns = np.repeat(np.arange(batch_size, dtype=int), repeats=fixations_per_image)
return xs, ys, n... | super(DistributionSGD, self).__init__(params, defaults) |
Using the snippet: <|code_start|>
def test_fixation_sampling():
class SamplingModel(SamplingModelMixin, GaussianSaliencyMapModel):
def sample_fixation(self, stimulus, x_hist, y_hist, t_hist, attributes=None, verbose=False, rst=None):
return x_hist[-1] + 1, y_hist[-1] + 1, t_hist[-1] + 1
m... | list(x_hist) + [x_hist[-1]] * samples, |
Next line prediction: <|code_start|>
def test_fixation_sampling():
class SamplingModel(SamplingModelMixin, GaussianSaliencyMapModel):
def sample_fixation(self, stimulus, x_hist, y_hist, t_hist, attributes=None, verbose=False, rst=None):
<|code_end|>
. Use current file imports:
(import numpy as np
from py... | return x_hist[-1] + 1, y_hist[-1] + 1, t_hist[-1] + 1 |
Predict the next line after this snippet: <|code_start|>
def test_fixation_sampling():
class SamplingModel(SamplingModelMixin, GaussianSaliencyMapModel):
def sample_fixation(self, stimulus, x_hist, y_hist, t_hist, attributes=None, verbose=False, rst=None):
return x_hist[-1] + 1, y_hist[-1] + 1... | x, y, t = model.sample_fixation(np.zeros((40, 40, 3)), [0], [1], [2]) |
Next line prediction: <|code_start|>
dataset_config_schema = Schema({
'stimuli': str,
'fixations': str,
Optional('filters', default=[]): [{
'type': str,
Optional('parameters', default={}): dict,
}],
})
def load_dataset_from_config(config):
config = dataset_config_schema.validate(... | def apply_dataset_filter_config(stimuli, fixations, filter_config): |
Given the code snippet: <|code_start|>def load_dataset_from_config(config):
config = dataset_config_schema.validate(config)
stimuli = read_hdf5(config['stimuli'])
fixations = read_hdf5(config['fixations'])
for filter_config in config['filters']:
stimuli, fixations = apply_dataset_filter_config(... | def wrapped(stimuli, fixations, **kwargs): |
Using the snippet: <|code_start|>
dataset_config_schema = Schema({
'stimuli': str,
'fixations': str,
Optional('filters', default=[]): [{
'type': str,
Optional('parameters', default={}): dict,
}],
})
def load_dataset_from_config(config):
config = dataset_config_schema.validate(con... | return stimuli, fixations |
Given the code snippet: <|code_start|>
dataset_config_schema = Schema({
'stimuli': str,
'fixations': str,
Optional('filters', default=[]): [{
'type': str,
Optional('parameters', default={}): dict,
}],
})
def load_dataset_from_config(config):
config = dataset_config_schema.validat... | return stimuli, fixations |
Given snippet: <|code_start|> config = dataset_config_schema.validate(config)
stimuli = read_hdf5(config['stimuli'])
fixations = read_hdf5(config['fixations'])
for filter_config in config['filters']:
stimuli, fixations = apply_dataset_filter_config(stimuli, fixations, filter_config)
return ... | new_fixations = fn(fixations, **kwargs) |
Continue the code snippet: <|code_start|>
DURATION_PATTERN = r'^((?P<hours>\d+)h)?((?P<minutes>\d+)m)?((?P<seconds>\d+)s)?$'
TIME_FORMAT = r'%Y-%m-%dT%H:%M:%S%z'
def utcnow() -> datetime.datetime:
return datetime.datetime.now(datetime.timezone.utc)
def parse_duration_to_time(duration: str) -> datetime.datetim... | ) |
Predict the next line after this snippet: <|code_start|>
DURATION_PATTERN = r'^((?P<hours>\d+)h)?((?P<minutes>\d+)m)?((?P<seconds>\d+)s)?$'
TIME_FORMAT = r'%Y-%m-%dT%H:%M:%S%z'
def utcnow() -> datetime.datetime:
return datetime.datetime.now(datetime.timezone.utc)
def parse_duration_to_time(duration: str) -> d... | delta = datetime.timedelta( |
Here is a snippet: <|code_start|>
def utcnow() -> datetime.datetime:
return datetime.datetime.now(datetime.timezone.utc)
def parse_duration_to_time(duration: str) -> datetime.datetime:
match = re.match(DURATION_PATTERN, duration)
if match is None:
raise ValueError(
f"Unknown duration f... | the queue for processing. |
Based on the snippet: <|code_start|>
if TYPE_CHECKING:
TIME_FORMAT = '%Y-%m-%d %H:%M:%S.%f'
class Job:
def __init__(
self,
path: str,
args: Tuple[Any, ...],
kwargs: Dict[str, Any],
timeout: Optional[int] = None,
sigkill_on_stop: bool = False,
) -> None:
... | self.timeout = timeout |
Here is a snippet: <|code_start|> self.sigkill_on_stop = sigkill_on_stop
self.created_time = datetime.datetime.utcnow()
self._json = None # type: Optional[str]
def __repr__(self) -> str:
return "<Job: {}(*{!r}, **{!r}) @ {}>".format(
self.path,
self.args,
... | return job |
Next line prediction: <|code_start|>
TIME_FORMAT = '%Y-%m-%d %H:%M:%S.%f'
class Job:
def __init__(
self,
path: str,
args: Tuple[Any, ...],
kwargs: Dict[str, Any],
timeout: Optional[int] = None,
sigkill_on_stop: bool = False,
) -> None:
self.path = path
... | @classmethod |
Predict the next line for this snippet: <|code_start|>
if TYPE_CHECKING:
TIME_FORMAT = '%Y-%m-%d %H:%M:%S.%f'
class Job:
def __init__(
<|code_end|>
with the help of current file imports:
import sys
import json
import time
import datetime
import warnings
from typing import Any, Dict, Tuple, Callable, Optional... | self, |
Predict the next line for this snippet: <|code_start|>
class Command(BaseCommand):
help = "Command to deduplicate tasks in a redis-backed queue" # noqa:A003 # inherited name
def add_arguments(self, parser: CommandParser) -> None:
parser.add_argument(
'queue',
action='store',
... | "No duplicate jobs detected (queue length remains {})".format( |
Based on the snippet: <|code_start|>class Command(BaseCommand):
help = "Command to deduplicate tasks in a redis-backed queue" # noqa:A003 # inherited name
def add_arguments(self, parser: CommandParser) -> None:
parser.add_argument(
'queue',
action='store',
help="The... | ), |
Continue the code snippet: <|code_start|>
T = TypeVar('T')
class Command(BaseCommand):
help = "Command to deduplicate tasks in a redis-backed queue" # noqa:A003 # inherited name
def add_arguments(self, parser: CommandParser) -> None:
parser.add_argument(
'queue',
action='st... | "Configured backend '{}.{}' doesn't support deduplication".format( |
Given snippet: <|code_start|> args: Tuple[Any, ...] = ('args',),
kwargs: Optional[Dict[str, Any]] = None,
timeout: Optional[int] = None,
sigkill_on_stop: bool = False,
created_time: Optional[datetime.datetime] = None,
) -> Job:
if created_time is None:
crea... | "Identities should match", |
Next line prediction: <|code_start|>def update_pk_argument(field_name, rdtype):
def add_update_pk_argument(parser, **kwargs):
parser.add_argument(
'--pk', required=True, default=None, type=int,
dest='pk', help="The database integer primary key (id) of the "
"{0} you are u... | def delete_pk_argument(field_name, rdtype): |
Here is a snippet: <|code_start|>
def build_extractor(field_name, nas_name):
def extractor(nas):
if not getattr(nas, nas_name):
return {}
data = {field_name: getattr(nas, nas_name)}
return data
return extractor
def extract_pk(nas, field_name):
return {field_name: geta... | def update_pk_argument(field_name, rdtype): |
Given the following code snippet before the placeholder: <|code_start|> __import__(d)
def do_dispatch(args, IN=sys.stdin):
inv_parser = argparse.ArgumentParser(prog='invtool')
format_group = inv_parser.add_mutually_exclusive_group()
format_group.add_argument(
'--json', default=False, dest='p_j... | nas = inv_parser.parse_args(args) |
Continue the code snippet: <|code_start|> 'invtool.kv.kv_sreg_dispatch',
'invtool.system_dispatch',
'invtool.csv_dispatch',
'invtool.ba_dispatch',
'invtool.sreg_dispatch',
'invtool.decommission_dispatch',
'invtool.service_dispatch'
]
for d in enabled_dispatches:
__import__(d)
def do_d... | '--pk-only', default=False, dest='p_pk_only', action='store_true', |
Next line prediction: <|code_start|> parser.add_argument(
'--domain', default=None, type=str, dest='domain',
help="The domain a record is in.", required=False)
def domain_argument(field_name):
def extract_domain(nas):
data = {}
if nas.domain:
data.update({field_name:... | parser.add_argument( |
Given the code snippet: <|code_start|> "used and is analigouse to using '@' in a zone file (the record "
"will get it's domain's name as it's fqdn).", required=False
)
def fqdn_argument(field_name, rdtype):
# We need rdtype because SRV requires a '_' to prefix it's test data
def add_fqdn_ar... | parser.add_argument( |
Next line prediction: <|code_start|> '--ip', default=None, type=str, dest='ip',
help="A string representation of an IP address.",
required=required
)
def test_data():
if ip_type == '4':
return 'ip', TEST_IPv4()
elif ip_type == '6':
... | '--{0}'.format('name'), type=str, |
Here is a snippet: <|code_start|> def add_text_argument(parser, required=True):
parser.add_argument(
'--text', default=None, type=str, dest='text',
help="The text data.", required=required
)
def test_data():
return 'text', TEST_TEXT
return add_text_argument, ... | def key_argument(field_name): |
Predict the next line after this snippet: <|code_start|>
def view_arguments(field_name):
def add_view_arguments(parser, required=False):
pri_group = parser.add_mutually_exclusive_group()
pri_group.add_argument('--no-private', default=False,
action='store_true', dest=... | pub_group.add_argument('--public', default=False, action='store_true', |
Predict the next line for this snippet: <|code_start|> action='store_true', dest='no_public',
help="Disable public view.", required=required)
pub_group.add_argument('--public', default=False, action='store_true',
dest='... | help="The domain a record is in.", required=False) |
Continue the code snippet: <|code_start|>
pri_group.add_argument('--no-private', default=False,
action='store_true', dest='no_private',
help="Disable private view.", required=required)
pri_group.add_argument('--private', default=False, actio... | data = {field_name: views} |
Based on the snippet: <|code_start|> help="Disable private view.", required=required)
pri_group.add_argument('--private', default=False, action='store_true',
dest='private', help="Enabled private view.",
required=False)... | def test_data(): |
Given the following code snippet before the placeholder: <|code_start|> if nas.ttl:
data['ttl'] = nas.ttl
return data
def test_data():
return 'ttl', TEST_TTL
return add_ttl_argument, build_extractor(field_name, 'ttl'), test_data
def key_argument(field_name):
def add_ke... | parser.add_argument( |
Given snippet: <|code_start|> parser, 'ttl', 'ttl', "The ttl of a record.", required=False
)
def extract_ttl(nas):
data = {}
if nas.ttl:
data['ttl'] = nas.ttl
return data
def test_data():
return 'ttl', TEST_TTL
return add_ttl_argument, build_... | return parser |
Predict the next line after this snippet: <|code_start|>
def name_argument(field_name, prefix='nic'):
def add_com_arg(parser, required=False, **kwargs):
parser.add_argument(
'--{0}'.format('name'), type=str,
dest='name', help="A short name",
required=required
)
... | def add_ttl_argument(parser, **kwargs): |
Next line prediction: <|code_start|> def add_fqdn_argument(parser, required=True):
parser.add_argument(
'--fqdn', default="", type=str, dest='fqdn',
help="The FQDN of the record being created. If you use this "
"option you cannot use label or domain", required=required
... | return 'system-hostname', 'toolsdev1.dmz.scl3.mozilla.com' |
Next line prediction: <|code_start|>
def name_argument(field_name, required=False):
def add_name_arg(parser, required=required, **kwargs):
parser.add_argument(
'--{0}'.format(field_name), type=str,
dest=field_name, help="A name.",
required=required
)
<|code_end|... | def test_data(): |
Predict the next line for this snippet: <|code_start|> )
def extract_arg(nas):
data = {}
if nas.vlan:
data = {field_name: nas.vlan}
return data
def test_data():
# vlan will need to be evaluated in at test time
return 'vlan-pk', '{{ vlan }}'
retur... | return 'site-pk', '{{ site }}' |
Continue the code snippet: <|code_start|> parser.add_argument(
'--{0}'.format(field_name), type=str,
dest=field_name, help="A name.",
required=required
)
def test_data():
return field_name, TEST_NAME() # Reuse this test data
return add_name_arg, buil... | def add_network_argument(parser, required=required): |
Predict the next line for this snippet: <|code_start|>
def name_argument(field_name, required=False):
def add_name_arg(parser, required=required, **kwargs):
parser.add_argument(
'--{0}'.format(field_name), type=str,
dest=field_name, help="A name.",
required=required
... | def test_data(): |
Given the code snippet: <|code_start|> return data
return extractor
return (
add_network_argument,
build_extractor('network_str', 'network_str'),
test_data
)
def vlan_argument(field_name):
def add_argument(parser, required=False):
parser.add_argument(
... | def site_argument(field_name): |
Using the snippet: <|code_start|> extractor = build_extractor(field_name, field_name)
return add_group_argument, extractor, test_data
def mac_argument(field_name):
def add_com_arg(parser, required=True, **kwargs):
parser.add_argument(
'--{0}'.format(field_name), default="", type=str,
... | ) |
Here is a snippet: <|code_start|> help="Enabled dhcp (True by default).", required=required
)
def test_data():
return '', '--no-dhcp'
extractor = build_extractor(field_name, 'enable_dhcp')
return add_enable_dhcp_argument, extractor, test_data
def sreg_argument(field_name):
... | data = {field_name: sreg} |
Based on the snippet: <|code_start|> nas, resp_msg, "http_status: 202 (Accepted)"
)
elif resp.status_code == 200:
return 0, self.format_response(
nas, resp_msg, "http_status: 200 (Success)"
)
elif resp.status_code == 401:
ret... | return 1, errors |
Given the following code snippet before the placeholder: <|code_start|> return self.action(nas, url, requests.post, data)
def action(self, nas, url, method, data, form_encode=True):
headers = {'content-type': 'application/json'}
if form_encode:
wire_data = json.dumps(data, indent... | object_url = None # fill me in |
Here is a snippet: <|code_start|> )
elif resp.status_code == 202:
return 0, self.format_response(
nas, resp_msg, "http_status: 202 (Accepted)"
)
elif resp.status_code == 200:
return 0, self.format_response(
nas, resp_msg, "ht... | else: |
Next line prediction: <|code_start|> return 1, resp_list
def delete(self, nas):
url = "{0}{1}?format=json".format(REMOTE, self.delete_url(nas))
headers = {'content-type': 'application/json'}
resp = requests.delete(url, headers=headers, auth=auth())
return self.handle_resp(nas... | if form_encode: |
Predict the next line after this snippet: <|code_start|> "Auth Failure! Check your password, or update your keychain "
"using inv-tool/scripts/reset_keychain.py"
]
else:
resp_list = []
resp_list.append("Client didn't understand the response.")
... | msg['http_status'] = resp.status_code |
Here is a snippet: <|code_start|> self.dtype,
help="Interface for {0}s".format(self.dtype),
add_help=True
)
action_parser = record_base_parser.add_subparsers(
help="{0} actions".format(self.dtype),
dest='action'
)
build_create_pa... | return self.object_list_url.format( |
Continue the code snippet: <|code_start|> # Bad Request
if nas.p_json:
if resp_msg:
return 1, [json.dumps(resp_msg, indent=2)]
else:
return 1, [json.dumps({'errors': resp.content}, indent=2)]
else:
... | elif resp.status_code == 401: |
Based on the snippet: <|code_start|>try:
except ImportError:
class Dispatch(object):
def format_response(self, nas, resp_msg, user_msg):
resp_list = []
if nas.p_json:
resp_list.append(json.dumps(resp_msg, indent=2))
else:
resp_list.append(user_msg)
for ... | if resp.status_code == 404: |
Predict the next line for this snippet: <|code_start|> def test_search():
expected_status, command = commands[0]
ret, errors, rc = call_to_json(command)
if errors:
self.fail(errors)
self.assertEqual(0, rc)
... | def test_csv_export(): |
Based on the snippet: <|code_start|> expected_status, command = commands[1]
ret, errors, rc = call_to_json(command)
if errors:
self.fail(errors)
self.assertEqual(0, rc)
self.assertTrue('http_status' in ret)
... | setattr(_TestCase, test_name, place_holder) |
Given the code snippet: <|code_start|>try:
except ImportError:
class DispatchSystem(CoreDispatch):
object_url = "/en-US/core/api/v1_core/{1}/{2}/"
<|code_end|>
, generate the next line using the imports in this file:
import simplejson as json
import json # noqa
from invtool.lib.registrar import regis... | object_list_url = "/en-US/core/api/v1_core/{1}/" |
Here is a snippet: <|code_start|>
def foreign_key_argument(field_name, help):
real_fname = field_name.replace('-', '_')
def add_srt_arg(parser, **kwargs):
parser.add_argument(
'--{0}-pk'.format(field_name), default="", type=str,
dest=real_fname, required=False, help=help
... | dest='hostname', required=False, help='If you are changing the ' |
Given the code snippet: <|code_start|>
def foreign_key_argument(field_name, help):
real_fname = field_name.replace('-', '_')
def add_srt_arg(parser, **kwargs):
parser.add_argument(
'--{0}-pk'.format(field_name), default="", type=str,
dest=real_fname, required=False, help=help
... | dest='hostname', required=False, help='If you are changing the ' |
Given the code snippet: <|code_start|>
def update_pk_argument(field_name, dtype):
display_name = field_name.replace('_', '-')
def add_update_pk_argument(parser, **kwargs):
parser.add_argument(
'--{0}'.format(display_name), required=True,
default=None, type=int, dest=field_name,... | return add_update_pk_argument, _extract_pk, test_data |
Based on the snippet: <|code_start|>def detail_pk_argument(field_name, dtype):
display_name = field_name.replace('_', '-')
def add_detail_pk_argument(parser, **kwargs):
parser.add_argument(
'--{0}'.format(display_name), required=True,
default=None, type=int, dest=field_name, hel... | return parser |
Here is a snippet: <|code_start|>
class MockTunnelled:
def __init__(self, base_cmd: list, target: str):
pass
def command(self, cmd, **kwargs):
return b''
def copy_file(self, src, dst):
pass
@contextmanager
<|code_end|>
. Write the next line using the current file imports:
impo... | def mocked_context(*args, **kwargs): |
Based on the snippet: <|code_start|>
@pytest.fixture
def aws_onprem_with_extra_volumes_config_path(tmpdir, mocked_aws_cfstack_bare_cluster):
return get_temp_config_path(tmpdir, 'aws-onprem-with-extra-volumes.yaml')
@pytest.fixture
def aws_onprem_with_extra_iam_config_path(tmpdir, mocked_aws_cfstack_bare_cluster)... | - 8.8.8.8 |
Given the following code snippet before the placeholder: <|code_start|>
app_name = 'admin'
urlpatterns = [
url(r'^$', views.NodeSearchView.as_view(), name='search'),
url(r'^flagged_spam$', views.NodeFlaggedSpamList.as_view(), name='flagged-spam'),
url(r'^known_spam$', views.NodeKnownSpamList.as_view(), nam... | name='restart-stuck-registrations'), |
Predict the next line after this snippet: <|code_start|>
class NodeMixin(PermissionRequiredMixin):
def get_object(self):
return AbstractNode.objects.filter(
guids___id=self.kwargs['guid']
).annotate(
guid=F('guids___id'),
public_cap=Case(
Wh... | then=F('custom_storage_usage_limit_public'), |
Next line prediction: <|code_start|>
class NodeMixin(PermissionRequiredMixin):
def get_object(self):
return AbstractNode.objects.filter(
guids___id=self.kwargs['guid']
).annotate(
<|code_end|>
. Use current file imports:
(import pytz
from datetime import datetime
from framework i... | guid=F('guids___id'), |
Using the snippet: <|code_start|>
class NodeMixin(PermissionRequiredMixin):
def get_object(self):
return AbstractNode.objects.filter(
guids___id=self.kwargs['guid']
).annotate(
guid=F('guids___id'),
public_cap=Case(
When(
... | When( |
Using the snippet: <|code_start|>
class NodeMixin(PermissionRequiredMixin):
def get_object(self):
return AbstractNode.objects.filter(
<|code_end|>
, determine the next line of code. You have imports:
import pytz
from datetime import datetime
from framework import status
from django.utils import time... | guids___id=self.kwargs['guid'] |
Continue the code snippet: <|code_start|>
def get_object(self):
return AbstractNode.objects.filter(
guids___id=self.kwargs['guid']
).annotate(
guid=F('guids___id'),
public_cap=Case(
When(
custom_storage_usage_limit_public=None,
... | def get_success_url(self): |
Given the code snippet: <|code_start|>
class NodeMixin(PermissionRequiredMixin):
def get_object(self):
return AbstractNode.objects.filter(
guids___id=self.kwargs['guid']
<|code_end|>
, generate the next line using the imports in this file:
import pytz
from datetime import datetime
from f... | ).annotate( |
Given snippet: <|code_start|>
class NodeMixin(PermissionRequiredMixin):
def get_object(self):
return AbstractNode.objects.filter(
guids___id=self.kwargs['guid']
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytz
from datetime import datetime
f... | ).annotate( |
Here is a snippet: <|code_start|>
class NodeMixin(PermissionRequiredMixin):
def get_object(self):
return AbstractNode.objects.filter(
guids___id=self.kwargs['guid']
).annotate(
guid=F('guids___id'),
public_cap=Case(
When(
... | output_field=IntegerField() |
Continue the code snippet: <|code_start|>
class NodeMixin(PermissionRequiredMixin):
def get_object(self):
return AbstractNode.objects.filter(
guids___id=self.kwargs['guid']
).annotate(
guid=F('guids___id'),
public_cap=Case(
When(
... | When( |
Here is a snippet: <|code_start|>
class NodeMixin(PermissionRequiredMixin):
def get_object(self):
return AbstractNode.objects.filter(
guids___id=self.kwargs['guid']
<|code_end|>
. Write the next line using the current file imports:
import pytz
from datetime import datetime
from framework... | ).annotate( |
Continue the code snippet: <|code_start|> def get_object(self):
return AbstractNode.objects.filter(
guids___id=self.kwargs['guid']
).annotate(
guid=F('guids___id'),
public_cap=Case(
When(
custom_storage_usage_limit_public=None,
... | return reverse('nodes:node', kwargs={'guid': self.kwargs['guid']}) |
Given the code snippet: <|code_start|> @pytest.fixture()
def header_row(self, question_headers, metadata_headers):
return [*metadata_headers, *question_headers]
@pytest.fixture()
def subjects_list(self, provider_subjects):
return [subject.text for subject in provider_subjects]
@pyte... | 'Bibliographic Contributors': [{'full_name': 'jane doe', 'email': 'jane.doe@email.com'}, {'full_name': 'joan doe', 'email': 'joan.doe@email.com'}], |
Given the following code snippet before the placeholder: <|code_start|>
logger = logging.getLogger(__file__)
increment = 100000
# Dict to map original schema formats to schema block types
FORMAT_TYPE_TO_TYPE_MAP = {
('multiselect', 'choose'): 'multi-select-input',
(None, 'multiselect'): 'multi-select-inp... | def get_osf_models(): |
Here is a snippet: <|code_start|>
@pytest.mark.django_db
class TestRegistrationBulkUploadJob:
@pytest.fixture()
def payload_hash(self):
return str(uuid.uuid4()).replace('-', '')
@pytest.fixture()
def initiator(self):
return UserFactory()
@pytest.fixture()
def schema(self):
... | upload_job = RegistrationBulkUploadJob.create(payload_hash, initiator, provider, schema) |
Continue the code snippet: <|code_start|> return str(uuid.uuid4()).replace('-', '')
@pytest.fixture()
def initiator(self):
return UserFactory()
@pytest.fixture()
def schema(self):
return get_default_metaschema()
@pytest.fixture()
def provider(self):
return Regis... | with pytest.raises(IntegrityError): |
Based on the snippet: <|code_start|>
@pytest.mark.django_db
class TestRegistrationBulkUploadJob:
@pytest.fixture()
def payload_hash(self):
return str(uuid.uuid4()).replace('-', '')
@pytest.fixture()
def initiator(self):
return UserFactory()
@pytest.fixture()
def schema(self... | assert upload_job.initiator == initiator |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.