Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given snippet: <|code_start|> class PatentName(BaseItem): is_required = True crawler_id = url_detail.get('crawler_id') english = ['patent_name', 'invention_name'] chinese = '专利名称' @classmethod def parse(cls, raw, item, process=None): if process is not None: patent_name = pr...
def push_item(json_list, item: DataItem, title, name):
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- """ Created on 2018/3/14 @author: will4906 采集的内容、方式定义 """ <|code_end|> . Use current file imports: from bs4 import BeautifulSoup from controller.url_config import url_search, url_detail, url_related_info, url_full_text from crawler.items import Data...
class PatentId(BaseItem):
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- """ Created on 2018/3/14 @author: will4906 采集的内容、方式定义 """ class PatentId(BaseItem): is_required = True crawler_id = url_search.get('crawler_id') english = 'patent_id' chinese = ['专利标志', '专利id', '专利ID', '专利Id'] @cla...
item.patent_id = ResultItem(title=cls.title, value=str(patent_id))
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- """ Created on 2017/3/19 @author: will4906 基础路径模块 以下地址、文件名可根据用户使用自行修改,工程所有地址将会采用。 """ """ 路径设置 """ # 工程根目录,注意此处以初次调用这个变量的元素为准,工程起始目录定位在main,若有修改请注意这个位置 BASE_PATH = os.path.split(os.path.split(__file__)[0])[0] # 输出目录 OUTPUT_PATH = os.pat...
OUTPUT_GROUP_PATH = os.path.join(OUTPUT_PATH, TimeUtil.getFormatTime('%Y%m%d_%H%M%S'))
Next line prediction: <|code_start|># -*- coding: utf-8 -*- """ Created on 2018/2/25 @author: will4906 代理模块 程序的代理决定使用https://github.com/jhao104/proxy_pool的代理池作为代理方式, 开发者可以修改下方get_proxy函数进行自定义 """ logger = Logger(__name__) def notify_ip_address(): """ 通知专利网我们的ip地址, 这个网站比较特别,每当有陌生ip地址时,都需要通过这个方法向网站发...
resp = requests.post(url_pre_execute.get('url'), proxies=ctrl.PROXIES, timeout=bs.TIMEOUT, cookies=ctrl.COOKIES)
Using the snippet: <|code_start|># -*- coding: utf-8 -*- """ Created on 2018/2/25 @author: will4906 代理模块 程序的代理决定使用https://github.com/jhao104/proxy_pool的代理池作为代理方式, 开发者可以修改下方get_proxy函数进行自定义 """ logger = Logger(__name__) def notify_ip_address(): """ 通知专利网我们的ip地址, 这个网站比较特别,每当有陌生ip地址时,都需要通过这个方法向网站发送一次...
resp = requests.post(url_pre_execute.get('url'), proxies=ctrl.PROXIES, timeout=bs.TIMEOUT, cookies=ctrl.COOKIES)
Using the snippet: <|code_start|> return None def update_proxy(): """ 获取并校验代理ip地址 :return: """ if bs.USE_PROXY: i = 0 while True: try: get_proxy() notify_ip_address() return True except Exception: ...
ctrl.COOKIES = requests.get(url=url_index.get('url'), proxies=ctrl.PROXIES, timeout=bs.TIMEOUT).cookies
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- # Define here the models for your spider middleware # # See documentation in: # http://doc.scrapy.org/en/latest/topics/spider-middleware.html logger = Logger(__name__) class PatentMiddleware(RetryMiddleware): def process_request(self, request, spider): ...
if USE_PROXY and ctrl.PROXIES is not None:
Given the following code snippet before the placeholder: <|code_start|># Define here the models for your spider middleware # # See documentation in: # http://doc.scrapy.org/en/latest/topics/spider-middleware.html logger = Logger(__name__) class PatentMiddleware(RetryMiddleware): def process_request(self, reque...
login_ok = login()
Here is a snippet: <|code_start|> def process_item(self, item, spider): data = item.get('data').__dict__ table_dict = {} logger.info('采集内容:%s' % str(data)) for name, fields in info.data_table.items(): table_list = [[]] for key, value in data.items(): ...
conn = sqlite3.connect(bs.DATABASE_NAME)
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html logger = Logger(__name__) class CrawlerPipeline(obje...
logger.info('采集内容:%s' % str(data))
Using the snippet: <|code_start|># -*- coding: utf-8 -*- """ Created on 2018/2/27 @author: will4906 """ def resolve_data(item, title, itemvalue): <|code_end|> , determine the next line of code. You have imports: from entity.query_item import title_define and context (class names, function names, or code) available...
for key, value in title_define.items():
Predict the next line for this snippet: <|code_start|> while True: try: password = click.prompt('密码出错,请填写') self.password = password break except: pass # 账户信息的单例 account = Account() def change_...
result = get_captcha_result(CAPTCHA_MODEL_NAME, 'captcha.png')
Given the following code snippet before the placeholder: <|code_start|> """ 登录API :return: True: 登录成功; False: 登录失败 """ if username is None or password is None: username = account.username password = account.password ctrl.BEING_LOG = True if check_login_status(): ctrl.B...
cookies=ctrl.COOKIES, proxies=ctrl.PROXIES, timeout=TIMEOUT)
Using the snippet: <|code_start|> except: pass # 账户信息的单例 account = Account() def change_to_base64(source): """ 将参数进行base64加密 :param source: :return: """ return str(base64.b64encode(bytes(source, encoding='utf-8')), 'utf-8') def get_captcha(): """ ...
if USE_PROXY:
Continue the code snippet: <|code_start|> password = cfg.get('account', 'password') self.password = password except: while True: try: password = click.prompt('密码出错,请填写') self.password = password break ...
resp = requests.get(url=url_captcha.get('url'), cookies=ctrl.COOKIES, proxies=ctrl.PROXIES)
Using the snippet: <|code_start|> except: pass return False def login(username=None, password=None): """ 登录API :return: True: 登录成功; False: 登录失败 """ if username is None or password is None: username = account.username password = account.password ctrl.BEING...
form_data = url_login.get('form_data')
Given the following code snippet before the placeholder: <|code_start|> def check_login_status(): if USE_PROXY: try: if ctrl.PROXIES is not None: notify_ip_address() logger.info('当前已有登录状态') return True except: pass return Fa...
update_proxy()
Using the snippet: <|code_start|> # 账户信息的单例 account = Account() def change_to_base64(source): """ 将参数进行base64加密 :param source: :return: """ return str(base64.b64encode(bytes(source, encoding='utf-8')), 'utf-8') def get_captcha(): """ 获取验证码 :return: """ resp = requests.get...
notify_ip_address()
Given the following code snippet before the placeholder: <|code_start|> if USE_PROXY: try: if ctrl.PROXIES is not None: notify_ip_address() logger.info('当前已有登录状态') return True except: pass return False def login(username=No...
update_cookies()
Given the code snippet: <|code_start|> while True: try: password = click.prompt('密码出错,请填写') self.password = password break except: pass # 账户信息的单例 account = Account() def change_to_base64(source...
result = get_captcha_result(CAPTCHA_MODEL_NAME, 'captcha.png')
Predict the next line after this snippet: <|code_start|>""" 文件清理模块,调用后清理所有log和output文件 """ logging.getLogger(__name__).setLevel(logging.DEBUG) def clean_outputs(): """ 清理输出文件夹的内容 :return: """ <|code_end|> using the current file's imports: import logging import os import sys import shutil from con...
output_list = os.listdir(OUTPUT_PATH)
Given the following code snippet before the placeholder: <|code_start|> # 添加表 def addSheet(self, sheet): return self.getExcel("WRITE").add_sheet(sheet) # 获取表 def getSheet(self, which, mode): try: wb = self.getExcel(mode) if isinstance(which, str): ...
return ExcelEditor(wb, self.__fileName)
Next line prediction: <|code_start|># -*- coding: utf-8 -*- """ Created on 2018/2/27 @author: will4906 """ logging.getLogger(__name__).setLevel(logging.DEBUG) <|code_end|> . Use current file imports: (import logging import requests import controller as ctrl from service.account import * from service.proxy import...
@check_proxy
Given snippet: <|code_start|> transcoded = collections.OrderedDict() cls = type(self) for field in self.fields: descriptor = getattr(cls, field) value = self._fields[field] # Note that the descriptor handles nested fields and Nones transcod...
raise ConfigError('Failed to decode field: ' +
Continue the code snippet: <|code_start|> # Get the environment config setting, if it exists. If not, use a # long random path which we "know" will not exist. envpath = os.getenv( 'HYPERGOLIX_HOME', default = '/qdubuddfsyvfafhlqcqetfkokykqeulsguoasnzjkc' ) ...
raise ConfigMissing()
Based on the snippet: <|code_start|>------------------------------------------------------ ''' # Global dependencies # Internal deps # ############################################### # Boilerplate # ############################################### logger = logging.getLogger(__name__) # Control * imports. __al...
class ObjCore(metaclass=TriplicateAPI):
Based on the snippet: <|code_start|> return self.createIndex(row, column, self.vocabularyList[row]) def find(self, entry): # TODO for i, e in enumerate(self.vocabularyList): for key in entry.keys(): if key in e and e[key] != entry[key]: break ...
class VocabularyPage(QWidget, VocabularyPageUI.Ui_Form):
Here is a snippet: <|code_start|> lambda: self._removeAction.setEnabled( self.vocabularyListView.selectionModel().hasSelection())) self.connect(self._removeAction, SIGNAL("triggered(bool)"), lambda: self.vocabularyModel.remove( self.vocabularyListView.selec...
fileName = util.getLocalData('eclectus.csv')
Given snippet: <|code_start|>#!/usr/bin/python # -*- coding: utf-8 -*- """ Component chooser plugin for accessing characters by searching for their components. @todo Fix: Component view has buggy updates, lesser characters are highlighted than actually chosen This program is free software; you can redistribute it...
class ComponentPage(QWidget, ComponentPageUI.Ui_Form):
Continue the code snippet: <|code_start|>as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A ...
self.includeSimilar = util.readConfigString(self.pluginConfig,
Predict the next line for this snippet: <|code_start|> self.connect(self.includeSimilarButton, SIGNAL("clicked(bool)"), self.componentIncludeSimilar) self.connect(self.componentView, SIGNAL("linkClicked(const QUrl &)"), self.componentClicked) self.connect(self.componentVi...
id = self.renderThread.enqueue(ComponentView,
Using the snippet: <|code_start|> QIcon(util.getIcon('radicalvariant.png'))) self.slotSettingsChanged() id = self.renderThread.enqueue(ComponentView, 'getComponentSearchTable', components=[], includeEquivalentRadicalForms=self.includeVariants, ...
char = decodeBase64(re.match('lookup\(([^\)]+)\)', cmd).group(1))
Given the code snippet: <|code_start|> subCharCount = 3 treeElements = [] curIndex = idx while len(treeElements) < subCharCount: curIndex = curIndex + 1 element = decomposition[curIndex] if type(element) != type(()): ...
@cachedproperty
Given the following code snippet before the placeholder: <|code_start|> @classmethod def getSimilarPlainEntities(cls, plainEntity, reading): # TODO the following is not independent of reading and really slow similar = [plainEntity] if reading in cls.AMBIGUOUS_INITIALS: for key...
getDatabaseConfiguration(databaseUrl))
Predict the next line after this snippet: <|code_start|>along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. """ class UpdateVersionBuilder(builder.EntryGeneratorBuilder): """Table for keeping track of which date the release...
kanaRanges.extend(util.UNICODE_SCRIPT_CLASSES['Hiragana'])
Next line prediction: <|code_start|># coding: utf-8 class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('-u', '--username', action='store', dest='username', required=True) def handle(self, *args, **options): active_user = options['username'] print(sel...
user_item_df = prepare_user_item_df(min_stargazers_count=500)
Predict the next line after this snippet: <|code_start|># coding: utf-8 class Command(BaseCommand): def handle(self, *args, **options): UserRelation.objects.all().delete() <|code_end|> using the current file's imports: from django.core.management.base import BaseCommand from app.models import RepoSta...
RepoStarring.objects.all().delete()
Given the code snippet: <|code_start|># coding: utf-8 class Command(BaseCommand): def handle(self, *args, **options): def batch_qs(qs, batch_size=500): total = qs.count() for start in range(0, total, batch_size): end = min(start + batch_size, total) ...
repo_info_doc = RepoInfoDoc()
Based on the snippet: <|code_start|># coding: utf-8 class Command(BaseCommand): def handle(self, *args, **options): def batch_qs(qs, batch_size=500): total = qs.count() for start in range(0, total, batch_size): end = min(start + batch_size, total) ...
large_qs = RepoInfo.objects.filter(stargazers_count__gte=10, stargazers_count__lte=290000, fork=False)
Next line prediction: <|code_start|># coding: utf-8 class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('-u', '--username', action='store', dest='username', required=True) def handle(self, *args, **options): active_user = options['username'] print(sel...
user_item_df = prepare_user_item_df(min_stargazers_count=100)
Predict the next line after this snippet: <|code_start|># coding: utf-8 class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('-i', '--repo_full_name', action='store', dest='repo_full_name', required=True) def handle(self, *args, **options): repo_full_name = op...
rs = RepoStarring.objects \
Based on the snippet: <|code_start|># coding: utf-8 class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('-i', '--repo_full_name', action='store', dest='repo_full_name', required=True) def handle(self, *args, **options): repo_full_name = options['repo_full_nam...
user_item_df = prepare_user_item_df(min_stargazers_count=min_stargazers_count)
Here is a snippet: <|code_start|> class Pshuf(Pattern): """ pattern to randomly shuffle elements from a list; the randomly shuffled list then is repeated verbatim for repats times """ def __init__(self, alist=None, repeats=sys.maxsize): super().__init__() if alist is None: ...
itertools.chain.from_iterable(itertools.repeat(random_permutation(self.alist), self.repeats)))
Here is a snippet: <|code_start|> class TestPtween(unittest.TestCase): def test_normal(self): n = NumberAnimation(frm=60, to=90, tween=['linear']) <|code_end|> . Write the next line using the current file imports: import unittest from vectortween.NumberAnimation import NumberAnimation from expremigen.pa...
a = [i for i in Ptween(n, 0, 0, 10, 10, None)]
Based on the snippet: <|code_start|> def myrepeat(what, fn, times=None): """ :param what: something to repeat :param fn: extra function to apply :param times: number of times to repeat :return: """ if times is None: while True: if fn is not None: yield fn...
if isinstance(el, Pattern) and not isinstance(el, Pchord):
Given the code snippet: <|code_start|> def myrepeat(what, fn, times=None): """ :param what: something to repeat :param fn: extra function to apply :param times: number of times to repeat :return: """ if times is None: while True: if fn is not None: yield ...
if isinstance(el, Pattern) and not isinstance(el, Pchord):
Based on the snippet: <|code_start|> class Pconst(Pattern): """ pattern that returns a given "constant" for "repeats" time """ def __init__(self, constant=0, repeats=sys.maxsize): super().__init__() self.constant = constant self.repeats = repeats def __str__(self): ...
return flatten(c for c in itertools.repeat(self.constant, self.repeats))
Given snippet: <|code_start|> """ internal helper function :return: list of drumnotes for inclusion in the textX grammar """ def mycmp(s1, s2): if len(s1) < len(s2): return 1 if len(s1) > len(s2): return -1 if s1 ...
return REST
Based on the snippet: <|code_start|> assert d[1] not in self.all_drum_notes self.all_drum_notes.add(d[0]) self.all_drum_notes.add(d[1]) def get_drumnotes_for_grammar(self): """ internal helper function :return: list of drumnotes for inclusion in the textX ...
if isinstance(note, Pchord):
Predict the next line for this snippet: <|code_start|> class Pgeom(Pattern): """ pattern that generates numbers in geometric series, e.g. Pgeom(1, 2, 5) -> 1, 2, 4, 8, 16 """ def __init__(self, frm=0, factor=1, length=5): """ :param frm: starting number :param factor: factor b...
return take(self.length, geom(self.frm, self.factor))
Next line prediction: <|code_start|> class Pgeom(Pattern): """ pattern that generates numbers in geometric series, e.g. Pgeom(1, 2, 5) -> 1, 2, 4, 8, 16 """ def __init__(self, frm=0, factor=1, length=5): """ :param frm: starting number :param factor: factor by which to keep mu...
return take(self.length, geom(self.frm, self.factor))
Here is a snippet: <|code_start|> class Pseries(Pattern): """ pattern to generate an arithmetic series, e.g. Pseries(0, 1, 5) -> 0, 1, 2, 3, 4 """ def __init__(self, frm=0, step=1, length=5): super().__init__() self.frm = frm self.step = step self.length = length ...
return take(self.length, itertools.count(self.frm, self.step))
Based on the snippet: <|code_start|> class TestPseq(unittest.TestCase): def test_normal(self): a = [i for i in Pseq([4, 5, 6], 2)] self.assertEqual(a, [4, 5, 6] * 2) def test_empty(self): b = [i for i in Pseq([4, 5, 6], 0)] self.assertEqual(b, []) def test_adult(self): ...
f = [i for i in Pseq([Pseq([1, Pconst(2, 2)], 2), Pseq(Pchord([3, 4]), 2)], 2)]
Using the snippet: <|code_start|> class TestPseq(unittest.TestCase): def test_normal(self): a = [i for i in Pseq([4, 5, 6], 2)] self.assertEqual(a, [4, 5, 6] * 2) def test_empty(self): b = [i for i in Pseq([4, 5, 6], 0)] self.assertEqual(b, []) def test_adult(self): ...
self.assertEqual("{0}".format(Pseq([1, -1, Pconst(2, 2)], 3)), "Pseq([1, -1, Pconst(2, 2)], 3)")
Continue the code snippet: <|code_start|> class Pseq(Pattern): """ pattern that generates numbers one by one from a list """ def __init__(self, alist=None, repeats=sys.maxsize): super().__init__() if alist is None: alist = [] self.alist = copy.deepcopy(alist) ...
return flatten(j for i in itertools.repeat(self.alist, self.repeats) for j in i)
Using the snippet: <|code_start|> class Prand(Pattern): """ Pattern used to draw random numbers from a list (numbers may repeat themselves) """ def __init__(self, alist=None, repeats=sys.maxsize): """ pattern that :param alist: possible numbers :param repeats: how ...
return flatten(take(self.repeats, (i for i in random_permutation(
Based on the snippet: <|code_start|> class Prand(Pattern): """ Pattern used to draw random numbers from a list (numbers may repeat themselves) """ def __init__(self, alist=None, repeats=sys.maxsize): """ pattern that :param alist: possible numbers :param repeats: h...
return flatten(take(self.repeats, (i for i in random_permutation(
Continue the code snippet: <|code_start|> class Prand(Pattern): """ Pattern used to draw random numbers from a list (numbers may repeat themselves) """ def __init__(self, alist=None, repeats=sys.maxsize): """ pattern that :param alist: possible numbers :param repea...
return flatten(take(self.repeats, (i for i in random_permutation(
Continue the code snippet: <|code_start|> class Padd(Pbinop): """ pattern that returns the sum of two other patterns """ def __init__(self, a: Pattern, b: Pattern): super().__init__(a, b) def __iter__(self): <|code_end|> . Use current file imports: import itertools import operator from ...
return flatten(i for i in itertools.starmap(operator.__add__, zip(self.a, self.b)))
Predict the next line after this snippet: <|code_start|># Copyright © 2014-16, Ugo Pozo # 2014-16, Câmara Municipal de São Paulo # aggregators.py - aggregators for boolean expressions. # This file is part of Anubis. # Anubis is free software: you can redistribute it and/or modify # it under the terms of ...
outside_precedence = Boolean.precedence.index(outside)
Based on the snippet: <|code_start|> if not self.is_cacheable: return super().get_full_state() key = "api:" + self.cache_key if self.is_api else self.cache_key cache = caches[self.cache] cached_value = cache.get(key, None) if cached_value is None: state...
aggregator = CachedQuerySetAggregator(cache, queryset,
Here is a snippet: <|code_start|> aggregate = self.procedure_aggregate(procname, *args, **kwargs) return self.order_by_aggregates(aggregate, field=field, extra_fields=extra_fields) def order_by_aggregates(self, *aggregates, field="id", extra_fields=None): ...
return ProcedureOrderingAnnotation(procname, *args, **kwargs)
Given snippet: <|code_start|> with pytest.raises(InvalidPublisher): require_different_publisher( Committed( publisher=message.header.publisher, batch_identifier=batch_identifier, ), 0, message, ) def test_stateful_valid...
{'begin_operation': begin},
Next line prediction: <|code_start|> Committed( publisher=message.header.publisher, batch_identifier=batch_identifier, ), 0, message, ) def test_stateful_validator_unhandled_starting_state(message): validator = StatefulStreamVa...
{'commit_operation': commit},
Predict the next line for this snippet: <|code_start|> def test_require_same_batch(message): batch_identifier = get_operation(message).batch_identifier require_same_batch( InTransaction( publisher=message.header.publisher, batch_identifier=batch_identifier, ), ...
batch_identifier=copy(batch_identifier, id=batch_identifier.id + 1),
Predict the next line after this snippet: <|code_start|> with pytest.raises(InvalidPublisher): require_different_publisher( Committed( publisher=message.header.publisher, batch_identifier=batch_identifier, ), 0, message, ...
messages = list(make_batch_messages(batch_identifier, [
Given snippet: <|code_start|> require_different_publisher( Committed( publisher=message.header.publisher, batch_identifier=batch_identifier, ), 0, message, ) def test_stateful_validator_unhandled_starting_state(message): ...
{'mutation_operation': mutation},
Predict the next line for this snippet: <|code_start|> message, ) def test_stateful_validator_unhandled_starting_state(message): validator = StatefulStreamValidator(lambda **kwargs: None, {}) with pytest.raises(InvalidEventError): validator(None, 0, message) def test_adds_expecte...
state = reserialize(validate_transaction_state(state, 0, messages[0]))
Based on the snippet: <|code_start|> stream = KafkaStream.configure(configuration, cluster, 'default') client.ensure_topic_exists(stream.topic) yield stream @pytest.yield_fixture def client(configuration): yield KafkaClient(configuration['hosts']) @pytest.yield_fixture def writer(client, stream): ...
assert head.batch_operation.begin_operation == begin
Continue the code snippet: <|code_start|>def client(configuration): yield KafkaClient(configuration['hosts']) @pytest.yield_fixture def writer(client, stream): producer = SimpleProducer(client) yield KafkaWriter(producer, stream.topic) @pytest.yield_fixture def state(): bootstrap_state = BootstrapSt...
writer.push(transaction)
Predict the next line after this snippet: <|code_start|> @pytest.yield_fixture def stream(configuration, cluster, client): stream = KafkaStream.configure(configuration, cluster, 'default') client.ensure_topic_exists(stream.topic) yield stream @pytest.yield_fixture def client(configuration): yield Kafk...
two_transactions = list(islice(transactions(), 6))
Based on the snippet: <|code_start|>from __future__ import absolute_import with import_extras('kafka'): def test_writer(): topic = '%s-mutations' % (uuid.uuid1().hex,) client = KafkaClient('kafka') producer = SimpleProducer(client) writer = KafkaWriter(producer, topic) <|code_end|> , predict the ...
inputs = list(transaction)
Using the snippet: <|code_start|> @pytest.yield_fixture def source_transaction_snapshot(source_connection): with source_connection as conn, conn.cursor() as cursor: cursor.execute('SELECT txid_current_snapshot();') row = cursor.fetchone() yield to_snapshot(row[0]) @pytest.yield_fixture def...
batch_identifier,
Continue the code snippet: <|code_start|> @pytest.yield_fixture def source_transaction_snapshot(source_connection): with source_connection as conn, conn.cursor() as cursor: cursor.execute('SELECT txid_current_snapshot();') row = cursor.fetchone() yield to_snapshot(row[0]) @pytest.yield_fi...
generator = make_batch_messages(
Here is a snippet: <|code_start|> def limited_to(self, limit): self.limit = limit return self def consume(self, *args, **kwargs): iterator = super(LimitedKafkaStream, self).consume(*args, **kwargs) return islice(iterator, self.limit) def get_mutation(transaction_id=1, user_1_n...
transaction=transaction_id,
Using the snippet: <|code_start|> def test_publisher(): messages = [] publisher = Publisher(messages.extend) <|code_end|> , determine the next line of code. You have imports: import pytest from pgshovel.interfaces.common_pb2 import Snapshot from pgshovel.interfaces.replication_pb2 import ( BootstrapStat...
with publisher.batch(batch_identifier, begin) as publish:
Next line prediction: <|code_start|> def test_publisher(): messages = [] publisher = Publisher(messages.extend) <|code_end|> . Use current file imports: (import pytest from pgshovel.interfaces.common_pb2 import Snapshot from pgshovel.interfaces.replication_pb2 import ( BootstrapState, ConsumerState,...
with publisher.batch(batch_identifier, begin) as publish:
Given the code snippet: <|code_start|> def test_publisher(): messages = [] publisher = Publisher(messages.extend) with publisher.batch(batch_identifier, begin) as publish: publish(mutation) published_messages = map(reserialize, messages) assert get_oneof_value( get_oneof_value(p...
) == commit
Given the code snippet: <|code_start|> def test_publisher(): messages = [] publisher = Publisher(messages.extend) with publisher.batch(batch_identifier, begin) as publish: <|code_end|> , generate the next line using the imports in this file: import pytest from pgshovel.interfaces.common_pb2 import Snaps...
publish(mutation)
Given the following code snippet before the placeholder: <|code_start|> def test_publisher(): messages = [] publisher = Publisher(messages.extend) with publisher.batch(batch_identifier, begin) as publish: publish(mutation) <|code_end|> , predict the next line using imports from the current file:...
published_messages = map(reserialize, messages)
Continue the code snippet: <|code_start|> 'operation' ) == commit for i, message in enumerate(published_messages): assert message.header.publisher == publisher.id assert message.header.sequence == i # Ensure it actually generates valid data. state = None for offset, message ...
) == rollback
Here is a snippet: <|code_start|> class Meta: abstract = True @python_2_unicode_compatible class Settings(ActionsMixin, TimeStampedMixin): """Settings for imported and exported files""" name = models.CharField( _('name'), blank=True, max_length=100, help_text=_('Small description ...
default=SETTINGS['default_processor'],
Here is a snippet: <|code_start|> def __str__(self): return '{} - {}'.format(self.started_at, self.get_status_display()) def get_absolute_url(self): if self.buffer_file: return self.buffer_file.url @receiver(export_started) def create_export_report(sender, **kwargs): return Re...
buffer_file=strip_media_root(kwargs['path']),
Using the snippet: <|code_start|> return super(ExportManager, self).get_queryset() \ .filter(action=self.model.EXPORT) class ImportManager(models.Manager): """Shortcut for import queryset""" def get_queryset(self): return super(ImportManager, self).get_queryset() \ .fi...
(EXPORT, _('Export')),
Predict the next line for this snippet: <|code_start|> max_row, max_col = processor.open(self.buffer_file.path) processor.set_dimensions(0, 0, max_row, max_col) start_row = 0 index = 1 while index < max_row: row = processor.read(index - 1) start_row = ind...
for name, label in model_attributes(self):
Predict the next line after this snippet: <|code_start|> _('started at'), auto_now_add=True) completed_at = models.DateTimeField( _('completed at'), null=True, blank=True) updated_at = models.DateTimeField( _('updated at'), auto_now=True) settings = models.ForeignKey( Setting...
@receiver(export_started)
Based on the snippet: <|code_start|> settings = models.ForeignKey( Settings, verbose_name=_('settings'), related_name='reports', null=True, blank=True ) objects = models.Manager() export_objects = ExportManager() import_objects = ImportManager() running_objects = RunningManager()...
@receiver(export_completed)
Predict the next line for this snippet: <|code_start|> verbose_name_plural = _('reports') ordering = ('-id',) def __str__(self): return '{} - {}'.format(self.started_at, self.get_status_display()) def get_absolute_url(self): if self.buffer_file: return self.buffer_f...
@receiver(import_started)
Given the following code snippet before the placeholder: <|code_start|> if self.buffer_file: return self.buffer_file.url @receiver(export_started) def create_export_report(sender, **kwargs): return Report.export_objects.create( action=Report.EXPORT, settings=sender.settings) @receiver...
@receiver(import_completed)
Here is a snippet: <|code_start|> ERROR = 0 INFO = 1 MESSAGE_CHOICES = ( (ERROR, _('Error')), (INFO, _('Info')) ) report = models.ForeignKey(Report, related_name='messages') message = models.TextField(_('message'), max_length=10000) step = models.PositiveSmallIntegerField( ...
@receiver(error_raised)
Given the code snippet: <|code_start|>def save_export_report(sender, **kwargs): report = sender.report report.completed_at = kwargs['date'] report.buffer_file = kwargs['path'] report.status = report.SUCCESS report.save() return report @receiver(import_started) def create_import_report(sender...
class Message(PositionRelatedMixin, ErrorChoicesMixin):
Predict the next line for this snippet: <|code_start|> return filter_params, can_create def filter_attrs(raw_attrs, fields, mfields, name=None): update_fields = [f.update for f in fields] or fields update_values = {} for field in update_fields: if ('_|' not in field.attribute and name is None...
@manager.register('action', _('Create only'), use_transaction=True)
Given the following code snippet before the placeholder: <|code_start|> return filter_params, can_create def filter_attrs(raw_attrs, fields, mfields, name=None): update_fields = [f.update for f in fields] or fields update_values = {} for field in update_fields: if ('_|' not in field.attribute...
@manager.register('action', _('Create only'), use_transaction=True)
Given the code snippet: <|code_start|> def save(self): """Save result file""" raise NotImplementedError def create_export_path(self): # TODO: refactor filepath filename = '{}{}'.format( self.settings.filename or str(self.report.id), self.file_format) path =...
for response in export_started.send(self):
Predict the next line for this snippet: <|code_start|> def export_data(self, data): """Export data from queryset to file and return path""" # send signal to create report for response in export_started.send(self): self.report = response[1] self.set_dimensions(0, data['ro...
for response in export_completed.send(
Given the following code snippet before the placeholder: <|code_start|> attrs = related_attrs.get(key_model, {}) attrs[key_attr] = value related_attrs[key_model] = attrs return related_attrs def prepare_attrs(self, _model): model_attrs = {} related_attrs = {} ...
for response in import_started.send(self, path=path):
Next line prediction: <|code_start|> model, model_attrs, related_attrs, context, **kwargs) except (Error, ValueError, ValidationError, AttributeError, TypeError, IndexError): if use_transaction: transaction.savepoint_rollback(sid) ...
for response in import_completed.send(
Predict the next line after this snippet: <|code_start|> action = transaction.atomic(action) for row, _model in data['items']: model_attrs, related_attrs = self.prepare_attrs(_model) model_attrs.update(**params) kwargs = dict( processor=self, path...
error_raised.send(
Here is a snippet: <|code_start|> kwargs = dict( processor=self, path=path, fields=data['fields'], params=params, raw_attrs=_model, mfields=data['mfields'], ) if use_transaction: sid = transaction.savepoint() ...
step=ErrorChoicesMixin.IMPORT_DATA)