Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- class PVData(SurrogatePK, Model): __tablename__ = "pvdata" id = Column(db.Integer(), nullable=False, primary_key=True) created_at = Column(db.Text(), nullable=False, default=dt.datetime.utcnow) dc_1_u = Column(db.Integer(), nullable=Tr...
def __init__(self):
Using the snippet: <|code_start|># -*- coding: utf-8 -*- class Electricity(SurrogatePK, Model): __tablename__ = "electricity_data" id = Column(db.Integer(), nullable=False, primary_key=True) created_at = Column(db.Text(), nullable=False, default=dt.datetime.utcnow) meter_180 = Column(db.Float(), null...
def __init__(self):
Based on the snippet: <|code_start|>def get_current_year_earnings(): query = """SELECT sum( delta_280 ) * 0.1702 AS total_earnings -- EUR per kWh FROM ( SELECT max( meter_280 ) - min( meter_280 ) AS delta_280 ...
) q;"""
Predict the next line for this snippet: <|code_start|> @cache.cached(timeout=3600, key_prefix="last_year_export") def get_last_year_export(): current_year = datetime.now().year return ( Electricity.query.with_entities(Electricity.meter_280) .filter(func.strftime("%Y", Electricity.created_at) == ...
strftime( '%Y-%m-%d', created_at )
Continue the code snippet: <|code_start|> blueprint = Blueprint("weather", __name__, url_prefix="/weather", static_folder="../static") @blueprint.route("/daily") @blueprint.route("/daily/<date>") def daily(date=datetime.now().strftime("%Y-%m-%d")): try: current_date = datetime.strptime(date, "%Y-%m-%d") ...
yesterday=yesterday,
Predict the next line for this snippet: <|code_start|> :return: the number of kWh for the remaining year """ query = """SELECT SUM(energy) AS prediction FROM ( SELECT max(total_energy) - min(total_energy) AS energy ...
return result
Based on the snippet: <|code_start|> query = """SELECT SUM(energy) AS prediction FROM ( SELECT max(total_energy) - min(total_energy) AS energy FROM pvdata WHERE ...
def get_efficiency(pv):
Here is a snippet: <|code_start|> class ConfigReader(object): def __init__(self, config_file_path): self._config = self._read(config_file_path) def _read(self, config_file_path): try: _, ext = os.path.splitext(config_file_path) with open(config_file_path) as fin: ...
return data
Based on the snippet: <|code_start|> with open(os.devnull) as devnull: git_hash = subprocess.check_output( ["git", "rev-parse", "HEAD"], cwd=os.path.dirname(os.path.abspath(__file__)), stderr=devnull, ...
plugin_paths = []
Next line prediction: <|code_start|> log = Messenger() try: parser = ArgumentParser(formatter_class=RawTextHelpFormatter) add_options(parser) options = parser.parse_args() if options.version: try: with open(os.devnull) as devnull: gi...
elif options.no_color:
Given snippet: <|code_start|> if options.force_color and options.no_color: log.error("`--force-color` and `--no-color` cannot both be provided") exit(1) elif options.force_color: log.use_color(True) elif options.no_color: log.use_color(False) ...
if options.base_directory:
Given the code snippet: <|code_start|> def main(): log = Messenger() try: parser = ArgumentParser(formatter_class=RawTextHelpFormatter) add_options(parser) options = parser.parse_args() if options.version: try: with open(os.devnull) as devnull: ...
elif options.force_color:
Predict the next line after this snippet: <|code_start|> try: with open(os.devnull) as devnull: git_hash = subprocess.check_output( ["git", "rev-parse", "HEAD"], cwd=os.path.dirname(os.path.abspath(__file__)), ...
if not options.disable_built_in_plugins:
Here is a snippet: <|code_start|> class Dispatcher(object): def __init__( self, base_directory, only=None, skip=None, exit_on_failure=False, options=Namespace() ): self._log = Messenger() self._setup_context(base_directory, options) self._load_plugins() self._only = only...
and action in self._skip
Continue the code snippet: <|code_start|> if not os.path.exists(path): raise DispatchError("Nonexistent base directory") self._context = Context(path, options) def dispatch(self, tasks): success = True for task in tasks: for action in task: if ...
handled = True
Based on the snippet: <|code_start|> class Messenger(with_metaclass(Singleton, object)): def __init__(self, level=Level.LOWINFO): self.set_level(level) self.use_color(True) def set_level(self, level): self._level = level def use_color(self, yesno): self._use_color = yesno ...
if level >= self._level:
Given the following code snippet before the placeholder: <|code_start|> class Messenger(with_metaclass(Singleton, object)): def __init__(self, level=Level.LOWINFO): self.set_level(level) self.use_color(True) def set_level(self, level): self._level = level def use_color(self, yesno...
def lowinfo(self, message):
Given the following code snippet before the placeholder: <|code_start|># Script to compare Snack formant methods on Windows # There is a known discrepancy between Snack formants calculated using # the full Snack Tcl library ('tcl' method) and the Windows standalone # executable ('exe' method) # Licensed under Apache v...
fig = plt.figure(figsize=(8,8))
Given snippet: <|code_start|> def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument( '--preserve', dest='preserve', default=False, action='store_true', help='Exit normally if any accounts already exist.', ) parser.add_...
equity = Account.objects.create(name='Equity', code='3', type=T.equity, **kw)
Here is a snippet: <|code_start|> @shared_task @transaction.atomic() def notify_housemates(): for billing_cycle in BillingCycle.objects.filter(transactions_created=True, statements_sent=False): billing_cycle.notify_housemates() @shared_task @transaction.atomic() def import_tellerio(): settings = Set...
first_billing_cycle = BillingCycle.objects.first()
Predict the next line for this snippet: <|code_start|> # Create your models here. class SettingsManager(models.Manager): def get(self): # TODO: Pull from cache try: <|code_end|> with the help of current file imports: from django.contrib.postgres.fields import ArrayField from django.db import m...
return super(SettingsManager, self).get()
Predict the next line after this snippet: <|code_start|> class DashboardViewTestCase(DataProvider, TestCase): def setUp(self): self.url = reverse('dashboard:dashboard') Command().handle(currency='GBP') <|code_end|> using the current file's imports: from django.test import TestCase from django....
def test_get(self):
Given the code snippet: <|code_start|> class DashboardViewTestCase(DataProvider, TestCase): def setUp(self): self.url = reverse('dashboard:dashboard') Command().handle(currency='GBP') def test_get(self): <|code_end|> , generate the next line using the imports in this file: from django.test ...
self.login()
Based on the snippet: <|code_start|> class GeneralSettingsForm(forms.ModelForm): default_currency = forms.ChoiceField(choices=CURRENCY_CHOICES, initial='EUR') additional_currencies = forms.MultipleChoiceField(choices=CURRENCY_CHOICES, widget=forms.SelectMultiple(), ...
def __init__(self, *args, **kwargs):
Given the code snippet: <|code_start|> class RedisSub(databench.Analysis): def __init__(self): # create a connection to redis self.redis_client = redis_creator().pubsub() <|code_end|> , generate the next line using the imports in this file: import databench import tornado.gen from analyses.redis...
self.redis_client.subscribe('someStatsProvider')
Using the snippet: <|code_start|> def can_handle_character(self, character): return character in Tube.__punctuation_characters def can_handle_contact(self, contact, clock): return contact.has('tubestation') def num_required_contacts(self): return 1 def transform(self, characte...
if name == station:
Predict the next line after this snippet: <|code_start|> # Tube station data from http://commons.wikimedia.org/wiki/London_Underground_geographic_maps/CSV class Tube(Transformer): __punctuation_characters = ['.', ',', '?', '!', ';', ':', '-'] def __init__(self): self.__import_stations() def can_h...
return contact.has('tubestation')
Here is a snippet: <|code_start|> class Tweet(Transformer): def can_handle_character(self, character): return character == ' ' def can_handle_contact(self, contact, clock): return (contact.has('twitter') and contact.get('twitter') == True) def num_required_contacts(self): return 1...
contact = contacts[0]
Here is a snippet: <|code_start|> class BankWire(Transformer): def can_handle_character(self, character): return utils.is_character_rare2(character) def can_handle_contact(self, contact, clock): return contact.has('name') def num_required_contacts(self): return 2 def transfor...
contact_from, contact_to, odd = utils.rare2_character_transform(character, contacts, 'name')
Given the code snippet: <|code_start|> class BankWire(Transformer): def can_handle_character(self, character): return utils.is_character_rare2(character) def can_handle_contact(self, contact, clock): <|code_end|> , generate the next line using the imports in this file: from ..lib.transformer import T...
return contact.has('name')
Based on the snippet: <|code_start|> class FBMsg(Transformer): def can_handle_character(self, character): return utils.is_character_common(character) <|code_end|> , predict the immediate next line with the help of imports: from ..lib.transformer import Transformer from ..lib.instruction import Instructio...
def can_handle_contact(self, contact, clock):
Given the following code snippet before the placeholder: <|code_start|> class SMS(Transformer): def can_handle_character(self, character): return utils.is_character_common(character) <|code_end|> , predict the next line using imports from the current file: from ..lib.transformer import Transformer from ....
def can_handle_contact(self, contact, clock):
Continue the code snippet: <|code_start|> class SMS(Transformer): def can_handle_character(self, character): return utils.is_character_common(character) <|code_end|> . Use current file imports: from ..lib.transformer import Transformer from ..lib.instruction import Instruction import utils and context (...
def can_handle_contact(self, contact, clock):
Next line prediction: <|code_start|> class DebitCard(Transformer): def can_handle_character(self, character): return utils.is_character_digit1(character) def can_handle_contact(self, contact, clock): return True def num_required_contacts(self): return 1 def transform(self, ch...
contact = contacts[0]
Based on the snippet: <|code_start|> class DebitCard(Transformer): def can_handle_character(self, character): return utils.is_character_digit1(character) def can_handle_contact(self, contact, clock): return True def num_required_contacts(self): <|code_end|> , predict the immediate next li...
return 1
Predict the next line after this snippet: <|code_start|> class ContactlessCard(Transformer): def can_handle_character(self, character): return utils.is_character_digit2(character) def can_handle_contact(self, contact, clock): return (contact.has('contactless') and contact.get('contactless') ==...
def transform(self, character, contacts, clock):
Predict the next line for this snippet: <|code_start|> class Paypal(Transformer): def can_handle_character(self, character): return utils.is_character_rare3(character) def can_handle_contact(self, contact, clock): <|code_end|> with the help of current file imports: from ..lib.transformer import Tran...
return contact.has('email')
Given the code snippet: <|code_start|> class Phone(Transformer): def can_handle_character(self, character): return utils.is_character_rare1(character) def can_handle_contact(self, contact, clock): <|code_end|> , generate the next line using the imports in this file: from ..lib.transformer import Tran...
return contact.has('phone')
Predict the next line for this snippet: <|code_start|> class Phone(Transformer): def can_handle_character(self, character): return utils.is_character_rare1(character) def can_handle_contact(self, contact, clock): <|code_end|> with the help of current file imports: from ..lib.transformer import Trans...
return contact.has('phone')
Using the snippet: <|code_start|>def get_devices(request): return render(request, "devices.html", { 'messagestore': jobs.get_messages(), 'devices': get_entries(), }) @require_POST @login_required def refresh_devices(request): try: utils.exec_upri_config('parse_user_agents') exc...
@login_required
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals logger = logging.getLogger('uprilogger') class VpnProfileForm(forms.Form): profilename = forms.CharField( required=True, label=ugettext_lazy("Name:"), max_length=64,...
)
Given the code snippet: <|code_start|>from __future__ import unicode_literals logger = logging.getLogger('uprilogger') @login_required def check_connection(request): if request.method != 'POST': raise Http404() # Check VPN connectivity # Get log lines with TLS-auth error before connection ...
with open(settings.OPENVPN_LOGFILE) as f:
Based on the snippet: <|code_start|> response = HttpResponse(profile.config, content_type='application/x-openvpn-profile') response['Content-Disposition'] = 'attachment; filename="upribox-%s.ovpn"' % profile.profilename return response else: # link timed out ...
if request.method != 'POST':
Here is a snippet: <|code_start|> days.append({ 'date': date.strftime('%Y-%m-%d'), 'traffic': traffic, 'text': texts }) total += sum(traffic.values()) total_protocols.update(traffic) protocols_sorted = sorted(total_protocols, key=total_protocols.g...
else:
Continue the code snippet: <|code_start|># coding: utf-8 def get_protocol_sums(traffic): protocols = parse_traffic_dict(traffic) amounts = dict() texts = dict() for protocol in protocols.keys(): text = list() amount = 0.0 text.append(protocol.encode('utf-8')) if 'sent...
def parse_traffic_dict(traffic):
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals # Get an instance of a logger logger = logging.getLogger('uprilogger') @require_http_methods(["GET", "POST"]) @login_required def silent(request): context = {} if request.method == 'POS...
logger.error("form validation failed for %s" % request.path)
Predict the next line for this snippet: <|code_start|> logger.debug("configuring device modes") utils.exec_upri_config('configure_devices') except utils.AnsibleError as e: logger.error("ansible failed with error %d: %s" % (e.rc, e.message)) ...
with sqlite3.connect(dbfile) as conn:
Given snippet: <|code_start|> downlink_format = common.df(m) crc = common.crc(m) icao = adsb.icao(m) tc = adsb.typecode(m) if 1 <= tc <= 4: category = adsb.category(m) callsign = adsb.callsign(m) if tc == 19: velocity = adsb.velocity(m...
else:
Continue the code snippet: <|code_start|> print_name() tret = jsocket.gethostname() ret = socket.gethostname() assert(ret == tret) # @check_stop def test_gethostbyaddr(): print_name() tret = jsocket.gethostbyaddr(HOST) ret = socket.gethostbyaddr(HOST) print(tret) print(ret) asser...
def test_getnameinfo():
Continue the code snippet: <|code_start|> # @check_stop def test_gethostbyname_ex_fail(): print_name() with raises(jsocket.gaierror): ret = jsocket.gethostbyname_ex(FAIL_HOST) # @check_stop def test_gethostname(): print_name() tret = jsocket.gethostname() ret = socket.gethostname() ass...
print(ret)
Next line prediction: <|code_start|> def _accept(): s = jsocket.socket(jsocket.AF_INET, jsocket.SOCK_STREAM) s.setsockopt(jsocket.SOL_SOCKET, jsocket.SO_REUSEADDR, 1) s.bind(("", 8080)) s.listen(1) c, a = s.accept() assert(a[0] == "127.0.0.1") f = c.makefile(m...
def test_recv():
Next line prediction: <|code_start|> def _conn(): s = jsocket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("", 8080)) s.send(b"A" * 10) return "_conn" f1 = executor.submit(_accept) f2 = executor.submit(_conn) r = event_loop.run_until_complete(f1) assert(r == ...
return "_accept"
Using the snippet: <|code_start|>patch.patch_socket() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) s.setsockopt(socket.IPPROTO_TCP, socket.TCP_DEFER_ACCEPT, 1) s.bind(("", 5000)) s.listen(1024) loop...
if not buf:
Based on the snippet: <|code_start|>def test_executor_submit(): print_name() event_loop = loop.get_event_loop() executor = jega.TaskExecutor(event_loop) def _call(a, b): return a + b f = executor.submit(_call, 1, 2) assert(3 == f.result()) def test_executor_until_complete(): prin...
return a / b
Given the code snippet: <|code_start|> def test_event_simple(): print_name() ev = Event() def waiter(): r = ev.wait() return r f1 = jega.spawn(waiter) f2 = jega.spawn(ev.set) r = f1.result() <|code_end|> , generate the next line using the imports in this file: from jega.even...
assert(True == r)
Predict the next line for this snippet: <|code_start|> class Packet15Parser(object): def parse(self, world, player, data, ev_man): streamer = Streamer(data) streamer.next_byte() # Skip packet byte item_id = streamer.next_short() position = (streamer.next_float(), streamer.next_float()) velocity = (streame...
if not item_id in world.item_owner_index:
Using the snippet: <|code_start|> class Packet15Parser(object): def parse(self, world, player, data, ev_man): streamer = Streamer(data) streamer.next_byte() # Skip packet byte <|code_end|> , determine the next line of code. You have imports: from terrabot.util.streamer import Streamer from terrabot.events.even...
item_id = streamer.next_short()
Based on the snippet: <|code_start|> class Packet15Parser(object): def parse(self, world, player, data, ev_man): streamer = Streamer(data) streamer.next_byte() # Skip packet byte item_id = streamer.next_short() position = (streamer.next_float(), streamer.next_float()) velocity = (streamer.next_float(), st...
prefix = streamer.next_byte()
Given the following code snippet before the placeholder: <|code_start|> for y in range(height): for x in range(width): if repeat_count > 0: repeat_count -= 1 world.tiles[starty + y][startx + x] = last_tile else: ...
frame_x = 0
Using the snippet: <|code_start|> class PacketAParser(object): def parse(self, world, player, data, ev_man): streamer = Streamer(data) streamer.next_byte() # Skip packet number byte compressed = streamer.next_byte() if compressed: compressed_data = streamer.remainder() ...
flag2 = streamer.next_byte()
Based on the snippet: <|code_start|> starty = streamer.next_int32() width = streamer.next_short() height = streamer.next_short() repeat_count = 0 last_tile = None for y in range(height): for x in range(width): if repeat_count > 0: ...
wire3 = flag2 & 8 > 0
Continue the code snippet: <|code_start|> class Packet7Parser(object): def parse(self, world, player, data, ev_man): streamer = Streamer(data) streamer.next_byte() # Ignore packet ID byte world.time = streamer.next_int32() world.daynight = streamer.next_byte() <|code_end|> . Use cu...
world.moonphase = streamer.next_byte()
Next line prediction: <|code_start|> bot = TerraBot('127.0.0.1') event = bot.get_event_manager() @event.on_event(Events.ItemOwnerChanged) def logged_in(event_id, data): print(data) @event.on_event(Events.ItemDropped) def drop_update(event_id, data): print("New item dropped") @event.on_event(Events.ItemDropUp...
bot.start()
Based on the snippet: <|code_start|> bot = TerraBot('127.0.0.1') event = bot.get_event_manager() @event.on_event(Events.ItemOwnerChanged) def logged_in(event_id, data): print(data) @event.on_event(Events.ItemDropped) <|code_end|> , predict the immediate next line with the help of imports: from terrabot import Te...
def drop_update(event_id, data):
Given the following code snippet before the placeholder: <|code_start|> # Create a TerraBot object bot = TerraBot('127.0.0.1') event = bot.get_event_manager() # Connect a function to an event using a decorator @event.on_event(Events.Chat) def chat(event_id, msg): # Do something with the message # In this case...
while bot.client.running:
Given the code snippet: <|code_start|> # Create a TerraBot object bot = TerraBot('127.0.0.1') event = bot.get_event_manager() # Connect a function to an event using a decorator @event.on_event(Events.Chat) def chat(event_id, msg): # Do something with the message # In this case, stop the bot if the word "Stop"...
if "stop" in msg:
Next line prediction: <|code_start|> class Packet39Parser(object): def parse(self, world, player, data, ev_man): streamer = Streamer(data) streamer.next_byte() # Skip packet number item_index = streamer.next_short() <|code_end|> . Use current file imports: (from terrabot.util.streamer i...
world.item_owner_index[item_index] = 255
Continue the code snippet: <|code_start|> @staticmethod def convert(value, unit, axis): 'convert value to a scalar or array' return dates.date2num(value) @staticmethod def axisinfo(unit, axis): 'return major and minor tick locators and formatters' ...
def __init__(self, majloc=None, minloc=None,
Using the snippet: <|code_start|> 'convert value to a scalar or array' return dates.date2num(value) @staticmethod def axisinfo(unit, axis): 'return major and minor tick locators and formatters' if unit!='date': return None majloc = dates.AutoDa...
default_limits=None):
Given the following code snippet before the placeholder: <|code_start|> log = core.log class CassandraMigrations(core.MigrationsExecutor): engine = 'cassandra' filename_extensions = ['cql'] TABLE = 'migration' def __init__(self, db_config, repository): core.MigrationsExecutor.__init__(se...
if db_config['pylib_path'] not in sys.path:
Given the code snippet: <|code_start|>from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals def make_venv(): enable_coverage() venv = Path('venv') run('virtualenv', venv.strpath) install_coverage(venv.strpath) pip = venv.join('bin/...
venv = make_venv()
Next line prediction: <|code_start|>from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals def assert_c_extension_runs(): out, err = run('venv/bin/c-extension-script') assert err == '' assert out == 'hello world\n' <|code_end|> . Use curren...
out, err = run('sh', '-c', '. venv/bin/activate && c-extension-script')
Here is a snippet: <|code_start|>from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals ENV_WHITELIST = ( # allows coverage of subprocesses 'COVERAGE_PROCESS_START', # used in the configuration of coverage 'TOP', # let's not fill up ...
'TERM',
Given the code snippet: <|code_start|>from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals @pytest.mark.usefixtures('pypi_server') def test_trivial(tmpdir): tmpdir.chdir() <|code_end|> , generate the next line using the imports in this file: impo...
requirements('')
Predict the next line for this snippet: <|code_start|>from __future__ import print_function from __future__ import unicode_literals ALWAYS = {'pip', 'setuptools', 'venv-update', 'wheel'} def get_installed(): out, err = run('myvenv/bin/python', '-c', '''\ import pip_faster as p for p in sorted(p.reqnames(p.pip_...
def test_pip_get_installed(tmpdir):
Given the code snippet: <|code_start|>for p in sorted(p.reqnames(p.pip_get_installed())): print(p)''') assert err == '' out = set(out.split()) # Most python distributions which have argparse in the stdlib fail to # expose it to setuptools as an installed package (it seems all but ubuntu # do t...
'pytest',
Next line prediction: <|code_start|> last_line = HELP_OUTPUT.rsplit('\n', 2)[-2].strip() assert last_line.startswith('Please send issues to: https://') out, err = venv_update('--help') assert strip_coverage_warnings(err) == '' assert out == HELP_OUTPUT out, err = venv_update('-h') assert st...
invalid option: venv
Given the code snippet: <|code_start|> class ChatRecord(Record): record_type = None database_id = '_public' def save(self): database = self._get_database() database.save([self]) def delete(self): <|code_end|> , generate the next line using the imports in this file: from skygear.mode...
database = self._get_database()
Continue the code snippet: <|code_start|> ["in", {"$type": "keypath", "$val": "type"}, ["cat", "dog"]]] self.assertListEqual(expected, p.to_dict()) def test_compound_statement_1(self): p = Predicate(_id__eq="chima", gender__eq="M", type__eq="dog") p2 = Predicate(_id__eq="f...
["not", ["and", ["eq", {"$type": "keypath", "$val": "_id"}, "milktea"],
Given the following code snippet before the placeholder: <|code_start|> @staticmethod def _encode_id(record_id): return record_id.type + "/" + record_id.key def delete(self, arg): if not isinstance(arg, list): arg = [arg] ids = [Database._encode_id(item.id) ...
if query.limit is not None:
Given 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 exp...
'database_id': self.database_id,
Based on the snippet: <|code_start|> class TestPublishEvent(unittest.TestCase): def record(self): return deserialize_record({ '_id': 'message/1', '_access': None, '_ownerID': 'user1', 'conversation': 'conversation1', 'body': 'hihi' }) ...
'_access': None,
Predict the next line after this snippet: <|code_start|> class MessageHistory(ChatRecord): record_type = 'message_history' def __init__(self, message): super().__init__(RecordID(self.record_type, str(uuid.uuid4())), current_user_id(), message.acl) ...
if key in message:
Using the snippet: <|code_start|> None, data={ 'user': Reference(RecordID('user', user_id)), 'message': Reference(RecordID('message', message_id)) } ) @classmethod def consistent_id(cls, user_id: str, message_id: str) -> str: se...
return cls.fetch_all(receipt_ids)
Here is a snippet: <|code_start|> class TestHandleMessageBeforeSave(unittest.TestCase): def setUp(self): self.conn = None self.patchers = [ patch('chat.utils.skyoptions', Mock(return_value={'masterkey': 'secret'})) <|code_end|> . Write the next line using the current...
]
Here is a snippet: <|code_start|> class TestHandleMessageBeforeSave(unittest.TestCase): def setUp(self): self.conn = None self.patchers = [ patch('chat.utils.skyoptions', Mock(return_value={'masterkey': 'secret'})) ] for each_patcher in self.patchers:...
def record(self):
Given the following code snippet before the placeholder: <|code_start|> def _publish_event(user_ids: [], event: str, data: dict = None) -> None: if not isinstance(user_ids, list): user_ids = user_ids if len(user_ids) == 0: return channel_names = _get_channels_by_user_ids(user_ids) if c...
def _publish_record_event(user_ids: [],
Given the code snippet: <|code_start|> def _publish_event(user_ids: [], event: str, data: dict = None) -> None: if not isinstance(user_ids, list): user_ids = user_ids if len(user_ids) == 0: return channel_names = _get_channels_by_user_ids(user_ids) if channel_names: hub = Hub(a...
'event': event,
Here is a snippet: <|code_start|> def _publish_event(user_ids: [], event: str, data: dict = None) -> None: if not isinstance(user_ids, list): user_ids = user_ids if len(user_ids) == 0: return channel_names = _get_channels_by_user_ids(user_ids) if channel_names: hub = Hub(api_ke...
'event': event,
Continue the code snippet: <|code_start|> def serialize_record(record): r = skyserialize(record) if 'attachment' in r: r['attachment']['$url'] = sign_asset_url(r['attachment']['$name']) <|code_end|> . Use current file imports: from skygear.encoding import serialize_record as skyserialize from .asset ...
return r
Given snippet: <|code_start|> message_history_schema = _message_history_schema() schema_helper.create([user_schema, user_conversation_schema, conversation_schema, message_schema, messag...
SELECT
Predict the next line after this snippet: <|code_start|> def register_initialization_event_handlers(settings): def _base_message_fields(): return [Field('attachment', 'asset'), Field('body', 'string'), Field('metadata', 'json'), Field('conversation', 'ref(c...
def _message_schema():
Next line prediction: <|code_start|> fields = _base_message_fields() + [Field('parent', 'ref(message)')] return Schema('message_history', fields) @skygear.event("before-plugins-ready") def chat_plugin_init(config): container = SkygearContainer(api_key=skyoptions.masterkey) schema...
'ref(message)'),
Predict the next line for this snippet: <|code_start|> FROM information_schema.constraint_column_usage WHERE table_schema = '%(schema_name)s' AND table_name = 'user_channel' AND constraint_name = 'user_channel_database_id_key' ""...
UNIQUE (_database_id);
Predict the next line after this snippet: <|code_start|># Copyright 2017 Oursky Ltd. # # 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 # # Unl...
self.sort = []
Using the snippet: <|code_start|> # one_term() class OneTermMatchRule(SubtreeMatchRule): def __str__(self) -> str: return str(categorization.Category('one_term', self._positive_properties, self._negative_properties)) def __call__(self, category_list: Sequen...
for index in range(len(category_list)):
Predict the next line after this snippet: <|code_start|> self._counter += 1 else: assert index not in self._index_map assert not self._counter self._index_map[index] = len(self._tokens) self._tokens.append(Token(index, spelling, span, category)) self._l...
self._links[source_id][sink_id].add(label)
Predict the next line after this snippet: <|code_start|> span: Tuple[int, int] = None) -> int: """Called to indicate the occurrence of a token.""" if index is None: index = self._counter self._counter += 1 else: assert index not in self._in...
source_id = self._index_map[source_index]
Predict the next line after this snippet: <|code_start|> """Called to indicate the occurrence of a token.""" if index is None: index = self._counter self._counter += 1 else: assert index not in self._index_map assert not self._counter self._...
sink_id = self._index_map[sink_index]
Using the snippet: <|code_start|> self._index_map[index] = len(self._tokens) self._tokens.append(Token(index, spelling, span, category)) self._links.append({}) self._phrases.append([(category, frozenset())]) # For convenience, return the id of the token so users can know ...
self._phrase_stack[-1][-1].append((source_id, sink_id))