Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
# Module API
class Spider(CrawlSpider):
# Public
<|code_end|>
, predict the immediate next line with the help of imports:
from urllib import urlencode
from collections import OrderedDict
from datetime import datetime, date, timedelta
from scrapy.spiders import Rule
from scrapy.spiders import CrawlSpider
from scrapy.linkextractors import LinkExtractor
from .parser import parse_record
and context (classes, functions, sometimes code) from other files:
# Path: collectors/actrn/parser.py
# def parse_record(res):
# fields_to_remove = [
# 'country',
# 'state_province',
# 'recruitment_postcode_s',
# 'recruitment_hospital',
# ]
#
# # Init data
# data = {}
#
# # Parse rawdata
# gpath = '.review-element-header, .health-header'
# kpath = '.review-element-name'
# vpath = '.review-element-content'
# rawdata = _parse_data(res, gpath, kpath, vpath)
# for group, key, value in rawdata:
#
# # Parse key
# index = None
# match = re.match(r'(.*?)(?:_(\d+))?_\d+_\d+', key)
# if match:
# key = match.group(1)
# index = match.group(2)
# if index is not None:
# index = int(index) - 1
#
# # Titles & IDs
#
# newkey = 'secondary_ids'
# oldkey = 'secondary_id'
# data.setdefault(newkey, [])
# if key == oldkey:
# data[newkey].append(value)
# continue
#
# # Intervention/exposure
#
# newkey = 'intervention_codes'
# oldkey = 'intervention_code'
# data.setdefault(newkey, [])
# if key == oldkey:
# data[newkey].append(value)
# continue
#
# # Outcomes
#
# newkey = 'primary_outcomes'
# oldkey = 'primary_outcome'
# data.setdefault(newkey, [])
# if key == oldkey:
# outcome_key = newkey
# outcome_data = {'outcome': value}
# continue
#
# newkey = 'secondary_outcomes'
# oldkey = 'secondary_outcome'
# data.setdefault(newkey, [])
# if key == oldkey:
# outcome_key = newkey
# outcome_data = {'outcome': value}
# continue
#
# oldkey = 'timepoint'
# if key == oldkey:
# outcome_data['timepoint'] = value
# data[outcome_key].append(outcome_data)
# continue
#
# # Funding & Sponsors
#
# newkey = 'primary_sponsor'
# oldgroup = 'Funding & Sponsors'
# data.setdefault(newkey, {})
# if group == oldgroup:
# if index is None:
# data[newkey][key] = value
# continue
#
# newkey = 'sponsors'
# oldgroup = 'Funding & Sponsors'
# data.setdefault(newkey, [])
# if group == oldgroup:
# while len(data[newkey]) <= index:
# data[newkey].append({})
# data[newkey][index][key] = value
# continue
#
# # Ethics approval
#
# newkey = 'ethics_application_status'
# if key == newkey:
# data[newkey] = value
# continue
#
# newkey = 'ethics_applications'
# oldgroup = 'Ethics approval'
# data.setdefault(newkey, [])
# if group == oldgroup:
# while len(data[newkey]) <= index:
# data[newkey].append({})
# data[newkey][index][key] = value
# continue
#
# # Summary
#
# newkey = 'attachments'
# oldkey = 'attachments'
# data.setdefault(newkey, [])
# if key == oldkey:
# data[newkey].append(value)
# continue
#
# # Contacts
#
# newkey = 'principal_investigator'
# oldgroup = 'Principal investigator'
# data.setdefault(newkey, {})
# if group == oldgroup:
# data[newkey][key] = value
# continue
#
# newkey = 'public_queries'
# oldgroup = 'Contact person for public queries'
# data.setdefault(newkey, {})
# if group == oldgroup:
# data[newkey][key] = value
# continue
#
# newkey = 'scientific_queries'
# oldgroup = 'Contact person for scientific queries'
# data.setdefault(newkey, {})
# if group == oldgroup:
# data[newkey][key] = value
# continue
#
# # Collect plain values
# data[key] = value
#
# # Health condition
#
# key = 'health_conditions_or_problems_studied'
# path = '.review-element-content.health'
# value = res.css(path).xpath('span[1]/text()').extract_first()
# data[key] = value
#
# key = 'condition_category'
# path = '.review-element-condition'
# value = res.css(path).xpath('span[1]/text()').extract_first()
# data[key] = value
#
# key = 'condition_code'
# path = '.review-element-condition-right'
# value = res.css(path).xpath('span[1]/text()').extract_first()
# data[key] = value
#
# # Remove data
# for key in fields_to_remove:
# if key in data:
# del data[key]
#
# # Create record
# record = Record.create(res.url, data)
#
# return record
. Output only the next line. | name = 'actrn' |
Using the snippet: <|code_start|>with betamax.Betamax.configure() as cfg:
cfg.cassette_library_dir = 'tests/cassettes/'
record_mode = 'none' if os.environ.get('CI') else 'once'
cfg.default_cassette_options['record_mode'] = record_mode
cfg.default_cassette_options['match_requests_on'] = [
'uri',
'method',
'headers',
'body',
]
# Fixtures
@pytest.fixture
def conf():
return helpers.get_variables(config, str.isupper)
@pytest.fixture
def conn():
warehouse = dataset.connect(config.WAREHOUSE_URL)
for table in warehouse.tables:
warehouse[table].delete()
return {'warehouse': warehouse}
@pytest.fixture
def get_url(betamax_session):
<|code_end|>
, determine the next line of code. You have imports:
import os
import pytest
import betamax
import dataset
from scrapy.http import Request, HtmlResponse
from collectors.base import config, helpers
and context (class names, function names, or code) available:
# Path: collectors/base/config.py
# ENV = os.environ.get('PYTHON_ENV', 'development')
# ENV = 'testing'
# WAREHOUSE_URL = os.environ['TEST_WAREHOUSE_URL']
# WAREHOUSE_URL = os.environ['WAREHOUSE_URL']
# SCRAPY_SETTINGS = {
# 'SPIDER_MODULES': [
# 'collectors.actrn.spider',
# 'collectors.euctr.spider',
# 'collectors.gsk.spider',
# 'collectors.ictrp.spider',
# 'collectors.isrctn.spider',
# 'collectors.jprn.spider',
# 'collectors.pfizer.spider',
# 'collectors.pubmed.spider',
# 'collectors.takeda.spider',
# ],
# 'DOWNLOAD_DELAY': float(os.getenv('DOWNLOAD_DELAY', 1)),
# 'AUTOTHROTTLE_ENABLED': True,
# 'ITEM_PIPELINES': {
# 'collectors.base.pipelines.Warehouse': 100,
# },
# }
# SENTRY_DSN = os.environ.get('SENTRY_DSN')
# SENTRY = raven.Client(SENTRY_DSN)
# LOGGING_CONFIG = {
# 'version': 1,
# 'disable_existing_loggers': False,
# 'formatters': {
# 'default': {
# 'format': '%(levelname)s %(name)s: %(message)s',
# },
# },
# 'handlers': {
# 'default_handler': {
# 'class': 'logging.StreamHandler',
# 'stream': 'ext://sys.stdout',
# 'level': 'DEBUG',
# 'formatter': 'default'
# },
# 'syslog_handler': {
# '()': setup_syslog_handler,
# 'level': 'INFO',
# 'formatter': 'default',
# },
# 'sentry': {
# 'level': 'ERROR',
# 'class': 'raven.handlers.logging.SentryHandler',
# 'dsn': SENTRY_DSN,
# },
# },
# 'root': {
# 'handlers': ['default_handler', 'syslog_handler'],
# 'level': os.environ.get('LOGGING_LEVEL', 'DEBUG').upper(),
# },
# }
# ICTRP_USER = os.environ.get('ICTRP_USER', None)
# ICTRP_PASS = os.environ.get('ICTRP_PASS', None)
# HRA_ENV = os.environ.get('HRA_ENV', None)
# HRA_URL = os.environ.get('HRA_URL', None)
# HRA_USER = os.environ.get('HRA_USER', None)
# HRA_PASS = os.environ.get('HRA_PASS', None)
# COCHRANE_ARCHIVE_URL = os.environ.get('COCHRANE_ARCHIVE_URL')
# def setup_syslog_handler():
#
# Path: collectors/base/helpers.py
# def slugify(value):
# def parse_date(value, format):
# def parse_datetime(value, format):
# def get_variables(object, filter=None):
# def start(conf, name, message):
# def stop(conf, name, message):
. Output only the next line. | def _get_url(url, request_kwargs={}): |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
<|code_end|>
with the help of current file imports:
import logging
import xmltodict
import xml.etree.ElementTree as etree
from lxml import etree
from .record import Record
and context from other files:
# Path: collectors/nct/record.py
# class Record(base.Record):
#
# # Config
#
# table = 'nct'
# _DATE_FORMATS = [
# '%B %Y',
# '%B %d, %Y',
# ]
#
# # General
#
# nct_id = Text(primary_key=True)
# download_date = Text()
# link_text = Text()
# url = Text()
# org_study_id = Text()
# secondary_ids = Array()
# nct_aliases = Array()
# brief_title = Text()
# acronym = Text()
# official_title = Text()
# sponsors = Json()
# source = Text()
# oversight_info = Json()
# brief_summary = Text()
# detailed_description = Text()
# overall_status = Text()
# why_stopped = Text()
# start_date = Date(_DATE_FORMATS)
# completion_date_actual = Date(_DATE_FORMATS)
# completion_date_anticipated = Date(_DATE_FORMATS)
# primary_completion_date_actual = Date(_DATE_FORMATS)
# primary_completion_date_anticipated = Date(_DATE_FORMATS)
# phase = Text()
# study_type = Text()
# study_design = Text()
# target_duration = Text()
# primary_outcomes = Json()
# secondary_outcomes = Json()
# other_outcomes = Json()
# number_of_arms = Integer()
# number_of_groups = Integer()
# enrollment_actual = Integer()
# enrollment_anticipated = Integer()
# conditions = Array()
# arm_groups = Json()
# interventions = Json()
# biospec_retention = Text()
# biospec_desrc = Text()
# eligibility = Json()
# overall_officials = Json()
# overall_contact = Json()
# overall_contact_backup = Json()
# locations = Json()
# location_countries = Array()
# removed_countries = Array()
# links = Json()
# references = Json()
# results_references = Json()
# verification_date = Date(_DATE_FORMATS)
# lastchanged_date = Date(_DATE_FORMATS)
# firstreceived_date = Date(_DATE_FORMATS)
# firstreceived_results_date = Date(_DATE_FORMATS)
# responsible_party = Json()
# keywords = Array()
# is_fda_regulated = Boolean('Yes')
# is_section_801 = Boolean('Yes')
# has_expanded_access = Boolean('Yes')
# condition_browse = Json()
# intervention_browse = Json()
# clinical_results = Json()
# results_exemption_date = Date(_DATE_FORMATS)
, which may contain function names, class names, or code. Output only the next line. | try: |
Given the code snippet: <|code_start|>from __future__ import unicode_literals
try:
except ImportError:
def parse_record(url, review_file):
tree = etree.parse(review_file)
study_robs = []
studies = []
# Get risk of bias
root = tree.getroot()
doi_id = root.attrib.get('DOI', '')
quality_item_data_entries = tree.findall('//QUALITY_ITEM_DATA_ENTRY')
for quality_item_data_entry in quality_item_data_entries:
study_rob = {
'study_id': quality_item_data_entry.attrib['STUDY_ID'],
'modified': quality_item_data_entry.attrib.get('MODIFIED', ''),
'result': quality_item_data_entry.attrib['RESULT'],
'group_id': quality_item_data_entry.attrib.get('GROUP_ID', ''),
'group_name': '',
'result_description': quality_item_data_entry.findtext('DESCRIPTION/P', ''),
}
quality_item = quality_item_data_entry.getparent().getparent()
study_rob['rob_id'] = quality_item.attrib['ID']
study_rob['rob_name'] = quality_item.findtext('NAME')
study_rob['rob_description'] = quality_item.findtext('DESCRIPTION/P', '')
for group in quality_item.iter('QUALITY_ITEM_DATA_ENTRY_GROUP'):
<|code_end|>
, generate the next line using the imports in this file:
import uuid
import xml.etree.ElementTree as etree
from lxml import etree
from .record import Record
and context (functions, classes, or occasionally code) from other files:
# Path: collectors/cochrane_reviews/record.py
# class Record(base.Record):
# table = 'cochrane_reviews'
#
# # Fields
#
# id = Text(primary_key=True)
# study_id = Text()
# file_name = Text()
# study_type = Text()
# doi_id = Text()
# robs = Json()
# refs = Json()
. Output only the next line. | group_id = group.attrib.get('ID') |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
# Module API
class Spider(CrawlSpider):
# Public
name = 'jprn'
allowed_domains = ['upload.umin.ac.jp']
def __init__(self, conf=None, conn=None, page_from=None, page_to=None):
# Save conf/conn
self.conf = conf
self.conn = conn
# Default values
<|code_end|>
, determine the next line of code. You have imports:
from functools import partial
from urllib import urlencode
from collections import OrderedDict
from scrapy.spiders import Rule
from scrapy.spiders import CrawlSpider
from scrapy.linkextractors import LinkExtractor
from six.moves.urllib.parse import urlparse, parse_qs
from .parser import parse_record
and context (class names, function names, or code) available:
# Path: collectors/jprn/parser.py
# def parse_record(res):
# fields_to_remove = [
# 'item',
# ]
#
# # Parse rawdata
# data = {}
#
# # Get meta
# subdata = _parse_table(res, key_index=0, value_index=2)
# data.update(subdata)
#
# # Process rawdata
# rawdata = _parse_table(res, key_index=0, value_index=1)
# prefix = ''
# for key, value in rawdata.items():
#
# # Interventions
#
# newkey = 'interventions'
# oldkey = 'interventionscontrol'
# data.setdefault(newkey, [])
# if key.startswith(oldkey):
# data[newkey].append(value)
# continue
#
# # Research contact person
#
# if key == 'name_of_lead_principal_investigator':
# prefix = 'research_'
#
# # Public contact
#
# if key == 'name_of_contact_person':
# prefix = 'public_'
#
# # Sponsor
#
# if key == 'name_of_primary_sponsor':
# prefix = ''
#
# # Collect plain values
# key = prefix + key
# data[key] = value
#
# # Remove data
# for key in fields_to_remove:
# if key in data:
# del data[key]
#
# identifier = data.get('unique_id_issued_by_umin')
# data['unique_trial_number'] = data.get('unique_trial_number', identifier)
#
# # Create record
# record = Record.create(res.url, data)
#
# return record
. Output only the next line. | if page_from is None: |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
class Spider(CrawlSpider):
name = 'fda_dap'
allowed_domains = ['accessdata.fda.gov']
def __init__(self, conf=None, conn=None):
self.conf = conf
self.conn = conn
self.start_urls = _make_start_urls(
'http://www.accessdata.fda.gov/scripts/cder/drugsatfda/index.cfm?fuseaction=Search.SearchResults_Browse&StepSize=100000&DrugInitial='
<|code_end|>
. Write the next line using the current file imports:
import urlparse
import re
import random
from scrapy.utils.url import canonicalize_url
from scrapy.spiders import CrawlSpider
from scrapy.http import Request
from scrapy.http.cookies import CookieJar
from .record import Record
and context from other files:
# Path: collectors/fda_dap/record.py
# class Record(base.Record):
#
# # Config
#
# table = 'fda_dap'
#
# # General
#
# id = Text(primary_key=True)
# drug_name = Text()
# active_ingredients = Text()
# company = Text()
# fda_application_num = Text()
# supplement_number = Integer()
# action_date = Date('%m/%d/%Y')
# approval_type = Text()
# notes = Text()
# documents = Json()
, which may include functions, classes, or code. Output only the next line. | ) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
logger = logging.getLogger(__name__)
# Module API
def parse_record(res):
# Init data
data = {}
# Main
key = 'register'
path = '#DataList3_ctl01_DescriptionLabel::text'
value = res.css(path).extract_first()
data[key] = value
key = 'last_refreshed_on'
path = '#DataList3_ctl01_Last_updatedLabel::text'
value = res.css(path).extract_first()
data[key] = value
key = 'main_id'
path = '#DataList3_ctl01_TrialIDLabel::text'
<|code_end|>
. Use current file imports:
(import logging
from .record import Record)
and context including class names, function names, or small code snippets from other files:
# Path: collectors/ictrp/record.py
# class Record(base.Record):
#
# # Config
#
# table = 'ictrp'
#
# # Main
#
# main_id = Text(primary_key=True)
# register = Text()
# last_refreshed_on = Date('%d %B %Y')
# date_of_registration = Text() # non regular format
# primary_sponsor = Text()
# public_title = Text()
# scientific_title = Text()
# date_of_first_enrollment = Text() # non regular format
# target_sample_size = Integer()
# recruitment_status = Text()
# url = Text()
# study_type = Text()
# study_design = Text()
# study_phase = Text()
#
# # Additional
#
# countries_of_recruitment = Array()
# contacts = Json()
# key_inclusion_exclusion_criteria = Text() # not presented on the site
# health_conditions_or_problems_studied = Array()
# interventions = Array()
# primary_outcomes = Array()
# secondary_outcomes = Array()
# secondary_ids = Array()
# sources_of_monetary_support = Array()
# secondary_sponsors = Array()
. Output only the next line. | value = res.css(path).extract_first() |
Given the code snippet: <|code_start|>from __future__ import unicode_literals
# Module API
class Spider(CrawlSpider):
# Public
name = 'isrctn'
allowed_domains = ['isrctn.com']
def __init__(self, conf=None, conn=None, date_from=None, date_to=None):
# Save conf/conn
self.conf = conf
self.conn = conn
# Make start urls
self.start_urls = _make_start_urls(
prefix='http://www.isrctn.com/search',
date_from=date_from, date_to=date_to)
# Make rules
self.rules = [
Rule(LinkExtractor(
allow=r'ISRCTN\d+',
), callback=parse_record),
Rule(LinkExtractor(
<|code_end|>
, generate the next line using the imports in this file:
from urllib import urlencode
from collections import OrderedDict
from datetime import date, timedelta
from scrapy.spiders import Rule
from scrapy.spiders import CrawlSpider
from scrapy.linkextractors import LinkExtractor
from .parser import parse_record
and context (functions, classes, or occasionally code) from other files:
# Path: collectors/isrctn/parser.py
# def parse_record(res):
#
# # Init data
# data = {}
#
# # General
#
# key = 'isrctn_id'
# path = '.ComplexTitle_primary::text'
# value = res.css(path).extract_first()
# data[key] = value
#
# key = 'doi_isrctn_id'
# path = '.ComplexTitle_secondary::text'
# value = res.css(path).extract_first()
# data[key] = value
#
# key = 'title'
# path = '//h1/text()'
# value = res.xpath(path).extract_first()
# data[key] = value
#
# kpath = '.Meta_name'
# vpath = '.Meta_name+.Meta_value'
# subdata = _parse_dict(res, kpath, vpath)
# data.update(subdata)
#
# tag = 'h3'
# text = 'Plain English Summary'
# kpath = '.Info_section_title'
# vpath = '.Info_section_title+p'
# section = _select_parent(res, tag, text)
# subdata = _parse_dict(section, kpath, vpath)
# data.update(subdata)
#
# # Contact information
#
# key = 'contacts'
# tag = 'h2'
# text = 'Contact information'
# kpath = '.Info_section_title'
# vpath = '.Info_section_title+p'
# first = 'type'
# section = _select_parent(res, tag, text)
# value = _parse_list(section, kpath, vpath, first)
# data.update({key: value})
#
# # Additional identifiers
#
# tag = 'h2'
# text = 'Additional identifiers'
# kpath = '.Info_section_title'
# vpath = '.Info_section_title+p'
# section = _select_parent(res, tag, text)
# subdata = _parse_dict(section, kpath, vpath)
# data.update(subdata)
#
# # Study information
#
# tag = 'h2'
# text = 'Study information'
# kpath = '.Info_section_title'
# vpath = '.Info_section_title+p'
# section = _select_parent(res, tag, text)
# subdata = _parse_dict(section, kpath, vpath)
# data.update(subdata)
#
# # Eligibility
#
# tag = 'h2'
# text = 'Eligibility'
# kpath = '.Info_section_title'
# vpath = '.Info_section_title+p'
# section = _select_parent(res, tag, text)
# subdata = _parse_dict(section, kpath, vpath)
# data.update(subdata)
#
# # Locations
#
# tag = 'h2'
# text = 'Locations'
# kpath = '.Info_section_title'
# vpath = '.Info_section_title+p'
# section = _select_parent(res, tag, text)
# subdata = _parse_dict(section, kpath, vpath)
# data.update(subdata)
#
# # Sponsor information
#
# key = 'sponsors'
# tag = 'h2'
# text = 'Sponsor information'
# kpath = '.Info_section_title'
# vpath = '.Info_section_title+p'
# first = 'organisation'
# section = _select_parent(res, tag, text)
# value = _parse_list(section, kpath, vpath, first)
# data.update({key: value})
#
# # Funders
#
# key = 'funders'
# tag = 'h2'
# text = 'Funders'
# kpath = '.Info_section_title'
# vpath = '.Info_section_title+p'
# first = 'funder_type'
# section = _select_parent(res, tag, text)
# value = _parse_list(section, kpath, vpath, first)
# data.update({key: value})
#
# # Results and publications
#
# tag = 'h2'
# text = 'Results and Publications'
# kpath = '.Info_section_title'
# vpath = '.Info_section_title+p'
# section = _select_parent(res, tag, text)
# subdata = _parse_dict(section, kpath, vpath)
# data.update(subdata)
#
# # Create record
# record = Record.create(res.url, data)
#
# return record
. Output only the next line. | allow=r'page=\d+', |
Based on the snippet: <|code_start|># coding=utf-8
# Copyright 2022 The init2winit Authors.
#
# 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 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 express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""BLEU evaluator container class."""
DEFAULT_EVAL_CONFIG = {
'eval_batch_size': 16,
<|code_end|>
, predict the immediate next line with the help of imports:
import copy
import functools
import os
import jax
import jax.numpy as jnp
import numpy as np
from absl import logging
from flax import jax_utils
from flax.training import common_utils
from init2winit.dataset_lib import mt_tokenizer
from init2winit.mt_eval import decode
from init2winit.mt_eval import eval_utils
from init2winit.optimizer_lib import optimizers
from tensorflow.io import gfile
and context (classes, functions, sometimes code) from other files:
# Path: init2winit/dataset_lib/mt_tokenizer.py
# def _dump_chars_to_textfile(
# dataset: tf.data.Dataset,
# maxchars: int = int(1e7),
# data_keys=('inputs', 'targets')
# ) -> Tuple[str, int]:
# def _train_sentencepiece(dataset: tf.data.Dataset,
# *,
# vocab_size: int,
# maxchars: int = int(1e7),
# model_path: str,
# model_type: str = 'unigram',
# character_coverage: float = 1.0,
# byte_fallback: bool = False,
# split_digits: bool = False,
# data_keys: Tuple[str, str] = ('inputs', 'targets'),
# user_defined_symbols: List[str] = []):
# def _load_sentencepiece_tokenizer(model_path: str,
# add_bos: bool = False,
# add_eos: bool = True,
# reverse: bool = False):
# def load_or_train_tokenizer(dataset: tf.data.Dataset,
# *,
# vocab_path: str,
# vocab_size: int,
# max_corpus_chars: int,
# character_coverage: float = 1.0,
# byte_fallback: bool = False,
# split_digits: bool = False,
# data_keys: Tuple[str, str] = ('inputs', 'targets'),
# user_defined_symbols: List[str] = []):
# def __call__(self, features: Features) -> Features:
# class TokenizeOp:
#
# Path: init2winit/mt_eval/decode.py
# EOS_ID = 2
# NEG_INF = np.array(-1.0e7)
# def brevity_penalty(alpha, length):
# def add_beam_dim(x, beam_size):
# def flatten_beam_dim(x):
# def unflatten_beam_dim(x, batch_size, beam_size):
# def flat_batch_beam_expand(x, beam_size):
# def gather_beams(nested, beam_indices, batch_size, new_beam_size):
# def gather_fn(x):
# def gather_topk_beams(nested, score_or_log_prob, batch_size, new_beam_size):
# def beam_init(batch_size, beam_size, max_decode_len, cache):
# def beam_search(inputs,
# cache,
# tokens_to_logits,
# beam_size=4,
# alpha=0.6,
# eos_id=EOS_ID,
# max_decode_len=None):
# def beam_search_loop_cond_fn(state):
# def beam_search_loop_body_fn(state):
# def decode_step(batch,
# flax_module,
# params,
# cache,
# max_decode_len,
# eos_id=EOS_ID,
# beam_size=4):
# def tokens_ids_to_logits(flat_ids, flat_cache):
# class BeamState:
#
# Path: init2winit/mt_eval/eval_utils.py
# def compute_bleu_from_predictions(predictions, references, name):
# def get_eval_fpath(ckpt_dir, ckpt_step, eval_split):
# def load_evals(ckpt_dir, ckpt_step, eval_split):
# def save_evals(ckpt_dir, ckpt_step, eval_split, bleu_score):
# def _load_checkpoint(checkpoint_path, params, optimizer_state, batch_stats,
# replicate=True):
# def average_checkpoints(
# checkpoint_paths, params, optimizer_state, batch_stats):
# def get_checkpoints_in_range(checkpoint_dir, lower_bound, upper_bound):
#
# Path: init2winit/optimizer_lib/optimizers.py
# def sgd(learning_rate, weight_decay, momentum=None, nesterov=False):
# def get_optimizer(hps, model=None):
# def _wrap_update_fn(opt_name, opt_update):
# def update_fn(grads, optimizer_state, params, batch=None, batch_stats=None):
. Output only the next line. | 'eval_split': 'test', |
Predict the next line after this snippet: <|code_start|> remainder = tf.constant(1.0, tf.float32,[self.batch_size]) - prob
remainder_expanded = tf.expand_dims(remainder,1)
tiled_remainder = tf.tile(remainder_expanded,[1,self.hidden_size])
acc_state = tf.nn.relu(tf.matmul(tf.concat(1, [acc_states, episode * tiled_remainder]), Wt) + bt)
return acc_state
def normal():
p_expanded = tf.expand_dims(p * new_float_mask,1)
tiled_p = tf.tile(p_expanded,[1,self.hidden_size])
acc_state = tf.nn.relu(tf.matmul(tf.concat(1, [acc_states, episode * tiled_p]), Wt) + bt)
return acc_state
counter += tf.constant(1.0,tf.float32,[self.batch_size]) * new_float_mask
counter_condition = tf.less(counter,self.N)
condition = tf.reduce_any(tf.logical_and(new_batch_mask,counter_condition))
acc_state = tf.cond(condition, normal, use_remainder)
'''ADD MECHANISM TO INCREASE HALT PROB IF MULTIPLE SIMILAR ATTENTION MASKS IN A ROW;
would be the difference between consecutive attention masks
based on this cooment: reddit.com/r/MachineLearning/comments/59sfz8/research_learning_to_reason_with_adaptive/d9bgqxw/'''
return (new_batch_mask, prob_compare, prob, counter, episode, fact_vecs, acc_state, counter_int, weight_container, bias_container)
#analogous to do_inference_steps
def do_generate_episodes(self, prev_memory, fact_vecs, batch_size, hidden_size, max_input_len, input_len_placeholder, max_num_hops, epsilon, weight_container, bias_container):
self.batch_size = batch_size
self.hidden_size = hidden_size
<|code_end|>
using the current file's imports:
import tensorflow as tf
from tensorflow.python.ops import rnn, rnn_cell, seq2seq
from utils import get_seq_length, _add_gradient_noise, _position_encoding, _xavier_weight_init, _last_relevant, batch_norm
and any relevant context from other files:
# Path: utils.py
# def get_seq_length(sequence):
# used = tf.sign(tf.reduce_max(tf.abs(sequence), reduction_indices=2))
# length = tf.reduce_sum(used, reduction_indices=1)
# length = tf.cast(length, tf.int32)
# return length
#
# def _add_gradient_noise(t, stddev=1e-3, name=None):
# """Adds gradient noise as described in http://arxiv.org/abs/1511.06807
# The input Tensor `t` should be a gradient.
# The output will be `t` + gaussian noise.
# 0.001 was said to be a good fixed value for memory networks."""
# with tf.op_scope([t, stddev], name, "add_gradient_noise") as name:
# t = tf.convert_to_tensor(t, name="t")
# gn = tf.random_normal(tf.shape(t), stddev=stddev)
# return tf.add(t, gn, name=name)
#
# def _position_encoding(sentence_size, embedding_size):
# """Position encoding described in section 4.1 in "End to End Memory Networks" (http://arxiv.org/pdf/1503.08895v5.pdf)"""
# encoding = np.ones((embedding_size, sentence_size), dtype=np.float32)
# ls = sentence_size + 1
# le = embedding_size + 1
# for i in range(1, le):
# for j in range(1, ls):
# encoding[i - 1, j - 1] = (i - (le - 1) / 2) * (j - (ls - 1) / 2)
# encoding = 1 + 4 * encoding / embedding_size / sentence_size
# return np.transpose(encoding)
#
# # TODO fix positional encoding so that it varies according to sentence lengths
#
# def _xavier_weight_init():
# """Xavier initializer for all variables except embeddings as desribed in [1]"""
#
# def _xavier_initializer(shape, **kwargs):
# eps = np.sqrt(6) / np.sqrt(np.sum(shape))
# out = tf.random_uniform(shape, minval=-eps, maxval=eps)
# return out
#
# return _xavier_initializer
#
# def _last_relevant(output, length):
# """Finds the output at the end of each input"""
# batch_size = int(output.get_shape()[0])
# max_length = int(output.get_shape()[1])
# out_size = int(output.get_shape()[2])
# index = tf.range(0, batch_size) * max_length + (length - 1)
# flat = tf.reshape(output, [-1, out_size])
# relevant = tf.gather(flat, index)
# return relevant
#
# def batch_norm(x, is_training):
# """ Batch normalization.
# :param x: Tensor
# :param is_training: boolean tf.Variable, true indicates training phase
# :return: batch-normalized tensor
# """
# with tf.variable_scope('BatchNorm'):
# # calculate dimensions (from tf.contrib.layers.batch_norm)
# inputs_shape = x.get_shape()
# axis = list(range(len(inputs_shape) - 1))
# param_shape = inputs_shape[-1:]
#
# beta = tf.get_variable('beta', param_shape, initializer=tf.constant_initializer(0.))
# gamma = tf.get_variable('gamma', param_shape, initializer=tf.constant_initializer(1.))
# batch_mean, batch_var = tf.nn.moments(x, axis)
# ema = tf.train.ExponentialMovingAverage(decay=0.5)
#
# def mean_var_with_update():
# ema_apply_op = ema.apply([batch_mean, batch_var])
# with tf.control_dependencies([ema_apply_op]):
# return tf.identity(batch_mean), tf.identity(batch_var)
#
# mean, var = tf.cond(is_training,
# mean_var_with_update,
# lambda: (ema.average(batch_mean), ema.average(batch_var)))
# normed = tf.nn.batch_normalization(x, mean, var, beta, gamma, 1e-3)
# return normed
. Output only the next line. | self.max_input_len = max_input_len |
Here is a snippet: <|code_start|>class Adaptive_Episodes(object):
""" Implements Iterative Alternating Attention for Machine Reading
http://arxiv.org/pdf/1606.02245v3.pdf """
def __init__(self, config, pretrained_embeddings=None,
update_embeddings=True, is_training=False):
self.config = config
def gate_mechanism(self, gate_input, scope):
with tf.variable_scope(scope):
if self.bidirectional:
size = 3*2*self.config.encoder_size + self.hidden_size
out_size = 2*self.config.encoder_size
else:
size = 3*self.config.encoder_size + self.hidden_size
out_size = self.config.encoder_size
hidden1_w = tf.get_variable("hidden1_w", [size, size])
hidden1_b = tf.get_variable("hidden1_b", [size])
hidden2_w = tf.get_variable("hidden2_w", [size, size])
hidden2_b = tf.get_variable("hidden2_b", [size])
sigmoid_w = tf.get_variable("sigmoid_w", [size, out_size])
sigmoid_b = tf.get_variable("sigmoid_b", [out_size])
if self.config.keep_prob < 1.0 and self.is_training:
<|code_end|>
. Write the next line using the current file imports:
import tensorflow as tf
from tensorflow.python.ops import rnn, rnn_cell, seq2seq
from utils import get_seq_length, _add_gradient_noise, _position_encoding, _xavier_weight_init, _last_relevant, batch_norm
and context from other files:
# Path: utils.py
# def get_seq_length(sequence):
# used = tf.sign(tf.reduce_max(tf.abs(sequence), reduction_indices=2))
# length = tf.reduce_sum(used, reduction_indices=1)
# length = tf.cast(length, tf.int32)
# return length
#
# def _add_gradient_noise(t, stddev=1e-3, name=None):
# """Adds gradient noise as described in http://arxiv.org/abs/1511.06807
# The input Tensor `t` should be a gradient.
# The output will be `t` + gaussian noise.
# 0.001 was said to be a good fixed value for memory networks."""
# with tf.op_scope([t, stddev], name, "add_gradient_noise") as name:
# t = tf.convert_to_tensor(t, name="t")
# gn = tf.random_normal(tf.shape(t), stddev=stddev)
# return tf.add(t, gn, name=name)
#
# def _position_encoding(sentence_size, embedding_size):
# """Position encoding described in section 4.1 in "End to End Memory Networks" (http://arxiv.org/pdf/1503.08895v5.pdf)"""
# encoding = np.ones((embedding_size, sentence_size), dtype=np.float32)
# ls = sentence_size + 1
# le = embedding_size + 1
# for i in range(1, le):
# for j in range(1, ls):
# encoding[i - 1, j - 1] = (i - (le - 1) / 2) * (j - (ls - 1) / 2)
# encoding = 1 + 4 * encoding / embedding_size / sentence_size
# return np.transpose(encoding)
#
# # TODO fix positional encoding so that it varies according to sentence lengths
#
# def _xavier_weight_init():
# """Xavier initializer for all variables except embeddings as desribed in [1]"""
#
# def _xavier_initializer(shape, **kwargs):
# eps = np.sqrt(6) / np.sqrt(np.sum(shape))
# out = tf.random_uniform(shape, minval=-eps, maxval=eps)
# return out
#
# return _xavier_initializer
#
# def _last_relevant(output, length):
# """Finds the output at the end of each input"""
# batch_size = int(output.get_shape()[0])
# max_length = int(output.get_shape()[1])
# out_size = int(output.get_shape()[2])
# index = tf.range(0, batch_size) * max_length + (length - 1)
# flat = tf.reshape(output, [-1, out_size])
# relevant = tf.gather(flat, index)
# return relevant
#
# def batch_norm(x, is_training):
# """ Batch normalization.
# :param x: Tensor
# :param is_training: boolean tf.Variable, true indicates training phase
# :return: batch-normalized tensor
# """
# with tf.variable_scope('BatchNorm'):
# # calculate dimensions (from tf.contrib.layers.batch_norm)
# inputs_shape = x.get_shape()
# axis = list(range(len(inputs_shape) - 1))
# param_shape = inputs_shape[-1:]
#
# beta = tf.get_variable('beta', param_shape, initializer=tf.constant_initializer(0.))
# gamma = tf.get_variable('gamma', param_shape, initializer=tf.constant_initializer(1.))
# batch_mean, batch_var = tf.nn.moments(x, axis)
# ema = tf.train.ExponentialMovingAverage(decay=0.5)
#
# def mean_var_with_update():
# ema_apply_op = ema.apply([batch_mean, batch_var])
# with tf.control_dependencies([ema_apply_op]):
# return tf.identity(batch_mean), tf.identity(batch_var)
#
# mean, var = tf.cond(is_training,
# mean_var_with_update,
# lambda: (ema.average(batch_mean), ema.average(batch_var)))
# normed = tf.nn.batch_normalization(x, mean, var, beta, gamma, 1e-3)
# return normed
, which may include functions, classes, or code. Output only the next line. | gate_input = tf.nn.dropout(gate_input, self.config.keep_prob) |
Based on the snippet: <|code_start|>
router = fastapi.APIRouter()
oauth = OAuth()
oauth.register(
name="sso",
server_metadata_url=aurweb.config.get("sso", "openid_configuration"),
client_kwargs={"scope": "openid"},
client_id=aurweb.config.get("sso", "client_id"),
client_secret=aurweb.config.get("sso", "client_secret"),
<|code_end|>
, predict the immediate next line with the help of imports:
import time
import uuid
import fastapi
import aurweb.config
import aurweb.db
from urllib.parse import urlencode
from authlib.integrations.starlette_client import OAuth, OAuthError
from fastapi import Depends, HTTPException
from fastapi.responses import RedirectResponse
from sqlalchemy.sql import select
from starlette.requests import Request
from aurweb.l10n import get_translator_for_request
from aurweb.schema import Bans, Sessions, Users
and context (classes, functions, sometimes code) from other files:
# Path: aurweb/l10n.py
# def get_translator_for_request(request):
# """
# Determine the preferred language from a FastAPI request object and build a
# translator function for it.
#
# Example:
# ```python
# _ = get_translator_for_request(request)
# print(_("Hello"))
# ```
# """
# lang = request.cookies.get("AURLANG")
# if lang is None:
# lang = aurweb.config.get("options", "default_lang")
# translator = Translator()
#
# def translate(message):
# return translator.translate(message, lang)
#
# return translate
#
# Path: aurweb/schema.py
# def compile_tinyint_sqlite(type_, compiler, **kw):
# def compile_bigint_sqlite(type_, compiler, **kw):
. Output only the next line. | ) |
Using the snippet: <|code_start|>
router = fastapi.APIRouter()
oauth = OAuth()
oauth.register(
name="sso",
<|code_end|>
, determine the next line of code. You have imports:
import time
import uuid
import fastapi
import aurweb.config
import aurweb.db
from urllib.parse import urlencode
from authlib.integrations.starlette_client import OAuth, OAuthError
from fastapi import Depends, HTTPException
from fastapi.responses import RedirectResponse
from sqlalchemy.sql import select
from starlette.requests import Request
from aurweb.l10n import get_translator_for_request
from aurweb.schema import Bans, Sessions, Users
and context (class names, function names, or code) available:
# Path: aurweb/l10n.py
# def get_translator_for_request(request):
# """
# Determine the preferred language from a FastAPI request object and build a
# translator function for it.
#
# Example:
# ```python
# _ = get_translator_for_request(request)
# print(_("Hello"))
# ```
# """
# lang = request.cookies.get("AURLANG")
# if lang is None:
# lang = aurweb.config.get("options", "default_lang")
# translator = Translator()
#
# def translate(message):
# return translator.translate(message, lang)
#
# return translate
#
# Path: aurweb/schema.py
# def compile_tinyint_sqlite(type_, compiler, **kw):
# def compile_bigint_sqlite(type_, compiler, **kw):
. Output only the next line. | server_metadata_url=aurweb.config.get("sso", "openid_configuration"), |
Based on the snippet: <|code_start|>
router = fastapi.APIRouter()
oauth = OAuth()
oauth.register(
name="sso",
server_metadata_url=aurweb.config.get("sso", "openid_configuration"),
client_kwargs={"scope": "openid"},
client_id=aurweb.config.get("sso", "client_id"),
client_secret=aurweb.config.get("sso", "client_secret"),
<|code_end|>
, predict the immediate next line with the help of imports:
import time
import uuid
import fastapi
import aurweb.config
import aurweb.db
from urllib.parse import urlencode
from authlib.integrations.starlette_client import OAuth, OAuthError
from fastapi import Depends, HTTPException
from fastapi.responses import RedirectResponse
from sqlalchemy.sql import select
from starlette.requests import Request
from aurweb.l10n import get_translator_for_request
from aurweb.schema import Bans, Sessions, Users
and context (classes, functions, sometimes code) from other files:
# Path: aurweb/l10n.py
# def get_translator_for_request(request):
# """
# Determine the preferred language from a FastAPI request object and build a
# translator function for it.
#
# Example:
# ```python
# _ = get_translator_for_request(request)
# print(_("Hello"))
# ```
# """
# lang = request.cookies.get("AURLANG")
# if lang is None:
# lang = aurweb.config.get("options", "default_lang")
# translator = Translator()
#
# def translate(message):
# return translator.translate(message, lang)
#
# return translate
#
# Path: aurweb/schema.py
# def compile_tinyint_sqlite(type_, compiler, **kw):
# def compile_bigint_sqlite(type_, compiler, **kw):
. Output only the next line. | ) |
Based on the snippet: <|code_start|> raise InvalidUserException("test")
except InvalidUserException as exc:
assert str(exc) == "unknown user: test"
def test_not_voted_exception():
try:
raise NotVotedException("test")
except NotVotedException as exc:
assert str(exc) == "missing vote for package base: test"
def test_packagebase_exists_exception():
try:
raise PackageBaseExistsException("test")
except PackageBaseExistsException as exc:
assert str(exc) == "package base already exists: test"
def test_permission_denied_exception():
try:
raise PermissionDeniedException("test")
except PermissionDeniedException as exc:
assert str(exc) == "permission denied: test"
def test_repository_name_exception():
try:
raise InvalidRepositoryNameException("test")
except InvalidRepositoryNameException as exc:
<|code_end|>
, predict the immediate next line with the help of imports:
from aurweb.exceptions import (AlreadyVotedException, AurwebException, BannedException, BrokenUpdateHookException,
InvalidArgumentsException, InvalidCommentException, InvalidPackageBaseException,
InvalidReasonException, InvalidRepositoryNameException, InvalidUserException,
MaintenanceException, NotVotedException, PackageBaseExistsException, PermissionDeniedException)
and context (classes, functions, sometimes code) from other files:
# Path: aurweb/exceptions.py
# class AlreadyVotedException(AurwebException):
# def __init__(self, comment):
# msg = 'already voted for package base: {:s}'.format(comment)
# super(AlreadyVotedException, self).__init__(msg)
#
# class AurwebException(Exception):
# pass
#
# class BannedException(AurwebException):
# pass
#
# class BrokenUpdateHookException(AurwebException):
# def __init__(self, cmd):
# msg = 'broken update hook: {:s}'.format(cmd)
# super(BrokenUpdateHookException, self).__init__(msg)
#
# class InvalidArgumentsException(AurwebException):
# def __init__(self, msg):
# super(InvalidArgumentsException, self).__init__(msg)
#
# class InvalidCommentException(AurwebException):
# def __init__(self, comment):
# msg = 'comment is too short: {:s}'.format(comment)
# super(InvalidCommentException, self).__init__(msg)
#
# class InvalidPackageBaseException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'package base not found: {:s}'.format(pkgbase)
# super(InvalidPackageBaseException, self).__init__(msg)
#
# class InvalidReasonException(AurwebException):
# def __init__(self, reason):
# msg = 'invalid reason: {:s}'.format(reason)
# super(InvalidReasonException, self).__init__(msg)
#
# class InvalidRepositoryNameException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'invalid repository name: {:s}'.format(pkgbase)
# super(InvalidRepositoryNameException, self).__init__(msg)
#
# class InvalidUserException(AurwebException):
# def __init__(self, user):
# msg = 'unknown user: {:s}'.format(user)
# super(InvalidUserException, self).__init__(msg)
#
# class MaintenanceException(AurwebException):
# pass
#
# class NotVotedException(AurwebException):
# def __init__(self, comment):
# msg = 'missing vote for package base: {:s}'.format(comment)
# super(NotVotedException, self).__init__(msg)
#
# class PackageBaseExistsException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'package base already exists: {:s}'.format(pkgbase)
# super(PackageBaseExistsException, self).__init__(msg)
#
# class PermissionDeniedException(AurwebException):
# def __init__(self, user):
# msg = 'permission denied: {:s}'.format(user)
# super(PermissionDeniedException, self).__init__(msg)
. Output only the next line. | assert str(exc) == "invalid repository name: test" |
Here is a snippet: <|code_start|>
def test_aurweb_exception():
try:
raise AurwebException("test")
except AurwebException as exc:
assert str(exc) == "test"
def test_maintenance_exception():
try:
raise MaintenanceException("test")
except MaintenanceException as exc:
assert str(exc) == "test"
<|code_end|>
. Write the next line using the current file imports:
from aurweb.exceptions import (AlreadyVotedException, AurwebException, BannedException, BrokenUpdateHookException,
InvalidArgumentsException, InvalidCommentException, InvalidPackageBaseException,
InvalidReasonException, InvalidRepositoryNameException, InvalidUserException,
MaintenanceException, NotVotedException, PackageBaseExistsException, PermissionDeniedException)
and context from other files:
# Path: aurweb/exceptions.py
# class AlreadyVotedException(AurwebException):
# def __init__(self, comment):
# msg = 'already voted for package base: {:s}'.format(comment)
# super(AlreadyVotedException, self).__init__(msg)
#
# class AurwebException(Exception):
# pass
#
# class BannedException(AurwebException):
# pass
#
# class BrokenUpdateHookException(AurwebException):
# def __init__(self, cmd):
# msg = 'broken update hook: {:s}'.format(cmd)
# super(BrokenUpdateHookException, self).__init__(msg)
#
# class InvalidArgumentsException(AurwebException):
# def __init__(self, msg):
# super(InvalidArgumentsException, self).__init__(msg)
#
# class InvalidCommentException(AurwebException):
# def __init__(self, comment):
# msg = 'comment is too short: {:s}'.format(comment)
# super(InvalidCommentException, self).__init__(msg)
#
# class InvalidPackageBaseException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'package base not found: {:s}'.format(pkgbase)
# super(InvalidPackageBaseException, self).__init__(msg)
#
# class InvalidReasonException(AurwebException):
# def __init__(self, reason):
# msg = 'invalid reason: {:s}'.format(reason)
# super(InvalidReasonException, self).__init__(msg)
#
# class InvalidRepositoryNameException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'invalid repository name: {:s}'.format(pkgbase)
# super(InvalidRepositoryNameException, self).__init__(msg)
#
# class InvalidUserException(AurwebException):
# def __init__(self, user):
# msg = 'unknown user: {:s}'.format(user)
# super(InvalidUserException, self).__init__(msg)
#
# class MaintenanceException(AurwebException):
# pass
#
# class NotVotedException(AurwebException):
# def __init__(self, comment):
# msg = 'missing vote for package base: {:s}'.format(comment)
# super(NotVotedException, self).__init__(msg)
#
# class PackageBaseExistsException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'package base already exists: {:s}'.format(pkgbase)
# super(PackageBaseExistsException, self).__init__(msg)
#
# class PermissionDeniedException(AurwebException):
# def __init__(self, user):
# msg = 'permission denied: {:s}'.format(user)
# super(PermissionDeniedException, self).__init__(msg)
, which may include functions, classes, or code. Output only the next line. | def test_banned_exception(): |
Continue the code snippet: <|code_start|>
def test_aurweb_exception():
try:
raise AurwebException("test")
except AurwebException as exc:
assert str(exc) == "test"
def test_maintenance_exception():
<|code_end|>
. Use current file imports:
from aurweb.exceptions import (AlreadyVotedException, AurwebException, BannedException, BrokenUpdateHookException,
InvalidArgumentsException, InvalidCommentException, InvalidPackageBaseException,
InvalidReasonException, InvalidRepositoryNameException, InvalidUserException,
MaintenanceException, NotVotedException, PackageBaseExistsException, PermissionDeniedException)
and context (classes, functions, or code) from other files:
# Path: aurweb/exceptions.py
# class AlreadyVotedException(AurwebException):
# def __init__(self, comment):
# msg = 'already voted for package base: {:s}'.format(comment)
# super(AlreadyVotedException, self).__init__(msg)
#
# class AurwebException(Exception):
# pass
#
# class BannedException(AurwebException):
# pass
#
# class BrokenUpdateHookException(AurwebException):
# def __init__(self, cmd):
# msg = 'broken update hook: {:s}'.format(cmd)
# super(BrokenUpdateHookException, self).__init__(msg)
#
# class InvalidArgumentsException(AurwebException):
# def __init__(self, msg):
# super(InvalidArgumentsException, self).__init__(msg)
#
# class InvalidCommentException(AurwebException):
# def __init__(self, comment):
# msg = 'comment is too short: {:s}'.format(comment)
# super(InvalidCommentException, self).__init__(msg)
#
# class InvalidPackageBaseException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'package base not found: {:s}'.format(pkgbase)
# super(InvalidPackageBaseException, self).__init__(msg)
#
# class InvalidReasonException(AurwebException):
# def __init__(self, reason):
# msg = 'invalid reason: {:s}'.format(reason)
# super(InvalidReasonException, self).__init__(msg)
#
# class InvalidRepositoryNameException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'invalid repository name: {:s}'.format(pkgbase)
# super(InvalidRepositoryNameException, self).__init__(msg)
#
# class InvalidUserException(AurwebException):
# def __init__(self, user):
# msg = 'unknown user: {:s}'.format(user)
# super(InvalidUserException, self).__init__(msg)
#
# class MaintenanceException(AurwebException):
# pass
#
# class NotVotedException(AurwebException):
# def __init__(self, comment):
# msg = 'missing vote for package base: {:s}'.format(comment)
# super(NotVotedException, self).__init__(msg)
#
# class PackageBaseExistsException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'package base already exists: {:s}'.format(pkgbase)
# super(PackageBaseExistsException, self).__init__(msg)
#
# class PermissionDeniedException(AurwebException):
# def __init__(self, user):
# msg = 'permission denied: {:s}'.format(user)
# super(PermissionDeniedException, self).__init__(msg)
. Output only the next line. | try: |
Given the code snippet: <|code_start|>
def test_banned_exception():
try:
raise BannedException("test")
except BannedException as exc:
assert str(exc) == "test"
def test_already_voted_exception():
try:
raise AlreadyVotedException("test")
except AlreadyVotedException as exc:
assert str(exc) == "already voted for package base: test"
def test_broken_update_hook_exception():
try:
raise BrokenUpdateHookException("test")
except BrokenUpdateHookException as exc:
assert str(exc) == "broken update hook: test"
def test_invalid_arguments_exception():
try:
raise InvalidArgumentsException("test")
except InvalidArgumentsException as exc:
assert str(exc) == "test"
<|code_end|>
, generate the next line using the imports in this file:
from aurweb.exceptions import (AlreadyVotedException, AurwebException, BannedException, BrokenUpdateHookException,
InvalidArgumentsException, InvalidCommentException, InvalidPackageBaseException,
InvalidReasonException, InvalidRepositoryNameException, InvalidUserException,
MaintenanceException, NotVotedException, PackageBaseExistsException, PermissionDeniedException)
and context (functions, classes, or occasionally code) from other files:
# Path: aurweb/exceptions.py
# class AlreadyVotedException(AurwebException):
# def __init__(self, comment):
# msg = 'already voted for package base: {:s}'.format(comment)
# super(AlreadyVotedException, self).__init__(msg)
#
# class AurwebException(Exception):
# pass
#
# class BannedException(AurwebException):
# pass
#
# class BrokenUpdateHookException(AurwebException):
# def __init__(self, cmd):
# msg = 'broken update hook: {:s}'.format(cmd)
# super(BrokenUpdateHookException, self).__init__(msg)
#
# class InvalidArgumentsException(AurwebException):
# def __init__(self, msg):
# super(InvalidArgumentsException, self).__init__(msg)
#
# class InvalidCommentException(AurwebException):
# def __init__(self, comment):
# msg = 'comment is too short: {:s}'.format(comment)
# super(InvalidCommentException, self).__init__(msg)
#
# class InvalidPackageBaseException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'package base not found: {:s}'.format(pkgbase)
# super(InvalidPackageBaseException, self).__init__(msg)
#
# class InvalidReasonException(AurwebException):
# def __init__(self, reason):
# msg = 'invalid reason: {:s}'.format(reason)
# super(InvalidReasonException, self).__init__(msg)
#
# class InvalidRepositoryNameException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'invalid repository name: {:s}'.format(pkgbase)
# super(InvalidRepositoryNameException, self).__init__(msg)
#
# class InvalidUserException(AurwebException):
# def __init__(self, user):
# msg = 'unknown user: {:s}'.format(user)
# super(InvalidUserException, self).__init__(msg)
#
# class MaintenanceException(AurwebException):
# pass
#
# class NotVotedException(AurwebException):
# def __init__(self, comment):
# msg = 'missing vote for package base: {:s}'.format(comment)
# super(NotVotedException, self).__init__(msg)
#
# class PackageBaseExistsException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'package base already exists: {:s}'.format(pkgbase)
# super(PackageBaseExistsException, self).__init__(msg)
#
# class PermissionDeniedException(AurwebException):
# def __init__(self, user):
# msg = 'permission denied: {:s}'.format(user)
# super(PermissionDeniedException, self).__init__(msg)
. Output only the next line. | def test_invalid_packagebase_exception(): |
Continue the code snippet: <|code_start|>
def test_already_voted_exception():
try:
raise AlreadyVotedException("test")
except AlreadyVotedException as exc:
assert str(exc) == "already voted for package base: test"
def test_broken_update_hook_exception():
try:
raise BrokenUpdateHookException("test")
except BrokenUpdateHookException as exc:
assert str(exc) == "broken update hook: test"
def test_invalid_arguments_exception():
try:
raise InvalidArgumentsException("test")
except InvalidArgumentsException as exc:
assert str(exc) == "test"
def test_invalid_packagebase_exception():
try:
raise InvalidPackageBaseException("test")
except InvalidPackageBaseException as exc:
assert str(exc) == "package base not found: test"
def test_invalid_comment_exception():
<|code_end|>
. Use current file imports:
from aurweb.exceptions import (AlreadyVotedException, AurwebException, BannedException, BrokenUpdateHookException,
InvalidArgumentsException, InvalidCommentException, InvalidPackageBaseException,
InvalidReasonException, InvalidRepositoryNameException, InvalidUserException,
MaintenanceException, NotVotedException, PackageBaseExistsException, PermissionDeniedException)
and context (classes, functions, or code) from other files:
# Path: aurweb/exceptions.py
# class AlreadyVotedException(AurwebException):
# def __init__(self, comment):
# msg = 'already voted for package base: {:s}'.format(comment)
# super(AlreadyVotedException, self).__init__(msg)
#
# class AurwebException(Exception):
# pass
#
# class BannedException(AurwebException):
# pass
#
# class BrokenUpdateHookException(AurwebException):
# def __init__(self, cmd):
# msg = 'broken update hook: {:s}'.format(cmd)
# super(BrokenUpdateHookException, self).__init__(msg)
#
# class InvalidArgumentsException(AurwebException):
# def __init__(self, msg):
# super(InvalidArgumentsException, self).__init__(msg)
#
# class InvalidCommentException(AurwebException):
# def __init__(self, comment):
# msg = 'comment is too short: {:s}'.format(comment)
# super(InvalidCommentException, self).__init__(msg)
#
# class InvalidPackageBaseException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'package base not found: {:s}'.format(pkgbase)
# super(InvalidPackageBaseException, self).__init__(msg)
#
# class InvalidReasonException(AurwebException):
# def __init__(self, reason):
# msg = 'invalid reason: {:s}'.format(reason)
# super(InvalidReasonException, self).__init__(msg)
#
# class InvalidRepositoryNameException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'invalid repository name: {:s}'.format(pkgbase)
# super(InvalidRepositoryNameException, self).__init__(msg)
#
# class InvalidUserException(AurwebException):
# def __init__(self, user):
# msg = 'unknown user: {:s}'.format(user)
# super(InvalidUserException, self).__init__(msg)
#
# class MaintenanceException(AurwebException):
# pass
#
# class NotVotedException(AurwebException):
# def __init__(self, comment):
# msg = 'missing vote for package base: {:s}'.format(comment)
# super(NotVotedException, self).__init__(msg)
#
# class PackageBaseExistsException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'package base already exists: {:s}'.format(pkgbase)
# super(PackageBaseExistsException, self).__init__(msg)
#
# class PermissionDeniedException(AurwebException):
# def __init__(self, user):
# msg = 'permission denied: {:s}'.format(user)
# super(PermissionDeniedException, self).__init__(msg)
. Output only the next line. | try: |
Using the snippet: <|code_start|>
def test_aurweb_exception():
try:
raise AurwebException("test")
except AurwebException as exc:
assert str(exc) == "test"
def test_maintenance_exception():
try:
raise MaintenanceException("test")
except MaintenanceException as exc:
assert str(exc) == "test"
def test_banned_exception():
try:
raise BannedException("test")
except BannedException as exc:
assert str(exc) == "test"
<|code_end|>
, determine the next line of code. You have imports:
from aurweb.exceptions import (AlreadyVotedException, AurwebException, BannedException, BrokenUpdateHookException,
InvalidArgumentsException, InvalidCommentException, InvalidPackageBaseException,
InvalidReasonException, InvalidRepositoryNameException, InvalidUserException,
MaintenanceException, NotVotedException, PackageBaseExistsException, PermissionDeniedException)
and context (class names, function names, or code) available:
# Path: aurweb/exceptions.py
# class AlreadyVotedException(AurwebException):
# def __init__(self, comment):
# msg = 'already voted for package base: {:s}'.format(comment)
# super(AlreadyVotedException, self).__init__(msg)
#
# class AurwebException(Exception):
# pass
#
# class BannedException(AurwebException):
# pass
#
# class BrokenUpdateHookException(AurwebException):
# def __init__(self, cmd):
# msg = 'broken update hook: {:s}'.format(cmd)
# super(BrokenUpdateHookException, self).__init__(msg)
#
# class InvalidArgumentsException(AurwebException):
# def __init__(self, msg):
# super(InvalidArgumentsException, self).__init__(msg)
#
# class InvalidCommentException(AurwebException):
# def __init__(self, comment):
# msg = 'comment is too short: {:s}'.format(comment)
# super(InvalidCommentException, self).__init__(msg)
#
# class InvalidPackageBaseException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'package base not found: {:s}'.format(pkgbase)
# super(InvalidPackageBaseException, self).__init__(msg)
#
# class InvalidReasonException(AurwebException):
# def __init__(self, reason):
# msg = 'invalid reason: {:s}'.format(reason)
# super(InvalidReasonException, self).__init__(msg)
#
# class InvalidRepositoryNameException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'invalid repository name: {:s}'.format(pkgbase)
# super(InvalidRepositoryNameException, self).__init__(msg)
#
# class InvalidUserException(AurwebException):
# def __init__(self, user):
# msg = 'unknown user: {:s}'.format(user)
# super(InvalidUserException, self).__init__(msg)
#
# class MaintenanceException(AurwebException):
# pass
#
# class NotVotedException(AurwebException):
# def __init__(self, comment):
# msg = 'missing vote for package base: {:s}'.format(comment)
# super(NotVotedException, self).__init__(msg)
#
# class PackageBaseExistsException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'package base already exists: {:s}'.format(pkgbase)
# super(PackageBaseExistsException, self).__init__(msg)
#
# class PermissionDeniedException(AurwebException):
# def __init__(self, user):
# msg = 'permission denied: {:s}'.format(user)
# super(PermissionDeniedException, self).__init__(msg)
. Output only the next line. | def test_already_voted_exception(): |
Predict the next line for this snippet: <|code_start|>
def test_aurweb_exception():
try:
raise AurwebException("test")
except AurwebException as exc:
assert str(exc) == "test"
def test_maintenance_exception():
try:
raise MaintenanceException("test")
except MaintenanceException as exc:
assert str(exc) == "test"
def test_banned_exception():
<|code_end|>
with the help of current file imports:
from aurweb.exceptions import (AlreadyVotedException, AurwebException, BannedException, BrokenUpdateHookException,
InvalidArgumentsException, InvalidCommentException, InvalidPackageBaseException,
InvalidReasonException, InvalidRepositoryNameException, InvalidUserException,
MaintenanceException, NotVotedException, PackageBaseExistsException, PermissionDeniedException)
and context from other files:
# Path: aurweb/exceptions.py
# class AlreadyVotedException(AurwebException):
# def __init__(self, comment):
# msg = 'already voted for package base: {:s}'.format(comment)
# super(AlreadyVotedException, self).__init__(msg)
#
# class AurwebException(Exception):
# pass
#
# class BannedException(AurwebException):
# pass
#
# class BrokenUpdateHookException(AurwebException):
# def __init__(self, cmd):
# msg = 'broken update hook: {:s}'.format(cmd)
# super(BrokenUpdateHookException, self).__init__(msg)
#
# class InvalidArgumentsException(AurwebException):
# def __init__(self, msg):
# super(InvalidArgumentsException, self).__init__(msg)
#
# class InvalidCommentException(AurwebException):
# def __init__(self, comment):
# msg = 'comment is too short: {:s}'.format(comment)
# super(InvalidCommentException, self).__init__(msg)
#
# class InvalidPackageBaseException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'package base not found: {:s}'.format(pkgbase)
# super(InvalidPackageBaseException, self).__init__(msg)
#
# class InvalidReasonException(AurwebException):
# def __init__(self, reason):
# msg = 'invalid reason: {:s}'.format(reason)
# super(InvalidReasonException, self).__init__(msg)
#
# class InvalidRepositoryNameException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'invalid repository name: {:s}'.format(pkgbase)
# super(InvalidRepositoryNameException, self).__init__(msg)
#
# class InvalidUserException(AurwebException):
# def __init__(self, user):
# msg = 'unknown user: {:s}'.format(user)
# super(InvalidUserException, self).__init__(msg)
#
# class MaintenanceException(AurwebException):
# pass
#
# class NotVotedException(AurwebException):
# def __init__(self, comment):
# msg = 'missing vote for package base: {:s}'.format(comment)
# super(NotVotedException, self).__init__(msg)
#
# class PackageBaseExistsException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'package base already exists: {:s}'.format(pkgbase)
# super(PackageBaseExistsException, self).__init__(msg)
#
# class PermissionDeniedException(AurwebException):
# def __init__(self, user):
# msg = 'permission denied: {:s}'.format(user)
# super(PermissionDeniedException, self).__init__(msg)
, which may contain function names, class names, or code. Output only the next line. | try: |
Given the code snippet: <|code_start|> raise InvalidArgumentsException("test")
except InvalidArgumentsException as exc:
assert str(exc) == "test"
def test_invalid_packagebase_exception():
try:
raise InvalidPackageBaseException("test")
except InvalidPackageBaseException as exc:
assert str(exc) == "package base not found: test"
def test_invalid_comment_exception():
try:
raise InvalidCommentException("test")
except InvalidCommentException as exc:
assert str(exc) == "comment is too short: test"
def test_invalid_reason_exception():
try:
raise InvalidReasonException("test")
except InvalidReasonException as exc:
assert str(exc) == "invalid reason: test"
def test_invalid_user_exception():
try:
raise InvalidUserException("test")
except InvalidUserException as exc:
<|code_end|>
, generate the next line using the imports in this file:
from aurweb.exceptions import (AlreadyVotedException, AurwebException, BannedException, BrokenUpdateHookException,
InvalidArgumentsException, InvalidCommentException, InvalidPackageBaseException,
InvalidReasonException, InvalidRepositoryNameException, InvalidUserException,
MaintenanceException, NotVotedException, PackageBaseExistsException, PermissionDeniedException)
and context (functions, classes, or occasionally code) from other files:
# Path: aurweb/exceptions.py
# class AlreadyVotedException(AurwebException):
# def __init__(self, comment):
# msg = 'already voted for package base: {:s}'.format(comment)
# super(AlreadyVotedException, self).__init__(msg)
#
# class AurwebException(Exception):
# pass
#
# class BannedException(AurwebException):
# pass
#
# class BrokenUpdateHookException(AurwebException):
# def __init__(self, cmd):
# msg = 'broken update hook: {:s}'.format(cmd)
# super(BrokenUpdateHookException, self).__init__(msg)
#
# class InvalidArgumentsException(AurwebException):
# def __init__(self, msg):
# super(InvalidArgumentsException, self).__init__(msg)
#
# class InvalidCommentException(AurwebException):
# def __init__(self, comment):
# msg = 'comment is too short: {:s}'.format(comment)
# super(InvalidCommentException, self).__init__(msg)
#
# class InvalidPackageBaseException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'package base not found: {:s}'.format(pkgbase)
# super(InvalidPackageBaseException, self).__init__(msg)
#
# class InvalidReasonException(AurwebException):
# def __init__(self, reason):
# msg = 'invalid reason: {:s}'.format(reason)
# super(InvalidReasonException, self).__init__(msg)
#
# class InvalidRepositoryNameException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'invalid repository name: {:s}'.format(pkgbase)
# super(InvalidRepositoryNameException, self).__init__(msg)
#
# class InvalidUserException(AurwebException):
# def __init__(self, user):
# msg = 'unknown user: {:s}'.format(user)
# super(InvalidUserException, self).__init__(msg)
#
# class MaintenanceException(AurwebException):
# pass
#
# class NotVotedException(AurwebException):
# def __init__(self, comment):
# msg = 'missing vote for package base: {:s}'.format(comment)
# super(NotVotedException, self).__init__(msg)
#
# class PackageBaseExistsException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'package base already exists: {:s}'.format(pkgbase)
# super(PackageBaseExistsException, self).__init__(msg)
#
# class PermissionDeniedException(AurwebException):
# def __init__(self, user):
# msg = 'permission denied: {:s}'.format(user)
# super(PermissionDeniedException, self).__init__(msg)
. Output only the next line. | assert str(exc) == "unknown user: test" |
Predict the next line for this snippet: <|code_start|>
def test_aurweb_exception():
try:
raise AurwebException("test")
except AurwebException as exc:
assert str(exc) == "test"
def test_maintenance_exception():
try:
raise MaintenanceException("test")
except MaintenanceException as exc:
assert str(exc) == "test"
<|code_end|>
with the help of current file imports:
from aurweb.exceptions import (AlreadyVotedException, AurwebException, BannedException, BrokenUpdateHookException,
InvalidArgumentsException, InvalidCommentException, InvalidPackageBaseException,
InvalidReasonException, InvalidRepositoryNameException, InvalidUserException,
MaintenanceException, NotVotedException, PackageBaseExistsException, PermissionDeniedException)
and context from other files:
# Path: aurweb/exceptions.py
# class AlreadyVotedException(AurwebException):
# def __init__(self, comment):
# msg = 'already voted for package base: {:s}'.format(comment)
# super(AlreadyVotedException, self).__init__(msg)
#
# class AurwebException(Exception):
# pass
#
# class BannedException(AurwebException):
# pass
#
# class BrokenUpdateHookException(AurwebException):
# def __init__(self, cmd):
# msg = 'broken update hook: {:s}'.format(cmd)
# super(BrokenUpdateHookException, self).__init__(msg)
#
# class InvalidArgumentsException(AurwebException):
# def __init__(self, msg):
# super(InvalidArgumentsException, self).__init__(msg)
#
# class InvalidCommentException(AurwebException):
# def __init__(self, comment):
# msg = 'comment is too short: {:s}'.format(comment)
# super(InvalidCommentException, self).__init__(msg)
#
# class InvalidPackageBaseException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'package base not found: {:s}'.format(pkgbase)
# super(InvalidPackageBaseException, self).__init__(msg)
#
# class InvalidReasonException(AurwebException):
# def __init__(self, reason):
# msg = 'invalid reason: {:s}'.format(reason)
# super(InvalidReasonException, self).__init__(msg)
#
# class InvalidRepositoryNameException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'invalid repository name: {:s}'.format(pkgbase)
# super(InvalidRepositoryNameException, self).__init__(msg)
#
# class InvalidUserException(AurwebException):
# def __init__(self, user):
# msg = 'unknown user: {:s}'.format(user)
# super(InvalidUserException, self).__init__(msg)
#
# class MaintenanceException(AurwebException):
# pass
#
# class NotVotedException(AurwebException):
# def __init__(self, comment):
# msg = 'missing vote for package base: {:s}'.format(comment)
# super(NotVotedException, self).__init__(msg)
#
# class PackageBaseExistsException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'package base already exists: {:s}'.format(pkgbase)
# super(PackageBaseExistsException, self).__init__(msg)
#
# class PermissionDeniedException(AurwebException):
# def __init__(self, user):
# msg = 'permission denied: {:s}'.format(user)
# super(PermissionDeniedException, self).__init__(msg)
, which may contain function names, class names, or code. Output only the next line. | def test_banned_exception(): |
Continue the code snippet: <|code_start|>
def test_banned_exception():
try:
raise BannedException("test")
except BannedException as exc:
assert str(exc) == "test"
def test_already_voted_exception():
try:
raise AlreadyVotedException("test")
except AlreadyVotedException as exc:
assert str(exc) == "already voted for package base: test"
def test_broken_update_hook_exception():
try:
raise BrokenUpdateHookException("test")
except BrokenUpdateHookException as exc:
assert str(exc) == "broken update hook: test"
def test_invalid_arguments_exception():
try:
raise InvalidArgumentsException("test")
except InvalidArgumentsException as exc:
assert str(exc) == "test"
<|code_end|>
. Use current file imports:
from aurweb.exceptions import (AlreadyVotedException, AurwebException, BannedException, BrokenUpdateHookException,
InvalidArgumentsException, InvalidCommentException, InvalidPackageBaseException,
InvalidReasonException, InvalidRepositoryNameException, InvalidUserException,
MaintenanceException, NotVotedException, PackageBaseExistsException, PermissionDeniedException)
and context (classes, functions, or code) from other files:
# Path: aurweb/exceptions.py
# class AlreadyVotedException(AurwebException):
# def __init__(self, comment):
# msg = 'already voted for package base: {:s}'.format(comment)
# super(AlreadyVotedException, self).__init__(msg)
#
# class AurwebException(Exception):
# pass
#
# class BannedException(AurwebException):
# pass
#
# class BrokenUpdateHookException(AurwebException):
# def __init__(self, cmd):
# msg = 'broken update hook: {:s}'.format(cmd)
# super(BrokenUpdateHookException, self).__init__(msg)
#
# class InvalidArgumentsException(AurwebException):
# def __init__(self, msg):
# super(InvalidArgumentsException, self).__init__(msg)
#
# class InvalidCommentException(AurwebException):
# def __init__(self, comment):
# msg = 'comment is too short: {:s}'.format(comment)
# super(InvalidCommentException, self).__init__(msg)
#
# class InvalidPackageBaseException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'package base not found: {:s}'.format(pkgbase)
# super(InvalidPackageBaseException, self).__init__(msg)
#
# class InvalidReasonException(AurwebException):
# def __init__(self, reason):
# msg = 'invalid reason: {:s}'.format(reason)
# super(InvalidReasonException, self).__init__(msg)
#
# class InvalidRepositoryNameException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'invalid repository name: {:s}'.format(pkgbase)
# super(InvalidRepositoryNameException, self).__init__(msg)
#
# class InvalidUserException(AurwebException):
# def __init__(self, user):
# msg = 'unknown user: {:s}'.format(user)
# super(InvalidUserException, self).__init__(msg)
#
# class MaintenanceException(AurwebException):
# pass
#
# class NotVotedException(AurwebException):
# def __init__(self, comment):
# msg = 'missing vote for package base: {:s}'.format(comment)
# super(NotVotedException, self).__init__(msg)
#
# class PackageBaseExistsException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'package base already exists: {:s}'.format(pkgbase)
# super(PackageBaseExistsException, self).__init__(msg)
#
# class PermissionDeniedException(AurwebException):
# def __init__(self, user):
# msg = 'permission denied: {:s}'.format(user)
# super(PermissionDeniedException, self).__init__(msg)
. Output only the next line. | def test_invalid_packagebase_exception(): |
Using the snippet: <|code_start|> raise AurwebException("test")
except AurwebException as exc:
assert str(exc) == "test"
def test_maintenance_exception():
try:
raise MaintenanceException("test")
except MaintenanceException as exc:
assert str(exc) == "test"
def test_banned_exception():
try:
raise BannedException("test")
except BannedException as exc:
assert str(exc) == "test"
def test_already_voted_exception():
try:
raise AlreadyVotedException("test")
except AlreadyVotedException as exc:
assert str(exc) == "already voted for package base: test"
def test_broken_update_hook_exception():
try:
raise BrokenUpdateHookException("test")
except BrokenUpdateHookException as exc:
<|code_end|>
, determine the next line of code. You have imports:
from aurweb.exceptions import (AlreadyVotedException, AurwebException, BannedException, BrokenUpdateHookException,
InvalidArgumentsException, InvalidCommentException, InvalidPackageBaseException,
InvalidReasonException, InvalidRepositoryNameException, InvalidUserException,
MaintenanceException, NotVotedException, PackageBaseExistsException, PermissionDeniedException)
and context (class names, function names, or code) available:
# Path: aurweb/exceptions.py
# class AlreadyVotedException(AurwebException):
# def __init__(self, comment):
# msg = 'already voted for package base: {:s}'.format(comment)
# super(AlreadyVotedException, self).__init__(msg)
#
# class AurwebException(Exception):
# pass
#
# class BannedException(AurwebException):
# pass
#
# class BrokenUpdateHookException(AurwebException):
# def __init__(self, cmd):
# msg = 'broken update hook: {:s}'.format(cmd)
# super(BrokenUpdateHookException, self).__init__(msg)
#
# class InvalidArgumentsException(AurwebException):
# def __init__(self, msg):
# super(InvalidArgumentsException, self).__init__(msg)
#
# class InvalidCommentException(AurwebException):
# def __init__(self, comment):
# msg = 'comment is too short: {:s}'.format(comment)
# super(InvalidCommentException, self).__init__(msg)
#
# class InvalidPackageBaseException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'package base not found: {:s}'.format(pkgbase)
# super(InvalidPackageBaseException, self).__init__(msg)
#
# class InvalidReasonException(AurwebException):
# def __init__(self, reason):
# msg = 'invalid reason: {:s}'.format(reason)
# super(InvalidReasonException, self).__init__(msg)
#
# class InvalidRepositoryNameException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'invalid repository name: {:s}'.format(pkgbase)
# super(InvalidRepositoryNameException, self).__init__(msg)
#
# class InvalidUserException(AurwebException):
# def __init__(self, user):
# msg = 'unknown user: {:s}'.format(user)
# super(InvalidUserException, self).__init__(msg)
#
# class MaintenanceException(AurwebException):
# pass
#
# class NotVotedException(AurwebException):
# def __init__(self, comment):
# msg = 'missing vote for package base: {:s}'.format(comment)
# super(NotVotedException, self).__init__(msg)
#
# class PackageBaseExistsException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'package base already exists: {:s}'.format(pkgbase)
# super(PackageBaseExistsException, self).__init__(msg)
#
# class PermissionDeniedException(AurwebException):
# def __init__(self, user):
# msg = 'permission denied: {:s}'.format(user)
# super(PermissionDeniedException, self).__init__(msg)
. Output only the next line. | assert str(exc) == "broken update hook: test" |
Given the following code snippet before the placeholder: <|code_start|>
def test_aurweb_exception():
try:
raise AurwebException("test")
except AurwebException as exc:
assert str(exc) == "test"
def test_maintenance_exception():
try:
raise MaintenanceException("test")
except MaintenanceException as exc:
assert str(exc) == "test"
def test_banned_exception():
try:
raise BannedException("test")
except BannedException as exc:
<|code_end|>
, predict the next line using imports from the current file:
from aurweb.exceptions import (AlreadyVotedException, AurwebException, BannedException, BrokenUpdateHookException,
InvalidArgumentsException, InvalidCommentException, InvalidPackageBaseException,
InvalidReasonException, InvalidRepositoryNameException, InvalidUserException,
MaintenanceException, NotVotedException, PackageBaseExistsException, PermissionDeniedException)
and context including class names, function names, and sometimes code from other files:
# Path: aurweb/exceptions.py
# class AlreadyVotedException(AurwebException):
# def __init__(self, comment):
# msg = 'already voted for package base: {:s}'.format(comment)
# super(AlreadyVotedException, self).__init__(msg)
#
# class AurwebException(Exception):
# pass
#
# class BannedException(AurwebException):
# pass
#
# class BrokenUpdateHookException(AurwebException):
# def __init__(self, cmd):
# msg = 'broken update hook: {:s}'.format(cmd)
# super(BrokenUpdateHookException, self).__init__(msg)
#
# class InvalidArgumentsException(AurwebException):
# def __init__(self, msg):
# super(InvalidArgumentsException, self).__init__(msg)
#
# class InvalidCommentException(AurwebException):
# def __init__(self, comment):
# msg = 'comment is too short: {:s}'.format(comment)
# super(InvalidCommentException, self).__init__(msg)
#
# class InvalidPackageBaseException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'package base not found: {:s}'.format(pkgbase)
# super(InvalidPackageBaseException, self).__init__(msg)
#
# class InvalidReasonException(AurwebException):
# def __init__(self, reason):
# msg = 'invalid reason: {:s}'.format(reason)
# super(InvalidReasonException, self).__init__(msg)
#
# class InvalidRepositoryNameException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'invalid repository name: {:s}'.format(pkgbase)
# super(InvalidRepositoryNameException, self).__init__(msg)
#
# class InvalidUserException(AurwebException):
# def __init__(self, user):
# msg = 'unknown user: {:s}'.format(user)
# super(InvalidUserException, self).__init__(msg)
#
# class MaintenanceException(AurwebException):
# pass
#
# class NotVotedException(AurwebException):
# def __init__(self, comment):
# msg = 'missing vote for package base: {:s}'.format(comment)
# super(NotVotedException, self).__init__(msg)
#
# class PackageBaseExistsException(AurwebException):
# def __init__(self, pkgbase):
# msg = 'package base already exists: {:s}'.format(pkgbase)
# super(PackageBaseExistsException, self).__init__(msg)
#
# class PermissionDeniedException(AurwebException):
# def __init__(self, user):
# msg = 'permission denied: {:s}'.format(user)
# super(PermissionDeniedException, self).__init__(msg)
. Output only the next line. | assert str(exc) == "test" |
Continue the code snippet: <|code_start|>
app = FastAPI()
session_secret = aurweb.config.get("fastapi", "session_secret")
if not session_secret:
raise Exception("[fastapi] session_secret must not be empty")
<|code_end|>
. Use current file imports:
import http
import aurweb.config
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse
from starlette.middleware.sessions import SessionMiddleware
from aurweb.routers import sso
and context (classes, functions, or code) from other files:
# Path: aurweb/routers/sso.py
# async def login(request: Request, redirect: str = None):
# def is_account_suspended(conn, user_id):
# def open_session(request, conn, user_id):
# def is_ip_banned(conn, ip):
# def is_aur_url(url):
# async def authenticate(request: Request, redirect: str = None, conn=Depends(aurweb.db.connect)):
# async def logout(request: Request):
. Output only the next line. | app.add_middleware(SessionMiddleware, secret_key=session_secret) |
Based on the snippet: <|code_start|>
class Test_remove_thousand_sep:
@pytest.mark.parametrize(
["value", "expected"],
[
["1,000,000,000,000", "1000000000000"],
["100,000,000,000", "100000000000"],
["10,000,000,000", "10000000000"],
["9,999,999,999", "9999999999"],
["123,456,789", "123456789"],
["2021-01-23", "2021-01-23"],
["1,000.1", "1000.1"],
],
)
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from typepy._common import remove_thousand_sep
and context (classes, functions, sometimes code) from other files:
# Path: typepy/_common.py
# def remove_thousand_sep(value: str) -> str:
# if REGEXP_THOUSAND_SEP.search(value) is None:
# return value
#
# return value.replace(",", "")
. Output only the next line. | def test_normal(self, value, expected): |
Using the snippet: <|code_start|> try:
if self.connect():
ftp_client= self.client.open_sftp()
ftp_client.put(uploadlocalfilepath,uploadremotefilepath)
ftp_client.close()
self.client.close()
else:
print("Could not establish SSH connection")
result_flag = False
except Exception as e:
print('\nUnable to upload the file to the remote server',uploadremotefilepath)
print('PYTHON SAYS:',e)
result_flag = False
ftp_client.close()
self.client.close()
return result_flag
def download_file(self,downloadremotefilepath,downloadlocalfilepath):
"This method downloads the file from remote server"
result_flag = True
try:
if self.connect():
ftp_client= self.client.open_sftp()
ftp_client.get(downloadremotefilepath,downloadlocalfilepath)
ftp_client.close()
self.client.close()
else:
print("Could not establish SSH connection")
<|code_end|>
, determine the next line of code. You have imports:
import paramiko
import os,sys
import socket
from conf import ssh_conf as conf_file
and context (class names, function names, or code) available:
# Path: conf/ssh_conf.py
# HOST='Enter your host details here'
# USERNAME='Enter your username here'
# PASSWORD='Enter your password here'
# PORT = 22
# TIMEOUT = 10
# PKEY = 'Enter your key filename here'
# COMMANDS = ['ls;mkdir sample']
# UPLOADREMOTEFILEPATH = '/etc/example/filename.txt'
# UPLOADLOCALFILEPATH = 'home/filename.txt'
# DOWNLOADREMOTEFILEPATH = '/etc/sample/data.txt'
# DOWNLOADLOCALFILEPATH = 'home/data.txt'
. Output only the next line. | result_flag = False |
Based on the snippet: <|code_start|>
# self.connect()
def connect(self, raise_errors=True):
# try:
# self.imap = imaplib.IMAP4_SSL(self.GMAIL_IMAP_HOST, self.GMAIL_IMAP_PORT)
# except socket.error:
# if raise_errors:
# raise Exception('Connection failure.')
# self.imap = None
self.imap = imaplib.IMAP4_SSL(self.GMAIL_IMAP_HOST, self.GMAIL_IMAP_PORT)
# self.smtp = smtplib.SMTP(self.server,self.port)
# self.smtp.set_debuglevel(self.debug)
# self.smtp.ehlo()
# self.smtp.starttls()
# self.smtp.ehlo()
return self.imap
def fetch_mailboxes(self):
response, mailbox_list = self.imap.list()
if response == 'OK':
for mailbox in mailbox_list:
mailbox_name = mailbox.split('"/"')[-1].replace('"', '').strip()
mailbox = Mailbox(self)
<|code_end|>
, predict the immediate next line with the help of imports:
import re
import imaplib
from .mailbox import Mailbox
from .utf import encode as encode_utf7, decode as decode_utf7
from .exceptions import *
and context (classes, functions, sometimes code) from other files:
# Path: utils/gmail/mailbox.py
# class Mailbox():
#
# def __init__(self, gmail, name="INBOX"):
# self.name = name
# self.gmail = gmail
# self.date_format = "%d-%b-%Y"
# self.messages = {}
#
# @property
# def external_name(self):
# if "external_name" not in vars(self):
# vars(self)["external_name"] = encode_utf7(self.name)
# return vars(self)["external_name"]
#
# @external_name.setter
# def external_name(self, value):
# if "external_name" in vars(self):
# del vars(self)["external_name"]
# self.name = decode_utf7(value)
#
# def mail(self, prefetch=False, **kwargs):
# search = ['ALL']
#
# kwargs.get('read') and search.append('SEEN')
# kwargs.get('unread') and search.append('UNSEEN')
#
# kwargs.get('starred') and search.append('FLAGGED')
# kwargs.get('unstarred') and search.append('UNFLAGGED')
#
# kwargs.get('deleted') and search.append('DELETED')
# kwargs.get('undeleted') and search.append('UNDELETED')
#
# kwargs.get('draft') and search.append('DRAFT')
# kwargs.get('undraft') and search.append('UNDRAFT')
#
# kwargs.get('before') and search.extend(['BEFORE', kwargs.get('before').strftime(self.date_format)])
# kwargs.get('after') and search.extend(['SINCE', kwargs.get('after').strftime(self.date_format)])
# kwargs.get('on') and search.extend(['ON', kwargs.get('on').strftime(self.date_format)])
#
# kwargs.get('header') and search.extend(['HEADER', kwargs.get('header')[0], kwargs.get('header')[1]])
#
# kwargs.get('sender') and search.extend(['FROM', kwargs.get('sender')])
# kwargs.get('fr') and search.extend(['FROM', kwargs.get('fr')])
# kwargs.get('to') and search.extend(['TO', kwargs.get('to')])
# kwargs.get('cc') and search.extend(['CC', kwargs.get('cc')])
#
# kwargs.get('subject') and search.extend(['SUBJECT', kwargs.get('subject')])
# kwargs.get('body') and search.extend(['BODY', kwargs.get('body')])
#
# kwargs.get('label') and search.extend(['X-GM-LABELS', kwargs.get('label')])
# kwargs.get('attachment') and search.extend(['HAS', 'attachment'])
#
# kwargs.get('query') and search.extend([kwargs.get('query')])
#
# emails = []
# # print search
# response, data = self.gmail.imap.uid('SEARCH', *search)
# if response == 'OK':
# uids = filter(None, data[0].split(' ')) # filter out empty strings
#
# for uid in uids:
# if not self.messages.get(uid):
# self.messages[uid] = Message(self, uid)
# emails.append(self.messages[uid])
#
# if prefetch and emails:
# messages_dict = {}
# for email in emails:
# messages_dict[email.uid] = email
# self.messages.update(self.gmail.fetch_multiple_messages(messages_dict))
#
# return emails
#
# # WORK IN PROGRESS. NOT FOR ACTUAL USE
# def threads(self, prefetch=False, **kwargs):
# emails = []
# response, data = self.gmail.imap.uid('SEARCH', 'ALL')
# if response == 'OK':
# uids = data[0].split(' ')
#
#
# for uid in uids:
# if not self.messages.get(uid):
# self.messages[uid] = Message(self, uid)
# emails.append(self.messages[uid])
#
# if prefetch:
# fetch_str = ','.join(uids)
# response, results = self.gmail.imap.uid('FETCH', fetch_str, '(BODY.PEEK[] FLAGS X-GM-THRID X-GM-MSGID X-GM-LABELS)')
# for index in xrange(len(results) - 1):
# raw_message = results[index]
# if re.search(r'UID (\d+)', raw_message[0]):
# uid = re.search(r'UID (\d+)', raw_message[0]).groups(1)[0]
# self.messages[uid].parse(raw_message)
#
# return emails
#
# def count(self, **kwargs):
# return len(self.mail(**kwargs))
#
# def cached_messages(self):
# return self.messages
. Output only the next line. | mailbox.external_name = mailbox_name |
Given the code snippet: <|code_start|>sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
#get details from conf file for POM
src_pom_files_list = conf.src_pom_files_list
dst_folder_pom = conf.dst_folder_pom
#check if POM folder exists and then copy files
if os.path.exists(dst_folder_pom):
for every_src_pom_file in src_pom_files_list:
<|code_end|>
, generate the next line using the imports in this file:
import os,sys
import shutil
from conf import test_path_conf as conf
and context (functions, classes, or occasionally code) from other files:
# Path: conf/test_path_conf.py
. Output only the next line. | shutil.copy2(every_src_pom_file,dst_folder_pom) |
Given snippet: <|code_start|> if response == "Remote Flag status":
remote_flag = get_remote_flag_status()
if response == "Testrail Flag status":
testrail_flag = get_testrailflag_status()
if response == "Tesults Flag status":
tesults_flag = get_tesultsflag_status()
if response == "App Name":
app_name = questionary.text("Enter App Name").ask()
if response == "App Path":
app_path = questionary.path("Enter the path to your app").ask()
if response == "Revert back to default options":
mobile_os_name, mobile_os_version, device_name, app_package, app_activity, remote_flag, device_flag, testrail_flag,tesults_flag, app_name, app_path = mobile_default_options()
if response == "Run":
if app_path is None:
questionary.print("Please enter the app path before you run the test",
style="bold fg:darkred")
else:
break
if response == "Exit":
sys.exit("Program interrupted by user, Exiting the program....")
return (mobile_os_name, mobile_os_version, device_name, app_package,
app_activity, remote_flag, device_flag, testrail_flag, tesults_flag,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import questionary
from clear_screen import clear
from conf import api_example_conf
from conf import browser_os_name_conf as conf
from conf import remote_credentials
and context:
# Path: conf/api_example_conf.py
#
# Path: conf/browser_os_name_conf.py
# def generate_configuration(browsers=browsers,firefox_versions=firefox_versions,chrome_versions=chrome_versions,safari_versions=safari_versions,
# os_list=os_list,windows_versions=windows_versions,os_x_versions=os_x_versions):
#
# Path: conf/remote_credentials.py
# REMOTE_BROWSER_PLATFORM = "BS"
# USERNAME = "Enter your username"
# ACCESS_KEY = "Enter your access key"
which might include code, classes, or functions. Output only the next line. | app_name,app_path) |
Here is a snippet: <|code_start|> "Other Devices"]).ask()
if device_name == "Other Devices":
device_name = questionary.text("Enter the device name").ask()
elif mobile_os_version == "8.1":
device_name = questionary.select("Select the device name",
choices=["Samsung Galaxy Note 9",
"Other Devices"]).ask()
if device_name == "Other Devices":
device_name = questionary.text("Enter the device name").ask()
elif mobile_os_version == "7.1":
device_name = questionary.select("Select the device name",
choices=["Samsung Galaxy Note 8",
"Google Pixel","Other Devices"]).ask()
if device_name == "Other Devices":
device_name = questionary.text("Enter the device name").ask()
elif mobile_os_version == "7.0":
device_name=questionary.select("Select the device name",
choices=["Samsung Galaxy S8",
"Google Nexus 6P", "Other Devices"]).ask()
if device_name == "Other Devices":
device_name = questionary.text("Enter the device name").ask()
elif mobile_os_version == "6.0":
device_name = questionary.select("Select the device name",
choices=["Samsung Galaxy S7",
"Google Nexus 6","Other Devices"]).ask()
if device_name == "Other Devices":
<|code_end|>
. Write the next line using the current file imports:
import sys
import questionary
from clear_screen import clear
from conf import api_example_conf
from conf import browser_os_name_conf as conf
from conf import remote_credentials
and context from other files:
# Path: conf/api_example_conf.py
#
# Path: conf/browser_os_name_conf.py
# def generate_configuration(browsers=browsers,firefox_versions=firefox_versions,chrome_versions=chrome_versions,safari_versions=safari_versions,
# os_list=os_list,windows_versions=windows_versions,os_x_versions=os_x_versions):
#
# Path: conf/remote_credentials.py
# REMOTE_BROWSER_PLATFORM = "BS"
# USERNAME = "Enter your username"
# ACCESS_KEY = "Enter your access key"
, which may include functions, classes, or code. Output only the next line. | device_name = questionary.text("Enter the device name").ask() |
Using the snippet: <|code_start|> choices=["Yes","No"]).ask()
if tesults_flag == "Yes":
tesults_flag = "Y"
else:
tesults_flag = "N"
return tesults_flag
def set_remote_credentials():
"set remote credentials file to run the test on browserstack or saucelabs"
platform = questionary.select("Select the remote platform on which you wish to run the test on",
choices=["Browserstack","Saucelabs"]).ask()
if platform == "Browserstack":
platform = "BS"
else:
platform = "SL"
username = questionary.text("Enter the Username").ask()
password = questionary.password("Enter the password").ask()
with open("conf/remote_credentials.py",'w') as cred_file:
cred_file.write("REMOTE_BROWSER_PLATFORM = '%s'\
\nUSERNAME = '%s'\
\nACCESS_KEY = '%s'"%(platform,username,password))
questionary.print("Updated the credentials successfully",
style="bold fg:green")
def get_remote_flag_status():
"Get the remote flag status"
remote_flag = questionary.select("Select the remote flag status",
choices=["Yes","No"]).ask()
<|code_end|>
, determine the next line of code. You have imports:
import sys
import questionary
from clear_screen import clear
from conf import api_example_conf
from conf import browser_os_name_conf as conf
from conf import remote_credentials
and context (class names, function names, or code) available:
# Path: conf/api_example_conf.py
#
# Path: conf/browser_os_name_conf.py
# def generate_configuration(browsers=browsers,firefox_versions=firefox_versions,chrome_versions=chrome_versions,safari_versions=safari_versions,
# os_list=os_list,windows_versions=windows_versions,os_x_versions=os_x_versions):
#
# Path: conf/remote_credentials.py
# REMOTE_BROWSER_PLATFORM = "BS"
# USERNAME = "Enter your username"
# ACCESS_KEY = "Enter your access key"
. Output only the next line. | if remote_flag == "Yes": |
Predict the next line after this snippet: <|code_start|>
class GitStashWindowCmd(GitCmd, GitStashHelper, GitErrorHelper):
def pop_or_apply_from_panel(self, action):
repo = self.get_repo()
if not repo:
return
stashes = self.get_stashes(repo)
if not stashes:
return sublime.error_message('No stashes. Use the Git: Stash command to stash changes')
callback = self.pop_or_apply_callback(repo, action, stashes)
panel = []
for name, title in stashes:
panel.append([title, "stash@{%s}" % name])
self.window.show_quick_panel(panel, callback)
def pop_or_apply_callback(self, repo, action, stashes):
def inner(choice):
if choice != -1:
name, _ = stashes[choice]
exit_code, stdout, stderr = self.git(['stash', action, '-q', 'stash@{%s}' % name], cwd=repo)
if exit_code != 0:
sublime.error_message(self.format_error_message(stderr))
<|code_end|>
using the current file's imports:
import time
import sublime
from sublime_plugin import WindowCommand
from .util import noop
from .cmd import GitCmd
from .helpers import GitStashHelper, GitStatusHelper, GitErrorHelper
and any relevant context from other files:
# Path: sgit/util.py
# def noop(*args, **kwargs):
# pass
#
# Path: sgit/cmd.py
# class GitCmd(GitRepoHelper, Cmd):
# executable = 'git'
# bin = ['git']
# opts = [
# '--no-pager',
# '-c', 'color.diff=false',
# '-c', 'color.status=false',
# '-c', 'color.branch=false',
# '-c', 'status.displayCommentPrefix=true',
# '-c', 'core.commentchar=#',
# ]
#
# def git(self, cmd, *args, **kwargs):
# return self.cmd(cmd, *args, **kwargs)
#
# def git_string(self, cmd, *args, **kwargs):
# return self._string(cmd, *args, **kwargs)
#
# def git_lines(self, cmd, *args, **kwargs):
# return self._lines(cmd, *args, **kwargs)
#
# def git_exit_code(self, cmd, *args, **kwargs):
# return self._exit_code(cmd, *args, **kwargs)
#
# def git_async(self, cmd, *args, **kwargs):
# return self.cmd_async(cmd, *args, **kwargs)
#
# Path: sgit/helpers.py
# class GitStashHelper(object):
#
# STASH_RE = re.compile(r'^stash@\{(.*)\}:\s*(.*)')
#
# def get_stashes(self, repo):
# stashes = []
# output = self.git_lines(['stash', 'list'], cwd=repo)
# for line in output:
# match = self.STASH_RE.match(line)
# if match:
# stashes.append((match.group(1), match.group(2)))
# return stashes
#
# class GitStatusHelper(object):
#
# def file_in_git(self, repo, filename):
# return self.git_exit_code(['ls-files', filename, '--error-unmatch'], cwd=repo) == 0
#
# def has_changes(self, repo):
# return self.has_staged_changes(repo) or self.has_unstaged_changes(repo)
#
# def has_staged_changes(self, repo):
# return self.git_exit_code(['diff', '--exit-code', '--quiet', '--cached'], cwd=repo) != 0
#
# def has_unstaged_changes(self, repo):
# return self.git_exit_code(['diff', '--exit-code', '--quiet'], cwd=repo) != 0
#
# # def get_porcelain_status(self, repo):
# # mode = self.get_untracked_mode()
# # cmd = ['status', '--porcelain', ('--untracked-files=%s' % mode) if mode else None]
# # return self.git_lines(cmd, cwd=repo)
#
# def get_porcelain_status(self, repo):
# mode = self.get_untracked_mode()
# cmd = ['status', '-z', ('--untracked-files=%s' % mode) if mode else None]
#
# output = self.git_string(cmd, cwd=repo, strip=False)
# rows = output.split('\x00')
# lines = []
# idx = 0
# while idx < len(rows):
# row = rows[idx]
# if row and not row.startswith('#'):
# status, filename = row[:2], row[3:]
# if status[0] == 'R':
# lines.append("%s %s -> %s" % (status, rows[idx + 1], filename))
# idx += 1
# else:
# lines.append("%s %s" % (status, filename))
# idx += 1
# return lines
#
# def get_files_status(self, repo):
# untracked, unstaged, staged = [], [], []
# status = self.get_porcelain_status(repo)
# for l in status:
# state, filename = l[:2], l[3:]
# index, worktree = state
# if state in ('DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU'):
# logger.warning("unmerged WTF: %s, %s", state, filename)
# elif state == '??':
# untracked.append(('?', filename))
# elif state == '!!':
# continue
# else:
# if worktree != ' ':
# unstaged.append((worktree, filename))
# if index != ' ':
# staged.append((index, filename))
# return untracked, unstaged, staged
#
# def get_untracked_mode(self):
# # get untracked files mode
# setting = get_setting('git_status_untracked_files', 'all')
#
# mode = 'all'
# if setting == 'none':
# mode = 'no'
# elif setting == 'auto':
# mode = None
# return mode
#
# class GitErrorHelper(object):
#
# def format_error_message(self, msg):
# if msg.startswith('error: '):
# msg = msg[7:]
# elif msg.lower().startswith('Note: '):
# msg = msg[6:]
# if msg.endswith('Aborting\n'):
# msg = msg.rstrip()[:-8]
# return msg
. Output only the next line. | window = sublime.active_window() |
Predict the next line after this snippet: <|code_start|># coding: utf-8
class GitStashWindowCmd(GitCmd, GitStashHelper, GitErrorHelper):
def pop_or_apply_from_panel(self, action):
repo = self.get_repo()
<|code_end|>
using the current file's imports:
import time
import sublime
from sublime_plugin import WindowCommand
from .util import noop
from .cmd import GitCmd
from .helpers import GitStashHelper, GitStatusHelper, GitErrorHelper
and any relevant context from other files:
# Path: sgit/util.py
# def noop(*args, **kwargs):
# pass
#
# Path: sgit/cmd.py
# class GitCmd(GitRepoHelper, Cmd):
# executable = 'git'
# bin = ['git']
# opts = [
# '--no-pager',
# '-c', 'color.diff=false',
# '-c', 'color.status=false',
# '-c', 'color.branch=false',
# '-c', 'status.displayCommentPrefix=true',
# '-c', 'core.commentchar=#',
# ]
#
# def git(self, cmd, *args, **kwargs):
# return self.cmd(cmd, *args, **kwargs)
#
# def git_string(self, cmd, *args, **kwargs):
# return self._string(cmd, *args, **kwargs)
#
# def git_lines(self, cmd, *args, **kwargs):
# return self._lines(cmd, *args, **kwargs)
#
# def git_exit_code(self, cmd, *args, **kwargs):
# return self._exit_code(cmd, *args, **kwargs)
#
# def git_async(self, cmd, *args, **kwargs):
# return self.cmd_async(cmd, *args, **kwargs)
#
# Path: sgit/helpers.py
# class GitStashHelper(object):
#
# STASH_RE = re.compile(r'^stash@\{(.*)\}:\s*(.*)')
#
# def get_stashes(self, repo):
# stashes = []
# output = self.git_lines(['stash', 'list'], cwd=repo)
# for line in output:
# match = self.STASH_RE.match(line)
# if match:
# stashes.append((match.group(1), match.group(2)))
# return stashes
#
# class GitStatusHelper(object):
#
# def file_in_git(self, repo, filename):
# return self.git_exit_code(['ls-files', filename, '--error-unmatch'], cwd=repo) == 0
#
# def has_changes(self, repo):
# return self.has_staged_changes(repo) or self.has_unstaged_changes(repo)
#
# def has_staged_changes(self, repo):
# return self.git_exit_code(['diff', '--exit-code', '--quiet', '--cached'], cwd=repo) != 0
#
# def has_unstaged_changes(self, repo):
# return self.git_exit_code(['diff', '--exit-code', '--quiet'], cwd=repo) != 0
#
# # def get_porcelain_status(self, repo):
# # mode = self.get_untracked_mode()
# # cmd = ['status', '--porcelain', ('--untracked-files=%s' % mode) if mode else None]
# # return self.git_lines(cmd, cwd=repo)
#
# def get_porcelain_status(self, repo):
# mode = self.get_untracked_mode()
# cmd = ['status', '-z', ('--untracked-files=%s' % mode) if mode else None]
#
# output = self.git_string(cmd, cwd=repo, strip=False)
# rows = output.split('\x00')
# lines = []
# idx = 0
# while idx < len(rows):
# row = rows[idx]
# if row and not row.startswith('#'):
# status, filename = row[:2], row[3:]
# if status[0] == 'R':
# lines.append("%s %s -> %s" % (status, rows[idx + 1], filename))
# idx += 1
# else:
# lines.append("%s %s" % (status, filename))
# idx += 1
# return lines
#
# def get_files_status(self, repo):
# untracked, unstaged, staged = [], [], []
# status = self.get_porcelain_status(repo)
# for l in status:
# state, filename = l[:2], l[3:]
# index, worktree = state
# if state in ('DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU'):
# logger.warning("unmerged WTF: %s, %s", state, filename)
# elif state == '??':
# untracked.append(('?', filename))
# elif state == '!!':
# continue
# else:
# if worktree != ' ':
# unstaged.append((worktree, filename))
# if index != ' ':
# staged.append((index, filename))
# return untracked, unstaged, staged
#
# def get_untracked_mode(self):
# # get untracked files mode
# setting = get_setting('git_status_untracked_files', 'all')
#
# mode = 'all'
# if setting == 'none':
# mode = 'no'
# elif setting == 'auto':
# mode = None
# return mode
#
# class GitErrorHelper(object):
#
# def format_error_message(self, msg):
# if msg.startswith('error: '):
# msg = msg[7:]
# elif msg.lower().startswith('Note: '):
# msg = msg[6:]
# if msg.endswith('Aborting\n'):
# msg = msg.rstrip()[:-8]
# return msg
. Output only the next line. | if not repo: |
Next line prediction: <|code_start|># coding: utf-8
class GitStashWindowCmd(GitCmd, GitStashHelper, GitErrorHelper):
def pop_or_apply_from_panel(self, action):
repo = self.get_repo()
<|code_end|>
. Use current file imports:
(import time
import sublime
from sublime_plugin import WindowCommand
from .util import noop
from .cmd import GitCmd
from .helpers import GitStashHelper, GitStatusHelper, GitErrorHelper)
and context including class names, function names, or small code snippets from other files:
# Path: sgit/util.py
# def noop(*args, **kwargs):
# pass
#
# Path: sgit/cmd.py
# class GitCmd(GitRepoHelper, Cmd):
# executable = 'git'
# bin = ['git']
# opts = [
# '--no-pager',
# '-c', 'color.diff=false',
# '-c', 'color.status=false',
# '-c', 'color.branch=false',
# '-c', 'status.displayCommentPrefix=true',
# '-c', 'core.commentchar=#',
# ]
#
# def git(self, cmd, *args, **kwargs):
# return self.cmd(cmd, *args, **kwargs)
#
# def git_string(self, cmd, *args, **kwargs):
# return self._string(cmd, *args, **kwargs)
#
# def git_lines(self, cmd, *args, **kwargs):
# return self._lines(cmd, *args, **kwargs)
#
# def git_exit_code(self, cmd, *args, **kwargs):
# return self._exit_code(cmd, *args, **kwargs)
#
# def git_async(self, cmd, *args, **kwargs):
# return self.cmd_async(cmd, *args, **kwargs)
#
# Path: sgit/helpers.py
# class GitStashHelper(object):
#
# STASH_RE = re.compile(r'^stash@\{(.*)\}:\s*(.*)')
#
# def get_stashes(self, repo):
# stashes = []
# output = self.git_lines(['stash', 'list'], cwd=repo)
# for line in output:
# match = self.STASH_RE.match(line)
# if match:
# stashes.append((match.group(1), match.group(2)))
# return stashes
#
# class GitStatusHelper(object):
#
# def file_in_git(self, repo, filename):
# return self.git_exit_code(['ls-files', filename, '--error-unmatch'], cwd=repo) == 0
#
# def has_changes(self, repo):
# return self.has_staged_changes(repo) or self.has_unstaged_changes(repo)
#
# def has_staged_changes(self, repo):
# return self.git_exit_code(['diff', '--exit-code', '--quiet', '--cached'], cwd=repo) != 0
#
# def has_unstaged_changes(self, repo):
# return self.git_exit_code(['diff', '--exit-code', '--quiet'], cwd=repo) != 0
#
# # def get_porcelain_status(self, repo):
# # mode = self.get_untracked_mode()
# # cmd = ['status', '--porcelain', ('--untracked-files=%s' % mode) if mode else None]
# # return self.git_lines(cmd, cwd=repo)
#
# def get_porcelain_status(self, repo):
# mode = self.get_untracked_mode()
# cmd = ['status', '-z', ('--untracked-files=%s' % mode) if mode else None]
#
# output = self.git_string(cmd, cwd=repo, strip=False)
# rows = output.split('\x00')
# lines = []
# idx = 0
# while idx < len(rows):
# row = rows[idx]
# if row and not row.startswith('#'):
# status, filename = row[:2], row[3:]
# if status[0] == 'R':
# lines.append("%s %s -> %s" % (status, rows[idx + 1], filename))
# idx += 1
# else:
# lines.append("%s %s" % (status, filename))
# idx += 1
# return lines
#
# def get_files_status(self, repo):
# untracked, unstaged, staged = [], [], []
# status = self.get_porcelain_status(repo)
# for l in status:
# state, filename = l[:2], l[3:]
# index, worktree = state
# if state in ('DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU'):
# logger.warning("unmerged WTF: %s, %s", state, filename)
# elif state == '??':
# untracked.append(('?', filename))
# elif state == '!!':
# continue
# else:
# if worktree != ' ':
# unstaged.append((worktree, filename))
# if index != ' ':
# staged.append((index, filename))
# return untracked, unstaged, staged
#
# def get_untracked_mode(self):
# # get untracked files mode
# setting = get_setting('git_status_untracked_files', 'all')
#
# mode = 'all'
# if setting == 'none':
# mode = 'no'
# elif setting == 'auto':
# mode = None
# return mode
#
# class GitErrorHelper(object):
#
# def format_error_message(self, msg):
# if msg.startswith('error: '):
# msg = msg[7:]
# elif msg.lower().startswith('Note: '):
# msg = msg[6:]
# if msg.endswith('Aborting\n'):
# msg = msg.rstrip()[:-8]
# return msg
. Output only the next line. | if not repo: |
Next line prediction: <|code_start|># coding: utf-8
class GitStashWindowCmd(GitCmd, GitStashHelper, GitErrorHelper):
def pop_or_apply_from_panel(self, action):
repo = self.get_repo()
if not repo:
return
<|code_end|>
. Use current file imports:
(import time
import sublime
from sublime_plugin import WindowCommand
from .util import noop
from .cmd import GitCmd
from .helpers import GitStashHelper, GitStatusHelper, GitErrorHelper)
and context including class names, function names, or small code snippets from other files:
# Path: sgit/util.py
# def noop(*args, **kwargs):
# pass
#
# Path: sgit/cmd.py
# class GitCmd(GitRepoHelper, Cmd):
# executable = 'git'
# bin = ['git']
# opts = [
# '--no-pager',
# '-c', 'color.diff=false',
# '-c', 'color.status=false',
# '-c', 'color.branch=false',
# '-c', 'status.displayCommentPrefix=true',
# '-c', 'core.commentchar=#',
# ]
#
# def git(self, cmd, *args, **kwargs):
# return self.cmd(cmd, *args, **kwargs)
#
# def git_string(self, cmd, *args, **kwargs):
# return self._string(cmd, *args, **kwargs)
#
# def git_lines(self, cmd, *args, **kwargs):
# return self._lines(cmd, *args, **kwargs)
#
# def git_exit_code(self, cmd, *args, **kwargs):
# return self._exit_code(cmd, *args, **kwargs)
#
# def git_async(self, cmd, *args, **kwargs):
# return self.cmd_async(cmd, *args, **kwargs)
#
# Path: sgit/helpers.py
# class GitStashHelper(object):
#
# STASH_RE = re.compile(r'^stash@\{(.*)\}:\s*(.*)')
#
# def get_stashes(self, repo):
# stashes = []
# output = self.git_lines(['stash', 'list'], cwd=repo)
# for line in output:
# match = self.STASH_RE.match(line)
# if match:
# stashes.append((match.group(1), match.group(2)))
# return stashes
#
# class GitStatusHelper(object):
#
# def file_in_git(self, repo, filename):
# return self.git_exit_code(['ls-files', filename, '--error-unmatch'], cwd=repo) == 0
#
# def has_changes(self, repo):
# return self.has_staged_changes(repo) or self.has_unstaged_changes(repo)
#
# def has_staged_changes(self, repo):
# return self.git_exit_code(['diff', '--exit-code', '--quiet', '--cached'], cwd=repo) != 0
#
# def has_unstaged_changes(self, repo):
# return self.git_exit_code(['diff', '--exit-code', '--quiet'], cwd=repo) != 0
#
# # def get_porcelain_status(self, repo):
# # mode = self.get_untracked_mode()
# # cmd = ['status', '--porcelain', ('--untracked-files=%s' % mode) if mode else None]
# # return self.git_lines(cmd, cwd=repo)
#
# def get_porcelain_status(self, repo):
# mode = self.get_untracked_mode()
# cmd = ['status', '-z', ('--untracked-files=%s' % mode) if mode else None]
#
# output = self.git_string(cmd, cwd=repo, strip=False)
# rows = output.split('\x00')
# lines = []
# idx = 0
# while idx < len(rows):
# row = rows[idx]
# if row and not row.startswith('#'):
# status, filename = row[:2], row[3:]
# if status[0] == 'R':
# lines.append("%s %s -> %s" % (status, rows[idx + 1], filename))
# idx += 1
# else:
# lines.append("%s %s" % (status, filename))
# idx += 1
# return lines
#
# def get_files_status(self, repo):
# untracked, unstaged, staged = [], [], []
# status = self.get_porcelain_status(repo)
# for l in status:
# state, filename = l[:2], l[3:]
# index, worktree = state
# if state in ('DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU'):
# logger.warning("unmerged WTF: %s, %s", state, filename)
# elif state == '??':
# untracked.append(('?', filename))
# elif state == '!!':
# continue
# else:
# if worktree != ' ':
# unstaged.append((worktree, filename))
# if index != ' ':
# staged.append((index, filename))
# return untracked, unstaged, staged
#
# def get_untracked_mode(self):
# # get untracked files mode
# setting = get_setting('git_status_untracked_files', 'all')
#
# mode = 'all'
# if setting == 'none':
# mode = 'no'
# elif setting == 'auto':
# mode = None
# return mode
#
# class GitErrorHelper(object):
#
# def format_error_message(self, msg):
# if msg.startswith('error: '):
# msg = msg[7:]
# elif msg.lower().startswith('Note: '):
# msg = msg[6:]
# if msg.endswith('Aborting\n'):
# msg = msg.rstrip()[:-8]
# return msg
. Output only the next line. | stashes = self.get_stashes(repo) |
Predict the next line after this snippet: <|code_start|>
enabled = True
__all__ = ['LegitSwitchCommand', 'LegitSyncCommand', 'LegitPublishCommand', 'LegitUnpublishCommand',
'LegitHarvestCommand', 'LegitSproutCommand', 'LegitGraftCommand', 'LegitBranchesCommand']
class LegitWindowCmd(LegitCmd):
def is_visible(self):
return enabled
def is_enabled(self):
return enabled
def get_branch_choices(self, repo, filter=('published', 'unpublished')):
lines = self.legit_lines(['branches'], cwd=repo)
branches, choices = [], []
for l in lines:
if not l:
continue
current = l[0:2]
name, pub = l[2:].split(None, 1)
pub = pub.strip(' \t()')
if not pub in filter:
continue
<|code_end|>
using the current file's imports:
from functools import partial
from sublime_plugin import WindowCommand
from ..util import noop, StatusSpinner
from ..cmd import LegitCmd
import sublime
and any relevant context from other files:
# Path: sgit/util.py
# def noop(*args, **kwargs):
# pass
#
# class StatusSpinner(object):
#
# SIZE = 10 # 10 equal signs
# TIME = 50 # 50 ms delay
#
# def __init__(self, thread, msg):
# self.counter = 0
# self.direction = 1
# self.msg = msg
# self.thread = thread
#
# def progress(self):
# if not self.thread.is_alive():
# sublime.status_message('')
# return
#
# left, right = self.counter, (self.SIZE - 1 - self.counter)
# self.counter += self.direction
# if self.counter in (0, self.SIZE - 1):
# self.direction *= -1
#
# status = "[%s=%s] %s" % (' ' * left, ' ' * right, self.msg)
#
# sublime.status_message(status)
# sublime.set_timeout(self.progress, self.TIME)
#
# def start(self):
# self.thread.start()
# sublime.set_timeout(self.progress, 0)
#
# Path: sgit/cmd.py
# class LegitCmd(GitRepoHelper, Cmd):
# executable = 'legit'
# bin = ['legit']
#
# def legit(self, cmd, *args, **kwargs):
# return self.cmd(cmd, *args, **kwargs)
#
# def legit_string(self, cmd, *args, **kwargs):
# return self._string(cmd, *args, **kwargs)
#
# def legit_lines(self, cmd, *args, **kwargs):
# return self._lines(cmd, *args, **kwargs)
#
# def legit_exit_code(self, cmd, *args, **kwargs):
# return self._exit_code(cmd, *args, **kwargs)
#
# def legit_async(self, cmd, *args, **kwargs):
# return self.cmd_async(cmd, *args, **kwargs)
. Output only the next line. | choices.append(['%s%s' % (current, name.strip()), ' %s' % pub]) |
Here is a snippet: <|code_start|>
def is_visible(self):
return enabled
def is_enabled(self):
return enabled
def get_branch_choices(self, repo, filter=('published', 'unpublished')):
lines = self.legit_lines(['branches'], cwd=repo)
branches, choices = [], []
for l in lines:
if not l:
continue
current = l[0:2]
name, pub = l[2:].split(None, 1)
pub = pub.strip(' \t()')
if not pub in filter:
continue
choices.append(['%s%s' % (current, name.strip()), ' %s' % pub])
branches.append(name)
return branches, choices
def show_branches_panel(self, repo, on_selection, *args, **kwargs):
branches, choices = self.get_branch_choices(repo, *args, **kwargs)
def on_done(idx):
if idx != -1:
branch = branches[idx]
on_selection(branch)
<|code_end|>
. Write the next line using the current file imports:
from functools import partial
from sublime_plugin import WindowCommand
from ..util import noop, StatusSpinner
from ..cmd import LegitCmd
import sublime
and context from other files:
# Path: sgit/util.py
# def noop(*args, **kwargs):
# pass
#
# class StatusSpinner(object):
#
# SIZE = 10 # 10 equal signs
# TIME = 50 # 50 ms delay
#
# def __init__(self, thread, msg):
# self.counter = 0
# self.direction = 1
# self.msg = msg
# self.thread = thread
#
# def progress(self):
# if not self.thread.is_alive():
# sublime.status_message('')
# return
#
# left, right = self.counter, (self.SIZE - 1 - self.counter)
# self.counter += self.direction
# if self.counter in (0, self.SIZE - 1):
# self.direction *= -1
#
# status = "[%s=%s] %s" % (' ' * left, ' ' * right, self.msg)
#
# sublime.status_message(status)
# sublime.set_timeout(self.progress, self.TIME)
#
# def start(self):
# self.thread.start()
# sublime.set_timeout(self.progress, 0)
#
# Path: sgit/cmd.py
# class LegitCmd(GitRepoHelper, Cmd):
# executable = 'legit'
# bin = ['legit']
#
# def legit(self, cmd, *args, **kwargs):
# return self.cmd(cmd, *args, **kwargs)
#
# def legit_string(self, cmd, *args, **kwargs):
# return self._string(cmd, *args, **kwargs)
#
# def legit_lines(self, cmd, *args, **kwargs):
# return self._lines(cmd, *args, **kwargs)
#
# def legit_exit_code(self, cmd, *args, **kwargs):
# return self._exit_code(cmd, *args, **kwargs)
#
# def legit_async(self, cmd, *args, **kwargs):
# return self.cmd_async(cmd, *args, **kwargs)
, which may include functions, classes, or code. Output only the next line. | self.window.show_quick_panel(choices, on_done, sublime.MONOSPACE_FONT) |
Continue the code snippet: <|code_start|> branches, choices = [], []
for l in lines:
if not l:
continue
current = l[0:2]
name, pub = l[2:].split(None, 1)
pub = pub.strip(' \t()')
if not pub in filter:
continue
choices.append(['%s%s' % (current, name.strip()), ' %s' % pub])
branches.append(name)
return branches, choices
def show_branches_panel(self, repo, on_selection, *args, **kwargs):
branches, choices = self.get_branch_choices(repo, *args, **kwargs)
def on_done(idx):
if idx != -1:
branch = branches[idx]
on_selection(branch)
self.window.show_quick_panel(choices, on_done, sublime.MONOSPACE_FONT)
def run_async_legit_with_panel(self, repo, cmd, progress, panel_name):
self.panel = self.window.get_output_panel(panel_name)
self.panel_name = panel_name
self.panel_shown = False
thread = self.legit_async(cmd, cwd=repo, on_data=self.on_data)
runner = StatusSpinner(thread, progress)
<|code_end|>
. Use current file imports:
from functools import partial
from sublime_plugin import WindowCommand
from ..util import noop, StatusSpinner
from ..cmd import LegitCmd
import sublime
and context (classes, functions, or code) from other files:
# Path: sgit/util.py
# def noop(*args, **kwargs):
# pass
#
# class StatusSpinner(object):
#
# SIZE = 10 # 10 equal signs
# TIME = 50 # 50 ms delay
#
# def __init__(self, thread, msg):
# self.counter = 0
# self.direction = 1
# self.msg = msg
# self.thread = thread
#
# def progress(self):
# if not self.thread.is_alive():
# sublime.status_message('')
# return
#
# left, right = self.counter, (self.SIZE - 1 - self.counter)
# self.counter += self.direction
# if self.counter in (0, self.SIZE - 1):
# self.direction *= -1
#
# status = "[%s=%s] %s" % (' ' * left, ' ' * right, self.msg)
#
# sublime.status_message(status)
# sublime.set_timeout(self.progress, self.TIME)
#
# def start(self):
# self.thread.start()
# sublime.set_timeout(self.progress, 0)
#
# Path: sgit/cmd.py
# class LegitCmd(GitRepoHelper, Cmd):
# executable = 'legit'
# bin = ['legit']
#
# def legit(self, cmd, *args, **kwargs):
# return self.cmd(cmd, *args, **kwargs)
#
# def legit_string(self, cmd, *args, **kwargs):
# return self._string(cmd, *args, **kwargs)
#
# def legit_lines(self, cmd, *args, **kwargs):
# return self._lines(cmd, *args, **kwargs)
#
# def legit_exit_code(self, cmd, *args, **kwargs):
# return self._exit_code(cmd, *args, **kwargs)
#
# def legit_async(self, cmd, *args, **kwargs):
# return self.cmd_async(cmd, *args, **kwargs)
. Output only the next line. | runner.start() |
Here is a snippet: <|code_start|># coding: utf-8
RE_DIFF_HEAD = re.compile(r'(---|\+\+\+){3} (a|b)/(dev/null)?')
GIT_DIFF_TITLE = '*git-diff*'
GIT_DIFF_TITLE_PREFIX = GIT_DIFF_TITLE + ': '
GIT_DIFF_CACHED_TITLE = '*git-diff-cached*'
GIT_DIFF_CACHED_TITLE_PREFIX = GIT_DIFF_CACHED_TITLE + ': '
GIT_DIFF_CLEAN = "Nothing to stage (no difference between working tree and index)"
GIT_DIFF_CLEAN_CACHED = "Nothing to unstage (no changes in index)"
<|code_end|>
. Write the next line using the current file imports:
import re
import sublime
from functools import partial
from sublime_plugin import WindowCommand, TextCommand, EventListener
from .util import find_view_by_settings, get_setting
from .cmd import GitCmd
from .helpers import GitDiffHelper, GitErrorHelper, GitStatusHelper
and context from other files:
# Path: sgit/util.py
# def find_view_by_settings(window, **kwargs):
# for view in window.views():
# s = view.settings()
# matches = [s.get(k) == v for k, v in list(kwargs.items())]
# if all(matches):
# return view
#
# def get_setting(key, default=None):
# return get_settings().get(key, default)
#
# Path: sgit/cmd.py
# class GitCmd(GitRepoHelper, Cmd):
# executable = 'git'
# bin = ['git']
# opts = [
# '--no-pager',
# '-c', 'color.diff=false',
# '-c', 'color.status=false',
# '-c', 'color.branch=false',
# '-c', 'status.displayCommentPrefix=true',
# '-c', 'core.commentchar=#',
# ]
#
# def git(self, cmd, *args, **kwargs):
# return self.cmd(cmd, *args, **kwargs)
#
# def git_string(self, cmd, *args, **kwargs):
# return self._string(cmd, *args, **kwargs)
#
# def git_lines(self, cmd, *args, **kwargs):
# return self._lines(cmd, *args, **kwargs)
#
# def git_exit_code(self, cmd, *args, **kwargs):
# return self._exit_code(cmd, *args, **kwargs)
#
# def git_async(self, cmd, *args, **kwargs):
# return self.cmd_async(cmd, *args, **kwargs)
#
# Path: sgit/helpers.py
# class GitDiffHelper(object):
#
# def get_diff(self, repo, path=None, cached=False, unified=None):
# try:
# unified = int(unified)
# except:
# unified = None
# args = ['diff',
# '--cached' if cached else None,
# '--unified=%s' % unified if unified else None]
# if path:
# args.extend(['--', path])
# return self.git_string(args, cwd=repo, strip=False)
#
# class GitErrorHelper(object):
#
# def format_error_message(self, msg):
# if msg.startswith('error: '):
# msg = msg[7:]
# elif msg.lower().startswith('Note: '):
# msg = msg[6:]
# if msg.endswith('Aborting\n'):
# msg = msg.rstrip()[:-8]
# return msg
#
# class GitStatusHelper(object):
#
# def file_in_git(self, repo, filename):
# return self.git_exit_code(['ls-files', filename, '--error-unmatch'], cwd=repo) == 0
#
# def has_changes(self, repo):
# return self.has_staged_changes(repo) or self.has_unstaged_changes(repo)
#
# def has_staged_changes(self, repo):
# return self.git_exit_code(['diff', '--exit-code', '--quiet', '--cached'], cwd=repo) != 0
#
# def has_unstaged_changes(self, repo):
# return self.git_exit_code(['diff', '--exit-code', '--quiet'], cwd=repo) != 0
#
# # def get_porcelain_status(self, repo):
# # mode = self.get_untracked_mode()
# # cmd = ['status', '--porcelain', ('--untracked-files=%s' % mode) if mode else None]
# # return self.git_lines(cmd, cwd=repo)
#
# def get_porcelain_status(self, repo):
# mode = self.get_untracked_mode()
# cmd = ['status', '-z', ('--untracked-files=%s' % mode) if mode else None]
#
# output = self.git_string(cmd, cwd=repo, strip=False)
# rows = output.split('\x00')
# lines = []
# idx = 0
# while idx < len(rows):
# row = rows[idx]
# if row and not row.startswith('#'):
# status, filename = row[:2], row[3:]
# if status[0] == 'R':
# lines.append("%s %s -> %s" % (status, rows[idx + 1], filename))
# idx += 1
# else:
# lines.append("%s %s" % (status, filename))
# idx += 1
# return lines
#
# def get_files_status(self, repo):
# untracked, unstaged, staged = [], [], []
# status = self.get_porcelain_status(repo)
# for l in status:
# state, filename = l[:2], l[3:]
# index, worktree = state
# if state in ('DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU'):
# logger.warning("unmerged WTF: %s, %s", state, filename)
# elif state == '??':
# untracked.append(('?', filename))
# elif state == '!!':
# continue
# else:
# if worktree != ' ':
# unstaged.append((worktree, filename))
# if index != ' ':
# staged.append((index, filename))
# return untracked, unstaged, staged
#
# def get_untracked_mode(self):
# # get untracked files mode
# setting = get_setting('git_status_untracked_files', 'all')
#
# mode = 'all'
# if setting == 'none':
# mode = 'no'
# elif setting == 'auto':
# mode = None
# return mode
, which may include functions, classes, or code. Output only the next line. | GIT_DIFF_VIEW_SYNTAX = 'Packages/SublimeGit/syntax/SublimeGit Diff.tmLanguage' |
Predict the next line for this snippet: <|code_start|># coding: utf-8
RE_DIFF_HEAD = re.compile(r'(---|\+\+\+){3} (a|b)/(dev/null)?')
GIT_DIFF_TITLE = '*git-diff*'
GIT_DIFF_TITLE_PREFIX = GIT_DIFF_TITLE + ': '
GIT_DIFF_CACHED_TITLE = '*git-diff-cached*'
GIT_DIFF_CACHED_TITLE_PREFIX = GIT_DIFF_CACHED_TITLE + ': '
<|code_end|>
with the help of current file imports:
import re
import sublime
from functools import partial
from sublime_plugin import WindowCommand, TextCommand, EventListener
from .util import find_view_by_settings, get_setting
from .cmd import GitCmd
from .helpers import GitDiffHelper, GitErrorHelper, GitStatusHelper
and context from other files:
# Path: sgit/util.py
# def find_view_by_settings(window, **kwargs):
# for view in window.views():
# s = view.settings()
# matches = [s.get(k) == v for k, v in list(kwargs.items())]
# if all(matches):
# return view
#
# def get_setting(key, default=None):
# return get_settings().get(key, default)
#
# Path: sgit/cmd.py
# class GitCmd(GitRepoHelper, Cmd):
# executable = 'git'
# bin = ['git']
# opts = [
# '--no-pager',
# '-c', 'color.diff=false',
# '-c', 'color.status=false',
# '-c', 'color.branch=false',
# '-c', 'status.displayCommentPrefix=true',
# '-c', 'core.commentchar=#',
# ]
#
# def git(self, cmd, *args, **kwargs):
# return self.cmd(cmd, *args, **kwargs)
#
# def git_string(self, cmd, *args, **kwargs):
# return self._string(cmd, *args, **kwargs)
#
# def git_lines(self, cmd, *args, **kwargs):
# return self._lines(cmd, *args, **kwargs)
#
# def git_exit_code(self, cmd, *args, **kwargs):
# return self._exit_code(cmd, *args, **kwargs)
#
# def git_async(self, cmd, *args, **kwargs):
# return self.cmd_async(cmd, *args, **kwargs)
#
# Path: sgit/helpers.py
# class GitDiffHelper(object):
#
# def get_diff(self, repo, path=None, cached=False, unified=None):
# try:
# unified = int(unified)
# except:
# unified = None
# args = ['diff',
# '--cached' if cached else None,
# '--unified=%s' % unified if unified else None]
# if path:
# args.extend(['--', path])
# return self.git_string(args, cwd=repo, strip=False)
#
# class GitErrorHelper(object):
#
# def format_error_message(self, msg):
# if msg.startswith('error: '):
# msg = msg[7:]
# elif msg.lower().startswith('Note: '):
# msg = msg[6:]
# if msg.endswith('Aborting\n'):
# msg = msg.rstrip()[:-8]
# return msg
#
# class GitStatusHelper(object):
#
# def file_in_git(self, repo, filename):
# return self.git_exit_code(['ls-files', filename, '--error-unmatch'], cwd=repo) == 0
#
# def has_changes(self, repo):
# return self.has_staged_changes(repo) or self.has_unstaged_changes(repo)
#
# def has_staged_changes(self, repo):
# return self.git_exit_code(['diff', '--exit-code', '--quiet', '--cached'], cwd=repo) != 0
#
# def has_unstaged_changes(self, repo):
# return self.git_exit_code(['diff', '--exit-code', '--quiet'], cwd=repo) != 0
#
# # def get_porcelain_status(self, repo):
# # mode = self.get_untracked_mode()
# # cmd = ['status', '--porcelain', ('--untracked-files=%s' % mode) if mode else None]
# # return self.git_lines(cmd, cwd=repo)
#
# def get_porcelain_status(self, repo):
# mode = self.get_untracked_mode()
# cmd = ['status', '-z', ('--untracked-files=%s' % mode) if mode else None]
#
# output = self.git_string(cmd, cwd=repo, strip=False)
# rows = output.split('\x00')
# lines = []
# idx = 0
# while idx < len(rows):
# row = rows[idx]
# if row and not row.startswith('#'):
# status, filename = row[:2], row[3:]
# if status[0] == 'R':
# lines.append("%s %s -> %s" % (status, rows[idx + 1], filename))
# idx += 1
# else:
# lines.append("%s %s" % (status, filename))
# idx += 1
# return lines
#
# def get_files_status(self, repo):
# untracked, unstaged, staged = [], [], []
# status = self.get_porcelain_status(repo)
# for l in status:
# state, filename = l[:2], l[3:]
# index, worktree = state
# if state in ('DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU'):
# logger.warning("unmerged WTF: %s, %s", state, filename)
# elif state == '??':
# untracked.append(('?', filename))
# elif state == '!!':
# continue
# else:
# if worktree != ' ':
# unstaged.append((worktree, filename))
# if index != ' ':
# staged.append((index, filename))
# return untracked, unstaged, staged
#
# def get_untracked_mode(self):
# # get untracked files mode
# setting = get_setting('git_status_untracked_files', 'all')
#
# mode = 'all'
# if setting == 'none':
# mode = 'no'
# elif setting == 'auto':
# mode = None
# return mode
, which may contain function names, class names, or code. Output only the next line. | GIT_DIFF_CLEAN = "Nothing to stage (no difference between working tree and index)" |
Given the code snippet: <|code_start|> return
self.kind = kind
self.base = base
self.window.show_input_panel('%s:' % self.kind.capitalize(), '', partial(self.on_select, repo), noop, noop)
def on_select(self, repo, selection):
selection = selection.strip()
if not selection:
return
if self.base:
self.window.show_input_panel('Base:', '', partial(self.on_complete, repo, selection), noop, noop)
else:
self.on_complete(repo, selection)
def on_complete(self, repo, selection, base=None):
cmd = [self.kind, 'start', selection]
if base and base.strip():
cmd.append(base.strip())
self.run_sync_gitflow_with_panel(repo, cmd, 'git-flow-%s-start' % self.kind)
self.window.run_command('git_status', {'refresh_only': True})
class GitFlowFinishCommand(GitFlowWindowCmd):
def finish(self, kind):
repo = self.get_repo()
if not repo:
<|code_end|>
, generate the next line using the imports in this file:
from functools import partial
from sublime_plugin import WindowCommand
from ..util import noop, StatusSpinner
from ..cmd import GitFlowCmd
import sublime
and context (functions, classes, or occasionally code) from other files:
# Path: sgit/util.py
# def noop(*args, **kwargs):
# pass
#
# class StatusSpinner(object):
#
# SIZE = 10 # 10 equal signs
# TIME = 50 # 50 ms delay
#
# def __init__(self, thread, msg):
# self.counter = 0
# self.direction = 1
# self.msg = msg
# self.thread = thread
#
# def progress(self):
# if not self.thread.is_alive():
# sublime.status_message('')
# return
#
# left, right = self.counter, (self.SIZE - 1 - self.counter)
# self.counter += self.direction
# if self.counter in (0, self.SIZE - 1):
# self.direction *= -1
#
# status = "[%s=%s] %s" % (' ' * left, ' ' * right, self.msg)
#
# sublime.status_message(status)
# sublime.set_timeout(self.progress, self.TIME)
#
# def start(self):
# self.thread.start()
# sublime.set_timeout(self.progress, 0)
#
# Path: sgit/cmd.py
# class GitFlowCmd(GitRepoHelper, Cmd):
# executable = 'git_flow'
# bin = ['git-flow']
#
# def git_flow(self, cmd, *args, **kwargs):
# return self.cmd(cmd, *args, **kwargs)
#
# def git_flow_string(self, cmd, *args, **kwargs):
# return self._string(cmd, *args, **kwargs)
#
# def git_flow_lines(self, cmd, *args, **kwargs):
# return self._lines(cmd, *args, **kwargs)
#
# def git_flow_exit_code(self, cmd, *args, **kwargs):
# return self._exit_code(cmd, *args, **kwargs)
#
# def git_flow_async(self, cmd, *args, **kwargs):
# return self.cmd_async(cmd, *args, **kwargs)
. Output only the next line. | return |
Continue the code snippet: <|code_start|> def on_select(self, repo, selection):
selection = selection.strip()
if not selection:
return
if self.base:
self.window.show_input_panel('Base:', '', partial(self.on_complete, repo, selection), noop, noop)
else:
self.on_complete(repo, selection)
def on_complete(self, repo, selection, base=None):
cmd = [self.kind, 'start', selection]
if base and base.strip():
cmd.append(base.strip())
self.run_sync_gitflow_with_panel(repo, cmd, 'git-flow-%s-start' % self.kind)
self.window.run_command('git_status', {'refresh_only': True})
class GitFlowFinishCommand(GitFlowWindowCmd):
def finish(self, kind):
repo = self.get_repo()
if not repo:
return
self.kind = kind
self.show_branches_panel(repo, partial(self.on_complete, repo), self.kind)
def on_complete(self, repo, selection):
<|code_end|>
. Use current file imports:
from functools import partial
from sublime_plugin import WindowCommand
from ..util import noop, StatusSpinner
from ..cmd import GitFlowCmd
import sublime
and context (classes, functions, or code) from other files:
# Path: sgit/util.py
# def noop(*args, **kwargs):
# pass
#
# class StatusSpinner(object):
#
# SIZE = 10 # 10 equal signs
# TIME = 50 # 50 ms delay
#
# def __init__(self, thread, msg):
# self.counter = 0
# self.direction = 1
# self.msg = msg
# self.thread = thread
#
# def progress(self):
# if not self.thread.is_alive():
# sublime.status_message('')
# return
#
# left, right = self.counter, (self.SIZE - 1 - self.counter)
# self.counter += self.direction
# if self.counter in (0, self.SIZE - 1):
# self.direction *= -1
#
# status = "[%s=%s] %s" % (' ' * left, ' ' * right, self.msg)
#
# sublime.status_message(status)
# sublime.set_timeout(self.progress, self.TIME)
#
# def start(self):
# self.thread.start()
# sublime.set_timeout(self.progress, 0)
#
# Path: sgit/cmd.py
# class GitFlowCmd(GitRepoHelper, Cmd):
# executable = 'git_flow'
# bin = ['git-flow']
#
# def git_flow(self, cmd, *args, **kwargs):
# return self.cmd(cmd, *args, **kwargs)
#
# def git_flow_string(self, cmd, *args, **kwargs):
# return self._string(cmd, *args, **kwargs)
#
# def git_flow_lines(self, cmd, *args, **kwargs):
# return self._lines(cmd, *args, **kwargs)
#
# def git_flow_exit_code(self, cmd, *args, **kwargs):
# return self._exit_code(cmd, *args, **kwargs)
#
# def git_flow_async(self, cmd, *args, **kwargs):
# return self.cmd_async(cmd, *args, **kwargs)
. Output only the next line. | progress = "Finishing %s: %s" % (self.kind, selection) |
Based on the snippet: <|code_start|> stderr = stderr.strip()
if stderr:
for line in stderr.splitlines():
stdout += "# %s\n" % line
old_msg = ''
if amend:
old_msg = self.git_lines(['rev-list', '--format=%B', '--max-count=1', 'HEAD'], cwd=repo)
old_msg = "%s\n" % "\n".join(old_msg[1:])
if self.is_verbose and CUT_LINE not in stdout:
comments = []
other = []
for line in stdout.splitlines():
if line.startswith('#'):
comments.append(line)
else:
other.append(line)
status = "\n".join(comments)
status += "\n# %s" % CUT_LINE
status += CUT_EXPLANATION
status += "\n".join(other)
else:
status = stdout
return GIT_COMMIT_TEMPLATE.format(status=status, old_msg=old_msg)
def show_commit_panel(self, content):
panel = self.window.get_output_panel('git-commit')
panel.run_command('git_panel_write', {'content': content})
<|code_end|>
, predict the immediate next line with the help of imports:
from functools import partial
from sublime_plugin import WindowCommand, TextCommand, EventListener
from .util import find_view_by_settings, noop, get_setting
from .cmd import GitCmd
from .helpers import GitStatusHelper
from .status import GIT_WORKING_DIR_CLEAN
import sublime
and context (classes, functions, sometimes code) from other files:
# Path: sgit/util.py
# def find_view_by_settings(window, **kwargs):
# for view in window.views():
# s = view.settings()
# matches = [s.get(k) == v for k, v in list(kwargs.items())]
# if all(matches):
# return view
#
# def noop(*args, **kwargs):
# pass
#
# def get_setting(key, default=None):
# return get_settings().get(key, default)
#
# Path: sgit/cmd.py
# class GitCmd(GitRepoHelper, Cmd):
# executable = 'git'
# bin = ['git']
# opts = [
# '--no-pager',
# '-c', 'color.diff=false',
# '-c', 'color.status=false',
# '-c', 'color.branch=false',
# '-c', 'status.displayCommentPrefix=true',
# '-c', 'core.commentchar=#',
# ]
#
# def git(self, cmd, *args, **kwargs):
# return self.cmd(cmd, *args, **kwargs)
#
# def git_string(self, cmd, *args, **kwargs):
# return self._string(cmd, *args, **kwargs)
#
# def git_lines(self, cmd, *args, **kwargs):
# return self._lines(cmd, *args, **kwargs)
#
# def git_exit_code(self, cmd, *args, **kwargs):
# return self._exit_code(cmd, *args, **kwargs)
#
# def git_async(self, cmd, *args, **kwargs):
# return self.cmd_async(cmd, *args, **kwargs)
#
# Path: sgit/helpers.py
# class GitStatusHelper(object):
#
# def file_in_git(self, repo, filename):
# return self.git_exit_code(['ls-files', filename, '--error-unmatch'], cwd=repo) == 0
#
# def has_changes(self, repo):
# return self.has_staged_changes(repo) or self.has_unstaged_changes(repo)
#
# def has_staged_changes(self, repo):
# return self.git_exit_code(['diff', '--exit-code', '--quiet', '--cached'], cwd=repo) != 0
#
# def has_unstaged_changes(self, repo):
# return self.git_exit_code(['diff', '--exit-code', '--quiet'], cwd=repo) != 0
#
# # def get_porcelain_status(self, repo):
# # mode = self.get_untracked_mode()
# # cmd = ['status', '--porcelain', ('--untracked-files=%s' % mode) if mode else None]
# # return self.git_lines(cmd, cwd=repo)
#
# def get_porcelain_status(self, repo):
# mode = self.get_untracked_mode()
# cmd = ['status', '-z', ('--untracked-files=%s' % mode) if mode else None]
#
# output = self.git_string(cmd, cwd=repo, strip=False)
# rows = output.split('\x00')
# lines = []
# idx = 0
# while idx < len(rows):
# row = rows[idx]
# if row and not row.startswith('#'):
# status, filename = row[:2], row[3:]
# if status[0] == 'R':
# lines.append("%s %s -> %s" % (status, rows[idx + 1], filename))
# idx += 1
# else:
# lines.append("%s %s" % (status, filename))
# idx += 1
# return lines
#
# def get_files_status(self, repo):
# untracked, unstaged, staged = [], [], []
# status = self.get_porcelain_status(repo)
# for l in status:
# state, filename = l[:2], l[3:]
# index, worktree = state
# if state in ('DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU'):
# logger.warning("unmerged WTF: %s, %s", state, filename)
# elif state == '??':
# untracked.append(('?', filename))
# elif state == '!!':
# continue
# else:
# if worktree != ' ':
# unstaged.append((worktree, filename))
# if index != ' ':
# staged.append((index, filename))
# return untracked, unstaged, staged
#
# def get_untracked_mode(self):
# # get untracked files mode
# setting = get_setting('git_status_untracked_files', 'all')
#
# mode = 'all'
# if setting == 'none':
# mode = 'no'
# elif setting == 'auto':
# mode = None
# return mode
#
# Path: sgit/status.py
# GIT_WORKING_DIR_CLEAN = "Nothing to commit (working directory clean)"
. Output only the next line. | self.window.run_command('show_panel', {'panel': 'output.git-commit'}) |
Predict the next line after this snippet: <|code_start|> '--verbose' if self.is_verbose else None]
exit, stdout, stderr = self.git(cmd, cwd=repo)
stderr = stderr.strip()
if stderr:
for line in stderr.splitlines():
stdout += "# %s\n" % line
old_msg = ''
if amend:
old_msg = self.git_lines(['rev-list', '--format=%B', '--max-count=1', 'HEAD'], cwd=repo)
old_msg = "%s\n" % "\n".join(old_msg[1:])
if self.is_verbose and CUT_LINE not in stdout:
comments = []
other = []
for line in stdout.splitlines():
if line.startswith('#'):
comments.append(line)
else:
other.append(line)
status = "\n".join(comments)
status += "\n# %s" % CUT_LINE
status += CUT_EXPLANATION
status += "\n".join(other)
else:
status = stdout
return GIT_COMMIT_TEMPLATE.format(status=status, old_msg=old_msg)
<|code_end|>
using the current file's imports:
from functools import partial
from sublime_plugin import WindowCommand, TextCommand, EventListener
from .util import find_view_by_settings, noop, get_setting
from .cmd import GitCmd
from .helpers import GitStatusHelper
from .status import GIT_WORKING_DIR_CLEAN
import sublime
and any relevant context from other files:
# Path: sgit/util.py
# def find_view_by_settings(window, **kwargs):
# for view in window.views():
# s = view.settings()
# matches = [s.get(k) == v for k, v in list(kwargs.items())]
# if all(matches):
# return view
#
# def noop(*args, **kwargs):
# pass
#
# def get_setting(key, default=None):
# return get_settings().get(key, default)
#
# Path: sgit/cmd.py
# class GitCmd(GitRepoHelper, Cmd):
# executable = 'git'
# bin = ['git']
# opts = [
# '--no-pager',
# '-c', 'color.diff=false',
# '-c', 'color.status=false',
# '-c', 'color.branch=false',
# '-c', 'status.displayCommentPrefix=true',
# '-c', 'core.commentchar=#',
# ]
#
# def git(self, cmd, *args, **kwargs):
# return self.cmd(cmd, *args, **kwargs)
#
# def git_string(self, cmd, *args, **kwargs):
# return self._string(cmd, *args, **kwargs)
#
# def git_lines(self, cmd, *args, **kwargs):
# return self._lines(cmd, *args, **kwargs)
#
# def git_exit_code(self, cmd, *args, **kwargs):
# return self._exit_code(cmd, *args, **kwargs)
#
# def git_async(self, cmd, *args, **kwargs):
# return self.cmd_async(cmd, *args, **kwargs)
#
# Path: sgit/helpers.py
# class GitStatusHelper(object):
#
# def file_in_git(self, repo, filename):
# return self.git_exit_code(['ls-files', filename, '--error-unmatch'], cwd=repo) == 0
#
# def has_changes(self, repo):
# return self.has_staged_changes(repo) or self.has_unstaged_changes(repo)
#
# def has_staged_changes(self, repo):
# return self.git_exit_code(['diff', '--exit-code', '--quiet', '--cached'], cwd=repo) != 0
#
# def has_unstaged_changes(self, repo):
# return self.git_exit_code(['diff', '--exit-code', '--quiet'], cwd=repo) != 0
#
# # def get_porcelain_status(self, repo):
# # mode = self.get_untracked_mode()
# # cmd = ['status', '--porcelain', ('--untracked-files=%s' % mode) if mode else None]
# # return self.git_lines(cmd, cwd=repo)
#
# def get_porcelain_status(self, repo):
# mode = self.get_untracked_mode()
# cmd = ['status', '-z', ('--untracked-files=%s' % mode) if mode else None]
#
# output = self.git_string(cmd, cwd=repo, strip=False)
# rows = output.split('\x00')
# lines = []
# idx = 0
# while idx < len(rows):
# row = rows[idx]
# if row and not row.startswith('#'):
# status, filename = row[:2], row[3:]
# if status[0] == 'R':
# lines.append("%s %s -> %s" % (status, rows[idx + 1], filename))
# idx += 1
# else:
# lines.append("%s %s" % (status, filename))
# idx += 1
# return lines
#
# def get_files_status(self, repo):
# untracked, unstaged, staged = [], [], []
# status = self.get_porcelain_status(repo)
# for l in status:
# state, filename = l[:2], l[3:]
# index, worktree = state
# if state in ('DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU'):
# logger.warning("unmerged WTF: %s, %s", state, filename)
# elif state == '??':
# untracked.append(('?', filename))
# elif state == '!!':
# continue
# else:
# if worktree != ' ':
# unstaged.append((worktree, filename))
# if index != ' ':
# staged.append((index, filename))
# return untracked, unstaged, staged
#
# def get_untracked_mode(self):
# # get untracked files mode
# setting = get_setting('git_status_untracked_files', 'all')
#
# mode = 'all'
# if setting == 'none':
# mode = 'no'
# elif setting == 'auto':
# mode = None
# return mode
#
# Path: sgit/status.py
# GIT_WORKING_DIR_CLEAN = "Nothing to commit (working directory clean)"
. Output only the next line. | def show_commit_panel(self, content): |
Predict the next line for this snippet: <|code_start|>GIT_COMMIT_TEMPLATE = u"""{old_msg}
# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
{status}"""
GIT_AMEND_PUSHED = (u"It is discouraged to rewrite history which has already been pushed. "
u"Are you sure you want to amend the commit?")
CUT_LINE = u"------------------------ >8 ------------------------\n"
CUT_EXPLANATION = u"# Do not touch the line above.\n# Everything below will be removed.\n"
class GitCommit(object):
windows = {}
class GitCommitWindowCmd(GitCmd, GitStatusHelper):
@property
def is_verbose(self):
return get_setting('git_commit_verbose', False)
def get_commit_template(self, repo, add=False, amend=False):
cmd = ['commit', '--dry-run', '--status',
'--all' if add else None,
'--amend' if amend else None,
'--verbose' if self.is_verbose else None]
exit, stdout, stderr = self.git(cmd, cwd=repo)
<|code_end|>
with the help of current file imports:
from functools import partial
from sublime_plugin import WindowCommand, TextCommand, EventListener
from .util import find_view_by_settings, noop, get_setting
from .cmd import GitCmd
from .helpers import GitStatusHelper
from .status import GIT_WORKING_DIR_CLEAN
import sublime
and context from other files:
# Path: sgit/util.py
# def find_view_by_settings(window, **kwargs):
# for view in window.views():
# s = view.settings()
# matches = [s.get(k) == v for k, v in list(kwargs.items())]
# if all(matches):
# return view
#
# def noop(*args, **kwargs):
# pass
#
# def get_setting(key, default=None):
# return get_settings().get(key, default)
#
# Path: sgit/cmd.py
# class GitCmd(GitRepoHelper, Cmd):
# executable = 'git'
# bin = ['git']
# opts = [
# '--no-pager',
# '-c', 'color.diff=false',
# '-c', 'color.status=false',
# '-c', 'color.branch=false',
# '-c', 'status.displayCommentPrefix=true',
# '-c', 'core.commentchar=#',
# ]
#
# def git(self, cmd, *args, **kwargs):
# return self.cmd(cmd, *args, **kwargs)
#
# def git_string(self, cmd, *args, **kwargs):
# return self._string(cmd, *args, **kwargs)
#
# def git_lines(self, cmd, *args, **kwargs):
# return self._lines(cmd, *args, **kwargs)
#
# def git_exit_code(self, cmd, *args, **kwargs):
# return self._exit_code(cmd, *args, **kwargs)
#
# def git_async(self, cmd, *args, **kwargs):
# return self.cmd_async(cmd, *args, **kwargs)
#
# Path: sgit/helpers.py
# class GitStatusHelper(object):
#
# def file_in_git(self, repo, filename):
# return self.git_exit_code(['ls-files', filename, '--error-unmatch'], cwd=repo) == 0
#
# def has_changes(self, repo):
# return self.has_staged_changes(repo) or self.has_unstaged_changes(repo)
#
# def has_staged_changes(self, repo):
# return self.git_exit_code(['diff', '--exit-code', '--quiet', '--cached'], cwd=repo) != 0
#
# def has_unstaged_changes(self, repo):
# return self.git_exit_code(['diff', '--exit-code', '--quiet'], cwd=repo) != 0
#
# # def get_porcelain_status(self, repo):
# # mode = self.get_untracked_mode()
# # cmd = ['status', '--porcelain', ('--untracked-files=%s' % mode) if mode else None]
# # return self.git_lines(cmd, cwd=repo)
#
# def get_porcelain_status(self, repo):
# mode = self.get_untracked_mode()
# cmd = ['status', '-z', ('--untracked-files=%s' % mode) if mode else None]
#
# output = self.git_string(cmd, cwd=repo, strip=False)
# rows = output.split('\x00')
# lines = []
# idx = 0
# while idx < len(rows):
# row = rows[idx]
# if row and not row.startswith('#'):
# status, filename = row[:2], row[3:]
# if status[0] == 'R':
# lines.append("%s %s -> %s" % (status, rows[idx + 1], filename))
# idx += 1
# else:
# lines.append("%s %s" % (status, filename))
# idx += 1
# return lines
#
# def get_files_status(self, repo):
# untracked, unstaged, staged = [], [], []
# status = self.get_porcelain_status(repo)
# for l in status:
# state, filename = l[:2], l[3:]
# index, worktree = state
# if state in ('DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU'):
# logger.warning("unmerged WTF: %s, %s", state, filename)
# elif state == '??':
# untracked.append(('?', filename))
# elif state == '!!':
# continue
# else:
# if worktree != ' ':
# unstaged.append((worktree, filename))
# if index != ' ':
# staged.append((index, filename))
# return untracked, unstaged, staged
#
# def get_untracked_mode(self):
# # get untracked files mode
# setting = get_setting('git_status_untracked_files', 'all')
#
# mode = 'all'
# if setting == 'none':
# mode = 'no'
# elif setting == 'auto':
# mode = None
# return mode
#
# Path: sgit/status.py
# GIT_WORKING_DIR_CLEAN = "Nothing to commit (working directory clean)"
, which may contain function names, class names, or code. Output only the next line. | stderr = stderr.strip() |
Given the code snippet: <|code_start|>
CUT_LINE = u"------------------------ >8 ------------------------\n"
CUT_EXPLANATION = u"# Do not touch the line above.\n# Everything below will be removed.\n"
class GitCommit(object):
windows = {}
class GitCommitWindowCmd(GitCmd, GitStatusHelper):
@property
def is_verbose(self):
return get_setting('git_commit_verbose', False)
def get_commit_template(self, repo, add=False, amend=False):
cmd = ['commit', '--dry-run', '--status',
'--all' if add else None,
'--amend' if amend else None,
'--verbose' if self.is_verbose else None]
exit, stdout, stderr = self.git(cmd, cwd=repo)
stderr = stderr.strip()
if stderr:
for line in stderr.splitlines():
stdout += "# %s\n" % line
old_msg = ''
if amend:
<|code_end|>
, generate the next line using the imports in this file:
from functools import partial
from sublime_plugin import WindowCommand, TextCommand, EventListener
from .util import find_view_by_settings, noop, get_setting
from .cmd import GitCmd
from .helpers import GitStatusHelper
from .status import GIT_WORKING_DIR_CLEAN
import sublime
and context (functions, classes, or occasionally code) from other files:
# Path: sgit/util.py
# def find_view_by_settings(window, **kwargs):
# for view in window.views():
# s = view.settings()
# matches = [s.get(k) == v for k, v in list(kwargs.items())]
# if all(matches):
# return view
#
# def noop(*args, **kwargs):
# pass
#
# def get_setting(key, default=None):
# return get_settings().get(key, default)
#
# Path: sgit/cmd.py
# class GitCmd(GitRepoHelper, Cmd):
# executable = 'git'
# bin = ['git']
# opts = [
# '--no-pager',
# '-c', 'color.diff=false',
# '-c', 'color.status=false',
# '-c', 'color.branch=false',
# '-c', 'status.displayCommentPrefix=true',
# '-c', 'core.commentchar=#',
# ]
#
# def git(self, cmd, *args, **kwargs):
# return self.cmd(cmd, *args, **kwargs)
#
# def git_string(self, cmd, *args, **kwargs):
# return self._string(cmd, *args, **kwargs)
#
# def git_lines(self, cmd, *args, **kwargs):
# return self._lines(cmd, *args, **kwargs)
#
# def git_exit_code(self, cmd, *args, **kwargs):
# return self._exit_code(cmd, *args, **kwargs)
#
# def git_async(self, cmd, *args, **kwargs):
# return self.cmd_async(cmd, *args, **kwargs)
#
# Path: sgit/helpers.py
# class GitStatusHelper(object):
#
# def file_in_git(self, repo, filename):
# return self.git_exit_code(['ls-files', filename, '--error-unmatch'], cwd=repo) == 0
#
# def has_changes(self, repo):
# return self.has_staged_changes(repo) or self.has_unstaged_changes(repo)
#
# def has_staged_changes(self, repo):
# return self.git_exit_code(['diff', '--exit-code', '--quiet', '--cached'], cwd=repo) != 0
#
# def has_unstaged_changes(self, repo):
# return self.git_exit_code(['diff', '--exit-code', '--quiet'], cwd=repo) != 0
#
# # def get_porcelain_status(self, repo):
# # mode = self.get_untracked_mode()
# # cmd = ['status', '--porcelain', ('--untracked-files=%s' % mode) if mode else None]
# # return self.git_lines(cmd, cwd=repo)
#
# def get_porcelain_status(self, repo):
# mode = self.get_untracked_mode()
# cmd = ['status', '-z', ('--untracked-files=%s' % mode) if mode else None]
#
# output = self.git_string(cmd, cwd=repo, strip=False)
# rows = output.split('\x00')
# lines = []
# idx = 0
# while idx < len(rows):
# row = rows[idx]
# if row and not row.startswith('#'):
# status, filename = row[:2], row[3:]
# if status[0] == 'R':
# lines.append("%s %s -> %s" % (status, rows[idx + 1], filename))
# idx += 1
# else:
# lines.append("%s %s" % (status, filename))
# idx += 1
# return lines
#
# def get_files_status(self, repo):
# untracked, unstaged, staged = [], [], []
# status = self.get_porcelain_status(repo)
# for l in status:
# state, filename = l[:2], l[3:]
# index, worktree = state
# if state in ('DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU'):
# logger.warning("unmerged WTF: %s, %s", state, filename)
# elif state == '??':
# untracked.append(('?', filename))
# elif state == '!!':
# continue
# else:
# if worktree != ' ':
# unstaged.append((worktree, filename))
# if index != ' ':
# staged.append((index, filename))
# return untracked, unstaged, staged
#
# def get_untracked_mode(self):
# # get untracked files mode
# setting = get_setting('git_status_untracked_files', 'all')
#
# mode = 'all'
# if setting == 'none':
# mode = 'no'
# elif setting == 'auto':
# mode = None
# return mode
#
# Path: sgit/status.py
# GIT_WORKING_DIR_CLEAN = "Nothing to commit (working directory clean)"
. Output only the next line. | old_msg = self.git_lines(['rev-list', '--format=%B', '--max-count=1', 'HEAD'], cwd=repo) |
Given snippet: <|code_start|>
class GitCommitWindowCmd(GitCmd, GitStatusHelper):
@property
def is_verbose(self):
return get_setting('git_commit_verbose', False)
def get_commit_template(self, repo, add=False, amend=False):
cmd = ['commit', '--dry-run', '--status',
'--all' if add else None,
'--amend' if amend else None,
'--verbose' if self.is_verbose else None]
exit, stdout, stderr = self.git(cmd, cwd=repo)
stderr = stderr.strip()
if stderr:
for line in stderr.splitlines():
stdout += "# %s\n" % line
old_msg = ''
if amend:
old_msg = self.git_lines(['rev-list', '--format=%B', '--max-count=1', 'HEAD'], cwd=repo)
old_msg = "%s\n" % "\n".join(old_msg[1:])
if self.is_verbose and CUT_LINE not in stdout:
comments = []
other = []
for line in stdout.splitlines():
if line.startswith('#'):
comments.append(line)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from functools import partial
from sublime_plugin import WindowCommand, TextCommand, EventListener
from .util import find_view_by_settings, noop, get_setting
from .cmd import GitCmd
from .helpers import GitStatusHelper
from .status import GIT_WORKING_DIR_CLEAN
import sublime
and context:
# Path: sgit/util.py
# def find_view_by_settings(window, **kwargs):
# for view in window.views():
# s = view.settings()
# matches = [s.get(k) == v for k, v in list(kwargs.items())]
# if all(matches):
# return view
#
# def noop(*args, **kwargs):
# pass
#
# def get_setting(key, default=None):
# return get_settings().get(key, default)
#
# Path: sgit/cmd.py
# class GitCmd(GitRepoHelper, Cmd):
# executable = 'git'
# bin = ['git']
# opts = [
# '--no-pager',
# '-c', 'color.diff=false',
# '-c', 'color.status=false',
# '-c', 'color.branch=false',
# '-c', 'status.displayCommentPrefix=true',
# '-c', 'core.commentchar=#',
# ]
#
# def git(self, cmd, *args, **kwargs):
# return self.cmd(cmd, *args, **kwargs)
#
# def git_string(self, cmd, *args, **kwargs):
# return self._string(cmd, *args, **kwargs)
#
# def git_lines(self, cmd, *args, **kwargs):
# return self._lines(cmd, *args, **kwargs)
#
# def git_exit_code(self, cmd, *args, **kwargs):
# return self._exit_code(cmd, *args, **kwargs)
#
# def git_async(self, cmd, *args, **kwargs):
# return self.cmd_async(cmd, *args, **kwargs)
#
# Path: sgit/helpers.py
# class GitStatusHelper(object):
#
# def file_in_git(self, repo, filename):
# return self.git_exit_code(['ls-files', filename, '--error-unmatch'], cwd=repo) == 0
#
# def has_changes(self, repo):
# return self.has_staged_changes(repo) or self.has_unstaged_changes(repo)
#
# def has_staged_changes(self, repo):
# return self.git_exit_code(['diff', '--exit-code', '--quiet', '--cached'], cwd=repo) != 0
#
# def has_unstaged_changes(self, repo):
# return self.git_exit_code(['diff', '--exit-code', '--quiet'], cwd=repo) != 0
#
# # def get_porcelain_status(self, repo):
# # mode = self.get_untracked_mode()
# # cmd = ['status', '--porcelain', ('--untracked-files=%s' % mode) if mode else None]
# # return self.git_lines(cmd, cwd=repo)
#
# def get_porcelain_status(self, repo):
# mode = self.get_untracked_mode()
# cmd = ['status', '-z', ('--untracked-files=%s' % mode) if mode else None]
#
# output = self.git_string(cmd, cwd=repo, strip=False)
# rows = output.split('\x00')
# lines = []
# idx = 0
# while idx < len(rows):
# row = rows[idx]
# if row and not row.startswith('#'):
# status, filename = row[:2], row[3:]
# if status[0] == 'R':
# lines.append("%s %s -> %s" % (status, rows[idx + 1], filename))
# idx += 1
# else:
# lines.append("%s %s" % (status, filename))
# idx += 1
# return lines
#
# def get_files_status(self, repo):
# untracked, unstaged, staged = [], [], []
# status = self.get_porcelain_status(repo)
# for l in status:
# state, filename = l[:2], l[3:]
# index, worktree = state
# if state in ('DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU'):
# logger.warning("unmerged WTF: %s, %s", state, filename)
# elif state == '??':
# untracked.append(('?', filename))
# elif state == '!!':
# continue
# else:
# if worktree != ' ':
# unstaged.append((worktree, filename))
# if index != ' ':
# staged.append((index, filename))
# return untracked, unstaged, staged
#
# def get_untracked_mode(self):
# # get untracked files mode
# setting = get_setting('git_status_untracked_files', 'all')
#
# mode = 'all'
# if setting == 'none':
# mode = 'no'
# elif setting == 'auto':
# mode = None
# return mode
#
# Path: sgit/status.py
# GIT_WORKING_DIR_CLEAN = "Nothing to commit (working directory clean)"
which might include code, classes, or functions. Output only the next line. | else: |
Using the snippet: <|code_start|>GIT_COMMIT_TEMPLATE = u"""{old_msg}
# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
{status}"""
GIT_AMEND_PUSHED = (u"It is discouraged to rewrite history which has already been pushed. "
u"Are you sure you want to amend the commit?")
CUT_LINE = u"------------------------ >8 ------------------------\n"
CUT_EXPLANATION = u"# Do not touch the line above.\n# Everything below will be removed.\n"
class GitCommit(object):
windows = {}
class GitCommitWindowCmd(GitCmd, GitStatusHelper):
@property
def is_verbose(self):
return get_setting('git_commit_verbose', False)
def get_commit_template(self, repo, add=False, amend=False):
cmd = ['commit', '--dry-run', '--status',
'--all' if add else None,
'--amend' if amend else None,
'--verbose' if self.is_verbose else None]
exit, stdout, stderr = self.git(cmd, cwd=repo)
<|code_end|>
, determine the next line of code. You have imports:
from functools import partial
from sublime_plugin import WindowCommand, TextCommand, EventListener
from .util import find_view_by_settings, noop, get_setting
from .cmd import GitCmd
from .helpers import GitStatusHelper
from .status import GIT_WORKING_DIR_CLEAN
import sublime
and context (class names, function names, or code) available:
# Path: sgit/util.py
# def find_view_by_settings(window, **kwargs):
# for view in window.views():
# s = view.settings()
# matches = [s.get(k) == v for k, v in list(kwargs.items())]
# if all(matches):
# return view
#
# def noop(*args, **kwargs):
# pass
#
# def get_setting(key, default=None):
# return get_settings().get(key, default)
#
# Path: sgit/cmd.py
# class GitCmd(GitRepoHelper, Cmd):
# executable = 'git'
# bin = ['git']
# opts = [
# '--no-pager',
# '-c', 'color.diff=false',
# '-c', 'color.status=false',
# '-c', 'color.branch=false',
# '-c', 'status.displayCommentPrefix=true',
# '-c', 'core.commentchar=#',
# ]
#
# def git(self, cmd, *args, **kwargs):
# return self.cmd(cmd, *args, **kwargs)
#
# def git_string(self, cmd, *args, **kwargs):
# return self._string(cmd, *args, **kwargs)
#
# def git_lines(self, cmd, *args, **kwargs):
# return self._lines(cmd, *args, **kwargs)
#
# def git_exit_code(self, cmd, *args, **kwargs):
# return self._exit_code(cmd, *args, **kwargs)
#
# def git_async(self, cmd, *args, **kwargs):
# return self.cmd_async(cmd, *args, **kwargs)
#
# Path: sgit/helpers.py
# class GitStatusHelper(object):
#
# def file_in_git(self, repo, filename):
# return self.git_exit_code(['ls-files', filename, '--error-unmatch'], cwd=repo) == 0
#
# def has_changes(self, repo):
# return self.has_staged_changes(repo) or self.has_unstaged_changes(repo)
#
# def has_staged_changes(self, repo):
# return self.git_exit_code(['diff', '--exit-code', '--quiet', '--cached'], cwd=repo) != 0
#
# def has_unstaged_changes(self, repo):
# return self.git_exit_code(['diff', '--exit-code', '--quiet'], cwd=repo) != 0
#
# # def get_porcelain_status(self, repo):
# # mode = self.get_untracked_mode()
# # cmd = ['status', '--porcelain', ('--untracked-files=%s' % mode) if mode else None]
# # return self.git_lines(cmd, cwd=repo)
#
# def get_porcelain_status(self, repo):
# mode = self.get_untracked_mode()
# cmd = ['status', '-z', ('--untracked-files=%s' % mode) if mode else None]
#
# output = self.git_string(cmd, cwd=repo, strip=False)
# rows = output.split('\x00')
# lines = []
# idx = 0
# while idx < len(rows):
# row = rows[idx]
# if row and not row.startswith('#'):
# status, filename = row[:2], row[3:]
# if status[0] == 'R':
# lines.append("%s %s -> %s" % (status, rows[idx + 1], filename))
# idx += 1
# else:
# lines.append("%s %s" % (status, filename))
# idx += 1
# return lines
#
# def get_files_status(self, repo):
# untracked, unstaged, staged = [], [], []
# status = self.get_porcelain_status(repo)
# for l in status:
# state, filename = l[:2], l[3:]
# index, worktree = state
# if state in ('DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU'):
# logger.warning("unmerged WTF: %s, %s", state, filename)
# elif state == '??':
# untracked.append(('?', filename))
# elif state == '!!':
# continue
# else:
# if worktree != ' ':
# unstaged.append((worktree, filename))
# if index != ' ':
# staged.append((index, filename))
# return untracked, unstaged, staged
#
# def get_untracked_mode(self):
# # get untracked files mode
# setting = get_setting('git_status_untracked_files', 'all')
#
# mode = 'all'
# if setting == 'none':
# mode = 'no'
# elif setting == 'auto':
# mode = None
# return mode
#
# Path: sgit/status.py
# GIT_WORKING_DIR_CLEAN = "Nothing to commit (working directory clean)"
. Output only the next line. | stderr = stderr.strip() |
Next line prediction: <|code_start|>
return repo
def get_repo_from_view(self, view=None, silent=True):
if view is None:
return
# first try the view settings (for things like status, diff, etc)
view_repo = view.settings().get('git_repo')
if view_repo:
logger.info('get_repo_from_view(view=%s, silent=%s): %s (view settings)', view.id(), silent, view_repo)
return view_repo
# else try the given view file
file_repo = self.git_repo_from_view(view)
if file_repo:
logger.info('get_repo(window=%s, silent=%s): %s (file)', view.id(), silent, file_repo)
return file_repo
def get_repo_from_window(self, window=None, silent=True):
if not window:
logger.info('get_repo_from_window(window=%s, silent=%s): None (no window)', None, silent)
return
active_view = window.active_view()
if active_view is not None:
# if the active view has a setting, use that
active_view_repo = active_view.settings().get('git_repo')
if active_view_repo:
logger.info('get_repo_from_window(window=%s, silent=%s): %s (view settings)', window.id(), silent, active_view_repo)
<|code_end|>
. Use current file imports:
(import re
import os
import logging
import sublime
from .util import get_setting)
and context including class names, function names, or small code snippets from other files:
# Path: sgit/util.py
# def get_setting(key, default=None):
# return get_settings().get(key, default)
. Output only the next line. | return active_view_repo |
Using the snippet: <|code_start|># coding: utf-8
NO_REMOTES = u"No remotes have been configured. Remotes can be added with the Git: Add Remote command. Do you want to add a remote now?"
DELETE_REMOTE = u"Are you sure you want to delete the remote %s?"
NO_ORIGIN_REMOTE = u"You are not on any branch and no origin has been configured. Please check out a branch and run Git: Remote Add to add a remote."
NO_BRANCH_REMOTES = u"No remotes have been configured for the branch %s and no origin exists. Please run Git: Remote Add to add a remote."
<|code_end|>
, determine the next line of code. You have imports:
from functools import partial
from sublime_plugin import WindowCommand
from .util import StatusSpinner, noop
from .cmd import GitCmd
from .helpers import GitRemoteHelper
import sublime
and context (class names, function names, or code) available:
# Path: sgit/util.py
# class StatusSpinner(object):
#
# SIZE = 10 # 10 equal signs
# TIME = 50 # 50 ms delay
#
# def __init__(self, thread, msg):
# self.counter = 0
# self.direction = 1
# self.msg = msg
# self.thread = thread
#
# def progress(self):
# if not self.thread.is_alive():
# sublime.status_message('')
# return
#
# left, right = self.counter, (self.SIZE - 1 - self.counter)
# self.counter += self.direction
# if self.counter in (0, self.SIZE - 1):
# self.direction *= -1
#
# status = "[%s=%s] %s" % (' ' * left, ' ' * right, self.msg)
#
# sublime.status_message(status)
# sublime.set_timeout(self.progress, self.TIME)
#
# def start(self):
# self.thread.start()
# sublime.set_timeout(self.progress, 0)
#
# def noop(*args, **kwargs):
# pass
#
# Path: sgit/cmd.py
# class GitCmd(GitRepoHelper, Cmd):
# executable = 'git'
# bin = ['git']
# opts = [
# '--no-pager',
# '-c', 'color.diff=false',
# '-c', 'color.status=false',
# '-c', 'color.branch=false',
# '-c', 'status.displayCommentPrefix=true',
# '-c', 'core.commentchar=#',
# ]
#
# def git(self, cmd, *args, **kwargs):
# return self.cmd(cmd, *args, **kwargs)
#
# def git_string(self, cmd, *args, **kwargs):
# return self._string(cmd, *args, **kwargs)
#
# def git_lines(self, cmd, *args, **kwargs):
# return self._lines(cmd, *args, **kwargs)
#
# def git_exit_code(self, cmd, *args, **kwargs):
# return self._exit_code(cmd, *args, **kwargs)
#
# def git_async(self, cmd, *args, **kwargs):
# return self.cmd_async(cmd, *args, **kwargs)
#
# Path: sgit/helpers.py
# class GitRemoteHelper(GitBranchHelper):
#
# def get_remotes(self, repo):
# return self.git_lines(['remote', '-v'], cwd=repo)
#
# def get_remote_names(self, remotes):
# names = set()
# for r in remotes:
# name, right = r.split('\t', 1)
# url, action = right.rsplit(' ', 1)
# names.append(name)
# return sorted(list(names))
#
# def format_quick_remotes(self, remotes):
# data = {}
# for r in remotes:
# name, right = r.split('\t', 1)
# url, action = right.rsplit(' ', 1)
# data.setdefault(name, {})[action] = "%s %s" % (url, action)
# choices = []
# for remote, urls in list(data.items()):
# choices.append([remote, urls.get('(fetch)', None), urls.get('(push)', None)])
# return choices
#
# def get_remote_url(self, repo, remote):
# return self.git_string(['config', 'remote.%s.url' % remote], cwd=repo)
#
# def get_branch_upstream(self, repo, branch):
# return (self.get_branch_remote(repo, branch), self.get_branch_merge(repo, branch))
#
# def get_branch_remote(self, repo, branch):
# return self.git_string(['config', 'branch.%s.remote' % branch], cwd=repo)
#
# def get_branch_merge(self, repo, branch):
# return self.git_string(['config', 'branch.%s.merge' % branch], cwd=repo)
#
# def get_remote_branches(self, repo, remote):
# branches = [b for _, b in self.get_branches(repo, remotes=True)]
# return [b for b in branches if b.startswith(remote + '/')]
#
# def format_quick_branches(self, branches):
# choices = []
# for b in branches:
# branch = b.split('/', 1)[1]
# choices.append([branch, b])
# return choices
. Output only the next line. | CURRENT_NO_UPSTREAM = u"No upstream currently is currently specified for {branch}. Do you want to set the upstream to {merge} on {remote}?" |
Given the code snippet: <|code_start|># coding: utf-8
NO_REMOTES = u"No remotes have been configured. Remotes can be added with the Git: Add Remote command. Do you want to add a remote now?"
DELETE_REMOTE = u"Are you sure you want to delete the remote %s?"
NO_ORIGIN_REMOTE = u"You are not on any branch and no origin has been configured. Please check out a branch and run Git: Remote Add to add a remote."
<|code_end|>
, generate the next line using the imports in this file:
from functools import partial
from sublime_plugin import WindowCommand
from .util import StatusSpinner, noop
from .cmd import GitCmd
from .helpers import GitRemoteHelper
import sublime
and context (functions, classes, or occasionally code) from other files:
# Path: sgit/util.py
# class StatusSpinner(object):
#
# SIZE = 10 # 10 equal signs
# TIME = 50 # 50 ms delay
#
# def __init__(self, thread, msg):
# self.counter = 0
# self.direction = 1
# self.msg = msg
# self.thread = thread
#
# def progress(self):
# if not self.thread.is_alive():
# sublime.status_message('')
# return
#
# left, right = self.counter, (self.SIZE - 1 - self.counter)
# self.counter += self.direction
# if self.counter in (0, self.SIZE - 1):
# self.direction *= -1
#
# status = "[%s=%s] %s" % (' ' * left, ' ' * right, self.msg)
#
# sublime.status_message(status)
# sublime.set_timeout(self.progress, self.TIME)
#
# def start(self):
# self.thread.start()
# sublime.set_timeout(self.progress, 0)
#
# def noop(*args, **kwargs):
# pass
#
# Path: sgit/cmd.py
# class GitCmd(GitRepoHelper, Cmd):
# executable = 'git'
# bin = ['git']
# opts = [
# '--no-pager',
# '-c', 'color.diff=false',
# '-c', 'color.status=false',
# '-c', 'color.branch=false',
# '-c', 'status.displayCommentPrefix=true',
# '-c', 'core.commentchar=#',
# ]
#
# def git(self, cmd, *args, **kwargs):
# return self.cmd(cmd, *args, **kwargs)
#
# def git_string(self, cmd, *args, **kwargs):
# return self._string(cmd, *args, **kwargs)
#
# def git_lines(self, cmd, *args, **kwargs):
# return self._lines(cmd, *args, **kwargs)
#
# def git_exit_code(self, cmd, *args, **kwargs):
# return self._exit_code(cmd, *args, **kwargs)
#
# def git_async(self, cmd, *args, **kwargs):
# return self.cmd_async(cmd, *args, **kwargs)
#
# Path: sgit/helpers.py
# class GitRemoteHelper(GitBranchHelper):
#
# def get_remotes(self, repo):
# return self.git_lines(['remote', '-v'], cwd=repo)
#
# def get_remote_names(self, remotes):
# names = set()
# for r in remotes:
# name, right = r.split('\t', 1)
# url, action = right.rsplit(' ', 1)
# names.append(name)
# return sorted(list(names))
#
# def format_quick_remotes(self, remotes):
# data = {}
# for r in remotes:
# name, right = r.split('\t', 1)
# url, action = right.rsplit(' ', 1)
# data.setdefault(name, {})[action] = "%s %s" % (url, action)
# choices = []
# for remote, urls in list(data.items()):
# choices.append([remote, urls.get('(fetch)', None), urls.get('(push)', None)])
# return choices
#
# def get_remote_url(self, repo, remote):
# return self.git_string(['config', 'remote.%s.url' % remote], cwd=repo)
#
# def get_branch_upstream(self, repo, branch):
# return (self.get_branch_remote(repo, branch), self.get_branch_merge(repo, branch))
#
# def get_branch_remote(self, repo, branch):
# return self.git_string(['config', 'branch.%s.remote' % branch], cwd=repo)
#
# def get_branch_merge(self, repo, branch):
# return self.git_string(['config', 'branch.%s.merge' % branch], cwd=repo)
#
# def get_remote_branches(self, repo, remote):
# branches = [b for _, b in self.get_branches(repo, remotes=True)]
# return [b for b in branches if b.startswith(remote + '/')]
#
# def format_quick_branches(self, branches):
# choices = []
# for b in branches:
# branch = b.split('/', 1)[1]
# choices.append([branch, b])
# return choices
. Output only the next line. | NO_BRANCH_REMOTES = u"No remotes have been configured for the branch %s and no origin exists. Please run Git: Remote Add to add a remote." |
Given the following code snippet before the placeholder: <|code_start|># coding: utf-8
NO_REMOTES = u"No remotes have been configured. Remotes can be added with the Git: Add Remote command. Do you want to add a remote now?"
DELETE_REMOTE = u"Are you sure you want to delete the remote %s?"
NO_ORIGIN_REMOTE = u"You are not on any branch and no origin has been configured. Please check out a branch and run Git: Remote Add to add a remote."
NO_BRANCH_REMOTES = u"No remotes have been configured for the branch %s and no origin exists. Please run Git: Remote Add to add a remote."
CURRENT_NO_UPSTREAM = u"No upstream currently is currently specified for {branch}. Do you want to set the upstream to {merge} on {remote}?"
CURRENT_DIFFERENT_UPSTREAM = u"The upstream for {branch} is currently set to {branch_merge} on {branch_remote}. Do you want to change it to {merge} on {remote}?"
NO_UPSTREAM = u"No upstream is configured for your current branch. Do you want to run Git: Push Current Branch?"
NO_TRACKING = u"No tracking information is configured for your current branch. Do you want to run Git: Pull Current Branch?"
<|code_end|>
, predict the next line using imports from the current file:
from functools import partial
from sublime_plugin import WindowCommand
from .util import StatusSpinner, noop
from .cmd import GitCmd
from .helpers import GitRemoteHelper
import sublime
and context including class names, function names, and sometimes code from other files:
# Path: sgit/util.py
# class StatusSpinner(object):
#
# SIZE = 10 # 10 equal signs
# TIME = 50 # 50 ms delay
#
# def __init__(self, thread, msg):
# self.counter = 0
# self.direction = 1
# self.msg = msg
# self.thread = thread
#
# def progress(self):
# if not self.thread.is_alive():
# sublime.status_message('')
# return
#
# left, right = self.counter, (self.SIZE - 1 - self.counter)
# self.counter += self.direction
# if self.counter in (0, self.SIZE - 1):
# self.direction *= -1
#
# status = "[%s=%s] %s" % (' ' * left, ' ' * right, self.msg)
#
# sublime.status_message(status)
# sublime.set_timeout(self.progress, self.TIME)
#
# def start(self):
# self.thread.start()
# sublime.set_timeout(self.progress, 0)
#
# def noop(*args, **kwargs):
# pass
#
# Path: sgit/cmd.py
# class GitCmd(GitRepoHelper, Cmd):
# executable = 'git'
# bin = ['git']
# opts = [
# '--no-pager',
# '-c', 'color.diff=false',
# '-c', 'color.status=false',
# '-c', 'color.branch=false',
# '-c', 'status.displayCommentPrefix=true',
# '-c', 'core.commentchar=#',
# ]
#
# def git(self, cmd, *args, **kwargs):
# return self.cmd(cmd, *args, **kwargs)
#
# def git_string(self, cmd, *args, **kwargs):
# return self._string(cmd, *args, **kwargs)
#
# def git_lines(self, cmd, *args, **kwargs):
# return self._lines(cmd, *args, **kwargs)
#
# def git_exit_code(self, cmd, *args, **kwargs):
# return self._exit_code(cmd, *args, **kwargs)
#
# def git_async(self, cmd, *args, **kwargs):
# return self.cmd_async(cmd, *args, **kwargs)
#
# Path: sgit/helpers.py
# class GitRemoteHelper(GitBranchHelper):
#
# def get_remotes(self, repo):
# return self.git_lines(['remote', '-v'], cwd=repo)
#
# def get_remote_names(self, remotes):
# names = set()
# for r in remotes:
# name, right = r.split('\t', 1)
# url, action = right.rsplit(' ', 1)
# names.append(name)
# return sorted(list(names))
#
# def format_quick_remotes(self, remotes):
# data = {}
# for r in remotes:
# name, right = r.split('\t', 1)
# url, action = right.rsplit(' ', 1)
# data.setdefault(name, {})[action] = "%s %s" % (url, action)
# choices = []
# for remote, urls in list(data.items()):
# choices.append([remote, urls.get('(fetch)', None), urls.get('(push)', None)])
# return choices
#
# def get_remote_url(self, repo, remote):
# return self.git_string(['config', 'remote.%s.url' % remote], cwd=repo)
#
# def get_branch_upstream(self, repo, branch):
# return (self.get_branch_remote(repo, branch), self.get_branch_merge(repo, branch))
#
# def get_branch_remote(self, repo, branch):
# return self.git_string(['config', 'branch.%s.remote' % branch], cwd=repo)
#
# def get_branch_merge(self, repo, branch):
# return self.git_string(['config', 'branch.%s.merge' % branch], cwd=repo)
#
# def get_remote_branches(self, repo, remote):
# branches = [b for _, b in self.get_branches(repo, remotes=True)]
# return [b for b in branches if b.startswith(remote + '/')]
#
# def format_quick_branches(self, branches):
# choices = []
# for b in branches:
# branch = b.split('/', 1)[1]
# choices.append([branch, b])
# return choices
. Output only the next line. | REMOTE_SHOW_TITLE_PREFIX = '*git-remote*: ' |
Predict the next line after this snippet: <|code_start|># coding: utf-8
GIT_INIT_NO_DIR_ERROR = "No directory provided. Aborting git init."
GIT_INIT_DIR_NOT_EXISTS_MSG = "The directory %s does not exist. Create directory?"
GIT_INIT_NOT_ISDIR_ERROR = "%s is not a directory. Aborting git init."
GIT_INIT_DIR_EXISTS_ERROR = "%s already exists. Aborting git init."
<|code_end|>
using the current file's imports:
import os
import sublime
from sublime_plugin import WindowCommand
from .util import noop, abbreviate_dir
from .cmd import GitCmd
and any relevant context from other files:
# Path: sgit/util.py
# def noop(*args, **kwargs):
# pass
#
# def abbreviate_dir(dirname):
# user_dir = get_user_dir()
# try:
# if dirname.startswith(user_dir):
# dirname = u'~%s' % dirname[len(user_dir):]
# except:
# pass
# return dirname
#
# Path: sgit/cmd.py
# class GitCmd(GitRepoHelper, Cmd):
# executable = 'git'
# bin = ['git']
# opts = [
# '--no-pager',
# '-c', 'color.diff=false',
# '-c', 'color.status=false',
# '-c', 'color.branch=false',
# '-c', 'status.displayCommentPrefix=true',
# '-c', 'core.commentchar=#',
# ]
#
# def git(self, cmd, *args, **kwargs):
# return self.cmd(cmd, *args, **kwargs)
#
# def git_string(self, cmd, *args, **kwargs):
# return self._string(cmd, *args, **kwargs)
#
# def git_lines(self, cmd, *args, **kwargs):
# return self._lines(cmd, *args, **kwargs)
#
# def git_exit_code(self, cmd, *args, **kwargs):
# return self._exit_code(cmd, *args, **kwargs)
#
# def git_async(self, cmd, *args, **kwargs):
# return self.cmd_async(cmd, *args, **kwargs)
. Output only the next line. | GIT_INIT_DIR_LABEL = "Directory:" |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
class MatterlloWizard(SessionWizardView):
form_list = [WebhookCreateForm, BridgeCreateForm]
template_name = "core/wizard.html"
def done(self, form_list, **kwargs):
<|code_end|>
. Write the next line using the current file imports:
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.utils.decorators import method_decorator
from formtools.wizard.views import SessionWizardView
from core.forms import BridgeCreateForm, WebhookCreateForm
and context from other files:
# Path: core/forms.py
# class BridgeCreateForm(forms.ModelForm):
# events = forms.MultipleChoiceField(
# choices=Bridge.EVENT_CHOICES,
# widget=forms.CheckboxSelectMultiple,
# )
#
# def __init__(self, *args, **kwargs):
# super(BridgeCreateForm, self).__init__(*args, **kwargs)
# helper = self.helper = FormHelper()
#
# layout = helper.layout = Layout()
# layout.append(Field("events", css_class="board-event"))
# layout.append(
# FormActions(
# HTML(
# '<button class="btn btn-info" type="button" onclick="document.querySelectorAll(\'.board-event\').forEach(x => x.checked = true);">Check all</button>'
# )
# )
# )
# layout.append(
# FormActions(
# HTML(
# '<button class="btn btn-info" type="button" onclick="document.querySelectorAll(\'.board-event\').forEach(x => x.checked = false);">Uncheck all</button>'
# )
# )
# )
# layout.append(FormActions(Submit("save", "Save")))
#
# helper.form_show_labels = False
# helper.form_class = "form-horizontal"
# helper.field_class = "col-lg-8"
# helper.help_text_inline = True
#
# class Meta:
# model = Bridge
# fields = ["events"]
# help_texts = {
# "events": 'The generated key from <a href="https://docs.mattermost.com/developer/webhooks-incoming.html#setting-up-existing-integrations">Mattermost webhook</a>.',
# }
#
# class WebhookCreateForm(forms.ModelForm):
# def __init__(self, *args, **kwargs):
# super(WebhookCreateForm, self).__init__(*args, **kwargs)
# helper = self.helper = FormHelper()
#
# layout = helper.layout = Layout()
# layout.append(Field("name", placeholder="webhook for town-square"))
# layout.append(
# Field(
# "incoming_webhook_url",
# placeholder="https://mattermost.gitlab.com/hooks/b5g6pyoqsjy88fa6kzn7xi1rzy",
# )
# )
# layout.append(FormActions(Submit("save", "Next")))
#
# helper.form_show_labels = False
# helper.form_class = "form-horizontal"
# helper.field_class = "col-lg-8"
# helper.help_text_inline = True
#
# class Meta:
# model = Webhook
# fields = ["name", "incoming_webhook_url"]
# help_texts = {
# "name": "The description.",
# "incoming_webhook_url": 'The generated url from <a href="https://docs.mattermost.com/developer/webhooks-incoming.html#setting-up-existing-integrations">Mattermost webhook</a>.',
# }
, which may include functions, classes, or code. Output only the next line. | return HttpResponseRedirect("/") |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
class BridgeListView(ListView):
model = Bridge
template_name = "core/index.html"
class BridgeDetailView(DetailView):
model = Bridge
class BridgeCreateView(SuccessMessageMixin, CreateView):
model = Bridge
form_class = BridgeCreateForm
success_message = "Bridge was created successfully"
def form_valid(self, form):
form.instance.board_id = self.kwargs.get("board_id")
form.instance.webhook_id = self.kwargs.get("webhook_id")
<|code_end|>
. Write the next line using the current file imports:
from django.contrib.messages.views import SuccessMessageMixin
from django.views.generic import ListView
from django.views.generic.edit import CreateView
from django.views.generic.detail import DetailView
from django.urls import reverse_lazy
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from core.models import Board, Webhook, Bridge
from core.forms import BridgeCreateForm
and context from other files:
# Path: core/models.py
# class Board(models.Model):
#
# name = models.CharField(max_length=100)
# webhook_activate = models.BooleanField(default=False)
# trello_board_id = models.CharField(max_length=100)
# trello_token = models.CharField(max_length=100)
# created_at = models.DateTimeField(auto_now_add=True)
# updated_at = models.DateTimeField(auto_now=True)
#
# class Meta:
# ordering = ["name"]
# verbose_name_plural = "boards"
#
# def __str__(self):
# return self.name
#
# def __unicode__(self):
# return "{}".format(self.name)
#
# class Webhook(models.Model):
#
# name = models.CharField(max_length=50)
# incoming_webhook_url = models.CharField(max_length=300, unique=True)
#
# icon_url = models.CharField(
# max_length=250,
# default="http://maffrigby.com/wp-content/uploads/2015/05/trello-icon.png",
# )
# username = models.CharField(max_length=30, default="Matterllo")
#
# board = models.ManyToManyField(Board)
#
# created_at = models.DateTimeField(auto_now_add=True)
# updated_at = models.DateTimeField(auto_now=True)
#
# class Meta:
# ordering = ["name"]
# verbose_name_plural = "webhooks"
#
# def __str__(self):
# return "{} :: {}".format(self.name, self.incoming_webhook_url)
#
# def __unicode__(self):
# return "{} :: {}".format(self.name, self.incoming_webhook_url)
#
# class Bridge(models.Model):
# EVENT_CHOICES = (
# # card
# ("addAttachmentToCard", "addAttachmentToCard"),
# ("addLabelToCard", "addLabelToCard"),
# ("addMemberToCard", "addMemberToCard"),
# ("commentCard", "commentCard"),
# ("copyCard", "copyCard"),
# ("createCard", "createCard"),
# ("emailCard", "emailCard"),
# ("moveCardFromBoard", "moveCardFromBoard"),
# ("moveCardToBoard", "moveCardToBoard"),
# ("removeLabelFromCard", "removeLabelFromCard"),
# ("removeMemberFromCard", "removeMemberFromCard"),
# (
# "updateCard",
# "updateCard (include moveCardToList, renameCard, renameCardDesc, updateCardDueDate, removeCardDueDate, archiveCard, unarchiveCard)",
# ),
# # checklist
# ("addChecklistToCard", "addChecklistToCard"),
# ("createCheckItem", "createCheckItem"),
# ("updateCheckItemStateOnCard", "updateCheckItemStateOnCard"),
# # list
# ("archiveList", "archiveList"),
# ("createList", "createList"),
# ("moveListFromBoard", "moveCardFromBoard"),
# ("moveListToBoard", "moveListToBoard"),
# ("renameList", "renameList"),
# ("updateList", "updateList"),
# )
#
# webhook = models.ForeignKey(Webhook, on_delete=models.CASCADE)
# board = models.ForeignKey(Board, on_delete=models.CASCADE)
#
# events = models.CharField(max_length=700)
#
# created_at = models.DateTimeField(auto_now_add=True)
# updated_at = models.DateTimeField(auto_now=True)
#
# class Meta:
# verbose_name_plural = "bridges"
#
# def __str__(self):
# return "{}::{}".format(self.board, self.webhook)
#
# def __unicode__(self):
# return "{}::{}".format(self.board, self.webhook)
#
# def events_as_list(self):
# return literal_eval(self.events)
#
# Path: core/forms.py
# class BridgeCreateForm(forms.ModelForm):
# events = forms.MultipleChoiceField(
# choices=Bridge.EVENT_CHOICES,
# widget=forms.CheckboxSelectMultiple,
# )
#
# def __init__(self, *args, **kwargs):
# super(BridgeCreateForm, self).__init__(*args, **kwargs)
# helper = self.helper = FormHelper()
#
# layout = helper.layout = Layout()
# layout.append(Field("events", css_class="board-event"))
# layout.append(
# FormActions(
# HTML(
# '<button class="btn btn-info" type="button" onclick="document.querySelectorAll(\'.board-event\').forEach(x => x.checked = true);">Check all</button>'
# )
# )
# )
# layout.append(
# FormActions(
# HTML(
# '<button class="btn btn-info" type="button" onclick="document.querySelectorAll(\'.board-event\').forEach(x => x.checked = false);">Uncheck all</button>'
# )
# )
# )
# layout.append(FormActions(Submit("save", "Save")))
#
# helper.form_show_labels = False
# helper.form_class = "form-horizontal"
# helper.field_class = "col-lg-8"
# helper.help_text_inline = True
#
# class Meta:
# model = Bridge
# fields = ["events"]
# help_texts = {
# "events": 'The generated key from <a href="https://docs.mattermost.com/developer/webhooks-incoming.html#setting-up-existing-integrations">Mattermost webhook</a>.',
# }
, which may include functions, classes, or code. Output only the next line. | return super(BridgeCreateView, self).form_valid(form) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
class WebhookDetailView(DetailView):
model = Webhook
class WebhookCreateView(SuccessMessageMixin, CreateView):
model = Webhook
form_class = WebhookCreateForm
success_message = "%(name)s was created successfully"
def form_valid(self, form):
form.instance.board_id = self.kwargs.get("board_id")
return super(WebhookCreateView, self).form_valid(form)
def get_context_data(self, **kwargs):
board_id = self.kwargs.get("board_id")
context = super(WebhookCreateView, self).get_context_data(**kwargs)
context["board"] = Board.objects.get(id=board_id)
context["webhooks"] = Webhook.objects.filter()
return context
<|code_end|>
, generate the next line using the imports in this file:
from django.contrib.auth.decorators import login_required
from django.contrib.messages.views import SuccessMessageMixin
from django.urls import reverse_lazy
from django.utils.decorators import method_decorator
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView
from core.models import Webhook, Board
from core.forms import WebhookCreateForm
and context (functions, classes, or occasionally code) from other files:
# Path: core/models.py
# class Webhook(models.Model):
#
# name = models.CharField(max_length=50)
# incoming_webhook_url = models.CharField(max_length=300, unique=True)
#
# icon_url = models.CharField(
# max_length=250,
# default="http://maffrigby.com/wp-content/uploads/2015/05/trello-icon.png",
# )
# username = models.CharField(max_length=30, default="Matterllo")
#
# board = models.ManyToManyField(Board)
#
# created_at = models.DateTimeField(auto_now_add=True)
# updated_at = models.DateTimeField(auto_now=True)
#
# class Meta:
# ordering = ["name"]
# verbose_name_plural = "webhooks"
#
# def __str__(self):
# return "{} :: {}".format(self.name, self.incoming_webhook_url)
#
# def __unicode__(self):
# return "{} :: {}".format(self.name, self.incoming_webhook_url)
#
# class Board(models.Model):
#
# name = models.CharField(max_length=100)
# webhook_activate = models.BooleanField(default=False)
# trello_board_id = models.CharField(max_length=100)
# trello_token = models.CharField(max_length=100)
# created_at = models.DateTimeField(auto_now_add=True)
# updated_at = models.DateTimeField(auto_now=True)
#
# class Meta:
# ordering = ["name"]
# verbose_name_plural = "boards"
#
# def __str__(self):
# return self.name
#
# def __unicode__(self):
# return "{}".format(self.name)
#
# Path: core/forms.py
# class WebhookCreateForm(forms.ModelForm):
# def __init__(self, *args, **kwargs):
# super(WebhookCreateForm, self).__init__(*args, **kwargs)
# helper = self.helper = FormHelper()
#
# layout = helper.layout = Layout()
# layout.append(Field("name", placeholder="webhook for town-square"))
# layout.append(
# Field(
# "incoming_webhook_url",
# placeholder="https://mattermost.gitlab.com/hooks/b5g6pyoqsjy88fa6kzn7xi1rzy",
# )
# )
# layout.append(FormActions(Submit("save", "Next")))
#
# helper.form_show_labels = False
# helper.form_class = "form-horizontal"
# helper.field_class = "col-lg-8"
# helper.help_text_inline = True
#
# class Meta:
# model = Webhook
# fields = ["name", "incoming_webhook_url"]
# help_texts = {
# "name": "The description.",
# "incoming_webhook_url": 'The generated url from <a href="https://docs.mattermost.com/developer/webhooks-incoming.html#setting-up-existing-integrations">Mattermost webhook</a>.',
# }
. Output only the next line. | def get_success_url(self): |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
class WebhookDetailView(DetailView):
model = Webhook
class WebhookCreateView(SuccessMessageMixin, CreateView):
model = Webhook
form_class = WebhookCreateForm
success_message = "%(name)s was created successfully"
def form_valid(self, form):
form.instance.board_id = self.kwargs.get("board_id")
return super(WebhookCreateView, self).form_valid(form)
def get_context_data(self, **kwargs):
<|code_end|>
with the help of current file imports:
from django.contrib.auth.decorators import login_required
from django.contrib.messages.views import SuccessMessageMixin
from django.urls import reverse_lazy
from django.utils.decorators import method_decorator
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView
from core.models import Webhook, Board
from core.forms import WebhookCreateForm
and context from other files:
# Path: core/models.py
# class Webhook(models.Model):
#
# name = models.CharField(max_length=50)
# incoming_webhook_url = models.CharField(max_length=300, unique=True)
#
# icon_url = models.CharField(
# max_length=250,
# default="http://maffrigby.com/wp-content/uploads/2015/05/trello-icon.png",
# )
# username = models.CharField(max_length=30, default="Matterllo")
#
# board = models.ManyToManyField(Board)
#
# created_at = models.DateTimeField(auto_now_add=True)
# updated_at = models.DateTimeField(auto_now=True)
#
# class Meta:
# ordering = ["name"]
# verbose_name_plural = "webhooks"
#
# def __str__(self):
# return "{} :: {}".format(self.name, self.incoming_webhook_url)
#
# def __unicode__(self):
# return "{} :: {}".format(self.name, self.incoming_webhook_url)
#
# class Board(models.Model):
#
# name = models.CharField(max_length=100)
# webhook_activate = models.BooleanField(default=False)
# trello_board_id = models.CharField(max_length=100)
# trello_token = models.CharField(max_length=100)
# created_at = models.DateTimeField(auto_now_add=True)
# updated_at = models.DateTimeField(auto_now=True)
#
# class Meta:
# ordering = ["name"]
# verbose_name_plural = "boards"
#
# def __str__(self):
# return self.name
#
# def __unicode__(self):
# return "{}".format(self.name)
#
# Path: core/forms.py
# class WebhookCreateForm(forms.ModelForm):
# def __init__(self, *args, **kwargs):
# super(WebhookCreateForm, self).__init__(*args, **kwargs)
# helper = self.helper = FormHelper()
#
# layout = helper.layout = Layout()
# layout.append(Field("name", placeholder="webhook for town-square"))
# layout.append(
# Field(
# "incoming_webhook_url",
# placeholder="https://mattermost.gitlab.com/hooks/b5g6pyoqsjy88fa6kzn7xi1rzy",
# )
# )
# layout.append(FormActions(Submit("save", "Next")))
#
# helper.form_show_labels = False
# helper.form_class = "form-horizontal"
# helper.field_class = "col-lg-8"
# helper.help_text_inline = True
#
# class Meta:
# model = Webhook
# fields = ["name", "incoming_webhook_url"]
# help_texts = {
# "name": "The description.",
# "incoming_webhook_url": 'The generated url from <a href="https://docs.mattermost.com/developer/webhooks-incoming.html#setting-up-existing-integrations">Mattermost webhook</a>.',
# }
, which may contain function names, class names, or code. Output only the next line. | board_id = self.kwargs.get("board_id") |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
class WebhookDetailView(DetailView):
model = Webhook
class WebhookCreateView(SuccessMessageMixin, CreateView):
model = Webhook
form_class = WebhookCreateForm
success_message = "%(name)s was created successfully"
def form_valid(self, form):
form.instance.board_id = self.kwargs.get("board_id")
return super(WebhookCreateView, self).form_valid(form)
<|code_end|>
. Use current file imports:
from django.contrib.auth.decorators import login_required
from django.contrib.messages.views import SuccessMessageMixin
from django.urls import reverse_lazy
from django.utils.decorators import method_decorator
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView
from core.models import Webhook, Board
from core.forms import WebhookCreateForm
and context (classes, functions, or code) from other files:
# Path: core/models.py
# class Webhook(models.Model):
#
# name = models.CharField(max_length=50)
# incoming_webhook_url = models.CharField(max_length=300, unique=True)
#
# icon_url = models.CharField(
# max_length=250,
# default="http://maffrigby.com/wp-content/uploads/2015/05/trello-icon.png",
# )
# username = models.CharField(max_length=30, default="Matterllo")
#
# board = models.ManyToManyField(Board)
#
# created_at = models.DateTimeField(auto_now_add=True)
# updated_at = models.DateTimeField(auto_now=True)
#
# class Meta:
# ordering = ["name"]
# verbose_name_plural = "webhooks"
#
# def __str__(self):
# return "{} :: {}".format(self.name, self.incoming_webhook_url)
#
# def __unicode__(self):
# return "{} :: {}".format(self.name, self.incoming_webhook_url)
#
# class Board(models.Model):
#
# name = models.CharField(max_length=100)
# webhook_activate = models.BooleanField(default=False)
# trello_board_id = models.CharField(max_length=100)
# trello_token = models.CharField(max_length=100)
# created_at = models.DateTimeField(auto_now_add=True)
# updated_at = models.DateTimeField(auto_now=True)
#
# class Meta:
# ordering = ["name"]
# verbose_name_plural = "boards"
#
# def __str__(self):
# return self.name
#
# def __unicode__(self):
# return "{}".format(self.name)
#
# Path: core/forms.py
# class WebhookCreateForm(forms.ModelForm):
# def __init__(self, *args, **kwargs):
# super(WebhookCreateForm, self).__init__(*args, **kwargs)
# helper = self.helper = FormHelper()
#
# layout = helper.layout = Layout()
# layout.append(Field("name", placeholder="webhook for town-square"))
# layout.append(
# Field(
# "incoming_webhook_url",
# placeholder="https://mattermost.gitlab.com/hooks/b5g6pyoqsjy88fa6kzn7xi1rzy",
# )
# )
# layout.append(FormActions(Submit("save", "Next")))
#
# helper.form_show_labels = False
# helper.form_class = "form-horizontal"
# helper.field_class = "col-lg-8"
# helper.help_text_inline = True
#
# class Meta:
# model = Webhook
# fields = ["name", "incoming_webhook_url"]
# help_texts = {
# "name": "The description.",
# "incoming_webhook_url": 'The generated url from <a href="https://docs.mattermost.com/developer/webhooks-incoming.html#setting-up-existing-integrations">Mattermost webhook</a>.',
# }
. Output only the next line. | def get_context_data(self, **kwargs): |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
class BridgeCreateForm(forms.ModelForm):
events = forms.MultipleChoiceField(
choices=Bridge.EVENT_CHOICES,
widget=forms.CheckboxSelectMultiple,
)
def __init__(self, *args, **kwargs):
super(BridgeCreateForm, self).__init__(*args, **kwargs)
helper = self.helper = FormHelper()
<|code_end|>
, predict the immediate next line with the help of imports:
from crispy_forms.bootstrap import FormActions, Field
from crispy_forms.helper import FormHelper, Layout
from crispy_forms.layout import Submit, HTML
from django import forms
from core.models import Bridge, Webhook
and context (classes, functions, sometimes code) from other files:
# Path: core/models.py
# class Bridge(models.Model):
# EVENT_CHOICES = (
# # card
# ("addAttachmentToCard", "addAttachmentToCard"),
# ("addLabelToCard", "addLabelToCard"),
# ("addMemberToCard", "addMemberToCard"),
# ("commentCard", "commentCard"),
# ("copyCard", "copyCard"),
# ("createCard", "createCard"),
# ("emailCard", "emailCard"),
# ("moveCardFromBoard", "moveCardFromBoard"),
# ("moveCardToBoard", "moveCardToBoard"),
# ("removeLabelFromCard", "removeLabelFromCard"),
# ("removeMemberFromCard", "removeMemberFromCard"),
# (
# "updateCard",
# "updateCard (include moveCardToList, renameCard, renameCardDesc, updateCardDueDate, removeCardDueDate, archiveCard, unarchiveCard)",
# ),
# # checklist
# ("addChecklistToCard", "addChecklistToCard"),
# ("createCheckItem", "createCheckItem"),
# ("updateCheckItemStateOnCard", "updateCheckItemStateOnCard"),
# # list
# ("archiveList", "archiveList"),
# ("createList", "createList"),
# ("moveListFromBoard", "moveCardFromBoard"),
# ("moveListToBoard", "moveListToBoard"),
# ("renameList", "renameList"),
# ("updateList", "updateList"),
# )
#
# webhook = models.ForeignKey(Webhook, on_delete=models.CASCADE)
# board = models.ForeignKey(Board, on_delete=models.CASCADE)
#
# events = models.CharField(max_length=700)
#
# created_at = models.DateTimeField(auto_now_add=True)
# updated_at = models.DateTimeField(auto_now=True)
#
# class Meta:
# verbose_name_plural = "bridges"
#
# def __str__(self):
# return "{}::{}".format(self.board, self.webhook)
#
# def __unicode__(self):
# return "{}::{}".format(self.board, self.webhook)
#
# def events_as_list(self):
# return literal_eval(self.events)
#
# class Webhook(models.Model):
#
# name = models.CharField(max_length=50)
# incoming_webhook_url = models.CharField(max_length=300, unique=True)
#
# icon_url = models.CharField(
# max_length=250,
# default="http://maffrigby.com/wp-content/uploads/2015/05/trello-icon.png",
# )
# username = models.CharField(max_length=30, default="Matterllo")
#
# board = models.ManyToManyField(Board)
#
# created_at = models.DateTimeField(auto_now_add=True)
# updated_at = models.DateTimeField(auto_now=True)
#
# class Meta:
# ordering = ["name"]
# verbose_name_plural = "webhooks"
#
# def __str__(self):
# return "{} :: {}".format(self.name, self.incoming_webhook_url)
#
# def __unicode__(self):
# return "{} :: {}".format(self.name, self.incoming_webhook_url)
. Output only the next line. | layout = helper.layout = Layout() |
Based on the snippet: <|code_start|> HTML(
'<button class="btn btn-info" type="button" onclick="document.querySelectorAll(\'.board-event\').forEach(x => x.checked = false);">Uncheck all</button>'
)
)
)
layout.append(FormActions(Submit("save", "Save")))
helper.form_show_labels = False
helper.form_class = "form-horizontal"
helper.field_class = "col-lg-8"
helper.help_text_inline = True
class Meta:
model = Bridge
fields = ["events"]
help_texts = {
"events": 'The generated key from <a href="https://docs.mattermost.com/developer/webhooks-incoming.html#setting-up-existing-integrations">Mattermost webhook</a>.',
}
class WebhookCreateForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(WebhookCreateForm, self).__init__(*args, **kwargs)
helper = self.helper = FormHelper()
layout = helper.layout = Layout()
layout.append(Field("name", placeholder="webhook for town-square"))
layout.append(
Field(
"incoming_webhook_url",
<|code_end|>
, predict the immediate next line with the help of imports:
from crispy_forms.bootstrap import FormActions, Field
from crispy_forms.helper import FormHelper, Layout
from crispy_forms.layout import Submit, HTML
from django import forms
from core.models import Bridge, Webhook
and context (classes, functions, sometimes code) from other files:
# Path: core/models.py
# class Bridge(models.Model):
# EVENT_CHOICES = (
# # card
# ("addAttachmentToCard", "addAttachmentToCard"),
# ("addLabelToCard", "addLabelToCard"),
# ("addMemberToCard", "addMemberToCard"),
# ("commentCard", "commentCard"),
# ("copyCard", "copyCard"),
# ("createCard", "createCard"),
# ("emailCard", "emailCard"),
# ("moveCardFromBoard", "moveCardFromBoard"),
# ("moveCardToBoard", "moveCardToBoard"),
# ("removeLabelFromCard", "removeLabelFromCard"),
# ("removeMemberFromCard", "removeMemberFromCard"),
# (
# "updateCard",
# "updateCard (include moveCardToList, renameCard, renameCardDesc, updateCardDueDate, removeCardDueDate, archiveCard, unarchiveCard)",
# ),
# # checklist
# ("addChecklistToCard", "addChecklistToCard"),
# ("createCheckItem", "createCheckItem"),
# ("updateCheckItemStateOnCard", "updateCheckItemStateOnCard"),
# # list
# ("archiveList", "archiveList"),
# ("createList", "createList"),
# ("moveListFromBoard", "moveCardFromBoard"),
# ("moveListToBoard", "moveListToBoard"),
# ("renameList", "renameList"),
# ("updateList", "updateList"),
# )
#
# webhook = models.ForeignKey(Webhook, on_delete=models.CASCADE)
# board = models.ForeignKey(Board, on_delete=models.CASCADE)
#
# events = models.CharField(max_length=700)
#
# created_at = models.DateTimeField(auto_now_add=True)
# updated_at = models.DateTimeField(auto_now=True)
#
# class Meta:
# verbose_name_plural = "bridges"
#
# def __str__(self):
# return "{}::{}".format(self.board, self.webhook)
#
# def __unicode__(self):
# return "{}::{}".format(self.board, self.webhook)
#
# def events_as_list(self):
# return literal_eval(self.events)
#
# class Webhook(models.Model):
#
# name = models.CharField(max_length=50)
# incoming_webhook_url = models.CharField(max_length=300, unique=True)
#
# icon_url = models.CharField(
# max_length=250,
# default="http://maffrigby.com/wp-content/uploads/2015/05/trello-icon.png",
# )
# username = models.CharField(max_length=30, default="Matterllo")
#
# board = models.ManyToManyField(Board)
#
# created_at = models.DateTimeField(auto_now_add=True)
# updated_at = models.DateTimeField(auto_now=True)
#
# class Meta:
# ordering = ["name"]
# verbose_name_plural = "webhooks"
#
# def __str__(self):
# return "{} :: {}".format(self.name, self.incoming_webhook_url)
#
# def __unicode__(self):
# return "{} :: {}".format(self.name, self.incoming_webhook_url)
. Output only the next line. | placeholder="https://mattermost.gitlab.com/hooks/b5g6pyoqsjy88fa6kzn7xi1rzy", |
Predict the next line after this snippet: <|code_start|>
_FASTQ_TYPE_TO_FLAG = {"sanger": "sanger",
"illumina_1.3+": "illumina",
"illumina_1.5+": "illumina",
"illumina_1.8+": "sanger",
"solexa": "solexa"}
def _get_quality_type(in_file):
""" get fastq quality format. if multiple types are detected,
pick the first one. no quality type is found assume sanger """
fastq_format = detect_fastq_format(in_file)
return _FASTQ_TYPE_TO_FLAG.get(fastq_format[0], "sanger")
def _get_length_cutoff(config):
return config["stage"]["sickle"].get("length_cutoff", 20)
def _get_quality_cutoff(config):
return config["stage"]["sickle"].get("quality_cutoff", 20)
def run_with_config(first, second=None, config=None):
first_out = append_stem(first, "sickle")
second_out = None
if second:
out_files = run_as_pe(first, second, config)
return out_files
<|code_end|>
using the current file's imports:
import subprocess
import os
import sh
import logging
from bipy.utils import append_stem
from bipy.toolbox.fastqc import detect_fastq_format
and any relevant context from other files:
# Path: bipy/utils.py
# def append_stem(filename, word, delim="."):
# """ returns a filename with word appended to the stem
# example: /path/to/test.run.sam -> /path/to/test.run.sorted.sam """
# dirname = os.path.dirname(filename)
# filename = os.path.basename(filename)
# fsplit = filename.split(delim)
# fsplit.insert(len(fsplit) - 1, word)
# return os.path.join(dirname, delim.join(fsplit))
#
# Path: bipy/toolbox/fastqc.py
# def detect_fastq_format(in_file, MAX_RECORDS=1000000):
# """
# detects the format of a fastq file
# will return multiple formats if it could be more than one
# """
# logger.info("Detecting FASTQ format on %s." % (in_file))
# kept = list(_FASTQ_RANGES.keys())
# with open(in_file) as in_handle:
# records_read = 0
# for i, line in enumerate(in_handle):
# # get the quality line
# if records_read >= MAX_RECORDS:
# break
# if i % 4 is 3:
# records_read += 1
# for c in line:
# formats = kept
# if len(formats) == 1:
# return formats
# for form in formats:
# if (_FASTQ_RANGES[form][0] > ord(c) or
# _FASTQ_RANGES[form][1] < ord(c)):
# kept.remove(form)
#
# return formats
. Output only the next line. | else: |
Given the code snippet: <|code_start|>
logger = logging.getLogger("bipy")
_FASTQ_TYPE_TO_FLAG = {"sanger": "sanger",
"illumina_1.3+": "illumina",
"illumina_1.5+": "illumina",
"illumina_1.8+": "sanger",
"solexa": "solexa"}
def _get_quality_type(in_file):
""" get fastq quality format. if multiple types are detected,
pick the first one. no quality type is found assume sanger """
fastq_format = detect_fastq_format(in_file)
return _FASTQ_TYPE_TO_FLAG.get(fastq_format[0], "sanger")
def _get_length_cutoff(config):
return config["stage"]["sickle"].get("length_cutoff", 20)
def _get_quality_cutoff(config):
return config["stage"]["sickle"].get("quality_cutoff", 20)
def run_with_config(first, second=None, config=None):
first_out = append_stem(first, "sickle")
second_out = None
if second:
<|code_end|>
, generate the next line using the imports in this file:
import subprocess
import os
import sh
import logging
from bipy.utils import append_stem
from bipy.toolbox.fastqc import detect_fastq_format
and context (functions, classes, or occasionally code) from other files:
# Path: bipy/utils.py
# def append_stem(filename, word, delim="."):
# """ returns a filename with word appended to the stem
# example: /path/to/test.run.sam -> /path/to/test.run.sorted.sam """
# dirname = os.path.dirname(filename)
# filename = os.path.basename(filename)
# fsplit = filename.split(delim)
# fsplit.insert(len(fsplit) - 1, word)
# return os.path.join(dirname, delim.join(fsplit))
#
# Path: bipy/toolbox/fastqc.py
# def detect_fastq_format(in_file, MAX_RECORDS=1000000):
# """
# detects the format of a fastq file
# will return multiple formats if it could be more than one
# """
# logger.info("Detecting FASTQ format on %s." % (in_file))
# kept = list(_FASTQ_RANGES.keys())
# with open(in_file) as in_handle:
# records_read = 0
# for i, line in enumerate(in_handle):
# # get the quality line
# if records_read >= MAX_RECORDS:
# break
# if i % 4 is 3:
# records_read += 1
# for c in line:
# formats = kept
# if len(formats) == 1:
# return formats
# for form in formats:
# if (_FASTQ_RANGES[form][0] > ord(c) or
# _FASTQ_RANGES[form][1] < ord(c)):
# kept.remove(form)
#
# return formats
. Output only the next line. | out_files = run_as_pe(first, second, config) |
Predict the next line for this snippet: <|code_start|>
STAGENAME = "piranha"
class TestPiranha(unittest.TestCase):
def setUp(self):
self.config_file = os.path.join("test", STAGENAME, "test_" +
STAGENAME + ".yaml")
<|code_end|>
with the help of current file imports:
import yaml
import unittest
import os
from bipy.toolbox import piranha
from bcbio.utils import safe_makedir, file_exists
from bipy.toolbox import reporting
from bipy.utils import in2out
and context from other files:
# Path: bipy/toolbox/piranha.py
# def run(in_file, bin_size=30, covariate=None, out_file=None):
# def __init__(self, config):
# def _start_message(self, in_file):
# def _end_message(self, in_file):
# def _check_run(self, in_file):
# def __call__(self, in_file):
# class PiranhaStage(AbstractStage):
#
# Path: bipy/toolbox/reporting.py
# def safe_latex(to_fix):
# def generate_pdf(self, sections=None, out_file=None):
# def template(self):
# def generate_report(self, *args, **kwargs):
# def make_latex_table_header(length):
# def panda_to_latex(table, caption=""):
# def _panda_row_to_latex_row(row):
# class LatexPdf(object):
# class LatexReport(object):
#
# Path: bipy/utils.py
# def in2out(in_file, word, transform=True, out_dir=None):
# """
# creates an out_file name from an in_file name by adding word to the
# in_file name and writing it to the output_directory if specified.
# if transform is True, the word replaces the extension of in_file.
# if False it adds it to the stem
# transform: in2out("test.bam", "sam", transform=True) -> "test.sam"
# non transform: in2out("test.bam", "sam", transform=False) -> "test_bam.sam"
#
# """
# (base, ext) = os.path.splitext(in_file)
# if out_dir:
# base = os.path.join(out_dir, os.path.basename(base))
#
# if transform:
# return "%s.%s" % (base, word)
#
# else:
# return "%s_%s.%s" % (base, ext, word)
, which may contain function names, class names, or code. Output only the next line. | with open(self.config_file) as in_handle: |
Using the snippet: <|code_start|>
class TestPiranha(unittest.TestCase):
def setUp(self):
self.config_file = os.path.join("test", STAGENAME, "test_" +
STAGENAME + ".yaml")
with open(self.config_file) as in_handle:
self.config = yaml.load(in_handle)
self.in_file = self.config["input"]
self.stage_config = self.config["stage"][STAGENAME]
self.bin_size = self.stage_config.get("bin_size", 30)
self.covariate = self.stage_config.get("covariate", None)
self.out_dir = os.path.join("results", "test", STAGENAME)
def test_run(self):
exp_out = in2out(self.in_file, "piranha.bed", transform=True,
out_dir = self.out_dir)
print exp_out
out_file = piranha.run(self.in_file, bin_size=self.bin_size,
covariate=self.covariate, out_file=exp_out)
print out_file
self.assertTrue(file_exists(out_file))
self.assertTrue(exp_out == out_file)
os.remove(out_file)
def test_stage_wrapper(self):
exp_out = in2out(self.in_file, "piranha.bed", transform=True,
<|code_end|>
, determine the next line of code. You have imports:
import yaml
import unittest
import os
from bipy.toolbox import piranha
from bcbio.utils import safe_makedir, file_exists
from bipy.toolbox import reporting
from bipy.utils import in2out
and context (class names, function names, or code) available:
# Path: bipy/toolbox/piranha.py
# def run(in_file, bin_size=30, covariate=None, out_file=None):
# def __init__(self, config):
# def _start_message(self, in_file):
# def _end_message(self, in_file):
# def _check_run(self, in_file):
# def __call__(self, in_file):
# class PiranhaStage(AbstractStage):
#
# Path: bipy/toolbox/reporting.py
# def safe_latex(to_fix):
# def generate_pdf(self, sections=None, out_file=None):
# def template(self):
# def generate_report(self, *args, **kwargs):
# def make_latex_table_header(length):
# def panda_to_latex(table, caption=""):
# def _panda_row_to_latex_row(row):
# class LatexPdf(object):
# class LatexReport(object):
#
# Path: bipy/utils.py
# def in2out(in_file, word, transform=True, out_dir=None):
# """
# creates an out_file name from an in_file name by adding word to the
# in_file name and writing it to the output_directory if specified.
# if transform is True, the word replaces the extension of in_file.
# if False it adds it to the stem
# transform: in2out("test.bam", "sam", transform=True) -> "test.sam"
# non transform: in2out("test.bam", "sam", transform=False) -> "test_bam.sam"
#
# """
# (base, ext) = os.path.splitext(in_file)
# if out_dir:
# base = os.path.join(out_dir, os.path.basename(base))
#
# if transform:
# return "%s.%s" % (base, word)
#
# else:
# return "%s_%s.%s" % (base, ext, word)
. Output only the next line. | out_dir = self.out_dir) |
Given the following code snippet before the placeholder: <|code_start|> correct_file = [os.path.join(cur_dir, "data", "correct_fastqc.txt"),
os.path.join(cur_dir, "data", "correct_fastqc.txt")]
run_result = self.stage(input_paired)
out_table = map(self._get_result, run_result)
self.assertTrue(all(map(file_exists, out_table)))
shutil.rmtree(os.path.join(cur_dir, "results"))
def test_fastqc_threads(self):
config = self.config
config["stage"]["fastqc"]["options"] = ["--threads", 2]
stage = fastqc.FastQC(config)
input_file = self.config["input_single"]
correct_file = os.path.join(cur_dir, "data", "correct_fastqc.txt")
run_result = stage(input_file)
out_table = self._get_result(run_result)
self.assertTrue(file_exists(out_table))
shutil.rmtree(os.path.join(cur_dir, "results"))
def test_fastqc_fq_extension(self):
base, ext = os.path.splitext(self.config["input_single"])
fq_file = base + ".fq"
os.symlink(os.path.basename(self.config["input_single"]), fq_file)
out_file = self.stage(fq_file)
self.assertTrue(file_exists(out_file))
os.unlink(out_file)
os.unlink(fq_file)
if __name__ == "__main__":
<|code_end|>
, predict the next line using imports from the current file:
import yaml
import unittest
import os
import filecmp
import shutil
from bipy.toolbox import fastqc
from bcbio.utils import file_exists
and context including class names, function names, and sometimes code from other files:
# Path: bipy/toolbox/fastqc.py
# _FASTQ_RANGES = {"sanger": [33, 73],
# "solexa": [59, 104],
# "illumina_1.3+": [64, 104],
# "illumina_1.5+": [66, 104],
# "illumina_1.8+": [33, 74]}
# MODULE_NAMES = ["Basic Statistics", "Per base sequence quality",
# "Per sequence quality scores",
# "Per base sequence content",
# "Per base GC content",
# "Per sequence GC content",
# "Per base N content",
# "Sequence Length Distribution",
# "Overrepresented sequences"]
# GRAPHS = (("per_base_quality.png", "", 1.0),
# ("per_base_sequence_content.png", "", 0.85),
# ("per_sequence_gc_content.png", "", 0.85),
# ("kmer_profiles.png", "", 0.85),
# ("duplication_levels.png", "", 0.85),
# ("per_bases_n_content.png", "", 0.85),
# ("per_sequence_quality.png", "", 1.0),
# ("sequence_length_distribution.png", "", 1.0))
# REPORT_LOOKUP = {"rnaseq": RNASeqFastQCReport}
# CAPTIONS = {"per_base_quality.png": "",
# "per_base_sequence_content.png": "",
# "per_sequence_gc_content.png": "",
# "kmer_profiles.png": "",
# "duplication_levels.png": "",
# "per_bases_n_content.png": "",
# "per_sequence_quality.png": "",
# "sequence_length_distribution.png": ""}
# CAPTIONS = {"per_base_quality.png": "",
# "per_base_sequence_content.png": "",
# "per_sequence_gc_content.png": "",
# "kmer_profiles.png": "",
# "duplication_levels.png": "",
# "per_bases_n_content.png": "",
# "per_sequence_quality.png": "",
# "sequence_length_distribution.png": ""}
# def detect_fastq_format(in_file, MAX_RECORDS=1000000):
# def _make_outdir(config):
# def _make_outfile(input_file, config):
# def _build_command(input_file, fastqc_config, config):
# def run(input_file, fastqc_config, config):
# def __init__(self, base_dir):
# def get_fastqc_graphs(self):
# def get_fastqc_summary(self):
# def _fastqc_data_section(self, section_name):
# def report(base_dir, report_type=None):
# def template(self):
# def _add_captions(self, figures):
# def generate_report(self, name=None, summary=None, figures=None,
# overrep=None):
# def __init__(self, config):
# def _start_message(self, in_file):
# def _end_message(self, in_file, out_file):
# def _memoized_message(self, in_file, out_file):
# def _check_run(self, in_file):
# def __call__(self, in_file):
# class FastQCParser(object):
# class FastQCReport(LatexReport):
# class RNASeqFastQCReport(FastQCReport):
# class FastQC(AbstractStage):
. Output only the next line. | suite = unittest.TestLoader().loadTestsFromTestCase(TestFastqc) |
Given snippet: <|code_start|>
CONFIG_FILE = "test/novoalign/test_novoalign.yaml"
class TestNovoalign(unittest.TestCase):
def setUp(self):
with open(CONFIG_FILE) as in_handle:
self.config = yaml.load(in_handle)
self.input_files = self.config["input"]
self.db = os.path.basename(replace_suffix(self.config["ref"], "nix"))
self.db = os.path.join(self.config["dir"]["ref"], self.db)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from bipy.toolbox import novoindex, novoalign
from bipy.utils import replace_suffix
import yaml
import sys
import unittest
import os
and context:
# Path: bipy/toolbox/novoindex.py
# def _build_output_file(input_file, config):
# def _build_command(input_file, novoindex_config, output_file):
# def run(input_file, novoindex_config, config):
#
# Path: bipy/toolbox/novoalign.py
# def _build_output_file(input_file, novoalign_config, config):
# def _build_command(input_file, ref, novoalign_config):
# def run(input_file, ref, novoalign_config, config):
#
# Path: bipy/utils.py
# def replace_suffix(filename, suffix, delim="."):
# """ returns a filename with the suffix replaced
# with a new suffix
# exampoe: /path/to/test.run.sam -> /path/to/test.run.fa"""
# dirname = os.path.dirname(filename)
# filename = os.path.basename(filename)
# fsplit = filename.split(delim)[:-1]
# fsplit.append(suffix)
# return os.path.join(dirname, delim.join(fsplit))
which might include code, classes, or functions. Output only the next line. | def test_novoindex(self): |
Predict the next line after this snippet: <|code_start|>
CONFIG_FILE = "test/novoalign/test_novoalign.yaml"
class TestNovoalign(unittest.TestCase):
def setUp(self):
with open(CONFIG_FILE) as in_handle:
self.config = yaml.load(in_handle)
self.input_files = self.config["input"]
self.db = os.path.basename(replace_suffix(self.config["ref"], "nix"))
self.db = os.path.join(self.config["dir"]["ref"], self.db)
def test_novoindex(self):
stage_config = self.config["stage"]["novoindex"]
self.db = novoindex.run(self.config["ref"],
stage_config,
self.config)
self.assertTrue(os.path.exists(self.db))
self.assertTrue(os.path.getsize(self.db) > 0)
<|code_end|>
using the current file's imports:
from bipy.toolbox import novoindex, novoalign
from bipy.utils import replace_suffix
import yaml
import sys
import unittest
import os
and any relevant context from other files:
# Path: bipy/toolbox/novoindex.py
# def _build_output_file(input_file, config):
# def _build_command(input_file, novoindex_config, output_file):
# def run(input_file, novoindex_config, config):
#
# Path: bipy/toolbox/novoalign.py
# def _build_output_file(input_file, novoalign_config, config):
# def _build_command(input_file, ref, novoalign_config):
# def run(input_file, ref, novoalign_config, config):
#
# Path: bipy/utils.py
# def replace_suffix(filename, suffix, delim="."):
# """ returns a filename with the suffix replaced
# with a new suffix
# exampoe: /path/to/test.run.sam -> /path/to/test.run.fa"""
# dirname = os.path.dirname(filename)
# filename = os.path.basename(filename)
# fsplit = filename.split(delim)[:-1]
# fsplit.append(suffix)
# return os.path.join(dirname, delim.join(fsplit))
. Output only the next line. | def test_novoalign(self): |
Predict the next line for this snippet: <|code_start|>
CONFIG_FILE = "test/novoalign/test_novoalign.yaml"
class TestNovoalign(unittest.TestCase):
def setUp(self):
with open(CONFIG_FILE) as in_handle:
self.config = yaml.load(in_handle)
self.input_files = self.config["input"]
self.db = os.path.basename(replace_suffix(self.config["ref"], "nix"))
self.db = os.path.join(self.config["dir"]["ref"], self.db)
def test_novoindex(self):
stage_config = self.config["stage"]["novoindex"]
self.db = novoindex.run(self.config["ref"],
stage_config,
self.config)
self.assertTrue(os.path.exists(self.db))
self.assertTrue(os.path.getsize(self.db) > 0)
def test_novoalign(self):
stage_config = self.config["stage"]["novoalign"]
for input_file in self.input_files:
output_file = novoalign.run(input_file,
self.db,
stage_config,
<|code_end|>
with the help of current file imports:
from bipy.toolbox import novoindex, novoalign
from bipy.utils import replace_suffix
import yaml
import sys
import unittest
import os
and context from other files:
# Path: bipy/toolbox/novoindex.py
# def _build_output_file(input_file, config):
# def _build_command(input_file, novoindex_config, output_file):
# def run(input_file, novoindex_config, config):
#
# Path: bipy/toolbox/novoalign.py
# def _build_output_file(input_file, novoalign_config, config):
# def _build_command(input_file, ref, novoalign_config):
# def run(input_file, ref, novoalign_config, config):
#
# Path: bipy/utils.py
# def replace_suffix(filename, suffix, delim="."):
# """ returns a filename with the suffix replaced
# with a new suffix
# exampoe: /path/to/test.run.sam -> /path/to/test.run.fa"""
# dirname = os.path.dirname(filename)
# filename = os.path.basename(filename)
# fsplit = filename.split(delim)[:-1]
# fsplit.append(suffix)
# return os.path.join(dirname, delim.join(fsplit))
, which may contain function names, class names, or code. Output only the next line. | self.config) |
Continue the code snippet: <|code_start|>
STAGENAME = "trim_galore"
class TestTrimgalore(unittest.TestCase):
def setUp(self):
self.config_file = "test/trim_galore/test_trim_galore.yaml"
with open(self.config_file) as in_handle:
self.config = yaml.load(in_handle)
<|code_end|>
. Use current file imports:
import yaml
import unittest
import os
import filecmp
from bipy.toolbox import trim
and context (classes, functions, or code) from other files:
# Path: bipy/toolbox/trim.py
# ADAPTERS = yaml.load(in_handle)
# class TrimGalore(AbstractStage):
# class Cutadapt(AbstractStage):
# def __init__(self, config):
# def get_adapters(self, chemistry):
# def _in2out(self, in_file):
# def __call__(self, in_file):
# def __init__(self, config):
# def _detect_fastq_format(self, in_file):
# def in2trimmed(self, in_file):
# def _get_adapters(self, chemistry):
# def _rc_adapters(self, adapters):
# def _cut_file(self, in_file):
# def _get_lf_file(self, in_file):
# def _run_se(self, in_file):
# def _run_pe(self, in_files):
# def __call__(self, in_file):
. Output only the next line. | self.input_file = self.config["input"] |
Given snippet: <|code_start|>
CONFIG_FILE = "test/bowtie/test_bowtie.yaml"
class TestBowtie(unittest.TestCase):
def setUp(self):
with open(CONFIG_FILE) as in_handle:
self.config = yaml.load(in_handle)
self.stage_config = self.config["stage"]["bowtie"]
def test_single(self):
correct_file = self.config["input_single_correct"]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from bipy.toolbox.tophat import Bowtie
from bcbio.utils import file_exists
import yaml
import unittest
import filecmp
import os
and context:
# Path: bipy/toolbox/tophat.py
# class Bowtie(AbstractStage):
#
# stage = "bowtie"
#
# def __init__(self, config):
# self.config = config
# self.stage_config = config["stage"][self.stage]
# # defaults = {"q": True, "n": 2, "k": 1,
# # "X": 2000, "best": True,
# # "sam": True,
# # "phred64-quals": True}
# #self.options = dict(defaults.items() +
# # self.stage_config.get("options", {}).items())
# self.options = self.stage_config.get("options", {})
# self.bowtie = sh.Command(self.stage_config.get("program", "bowtie"))
# self.out_prefix = os.path.join(get_in(self.config,
# ("dir", "results"), "results"),
# self.stage)
# self.ref_file = self.config["ref"]
# if not any_bowtie_reference_exists(self.ref_file):
# bowtie_reference_not_found_error()
#
# def _bowtie_se(self, in_file, out_file):
# self.bowtie(self.options, self.ref_file, in_file, out_file)
#
# def _bowtie_pe(self, in_file, out_file):
# self.bowtie(self.options, self.ref_file,
# "-1", in_file[0], "-2", in_file[1], out_file)
#
# def _get_out_file(self, in_file):
# base, _ = os.path.splitext(os.path.basename(in_file))
# out_prefix = os.path.join(get_in(self.config,
# ("dir", "results"), "results"),
# self.stage)
# out_dir = os.path.join(out_prefix, base)
# out_file = os.path.join(out_dir, base + ".sam")
# return out_file
#
# def out_file(self, in_file):
# if is_pair(in_file):
# return self._get_out_file(in_file[0])
# else:
# return self._get_out_file(in_file)
#
# def __call__(self, in_file):
# self._start_message(in_file)
# out_file = self.out_file(in_file)
#
# if file_exists(out_file):
# return out_file
#
# with file_transaction(out_file) as tmp_out_file:
# if is_pair(in_file):
# self._bowtie_pe(in_file, tmp_out_file)
# else:
# self._bowtie_se(in_file, tmp_out_file)
# self._end_message(in_file)
#
# return out_file
which might include code, classes, or functions. Output only the next line. | single = self.config["input_single"] |
Here is a snippet: <|code_start|> self.assertTrue(isinstance(repository, StageRepository))
def test_builtin_plugins(self):
"""
test that we can find some of the built in plugins
"""
fastqc = self.repository["fastqc"]
self.assertTrue(issubclass(fastqc, AbstractStage))
def test_custom_plugins(self):
"""
test that the custom plugin directory is working
"""
plugin_file = self._make_test_class()
plugin_dir = os.path.dirname(plugin_file.name)
repo = StageRepository({"dir": {"plugins": plugin_dir}})
testplugin = repo["test_plugin"](self.config)
self.assertTrue(testplugin("Test") == "Test")
def _make_test_class(self):
temp = tempfile.NamedTemporaryFile(suffix=".py")
test_class = """
from bipy.pipeline.stages import AbstractStage
class TestPlugin(AbstractStage):
stage = "test_plugin"
<|code_end|>
. Write the next line using the current file imports:
import yaml
import unittest
import os
import tempfile
from bipy.pipeline.stages import AbstractStage
from bipy.plugins import StageRepository
from bcbio.utils import safe_makedir
and context from other files:
# Path: bipy/pipeline/stages.py
# class AbstractStage(object):
# """
# Wrapper around a stage for use with the pipeline manager. Subclasses should
# implement their own __init__ in addition to calling the super
# __init__. __init__ should parse the appropriate information from the config
# dict and save it in the objects state. __call__ should be implemented as a
# pure function with no closures.
#
# """
#
# stage = "abstract"
#
# def __init__(self, config):
# self.config = config
# self._validate_config()
#
# def _start_message(self, in_file, **kwargs):
# if kwargs:
# logger.info("Starting %s on %s with arguments %s." % (self.stage,
# in_file,
# kwargs))
# else:
# logger.info("Starting %s on %s." % (self.stage, in_file))
#
# def _end_message(self, in_file):
# logger.info("%s complete on %s." % (self.stage, in_file))
#
# def _check_run(self, in_file):
# if not file_exists(in_file):
# raise IOError("%s not found." % (in_file))
#
# def __call__(self, in_file):
# pass
#
# def _validate_config(self):
# if "stage" not in self.config:
# raise ValueError('Could not find "stage" in the config file.')
#
# Path: bipy/plugins.py
# class StageRepository(object):
# """
# builds a repository of all of the stage objects. loads all of the
# AbstractStage objects in the toolbox directory and adds to it anything
# in the plugins directory.
#
# will overwrite the main toolbox stages with the ones in the plugins
# directory
#
# """
#
# def __init__(self, config):
# self.config = config
# self.plugins = {}
# #self.scan(get_in(config, "dir", "plugins"))
# plugin_dir = get_in(config, ("dir", "plugins"))
# if plugin_dir:
# logger.info("Scanning %s for plugins." % plugin_dir)
# plugins = types.ModuleType("plugins")
# plugins.__path__ = [plugin_dir]
# sys.modules["plugins"] = plugins
# self.scan(plugin_dir)
# else:
# self.scan()
#
# def scan(self, plugin_dir=None):
#
# files = os.listdir(PluginDirectory)
# if plugin_dir:
# sys.path.append(plugin_dir)
# files += os.listdir(plugin_dir)
#
# plugins = []
# for fn in files:
# if fn.endswith('.py'):
# plugins.append(fn)
# mods = [fn.split('.')[0] for fn in plugins]
# # build the map of plugins
# for modname in mods:
# try:
# mod = import_(modname, PackagePrefix)
# except:
# logger.error("Error loading plugin: %s" % modname)
# traceback.print_exc()
# continue
# self.scan_module(mod)
#
# def scan_module(self, mod):
# ns = dir(mod)
# for name in ns:
# # skip over the base class
# thing = getattr(mod, name)
# if thing == AbstractStage:
# continue
# if type(thing) is not type:
# continue
# if issubclass(thing, AbstractStage):
# # found a plugin!
# self.plugins[thing.stage] = thing
#
# def __getitem__(self, key):
# return self.plugins.get(key, None)
, which may include functions, classes, or code. Output only the next line. | def __init__(self, config): |
Predict the next line for this snippet: <|code_start|> """
repository = StageRepository(self.config)
self.assertTrue(isinstance(repository, StageRepository))
def test_builtin_plugins(self):
"""
test that we can find some of the built in plugins
"""
fastqc = self.repository["fastqc"]
self.assertTrue(issubclass(fastqc, AbstractStage))
def test_custom_plugins(self):
"""
test that the custom plugin directory is working
"""
plugin_file = self._make_test_class()
plugin_dir = os.path.dirname(plugin_file.name)
repo = StageRepository({"dir": {"plugins": plugin_dir}})
testplugin = repo["test_plugin"](self.config)
self.assertTrue(testplugin("Test") == "Test")
def _make_test_class(self):
temp = tempfile.NamedTemporaryFile(suffix=".py")
test_class = """
from bipy.pipeline.stages import AbstractStage
class TestPlugin(AbstractStage):
<|code_end|>
with the help of current file imports:
import yaml
import unittest
import os
import tempfile
from bipy.pipeline.stages import AbstractStage
from bipy.plugins import StageRepository
from bcbio.utils import safe_makedir
and context from other files:
# Path: bipy/pipeline/stages.py
# class AbstractStage(object):
# """
# Wrapper around a stage for use with the pipeline manager. Subclasses should
# implement their own __init__ in addition to calling the super
# __init__. __init__ should parse the appropriate information from the config
# dict and save it in the objects state. __call__ should be implemented as a
# pure function with no closures.
#
# """
#
# stage = "abstract"
#
# def __init__(self, config):
# self.config = config
# self._validate_config()
#
# def _start_message(self, in_file, **kwargs):
# if kwargs:
# logger.info("Starting %s on %s with arguments %s." % (self.stage,
# in_file,
# kwargs))
# else:
# logger.info("Starting %s on %s." % (self.stage, in_file))
#
# def _end_message(self, in_file):
# logger.info("%s complete on %s." % (self.stage, in_file))
#
# def _check_run(self, in_file):
# if not file_exists(in_file):
# raise IOError("%s not found." % (in_file))
#
# def __call__(self, in_file):
# pass
#
# def _validate_config(self):
# if "stage" not in self.config:
# raise ValueError('Could not find "stage" in the config file.')
#
# Path: bipy/plugins.py
# class StageRepository(object):
# """
# builds a repository of all of the stage objects. loads all of the
# AbstractStage objects in the toolbox directory and adds to it anything
# in the plugins directory.
#
# will overwrite the main toolbox stages with the ones in the plugins
# directory
#
# """
#
# def __init__(self, config):
# self.config = config
# self.plugins = {}
# #self.scan(get_in(config, "dir", "plugins"))
# plugin_dir = get_in(config, ("dir", "plugins"))
# if plugin_dir:
# logger.info("Scanning %s for plugins." % plugin_dir)
# plugins = types.ModuleType("plugins")
# plugins.__path__ = [plugin_dir]
# sys.modules["plugins"] = plugins
# self.scan(plugin_dir)
# else:
# self.scan()
#
# def scan(self, plugin_dir=None):
#
# files = os.listdir(PluginDirectory)
# if plugin_dir:
# sys.path.append(plugin_dir)
# files += os.listdir(plugin_dir)
#
# plugins = []
# for fn in files:
# if fn.endswith('.py'):
# plugins.append(fn)
# mods = [fn.split('.')[0] for fn in plugins]
# # build the map of plugins
# for modname in mods:
# try:
# mod = import_(modname, PackagePrefix)
# except:
# logger.error("Error loading plugin: %s" % modname)
# traceback.print_exc()
# continue
# self.scan_module(mod)
#
# def scan_module(self, mod):
# ns = dir(mod)
# for name in ns:
# # skip over the base class
# thing = getattr(mod, name)
# if thing == AbstractStage:
# continue
# if type(thing) is not type:
# continue
# if issubclass(thing, AbstractStage):
# # found a plugin!
# self.plugins[thing.stage] = thing
#
# def __getitem__(self, key):
# return self.plugins.get(key, None)
, which may contain function names, class names, or code. Output only the next line. | stage = "test_plugin" |
Given the following code snippet before the placeholder: <|code_start|>
class TestDss(unittest.TestCase):
def setUp(self):
self.count_file = "test/data/pasilla_gene_counts.tsv"
self.conds = ["untreat", "untreat", "untreat", "untreat",
"treat", "treat", "treat"]
def test_run(self):
<|code_end|>
, predict the next line using imports from the current file:
from bipy.toolbox import dss
from bcbio.utils import safe_makedir, file_exists
import os
import unittest
and context including class names, function names, and sometimes code from other files:
# Path: bipy/toolbox/dss.py
# def _plot_disp_ests(r, dispersion_plot_out):
# def _plot_MvA(r, mva_plot_out):
# def load_count_file_as_matrix(in_file, r):
# def make_count_set(conds, r):
# def run(in_file, conds, tests, out_prefix):
. Output only the next line. | out_prefix = "results/tests/dss/test_dss" |
Given the code snippet: <|code_start|>
if file_exists(out_file):
return out_file
if exclude:
exclude_arg = "-v"
else:
exclude_arg = "-u"
sh.bedtools.intersect(exclude_arg, "-abam", bam_file, b=bed_file,
_out=out_file)
return out_file
def count_overlaps(in_file, bed, out_file=None):
""" calculates coverage across the features in the bedfile
bed """
if not which("coverageBed"):
logger.error("Cannot find coverageBed. Make sure it is in your "
"path or install bedtools.")
exit(-1)
if not out_file:
out_file = replace_suffix(in_file, ".counts")
if os.path.exists(out_file):
return out_file
<|code_end|>
, generate the next line using the imports in this file:
import subprocess
import os
import logging
import sh
from bipy.utils import (replace_suffix, which, flatten,
remove_suffix)
from bcbio.utils import file_exists
and context (functions, classes, or occasionally code) from other files:
# Path: bipy/utils.py
# def replace_suffix(filename, suffix, delim="."):
# """ returns a filename with the suffix replaced
# with a new suffix
# exampoe: /path/to/test.run.sam -> /path/to/test.run.fa"""
# dirname = os.path.dirname(filename)
# filename = os.path.basename(filename)
# fsplit = filename.split(delim)[:-1]
# fsplit.append(suffix)
# return os.path.join(dirname, delim.join(fsplit))
#
# def which(program):
# """ returns the path to an executable"""
#
# def is_exe(fpath):
# return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
#
# fpath, fname = os.path.split(program)
# if fpath:
# if is_exe(program):
# return program
# else:
# for path in os.environ["PATH"].split(os.pathsep):
# exe_file = os.path.join(path, program)
# if is_exe(exe_file):
# return exe_file
#
# return None
#
# def flatten(l):
# for el in l:
# if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
# for sub in flatten(el):
# yield sub
# else:
# yield el
#
# def remove_suffix(filename):
# filename, extension = os.path.splitext(filename)
# return filename
. Output only the next line. | cmd = ["coverageBed", "-abam", in_file, "-b", bed] |
Given the code snippet: <|code_start|>"""reporting.py provides classes to inherit from to provide output
reports for stages of pipelines.
"""
def safe_latex(to_fix):
"""Escape characters that make LaTeX unhappy.
Lifted from Brad Chapman (bcbio)
"""
chars = ["%", "_", "&", "#"]
for char in chars:
to_fix = to_fix.replace(char, "\\%s" % char)
return to_fix
class LatexPdf(object):
"""Generates a PDF document from a list of sections.
usage: generate_pdf(sections)"""
@classmethod
def generate_pdf(self, sections=None, out_file=None):
out_tmpl = Template(self._base_template)
if not out_file:
<|code_end|>
, generate the next line using the imports in this file:
from mako.template import Template
from itertools import repeat
from bipy.utils import remove_suffix
from bcbio.distributed.transaction import file_transaction
from bcbio.utils import curdir_tmpdir
import sh
import os
import abc
import shutil
and context (functions, classes, or occasionally code) from other files:
# Path: bipy/utils.py
# def remove_suffix(filename):
# filename, extension = os.path.splitext(filename)
# return filename
. Output only the next line. | latex_file = "latex.tex" |
Using the snippet: <|code_start|>
logger = logging.getLogger('config_test')
logger.setLevel(logging.INFO)
class ConfigValidator(object):
def __init__(self):
<|code_end|>
, determine the next line of code. You have imports:
import unittest
import yaml
import logging
import os
from bcbio.utils import file_exists
from bipy.utils import which
and context (class names, function names, or code) available:
# Path: bipy/utils.py
# def which(program):
# """ returns the path to an executable"""
#
# def is_exe(fpath):
# return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
#
# fpath, fname = os.path.split(program)
# if fpath:
# if is_exe(program):
# return program
# else:
# for path in os.environ["PATH"].split(os.pathsep):
# exe_file = os.path.join(path, program)
# if is_exe(exe_file):
# return exe_file
#
# return None
. Output only the next line. | pass |
Predict the next line for this snippet: <|code_start|>TOPHAT_2_CONFIG = "test/tophat/test_tophat2_bowtie2.yaml"
def _load_config(config_file):
with open(config_file) as in_handle:
config = yaml.load(in_handle)
return config
def _run_fixture(input_files, config):
if len(input_files) == 2:
out_file = tophat.run_with_config(input_files[0], input_files[1],
config["ref"], "tophat", config)
else:
out_file = tophat.run_with_config(input_files[0], None,
config["ref"], "tophat", config)
return out_file
class TestTophat(unittest.TestCase):
def setUp(self):
pass
def test_run_with_config_tophat1(self):
config = _load_config(TOPHAT_1_CONFIG)
for input_files in config["input"]:
out_file = _run_fixture(input_files, config)
self.assertTrue(file_exists(out_file))
def test_run_with_config_tophat2(self):
config = _load_config(TOPHAT_2_CONFIG)
<|code_end|>
with the help of current file imports:
import yaml
import unittest
import os
import tempfile
import shutil
from bipy.toolbox import tophat
from bcbio.utils import file_exists
and context from other files:
# Path: bipy/toolbox/tophat.py
# FASTQ_FORMAT_TO_BCBIO = {"sanger": None,
# "illumina_1.3+": "illumina",
# "illumina_1.5+": "illumina",
# "illumina_1.8+": None,
# "solexa": "solexa"}
# def run_with_config(fastq_file, pair_file, ref_file,
# stage_name, config):
# def _bcbio_tophat_wrapper(fastq_file, pair_file, ref_file,
# stage_name, config):
# def __init__(self, config):
# def __call__(self, in_file):
# def __init__(self, config):
# def _bowtie_se(self, in_file, out_file):
# def _bowtie_pe(self, in_file, out_file):
# def _get_out_file(self, in_file):
# def out_file(self, in_file):
# def __call__(self, in_file):
# def any_bowtie_reference_exists(prefix):
# def bowtie_1_reference_exists(prefix):
# def bowtie_2_reference_exists(prefix):
# def bowtie_reference_not_found_error():
# class Tophat(AbstractStage):
# class Bowtie(AbstractStage):
, which may contain function names, class names, or code. Output only the next line. | for input_files in config["input"]: |
Next line prediction: <|code_start|>
def program_exists(path):
return which(path)
def _results_dir(config, prefix=""):
def _make_dir(base):
out_dir = os.path.join(base, "rseqc",
prefix)
safe_makedir(out_dir)
return out_dir
if "dir" not in config:
return _make_dir("results")
if "results" not in config["dir"]:
return _make_dir("results")
else:
return _make_dir(config["dir"]["results"])
def _fetch_chrom_sizes(config):
PROGRAM = "fetchChromSizes"
<|code_end|>
. Use current file imports:
(import os
import sh
import glob
import pandas as pd
from bipy.utils import (replace_suffix, which, remove_suffix, append_stem,
prepare_ref_file)
from bcbio.utils import file_exists, safe_makedir, add_full_path
from math import sqrt
from mako.template import Template
from bipy.toolbox.reporting import LatexReport, safe_latex
from bcbio.distributed.transaction import file_transaction
from bipy.pipeline.stages import AbstractStage
from bcbio.broad import BroadRunner, picardrun
from bcbio.log import logger
from bcbio.provenance import do)
and context including class names, function names, or small code snippets from other files:
# Path: bipy/utils.py
# def replace_suffix(filename, suffix, delim="."):
# """ returns a filename with the suffix replaced
# with a new suffix
# exampoe: /path/to/test.run.sam -> /path/to/test.run.fa"""
# dirname = os.path.dirname(filename)
# filename = os.path.basename(filename)
# fsplit = filename.split(delim)[:-1]
# fsplit.append(suffix)
# return os.path.join(dirname, delim.join(fsplit))
#
# def which(program):
# """ returns the path to an executable"""
#
# def is_exe(fpath):
# return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
#
# fpath, fname = os.path.split(program)
# if fpath:
# if is_exe(program):
# return program
# else:
# for path in os.environ["PATH"].split(os.pathsep):
# exe_file = os.path.join(path, program)
# if is_exe(exe_file):
# return exe_file
#
# return None
#
# def remove_suffix(filename):
# filename, extension = os.path.splitext(filename)
# return filename
#
# def append_stem(filename, word, delim="."):
# """ returns a filename with word appended to the stem
# example: /path/to/test.run.sam -> /path/to/test.run.sorted.sam """
# dirname = os.path.dirname(filename)
# filename = os.path.basename(filename)
# fsplit = filename.split(delim)
# fsplit.insert(len(fsplit) - 1, word)
# return os.path.join(dirname, delim.join(fsplit))
#
# def prepare_ref_file(ref, config):
# """Get a reference file, either by URL or locally.
# Lifted from Brad Chapman
# """
# url = ref.get("url", None)
# if url:
# ref_file = _download_ref(url, config["dir"]["ref"])
# else:
# ref_file = ref.get("file", None)
# assert ref_file is not None and os.path.exists(ref_file), ref_file
# return ref_file
#
# Path: bipy/toolbox/reporting.py
# class LatexReport(object):
# """Abstract class for generating Latex reports. Inherit from this
# and implement template and generate_report"""
# __metaclass__ = abc.ABCMeta
#
# @abc.abstractproperty
# def template(self):
# return
#
# @abc.abstractmethod
# def generate_report(self, *args, **kwargs):
# """Generate the Latex output using the template"""
# return
#
# def safe_latex(to_fix):
# """Escape characters that make LaTeX unhappy.
# Lifted from Brad Chapman (bcbio)
# """
# chars = ["%", "_", "&", "#"]
# for char in chars:
# to_fix = to_fix.replace(char, "\\%s" % char)
# return to_fix
#
# Path: bipy/pipeline/stages.py
# class AbstractStage(object):
# """
# Wrapper around a stage for use with the pipeline manager. Subclasses should
# implement their own __init__ in addition to calling the super
# __init__. __init__ should parse the appropriate information from the config
# dict and save it in the objects state. __call__ should be implemented as a
# pure function with no closures.
#
# """
#
# stage = "abstract"
#
# def __init__(self, config):
# self.config = config
# self._validate_config()
#
# def _start_message(self, in_file, **kwargs):
# if kwargs:
# logger.info("Starting %s on %s with arguments %s." % (self.stage,
# in_file,
# kwargs))
# else:
# logger.info("Starting %s on %s." % (self.stage, in_file))
#
# def _end_message(self, in_file):
# logger.info("%s complete on %s." % (self.stage, in_file))
#
# def _check_run(self, in_file):
# if not file_exists(in_file):
# raise IOError("%s not found." % (in_file))
#
# def __call__(self, in_file):
# pass
#
# def _validate_config(self):
# if "stage" not in self.config:
# raise ValueError('Could not find "stage" in the config file.')
. Output only the next line. | if not program_exists(PROGRAM): |
Given the code snippet: <|code_start|>
def program_exists(path):
return which(path)
def _results_dir(config, prefix=""):
def _make_dir(base):
out_dir = os.path.join(base, "rseqc",
prefix)
safe_makedir(out_dir)
return out_dir
if "dir" not in config:
return _make_dir("results")
if "results" not in config["dir"]:
return _make_dir("results")
else:
return _make_dir(config["dir"]["results"])
def _fetch_chrom_sizes(config):
PROGRAM = "fetchChromSizes"
if not program_exists(PROGRAM):
logger.error("%s is not in the path or is not executable. Make sure "
"it is installed or go to "
"http://hgdownload.cse.ucsc.edu/admin/exe/"
"to download it." % (PROGRAM))
<|code_end|>
, generate the next line using the imports in this file:
import os
import sh
import glob
import pandas as pd
from bipy.utils import (replace_suffix, which, remove_suffix, append_stem,
prepare_ref_file)
from bcbio.utils import file_exists, safe_makedir, add_full_path
from math import sqrt
from mako.template import Template
from bipy.toolbox.reporting import LatexReport, safe_latex
from bcbio.distributed.transaction import file_transaction
from bipy.pipeline.stages import AbstractStage
from bcbio.broad import BroadRunner, picardrun
from bcbio.log import logger
from bcbio.provenance import do
and context (functions, classes, or occasionally code) from other files:
# Path: bipy/utils.py
# def replace_suffix(filename, suffix, delim="."):
# """ returns a filename with the suffix replaced
# with a new suffix
# exampoe: /path/to/test.run.sam -> /path/to/test.run.fa"""
# dirname = os.path.dirname(filename)
# filename = os.path.basename(filename)
# fsplit = filename.split(delim)[:-1]
# fsplit.append(suffix)
# return os.path.join(dirname, delim.join(fsplit))
#
# def which(program):
# """ returns the path to an executable"""
#
# def is_exe(fpath):
# return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
#
# fpath, fname = os.path.split(program)
# if fpath:
# if is_exe(program):
# return program
# else:
# for path in os.environ["PATH"].split(os.pathsep):
# exe_file = os.path.join(path, program)
# if is_exe(exe_file):
# return exe_file
#
# return None
#
# def remove_suffix(filename):
# filename, extension = os.path.splitext(filename)
# return filename
#
# def append_stem(filename, word, delim="."):
# """ returns a filename with word appended to the stem
# example: /path/to/test.run.sam -> /path/to/test.run.sorted.sam """
# dirname = os.path.dirname(filename)
# filename = os.path.basename(filename)
# fsplit = filename.split(delim)
# fsplit.insert(len(fsplit) - 1, word)
# return os.path.join(dirname, delim.join(fsplit))
#
# def prepare_ref_file(ref, config):
# """Get a reference file, either by URL or locally.
# Lifted from Brad Chapman
# """
# url = ref.get("url", None)
# if url:
# ref_file = _download_ref(url, config["dir"]["ref"])
# else:
# ref_file = ref.get("file", None)
# assert ref_file is not None and os.path.exists(ref_file), ref_file
# return ref_file
#
# Path: bipy/toolbox/reporting.py
# class LatexReport(object):
# """Abstract class for generating Latex reports. Inherit from this
# and implement template and generate_report"""
# __metaclass__ = abc.ABCMeta
#
# @abc.abstractproperty
# def template(self):
# return
#
# @abc.abstractmethod
# def generate_report(self, *args, **kwargs):
# """Generate the Latex output using the template"""
# return
#
# def safe_latex(to_fix):
# """Escape characters that make LaTeX unhappy.
# Lifted from Brad Chapman (bcbio)
# """
# chars = ["%", "_", "&", "#"]
# for char in chars:
# to_fix = to_fix.replace(char, "\\%s" % char)
# return to_fix
#
# Path: bipy/pipeline/stages.py
# class AbstractStage(object):
# """
# Wrapper around a stage for use with the pipeline manager. Subclasses should
# implement their own __init__ in addition to calling the super
# __init__. __init__ should parse the appropriate information from the config
# dict and save it in the objects state. __call__ should be implemented as a
# pure function with no closures.
#
# """
#
# stage = "abstract"
#
# def __init__(self, config):
# self.config = config
# self._validate_config()
#
# def _start_message(self, in_file, **kwargs):
# if kwargs:
# logger.info("Starting %s on %s with arguments %s." % (self.stage,
# in_file,
# kwargs))
# else:
# logger.info("Starting %s on %s." % (self.stage, in_file))
#
# def _end_message(self, in_file):
# logger.info("%s complete on %s." % (self.stage, in_file))
#
# def _check_run(self, in_file):
# if not file_exists(in_file):
# raise IOError("%s not found." % (in_file))
#
# def __call__(self, in_file):
# pass
#
# def _validate_config(self):
# if "stage" not in self.config:
# raise ValueError('Could not find "stage" in the config file.')
. Output only the next line. | exit(1) |
Given the code snippet: <|code_start|>
def program_exists(path):
return which(path)
def _results_dir(config, prefix=""):
def _make_dir(base):
out_dir = os.path.join(base, "rseqc",
prefix)
safe_makedir(out_dir)
return out_dir
if "dir" not in config:
return _make_dir("results")
if "results" not in config["dir"]:
return _make_dir("results")
else:
return _make_dir(config["dir"]["results"])
def _fetch_chrom_sizes(config):
PROGRAM = "fetchChromSizes"
<|code_end|>
, generate the next line using the imports in this file:
import os
import sh
import glob
import pandas as pd
from bipy.utils import (replace_suffix, which, remove_suffix, append_stem,
prepare_ref_file)
from bcbio.utils import file_exists, safe_makedir, add_full_path
from math import sqrt
from mako.template import Template
from bipy.toolbox.reporting import LatexReport, safe_latex
from bcbio.distributed.transaction import file_transaction
from bipy.pipeline.stages import AbstractStage
from bcbio.broad import BroadRunner, picardrun
from bcbio.log import logger
from bcbio.provenance import do
and context (functions, classes, or occasionally code) from other files:
# Path: bipy/utils.py
# def replace_suffix(filename, suffix, delim="."):
# """ returns a filename with the suffix replaced
# with a new suffix
# exampoe: /path/to/test.run.sam -> /path/to/test.run.fa"""
# dirname = os.path.dirname(filename)
# filename = os.path.basename(filename)
# fsplit = filename.split(delim)[:-1]
# fsplit.append(suffix)
# return os.path.join(dirname, delim.join(fsplit))
#
# def which(program):
# """ returns the path to an executable"""
#
# def is_exe(fpath):
# return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
#
# fpath, fname = os.path.split(program)
# if fpath:
# if is_exe(program):
# return program
# else:
# for path in os.environ["PATH"].split(os.pathsep):
# exe_file = os.path.join(path, program)
# if is_exe(exe_file):
# return exe_file
#
# return None
#
# def remove_suffix(filename):
# filename, extension = os.path.splitext(filename)
# return filename
#
# def append_stem(filename, word, delim="."):
# """ returns a filename with word appended to the stem
# example: /path/to/test.run.sam -> /path/to/test.run.sorted.sam """
# dirname = os.path.dirname(filename)
# filename = os.path.basename(filename)
# fsplit = filename.split(delim)
# fsplit.insert(len(fsplit) - 1, word)
# return os.path.join(dirname, delim.join(fsplit))
#
# def prepare_ref_file(ref, config):
# """Get a reference file, either by URL or locally.
# Lifted from Brad Chapman
# """
# url = ref.get("url", None)
# if url:
# ref_file = _download_ref(url, config["dir"]["ref"])
# else:
# ref_file = ref.get("file", None)
# assert ref_file is not None and os.path.exists(ref_file), ref_file
# return ref_file
#
# Path: bipy/toolbox/reporting.py
# class LatexReport(object):
# """Abstract class for generating Latex reports. Inherit from this
# and implement template and generate_report"""
# __metaclass__ = abc.ABCMeta
#
# @abc.abstractproperty
# def template(self):
# return
#
# @abc.abstractmethod
# def generate_report(self, *args, **kwargs):
# """Generate the Latex output using the template"""
# return
#
# def safe_latex(to_fix):
# """Escape characters that make LaTeX unhappy.
# Lifted from Brad Chapman (bcbio)
# """
# chars = ["%", "_", "&", "#"]
# for char in chars:
# to_fix = to_fix.replace(char, "\\%s" % char)
# return to_fix
#
# Path: bipy/pipeline/stages.py
# class AbstractStage(object):
# """
# Wrapper around a stage for use with the pipeline manager. Subclasses should
# implement their own __init__ in addition to calling the super
# __init__. __init__ should parse the appropriate information from the config
# dict and save it in the objects state. __call__ should be implemented as a
# pure function with no closures.
#
# """
#
# stage = "abstract"
#
# def __init__(self, config):
# self.config = config
# self._validate_config()
#
# def _start_message(self, in_file, **kwargs):
# if kwargs:
# logger.info("Starting %s on %s with arguments %s." % (self.stage,
# in_file,
# kwargs))
# else:
# logger.info("Starting %s on %s." % (self.stage, in_file))
#
# def _end_message(self, in_file):
# logger.info("%s complete on %s." % (self.stage, in_file))
#
# def _check_run(self, in_file):
# if not file_exists(in_file):
# raise IOError("%s not found." % (in_file))
#
# def __call__(self, in_file):
# pass
#
# def _validate_config(self):
# if "stage" not in self.config:
# raise ValueError('Could not find "stage" in the config file.')
. Output only the next line. | if not program_exists(PROGRAM): |
Predict the next line for this snippet: <|code_start|>
def program_exists(path):
return which(path)
def _results_dir(config, prefix=""):
def _make_dir(base):
out_dir = os.path.join(base, "rseqc",
prefix)
safe_makedir(out_dir)
return out_dir
<|code_end|>
with the help of current file imports:
import os
import sh
import glob
import pandas as pd
from bipy.utils import (replace_suffix, which, remove_suffix, append_stem,
prepare_ref_file)
from bcbio.utils import file_exists, safe_makedir, add_full_path
from math import sqrt
from mako.template import Template
from bipy.toolbox.reporting import LatexReport, safe_latex
from bcbio.distributed.transaction import file_transaction
from bipy.pipeline.stages import AbstractStage
from bcbio.broad import BroadRunner, picardrun
from bcbio.log import logger
from bcbio.provenance import do
and context from other files:
# Path: bipy/utils.py
# def replace_suffix(filename, suffix, delim="."):
# """ returns a filename with the suffix replaced
# with a new suffix
# exampoe: /path/to/test.run.sam -> /path/to/test.run.fa"""
# dirname = os.path.dirname(filename)
# filename = os.path.basename(filename)
# fsplit = filename.split(delim)[:-1]
# fsplit.append(suffix)
# return os.path.join(dirname, delim.join(fsplit))
#
# def which(program):
# """ returns the path to an executable"""
#
# def is_exe(fpath):
# return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
#
# fpath, fname = os.path.split(program)
# if fpath:
# if is_exe(program):
# return program
# else:
# for path in os.environ["PATH"].split(os.pathsep):
# exe_file = os.path.join(path, program)
# if is_exe(exe_file):
# return exe_file
#
# return None
#
# def remove_suffix(filename):
# filename, extension = os.path.splitext(filename)
# return filename
#
# def append_stem(filename, word, delim="."):
# """ returns a filename with word appended to the stem
# example: /path/to/test.run.sam -> /path/to/test.run.sorted.sam """
# dirname = os.path.dirname(filename)
# filename = os.path.basename(filename)
# fsplit = filename.split(delim)
# fsplit.insert(len(fsplit) - 1, word)
# return os.path.join(dirname, delim.join(fsplit))
#
# def prepare_ref_file(ref, config):
# """Get a reference file, either by URL or locally.
# Lifted from Brad Chapman
# """
# url = ref.get("url", None)
# if url:
# ref_file = _download_ref(url, config["dir"]["ref"])
# else:
# ref_file = ref.get("file", None)
# assert ref_file is not None and os.path.exists(ref_file), ref_file
# return ref_file
#
# Path: bipy/toolbox/reporting.py
# class LatexReport(object):
# """Abstract class for generating Latex reports. Inherit from this
# and implement template and generate_report"""
# __metaclass__ = abc.ABCMeta
#
# @abc.abstractproperty
# def template(self):
# return
#
# @abc.abstractmethod
# def generate_report(self, *args, **kwargs):
# """Generate the Latex output using the template"""
# return
#
# def safe_latex(to_fix):
# """Escape characters that make LaTeX unhappy.
# Lifted from Brad Chapman (bcbio)
# """
# chars = ["%", "_", "&", "#"]
# for char in chars:
# to_fix = to_fix.replace(char, "\\%s" % char)
# return to_fix
#
# Path: bipy/pipeline/stages.py
# class AbstractStage(object):
# """
# Wrapper around a stage for use with the pipeline manager. Subclasses should
# implement their own __init__ in addition to calling the super
# __init__. __init__ should parse the appropriate information from the config
# dict and save it in the objects state. __call__ should be implemented as a
# pure function with no closures.
#
# """
#
# stage = "abstract"
#
# def __init__(self, config):
# self.config = config
# self._validate_config()
#
# def _start_message(self, in_file, **kwargs):
# if kwargs:
# logger.info("Starting %s on %s with arguments %s." % (self.stage,
# in_file,
# kwargs))
# else:
# logger.info("Starting %s on %s." % (self.stage, in_file))
#
# def _end_message(self, in_file):
# logger.info("%s complete on %s." % (self.stage, in_file))
#
# def _check_run(self, in_file):
# if not file_exists(in_file):
# raise IOError("%s not found." % (in_file))
#
# def __call__(self, in_file):
# pass
#
# def _validate_config(self):
# if "stage" not in self.config:
# raise ValueError('Could not find "stage" in the config file.')
, which may contain function names, class names, or code. Output only the next line. | if "dir" not in config: |
Given snippet: <|code_start|> new_figures = []
for figure in figures:
filename = os.path.basename(figure[0])
caption = self.CAPTIONS.get(filename, "")
new_figures.append((figure[0], caption, figure[2]))
return new_figures
def clean_figures(self, figures):
new_figures = []
for figure in figures:
filename = safe_latex(figure[0])
new_figures.append((filename, figure[1], figure[2]))
return new_figures
def generate_report(self, name, figures=None):
template = Template(self._template)
clean_name = safe_latex(name)
#clean_figures = self.clean_figures(figures)
#section = template.render(name=clean_name, figures=clean_figures)
clean_figures = [(remove_suffix(figure[0]), figure[1], figure[2])
for figure in figures]
section = template.render(name=clean_name, figures=clean_figures)
return section
_template = r"""
\subsection*{Rseqc report for ${name}}
% if figures:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import sh
import glob
import pandas as pd
from bipy.utils import (replace_suffix, which, remove_suffix, append_stem,
prepare_ref_file)
from bcbio.utils import file_exists, safe_makedir, add_full_path
from math import sqrt
from mako.template import Template
from bipy.toolbox.reporting import LatexReport, safe_latex
from bcbio.distributed.transaction import file_transaction
from bipy.pipeline.stages import AbstractStage
from bcbio.broad import BroadRunner, picardrun
from bcbio.log import logger
from bcbio.provenance import do
and context:
# Path: bipy/utils.py
# def replace_suffix(filename, suffix, delim="."):
# """ returns a filename with the suffix replaced
# with a new suffix
# exampoe: /path/to/test.run.sam -> /path/to/test.run.fa"""
# dirname = os.path.dirname(filename)
# filename = os.path.basename(filename)
# fsplit = filename.split(delim)[:-1]
# fsplit.append(suffix)
# return os.path.join(dirname, delim.join(fsplit))
#
# def which(program):
# """ returns the path to an executable"""
#
# def is_exe(fpath):
# return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
#
# fpath, fname = os.path.split(program)
# if fpath:
# if is_exe(program):
# return program
# else:
# for path in os.environ["PATH"].split(os.pathsep):
# exe_file = os.path.join(path, program)
# if is_exe(exe_file):
# return exe_file
#
# return None
#
# def remove_suffix(filename):
# filename, extension = os.path.splitext(filename)
# return filename
#
# def append_stem(filename, word, delim="."):
# """ returns a filename with word appended to the stem
# example: /path/to/test.run.sam -> /path/to/test.run.sorted.sam """
# dirname = os.path.dirname(filename)
# filename = os.path.basename(filename)
# fsplit = filename.split(delim)
# fsplit.insert(len(fsplit) - 1, word)
# return os.path.join(dirname, delim.join(fsplit))
#
# def prepare_ref_file(ref, config):
# """Get a reference file, either by URL or locally.
# Lifted from Brad Chapman
# """
# url = ref.get("url", None)
# if url:
# ref_file = _download_ref(url, config["dir"]["ref"])
# else:
# ref_file = ref.get("file", None)
# assert ref_file is not None and os.path.exists(ref_file), ref_file
# return ref_file
#
# Path: bipy/toolbox/reporting.py
# class LatexReport(object):
# """Abstract class for generating Latex reports. Inherit from this
# and implement template and generate_report"""
# __metaclass__ = abc.ABCMeta
#
# @abc.abstractproperty
# def template(self):
# return
#
# @abc.abstractmethod
# def generate_report(self, *args, **kwargs):
# """Generate the Latex output using the template"""
# return
#
# def safe_latex(to_fix):
# """Escape characters that make LaTeX unhappy.
# Lifted from Brad Chapman (bcbio)
# """
# chars = ["%", "_", "&", "#"]
# for char in chars:
# to_fix = to_fix.replace(char, "\\%s" % char)
# return to_fix
#
# Path: bipy/pipeline/stages.py
# class AbstractStage(object):
# """
# Wrapper around a stage for use with the pipeline manager. Subclasses should
# implement their own __init__ in addition to calling the super
# __init__. __init__ should parse the appropriate information from the config
# dict and save it in the objects state. __call__ should be implemented as a
# pure function with no closures.
#
# """
#
# stage = "abstract"
#
# def __init__(self, config):
# self.config = config
# self._validate_config()
#
# def _start_message(self, in_file, **kwargs):
# if kwargs:
# logger.info("Starting %s on %s with arguments %s." % (self.stage,
# in_file,
# kwargs))
# else:
# logger.info("Starting %s on %s." % (self.stage, in_file))
#
# def _end_message(self, in_file):
# logger.info("%s complete on %s." % (self.stage, in_file))
#
# def _check_run(self, in_file):
# if not file_exists(in_file):
# raise IOError("%s not found." % (in_file))
#
# def __call__(self, in_file):
# pass
#
# def _validate_config(self):
# if "stage" not in self.config:
# raise ValueError('Could not find "stage" in the config file.')
which might include code, classes, or functions. Output only the next line. | % for i, (figure, caption, size) in enumerate (figures): |
Next line prediction: <|code_start|> return new_figures
def clean_figures(self, figures):
new_figures = []
for figure in figures:
filename = safe_latex(figure[0])
new_figures.append((filename, figure[1], figure[2]))
return new_figures
def generate_report(self, name, figures=None):
template = Template(self._template)
clean_name = safe_latex(name)
#clean_figures = self.clean_figures(figures)
#section = template.render(name=clean_name, figures=clean_figures)
clean_figures = [(remove_suffix(figure[0]), figure[1], figure[2])
for figure in figures]
section = template.render(name=clean_name, figures=clean_figures)
return section
_template = r"""
\subsection*{Rseqc report for ${name}}
% if figures:
% for i, (figure, caption, size) in enumerate (figures):
\begin{figure}[htbp]
\centering
\includegraphics[width=${size}\linewidth,natwidth=610,natheight=64]{${figure}}
\caption{${caption}}
<|code_end|>
. Use current file imports:
(import os
import sh
import glob
import pandas as pd
from bipy.utils import (replace_suffix, which, remove_suffix, append_stem,
prepare_ref_file)
from bcbio.utils import file_exists, safe_makedir, add_full_path
from math import sqrt
from mako.template import Template
from bipy.toolbox.reporting import LatexReport, safe_latex
from bcbio.distributed.transaction import file_transaction
from bipy.pipeline.stages import AbstractStage
from bcbio.broad import BroadRunner, picardrun
from bcbio.log import logger
from bcbio.provenance import do)
and context including class names, function names, or small code snippets from other files:
# Path: bipy/utils.py
# def replace_suffix(filename, suffix, delim="."):
# """ returns a filename with the suffix replaced
# with a new suffix
# exampoe: /path/to/test.run.sam -> /path/to/test.run.fa"""
# dirname = os.path.dirname(filename)
# filename = os.path.basename(filename)
# fsplit = filename.split(delim)[:-1]
# fsplit.append(suffix)
# return os.path.join(dirname, delim.join(fsplit))
#
# def which(program):
# """ returns the path to an executable"""
#
# def is_exe(fpath):
# return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
#
# fpath, fname = os.path.split(program)
# if fpath:
# if is_exe(program):
# return program
# else:
# for path in os.environ["PATH"].split(os.pathsep):
# exe_file = os.path.join(path, program)
# if is_exe(exe_file):
# return exe_file
#
# return None
#
# def remove_suffix(filename):
# filename, extension = os.path.splitext(filename)
# return filename
#
# def append_stem(filename, word, delim="."):
# """ returns a filename with word appended to the stem
# example: /path/to/test.run.sam -> /path/to/test.run.sorted.sam """
# dirname = os.path.dirname(filename)
# filename = os.path.basename(filename)
# fsplit = filename.split(delim)
# fsplit.insert(len(fsplit) - 1, word)
# return os.path.join(dirname, delim.join(fsplit))
#
# def prepare_ref_file(ref, config):
# """Get a reference file, either by URL or locally.
# Lifted from Brad Chapman
# """
# url = ref.get("url", None)
# if url:
# ref_file = _download_ref(url, config["dir"]["ref"])
# else:
# ref_file = ref.get("file", None)
# assert ref_file is not None and os.path.exists(ref_file), ref_file
# return ref_file
#
# Path: bipy/toolbox/reporting.py
# class LatexReport(object):
# """Abstract class for generating Latex reports. Inherit from this
# and implement template and generate_report"""
# __metaclass__ = abc.ABCMeta
#
# @abc.abstractproperty
# def template(self):
# return
#
# @abc.abstractmethod
# def generate_report(self, *args, **kwargs):
# """Generate the Latex output using the template"""
# return
#
# def safe_latex(to_fix):
# """Escape characters that make LaTeX unhappy.
# Lifted from Brad Chapman (bcbio)
# """
# chars = ["%", "_", "&", "#"]
# for char in chars:
# to_fix = to_fix.replace(char, "\\%s" % char)
# return to_fix
#
# Path: bipy/pipeline/stages.py
# class AbstractStage(object):
# """
# Wrapper around a stage for use with the pipeline manager. Subclasses should
# implement their own __init__ in addition to calling the super
# __init__. __init__ should parse the appropriate information from the config
# dict and save it in the objects state. __call__ should be implemented as a
# pure function with no closures.
#
# """
#
# stage = "abstract"
#
# def __init__(self, config):
# self.config = config
# self._validate_config()
#
# def _start_message(self, in_file, **kwargs):
# if kwargs:
# logger.info("Starting %s on %s with arguments %s." % (self.stage,
# in_file,
# kwargs))
# else:
# logger.info("Starting %s on %s." % (self.stage, in_file))
#
# def _end_message(self, in_file):
# logger.info("%s complete on %s." % (self.stage, in_file))
#
# def _check_run(self, in_file):
# if not file_exists(in_file):
# raise IOError("%s not found." % (in_file))
#
# def __call__(self, in_file):
# pass
#
# def _validate_config(self):
# if "stage" not in self.config:
# raise ValueError('Could not find "stage" in the config file.')
. Output only the next line. | \end{figure} |
Using the snippet: <|code_start|>
def program_exists(path):
return which(path)
def _results_dir(config, prefix=""):
def _make_dir(base):
out_dir = os.path.join(base, "rseqc",
prefix)
safe_makedir(out_dir)
return out_dir
if "dir" not in config:
return _make_dir("results")
if "results" not in config["dir"]:
return _make_dir("results")
else:
return _make_dir(config["dir"]["results"])
def _fetch_chrom_sizes(config):
PROGRAM = "fetchChromSizes"
if not program_exists(PROGRAM):
<|code_end|>
, determine the next line of code. You have imports:
import os
import sh
import glob
import pandas as pd
from bipy.utils import (replace_suffix, which, remove_suffix, append_stem,
prepare_ref_file)
from bcbio.utils import file_exists, safe_makedir, add_full_path
from math import sqrt
from mako.template import Template
from bipy.toolbox.reporting import LatexReport, safe_latex
from bcbio.distributed.transaction import file_transaction
from bipy.pipeline.stages import AbstractStage
from bcbio.broad import BroadRunner, picardrun
from bcbio.log import logger
from bcbio.provenance import do
and context (class names, function names, or code) available:
# Path: bipy/utils.py
# def replace_suffix(filename, suffix, delim="."):
# """ returns a filename with the suffix replaced
# with a new suffix
# exampoe: /path/to/test.run.sam -> /path/to/test.run.fa"""
# dirname = os.path.dirname(filename)
# filename = os.path.basename(filename)
# fsplit = filename.split(delim)[:-1]
# fsplit.append(suffix)
# return os.path.join(dirname, delim.join(fsplit))
#
# def which(program):
# """ returns the path to an executable"""
#
# def is_exe(fpath):
# return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
#
# fpath, fname = os.path.split(program)
# if fpath:
# if is_exe(program):
# return program
# else:
# for path in os.environ["PATH"].split(os.pathsep):
# exe_file = os.path.join(path, program)
# if is_exe(exe_file):
# return exe_file
#
# return None
#
# def remove_suffix(filename):
# filename, extension = os.path.splitext(filename)
# return filename
#
# def append_stem(filename, word, delim="."):
# """ returns a filename with word appended to the stem
# example: /path/to/test.run.sam -> /path/to/test.run.sorted.sam """
# dirname = os.path.dirname(filename)
# filename = os.path.basename(filename)
# fsplit = filename.split(delim)
# fsplit.insert(len(fsplit) - 1, word)
# return os.path.join(dirname, delim.join(fsplit))
#
# def prepare_ref_file(ref, config):
# """Get a reference file, either by URL or locally.
# Lifted from Brad Chapman
# """
# url = ref.get("url", None)
# if url:
# ref_file = _download_ref(url, config["dir"]["ref"])
# else:
# ref_file = ref.get("file", None)
# assert ref_file is not None and os.path.exists(ref_file), ref_file
# return ref_file
#
# Path: bipy/toolbox/reporting.py
# class LatexReport(object):
# """Abstract class for generating Latex reports. Inherit from this
# and implement template and generate_report"""
# __metaclass__ = abc.ABCMeta
#
# @abc.abstractproperty
# def template(self):
# return
#
# @abc.abstractmethod
# def generate_report(self, *args, **kwargs):
# """Generate the Latex output using the template"""
# return
#
# def safe_latex(to_fix):
# """Escape characters that make LaTeX unhappy.
# Lifted from Brad Chapman (bcbio)
# """
# chars = ["%", "_", "&", "#"]
# for char in chars:
# to_fix = to_fix.replace(char, "\\%s" % char)
# return to_fix
#
# Path: bipy/pipeline/stages.py
# class AbstractStage(object):
# """
# Wrapper around a stage for use with the pipeline manager. Subclasses should
# implement their own __init__ in addition to calling the super
# __init__. __init__ should parse the appropriate information from the config
# dict and save it in the objects state. __call__ should be implemented as a
# pure function with no closures.
#
# """
#
# stage = "abstract"
#
# def __init__(self, config):
# self.config = config
# self._validate_config()
#
# def _start_message(self, in_file, **kwargs):
# if kwargs:
# logger.info("Starting %s on %s with arguments %s." % (self.stage,
# in_file,
# kwargs))
# else:
# logger.info("Starting %s on %s." % (self.stage, in_file))
#
# def _end_message(self, in_file):
# logger.info("%s complete on %s." % (self.stage, in_file))
#
# def _check_run(self, in_file):
# if not file_exists(in_file):
# raise IOError("%s not found." % (in_file))
#
# def __call__(self, in_file):
# pass
#
# def _validate_config(self):
# if "stage" not in self.config:
# raise ValueError('Could not find "stage" in the config file.')
. Output only the next line. | logger.error("%s is not in the path or is not executable. Make sure " |
Predict the next line after this snippet: <|code_start|>
def _fetch_chrom_sizes(config):
PROGRAM = "fetchChromSizes"
if not program_exists(PROGRAM):
logger.error("%s is not in the path or is not executable. Make sure "
"it is installed or go to "
"http://hgdownload.cse.ucsc.edu/admin/exe/"
"to download it." % (PROGRAM))
exit(1)
if "annotation" not in config:
logger.error("'annotation' must be in the yaml file. See example "
" configuration files")
exit(1)
if "name" not in config["annotation"]:
logger.error("'name' must be in the yaml file under "
" 'annotation'. See example configuration files.")
exit(1)
genome = config["annotation"]["name"]
chrom_size_file = os.path.join(_results_dir(config),
genome + ".sizes")
if file_exists(chrom_size_file):
return chrom_size_file
with file_transaction(chrom_size_file) as tmp_chrom_size_file:
sh.fetchChromSizes(genome, _out=tmp_chrom_size_file)
if not file_exists(chrom_size_file):
<|code_end|>
using the current file's imports:
import os
import sh
import glob
import pandas as pd
from bipy.utils import (replace_suffix, which, remove_suffix, append_stem,
prepare_ref_file)
from bcbio.utils import file_exists, safe_makedir, add_full_path
from math import sqrt
from mako.template import Template
from bipy.toolbox.reporting import LatexReport, safe_latex
from bcbio.distributed.transaction import file_transaction
from bipy.pipeline.stages import AbstractStage
from bcbio.broad import BroadRunner, picardrun
from bcbio.log import logger
from bcbio.provenance import do
and any relevant context from other files:
# Path: bipy/utils.py
# def replace_suffix(filename, suffix, delim="."):
# """ returns a filename with the suffix replaced
# with a new suffix
# exampoe: /path/to/test.run.sam -> /path/to/test.run.fa"""
# dirname = os.path.dirname(filename)
# filename = os.path.basename(filename)
# fsplit = filename.split(delim)[:-1]
# fsplit.append(suffix)
# return os.path.join(dirname, delim.join(fsplit))
#
# def which(program):
# """ returns the path to an executable"""
#
# def is_exe(fpath):
# return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
#
# fpath, fname = os.path.split(program)
# if fpath:
# if is_exe(program):
# return program
# else:
# for path in os.environ["PATH"].split(os.pathsep):
# exe_file = os.path.join(path, program)
# if is_exe(exe_file):
# return exe_file
#
# return None
#
# def remove_suffix(filename):
# filename, extension = os.path.splitext(filename)
# return filename
#
# def append_stem(filename, word, delim="."):
# """ returns a filename with word appended to the stem
# example: /path/to/test.run.sam -> /path/to/test.run.sorted.sam """
# dirname = os.path.dirname(filename)
# filename = os.path.basename(filename)
# fsplit = filename.split(delim)
# fsplit.insert(len(fsplit) - 1, word)
# return os.path.join(dirname, delim.join(fsplit))
#
# def prepare_ref_file(ref, config):
# """Get a reference file, either by URL or locally.
# Lifted from Brad Chapman
# """
# url = ref.get("url", None)
# if url:
# ref_file = _download_ref(url, config["dir"]["ref"])
# else:
# ref_file = ref.get("file", None)
# assert ref_file is not None and os.path.exists(ref_file), ref_file
# return ref_file
#
# Path: bipy/toolbox/reporting.py
# class LatexReport(object):
# """Abstract class for generating Latex reports. Inherit from this
# and implement template and generate_report"""
# __metaclass__ = abc.ABCMeta
#
# @abc.abstractproperty
# def template(self):
# return
#
# @abc.abstractmethod
# def generate_report(self, *args, **kwargs):
# """Generate the Latex output using the template"""
# return
#
# def safe_latex(to_fix):
# """Escape characters that make LaTeX unhappy.
# Lifted from Brad Chapman (bcbio)
# """
# chars = ["%", "_", "&", "#"]
# for char in chars:
# to_fix = to_fix.replace(char, "\\%s" % char)
# return to_fix
#
# Path: bipy/pipeline/stages.py
# class AbstractStage(object):
# """
# Wrapper around a stage for use with the pipeline manager. Subclasses should
# implement their own __init__ in addition to calling the super
# __init__. __init__ should parse the appropriate information from the config
# dict and save it in the objects state. __call__ should be implemented as a
# pure function with no closures.
#
# """
#
# stage = "abstract"
#
# def __init__(self, config):
# self.config = config
# self._validate_config()
#
# def _start_message(self, in_file, **kwargs):
# if kwargs:
# logger.info("Starting %s on %s with arguments %s." % (self.stage,
# in_file,
# kwargs))
# else:
# logger.info("Starting %s on %s." % (self.stage, in_file))
#
# def _end_message(self, in_file):
# logger.info("%s complete on %s." % (self.stage, in_file))
#
# def _check_run(self, in_file):
# if not file_exists(in_file):
# raise IOError("%s not found." % (in_file))
#
# def __call__(self, in_file):
# pass
#
# def _validate_config(self):
# if "stage" not in self.config:
# raise ValueError('Could not find "stage" in the config file.')
. Output only the next line. | logger.error("chromosome size file does not exist. Check " |
Next line prediction: <|code_start|> os.unlink(out_file)
def test_bamstat(self):
out_file = rseqc.bam_stat(self.input_file, self.config)
self.assertTrue(file_exists(out_file))
os.unlink(out_file)
def test_clipping_profile(self):
out_file = rseqc.clipping_profile(self.input_file, self.config)
self.assertTrue(file_exists(out_file))
os.unlink(out_file)
def test_genebody_coverage(self):
# test on the bam file
out_file_bam = rseqc.genebody_coverage(self.input_file, self.config)
self.assertTrue(file_exists(out_file_bam))
os.unlink(out_file_bam)
# test on the bigwig file
#bigwig = rseqc.bam2bigwig(self.input_file, self.config)
#out_file_bw = reseqc.genebody_coverage(bigwig, self.config)
#self.assertTrue(file_exists(out_file_bw))
def test_genebody_coverage2(self):
# test on a bam file
out_file_bam = rseqc.genebody_coverage2(self.input_file, self.config)
self.assertTrue(file_exists(out_file_bam))
os.unlink(out_file_bam)
def test_junction_annotation(self):
out_file_junction = rseqc.junction_annotation(self.input_file,
<|code_end|>
. Use current file imports:
(import yaml
import unittest
import os
from bipy.toolbox import rseqc
from bcbio.utils import safe_makedir, file_exists
from bipy.toolbox import reporting)
and context including class names, function names, or small code snippets from other files:
# Path: bipy/toolbox/rseqc.py
# def program_exists(path):
# def _results_dir(config, prefix=""):
# def _make_dir(base):
# def _fetch_chrom_sizes(config):
# def bam2bigwig(in_file, config, out_prefix=None):
# def wig2bigwig(wiggle_file, chrom_size_file, out_file):
# def bam_stat(in_file, config, out_prefix=None):
# def clipping_profile(in_file, config, out_prefix=None):
# def genebody_coverage(in_file, config, out_prefix=None):
# def genebody_coverage2(in_file, config, out_prefix=None):
# def junction_annotation(in_file, config, out_prefix=None):
# def junction_saturation(in_file, config, out_prefix=None):
# def RPKM_count(in_file, config, out_prefix=None):
# def merge_RPKM(in_dir):
# def fix_RPKM_count_file(in_file, out_file=None):
# def RPKM_saturation(in_file, config, out_prefix=None):
# def _get_out_dir(in_file, config, out_prefix, prefix):
# def _get_out_prefix(in_file, config, out_prefix, prefix):
# def _get_gtf(config):
# def _gtf2bed(gtf):
# def __init__(self, base_dir):
# def get_rseqc_graphs(self):
# def __init__(self):
# def template(self):
# def _add_captions(self, figures):
# def clean_figures(self, figures):
# def generate_report(self, name, figures=None):
# def __init__(self, config):
# def out_file(self, in_file):
# def __call__(self, in_file):
# PROGRAM = "fetchChromSizes"
# PROGRAM = "bam2wig.py"
# PROGRAM = "wigToBigWig"
# PROGRAM = "bam_stat.py"
# PROGRAM = "clipping_profile.py"
# PROGRAM = "geneBody_coverage.py"
# PROGRAM = "geneBody_coverage2.py"
# PROGRAM = "junction_annotation.py"
# PROGRAM = "junction_saturation.py"
# PROGRAM = "RPKM_count.py"
# HEADER = ["chrom", "st", "end", "accession" "score",
# "gene_strand", "tag_count", "RPKM"]
# NAME_COL = 3
# HEADER_START = 0
# HEADER_END = 5
# RPKM_COLUMN = 6
# COUNT_COLUMN = 5
# PROGRAM = "RPKM_saturation.py"
# DIRS = ["bam_sta", "clipping", "coverage", "junction",
# "saturation", "RPKM_count", "RPKM_saturation"]
# GRAPHS = ((os.path.join("RPKM_saturation", "RPKM_saturation.pdf"),
# "", 1.0),
# (os.path.join("clipping", "clipping.pdf"), "", 1.0),
# (os.path.join("coverage", "coverage.geneBodyCoverage.pdf"),
# "", 1.0),
# (os.path.join("saturation", "junction_saturation.pdf"),
# "", 1.0),
# (os.path.join("junction", "junction.splice_junction.pdf"),
# "", 1.0))
# INFO = (os.path.join("bam_stat", "bam_stat.txt"),
# os.path.join("RPKM_count", "RPKM_count.txt"))
# CAPTIONS = {"RPKM_saturation.pdf": "",
# "coverage.geneBodyCoverage.pdf": "",
# "clipping.pdf": "",
# "coverage.pdf": "",
# "junction_saturation.pdf": "",
# "splice_events.pdf": ""}
# class RseqcParser(object):
# class RseqcReport(LatexReport):
# class RNASeqMetrics(AbstractStage):
#
# Path: bipy/toolbox/reporting.py
# def safe_latex(to_fix):
# def generate_pdf(self, sections=None, out_file=None):
# def template(self):
# def generate_report(self, *args, **kwargs):
# def make_latex_table_header(length):
# def panda_to_latex(table, caption=""):
# def _panda_row_to_latex_row(row):
# class LatexPdf(object):
# class LatexReport(object):
. Output only the next line. | self.config) |
Given the following code snippet before the placeholder: <|code_start|>STAGENAME = "htseq-count"
class TestHtseqcount(unittest.TestCase):
def setUp(self):
self.config_file = "test/htseq-count/test_htseq_count.yaml"
with open(self.config_file) as in_handle:
self.config = yaml.load(in_handle)
self.input_file = self.config["input"]
self.gtf = self.config["annotation"]["file"]
self.stage_config = self.config["stage"][STAGENAME]
self.options = self.stage_config["options"]
def test_run(self):
out_file = "results/htseq-count/test_run.count"
run_result = htseq_count.run(self.input_file,
self.gtf,
self.options,
out_file)
self.assertTrue(run_result == out_file)
self.assertTrue(os.path.exists(run_result))
self.assertTrue(os.path.getsize(run_result) > 0)
def test_run_with_config(self):
run_result = htseq_count.run_with_config(self.input_file,
self.config,
STAGENAME)
self.assertTrue(os.path.exists(run_result))
<|code_end|>
, predict the next line using imports from the current file:
import yaml
import unittest
import os
import shutil
from bipy.toolbox import htseq_count
from bcbio.utils import safe_makedir
and context including class names, function names, and sometimes code from other files:
# Path: bipy/toolbox/htseq_count.py
# def _load_htseq_count_file(filename):
# def _make_length_dict(gtf_file):
# def calculate_rpkm(count_file, gtf_file):
# def combine_counts(in_files, column_names=None, out_file=None):
# def _get_outfilename(input_file):
# def run(input_file, gtf_file, out_file=None):
# def run_with_config(input_file, config, stage, out_file=None):
. Output only the next line. | self.assertTrue(os.path.getsize(run_result) > 0) |
Predict the next line after this snippet: <|code_start|> r('''
cds = estimateDispersions(cds, method="blind", sharingMode="fit-only")
''')
else:
r('''
cds = estimateDispersions(cds)
''')
_plot_disp_ests(r, dispersion_plot_out)
# if there are two conditions use the standard deseq diffexpression
sconds = set(conds)
if len(sconds) == 2:
r.assign('cond1', str(list(sconds)[0]))
r.assign('cond2', str(list(sconds)[1]))
r('''
res = nbinomTest(cds, cond1, cond2)
''')
_plot_MvA(r, mva_plot_out)
r('''write.table(res, file=deseq_table_out, quote=FALSE,
row.names=FALSE, sep="\t")''')
return deseq_table_out
def _plot_disp_ests(r, dispersion_plot_out):
"""
make a plot of the dispersion estimation
"""
r.assign("dispersion_plot_out", dispersion_plot_out)
r('''
<|code_end|>
using the current file's imports:
import os
import rpy2.robjects as robjects
import rpy2.robjects.vectors as vectors
import pandas as pd
from bcbio.utils import safe_makedir, file_exists
from bipy.toolbox.reporting import LatexReport, panda_to_latex
from mako.template import Template
and any relevant context from other files:
# Path: bipy/toolbox/reporting.py
# class LatexReport(object):
# """Abstract class for generating Latex reports. Inherit from this
# and implement template and generate_report"""
# __metaclass__ = abc.ABCMeta
#
# @abc.abstractproperty
# def template(self):
# return
#
# @abc.abstractmethod
# def generate_report(self, *args, **kwargs):
# """Generate the Latex output using the template"""
# return
#
# def panda_to_latex(table, caption=""):
# header = make_latex_table_header(len(table.keys()))
#
# def _panda_row_to_latex_row(row):
# vals = map(str, [e for e in row[1]])
# return " & ".join(vals) + " \\\\"
#
# rows = [_panda_row_to_latex_row(x) for x in table.iterrows()]
#
# _table_template = r"""
# \begin{table}[h]
# \centering
# ${header}
#
# % for row in rows:
# ${row}
# % endfor
# \hline
# \end{tabular}
# \caption{${caption}}
# \end{table}
# """
#
# template = Template(_table_template)
# latex_table = template.render(header=header, rows=rows, caption=caption)
# return latex_table
. Output only the next line. | plotDispEsts <- function(cds) { |
Next line prediction: <|code_start|> "duplication_levels.png": "",
"per_bases_n_content.png": "",
"per_sequence_quality.png": "",
"sequence_length_distribution.png": ""}
def template(self):
return self._template
def _add_captions(self, figures):
new_figures = []
for figure in figures:
filename = os.path.basename(figure)
caption = self.CAPTIONS.get(filename, "")
new_figures.append((figure[0], caption, figure[2]))
return new_figures
@classmethod
def generate_report(self, name=None, summary=None, figures=None,
overrep=None):
template = Template(self._template)
safe_name = safe_latex(name)
section = template.render(name=safe_name, summary=summary,
summary_table=summary, figures=figures,
overrep=overrep)
return section
_template = r"""
\subsection*{FastQC report for ${name}}
% if summary:
<|code_end|>
. Use current file imports:
(import subprocess
import os
import logging
import abc
import sh
import zipfile
from bipy.utils import flatten, remove_suffix, is_pair
from bcbio.utils import safe_makedir, file_exists
from mako.template import Template
from bipy.toolbox.reporting import LatexReport, safe_latex
from bipy.pipeline.stages import AbstractStage
from bcbio.log import logger, setup_local_logging
from bcbio.provenance import do)
and context including class names, function names, or small code snippets from other files:
# Path: bipy/utils.py
# def flatten(l):
# for el in l:
# if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
# for sub in flatten(el):
# yield sub
# else:
# yield el
#
# def remove_suffix(filename):
# filename, extension = os.path.splitext(filename)
# return filename
#
# def is_pair(arg):
# """
# check if 'arg' is a two-item sequence
#
# """
# return is_sequence(arg) and len(arg) == 2
#
# Path: bipy/toolbox/reporting.py
# class LatexReport(object):
# """Abstract class for generating Latex reports. Inherit from this
# and implement template and generate_report"""
# __metaclass__ = abc.ABCMeta
#
# @abc.abstractproperty
# def template(self):
# return
#
# @abc.abstractmethod
# def generate_report(self, *args, **kwargs):
# """Generate the Latex output using the template"""
# return
#
# def safe_latex(to_fix):
# """Escape characters that make LaTeX unhappy.
# Lifted from Brad Chapman (bcbio)
# """
# chars = ["%", "_", "&", "#"]
# for char in chars:
# to_fix = to_fix.replace(char, "\\%s" % char)
# return to_fix
#
# Path: bipy/pipeline/stages.py
# class AbstractStage(object):
# """
# Wrapper around a stage for use with the pipeline manager. Subclasses should
# implement their own __init__ in addition to calling the super
# __init__. __init__ should parse the appropriate information from the config
# dict and save it in the objects state. __call__ should be implemented as a
# pure function with no closures.
#
# """
#
# stage = "abstract"
#
# def __init__(self, config):
# self.config = config
# self._validate_config()
#
# def _start_message(self, in_file, **kwargs):
# if kwargs:
# logger.info("Starting %s on %s with arguments %s." % (self.stage,
# in_file,
# kwargs))
# else:
# logger.info("Starting %s on %s." % (self.stage, in_file))
#
# def _end_message(self, in_file):
# logger.info("%s complete on %s." % (self.stage, in_file))
#
# def _check_run(self, in_file):
# if not file_exists(in_file):
# raise IOError("%s not found." % (in_file))
#
# def __call__(self, in_file):
# pass
#
# def _validate_config(self):
# if "stage" not in self.config:
# raise ValueError('Could not find "stage" in the config file.')
. Output only the next line. | \begin{table}[h] |
Given the code snippet: <|code_start|> def template(self):
return self._template
def _add_captions(self, figures):
new_figures = []
for figure in figures:
filename = os.path.basename(figure)
caption = self.CAPTIONS.get(filename, "")
new_figures.append((figure[0], caption, figure[2]))
return new_figures
@classmethod
def generate_report(self, name=None, summary=None, figures=None,
overrep=None):
template = Template(self._template)
safe_name = safe_latex(name)
section = template.render(name=safe_name, summary=summary,
summary_table=summary, figures=figures,
overrep=overrep)
return section
_template = r"""
\subsection*{FastQC report for ${name}}
% if summary:
\begin{table}[h]
\centering
\begin{tabular}{|l|r|}
\hline
% for k, v in summary.items():
<|code_end|>
, generate the next line using the imports in this file:
import subprocess
import os
import logging
import abc
import sh
import zipfile
from bipy.utils import flatten, remove_suffix, is_pair
from bcbio.utils import safe_makedir, file_exists
from mako.template import Template
from bipy.toolbox.reporting import LatexReport, safe_latex
from bipy.pipeline.stages import AbstractStage
from bcbio.log import logger, setup_local_logging
from bcbio.provenance import do
and context (functions, classes, or occasionally code) from other files:
# Path: bipy/utils.py
# def flatten(l):
# for el in l:
# if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
# for sub in flatten(el):
# yield sub
# else:
# yield el
#
# def remove_suffix(filename):
# filename, extension = os.path.splitext(filename)
# return filename
#
# def is_pair(arg):
# """
# check if 'arg' is a two-item sequence
#
# """
# return is_sequence(arg) and len(arg) == 2
#
# Path: bipy/toolbox/reporting.py
# class LatexReport(object):
# """Abstract class for generating Latex reports. Inherit from this
# and implement template and generate_report"""
# __metaclass__ = abc.ABCMeta
#
# @abc.abstractproperty
# def template(self):
# return
#
# @abc.abstractmethod
# def generate_report(self, *args, **kwargs):
# """Generate the Latex output using the template"""
# return
#
# def safe_latex(to_fix):
# """Escape characters that make LaTeX unhappy.
# Lifted from Brad Chapman (bcbio)
# """
# chars = ["%", "_", "&", "#"]
# for char in chars:
# to_fix = to_fix.replace(char, "\\%s" % char)
# return to_fix
#
# Path: bipy/pipeline/stages.py
# class AbstractStage(object):
# """
# Wrapper around a stage for use with the pipeline manager. Subclasses should
# implement their own __init__ in addition to calling the super
# __init__. __init__ should parse the appropriate information from the config
# dict and save it in the objects state. __call__ should be implemented as a
# pure function with no closures.
#
# """
#
# stage = "abstract"
#
# def __init__(self, config):
# self.config = config
# self._validate_config()
#
# def _start_message(self, in_file, **kwargs):
# if kwargs:
# logger.info("Starting %s on %s with arguments %s." % (self.stage,
# in_file,
# kwargs))
# else:
# logger.info("Starting %s on %s." % (self.stage, in_file))
#
# def _end_message(self, in_file):
# logger.info("%s complete on %s." % (self.stage, in_file))
#
# def _check_run(self, in_file):
# if not file_exists(in_file):
# raise IOError("%s not found." % (in_file))
#
# def __call__(self, in_file):
# pass
#
# def _validate_config(self):
# if "stage" not in self.config:
# raise ValueError('Could not find "stage" in the config file.')
. Output only the next line. | ${k} & ${v} \\\ |
Given the following code snippet before the placeholder: <|code_start|> \hline
\end{tabular}
\caption{Summary of lane results}
\end{table}
% endif
% if figures:
% for i, (figure, caption, size) in enumerate(figures):
\begin{figure}[htbp]
\centering
\includegraphics[width=${size}\linewidth] {${figure}}
\caption{${caption}}
\end{figure}
% endfor
% endif
% if overrep:
% if len(overrep) > 0:
\begin{table}[htbp]
\centering
\begin{tabular}{|p{8cm}rrp{4cm}|}
\hline
Sequence & Count & Percent & Match \\\
\hline
% for seq, count, percent, match in overrep:
\texttt{${seq}} & ${count} & ${"%.2f" % float(percent)} & ${match} \\\
% endfor
\hline
\end{tabular}
\caption{Overrepresented read sequences}
<|code_end|>
, predict the next line using imports from the current file:
import subprocess
import os
import logging
import abc
import sh
import zipfile
from bipy.utils import flatten, remove_suffix, is_pair
from bcbio.utils import safe_makedir, file_exists
from mako.template import Template
from bipy.toolbox.reporting import LatexReport, safe_latex
from bipy.pipeline.stages import AbstractStage
from bcbio.log import logger, setup_local_logging
from bcbio.provenance import do
and context including class names, function names, and sometimes code from other files:
# Path: bipy/utils.py
# def flatten(l):
# for el in l:
# if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
# for sub in flatten(el):
# yield sub
# else:
# yield el
#
# def remove_suffix(filename):
# filename, extension = os.path.splitext(filename)
# return filename
#
# def is_pair(arg):
# """
# check if 'arg' is a two-item sequence
#
# """
# return is_sequence(arg) and len(arg) == 2
#
# Path: bipy/toolbox/reporting.py
# class LatexReport(object):
# """Abstract class for generating Latex reports. Inherit from this
# and implement template and generate_report"""
# __metaclass__ = abc.ABCMeta
#
# @abc.abstractproperty
# def template(self):
# return
#
# @abc.abstractmethod
# def generate_report(self, *args, **kwargs):
# """Generate the Latex output using the template"""
# return
#
# def safe_latex(to_fix):
# """Escape characters that make LaTeX unhappy.
# Lifted from Brad Chapman (bcbio)
# """
# chars = ["%", "_", "&", "#"]
# for char in chars:
# to_fix = to_fix.replace(char, "\\%s" % char)
# return to_fix
#
# Path: bipy/pipeline/stages.py
# class AbstractStage(object):
# """
# Wrapper around a stage for use with the pipeline manager. Subclasses should
# implement their own __init__ in addition to calling the super
# __init__. __init__ should parse the appropriate information from the config
# dict and save it in the objects state. __call__ should be implemented as a
# pure function with no closures.
#
# """
#
# stage = "abstract"
#
# def __init__(self, config):
# self.config = config
# self._validate_config()
#
# def _start_message(self, in_file, **kwargs):
# if kwargs:
# logger.info("Starting %s on %s with arguments %s." % (self.stage,
# in_file,
# kwargs))
# else:
# logger.info("Starting %s on %s." % (self.stage, in_file))
#
# def _end_message(self, in_file):
# logger.info("%s complete on %s." % (self.stage, in_file))
#
# def _check_run(self, in_file):
# if not file_exists(in_file):
# raise IOError("%s not found." % (in_file))
#
# def __call__(self, in_file):
# pass
#
# def _validate_config(self):
# if "stage" not in self.config:
# raise ValueError('Could not find "stage" in the config file.')
. Output only the next line. | \end{table} |
Continue the code snippet: <|code_start|> filename = os.path.basename(figure)
caption = self.CAPTIONS.get(filename, "")
new_figures.append((figure[0], caption, figure[2]))
return new_figures
@classmethod
def generate_report(self, name=None, summary=None, figures=None,
overrep=None):
template = Template(self._template)
safe_name = safe_latex(name)
section = template.render(name=safe_name, summary=summary,
summary_table=summary, figures=figures,
overrep=overrep)
return section
_template = r"""
\subsection*{FastQC report for ${name}}
% if summary:
\begin{table}[h]
\centering
\begin{tabular}{|l|r|}
\hline
% for k, v in summary.items():
${k} & ${v} \\\
% endfor
\hline
\end{tabular}
\caption{Summary of lane results}
\end{table}
<|code_end|>
. Use current file imports:
import subprocess
import os
import logging
import abc
import sh
import zipfile
from bipy.utils import flatten, remove_suffix, is_pair
from bcbio.utils import safe_makedir, file_exists
from mako.template import Template
from bipy.toolbox.reporting import LatexReport, safe_latex
from bipy.pipeline.stages import AbstractStage
from bcbio.log import logger, setup_local_logging
from bcbio.provenance import do
and context (classes, functions, or code) from other files:
# Path: bipy/utils.py
# def flatten(l):
# for el in l:
# if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
# for sub in flatten(el):
# yield sub
# else:
# yield el
#
# def remove_suffix(filename):
# filename, extension = os.path.splitext(filename)
# return filename
#
# def is_pair(arg):
# """
# check if 'arg' is a two-item sequence
#
# """
# return is_sequence(arg) and len(arg) == 2
#
# Path: bipy/toolbox/reporting.py
# class LatexReport(object):
# """Abstract class for generating Latex reports. Inherit from this
# and implement template and generate_report"""
# __metaclass__ = abc.ABCMeta
#
# @abc.abstractproperty
# def template(self):
# return
#
# @abc.abstractmethod
# def generate_report(self, *args, **kwargs):
# """Generate the Latex output using the template"""
# return
#
# def safe_latex(to_fix):
# """Escape characters that make LaTeX unhappy.
# Lifted from Brad Chapman (bcbio)
# """
# chars = ["%", "_", "&", "#"]
# for char in chars:
# to_fix = to_fix.replace(char, "\\%s" % char)
# return to_fix
#
# Path: bipy/pipeline/stages.py
# class AbstractStage(object):
# """
# Wrapper around a stage for use with the pipeline manager. Subclasses should
# implement their own __init__ in addition to calling the super
# __init__. __init__ should parse the appropriate information from the config
# dict and save it in the objects state. __call__ should be implemented as a
# pure function with no closures.
#
# """
#
# stage = "abstract"
#
# def __init__(self, config):
# self.config = config
# self._validate_config()
#
# def _start_message(self, in_file, **kwargs):
# if kwargs:
# logger.info("Starting %s on %s with arguments %s." % (self.stage,
# in_file,
# kwargs))
# else:
# logger.info("Starting %s on %s." % (self.stage, in_file))
#
# def _end_message(self, in_file):
# logger.info("%s complete on %s." % (self.stage, in_file))
#
# def _check_run(self, in_file):
# if not file_exists(in_file):
# raise IOError("%s not found." % (in_file))
#
# def __call__(self, in_file):
# pass
#
# def _validate_config(self):
# if "stage" not in self.config:
# raise ValueError('Could not find "stage" in the config file.')
. Output only the next line. | % endif |
Given snippet: <|code_start|> \hline
% for k, v in summary.items():
${k} & ${v} \\\
% endfor
\hline
\end{tabular}
\caption{Summary of lane results}
\end{table}
% endif
% if figures:
% for i, (figure, caption, size) in enumerate(figures):
\begin{figure}[htbp]
\centering
\includegraphics[width=${size}\linewidth] {${figure}}
\caption{${caption}}
\end{figure}
% endfor
% endif
% if overrep:
% if len(overrep) > 0:
\begin{table}[htbp]
\centering
\begin{tabular}{|p{8cm}rrp{4cm}|}
\hline
Sequence & Count & Percent & Match \\\
\hline
% for seq, count, percent, match in overrep:
\texttt{${seq}} & ${count} & ${"%.2f" % float(percent)} & ${match} \\\
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import subprocess
import os
import logging
import abc
import sh
import zipfile
from bipy.utils import flatten, remove_suffix, is_pair
from bcbio.utils import safe_makedir, file_exists
from mako.template import Template
from bipy.toolbox.reporting import LatexReport, safe_latex
from bipy.pipeline.stages import AbstractStage
from bcbio.log import logger, setup_local_logging
from bcbio.provenance import do
and context:
# Path: bipy/utils.py
# def flatten(l):
# for el in l:
# if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
# for sub in flatten(el):
# yield sub
# else:
# yield el
#
# def remove_suffix(filename):
# filename, extension = os.path.splitext(filename)
# return filename
#
# def is_pair(arg):
# """
# check if 'arg' is a two-item sequence
#
# """
# return is_sequence(arg) and len(arg) == 2
#
# Path: bipy/toolbox/reporting.py
# class LatexReport(object):
# """Abstract class for generating Latex reports. Inherit from this
# and implement template and generate_report"""
# __metaclass__ = abc.ABCMeta
#
# @abc.abstractproperty
# def template(self):
# return
#
# @abc.abstractmethod
# def generate_report(self, *args, **kwargs):
# """Generate the Latex output using the template"""
# return
#
# def safe_latex(to_fix):
# """Escape characters that make LaTeX unhappy.
# Lifted from Brad Chapman (bcbio)
# """
# chars = ["%", "_", "&", "#"]
# for char in chars:
# to_fix = to_fix.replace(char, "\\%s" % char)
# return to_fix
#
# Path: bipy/pipeline/stages.py
# class AbstractStage(object):
# """
# Wrapper around a stage for use with the pipeline manager. Subclasses should
# implement their own __init__ in addition to calling the super
# __init__. __init__ should parse the appropriate information from the config
# dict and save it in the objects state. __call__ should be implemented as a
# pure function with no closures.
#
# """
#
# stage = "abstract"
#
# def __init__(self, config):
# self.config = config
# self._validate_config()
#
# def _start_message(self, in_file, **kwargs):
# if kwargs:
# logger.info("Starting %s on %s with arguments %s." % (self.stage,
# in_file,
# kwargs))
# else:
# logger.info("Starting %s on %s." % (self.stage, in_file))
#
# def _end_message(self, in_file):
# logger.info("%s complete on %s." % (self.stage, in_file))
#
# def _check_run(self, in_file):
# if not file_exists(in_file):
# raise IOError("%s not found." % (in_file))
#
# def __call__(self, in_file):
# pass
#
# def _validate_config(self):
# if "stage" not in self.config:
# raise ValueError('Could not find "stage" in the config file.')
which might include code, classes, or functions. Output only the next line. | % endfor |
Using the snippet: <|code_start|> out_md5 = map(self._get_md5, output)
correct_files = self._correct_files(output)
correct_md5 = map(self._get_md5, correct_files)
self.assertTrue(out_md5 == correct_md5)
#map(os.remove, output)
def _get_md5(self, out_file):
with open(out_file, "rb") as out_handle:
data = out_handle.read()
md5 = hashlib.md5(data)
return md5.digest()
def _correct_files(self, out_files):
dirs = map(os.path.dirname, out_files)
dirs = [os.path.join(x, "correct") for x in dirs]
basenames = map(os.path.basename, out_files)
return [os.path.join(d, f) for d, f in zip(dirs, basenames)]
def test_get_reads_in_bamfile(self):
bam_file = self.config["input_bamdiff"][0]
reads = sam._get_reads_in_bamfile(bam_file)
self.assertTrue(type(reads) == int)
def test_downsample_bam_with_outfile(self):
out_handle = tempfile.NamedTemporaryFile(suffix=".bam")
bam_file = self.config["input_bamdiff"][0]
target_reads = 2
out_file = sam.downsample_bam(bam_file, target_reads, out_handle.name)
self.assertEquals(sam._get_reads_in_bamfile(out_file), target_reads)
<|code_end|>
, determine the next line of code. You have imports:
import yaml
import unittest
import os
import hashlib
import tempfile
from bipy.toolbox import sam
from bcbio.utils import file_exists, flatten
and context (class names, function names, or code) available:
# Path: bipy/toolbox/sam.py
# def downsample_bam(bam_file, target_reads, out_file=None):
# def _get_reads_in_bamfile(bam_file):
# def _get_percentage_to_sample(bam_file, target_reads):
# def bam2sam(in_file, out_file=None):
# def is_sam_or_bam(in_file):
# def is_bam(in_file):
# def is_sam(in_file):
# def coordinate_sort_sam(in_file, config, out_file=None):
# def sortsam(in_file, out_file=None):
# def only_mapped(in_file, out_file=None):
# def only_unmapped(in_file, out_file=None):
# def sam2bam(in_file, out_file=None):
# def bamsort(in_file, out_prefix=None):
# def bam_name_sort(in_file, out_prefix=None):
# def bamindex(in_file):
# def bamdiff(pair, out_prefix=None):
# def get_out_file(out_prefix, in_file, number):
# def __init__(self, config):
# def __call__(self, pair):
# def _get_handles(self, in_file):
# def _dump_rest(self, handles, read):
# def _process_reads(self, handles_0, handles_1, read0, read1):
# def _score_read_pair(self, read0, read1):
# def _az_score_read_pair(self):
# class Disambiguate(AbstractStage):
. Output only the next line. | def test_downsample_bam_with_memoize(self): |
Here is a snippet: <|code_start|>
CONFIG_FILE = "test/utils/test_utils.yaml"
PAIRED_FILES = ["FA14dayrep1_1.fastq", "FA14dayrep1_2.fastq",
"FA1dayrep1_1.fastq", "FA1dayrep1_2.fastq",
"FA28dayrep1_1.fastq", "FA28dayrep1_2.fastq",
"FA3dayrep3_1.fastq", "FA3dayrep3_2.fastq",
"FA2dayrep1_1.fastq", "FA2dayrep1_2.fastq",
"FA3dayrep1_1.fastq", "FA3dayrep1_2.fastq",
"FA7dayrep1_1.fastq", "FA7dayrep1_2.fastq",
"FA14dayrep2_1.fastq", "FA14dayrep2_2.fastq",
"FA1dayrep2_1.fastq", "FA1dayrep2_2.fastq",
"FA28dayrep2_1.fastq", "FA28dayrep2_2.fastq",
"FA2dayrep2_1.fastq", "FA2dayrep2_2.fastq",
"FA3dayrep2_1.fastq", "FA3dayrep2_2.fastq",
"FA7dayrep2_1.fastq", "FA7dayrep2_2.fastq",
"FA1dayrep3_1.fastq", "FA1dayrep3_2.fastq",
"FA28dayrep3_1.fastq", "FA28dayrep3_2.fastq",
"FA2dayrep3_1.fastq", "FA2dayrep3_2.fastq",
"FA3dayrep3_1.fastq", "FA3dayrep3_2.fastq",
"FA7dayrep3_1.fastq", "FA7dayrep3_2.fastq"]
CORRECT_DIR = "test/cutadapt/data/correct"
class TestUtils(unittest.TestCase):
def setUp(self):
<|code_end|>
. Write the next line using the current file imports:
from bipy import utils
import yaml
import unittest
import os
import tempfile
import sh
and context from other files:
# Path: bipy/utils.py
# def in2out(in_file, word, transform=True, out_dir=None):
# def get_stem(filename):
# def combine_pairs(input_files):
# def freeze_files(files, directory):
# def memoize_outfile_to_dir(res_dir, ext):
# def decor(f):
# def wrapper(*args, **kwargs):
# def prepare_ref_file(ref, config):
# def _download_ref(url, ref_dir):
# def build_results_dir(stage_config, config):
# def transform_infile(filename, stage, delim="."):
# def filter_infile(filename, stage, delim="."):
# def remove_suffix(filename):
# def append_stem(filename, word, delim="."):
# def replace_suffix(filename, suffix, delim="."):
# def flatten_options(config):
# def flatten(l):
# def rfind_key(d, item):
# def rfind_value(d, item):
# def validate_config(config, data=True):
# def get_stages(config):
# def _add_full_path(program):
# def find_one_if(predicate, coll):
# def load_yaml(filename):
# def which(program):
# def is_exe(fpath):
# def __init__(self, in_file, **kwargs):
# def curr_file(self):
# def add_file(self, in_file):
# def was_file(self, in_file):
# def update_tracker(tracker, curr_files):
# def curr_files(tracker):
# def dict_to_vectors(d):
# def __getattr__(self, attr):
# def nested_lookup(d, t):
# def get_in(d, t, default=None):
# def is_sequence(arg):
# def is_pair(arg):
# def locate(pattern, root=os.curdir):
# PAIR_FILE_IDENTIFIERS = ["1", "2"]
# class FileWithHistory(object):
# class dotdict(dict):
, which may include functions, classes, or code. Output only the next line. | with open(CONFIG_FILE) as in_handle: |
Given snippet: <|code_start|>
manager = Manager(app)
manager.add_command('db', MigrateCommand)
@manager.command
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from flask.ext.script import Manager
from flask.ext.migrate import MigrateCommand
from flask.ext import migrate
from datawire.model import db
from datawire.views import app
and context:
# Path: datawire/core.py
# def url_for(*a, **kw):
#
# Path: datawire/core.py
# def url_for(*a, **kw):
which might include code, classes, or functions. Output only the next line. | def reset(): |
Given the following code snippet before the placeholder: <|code_start|>from __future__ import with_statement
config = context.config
config.set_main_option('sqlalchemy.url', app.config['SQLALCHEMY_DATABASE_URI'])
target_metadata = db.metadata
def run_migrations_offline():
url = config.get_main_option("sqlalchemy.url")
context.configure(url=url)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
<|code_end|>
, predict the next line using imports from the current file:
from alembic import context
from sqlalchemy import engine_from_config, pool
from datawire.core import app
from datawire.model import db
and context including class names, function names, and sometimes code from other files:
# Path: datawire/core.py
# def url_for(*a, **kw):
#
# Path: datawire/core.py
# def url_for(*a, **kw):
. Output only the next line. | engine = engine_from_config( |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.