Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the code snippet: <|code_start|> success_url = reverse_lazy('feeds_list')
def get_initial(self):
source = self.request.GET.get('source')
feed = self.request.GET.get('feed')
if source == 'subtome' and feed:
return {
'feed_url': feed
}
de... | return kwargs |
Predict the next line after this snippet: <|code_start|>
self.cleaned_data['api_token'] = user['api_token']
return self.cleaned_data
def save(self, commit=True):
user, created = KipptUser.objects.get_or_create(
username=self.cleaned_data['username'],
)
user.api... | meta, lists = kippt.lists() |
Here is a snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
log = logging.getLogger(__name__)
def read_config(scan_config):
config_path = os.path.join(
os.path.dirname(os.path.realpath(sys.argv[0])), "config.json")
if os.path.isfile(config_path):
config['CONFIG_PATH'] = conf... | try: |
Given the following code snippet before the placeholder: <|code_start|>
if parse_version(ks_version) < parse_version('0.7'):
raise Exception("Incompatible Kaitai Struct Python API: 0.7 or later is required, but you have %s" % (ks_version))
class Ipv6Packet(KaitaiStruct):
def __init__(self, _io, _parent=None, _... | elif _on == 59: |
Using the snippet: <|code_start|> elif _on == 4:
self.next_header = Ipv4Packet(self._io)
elif _on == 6:
self.next_header = TcpSegment(self._io)
elif _on == 59:
self.next_header = self._root.NoNextHeader(self._io, self, self._root)
self.rest = self._io.r... | _on = self.next_header_type |
Using the snippet: <|code_start|>sys.path.append("../../")
MockRPi = MagicMock()
MockSpidev = MagicMock()
modules = {
<|code_end|>
, determine the next line of code. You have imports:
import sys
from unittest.mock import patch, MagicMock
from gfxlcd.driver.ssd1306.spi import SPI
from gfxlcd.driver.ssd1306.ssd1306 imp... | "RPi": MockRPi, |
Based on the snippet: <|code_start|>sys.path.append("../../")
RPi.GPIO.setmode(RPi.GPIO.BCM)
lcd_oled = SSD1306(128, 64, SPI())
lcd_oled.init()
lcd_oled.auto_flush = False
image_file = Image.open("assets/dsp2017_101_64.png")
lcd_oled.threshold = 50
<|code_end|>
, predict the immediate next line with the help of imp... | lcd_oled.threshold = 0 |
Based on the snippet: <|code_start|>sys.path.append("../../")
RPi.GPIO.setmode(RPi.GPIO.BCM)
lcd_oled = SSD1306(128, 64, SPI())
<|code_end|>
, predict the immediate next line with the help of imports:
import RPi.GPIO
import sys
from PIL import Image
from gfxlcd.driver.ssd1306.spi import SPI
from gfxlcd.driver.ssd1306... | lcd_oled.init() |
Given the following code snippet before the placeholder: <|code_start|>sys.path.append("../../")
RPi.GPIO.setmode(RPi.GPIO.BCM)
def hole(o, x, y):
o.draw_pixel(x+1, y)
<|code_end|>
, predict the next line using imports from the current file:
import RPi.GPIO
import sys
import random
from gfxlcd.driver.ssd1306.spi... | o.draw_pixel(x+2, y) |
Based on the snippet: <|code_start|>sys.path.append("../../")
RPi.GPIO.setmode(RPi.GPIO.BCM)
lcd_oled = SSD1306(128, 64, SPI())
lcd_oled.rotation = 270
lcd_oled.init()
lcd_oled.auto_flush = False
<|code_end|>
, predict the immediate next line with the help of imports:
import RPi.GPIO
import sys
from PIL import Image... | image_file = Image.open("assets/20x20.png") |
Here is a snippet: <|code_start|>sys.path.append("../../")
RPi.GPIO.setmode(RPi.GPIO.BCM)
lcd_oled = SSD1306(128, 64, SPI())
lcd_oled.rotation = 270
<|code_end|>
. Write the next line using the current file imports:
import RPi.GPIO
import sys
from PIL import Image
from gfxlcd.driver.ssd1306.spi import SPI
from gfxlcd... | lcd_oled.init() |
Next line prediction: <|code_start|>sys.path.append("../../")
class TestPageDrawing(object):
def setUp(self):
self.lcd = NullPage(10, 16, None, False)
<|code_end|>
. Use current file imports:
(import sys
from nose.tools import assert_equal
from gfxlcd.driver.null.null_page import NullPage)
and context i... | self.lcd.init() |
Given the following code snippet before the placeholder: <|code_start|>__author__ = 'kosci'
sys.path.append("../../")
class TestChip(object):
def setUp(self):
self.lcd = NullPage(10, 16, None, False)
def test_rotate_by_0(self):
<|code_end|>
, predict the next line using imports from the current file... | self.lcd.rotation = 0 |
Given the following code snippet before the placeholder: <|code_start|>__author__ = 'kosci'
sys.path.append("../../")
class TestChip(object):
def setUp(self):
self.gfx_lcd = NullPage(132, 16, None, False)
self.drv = HD44780(self.gfx_lcd)
self.output = [" ".ljust(16, " ") for i in range(0,... | def get_lcd(self): |
Continue the code snippet: <|code_start|>
class TestChip(object):
def setUp(self):
self.gfx_lcd = NullPage(132, 16, None, False)
self.drv = HD44780(self.gfx_lcd)
self.output = [" ".ljust(16, " ") for i in range(0, 2)]
def get_lcd(self):
lcd = CharLCD(self.drv.width, self.drv.hei... | lcd.write('Hello') |
Here is a snippet: <|code_start|> buffer[8][14] = self.color_white
buffer[9][15] = self.color_white
assert_equal(self.drv.buffer, buffer)
def test_draw_diagonal_line_even_steps_even_rest(self):
self.lcd.draw_line(0, 0, 9, 5)
buffer = self.get_buffer()
buffer[0][0] = s... | buffer[8][5] = self.color_white |
Using the snippet: <|code_start|> self.lcd.draw_line(1, 1, 8, 1)
self.lcd.draw_line(1, 1, 1, 14)
buffer = self.get_buffer()
buffer[1][1] = self.color_white
buffer[2][1] = self.color_white
buffer[3][1] = self.color_white
buffer[4][1] = self.color_white
buffe... | buffer[0][0] = self.color_white |
Next line prediction: <|code_start|>from __future__ import absolute_import
from __future__ import print_function
class Network(Model):
def __init__(self, dim, batch_norm, dropout, rec_dropout, header,
partition, ihm_pos, target_repl=False, depth=1, input_dim=76,
size_coef=4, **k... | self.size_coef = size_coef |
Given snippet: <|code_start|>
inputs = [X, ihm_M, decomp_M, los_M]
# Preprocess each channel
cX = []
for ch in channels:
cX.append(Slice(ch)(mX))
pX = [] # LSTM processed version of cX
for x in cX:
p = x
for i in range(depth):
... | if dropout > 0: |
Based on the snippet: <|code_start|> if pos != -1:
channel_names.add(ch[:pos])
else:
channel_names.add(ch)
channel_names = sorted(list(channel_names))
print("==> found {} channels: {}".format(len(channel_names), channel_names))
channels = [... | p = x |
Given the code snippet: <|code_start|> ihm_M = Input(shape=(1,), name='ihm_M')
decomp_M = Input(shape=(None,), name='decomp_M')
los_M = Input(shape=(None,), name='los_M')
inputs = [X, ihm_M, decomp_M, los_M]
# Preprocess each channel
cX = []
for ch in channels:
... | recurrent_dropout=rec_dropout)(Z) |
Predict the next line for this snippet: <|code_start|>def read_and_extract_features(reader, count, period, features):
read_chunk_size = 1000
Xs = []
ys = []
names = []
ts = []
for i in range(0, count, read_chunk_size):
j = min(count, i + read_chunk_size)
ret = common_utils.read_c... | parser.add_argument('--output_dir', type=str, help='Directory relative which all output files are stored', |
Given the following code snippet before the placeholder: <|code_start|> result_dir = os.path.join(args.output_dir, 'cf_results')
common_utils.create_directory(result_dir)
for (penalty, C) in zip(penalties, coefs):
model_name = '{}.{}.{}.C{}'.format(args.period, args.features, penalty, C)
tr... | json.dump(ret, f) |
Given the code snippet: <|code_start|> val_reader = LengthOfStayReader(dataset_dir=os.path.join(args.data, 'train'),
listfile=os.path.join(args.data, 'val_listfile.csv'))
test_reader = LengthOfStayReader(dataset_dir=os.path.join(args.data, 'test'),
... | print('Normalizing the data to have zero mean and unit variance ...') |
Given the following code snippet before the placeholder: <|code_start|>from __future__ import absolute_import
from __future__ import print_function
def read_and_extract_features(reader, count, period, features):
read_chunk_size = 1000
<|code_end|>
, predict the next line using imports from the current file:
fr... | Xs = [] |
Based on the snippet: <|code_start|> parser.add_argument('--prefix', type=str, default="",
help='optional prefix of network name')
parser.add_argument('--dropout', type=float, default=0.0)
parser.add_argument('--rec_dropout', type=float, default=0.0,
help="drop... | ---------- |
Predict the next line for this snippet: <|code_start|> print('Normalizing the data to have zero mean and unit variance ...')
scaler = StandardScaler()
scaler.fit(train_X)
train_X = scaler.transform(train_X)
val_X = scaler.transform(val_X)
test_X = scaler.transform(test_X)
n_tasks = 25
re... | test_preds = logreg.predict_proba(test_X) |
Next line prediction: <|code_start|> data[:, 0] = np.array(df['prediction'])
data[:, 1] = np.array(df['y_true_l'])
results = dict()
results['n_iters'] = args.n_iters
ret = print_metrics_binary(data[:, 1], data[:, 0], verbose=0)
for (m, k) in metrics:
results[m] = dict()
results[m... | print(results) |
Given the code snippet: <|code_start|>
parser = argparse.ArgumentParser(description='Extract per-subject data from MIMIC-III CSV files.')
parser.add_argument('mimic3_path', type=str, help='Directory containing MIMIC-III CSV files.')
parser.add_argument('output_path', type=str, help='Directory where per-subject data sh... | if args.verbose: |
Given the following code snippet before the placeholder: <|code_start|> pred_df = pd.read_csv(args.prediction, index_col=False, dtype={'period_length': np.float32,
'y_true': np.float32})
test_df = pd.read_csv(args.test_listfile, index_col=False, ... | for (m, k) in metrics: |
Given the code snippet: <|code_start|> test_df = pd.read_csv(args.test_listfile, index_col=False)
df = test_df.merge(pred_df, left_on='stay', right_on='stay', how='left', suffixes=['_l', '_r'])
assert (df['prediction'].isnull().sum() == 0)
assert (df['y_true_l'].equals(df['y_true_r']))
metrics = [(... | results[m]['mean'] = np.mean(runs) |
Here is a snippet: <|code_start|>
class BatchGen(object):
def __init__(self, reader, discretizer, normalizer,
batch_size, steps, shuffle, return_names=False):
self.reader = reader
self.discretizer = discretizer
self.normalizer = normalizer
self.batch_size = batch_si... | current_size = min(self.chunk_size, remaining) |
Here is a snippet: <|code_start|> stays.INTIME = pd.to_datetime(stays.INTIME)
stays.OUTTIME = pd.to_datetime(stays.OUTTIME)
stays.DOB = pd.to_datetime(stays.DOB)
stays.DOD = pd.to_datetime(stays.DOD)
stays.DEATHTIME = pd.to_datetime(stays.DEATHTIME)
stays.sort_values(by=['INTIME', 'OUTTIME'], inp... | del events['ICUSTAY_ID'] |
Predict the next line for this snippet: <|code_start|>from __future__ import absolute_import
from __future__ import print_function
def main():
parser = argparse.ArgumentParser()
parser.add_argument('prediction', type=str)
parser.add_argument('--test_listfile', type=str,
default=os... | assert (df['period_length_l'].equals(df['period_length_r'])) |
Continue the code snippet: <|code_start|> parser = argparse.ArgumentParser()
parser.add_argument('prediction', type=str)
parser.add_argument('--test_listfile', type=str,
default=os.path.join(os.path.dirname(__file__), '../../data/phenotyping/test/listfile.csv'))
parser.add_argumen... | results = dict() |
Given snippet: <|code_start|> self.steps = (N + batch_size - 1) // batch_size
self.lock = threading.Lock()
ret = common_utils.read_chunk(reader, N)
Xs = ret['X']
ts = ret['t']
ihms = ret['ihm']
loss = ret['los']
phenos = ret['pheno']
decomps = ret[... | self.data['pheno_y'] = phenos |
Predict the next line after this snippet: <|code_start|> los_M = common_utils.pad_zeros(los_M, min_length=self.ihm_pos + 1)
los_y = self.data['los_y'][i:i+B]
los_y_true = common_utils.pad_zeros(los_y, min_length=self.ihm_pos + 1)
if self.partition == 'log'... | 'names': self.data['names'][i:i+B], |
Using the snippet: <|code_start|> Xs = ret["X"]
ts = ret["t"]
ys = ret["y"]
names = ret["name"]
Xs = preprocess_chunk(Xs, ts, self.discretizer, self.normalizer)
(Xs, ys, ts, names) = common_utils.sort_and_shuffle([Xs, ys, ts... | yield {"data": batch_data, "names": batch_names, "ts": batch_ts} |
Given the following code snippet before the placeholder: <|code_start|>
assert np.sum(mask) > 0
assert len(X) == len(mask) and len(X) == len(y)
self.data = [[Xs, masks], ys]
self.names = names
self.ts = ts
def _generator(self):
B = self.batch_size
wh... | masks = self.data[0][1] |
Predict the next line for this snippet: <|code_start|>
def add_hcup_ccs_2015_groups(diagnoses, definitions):
def_map = {}
for dx in definitions:
for code in definitions[dx]['codes']:
def_map[code] = (dx, definitions[dx]['use_in_benchmark'])
diagnoses['HCUP_CCS_2015'] = diagnoses.ICD9_COD... | var_map.ITEMID = var_map.ITEMID.astype(int) |
Based on the snippet: <|code_start|> for k, v in ret.items():
logs[dataset + '_' + k] = v
history.append(ret)
def on_epoch_end(self, epoch, logs={}):
print("\n==>predicting on train")
self.calc_metrics(self.train_data, self.train_history, 'train', logs)
print("\n=... | y_true = [] |
Given the code snippet: <|code_start|> inputs.append(M)
# Configurations
is_bidirectional = True
if deep_supervision:
is_bidirectional = False
# Main part of the network
for i in range(depth - 1):
num_units = dim
if is_bidirectiona... | recurrent_dropout=rec_dropout)(mX) |
Given snippet: <|code_start|> # Main part of the network
for i in range(depth - 1):
num_units = dim
if is_bidirectional:
num_units = num_units // 2
lstm = LSTM(units=num_units,
activation='tanh',
return_s... | name='seq')(L) |
Here is a snippet: <|code_start|> dn = os.path.join(output_path, str(subject_id))
try:
os.makedirs(dn)
except:
pass
diagnoses[diagnoses.SUBJECT_ID == subject_id].sort_values(by=['ICUSTAY_ID', 'SEQ_NUM'])\
.to_cs... | pass |
Predict the next line for this snippet: <|code_start|> self.ts = tmp_ts
else:
# sort entirely
X = self.data[0]
y = self.data[1]
(X, y, self.names, self.ts) = common_utils.sort_and_shuffle([X, y, self.names, self.ts], B)
... | return self.generator |
Predict the next line after this snippet: <|code_start|>
self.dim = dim
self.batch_norm = batch_norm
self.dropout = dropout
self.rec_dropout = rec_dropout
self.depth = depth
self.size_coef = size_coef
if task in ['decomp', 'ihm', 'ph']:
final_activati... | channel_names = sorted(list(channel_names)) |
Using the snippet: <|code_start|> inputs = [X]
mX = Masking()(X)
if deep_supervision:
M = Input(shape=(None,), name='M')
inputs.append(M)
# Configurations
is_bidirectional = True
if deep_supervision:
is_bidirectional = False
#... | if is_bidirectional: |
Using the snippet: <|code_start|>
# Main part of the network
for i in range(depth-1):
num_units = int(size_coef*dim)
if is_bidirectional:
num_units = num_units // 2
lstm = LSTM(units=num_units,
activation='tanh',
... | y = TimeDistributed(Dense(num_classes, activation=final_activation), |
Continue the code snippet: <|code_start|>from __future__ import absolute_import
from __future__ import print_function
def load_data(reader, discretizer, normalizer, small_part=False, return_names=False):
N = reader.get_number_of_examples()
if small_part:
N = 1000
ret = common_utils.read_chunk(rea... | f.write("{},{:.6f},{}\n".format(name, x, y)) |
Next line prediction: <|code_start|> command += ' --ihm_C {}'.format(ihm_C)
if decomp_C:
command += ' --decomp_C {}'.format(decomp_C)
if los_C:
command += ' --los_C {}'.format(los_C)
if pheno_C:
command += ' --pheno_C {}'.format(pheno_C)
if dropout > 0.0:
comma... | "n_epochs": n_epochs, |
Given the code snippet: <|code_start|>from __future__ import absolute_import
from __future__ import print_function
class Network(Model):
def __init__(self, dim, batch_norm, dropout, rec_dropout, partition,
ihm_pos, target_repl=False, depth=1, input_dim=76, **kwargs):
print("==> not used... | self.dropout = dropout |
Given the following code snippet before the placeholder: <|code_start|> ihm_y = GetTimestep(ihm_pos)(ihm_seq)
ihm_y = Multiply(name='ihm_single')([ihm_y, ihm_M])
outputs += [ihm_y, ihm_seq]
else:
ihm_seq = TimeDistributed(Dense(1, activation='sigmoid'))(L)
... | outputs += [pheno_y] |
Here is a snippet: <|code_start|>
# decomp output
decomp_y = TimeDistributed(Dense(1, activation='sigmoid'))(L)
decomp_y = ExtendMask(name='decomp', add_epsilon=True)([decomp_y, decomp_M])
outputs += [decomp_y]
# los output
if partition == 'none':
los_y = Tim... | ".d{}".format(self.dropout) if self.dropout > 0 else "", |
Given the code snippet: <|code_start|>
logger = logging.getLogger('timeline_logger')
DEFAULT_TEMPLATE = settings.TIMELINE_DEFAULT_TEMPLATE
@python_2_unicode_compatible
class TimelineLog(models.Model):
<|code_end|>
, generate the next line using the imports in this file:
import logging
from django.contrib.content... | content_type = models.ForeignKey( |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
class TimelineLogTestCase(TestCase):
def setUp(self):
self.article = ArticleFactory.create()
self.user = User.objects.create(username='john_doe', email='john.doe@maykinmedia.nl')
self.timel... | def test_log_from_request_no_user(self): |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
class TimelineLogTestCase(TestCase):
def setUp(self):
self.article = ArticleFactory.create()
self.user = User.objects.create(username='john_doe', email='john.doe@maykinmedia.nl')
self.timeline_log = TimelineLog.objects.create(
... | user=self.user, |
Here is a snippet: <|code_start|>
app_name = 'timeline'
urlpatterns = [
url(r'^$', TimelineLogListView.as_view(), name='timeline'),
<|code_end|>
. Write the next line using the current file imports:
from django.conf.urls import url
from .views import TimelineLogListView
and context from other files:
# Path: tim... | ] |
Based on the snippet: <|code_start|>
admin.site.unregister(TimelineLog)
@admin.register(TimelineLog)
class TimelineLogAdmin(ExportMixin, TimelineLogAdmin):
<|code_end|>
, predict the immediate next line with the help of imports:
from django.contrib import admin
from import_export.admin import ExportMixin
from impor... | formats = ( |
Continue the code snippet: <|code_start|>
admin.site.unregister(TimelineLog)
@admin.register(TimelineLog)
class TimelineLogAdmin(ExportMixin, TimelineLogAdmin):
formats = (
XML,
base_formats.CSV,
<|code_end|>
. Use current file imports:
from django.contrib import admin
from import_export.admin i... | base_formats.XLS, |
Using the snippet: <|code_start|>
admin.site.unregister(TimelineLog)
@admin.register(TimelineLog)
class TimelineLogAdmin(ExportMixin, TimelineLogAdmin):
formats = (
<|code_end|>
, determine the next line of code. You have imports:
from django.contrib import admin
from import_export.admin import ExportMixin
from... | XML, |
Here is a snippet: <|code_start|>
class JSONWidget(Widget):
def render(self, value, obj=None):
return value
<|code_end|>
. Write the next line using the current file imports:
from import_export.resources import ModelResource
from import_export.fields import Field
from import_export.widgets import Widg... | class TimelineLogResource(ModelResource): |
Given the following code snippet before the placeholder: <|code_start|>
logger = logging.getLogger('timeline_logger')
class Command(BaseCommand):
help = 'Sends mail notifications for last events to (admin) users.'
template_name = 'timeline_logger/notifications.html'
def add_arguments(self, parser):
... | recipients_group.add_argument( |
Predict the next line after this snippet: <|code_start|>
logger = logging.getLogger('timeline_logger')
class Command(BaseCommand):
help = 'Sends mail notifications for last events to (admin) users.'
template_name = 'timeline_logger/notifications.html'
def add_arguments(self, parser):
parser.add... | ) |
Given the code snippet: <|code_start|>
@pytest.mark.skipif(
settings.DATABASES['default']['ENGINE'] != 'django.db.backends.postgresql',
reason='Requires PostgreSQL'
)
@pytest.mark.django_db
def test_render_message():
log = TimelineLogFactory.create(extra_data={'foo': 'bar'})
with patch.object(log, 'ge... | render_to_string('test_render_message', {'log': log}) |
Here is a snippet: <|code_start|>
class ReportMailingTestCase(TestCase):
def setUp(self):
self.article = ArticleFactory.create()
self.user = UserFactory.create(email='jose@maykinmedia.nl')
self.staff_user = UserFactory.create(is_staff=True)
self.admin_user = UserFactory.create(i... | ) |
Given the following code snippet before the placeholder: <|code_start|>
class ReportMailingTestCase(TestCase):
def setUp(self):
self.article = ArticleFactory.create()
self.user = UserFactory.create(email='jose@maykinmedia.nl')
self.staff_user = UserFactory.create(is_staff=True)
... | content_object=self.article, |
Based on the snippet: <|code_start|>
class ReportMailingTestCase(TestCase):
def setUp(self):
self.article = ArticleFactory.create()
self.user = UserFactory.create(email='jose@maykinmedia.nl')
self.staff_user = UserFactory.create(is_staff=True)
self.admin_user = UserFactory.creat... | content_object=self.article, |
Using the snippet: <|code_start|>
logger = logging.getLogger(__name__)
CRS_BOUNDS = {
# http://spatialreference.org/ref/epsg/wgs-84/
"epsg:4326": (-180.0, -90.0, 180.0, 90.0),
# unknown source
"epsg:3857": (-180.0, -85.0511, 180.0, 85.0511),
# http://spatialreference.org/ref/epsg/3035/
"epsg:... | dst_crs=None, |
Here is a snippet: <|code_start|>
logger = logging.getLogger(__name__)
CRS_BOUNDS = {
# http://spatialreference.org/ref/epsg/wgs-84/
"epsg:4326": (-180.0, -90.0, 180.0, 90.0),
# unknown source
"epsg:3857": (-180.0, -85.0511, 180.0, 85.0511),
# http://spatialreference.org/ref/epsg/3035/
"epsg:... | segmentize_fraction=100, |
Given the following code snippet before the placeholder: <|code_start|>
def test_timer():
timer1 = Timer(elapsed=1000)
timer2 = Timer(elapsed=2000)
timer3 = Timer(elapsed=1000)
assert timer1 < timer2
assert timer1 <= timer2
assert timer2 > timer3
assert timer2 >= timer3
assert timer1 =... | assert timer1 + timer3 == timer2 |
Next line prediction: <|code_start|> items = list(range(10))
with Executor(concurrency="threads") as executor:
result = executor.map(_dummy_process, items)
assert [i + 1 for i in items] == result
def test_dask_executor_as_completed():
items = 100
with Executor(concurrency="dask", max_wo... | ): |
Based on the snippet: <|code_start|> ):
assert future.result()
executor.cancel()
break
assert not executor.running_futures
def test_dask_executor_as_completed_skip():
items = 100
skip_info = "foo"
with Executor(concurrency="dask", max_workers=2) as execu... | _dummy_process, range(items), max_submitted_tasks=1 |
Given the code snippet: <|code_start|> count += 1
assert isinstance(future, SkippedFuture)
assert future.skip_info == skip_info
assert items == count
def test_dask_executor_as_completed_max_tasks():
items = 100
with Executor(concurrency="dask") as executor:
#... | def test_concurrent_futures_dask_executor_map(): |
Based on the snippet: <|code_start|>KNOWN_MATRIX_PROPERTIES = {
"geodetic": {
"name": "WorldCRS84Quad",
"url": "http://schemas.opengis.net/tms/1.0/json/examples/WorldCRS84Quad.json",
"title": "CRS84 for the World",
"crs": "http://www.opengis.net/def/crs/OGC/1.3/CRS84",
"suppo... | bounds_crs=None, |
Given the following code snippet before the placeholder: <|code_start|>
out_path = mp.config.output_reader.get_path(
mp.config.process_pyramid.tile(*tile)
)
with rasterio.open(out_path) as src:
assert not src.read(masked=True).mask.all()
out_path = mp.config.outp... | ) |
Based on the snippet: <|code_start|> assert inp1.get_preprocessing_task_result("test_task") == "foofoobar"
assert mp.config.preprocessing_task_finished(
f"{inp1.input_key}:test_other_task"
)
assert inp1.get_preprocessing_task_result("test_other_task") == "barfoobar"
as... | with preprocess_cache_raster_vector.mp() as mp: |
Using the snippet: <|code_start|>
def _validate_json(self, json_object):
contents = pkg_resources.resource_string(__name__, 'sperimentschema.json')
schema = json.loads(contents)
jsonschema.validate(json_object, schema)
def to_JSON(self):
SampleFrom._compile_time_generators = cop... | attrs = obj.__dict__ |
Continue the code snippet: <|code_start|> if any_replacement and not all_replacement:
raise ValueError('''Some SampleFrom objects for bank {} are
with replacement and some are without replacement. They
must all sample the same way.'''.format(bank_name))... | self._validate_json(json_experiment) |
Continue the code snippet: <|code_start|> raise ValueError('''All values in {} must have the same fields'''.format(bank_name))
if not all(hasattr(sampler, field) for sampler in samplers):
raise ValueError('''All SampleFrom objects sampling from {} must specify a fi... | filename = experiment_name + '.js' |
Here is a snippet: <|code_start|>
class SampleFrom:
'''Stands in place of a value of a Page or Option and tells the program to
randomly choose a value to go there on a per-participant basis. Once
sampled, the choice will remain in place for all iterations of the block.
Sampling happens after pages are c... | with_replacement = False): |
Predict the next line after this snippet: <|code_start|> group]
except AttributeError:
raise ValueError, '''In block {0}, can't pseudorandomize pages without
conditions.'''.format(self.id_str)
cond_counter = Counter(condition... | block.run_if = RunIf(permutation = i) |
Predict the next line after this snippet: <|code_start|> that Pages can display multiple times if they are in Blocks with a
criterion.'''
if item != None:
self.item = item
if page != None:
self.page = page
if option != None:
self.option = option... | del self.item |
Based on the snippet: <|code_start|> raise ValueError, '''A text box option should have a regular
expression rather than a boolean as its "correct" attribute.'''
if hasattr(self, 'correct'):
if self.correct in [True, False]:
raise Va... | elif self.keyboard: |
Next line prediction: <|code_start|>BACKENDS = settings.AUTHENTICATION_BACKENDS
STRATEGY = getattr(settings, setting_name('STRATEGY'),
'social.strategies.django_strategy.DjangoStrategy')
STORAGE = getattr(settings, setting_name('STORAGE'),
'social.apps.django_app.default.models.Djan... | except AttributeError: |
Using the snippet: <|code_start|>
BACKENDS = settings.AUTHENTICATION_BACKENDS
STRATEGY = getattr(settings, setting_name('STRATEGY'),
'social.strategies.django_strategy.DjangoStrategy')
STORAGE = getattr(settings, setting_name('STORAGE'),
'social.apps.django_app.default.models.Dja... | uri = redirect_uri |
Based on the snippet: <|code_start|> tpl = tpl or BaseTemplateStrategy
if not isinstance(tpl, BaseTemplateStrategy):
tpl = tpl(self)
self.tpl = tpl
self.request = request
self.storage = storage
self.backends = backends
if backend:
self.backe... | else: |
Predict the next line for this snippet: <|code_start|> def session_setdefault(self, name, value):
self.session_set(name, value)
return self.session_get(name)
def to_session(self, next, backend, *args, **kwargs):
return {
'next': next,
'backend': backend.name,
... | )) |
Using the snippet: <|code_start|> username = details['username']
else:
username = uuid4().hex
short_username = username[:max_length - uuid_length]
final_username = username[:max_length]
if do_clean:
final_username = storage.user.clean_username(final_us... | return { |
Continue the code snippet: <|code_start|>
def do_auth(strategy, redirect_name='next'):
# Save any defined next value into session
data = strategy.request_data(merge=False)
# Save extra data into session.
for field_name in strategy.setting('FIELDS_STORED_IN_SESSION', []):
if field_name in data:
... | redirect_value = strategy.session_get(redirect_name, '') or \ |
Next line prediction: <|code_start|> redirect_uri)
strategy.session_set(
redirect_name,
redirect_uri or strategy.setting('LOGIN_REDIRECT_URL')
)
return strategy.start()
def do_complete(strategy, login, user=None, redirect_name='ne... | *xargs, **xkwargs) |
Predict the next line after this snippet: <|code_start|>
def do_complete(strategy, login, user=None, redirect_name='next',
*args, **kwargs):
# pop redirect value before the session is trashed on login()
data = strategy.request_data()
redirect_value = strategy.session_get(redirect_name, '') ... | user = strategy.complete(user=user, request=strategy.request, |
Given the code snippet: <|code_start|>"""
Base backends classes.
This module defines base classes needed to define custom OpenID or OAuth1/2
auth services from third parties. This customs must subclass an Auth and a
Backend class, check current implementation for examples.
Also the modules *must* define a BACKENDS di... | self.redirect_uri = self.strategy.build_absolute_uri( |
Using the snippet: <|code_start|> def request_token_extra_arguments(self):
"""Return extra arguments needed on request-token process"""
return self.setting('REQUEST_TOKEN_EXTRA_ARGUMENTS', {})
def auth_extra_arguments(self):
"""Return extra arguments needed on auth process. The defaults ... | def get_key_and_secret(self): |
Based on the snippet: <|code_start|>
DEFAULT_REDIRECT = setting('LOGIN_REDIRECT_URL')
LOGIN_ERROR_URL = setting('LOGIN_ERROR_URL', setting('LOGIN_URL'))
@strategy('social:complete')
def auth(request, backend):
return do_auth(request.strategy, redirect_name=REDIRECT_FIELD_NAME)
@csrf_exempt
@strategy('social:c... | def disconnect(request, backend, association_id=None): |
Continue the code snippet: <|code_start|>
DEFAULT_REDIRECT = setting('LOGIN_REDIRECT_URL')
LOGIN_ERROR_URL = setting('LOGIN_ERROR_URL', setting('LOGIN_URL'))
@strategy('social:complete')
def auth(request, backend):
return do_auth(request.strategy, redirect_name=REDIRECT_FIELD_NAME)
@csrf_exempt
@strategy('soc... | redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs) |
Using the snippet: <|code_start|>
DEFAULT_REDIRECT = setting('LOGIN_REDIRECT_URL')
LOGIN_ERROR_URL = setting('LOGIN_ERROR_URL', setting('LOGIN_URL'))
@strategy('social:complete')
def auth(request, backend):
return do_auth(request.strategy, redirect_name=REDIRECT_FIELD_NAME)
@csrf_exempt
@strategy('social:comp... | def disconnect(request, backend, association_id=None): |
Using the snippet: <|code_start|>
DEFAULT_REDIRECT = setting('LOGIN_REDIRECT_URL')
LOGIN_ERROR_URL = setting('LOGIN_ERROR_URL', setting('LOGIN_URL'))
@strategy('social:complete')
def auth(request, backend):
return do_auth(request.strategy, redirect_name=REDIRECT_FIELD_NAME)
@csrf_exempt
@strategy('social:comp... | @login_required |
Based on the snippet: <|code_start|>
DEFAULT_REDIRECT = setting('LOGIN_REDIRECT_URL')
LOGIN_ERROR_URL = setting('LOGIN_ERROR_URL', setting('LOGIN_URL'))
@strategy('social:complete')
def auth(request, backend):
return do_auth(request.strategy, redirect_name=REDIRECT_FIELD_NAME)
@csrf_exempt
@strategy('social:c... | redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs) |
Based on the snippet: <|code_start|>
DEFAULT_REDIRECT = setting('LOGIN_REDIRECT_URL')
LOGIN_ERROR_URL = setting('LOGIN_ERROR_URL', setting('LOGIN_URL'))
@strategy('social:complete')
def auth(request, backend):
return do_auth(request.strategy, redirect_name=REDIRECT_FIELD_NAME)
@csrf_exempt
@strategy('social:c... | @require_POST |
Given the code snippet: <|code_start|>
social_auth = Blueprint('social', __name__)
@social_auth.route('/login/<string:backend>/', methods=['GET', 'POST'])
@strategy('social.complete')
def auth(backend):
return do_auth(g.strategy)
@social_auth.route('/complete/<string:backend>/', methods=['GET', 'POST'])
@stra... | methods=['POST']) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.