Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given snippet: <|code_start|>
# Non-market-aware mode requires a timedelta.
else:
assert self.delta and not self.window_length, \
"Non-market-aware mode requires a timedelta."
# No way to pass arguments to the defaultdict factory, so we
# need to define a met... | class VWAPEventWindow(EventWindow): |
Given the code snippet: <|code_start|> """
There should only ever be one TSC in the system, so
we don't bother passing args into the hash.
"""
return self.__class__.__name__ + hash_args()
def __init__(self, algo, sim_params):
# ==============
# Simulation
... | self.current_data = BarData() |
Given the code snippet: <|code_start|> trading.environment.next_open_and_close(
mkt_close
)
self.algo.perf_tracker.handle_intraday_close()
risk_message = self.algo.... | self.current_data[event.sid] = {event.contract: SIDData()} |
Predict the next line for this snippet: <|code_start|> for txn, order in process_trade(event):
if txn.amount != 0:
self.algo.perf_tracker.process_event(txn)
self.algo.perf_tracker.process_event(order)
self.algo.perf_tracker.process_event(event)
def transform(... | if event.type == DATASOURCE_TYPE.SPLIT: |
Here is a snippet: <|code_start|># Copyright 2013 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... | return self.__class__.__name__ + hash_args() |
Given the following code snippet before the placeholder: <|code_start|>
if 'expected_transactions' in test.zipline_test_config:
test.assertEqual(
test.zipline_test_config['expected_transactions'],
transaction_count
)
else:
test.assertEqual(
test.ziplin... | ORDER_STATUS.FILLED, |
Predict the next line after this snippet: <|code_start|># limitations under the License.
#
log = Logger('Blotter')
ORDER_STATUS = Enum(
'OPEN',
'FILLED',
'CANCELLED'
)
# On an order to buy, between .05 below to .95 above a penny, use that penny.
# On an order to sell, between .05 above to .95 below... | self.transact = transact_partial(VolumeShareSlippage(), PerShare()) |
Given snippet: <|code_start|># limitations under the License.
#
log = Logger('Blotter')
ORDER_STATUS = Enum(
'OPEN',
'FILLED',
'CANCELLED'
)
# On an order to buy, between .05 below to .95 above a penny, use that penny.
# On an order to sell, between .05 above to .95 below a penny, use that penny.
#... | self.transact = transact_partial(VolumeShareSlippage(), PerShare()) |
Given the code snippet: <|code_start|> self.filled = filled
self.status = ORDER_STATUS.OPEN
self.stop = stop
self.limit = limit
self.stop_reached = False
self.limit_reached = False
self.direction = math.copysign(1, self.amount)
self.type = zp.DATASOURCE_TYP... | check_order_triggers(self, event) |
Given snippet: <|code_start|>Tools to generate data sources.
"""
class DataFrameSource(DataSource):
"""
Yields all events in event_list that match the given sid_filter.
If no event_list is specified, generates an internal stream of events
to filter. Returns all events if filter is None.
Config... | self.arg_string = hash_args(data, **kwargs) |
Predict the next line for this snippet: <|code_start|> all_ = pd.concat(frames, axis=1).T
try:
all_ = all_.groupby(axis=0, level=0).apply(logic).reset_index(
level=(0, 2), drop=True)
except:
all_ = all_.groupby(axis=0, level=0).apply... | bar_data = BarData() |
Based on the snippet: <|code_start|> try:
all_ = all_.groupby(axis=0, level=0).apply(logic).reset_index(
level=(0, 2), drop=True)
except:
all_ = all_.groupby(axis=0, level=0).apply(logic)
#Todo: handle multiple contract returns
... | bar_data.__dict__['_data'].update({k: SIDData(v) for k, v in data.iteritems()}) |
Predict the next line after this snippet: <|code_start|>
for date, group in grouped_events:
for event in group:
perf_tracker.process_event(event)
msg = perf_tracker.handle_market_close()
perf_messages.append(msg)
self.assertEqual(perf_tracker.txn_coun... | txn = Transaction( |
Using the snippet: <|code_start|>#
# Copyright 2013 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | return create_transaction(event, mock_order, price, amount) |
Given snippet: <|code_start|> beta value for the same period as all other values
Returns:
float. The alpha of the algorithm.
"""
return algorithm_period_return - \
(treasury_period_return + beta *
(benchmark_period_returns - treasury_period_return))
####################... | tdd = trading.environment.trading_day_distance(dt, end_date) |
Based on the snippet: <|code_start|>"""
Unit tests for finance.slippage
"""
class SlippageTestCase(TestCase):
def test_volume_share_slippage(self):
event = Event(
{'volume': 200,
'type': 4,
'price': 3.0,
'datetime': datetime.datetime(
... | slippage_model = VolumeShareSlippage() |
Next line prediction: <|code_start|>#
# Copyright 2013 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... | __metaclass__ = TransformMeta |
Using the snippet: <|code_start|># You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either... | assert event.type in DATASOURCE_TYPE |
Given snippet: <|code_start|>#
# Copyright 2013 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | 'slippage': FixedSlippage() |
Using the snippet: <|code_start|> | _metrics | calculated based on the positions aggregated |
| | through all the events delivered to this tracker. |
| | For details look at the comments for |
| | :py:meth:`zipline.finance.risk.R... | trading.environment.get_open_and_close(first_day) |
Given snippet: <|code_start|> # responsibility of creating an instance to
# TransformMeta's parent class, which is 'type'. This is
# what is implicitly done behind the scenes by the python
# interpreter for most classes anyway, but here we have to
# be explicit... | DATASOURCE_TYPE.TRADE, |
Here is a snippet: <|code_start|> else:
self.state = tnfm_class(*args, **kwargs)
# save the window_length of the state for external access.
self.window_length = self.state.window_length
# Create the string associated with this generator's output.
self.namestring = tnfm... | assert_sort_unframe_protocol(message) |
Given snippet: <|code_start|> update, the state class must produce a message to be fed
downstream. Any transform class with the FORWARDER class variable
set to true will forward all fields in the original message.
Otherwise only dt, tnfm_id, and tnfm_value are forwarded.
"""
def __init__(self, tn... | self.namestring = tnfm_class.__name__ + hash_args(*args, **kwargs) |
Here is a snippet: <|code_start|>
if (hasattr(event, 'type')
and event.type not in (
DATASOURCE_TYPE.TRADE,
DATASOURCE_TYPE.CUSTOM)):
return
self.assert_well_formed(event)
# Add new event and increment totals.
self.tick... | trading.environment.trading_days.searchsorted(oldest) |
Given the code snippet: <|code_start|> / algo_volatility)
class RiskMetricsCumulative(object):
"""
:Usage:
Instantiate RiskMetricsCumulative once.
Call update() method on each dt to update the metrics.
"""
METRIC_NAMES = (
'alpha',
'beta',
'sharpe',
... | self.treasury_curves = trading.environment.treasury_curves |
Based on the snippet: <|code_start|>
self.full = False
# Set to -inf essentially to cause update on first attempt.
self.last_dt = pd.Timestamp('1900-1-1', tz='UTC')
self.updated = False
self.cached = None
self.last_args = None
self.last_kwargs = None
# D... | event = Event() |
Given the code snippet: <|code_start|>log = logbook.Logger('BatchTransform')
func_map = {'open_price': 'first',
'close_price': 'last',
'low': 'min',
'high': 'max',
'volume': 'sum'
}
def get_sample_func(item):
if item in func_map:
return func_map[... | dt1 = trading.environment.normalize_date(mkt_close) |
Here is a snippet: <|code_start|> sid_list = config.get('sid_list')
if not sid_list:
sid = config.get('sid')
sid_list = [sid]
concurrent_trades = config.get('concurrent_trades', False)
if 'order_count' in config:
order_count = config['order_count']
else:
order_count ... | test_algo = TestAlgorithm( |
Predict the next line for this snippet: <|code_start|>
# Create your views here.
def post_list(request):
posts = Post.objects.filter().order_by('-published_date')
categories = Category.objects.filter().order_by('name')
template_name = 'bamboo/post_list.html'
context_data = {'posts': posts, 'cate... | form = PostForm(request.POST)
|
Continue the code snippet: <|code_start|> return redirect('post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'bamboo/post_edit.html', {'form': form})
def post_edit(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
... | form = CommentForm(request.POST)
|
Here is a snippet: <|code_start|> post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm(instance=post)
return render(request, 'bamboo/post_edit.html', {'form': form})
def post_remove(request, pk):
post = get_object_or_404(Post, pk=pk)
post... | form = PasswordCheckForm(request.POST)
|
Here is a snippet: <|code_start|>
# Register your models here.
class CategoryAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ['name']}
list_display = ['id', 'name', 'slug']
list_editable = ['name', 'slug', 'description']
search_fields = ['name']
ordering = ['name']
class PostAd... | admin.site.register(Category, CategoryAdmin)
|
Next line prediction: <|code_start|>
# Register your models here.
class CategoryAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ['name']}
list_display = ['id', 'name', 'slug']
list_editable = ['name', 'slug', 'description']
search_fields = ['name']
ordering = ['name']
class Pos... | admin.site.register(Post, PostAdmin)
|
Predict the next line after this snippet: <|code_start|>
# Register your models here.
class CategoryAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ['name']}
list_display = ['id', 'name', 'slug']
list_editable = ['name', 'slug', 'description']
search_fields = ['name']
ordering = ['n... | admin.site.register(Comment, CommentAdmin)
|
Given snippet: <|code_start|>
class PostForm(forms.ModelForm):
post_password = forms.CharField(widget=forms.PasswordInput)
class Meta:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django import forms
from .models import Post, Comment
and context:
# Path... | model = Post
|
Here is a snippet: <|code_start|>
class PostForm(forms.ModelForm):
post_password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = Post
fields = ('category', 'writer', 'post_password', 'title', 'text', )
class CommentForm(forms.ModelForm):
class Meta:
<|co... | model = Comment
|
Continue the code snippet: <|code_start|>
INSTALL_REQ = False
def test_deepsea():
model = kipoi.get_model("DeepSEA/variantEffects")
<|code_end|>
. Use current file imports:
import kipoi
import kipoi_veff
import kipoi_veff.snv_predict as sp
import pytest
import os
from kipoi_veff.utils.generic import ModelInfoExt... | mie = ModelInfoExtractor(model, SeqIntervalDl) |
Predict the next line after this snippet: <|code_start|>
class SwapAxes(object):
"""np.swapaxes wrapper
If any if the axis is None, do nothing.
"""
def __init__(self, axis1=None, axis2=None):
self.axis1 = axis1
self.axis2 = axis2
def __call__(self, x):
if self.axis1 is Non... | return F.resize_interval(interval, self.width, self.anchor) |
Continue the code snippet: <|code_start|># Intervals
class ResizeInterval(object):
"""Resize the interval
"""
def __init__(self, width, anchor='center'):
self.width = width
self.anchor = anchor
def __call__(self, interval):
return F.resize_interval(interval, self.width, self.... | def __init__(self, alphabet=DNA, neutral_alphabet='N', neutral_value=0.25, dtype=None): |
Given snippet: <|code_start|>from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
# sequence -> array
def _get_alphabet_dict(alphabet):
return {l: i for i, l in enumerate(alphabet)}
def _get_index_dict(alphabet):
return {i: l for i, l in enumerate(al... | def one_hot2string(arr, alphabet=DNA): |
Here is a snippet: <|code_start|>"""Test BedDataset
"""
def write_tmp(string, tmpdir):
p = tmpdir.mkdir("bed-files").join("file2.txt")
p.write(string)
return str(p)
def test_bed3(tmpdir):
bed_file = write_tmp('chr1\t1\t2\nchr1\t1\t3', tmpdir)
<|code_end|>
. Write the next line using the current file... | bt = BedDataset(bed_file) |
Predict the next line for this snippet: <|code_start|>
pytestmark_gtf = pytest.mark.skipif(not os.path.isfile(gtf_file_GRCh38),
reason="File does not exist")
pytestmark_fasta = pytest.mark.skipif(not os.path.isfile(fasta_file_GRCh38),
reason="Fi... | return TranscriptSeqExtractor(gtf_file_GRCh38, fasta_file_GRCh38) |
Predict the next line after this snippet: <|code_start|>@pytestmark_vcf
@pytestmark_protein
@pytest.mark.xfail
def test_hg38(tse):
with open('err_transcripts', 'w+') as f:
dfp = read_pep_fa(protein_file)
dfp['transcript_id'] = dfp.transcript.str.split(".", n=1, expand=True)[0]
#assert not df... | prot_seq = translate(dna_seq, hg38=True) |
Based on the snippet: <|code_start|>
def test_parse_alphabet():
assert parse_alphabet(['A', 'C']) == ['A', 'C']
assert parse_alphabet('AC') == ['A', 'C']
def test_parse_type():
with pytest.raises(Exception):
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
import nu... | parse_dtype('string') |
Predict the next line for this snippet: <|code_start|>
pytestmark_gtf = pytest.mark.skipif(not os.path.isfile(gtf_file_GRCh38),
reason="File does not exist")
pytestmark_fasta = pytest.mark.skipif(not os.path.isfile(fasta_file_GRCh38),
reason="Fi... | return SingleVariantProteinVCFSeqExtractor(gtf_file_GRCh38, fasta_file_GRCh38, vcf_file_for_testing_synonymous_mutations) |
Predict the next line after this snippet: <|code_start|>pytestmark_vcf = pytest.mark.skipif(not os.path.isfile(vcf_file_for_testing_synonymous_mutations),
reason="File does not exist")
pytestmark_protein = pytest.mark.skipif(not os.path.isfile(protein_file_GRCh38),
... | return TranscriptSeqExtractor(gtf_file_GRCh38, fasta_file_GRCh38) |
Using the snippet: <|code_start|>
pytestmark_gtf = pytest.mark.skipif(not os.path.isfile(gtf_file_GRCh38),
reason="File does not exist")
pytestmark_fasta = pytest.mark.skipif(not os.path.isfile(fasta_file_GRCh38),
reason="File does not exist")
p... | return SingleSeqProteinVCFSeqExtractor(gtf_file_GRCh38, fasta_file_GRCh38, vcf_file_for_testing_synonymous_mutations) |
Based on the snippet: <|code_start|>@pytestmark_protein
@pytest.fixture
def ssp():
return SingleSeqProteinVCFSeqExtractor(gtf_file_GRCh38, fasta_file_GRCh38, vcf_file_for_testing_synonymous_mutations)
@pytestmark_gtf
@pytestmark_fasta
@pytestmark_vcf
@pytestmark_protein
@pytest.fixture
def svp():
return Singl... | ref_seq = translate(tse.get_seq(transcript_id), True) |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
#
# mididings
#
# Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either... | return _Filter(_mididings.PortFilter(map(_util.actual, ports))) |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
#
# mididings
#
# Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Soft... | self.registry_bak = overload._registry.copy() |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
#
# mididings
#
# Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Softwa... | return _Unit(_mididings.Port(_util.actual(port))) |
Given snippet: <|code_start|>
Process the incoming MIDI event using a Python function, then continue
executing the mididings patch with the events returned from that
function.
:param function:
a function, or any other callable object, that will be called with
a :class:`~.MidiEvent` obje... | if _get_config('backend') == 'jack-rt' and not _get_config('silent'): |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# mididings
#
# Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either... | self.assertEqual(engine.in_ports(), ports) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# mididings
#
# Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either... | return _Unit(_mididings.Generator( |
Next line prediction: <|code_start|> yield _event.NoteOnEvent(
ev.port, ev.channel, n, self.notes[n][0])
self.current_note = n
self.diverted = d
def VoiceFilter(voice='highest', time=0.1, retrigger=False):
"""
Filter individual voices... | return _m.Filter(_m.NOTE) % _m.Process(_PerChannel( |
Here is a snippet: <|code_start|>#
# mididings
#
# Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the Licens... | _m.Process(_PerChannel(_SuppressPC))) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
#
# mididings
#
# Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
... | unit._name = f.name if isinstance(f, overload._Overload) else f.__name__ |
Next line prediction: <|code_start|># (at your option) any later version.
#
@decorator.decorator
def store(f, *args, **kwargs):
"""
Decorator that modifies the function f to store its own arguments in the
unit it returns.
"""
unit = f(*args, **kwargs)
# store the unit's name, the function ... | return arguments.accept(*constraints, **kwargs) (store(f)) |
Here is a snippet: <|code_start|> """
Decorator that modifies the function f to store its own arguments in the
unit it returns.
"""
unit = f(*args, **kwargs)
# store the unit's name, the function object, and the value of
# each argument
unit._name = f.name if isinstance(f, overload._Over... | argnames = misc.getargspec(unit._function)[0] |
Given snippet: <|code_start|>#
# router.py - A simple OSC-controlled MIDI router that sends all incoming
# events to the output port/channel determined by the current scene/subscene.
#
# To route the output to a different MIDI port/channel, send an OSC message
# /mididings/switch_scene <port> <channel>
# to UDP port 56... | OSCInterface(56418, 56419), |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# mididings
#
# Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; eit... | @_arguments.accept(None, _arguments.nullable(str), _UNIT_TYPES, |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
#
# mididings
#
# Copyright (C) 2011 Sébastien Devaux
# Copyright (C) 2012-2014 Dominic Sacré <dominic.sacre@gmx.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public ... | return event.SysExEvent(ev.port, sysex) |
Given the following code snippet before the placeholder: <|code_start|>#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.... | setup.reset() |
Given the following code snippet before the placeholder: <|code_start|> resulting events.
"""
r = self.run_scenes({ setup.get_config('data_offset'): patch }, events)
return list(itertools.chain(*r))
def run_scenes(self, scenes, events):
"""
Run the given events throug... | e = engine.Engine() |
Here is a snippet: <|code_start|>
def run_scenes(self, scenes, events):
"""
Run the given events through the given scenes, return the list of
resulting events.
"""
# run scenes
r1 = self._run_scenes_impl(scenes, events)
# check if events can be rebuilt from t... | if not misc.issequence(events): |
Given the following code snippet before the placeholder: <|code_start|> rep = repr(v)
if 'Process' in rep or 'Call' in rep:
# patches with Process() units etc. are too tricky for now
return None
w = eval(rep, self.mididings_dict)
# the repr(... | type = random.choice(list(set(constants._EVENT_TYPES.values()) |
Given the following code snippet before the placeholder: <|code_start|>#
# klick.py - uses SendOSC() to start/stop klick, or change its tempo
#
# klick: http://das.nasophon.de/klick/
#
# CC 13 runs/terminates the klick process (alternatively,
# run "klick -P -o 1234"),
# CC 14 starts/stops the metronome, and CC 15 chan... | SendOSC(port, '/klick/quit'), |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
#
# mididings
#
# Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Softwa... | @arguments.accept(int) |
Predict the next line after this snippet: <|code_start|> def test_kwargs_any(self):
@arguments.accept(None, kwargs={None: int})
def foo(*args, **kwargs):
self.assertEqual(len(args), 2)
self.assertEqual(args[0], 23)
self.assertEqual(args[1], 42)
self.ass... | self.assertTrue(misc.issequenceof(a, int)) |
Predict the next line after this snippet: <|code_start|> self.notes[-2][0], self.notes[-2][1])
r = [ev, noteon]
else:
# note isn't sounding, discard note off
r = None
# remove released note from list
... | _m.Process(_PerChannel( |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
#
# mididings
#
# Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either ver... | return _Unit(_mididings.Sanitize()) |
Based on the snippet: <|code_start|> """
if port is None:
port = _util.offset(0)
if channel is None:
channel = _util.offset(0)
if isinstance(program, tuple):
bank, program = program
else:
bank = None
init = []
if bank is not None:
init.append(Ctrl(po... | return Fork([ |
Given snippet: <|code_start|> init.append(Ctrl(port, channel, 11, expression))
for k, v in ctrls.items():
init.append(Ctrl(port, channel, k, v))
return Fork([
Init(init),
Port(port) >> Channel(channel)
])
class OutputTemplate(object):
"""
OutputTemplate(*args, **kw... | return (Chain(self.before) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# mididings
#
# Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; eit... | @_unitrepr.accept(_UNIT_TYPES) |
Next line prediction: <|code_start|>
To send a bank select (CC #0 and CC #32) before the program change,
*program* can be a tuple with two elements, where the first element is the
bank number, and the second is the program number.
Values for the commonly used controllers *volume* (#7), *pan* (#10) and
... | init.append(Program(port, channel, program)) |
Given the following code snippet before the placeholder: <|code_start|>
Route incoming events to the specified *port* and *channel*.
When switching to the scene containing this unit, a program change and/or
arbitrary control changes can be sent.
To send a bank select (CC #0 and CC #32) before the progr... | init.append(Ctrl(port, channel, 0, bank // 128)) |
Continue the code snippet: <|code_start|> port = _util.offset(0)
if channel is None:
channel = _util.offset(0)
if isinstance(program, tuple):
bank, program = program
else:
bank = None
init = []
if bank is not None:
init.append(Ctrl(port, channel, 0, bank // ... | Port(port) >> Channel(channel) |
Next line prediction: <|code_start|> port = _util.offset(0)
if channel is None:
channel = _util.offset(0)
if isinstance(program, tuple):
bank, program = program
else:
bank = None
init = []
if bank is not None:
init.append(Ctrl(port, channel, 0, bank // 128))... | Port(port) >> Channel(channel) |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
#
# mididings
#
# Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either ver... | widget_factory = LiveThemedFactory(self.options.color, |
Given the following code snippet before the placeholder: <|code_start|>#
# mididings
#
# Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foun... | widget_factory = UnthemedFactory() |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
#
# mididings
#
# Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either... | self.osc = LiveOSC(self, self.options.control_port, |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
#
# mididings
#
# Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
... | argspec = misc.getargspec(f) |
Next line prediction: <|code_start|> return r
elif ev.type == _m.NOTEON:
self.held_notes.add(ev.note)
return ev
elif ev.type == _m.NOTEOFF:
self.held_notes.discard(ev.note)
# send note off only if the note is not currently being sustained
... | proc = _m.Process(_PerChannel(lambda: _SostenutoToNoteoff(ctrl))) |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
#
# mididings
#
# Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Softwa... | f = Chain(~t(k) for k in dd.keys()) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
#
# mididings
#
# Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; eit... | r = Fork((t(k) >> w) for k, w in dd.items()) |
Given the code snippet: <|code_start|>def _make_split(t, d, unpack=False):
if unpack:
# if dictionary key is a tuple, unpack and pass as individual
# parameters to ctor
t = lambda p, t=t: t(*(p if isinstance(p, tuple) else (p,)))
# build dict with all items from d, except d[None]
dd... | _UNIT_TYPES |
Predict the next line for this snippet: <|code_start|> # build fork from all normal items
r = Fork((t(k) >> w) for k, w in dd.items())
# add else-rule, if any
if None in d:
f = Chain(~t(k) for k in dd.keys())
r.append(f >> d[None])
return r
def _make_threshold(f, patch_lower, patc... | return _make_split(PortFilter, mapping) |
Next line prediction: <|code_start|> ~f >> patch_upper,
])
@_arguments.accept({
_arguments.nullable(_arguments.flatten(_util.port_number, tuple)):
_UNIT_TYPES
})
def PortSplit(mapping):
"""
PortSplit(mapping)
Split events by input port, with *mapping* being a dictionary of the for... | return _make_split(ChannelFilter, mapping) |
Based on the snippet: <|code_start|>
@_arguments.accept({
_arguments.nullable(_arguments.flatten(_util.channel_number, tuple)):
_UNIT_TYPES
})
def ChannelSplit(mapping):
"""
ChannelSplit(mapping)
Split events by input channel, with *mapping* being a dictionary of
the form ``{channels: patc... | return _make_threshold(KeyFilter(0, threshold), |
Here is a snippet: <|code_start|>})
def CtrlSplit(mapping):
"""
CtrlSplit(mapping)
Split events by controller number, with *mapping* being a dictionary of
the form ``{ctrls: patch, ...}``.
Non-control-change events are discarded.
"""
return _make_split(CtrlFilter, mapping)
@_overload.mark... | return _make_threshold(CtrlValueFilter(0, threshold), |
Based on the snippet: <|code_start|>@_arguments.accept({
_arguments.nullable(_arguments.flatten(_util.program_number, tuple)):
_UNIT_TYPES
})
def ProgramSplit(mapping):
"""
ProgramSplit(mapping)
Split events by program number, with *mapping* being a dictionary of the
form ``{programs: patch... | return _make_split(SysExFilter, mapping) |
Here is a snippet: <|code_start|> """
A decorator that applies type checks and other constraints to the
arguments of the decorated function.
Constraints must be given in the order of the function's positional
arguments, one constraint per argument. If the function accepts
variable arguments, one... | argspec = misc.getargspec(f) |
Given snippet: <|code_start|> # monophonic: turn off previous note, play new note
if len(self.notes):
r = [_event.NoteOffEvent(
ev.port, ev.channel, self.notes[0], 0)]
else:
r = []
... | _m.Process(_PerChannel( |
Using the snippet: <|code_start|> # run the same interpreter with the same arguments again
_os.execl(_sys.executable, _sys.executable, *_sys.argv)
def quit(self):
self._quit.set()
@_overload.mark(
"""
run(patch)
run(scenes=..., control=None, pre=None, post=None)
Start the... | @_arguments.accept(_UNIT_TYPES) |
Based on the snippet: <|code_start|> The first version just runs a single patch, while the second version
allows switching between multiple scenes.
:param patch: a single patch.
:param scenes: a dictionary with program numbers as keys, and
:class:`Scene` objects, :class:`SceneGroup` objects or p... | {_util.scene_number: _SCENE_TYPES}, |
Here is a snippet: <|code_start|>
dir = os.path.dirname(os.path.realpath(__file__))
sys.path.append(dir + '/../..')
class TestCapacities(unittest.TestCase):
def test_tabular_eps_greedy(self):
nb_states = 3
nb_actions = 2
with tf.Graph().as_default():
tf.set_random_seed(1)
... | actions, probs = capacities.tabular_eps_greedy(inputs_t, q_preds, nb_states, nb_actions, N0, 0.) |
Here is a snippet: <|code_start|> def play(self, env, render=True):
obs = env.reset()
score = 0
done = False
while True:
if render:
env.render()
act, state = self.act(obs)
next_obs, reward, done, info = env.step(act)
sc... | config.update(phis.getPhiConfig(config['env_name'], config['debug'])) |
Next line prediction: <|code_start|>
dir = os.path.dirname(os.path.realpath(__file__))
sys.path.append(dir + '/../..')
class TestReplayBuffer(unittest.TestCase):
def test_replay_buffer_init(self):
templates = [('test1', tf.int32, ()), ('test2', tf.int32, (1,)), ('test3', tf.int32, (2, 2))]
capaci... | rep_buf = replay_buffer.ReplayBuffer(templates, capacity) |
Given the code snippet: <|code_start|> random_config.update(fixed_params)
return random_config
def act(self, obs, done=False):
state_id = self.phi(obs, done)
act, estimate = self.sess.run([self.action_t, self.q_value_t], feed_dict={
self.inputs_plh: [ state_id ]
... | self.actions_t, self.probs_t = capacities.tabular_eps_greedy( |
Predict the next line for this 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()
}
rand... | self.actions_t, self.probs_t = capacities.tabular_UCB( |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.