Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the following code snippet before the placeholder: <|code_start|># WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
log = HMCClientLogger.HMCClientLogger(__name__)
ROOT = "Cluster"
CONTENT_TYPE = "application/atom+xml, application/vnd.ibm.powervm.uom+xml;type=SharedStoragePool"
class ListSharedStoragePool:
"""
Lists the details of SharedStoragePool
"""
def __init__(self):
"""
initializes root and content-type
"""
self.root = ROOT
self.content_type = CONTENT_TYPE
def list_shared_storagepool(self, ip, cluster_id, x_api_session):
"""
returns a shared storage pool object of a given cluster
Args:
ip : ip address of HMC
cluster_id : the UUID Of the Cluster to get ssp
x_api_session : session to be used
"""
log.log_debug("ssp object of a cluster is started")
<|code_end|>
, predict the next line using imports from the current file:
from src.common import ListModule
from src.utility import HMCClientLogger
and context including class names, function names, and sometimes code from other files:
# Path: src/common/ListModule.py
# class ListModule:
# """
# called in Listing operation to get the object list
# of ManagementConsole,ManagedSystem,LogicalPartition,
# LogicalPartitionProfile,VirtualIOServer and other objects.
# """
# log_object = HMCClientLogger.HMCClientLogger(__name__)
#
# def listing(self, service, ip, root, content_type, Resource, session_id, uuid=None):
#
# """
# Makes an HTTPRequest to get the details of the
# corresponding object and store the response content
# into a python object.
# Args:
# service:uom or web
# ip:ip address of the hmc
# root:root element in rest uri
# content_type:type of object to be extracted
# (logicalpartition,logicalpartitionprofile,
# ManagedSystem,VirtualIOServer and other objects)
# session_id:to access the session
# uuid:root unique id
# Returns:
# list of corresponding objects
# """
# #for ManagementConsole the uuid is none and for other types the uri is appended with roots uuid
# obj_list = []
# xml_object = None
# headers_obj = HmcHeaders.HmcHeaders(service)
# ns = headers_obj.ns
# request_obj = HTTPClient.HTTPClient(service, ip, root, content_type, session_id)
# if uuid == None:
# request_obj.HTTPGet()
# else:
# request_obj.HTTPGet(append=str(uuid)+"/"+Resource)
# if request_obj.response_b:
# root = etree.fromstring(request_obj.response.text)
# entries = root.findall(".//%s:%s"%(Resource,Resource),
# namespaces={"%s" %(Resource): ns["xmlns"]})
# for entry in entries:
# if entry.getchildren() != []:
# xmlstring = etree.tostring(entry)
# xml_object = UOM.CreateFromDocument(xmlstring)
# obj_list.append(xml_object)
# return obj_list
#
# Path: src/utility/HMCClientLogger.py
# class HMCClientLogger:
# def __init__(self,module_name):
# self.logger_module = logging.getLogger(module_name)
# self.logger_module.setLevel(logging.DEBUG)
#
# # create file handler which logs even debug messages
# if not os.path.exists("output/Log"):
# os.makedirs("output/Log")
# filehandler = logging.FileHandler('output/Log/Debug.log')
# filehandler.setLevel(logging.DEBUG)
# consolehandler=logging.StreamHandler()
# consolehandler.setLevel(logging.WARNING)
# # create formatter and add it to the handlers
# fileformatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s',datefmt='%m/%d/%Y %I:%M:%S %p')
# consoleformatter = logging.Formatter(' %(levelname)s : %(message)s')
# filehandler.setFormatter(fileformatter)
# consolehandler.setFormatter(consoleformatter)
# # add the handlers to logger
# self.logger_module.addHandler(filehandler)
# self.logger_module.addHandler(consolehandler)
#
# def log_debug(self,message):
# self.logger_module.debug(message)
# def log_info(self,message):
# self.logger_module.info(message)
# def log_error(self,message):
# self.logger_module.error(message)
# def log_warn(self,message):
# self.logger_module.warn(message)
. Output only the next line. | list_object = ListModule.ListModule() |
Using the snippet: <|code_start|># License for the specific language governing permissions and limitations
# under the License.
log = HMCClientLogger.HMCClientLogger(__name__)
ROOT = "LogicalPartition"
CONTENT_TYPE = "application/vnd.ibm.powervm.uom+xml; Type=ClientNetworkAdapter"
class ListClientNetworkAdapter:
"""
List the details of existing client network adapter
"""
def __init__(self):
"""
assign the root and content_type for request
"""
self.root = ROOT
self.content_type = CONTENT_TYPE
def list_clientnetwork_adapter(self, ip, logicalpartition_id, x_api_session):
"""
returns a list client network adapters available in the given logical partition
Args:
ip : ip address of HMC
logicalpartition_object : object of Logical Partition in which client Network Adapter
is to be created
x_api_session : session to be used
"""
log.log_debug("client network adapter object list is started")
<|code_end|>
, determine the next line of code. You have imports:
from src.common import ListModule
from src.utility import HMCClientLogger
and context (class names, function names, or code) available:
# Path: src/common/ListModule.py
# class ListModule:
# """
# called in Listing operation to get the object list
# of ManagementConsole,ManagedSystem,LogicalPartition,
# LogicalPartitionProfile,VirtualIOServer and other objects.
# """
# log_object = HMCClientLogger.HMCClientLogger(__name__)
#
# def listing(self, service, ip, root, content_type, Resource, session_id, uuid=None):
#
# """
# Makes an HTTPRequest to get the details of the
# corresponding object and store the response content
# into a python object.
# Args:
# service:uom or web
# ip:ip address of the hmc
# root:root element in rest uri
# content_type:type of object to be extracted
# (logicalpartition,logicalpartitionprofile,
# ManagedSystem,VirtualIOServer and other objects)
# session_id:to access the session
# uuid:root unique id
# Returns:
# list of corresponding objects
# """
# #for ManagementConsole the uuid is none and for other types the uri is appended with roots uuid
# obj_list = []
# xml_object = None
# headers_obj = HmcHeaders.HmcHeaders(service)
# ns = headers_obj.ns
# request_obj = HTTPClient.HTTPClient(service, ip, root, content_type, session_id)
# if uuid == None:
# request_obj.HTTPGet()
# else:
# request_obj.HTTPGet(append=str(uuid)+"/"+Resource)
# if request_obj.response_b:
# root = etree.fromstring(request_obj.response.text)
# entries = root.findall(".//%s:%s"%(Resource,Resource),
# namespaces={"%s" %(Resource): ns["xmlns"]})
# for entry in entries:
# if entry.getchildren() != []:
# xmlstring = etree.tostring(entry)
# xml_object = UOM.CreateFromDocument(xmlstring)
# obj_list.append(xml_object)
# return obj_list
#
# Path: src/utility/HMCClientLogger.py
# class HMCClientLogger:
# def __init__(self,module_name):
# self.logger_module = logging.getLogger(module_name)
# self.logger_module.setLevel(logging.DEBUG)
#
# # create file handler which logs even debug messages
# if not os.path.exists("output/Log"):
# os.makedirs("output/Log")
# filehandler = logging.FileHandler('output/Log/Debug.log')
# filehandler.setLevel(logging.DEBUG)
# consolehandler=logging.StreamHandler()
# consolehandler.setLevel(logging.WARNING)
# # create formatter and add it to the handlers
# fileformatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s',datefmt='%m/%d/%Y %I:%M:%S %p')
# consoleformatter = logging.Formatter(' %(levelname)s : %(message)s')
# filehandler.setFormatter(fileformatter)
# consolehandler.setFormatter(consoleformatter)
# # add the handlers to logger
# self.logger_module.addHandler(filehandler)
# self.logger_module.addHandler(consolehandler)
#
# def log_debug(self,message):
# self.logger_module.debug(message)
# def log_info(self,message):
# self.logger_module.info(message)
# def log_error(self,message):
# self.logger_module.error(message)
# def log_warn(self,message):
# self.logger_module.warn(message)
. Output only the next line. | list_object_list = ListModule.ListModule() |
Predict the next line for this snippet: <|code_start|># 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.
class HTTPClient:
def __init__(self, service, ip, root, content_type, session_id=None):
"""
Initializes the default values to the arguments
Args:
service : To specify the type of service(web/uom/pcm)
ip : ip address of the hmc
root : root element in the url
content_type : specifies the content type of the request
session_id : id for the current X_API_Session
"""
self.payload = None
self.response_b = None
self.response = None
<|code_end|>
with the help of current file imports:
import requests
import warnings
from src.utility import HmcHeaders
and context from other files:
# Path: src/utility/HmcHeaders.py
# class HmcHeaders:
#
# """ Contains Headers used in HMC"""
#
#
# def __init__(self,service=None,ip=None,root=None,session_id=None):
# """ Initializes url,namespaces """
#
# self.url="https://%s:12443/rest/api/%s/%s"%(ip,service,root)
# self.ns={'xmlns':'http://www.ibm.com/xmlns/systems/power/firmware/%s/mc/2012_10/'%(service)}
# self.feed_ns={'atom':'http://www.w3.org/2005/Atom'}
#
# def getHeader(self,service,session_id,content_type):
# header={"Content-Type":"%s"%(content_type),"X-API-Session":session_id}
# return header
, which may contain function names, class names, or code. Output only the next line. | HmcHeaders_obj = HmcHeaders.HmcHeaders(service, ip, root, |
Given the code snippet: <|code_start|># License for the specific language governing permissions and limitations
# under the License.
log = HMCClientLogger.HMCClientLogger(__file__)
ROOT = "LogicalPartition"
CONTENT_TYPE = "application/vnd.ibm.powervm.uom+xml;type=VirtualSCSIClientAdapter"
class ListVirtualSCSIClientAdapter:
"""
List the details of the virtual SCSI adapter
for a given logical partition
"""
def __init__(self):
"""
assign the root and content_type for request
"""
self.root = ROOT
self.content_type = CONTENT_TYPE
def list_virtualscsi_clientadapter(self, ip, logicalpartition_id, x_api_session):
"""
returns the list of virtual SCSI adapter available in the
client partition
Args:
ip : ip address of HMC
logicalpartition_id : UUID of the Logical Partition
x_api_session : session to be used
"""
log.log_debug("List of vscsi adapter started")
<|code_end|>
, generate the next line using the imports in this file:
from src.common import ListModule
from src.utility import HMCClientLogger
and context (functions, classes, or occasionally code) from other files:
# Path: src/common/ListModule.py
# class ListModule:
# """
# called in Listing operation to get the object list
# of ManagementConsole,ManagedSystem,LogicalPartition,
# LogicalPartitionProfile,VirtualIOServer and other objects.
# """
# log_object = HMCClientLogger.HMCClientLogger(__name__)
#
# def listing(self, service, ip, root, content_type, Resource, session_id, uuid=None):
#
# """
# Makes an HTTPRequest to get the details of the
# corresponding object and store the response content
# into a python object.
# Args:
# service:uom or web
# ip:ip address of the hmc
# root:root element in rest uri
# content_type:type of object to be extracted
# (logicalpartition,logicalpartitionprofile,
# ManagedSystem,VirtualIOServer and other objects)
# session_id:to access the session
# uuid:root unique id
# Returns:
# list of corresponding objects
# """
# #for ManagementConsole the uuid is none and for other types the uri is appended with roots uuid
# obj_list = []
# xml_object = None
# headers_obj = HmcHeaders.HmcHeaders(service)
# ns = headers_obj.ns
# request_obj = HTTPClient.HTTPClient(service, ip, root, content_type, session_id)
# if uuid == None:
# request_obj.HTTPGet()
# else:
# request_obj.HTTPGet(append=str(uuid)+"/"+Resource)
# if request_obj.response_b:
# root = etree.fromstring(request_obj.response.text)
# entries = root.findall(".//%s:%s"%(Resource,Resource),
# namespaces={"%s" %(Resource): ns["xmlns"]})
# for entry in entries:
# if entry.getchildren() != []:
# xmlstring = etree.tostring(entry)
# xml_object = UOM.CreateFromDocument(xmlstring)
# obj_list.append(xml_object)
# return obj_list
#
# Path: src/utility/HMCClientLogger.py
# class HMCClientLogger:
# def __init__(self,module_name):
# self.logger_module = logging.getLogger(module_name)
# self.logger_module.setLevel(logging.DEBUG)
#
# # create file handler which logs even debug messages
# if not os.path.exists("output/Log"):
# os.makedirs("output/Log")
# filehandler = logging.FileHandler('output/Log/Debug.log')
# filehandler.setLevel(logging.DEBUG)
# consolehandler=logging.StreamHandler()
# consolehandler.setLevel(logging.WARNING)
# # create formatter and add it to the handlers
# fileformatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s',datefmt='%m/%d/%Y %I:%M:%S %p')
# consoleformatter = logging.Formatter(' %(levelname)s : %(message)s')
# filehandler.setFormatter(fileformatter)
# consolehandler.setFormatter(consoleformatter)
# # add the handlers to logger
# self.logger_module.addHandler(filehandler)
# self.logger_module.addHandler(consolehandler)
#
# def log_debug(self,message):
# self.logger_module.debug(message)
# def log_info(self,message):
# self.logger_module.info(message)
# def log_error(self,message):
# self.logger_module.error(message)
# def log_warn(self,message):
# self.logger_module.warn(message)
. Output only the next line. | list_object = ListModule.ListModule() |
Here is a snippet: <|code_start|># 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.
log = HMCClientLogger.HMCClientLogger(__file__)
ROOT = "VirtualIOServer"
CONTENT_TYPE = "application/vnd.ibm.powervm.uom+xml; type=VolumeGroup"
class ListVolumeGroup:
def __init__(self):
"""
initializes root and content-type
"""
self.root = ROOT
self.content_type = CONTENT_TYPE
def list_volumegroup(self, ip, virtualioserver_id, x_api_session):
"""
returns a list of volume group objects available in the given virtualioserver
Args:
ip : ip address of HMC
virtualioserver_id : UUID of VirtualIOServer on which VolumeGroups are to be listed
x_api_session : session to be used
"""
log.log_debug("List of Volume Group started")
<|code_end|>
. Write the next line using the current file imports:
from src.common import ListModule
from src.utility import HMCClientLogger
import xml.etree.ElementTree as etree
and context from other files:
# Path: src/common/ListModule.py
# class ListModule:
# """
# called in Listing operation to get the object list
# of ManagementConsole,ManagedSystem,LogicalPartition,
# LogicalPartitionProfile,VirtualIOServer and other objects.
# """
# log_object = HMCClientLogger.HMCClientLogger(__name__)
#
# def listing(self, service, ip, root, content_type, Resource, session_id, uuid=None):
#
# """
# Makes an HTTPRequest to get the details of the
# corresponding object and store the response content
# into a python object.
# Args:
# service:uom or web
# ip:ip address of the hmc
# root:root element in rest uri
# content_type:type of object to be extracted
# (logicalpartition,logicalpartitionprofile,
# ManagedSystem,VirtualIOServer and other objects)
# session_id:to access the session
# uuid:root unique id
# Returns:
# list of corresponding objects
# """
# #for ManagementConsole the uuid is none and for other types the uri is appended with roots uuid
# obj_list = []
# xml_object = None
# headers_obj = HmcHeaders.HmcHeaders(service)
# ns = headers_obj.ns
# request_obj = HTTPClient.HTTPClient(service, ip, root, content_type, session_id)
# if uuid == None:
# request_obj.HTTPGet()
# else:
# request_obj.HTTPGet(append=str(uuid)+"/"+Resource)
# if request_obj.response_b:
# root = etree.fromstring(request_obj.response.text)
# entries = root.findall(".//%s:%s"%(Resource,Resource),
# namespaces={"%s" %(Resource): ns["xmlns"]})
# for entry in entries:
# if entry.getchildren() != []:
# xmlstring = etree.tostring(entry)
# xml_object = UOM.CreateFromDocument(xmlstring)
# obj_list.append(xml_object)
# return obj_list
#
# Path: src/utility/HMCClientLogger.py
# class HMCClientLogger:
# def __init__(self,module_name):
# self.logger_module = logging.getLogger(module_name)
# self.logger_module.setLevel(logging.DEBUG)
#
# # create file handler which logs even debug messages
# if not os.path.exists("output/Log"):
# os.makedirs("output/Log")
# filehandler = logging.FileHandler('output/Log/Debug.log')
# filehandler.setLevel(logging.DEBUG)
# consolehandler=logging.StreamHandler()
# consolehandler.setLevel(logging.WARNING)
# # create formatter and add it to the handlers
# fileformatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s',datefmt='%m/%d/%Y %I:%M:%S %p')
# consoleformatter = logging.Formatter(' %(levelname)s : %(message)s')
# filehandler.setFormatter(fileformatter)
# consolehandler.setFormatter(consoleformatter)
# # add the handlers to logger
# self.logger_module.addHandler(filehandler)
# self.logger_module.addHandler(consolehandler)
#
# def log_debug(self,message):
# self.logger_module.debug(message)
# def log_info(self,message):
# self.logger_module.info(message)
# def log_error(self,message):
# self.logger_module.error(message)
# def log_warn(self,message):
# self.logger_module.warn(message)
, which may include functions, classes, or code. Output only the next line. | list_object = ListModule.ListModule() |
Using the snippet: <|code_start|># Copyright 2015, 2016 IBM Corp.
#
# All Rights Reserved.
#
# 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.
ROOT = "VirtualIOServer"
CONTENT_TYPE = "application/vnd.ibm.powervm.uom+xml; type=VolumeGroup"
LOGICALVOLUME_NAME = "lv_1"
PHYSICALVOLUME_NAME = "hdisk7"
SCHEMA_VERSION = "V1_3_0"
def sendrequest(xml, ip, root, content_type, x_api_session, vios_uuid, volumegroup_id):
"""
performs the HTTPPost request with modified volume group
"""
<|code_end|>
, determine the next line of code. You have imports:
from src.utility import HTTPClient
from src.generated_src import UOM
import pyxb
and context (class names, function names, or code) available:
# Path: src/utility/HTTPClient.py
# class HTTPClient:
#
# def __init__(self, service, ip, root, content_type, session_id=None):
# """
# Initializes the default values to the arguments
#
# Args:
# service : To specify the type of service(web/uom/pcm)
# ip : ip address of the hmc
# root : root element in the url
# content_type : specifies the content type of the request
# session_id : id for the current X_API_Session
#
# """
#
# self.payload = None
# self.response_b = None
# self.response = None
# HmcHeaders_obj = HmcHeaders.HmcHeaders(service, ip, root,
# session_id)
# global global_HmcHeaders
# global_HmcHeaders = HmcHeaders_obj
# self.head = global_HmcHeaders.getHeader(service, session_id,
# content_type)
#
# def verify_response(self, response):
# """ This function verifies the status code of the request made """
#
# if response.status_code == 200:
# self.response_b = True
# else:
# self.response_b = False
#
# def HTTPGet(self, **kwargs):
# """ This function performs the HTTP get request """
#
# global global_HmcHeaders
# url = global_HmcHeaders.url
# if any(kwargs):
# if not "url" in kwargs:
# l_kwargs = list(kwargs.keys())
# url = global_HmcHeaders.url+"/"+kwargs[l_kwargs[0]]
#
# else:
# url = kwargs["url"]
# self.response = requests.get(url, headers=self.head,
# verify=False)
# # call the verify function to check with the response status
# self.verify_response(self.response)
#
# def HTTPPut(self, payload, **kwargs):
# """ This function performs the HTTP put request """
#
# self.payload = payload
# global global_HmcHeaders
# url = global_HmcHeaders.url
# if any(kwargs):
# if not "url" in kwargs:
# l_kwargs = list(kwargs.keys())
# url = global_HmcHeaders.url+"/"+kwargs[l_kwargs[0]]
# else:
# url = kwargs["url"]
# self.response = requests.put(url, headers=self.head,
# data=self.payload, verify=False)
# # call the verify function to check with the response status
# self.verify_response(self.response)
#
# def HTTPPost(self, payload, **kwargs):
# """ This function performs the HTTP post request """
#
# self.payload = payload
# global global_HmcHeaders
# url = global_HmcHeaders.url
# if any(kwargs):
# if not "url" in kwargs:
# l_kwargs = list(kwargs.keys())
# url = global_HmcHeaders.url+"/"+kwargs[l_kwargs[0]]
# else:
# url = kwargs["url"]
# self.response = requests.post(url, headers=self.head,
# data=self.payload, verify=False)
# # call the verify function to check with the response status
# self.verify_response(self.response)
#
# def HTTPDelete(self, **kwargs):
# """ This function performs the HTTP delete request """
#
# global global_HmcHeaders
# url = global_HmcHeaders.url
# if any(kwargs):
# if not "url" in kwargs:
# l_kwargs = list(kwargs.keys())
# url = global_HmcHeaders.url+"/"+kwargs[l_kwargs[0]]
# else:
# url = kwargs["url"]
# self.response = requests.delete(url, headers=self.head,
# verify=False)
# # call the verify function to check with the response status
# if self.response.status_code == 204:
# self.response_b = True
# else:
# self.response_b = False
. Output only the next line. | http_object = HTTPClient.HTTPClient("uom", ip, root, content_type, x_api_session) |
Using the snippet: <|code_start|>
# as will this
class CouchProvider(object):
def __init__(self, database):
cf = saunter.ConfigWrapper.ConfigWrapper()
# read url from the config
if "couchdb" in cf and "url" in cf["couch"]:
url = cf["saunter"]["couchdb"]["url"]
else:
url = None
# make sure we can connect to the server
server = couchdb.client.Server(url=url)
try:
server.version()
except socket.error:
<|code_end|>
, determine the next line of code. You have imports:
import ConfigParser
import couchdb.client
import random
import socket
import saunter.ConfigWrapper
from saunter.exceptions import ProviderException
and context (class names, function names, or code) available:
# Path: saunter/exceptions.py
# class ProviderException(SaunterExceptions):
# def _get_message(self):
# return self._message
#
# def _set_message(self, message):
# self._message = message
# message = property(_get_message, _set_message)
. Output only the next line. | raise ProviderException('couch server not found at %s' % url) |
Predict the next line after this snippet: <|code_start|>"""
=============
WebDriver
=============
"""
<|code_end|>
using the current file's imports:
from saunter.SaunterWebDriver import SaunterWebDriver
and any relevant context from other files:
# Path: saunter/SaunterWebDriver.py
# class SaunterWebDriver(webdriver.Remote):
# def __init__(self, **kwargs):
# super(SaunterWebDriver, self).__init__(**kwargs)
#
# def find_element_by_locator(self, locator):
# locator_type = locator[:locator.find("=")]
# if locator_type == "":
# raise saunter.exceptions.InvalidLocatorString(locator)
# locator_value = locator[locator.find("=") + 1:]
# if locator_type == 'class':
# return WebElement(self.find_element_by_class_name(locator_value))
# elif locator_type == 'css':
# return WebElement(self.find_element_by_css_selector(locator_value))
# elif locator_type == 'id':
# return WebElement(self.find_element_by_id(locator_value))
# elif locator_type == 'link':
# return WebElement(self.find_element_by_link_text(locator_value))
# elif locator_type == 'name':
# return WebElement(self.find_element_by_name(locator_value))
# elif locator_type == 'plink':
# return WebElement(self.find_element_by_partial_link_text(locator_value))
# elif locator_type == 'tag':
# return WebElement(self.find_element_by_tag_name(locator_value))
# elif locator_type == 'xpath':
# return WebElement(self.find_element_by_xpath(locator_value))
# else:
# raise saunter.exceptions.InvalidLocatorString(locator)
#
# def find_elements_by_locator(self, locator):
# locator_type = locator[:locator.find("=")]
# if locator_type == "":
# raise saunter.exceptions.InvalidLocatorString(locator)
# locator_value = locator[locator.find("=") + 1:]
# if locator_type == 'class':
# elements = self.find_elements_by_class_name(locator_value)
# elif locator_type == 'css':
# elements = self.find_elements_by_css_selector(locator_value)
# elif locator_type == 'id':
# elements = self.find_elements_by_id(locator_value)
# elif locator_type == 'link':
# elements = self.find_elements_by_link_text(locator_value)
# elif locator_type == 'name':
# elements = self.find_elements_by_name(locator_value)
# elif locator_type == 'plink':
# elements = self.find_elements_by_partial_link_text(locator_value)
# elif locator_type == 'tag':
# elements = self.find_elements_by_tag_name(locator_value)
# elif locator_type == 'xpath':
# elements = self.find_elements_by_xpath(locator_value)
# else:
# raise saunter.exceptions.InvalidLocatorString(locator)
#
# return [WebElement(e) for e in elements]
#
# # @deprecated
# @classmethod
# def click(cls, locator):
# driver = se_wrapper().connection
#
# e = cls.find_element_by_locator(locator)
# e.click()
#
# def is_element_present(self, locator):
# try:
# self.find_element_by_locator(locator)
# return True
# except NoSuchElementException:
# return False
#
# def is_visible(self, locator):
# return self.find_element_by_locator(locator).is_displayed()
. Output only the next line. | class WebDriver(SaunterWebDriver): |
Predict the next line for this snippet: <|code_start|># Copyright 2011 Element 34
#
# 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.
"""
======
Number
======
"""
<|code_end|>
with the help of current file imports:
from saunter.po.webdriver.element import Element
from saunter.SeleniumWrapper import SeleniumWrapper as wrapper
from saunter.exceptions import ElementNotFound
from saunter.SaunterWebDriver import SaunterWebDriver
and context from other files:
# Path: saunter/po/webdriver/element.py
# class Element(object):
# """
# Top of the PO element tree
# """
# pass
#
# Path: saunter/exceptions.py
# class ElementNotFound(SaunterExceptions):
# def _get_message(self):
# return self._message
#
# def _set_message(self, message):
# self._message = message
# message = property(_get_message, _set_message)
#
# Path: saunter/SaunterWebDriver.py
# class SaunterWebDriver(webdriver.Remote):
# def __init__(self, **kwargs):
# super(SaunterWebDriver, self).__init__(**kwargs)
#
# def find_element_by_locator(self, locator):
# locator_type = locator[:locator.find("=")]
# if locator_type == "":
# raise saunter.exceptions.InvalidLocatorString(locator)
# locator_value = locator[locator.find("=") + 1:]
# if locator_type == 'class':
# return WebElement(self.find_element_by_class_name(locator_value))
# elif locator_type == 'css':
# return WebElement(self.find_element_by_css_selector(locator_value))
# elif locator_type == 'id':
# return WebElement(self.find_element_by_id(locator_value))
# elif locator_type == 'link':
# return WebElement(self.find_element_by_link_text(locator_value))
# elif locator_type == 'name':
# return WebElement(self.find_element_by_name(locator_value))
# elif locator_type == 'plink':
# return WebElement(self.find_element_by_partial_link_text(locator_value))
# elif locator_type == 'tag':
# return WebElement(self.find_element_by_tag_name(locator_value))
# elif locator_type == 'xpath':
# return WebElement(self.find_element_by_xpath(locator_value))
# else:
# raise saunter.exceptions.InvalidLocatorString(locator)
#
# def find_elements_by_locator(self, locator):
# locator_type = locator[:locator.find("=")]
# if locator_type == "":
# raise saunter.exceptions.InvalidLocatorString(locator)
# locator_value = locator[locator.find("=") + 1:]
# if locator_type == 'class':
# elements = self.find_elements_by_class_name(locator_value)
# elif locator_type == 'css':
# elements = self.find_elements_by_css_selector(locator_value)
# elif locator_type == 'id':
# elements = self.find_elements_by_id(locator_value)
# elif locator_type == 'link':
# elements = self.find_elements_by_link_text(locator_value)
# elif locator_type == 'name':
# elements = self.find_elements_by_name(locator_value)
# elif locator_type == 'plink':
# elements = self.find_elements_by_partial_link_text(locator_value)
# elif locator_type == 'tag':
# elements = self.find_elements_by_tag_name(locator_value)
# elif locator_type == 'xpath':
# elements = self.find_elements_by_xpath(locator_value)
# else:
# raise saunter.exceptions.InvalidLocatorString(locator)
#
# return [WebElement(e) for e in elements]
#
# # @deprecated
# @classmethod
# def click(cls, locator):
# driver = se_wrapper().connection
#
# e = cls.find_element_by_locator(locator)
# e.click()
#
# def is_element_present(self, locator):
# try:
# self.find_element_by_locator(locator)
# return True
# except NoSuchElementException:
# return False
#
# def is_visible(self, locator):
# return self.find_element_by_locator(locator).is_displayed()
, which may contain function names, class names, or code. Output only the next line. | class Number(Element): |
Based on the snippet: <|code_start|>#
# 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.
"""
======
Number
======
"""
class Number(Element):
"""
Base element class for Number fields
"""
def __set__(self, obj, val):
e = SaunterWebDriver.find_element_by_locator(self.locator)
e.send_keys(val)
def __get__(self, obj, cls=None):
try:
e = SaunterWebDriver.find_element_by_locator(self.locator)
return int(e.text)
except AttributeError as e:
if str(e) == "'SeleniumWrapper' object has no attribute 'connection'":
pass
else:
raise e
<|code_end|>
, predict the immediate next line with the help of imports:
from saunter.po.webdriver.element import Element
from saunter.SeleniumWrapper import SeleniumWrapper as wrapper
from saunter.exceptions import ElementNotFound
from saunter.SaunterWebDriver import SaunterWebDriver
and context (classes, functions, sometimes code) from other files:
# Path: saunter/po/webdriver/element.py
# class Element(object):
# """
# Top of the PO element tree
# """
# pass
#
# Path: saunter/exceptions.py
# class ElementNotFound(SaunterExceptions):
# def _get_message(self):
# return self._message
#
# def _set_message(self, message):
# self._message = message
# message = property(_get_message, _set_message)
#
# Path: saunter/SaunterWebDriver.py
# class SaunterWebDriver(webdriver.Remote):
# def __init__(self, **kwargs):
# super(SaunterWebDriver, self).__init__(**kwargs)
#
# def find_element_by_locator(self, locator):
# locator_type = locator[:locator.find("=")]
# if locator_type == "":
# raise saunter.exceptions.InvalidLocatorString(locator)
# locator_value = locator[locator.find("=") + 1:]
# if locator_type == 'class':
# return WebElement(self.find_element_by_class_name(locator_value))
# elif locator_type == 'css':
# return WebElement(self.find_element_by_css_selector(locator_value))
# elif locator_type == 'id':
# return WebElement(self.find_element_by_id(locator_value))
# elif locator_type == 'link':
# return WebElement(self.find_element_by_link_text(locator_value))
# elif locator_type == 'name':
# return WebElement(self.find_element_by_name(locator_value))
# elif locator_type == 'plink':
# return WebElement(self.find_element_by_partial_link_text(locator_value))
# elif locator_type == 'tag':
# return WebElement(self.find_element_by_tag_name(locator_value))
# elif locator_type == 'xpath':
# return WebElement(self.find_element_by_xpath(locator_value))
# else:
# raise saunter.exceptions.InvalidLocatorString(locator)
#
# def find_elements_by_locator(self, locator):
# locator_type = locator[:locator.find("=")]
# if locator_type == "":
# raise saunter.exceptions.InvalidLocatorString(locator)
# locator_value = locator[locator.find("=") + 1:]
# if locator_type == 'class':
# elements = self.find_elements_by_class_name(locator_value)
# elif locator_type == 'css':
# elements = self.find_elements_by_css_selector(locator_value)
# elif locator_type == 'id':
# elements = self.find_elements_by_id(locator_value)
# elif locator_type == 'link':
# elements = self.find_elements_by_link_text(locator_value)
# elif locator_type == 'name':
# elements = self.find_elements_by_name(locator_value)
# elif locator_type == 'plink':
# elements = self.find_elements_by_partial_link_text(locator_value)
# elif locator_type == 'tag':
# elements = self.find_elements_by_tag_name(locator_value)
# elif locator_type == 'xpath':
# elements = self.find_elements_by_xpath(locator_value)
# else:
# raise saunter.exceptions.InvalidLocatorString(locator)
#
# return [WebElement(e) for e in elements]
#
# # @deprecated
# @classmethod
# def click(cls, locator):
# driver = se_wrapper().connection
#
# e = cls.find_element_by_locator(locator)
# e.click()
#
# def is_element_present(self, locator):
# try:
# self.find_element_by_locator(locator)
# return True
# except NoSuchElementException:
# return False
#
# def is_visible(self, locator):
# return self.find_element_by_locator(locator).is_displayed()
. Output only the next line. | except ElementNotFound as e: |
Given the following code snippet before the placeholder: <|code_start|># Copyright 2011 Element 34
#
# 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.
"""
======
Number
======
"""
class Number(Element):
"""
Base element class for Number fields
"""
def __set__(self, obj, val):
<|code_end|>
, predict the next line using imports from the current file:
from saunter.po.webdriver.element import Element
from saunter.SeleniumWrapper import SeleniumWrapper as wrapper
from saunter.exceptions import ElementNotFound
from saunter.SaunterWebDriver import SaunterWebDriver
and context including class names, function names, and sometimes code from other files:
# Path: saunter/po/webdriver/element.py
# class Element(object):
# """
# Top of the PO element tree
# """
# pass
#
# Path: saunter/exceptions.py
# class ElementNotFound(SaunterExceptions):
# def _get_message(self):
# return self._message
#
# def _set_message(self, message):
# self._message = message
# message = property(_get_message, _set_message)
#
# Path: saunter/SaunterWebDriver.py
# class SaunterWebDriver(webdriver.Remote):
# def __init__(self, **kwargs):
# super(SaunterWebDriver, self).__init__(**kwargs)
#
# def find_element_by_locator(self, locator):
# locator_type = locator[:locator.find("=")]
# if locator_type == "":
# raise saunter.exceptions.InvalidLocatorString(locator)
# locator_value = locator[locator.find("=") + 1:]
# if locator_type == 'class':
# return WebElement(self.find_element_by_class_name(locator_value))
# elif locator_type == 'css':
# return WebElement(self.find_element_by_css_selector(locator_value))
# elif locator_type == 'id':
# return WebElement(self.find_element_by_id(locator_value))
# elif locator_type == 'link':
# return WebElement(self.find_element_by_link_text(locator_value))
# elif locator_type == 'name':
# return WebElement(self.find_element_by_name(locator_value))
# elif locator_type == 'plink':
# return WebElement(self.find_element_by_partial_link_text(locator_value))
# elif locator_type == 'tag':
# return WebElement(self.find_element_by_tag_name(locator_value))
# elif locator_type == 'xpath':
# return WebElement(self.find_element_by_xpath(locator_value))
# else:
# raise saunter.exceptions.InvalidLocatorString(locator)
#
# def find_elements_by_locator(self, locator):
# locator_type = locator[:locator.find("=")]
# if locator_type == "":
# raise saunter.exceptions.InvalidLocatorString(locator)
# locator_value = locator[locator.find("=") + 1:]
# if locator_type == 'class':
# elements = self.find_elements_by_class_name(locator_value)
# elif locator_type == 'css':
# elements = self.find_elements_by_css_selector(locator_value)
# elif locator_type == 'id':
# elements = self.find_elements_by_id(locator_value)
# elif locator_type == 'link':
# elements = self.find_elements_by_link_text(locator_value)
# elif locator_type == 'name':
# elements = self.find_elements_by_name(locator_value)
# elif locator_type == 'plink':
# elements = self.find_elements_by_partial_link_text(locator_value)
# elif locator_type == 'tag':
# elements = self.find_elements_by_tag_name(locator_value)
# elif locator_type == 'xpath':
# elements = self.find_elements_by_xpath(locator_value)
# else:
# raise saunter.exceptions.InvalidLocatorString(locator)
#
# return [WebElement(e) for e in elements]
#
# # @deprecated
# @classmethod
# def click(cls, locator):
# driver = se_wrapper().connection
#
# e = cls.find_element_by_locator(locator)
# e.click()
#
# def is_element_present(self, locator):
# try:
# self.find_element_by_locator(locator)
# return True
# except NoSuchElementException:
# return False
#
# def is_visible(self, locator):
# return self.find_element_by_locator(locator).is_displayed()
. Output only the next line. | e = SaunterWebDriver.find_element_by_locator(self.locator) |
Here is a snippet: <|code_start|># Copyright 2011 Element 34
#
# 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.
"""
====
Text
====
"""
<|code_end|>
. Write the next line using the current file imports:
from saunter.po.webdriver.unicode import Unicode
and context from other files:
# Path: saunter/po/webdriver/unicode.py
# class Unicode(Element):
# """
# Base element class for Unicode fields
# """
# def __set__(self, obj, val):
# e = obj.driver.find_element_by_locator(self.locator)
# e.send_keys(val)
#
# def __get__(self, obj, cls=None):
# e = obj.driver.find_element_by_locator(self.locator)
# if e.tag_name in ["input", "textarea"]:
# return e.get_attribute("value")
# return e.text
, which may include functions, classes, or code. Output only the next line. | class Text(Unicode): |
Predict the next line after this snippet: <|code_start|># Copyright 2011 Element 34
#
# 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.
"""
========
Checkbox
========
"""
<|code_end|>
using the current file's imports:
from saunter.po.webdriver.element import Element
and any relevant context from other files:
# Path: saunter/po/webdriver/element.py
# class Element(object):
# """
# Top of the PO element tree
# """
# pass
. Output only the next line. | class CheckBox(Element): |
Given the following code snippet before the placeholder: <|code_start|># Copyright 2011 Element 34
#
# 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.
"""
=======
Unicode
=======
"""
<|code_end|>
, predict the next line using imports from the current file:
from saunter.po.webdriver.element import Element
from saunter.exceptions import ElementNotFound
from saunter.SaunterWebDriver import SaunterWebDriver
and context including class names, function names, and sometimes code from other files:
# Path: saunter/po/webdriver/element.py
# class Element(object):
# """
# Top of the PO element tree
# """
# pass
#
# Path: saunter/exceptions.py
# class ElementNotFound(SaunterExceptions):
# def _get_message(self):
# return self._message
#
# def _set_message(self, message):
# self._message = message
# message = property(_get_message, _set_message)
#
# Path: saunter/SaunterWebDriver.py
# class SaunterWebDriver(webdriver.Remote):
# def __init__(self, **kwargs):
# super(SaunterWebDriver, self).__init__(**kwargs)
#
# def find_element_by_locator(self, locator):
# locator_type = locator[:locator.find("=")]
# if locator_type == "":
# raise saunter.exceptions.InvalidLocatorString(locator)
# locator_value = locator[locator.find("=") + 1:]
# if locator_type == 'class':
# return WebElement(self.find_element_by_class_name(locator_value))
# elif locator_type == 'css':
# return WebElement(self.find_element_by_css_selector(locator_value))
# elif locator_type == 'id':
# return WebElement(self.find_element_by_id(locator_value))
# elif locator_type == 'link':
# return WebElement(self.find_element_by_link_text(locator_value))
# elif locator_type == 'name':
# return WebElement(self.find_element_by_name(locator_value))
# elif locator_type == 'plink':
# return WebElement(self.find_element_by_partial_link_text(locator_value))
# elif locator_type == 'tag':
# return WebElement(self.find_element_by_tag_name(locator_value))
# elif locator_type == 'xpath':
# return WebElement(self.find_element_by_xpath(locator_value))
# else:
# raise saunter.exceptions.InvalidLocatorString(locator)
#
# def find_elements_by_locator(self, locator):
# locator_type = locator[:locator.find("=")]
# if locator_type == "":
# raise saunter.exceptions.InvalidLocatorString(locator)
# locator_value = locator[locator.find("=") + 1:]
# if locator_type == 'class':
# elements = self.find_elements_by_class_name(locator_value)
# elif locator_type == 'css':
# elements = self.find_elements_by_css_selector(locator_value)
# elif locator_type == 'id':
# elements = self.find_elements_by_id(locator_value)
# elif locator_type == 'link':
# elements = self.find_elements_by_link_text(locator_value)
# elif locator_type == 'name':
# elements = self.find_elements_by_name(locator_value)
# elif locator_type == 'plink':
# elements = self.find_elements_by_partial_link_text(locator_value)
# elif locator_type == 'tag':
# elements = self.find_elements_by_tag_name(locator_value)
# elif locator_type == 'xpath':
# elements = self.find_elements_by_xpath(locator_value)
# else:
# raise saunter.exceptions.InvalidLocatorString(locator)
#
# return [WebElement(e) for e in elements]
#
# # @deprecated
# @classmethod
# def click(cls, locator):
# driver = se_wrapper().connection
#
# e = cls.find_element_by_locator(locator)
# e.click()
#
# def is_element_present(self, locator):
# try:
# self.find_element_by_locator(locator)
# return True
# except NoSuchElementException:
# return False
#
# def is_visible(self, locator):
# return self.find_element_by_locator(locator).is_displayed()
. Output only the next line. | class Unicode(Element): |
Given snippet: <|code_start|>
class NoSuchDayException(Exception):
""" Custom exception for trying to select an invalid day of the month
Rather than try and be clever around which days are valid in a month, we trust that
the widget is populating things correctly and just blow up if you request the 4th day
of the month for instance.
"""
pass
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from saunter.po.webdriver.element import Element
and context:
# Path: saunter/po/webdriver/element.py
# class Element(object):
# """
# Top of the PO element tree
# """
# pass
which might include code, classes, or functions. Output only the next line. | class DatePicker(Element): |
Predict the next line after this snippet: <|code_start|># Copyright 2011 Element 34
#
# 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.
"""
=========
Attribute
=========
"""
<|code_end|>
using the current file's imports:
from saunter.po.webdriver.element import Element
from saunter.exceptions import ElementNotFound
and any relevant context from other files:
# Path: saunter/po/webdriver/element.py
# class Element(object):
# """
# Top of the PO element tree
# """
# pass
#
# Path: saunter/exceptions.py
# class ElementNotFound(SaunterExceptions):
# def _get_message(self):
# return self._message
#
# def _set_message(self, message):
# self._message = message
# message = property(_get_message, _set_message)
. Output only the next line. | class Attribute(Element): |
Using the snippet: <|code_start|># 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.
"""
=========
Attribute
=========
"""
class Attribute(Element):
"""
Base element class for Text fields
"""
def __init__(self, element, attribute):
self.locator = element
self.attribute = attribute
def __set__(self, obj, val):
pass
def __get__(self, obj, cls=None):
try:
e = obj.driver.find_element_by_locator(self.locator)
return e.get_attribute(self.attribute)
except AttributeError as e:
if str(e) == "'SeleniumWrapper' object has no attribute 'connection'":
pass
else:
raise e
<|code_end|>
, determine the next line of code. You have imports:
from saunter.po.webdriver.element import Element
from saunter.exceptions import ElementNotFound
and context (class names, function names, or code) available:
# Path: saunter/po/webdriver/element.py
# class Element(object):
# """
# Top of the PO element tree
# """
# pass
#
# Path: saunter/exceptions.py
# class ElementNotFound(SaunterExceptions):
# def _get_message(self):
# return self._message
#
# def _set_message(self, message):
# self._message = message
# message = property(_get_message, _set_message)
. Output only the next line. | except ElementNotFound as e: |
Given the following code snippet before the placeholder: <|code_start|># Copyright 2011 Element 34
#
# 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.
class SaunterWebDriver(webdriver.Remote):
def __init__(self, **kwargs):
super(SaunterWebDriver, self).__init__(**kwargs)
def find_element_by_locator(self, locator):
locator_type = locator[:locator.find("=")]
if locator_type == "":
raise saunter.exceptions.InvalidLocatorString(locator)
locator_value = locator[locator.find("=") + 1:]
if locator_type == 'class':
<|code_end|>
, predict the next line using imports from the current file:
import saunter.exceptions
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from saunter.web_element import WebElement
and context including class names, function names, and sometimes code from other files:
# Path: saunter/web_element.py
# class WebElement(WebElement):
# def __init__(self, element):
# self.__dict__.update(element.__dict__)
#
# def find_element_by_locator(self, locator):
# locator_type = locator[:locator.find("=")]
# if locator_type == "":
# raise saunter.exceptions.InvalidLocatorString(locator)
# locator_value = locator[locator.find("=") + 1:]
# if locator_type == 'class':
# return WebElement(self.find_element_by_class_name(locator_value))
# elif locator_type == 'css':
# return WebElement(self.find_element_by_css_selector(locator_value))
# elif locator_type == 'id':
# return WebElement(self.find_element_by_id(locator_value))
# elif locator_type == 'link':
# return WebElement(self.find_element_by_link_text(locator_value))
# elif locator_type == 'name':
# return WebElement(self.find_element_by_name(locator_value))
# elif locator_type == 'plink':
# return WebElement(self.find_element_by_partial_link_text(locator_value))
# elif locator_type == 'tag':
# return WebElement(self.find_element_by_tag_name(locator_value))
# elif locator_type == 'xpath':
# return WebElement(self.find_element_by_xpath(locator_value))
# else:
# raise saunter.exceptions.InvalidLocatorString(locator)
#
# def find_elements_by_locator(self, locator):
# locator_type = locator[:locator.find("=")]
# if locator_type == "":
# raise saunter.exceptions.InvalidLocatorString(locator)
# locator_value = locator[locator.find("=") + 1:]
# if locator_type == 'class':
# elements = self.find_elements_by_class_name(locator_value)
# elif locator_type == 'css':
# elements = self.find_elements_by_css_selector(locator_value)
# elif locator_type == 'id':
# elements = self.find_elements_by_id(locator_value)
# elif locator_type == 'link':
# elements = self.find_elements_by_link_text(locator_value)
# elif locator_type == 'name':
# elements = self.find_elements_by_name(locator_value)
# elif locator_type == 'plink':
# elements = self.find_elements_by_partial_link_text(locator_value)
# elif locator_type == 'tag':
# elements = self.find_elements_by_tag_name(locator_value)
# elif locator_type == 'xpath':
# elements = self.find_elements_by_xpath(locator_value)
# else:
# raise saunter.exceptions.InvalidLocatorString(locator)
#
# return [WebElement(e) for e in elements]
. Output only the next line. | return WebElement(self.find_element_by_class_name(locator_value)) |
Given the code snippet: <|code_start|>#!/usr/bin/python3
# -!- encoding:utf8 -!-
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# file: test.py
# date: 2017-09-19
# author: paul.dautry
# purpose:
# Module (incomplete :/) testing
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#===============================================================================
# IMPORTS
#===============================================================================
#===============================================================================
# FUNCTIONS
#===============================================================================
#-------------------------------------------------------------------------------
# main
#-------------------------------------------------------------------------------
def main():
ini.test()
db.test()
logger.test()
<|code_end|>
, generate the next line using the imports in this file:
from core.modules import ini
from core.modules import db
from core.modules import logger
from core.modules import nominatim
from core.modules import validator
from core.classes import response
from core import mapif
and context (functions, classes, or occasionally code) from other files:
# Path: core/modules/ini.py
# _CONFIG_ = None
# _CONFIG_ = configparser.ConfigParser()
# def init(filename):
# def getenv(env_var, default=None):
# def config(section, option, env_var=None, default=None, boolean=False):
# def test():
#
# Path: core/modules/nominatim.py
# _SEARCH_BASE_URL_ = "http://nominatim.openstreetmap.org/search/"
# _SEARCH_PARAMS_ = {
# 'format': 'json',
# 'addressdetails':'1',
# 'limit':'1'
# }
# _REVERSE_BASE_URL_ = "http://nominatim.openstreetmap.org/reverse"
# _REVERSE_PARAMS_ = {
# 'format': 'json',
# 'addressdetails':'1'
# }
# _OSM_TYPES_ = {
# 'way': 'W',
# 'node': 'N',
# 'relation': 'R'
# }
# def location_for(city, country):
# def reverse_location_for(osm_id, osm_type):
# def test():
#
# Path: core/modules/validator.py
# _VALIDATORS_ = {
# 'email': re.compile('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'),
# 'alphanum': re.compile('^\w+$'),
# 'int': re.compile('^\d+$'),
# 'double': re.compile('^\d+(\.\d+)?$'),
# 'phone': re.compile('^(\+\d{2}(\s)?\d|\d{2})(\s)?(\d{2}(\s)?){4}$'),
# 'year': re.compile('^\d{4}$'),
# 'timestamp': re.compile('^\d{4}(-\d{2}){2}$')
# }
# def validate(field, vtype=None):
# def is_empty(field):
# def check_captcha(request):
# def normalize_filter(search_filter):
# def test():
#
# Path: core/classes/response.py
# class Response(object):
# def __init__(self, has_error = True, content = {}, code=None):
# def json(self):
# def dumps(self, indent=None):
# def test():
#
# Path: core/mapif.py
# def _load_user(session, email, sha_pwd):
# def _update_user(session, uid):
# def _check_connected(session):
# def _hash_pwd(plain_pwd):
# def beforeRequest():
# def root():
# def profile():
# def login():
# def logout():
# def password_reset():
# def password_reset_page():
# def search_users():
# def account_create():
# def account_update_names():
# def account_update_email():
# def account_update_password():
# def account_update_promo():
# def account_delete():
# def locations():
# def location_create():
# def location_update():
# def location_delete():
# def page_not_found(msg):
# def run():
# def test():
. Output only the next line. | nominatim.test() |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/python3
# -!- encoding:utf8 -!-
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# file: test.py
# date: 2017-09-19
# author: paul.dautry
# purpose:
# Module (incomplete :/) testing
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#===============================================================================
# IMPORTS
#===============================================================================
#===============================================================================
# FUNCTIONS
#===============================================================================
#-------------------------------------------------------------------------------
# main
#-------------------------------------------------------------------------------
def main():
ini.test()
db.test()
logger.test()
nominatim.test()
response.test()
timer.test()
<|code_end|>
, predict the next line using imports from the current file:
from core.modules import ini
from core.modules import db
from core.modules import logger
from core.modules import nominatim
from core.modules import validator
from core.classes import response
from core import mapif
and context including class names, function names, and sometimes code from other files:
# Path: core/modules/ini.py
# _CONFIG_ = None
# _CONFIG_ = configparser.ConfigParser()
# def init(filename):
# def getenv(env_var, default=None):
# def config(section, option, env_var=None, default=None, boolean=False):
# def test():
#
# Path: core/modules/nominatim.py
# _SEARCH_BASE_URL_ = "http://nominatim.openstreetmap.org/search/"
# _SEARCH_PARAMS_ = {
# 'format': 'json',
# 'addressdetails':'1',
# 'limit':'1'
# }
# _REVERSE_BASE_URL_ = "http://nominatim.openstreetmap.org/reverse"
# _REVERSE_PARAMS_ = {
# 'format': 'json',
# 'addressdetails':'1'
# }
# _OSM_TYPES_ = {
# 'way': 'W',
# 'node': 'N',
# 'relation': 'R'
# }
# def location_for(city, country):
# def reverse_location_for(osm_id, osm_type):
# def test():
#
# Path: core/modules/validator.py
# _VALIDATORS_ = {
# 'email': re.compile('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'),
# 'alphanum': re.compile('^\w+$'),
# 'int': re.compile('^\d+$'),
# 'double': re.compile('^\d+(\.\d+)?$'),
# 'phone': re.compile('^(\+\d{2}(\s)?\d|\d{2})(\s)?(\d{2}(\s)?){4}$'),
# 'year': re.compile('^\d{4}$'),
# 'timestamp': re.compile('^\d{4}(-\d{2}){2}$')
# }
# def validate(field, vtype=None):
# def is_empty(field):
# def check_captcha(request):
# def normalize_filter(search_filter):
# def test():
#
# Path: core/classes/response.py
# class Response(object):
# def __init__(self, has_error = True, content = {}, code=None):
# def json(self):
# def dumps(self, indent=None):
# def test():
#
# Path: core/mapif.py
# def _load_user(session, email, sha_pwd):
# def _update_user(session, uid):
# def _check_connected(session):
# def _hash_pwd(plain_pwd):
# def beforeRequest():
# def root():
# def profile():
# def login():
# def logout():
# def password_reset():
# def password_reset_page():
# def search_users():
# def account_create():
# def account_update_names():
# def account_update_email():
# def account_update_password():
# def account_update_promo():
# def account_delete():
# def locations():
# def location_create():
# def location_update():
# def location_delete():
# def page_not_found(msg):
# def run():
# def test():
. Output only the next line. | validator.test() |
Using the snippet: <|code_start|>#!/usr/bin/python3
# -!- encoding:utf8 -!-
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# file: test.py
# date: 2017-09-19
# author: paul.dautry
# purpose:
# Module (incomplete :/) testing
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#===============================================================================
# IMPORTS
#===============================================================================
#===============================================================================
# FUNCTIONS
#===============================================================================
#-------------------------------------------------------------------------------
# main
#-------------------------------------------------------------------------------
def main():
ini.test()
db.test()
logger.test()
nominatim.test()
<|code_end|>
, determine the next line of code. You have imports:
from core.modules import ini
from core.modules import db
from core.modules import logger
from core.modules import nominatim
from core.modules import validator
from core.classes import response
from core import mapif
and context (class names, function names, or code) available:
# Path: core/modules/ini.py
# _CONFIG_ = None
# _CONFIG_ = configparser.ConfigParser()
# def init(filename):
# def getenv(env_var, default=None):
# def config(section, option, env_var=None, default=None, boolean=False):
# def test():
#
# Path: core/modules/nominatim.py
# _SEARCH_BASE_URL_ = "http://nominatim.openstreetmap.org/search/"
# _SEARCH_PARAMS_ = {
# 'format': 'json',
# 'addressdetails':'1',
# 'limit':'1'
# }
# _REVERSE_BASE_URL_ = "http://nominatim.openstreetmap.org/reverse"
# _REVERSE_PARAMS_ = {
# 'format': 'json',
# 'addressdetails':'1'
# }
# _OSM_TYPES_ = {
# 'way': 'W',
# 'node': 'N',
# 'relation': 'R'
# }
# def location_for(city, country):
# def reverse_location_for(osm_id, osm_type):
# def test():
#
# Path: core/modules/validator.py
# _VALIDATORS_ = {
# 'email': re.compile('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'),
# 'alphanum': re.compile('^\w+$'),
# 'int': re.compile('^\d+$'),
# 'double': re.compile('^\d+(\.\d+)?$'),
# 'phone': re.compile('^(\+\d{2}(\s)?\d|\d{2})(\s)?(\d{2}(\s)?){4}$'),
# 'year': re.compile('^\d{4}$'),
# 'timestamp': re.compile('^\d{4}(-\d{2}){2}$')
# }
# def validate(field, vtype=None):
# def is_empty(field):
# def check_captcha(request):
# def normalize_filter(search_filter):
# def test():
#
# Path: core/classes/response.py
# class Response(object):
# def __init__(self, has_error = True, content = {}, code=None):
# def json(self):
# def dumps(self, indent=None):
# def test():
#
# Path: core/mapif.py
# def _load_user(session, email, sha_pwd):
# def _update_user(session, uid):
# def _check_connected(session):
# def _hash_pwd(plain_pwd):
# def beforeRequest():
# def root():
# def profile():
# def login():
# def logout():
# def password_reset():
# def password_reset_page():
# def search_users():
# def account_create():
# def account_update_names():
# def account_update_email():
# def account_update_password():
# def account_update_promo():
# def account_delete():
# def locations():
# def location_create():
# def location_update():
# def location_delete():
# def page_not_found(msg):
# def run():
# def test():
. Output only the next line. | response.test() |
Given the code snippet: <|code_start|>#!/usr/bin/python3
# -!- encoding:utf8 -!-
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# file: test.py
# date: 2017-09-19
# author: paul.dautry
# purpose:
# Module (incomplete :/) testing
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#===============================================================================
# IMPORTS
#===============================================================================
#===============================================================================
# FUNCTIONS
#===============================================================================
#-------------------------------------------------------------------------------
# main
#-------------------------------------------------------------------------------
def main():
ini.test()
db.test()
logger.test()
nominatim.test()
response.test()
timer.test()
validator.test()
<|code_end|>
, generate the next line using the imports in this file:
from core.modules import ini
from core.modules import db
from core.modules import logger
from core.modules import nominatim
from core.modules import validator
from core.classes import response
from core import mapif
and context (functions, classes, or occasionally code) from other files:
# Path: core/modules/ini.py
# _CONFIG_ = None
# _CONFIG_ = configparser.ConfigParser()
# def init(filename):
# def getenv(env_var, default=None):
# def config(section, option, env_var=None, default=None, boolean=False):
# def test():
#
# Path: core/modules/nominatim.py
# _SEARCH_BASE_URL_ = "http://nominatim.openstreetmap.org/search/"
# _SEARCH_PARAMS_ = {
# 'format': 'json',
# 'addressdetails':'1',
# 'limit':'1'
# }
# _REVERSE_BASE_URL_ = "http://nominatim.openstreetmap.org/reverse"
# _REVERSE_PARAMS_ = {
# 'format': 'json',
# 'addressdetails':'1'
# }
# _OSM_TYPES_ = {
# 'way': 'W',
# 'node': 'N',
# 'relation': 'R'
# }
# def location_for(city, country):
# def reverse_location_for(osm_id, osm_type):
# def test():
#
# Path: core/modules/validator.py
# _VALIDATORS_ = {
# 'email': re.compile('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'),
# 'alphanum': re.compile('^\w+$'),
# 'int': re.compile('^\d+$'),
# 'double': re.compile('^\d+(\.\d+)?$'),
# 'phone': re.compile('^(\+\d{2}(\s)?\d|\d{2})(\s)?(\d{2}(\s)?){4}$'),
# 'year': re.compile('^\d{4}$'),
# 'timestamp': re.compile('^\d{4}(-\d{2}){2}$')
# }
# def validate(field, vtype=None):
# def is_empty(field):
# def check_captcha(request):
# def normalize_filter(search_filter):
# def test():
#
# Path: core/classes/response.py
# class Response(object):
# def __init__(self, has_error = True, content = {}, code=None):
# def json(self):
# def dumps(self, indent=None):
# def test():
#
# Path: core/mapif.py
# def _load_user(session, email, sha_pwd):
# def _update_user(session, uid):
# def _check_connected(session):
# def _hash_pwd(plain_pwd):
# def beforeRequest():
# def root():
# def profile():
# def login():
# def logout():
# def password_reset():
# def password_reset_page():
# def search_users():
# def account_create():
# def account_update_names():
# def account_update_email():
# def account_update_password():
# def account_update_promo():
# def account_delete():
# def locations():
# def location_create():
# def location_update():
# def location_delete():
# def page_not_found(msg):
# def run():
# def test():
. Output only the next line. | mapif.test() |
Given the following code snippet before the placeholder: <|code_start|> 'int': re.compile('^\d+$'),
'double': re.compile('^\d+(\.\d+)?$'),
'phone': re.compile('^(\+\d{2}(\s)?\d|\d{2})(\s)?(\d{2}(\s)?){4}$'),
'year': re.compile('^\d{4}$'),
'timestamp': re.compile('^\d{4}(-\d{2}){2}$')
}
#===============================================================================
# FUNCTIONS
#===============================================================================
#-------------------------------------------------------------------------------
# validate
# (In)Validates data based on its type using regular expressions
#-------------------------------------------------------------------------------
def validate(field, vtype=None):
if vtype in _VALIDATORS_.keys():
return True if _VALIDATORS_[vtype].match(str(field)) else False
else:
return False
#-------------------------------------------------------------------------------
# is_empty
# Tests if a field is empty
#-------------------------------------------------------------------------------
def is_empty(field):
return len(str(field).strip()) == 0
#-------------------------------------------------------------------------------
# check_captcha
# Google ReCaptcha validation process
#-------------------------------------------------------------------------------
def check_captcha(request):
payload = {
<|code_end|>
, predict the next line using imports from the current file:
import re
import json
from core.modules import ini
from core.modules import logger
from core.modules import request
and context including class names, function names, and sometimes code from other files:
# Path: core/modules/ini.py
# _CONFIG_ = None
# _CONFIG_ = configparser.ConfigParser()
# def init(filename):
# def getenv(env_var, default=None):
# def config(section, option, env_var=None, default=None, boolean=False):
# def test():
. Output only the next line. | 'secret': ini.config('RECAPTCHA','recaptcha_secret_key'), |
Based on the snippet: <|code_start|> if 'password1' not in request.form or 'password2' not in request.form or request.form['password1'] != request.form['password2']:
return render_template('password-reset.html', reset_form=True, error='Deux fois le même mot de passe on a dit...')
new_pass = request.form['password1']
hashed_pass = _hash_pwd(new_pass)
if db.update_user(user.id, pwd=hashed_pass):
db.set_password_reset_used(user.id)
return render_template('password-reset.html', reset_form=False)
else:
return render_template('password-reset.html', reset_form=True, error='A merde, y a eu une couille.')
#-------------------------------------------------------------------------------
# search_users
# This route can be used to search users based on given filters
#-------------------------------------------------------------------------------
@app.route('/search/users', methods=['POST'])
@internal_error_handler('534RCHU53R5K0')
@require_connected()
def search_users():
filters = request.form['filters']
content = db.search_users(filters)
return json_response(Response(False, content).json(), status_code=200)
#-------------------------------------------------------------------------------
# account_create
# This route can be used by the application to add a new user to the application
#-------------------------------------------------------------------------------
@app.route('/account/create', methods=['POST'])
@internal_error_handler('4CC0U7CR34T3K0')
@require_disconnected()
def account_create():
content = "Captcha invalide. Annulation de l'inscription ! Encore un bot..."
err = True
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import uuid
import locale
import hashlib
import binascii
import datetime
from flask import Flask
from flask import request
from flask import session
from flask import redirect
from flask import abort
from flask import render_template
from flask import flash
from flask import escape
from flask_responses import json_response
from flask_responses import xml_response
from flask_responses import auto_response
from flask_cors import CORS
from core.modules import db
from core.modules import validator
from core.modules import ini
from core.modules import logger
from core.modules import emails
from core.modules.wrappers import internal_error_handler
from core.modules.wrappers import require_connected
from core.modules.wrappers import require_disconnected
from core.classes.response import Response
from core.classes.slack_log_handler import SlackLogHandler
and context (classes, functions, sometimes code) from other files:
# Path: core/modules/validator.py
# _VALIDATORS_ = {
# 'email': re.compile('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'),
# 'alphanum': re.compile('^\w+$'),
# 'int': re.compile('^\d+$'),
# 'double': re.compile('^\d+(\.\d+)?$'),
# 'phone': re.compile('^(\+\d{2}(\s)?\d|\d{2})(\s)?(\d{2}(\s)?){4}$'),
# 'year': re.compile('^\d{4}$'),
# 'timestamp': re.compile('^\d{4}(-\d{2}){2}$')
# }
# def validate(field, vtype=None):
# def is_empty(field):
# def check_captcha(request):
# def normalize_filter(search_filter):
# def test():
#
# Path: core/modules/ini.py
# _CONFIG_ = None
# _CONFIG_ = configparser.ConfigParser()
# def init(filename):
# def getenv(env_var, default=None):
# def config(section, option, env_var=None, default=None, boolean=False):
# def test():
#
# Path: core/modules/wrappers.py
# def internal_error_handler(err_code):
# def wrapper(f):
# @wraps(f)
# def wrapped_f(*args, **kwargs):
# try:
# return f(*args, **kwargs)
# except Exception as e:
# timestamp = time.strftime('%d%m%H%M%S')
# desc = '`mapif.{0}()` at `{1}` error: details below.'.format(
# f.__name__, timestamp
# )
# modlgr.exception(desc)
# code = '{0}.{1}'.format(err_code, timestamp)
# resp = Response(has_error=True, code=code, content='')
# return json_response(resp.json(), status_code=500)
# return wrapped_f
# return wrapper
#
# Path: core/modules/wrappers.py
# def require_connected():
# def wrapper(f):
# @wraps(f)
# def wrapped_f(*args, **kwargs):
# if not session.get('user', None):
# resp = Response(True, "Opération interdite vous n'êtes pas connecté !")
# return json_response(resp.json(), status_code=403)
# else:
# return f(*args, **kwargs)
# return wrapped_f
# return wrapper
#
# Path: core/modules/wrappers.py
# def require_disconnected():
# def wrapper(f):
# @wraps(f)
# def wrapped_f(*args, **kwargs):
# if session.get('user', None):
# resp = Response(True, "Opération interdite vous n'êtes pas déconnecté !")
# return json_response(resp.json(), status_code=403)
# else:
# return f(*args, **kwargs)
# return wrapped_f
# return wrapper
#
# Path: core/classes/response.py
# class Response(object):
# def __init__(self, has_error = True, content = {}, code=None):
# super(Response, self).__init__()
# self.has_error = has_error
# self.content = content
# self.code = code
# #---------------------------------------------------------------------------
# # json
# #---------------------------------------------------------------------------
# def json(self):
# return {
# 'has_error': self.has_error,
# 'content': self.content,
# 'code': self.code
# }
# #---------------------------------------------------------------------------
# # dumps
# #---------------------------------------------------------------------------
# def dumps(self, indent=None):
# return json.dumps(self.json(), indent=indent)
. Output only the next line. | if app.debug or validator.check_captcha(request): |
Based on the snippet: <|code_start|># license:
# MapIF - Where are INSA de Lyon IF students right now ?
# Copyright (C) 2017 Loic Touzard
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#===============================================================================
# IMPORTS
#===============================================================================
#===============================================================================
# GLOBALS
#===============================================================================
# initialize logger
logger.init()
modlgr = logger.get('mapif.api')
# print current root for debugging
modlgr.debug("Running from {0}".format(os.getcwd()))
# load config file and exit on error
modlgr.debug("Loading configuration file...")
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import uuid
import locale
import hashlib
import binascii
import datetime
from flask import Flask
from flask import request
from flask import session
from flask import redirect
from flask import abort
from flask import render_template
from flask import flash
from flask import escape
from flask_responses import json_response
from flask_responses import xml_response
from flask_responses import auto_response
from flask_cors import CORS
from core.modules import db
from core.modules import validator
from core.modules import ini
from core.modules import logger
from core.modules import emails
from core.modules.wrappers import internal_error_handler
from core.modules.wrappers import require_connected
from core.modules.wrappers import require_disconnected
from core.classes.response import Response
from core.classes.slack_log_handler import SlackLogHandler
and context (classes, functions, sometimes code) from other files:
# Path: core/modules/validator.py
# _VALIDATORS_ = {
# 'email': re.compile('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'),
# 'alphanum': re.compile('^\w+$'),
# 'int': re.compile('^\d+$'),
# 'double': re.compile('^\d+(\.\d+)?$'),
# 'phone': re.compile('^(\+\d{2}(\s)?\d|\d{2})(\s)?(\d{2}(\s)?){4}$'),
# 'year': re.compile('^\d{4}$'),
# 'timestamp': re.compile('^\d{4}(-\d{2}){2}$')
# }
# def validate(field, vtype=None):
# def is_empty(field):
# def check_captcha(request):
# def normalize_filter(search_filter):
# def test():
#
# Path: core/modules/ini.py
# _CONFIG_ = None
# _CONFIG_ = configparser.ConfigParser()
# def init(filename):
# def getenv(env_var, default=None):
# def config(section, option, env_var=None, default=None, boolean=False):
# def test():
#
# Path: core/modules/wrappers.py
# def internal_error_handler(err_code):
# def wrapper(f):
# @wraps(f)
# def wrapped_f(*args, **kwargs):
# try:
# return f(*args, **kwargs)
# except Exception as e:
# timestamp = time.strftime('%d%m%H%M%S')
# desc = '`mapif.{0}()` at `{1}` error: details below.'.format(
# f.__name__, timestamp
# )
# modlgr.exception(desc)
# code = '{0}.{1}'.format(err_code, timestamp)
# resp = Response(has_error=True, code=code, content='')
# return json_response(resp.json(), status_code=500)
# return wrapped_f
# return wrapper
#
# Path: core/modules/wrappers.py
# def require_connected():
# def wrapper(f):
# @wraps(f)
# def wrapped_f(*args, **kwargs):
# if not session.get('user', None):
# resp = Response(True, "Opération interdite vous n'êtes pas connecté !")
# return json_response(resp.json(), status_code=403)
# else:
# return f(*args, **kwargs)
# return wrapped_f
# return wrapper
#
# Path: core/modules/wrappers.py
# def require_disconnected():
# def wrapper(f):
# @wraps(f)
# def wrapped_f(*args, **kwargs):
# if session.get('user', None):
# resp = Response(True, "Opération interdite vous n'êtes pas déconnecté !")
# return json_response(resp.json(), status_code=403)
# else:
# return f(*args, **kwargs)
# return wrapped_f
# return wrapper
#
# Path: core/classes/response.py
# class Response(object):
# def __init__(self, has_error = True, content = {}, code=None):
# super(Response, self).__init__()
# self.has_error = has_error
# self.content = content
# self.code = code
# #---------------------------------------------------------------------------
# # json
# #---------------------------------------------------------------------------
# def json(self):
# return {
# 'has_error': self.has_error,
# 'content': self.content,
# 'code': self.code
# }
# #---------------------------------------------------------------------------
# # dumps
# #---------------------------------------------------------------------------
# def dumps(self, indent=None):
# return json.dumps(self.json(), indent=indent)
. Output only the next line. | if not ini.init('mapif.ini'): |
Predict the next line after this snippet: <|code_start|> 'promo': usr.promo
}
#-------------------------------------------------------------------------------
# _check_connected
# check if user is connected (user in session)
#-------------------------------------------------------------------------------
def _check_connected(session):
return session.get('user', None)
#-------------------------------------------------------------------------------
# _hash_pwd
# hash given password using SHA-256 algorithm from hashlib
#-------------------------------------------------------------------------------
def _hash_pwd(plain_pwd):
return hashlib.sha256(plain_pwd.encode()).hexdigest()
#===============================================================================
# FLASK ROUTES
#===============================================================================
#-------------------------------------------------------------------------------
# beforeRequest
# override of Flask.beforeRequest method to ensure client is using HTTPS !
#-------------------------------------------------------------------------------
@app.before_request
def beforeRequest():
if not app.debug and 'https' not in request.url:
return redirect(request.url.replace('http', 'https'))
#-------------------------------------------------------------------------------
# root
# This is the main application's route. It displays the application main page.
#-------------------------------------------------------------------------------
@app.route('/', methods=['GET'])
<|code_end|>
using the current file's imports:
import os
import uuid
import locale
import hashlib
import binascii
import datetime
from flask import Flask
from flask import request
from flask import session
from flask import redirect
from flask import abort
from flask import render_template
from flask import flash
from flask import escape
from flask_responses import json_response
from flask_responses import xml_response
from flask_responses import auto_response
from flask_cors import CORS
from core.modules import db
from core.modules import validator
from core.modules import ini
from core.modules import logger
from core.modules import emails
from core.modules.wrappers import internal_error_handler
from core.modules.wrappers import require_connected
from core.modules.wrappers import require_disconnected
from core.classes.response import Response
from core.classes.slack_log_handler import SlackLogHandler
and any relevant context from other files:
# Path: core/modules/validator.py
# _VALIDATORS_ = {
# 'email': re.compile('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'),
# 'alphanum': re.compile('^\w+$'),
# 'int': re.compile('^\d+$'),
# 'double': re.compile('^\d+(\.\d+)?$'),
# 'phone': re.compile('^(\+\d{2}(\s)?\d|\d{2})(\s)?(\d{2}(\s)?){4}$'),
# 'year': re.compile('^\d{4}$'),
# 'timestamp': re.compile('^\d{4}(-\d{2}){2}$')
# }
# def validate(field, vtype=None):
# def is_empty(field):
# def check_captcha(request):
# def normalize_filter(search_filter):
# def test():
#
# Path: core/modules/ini.py
# _CONFIG_ = None
# _CONFIG_ = configparser.ConfigParser()
# def init(filename):
# def getenv(env_var, default=None):
# def config(section, option, env_var=None, default=None, boolean=False):
# def test():
#
# Path: core/modules/wrappers.py
# def internal_error_handler(err_code):
# def wrapper(f):
# @wraps(f)
# def wrapped_f(*args, **kwargs):
# try:
# return f(*args, **kwargs)
# except Exception as e:
# timestamp = time.strftime('%d%m%H%M%S')
# desc = '`mapif.{0}()` at `{1}` error: details below.'.format(
# f.__name__, timestamp
# )
# modlgr.exception(desc)
# code = '{0}.{1}'.format(err_code, timestamp)
# resp = Response(has_error=True, code=code, content='')
# return json_response(resp.json(), status_code=500)
# return wrapped_f
# return wrapper
#
# Path: core/modules/wrappers.py
# def require_connected():
# def wrapper(f):
# @wraps(f)
# def wrapped_f(*args, **kwargs):
# if not session.get('user', None):
# resp = Response(True, "Opération interdite vous n'êtes pas connecté !")
# return json_response(resp.json(), status_code=403)
# else:
# return f(*args, **kwargs)
# return wrapped_f
# return wrapper
#
# Path: core/modules/wrappers.py
# def require_disconnected():
# def wrapper(f):
# @wraps(f)
# def wrapped_f(*args, **kwargs):
# if session.get('user', None):
# resp = Response(True, "Opération interdite vous n'êtes pas déconnecté !")
# return json_response(resp.json(), status_code=403)
# else:
# return f(*args, **kwargs)
# return wrapped_f
# return wrapper
#
# Path: core/classes/response.py
# class Response(object):
# def __init__(self, has_error = True, content = {}, code=None):
# super(Response, self).__init__()
# self.has_error = has_error
# self.content = content
# self.code = code
# #---------------------------------------------------------------------------
# # json
# #---------------------------------------------------------------------------
# def json(self):
# return {
# 'has_error': self.has_error,
# 'content': self.content,
# 'code': self.code
# }
# #---------------------------------------------------------------------------
# # dumps
# #---------------------------------------------------------------------------
# def dumps(self, indent=None):
# return json.dumps(self.json(), indent=indent)
. Output only the next line. | @internal_error_handler('R00TK0') |
Based on the snippet: <|code_start|> return hashlib.sha256(plain_pwd.encode()).hexdigest()
#===============================================================================
# FLASK ROUTES
#===============================================================================
#-------------------------------------------------------------------------------
# beforeRequest
# override of Flask.beforeRequest method to ensure client is using HTTPS !
#-------------------------------------------------------------------------------
@app.before_request
def beforeRequest():
if not app.debug and 'https' not in request.url:
return redirect(request.url.replace('http', 'https'))
#-------------------------------------------------------------------------------
# root
# This is the main application's route. It displays the application main page.
#-------------------------------------------------------------------------------
@app.route('/', methods=['GET'])
@internal_error_handler('R00TK0')
def root():
locations = db.retrieve_locations_with_users()
user_locations = None
if _check_connected(session):
user_locations = db.retrieve_user_locations(session['user']['id'])
return render_template('map.html', locations=locations, user_locations=user_locations, active="map") # users=users)
#-------------------------------------------------------------------------------
# profile
# This is profile view of the current user.
#-------------------------------------------------------------------------------
@app.route('/profile', methods=['GET'])
@internal_error_handler('PR0F1LK0')
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import uuid
import locale
import hashlib
import binascii
import datetime
from flask import Flask
from flask import request
from flask import session
from flask import redirect
from flask import abort
from flask import render_template
from flask import flash
from flask import escape
from flask_responses import json_response
from flask_responses import xml_response
from flask_responses import auto_response
from flask_cors import CORS
from core.modules import db
from core.modules import validator
from core.modules import ini
from core.modules import logger
from core.modules import emails
from core.modules.wrappers import internal_error_handler
from core.modules.wrappers import require_connected
from core.modules.wrappers import require_disconnected
from core.classes.response import Response
from core.classes.slack_log_handler import SlackLogHandler
and context (classes, functions, sometimes code) from other files:
# Path: core/modules/validator.py
# _VALIDATORS_ = {
# 'email': re.compile('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'),
# 'alphanum': re.compile('^\w+$'),
# 'int': re.compile('^\d+$'),
# 'double': re.compile('^\d+(\.\d+)?$'),
# 'phone': re.compile('^(\+\d{2}(\s)?\d|\d{2})(\s)?(\d{2}(\s)?){4}$'),
# 'year': re.compile('^\d{4}$'),
# 'timestamp': re.compile('^\d{4}(-\d{2}){2}$')
# }
# def validate(field, vtype=None):
# def is_empty(field):
# def check_captcha(request):
# def normalize_filter(search_filter):
# def test():
#
# Path: core/modules/ini.py
# _CONFIG_ = None
# _CONFIG_ = configparser.ConfigParser()
# def init(filename):
# def getenv(env_var, default=None):
# def config(section, option, env_var=None, default=None, boolean=False):
# def test():
#
# Path: core/modules/wrappers.py
# def internal_error_handler(err_code):
# def wrapper(f):
# @wraps(f)
# def wrapped_f(*args, **kwargs):
# try:
# return f(*args, **kwargs)
# except Exception as e:
# timestamp = time.strftime('%d%m%H%M%S')
# desc = '`mapif.{0}()` at `{1}` error: details below.'.format(
# f.__name__, timestamp
# )
# modlgr.exception(desc)
# code = '{0}.{1}'.format(err_code, timestamp)
# resp = Response(has_error=True, code=code, content='')
# return json_response(resp.json(), status_code=500)
# return wrapped_f
# return wrapper
#
# Path: core/modules/wrappers.py
# def require_connected():
# def wrapper(f):
# @wraps(f)
# def wrapped_f(*args, **kwargs):
# if not session.get('user', None):
# resp = Response(True, "Opération interdite vous n'êtes pas connecté !")
# return json_response(resp.json(), status_code=403)
# else:
# return f(*args, **kwargs)
# return wrapped_f
# return wrapper
#
# Path: core/modules/wrappers.py
# def require_disconnected():
# def wrapper(f):
# @wraps(f)
# def wrapped_f(*args, **kwargs):
# if session.get('user', None):
# resp = Response(True, "Opération interdite vous n'êtes pas déconnecté !")
# return json_response(resp.json(), status_code=403)
# else:
# return f(*args, **kwargs)
# return wrapped_f
# return wrapper
#
# Path: core/classes/response.py
# class Response(object):
# def __init__(self, has_error = True, content = {}, code=None):
# super(Response, self).__init__()
# self.has_error = has_error
# self.content = content
# self.code = code
# #---------------------------------------------------------------------------
# # json
# #---------------------------------------------------------------------------
# def json(self):
# return {
# 'has_error': self.has_error,
# 'content': self.content,
# 'code': self.code
# }
# #---------------------------------------------------------------------------
# # dumps
# #---------------------------------------------------------------------------
# def dumps(self, indent=None):
# return json.dumps(self.json(), indent=indent)
. Output only the next line. | @require_connected() |
Given the code snippet: <|code_start|> if not app.debug and 'https' not in request.url:
return redirect(request.url.replace('http', 'https'))
#-------------------------------------------------------------------------------
# root
# This is the main application's route. It displays the application main page.
#-------------------------------------------------------------------------------
@app.route('/', methods=['GET'])
@internal_error_handler('R00TK0')
def root():
locations = db.retrieve_locations_with_users()
user_locations = None
if _check_connected(session):
user_locations = db.retrieve_user_locations(session['user']['id'])
return render_template('map.html', locations=locations, user_locations=user_locations, active="map") # users=users)
#-------------------------------------------------------------------------------
# profile
# This is profile view of the current user.
#-------------------------------------------------------------------------------
@app.route('/profile', methods=['GET'])
@internal_error_handler('PR0F1LK0')
@require_connected()
def profile():
user_locations = db.retrieve_user_locations(session['user']['id'])
return render_template('profile.html', user_locations=user_locations, active='profile') # users=users)
#-------------------------------------------------------------------------------
# login
# This route is used to authenticate a user in the application
#-------------------------------------------------------------------------------
@app.route('/login', methods=['POST'])
@internal_error_handler('L0G1NK0')
<|code_end|>
, generate the next line using the imports in this file:
import os
import uuid
import locale
import hashlib
import binascii
import datetime
from flask import Flask
from flask import request
from flask import session
from flask import redirect
from flask import abort
from flask import render_template
from flask import flash
from flask import escape
from flask_responses import json_response
from flask_responses import xml_response
from flask_responses import auto_response
from flask_cors import CORS
from core.modules import db
from core.modules import validator
from core.modules import ini
from core.modules import logger
from core.modules import emails
from core.modules.wrappers import internal_error_handler
from core.modules.wrappers import require_connected
from core.modules.wrappers import require_disconnected
from core.classes.response import Response
from core.classes.slack_log_handler import SlackLogHandler
and context (functions, classes, or occasionally code) from other files:
# Path: core/modules/validator.py
# _VALIDATORS_ = {
# 'email': re.compile('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'),
# 'alphanum': re.compile('^\w+$'),
# 'int': re.compile('^\d+$'),
# 'double': re.compile('^\d+(\.\d+)?$'),
# 'phone': re.compile('^(\+\d{2}(\s)?\d|\d{2})(\s)?(\d{2}(\s)?){4}$'),
# 'year': re.compile('^\d{4}$'),
# 'timestamp': re.compile('^\d{4}(-\d{2}){2}$')
# }
# def validate(field, vtype=None):
# def is_empty(field):
# def check_captcha(request):
# def normalize_filter(search_filter):
# def test():
#
# Path: core/modules/ini.py
# _CONFIG_ = None
# _CONFIG_ = configparser.ConfigParser()
# def init(filename):
# def getenv(env_var, default=None):
# def config(section, option, env_var=None, default=None, boolean=False):
# def test():
#
# Path: core/modules/wrappers.py
# def internal_error_handler(err_code):
# def wrapper(f):
# @wraps(f)
# def wrapped_f(*args, **kwargs):
# try:
# return f(*args, **kwargs)
# except Exception as e:
# timestamp = time.strftime('%d%m%H%M%S')
# desc = '`mapif.{0}()` at `{1}` error: details below.'.format(
# f.__name__, timestamp
# )
# modlgr.exception(desc)
# code = '{0}.{1}'.format(err_code, timestamp)
# resp = Response(has_error=True, code=code, content='')
# return json_response(resp.json(), status_code=500)
# return wrapped_f
# return wrapper
#
# Path: core/modules/wrappers.py
# def require_connected():
# def wrapper(f):
# @wraps(f)
# def wrapped_f(*args, **kwargs):
# if not session.get('user', None):
# resp = Response(True, "Opération interdite vous n'êtes pas connecté !")
# return json_response(resp.json(), status_code=403)
# else:
# return f(*args, **kwargs)
# return wrapped_f
# return wrapper
#
# Path: core/modules/wrappers.py
# def require_disconnected():
# def wrapper(f):
# @wraps(f)
# def wrapped_f(*args, **kwargs):
# if session.get('user', None):
# resp = Response(True, "Opération interdite vous n'êtes pas déconnecté !")
# return json_response(resp.json(), status_code=403)
# else:
# return f(*args, **kwargs)
# return wrapped_f
# return wrapper
#
# Path: core/classes/response.py
# class Response(object):
# def __init__(self, has_error = True, content = {}, code=None):
# super(Response, self).__init__()
# self.has_error = has_error
# self.content = content
# self.code = code
# #---------------------------------------------------------------------------
# # json
# #---------------------------------------------------------------------------
# def json(self):
# return {
# 'has_error': self.has_error,
# 'content': self.content,
# 'code': self.code
# }
# #---------------------------------------------------------------------------
# # dumps
# #---------------------------------------------------------------------------
# def dumps(self, indent=None):
# return json.dumps(self.json(), indent=indent)
. Output only the next line. | @require_disconnected() |
Based on the snippet: <|code_start|> if _check_connected(session):
user_locations = db.retrieve_user_locations(session['user']['id'])
return render_template('map.html', locations=locations, user_locations=user_locations, active="map") # users=users)
#-------------------------------------------------------------------------------
# profile
# This is profile view of the current user.
#-------------------------------------------------------------------------------
@app.route('/profile', methods=['GET'])
@internal_error_handler('PR0F1LK0')
@require_connected()
def profile():
user_locations = db.retrieve_user_locations(session['user']['id'])
return render_template('profile.html', user_locations=user_locations, active='profile') # users=users)
#-------------------------------------------------------------------------------
# login
# This route is used to authenticate a user in the application
#-------------------------------------------------------------------------------
@app.route('/login', methods=['POST'])
@internal_error_handler('L0G1NK0')
@require_disconnected()
def login():
content = "L'utilisateur et/ou le mot de passe est érroné."
email = request.form['email']
pwd_clear = request.form['password']
pwd_hash = _hash_pwd(pwd_clear)
_load_user(session, email, pwd_hash)
err = True
if _check_connected(session):
err = False
content = "Vous êtes maintenant connecté !"
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import uuid
import locale
import hashlib
import binascii
import datetime
from flask import Flask
from flask import request
from flask import session
from flask import redirect
from flask import abort
from flask import render_template
from flask import flash
from flask import escape
from flask_responses import json_response
from flask_responses import xml_response
from flask_responses import auto_response
from flask_cors import CORS
from core.modules import db
from core.modules import validator
from core.modules import ini
from core.modules import logger
from core.modules import emails
from core.modules.wrappers import internal_error_handler
from core.modules.wrappers import require_connected
from core.modules.wrappers import require_disconnected
from core.classes.response import Response
from core.classes.slack_log_handler import SlackLogHandler
and context (classes, functions, sometimes code) from other files:
# Path: core/modules/validator.py
# _VALIDATORS_ = {
# 'email': re.compile('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'),
# 'alphanum': re.compile('^\w+$'),
# 'int': re.compile('^\d+$'),
# 'double': re.compile('^\d+(\.\d+)?$'),
# 'phone': re.compile('^(\+\d{2}(\s)?\d|\d{2})(\s)?(\d{2}(\s)?){4}$'),
# 'year': re.compile('^\d{4}$'),
# 'timestamp': re.compile('^\d{4}(-\d{2}){2}$')
# }
# def validate(field, vtype=None):
# def is_empty(field):
# def check_captcha(request):
# def normalize_filter(search_filter):
# def test():
#
# Path: core/modules/ini.py
# _CONFIG_ = None
# _CONFIG_ = configparser.ConfigParser()
# def init(filename):
# def getenv(env_var, default=None):
# def config(section, option, env_var=None, default=None, boolean=False):
# def test():
#
# Path: core/modules/wrappers.py
# def internal_error_handler(err_code):
# def wrapper(f):
# @wraps(f)
# def wrapped_f(*args, **kwargs):
# try:
# return f(*args, **kwargs)
# except Exception as e:
# timestamp = time.strftime('%d%m%H%M%S')
# desc = '`mapif.{0}()` at `{1}` error: details below.'.format(
# f.__name__, timestamp
# )
# modlgr.exception(desc)
# code = '{0}.{1}'.format(err_code, timestamp)
# resp = Response(has_error=True, code=code, content='')
# return json_response(resp.json(), status_code=500)
# return wrapped_f
# return wrapper
#
# Path: core/modules/wrappers.py
# def require_connected():
# def wrapper(f):
# @wraps(f)
# def wrapped_f(*args, **kwargs):
# if not session.get('user', None):
# resp = Response(True, "Opération interdite vous n'êtes pas connecté !")
# return json_response(resp.json(), status_code=403)
# else:
# return f(*args, **kwargs)
# return wrapped_f
# return wrapper
#
# Path: core/modules/wrappers.py
# def require_disconnected():
# def wrapper(f):
# @wraps(f)
# def wrapped_f(*args, **kwargs):
# if session.get('user', None):
# resp = Response(True, "Opération interdite vous n'êtes pas déconnecté !")
# return json_response(resp.json(), status_code=403)
# else:
# return f(*args, **kwargs)
# return wrapped_f
# return wrapper
#
# Path: core/classes/response.py
# class Response(object):
# def __init__(self, has_error = True, content = {}, code=None):
# super(Response, self).__init__()
# self.has_error = has_error
# self.content = content
# self.code = code
# #---------------------------------------------------------------------------
# # json
# #---------------------------------------------------------------------------
# def json(self):
# return {
# 'has_error': self.has_error,
# 'content': self.content,
# 'code': self.code
# }
# #---------------------------------------------------------------------------
# # dumps
# #---------------------------------------------------------------------------
# def dumps(self, indent=None):
# return json.dumps(self.json(), indent=indent)
. Output only the next line. | return json_response(Response(err, content).json(), status_code=200) |
Continue the code snippet: <|code_start|>#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# file: maintenance.py
# date: 2017-09-19
# author: paul.dautry
# purpose:
# Perform maintenance actions on DB
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#==============================================================================
# IMPORTS
#==============================================================================
#==============================================================================
# FUNCTIONS
#==============================================================================
##
## @brief { function_description }
##
## @return { description_of_the_return_value }
##
def __confirm():
print("Do you really want to run this script ? [yes/n]: ", end='')
resp=input("");
if resp != 'yes':
exit(1)
##
## @brief { function_description }
##
## @return { description_of_the_return_value }
##
def __configure(configuration_file):
# load ini file
<|code_end|>
. Use current file imports:
import os
from argparse import ArgumentParser
from core.modules import db
from core.modules import ini
and context (classes, functions, or code) from other files:
# Path: core/modules/ini.py
# _CONFIG_ = None
# _CONFIG_ = configparser.ConfigParser()
# def init(filename):
# def getenv(env_var, default=None):
# def config(section, option, env_var=None, default=None, boolean=False):
# def test():
. Output only the next line. | if not ini.init(configuration_file): |
Next line prediction: <|code_start|>#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#===============================================================================
# IMPORTS
#===============================================================================
#===============================================================================
# GLOBALS
#===============================================================================
modlgr = logger.get('mapif.wrappers')
#===============================================================================
# DECORATORS
#===============================================================================
#-------------------------------------------------------------------------------
# internal_error_handler
#-------------------------------------------------------------------------------
def internal_error_handler(err_code):
def wrapper(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
try:
return f(*args, **kwargs)
except Exception as e:
timestamp = time.strftime('%d%m%H%M%S')
desc = '`mapif.{0}()` at `{1}` error: details below.'.format(
f.__name__, timestamp
)
modlgr.exception(desc)
code = '{0}.{1}'.format(err_code, timestamp)
<|code_end|>
. Use current file imports:
(import time
from flask_responses import json_response
from flask import session
from functools import wraps
from core.classes.response import Response
from core.modules import logger)
and context including class names, function names, or small code snippets from other files:
# Path: core/classes/response.py
# class Response(object):
# def __init__(self, has_error = True, content = {}, code=None):
# super(Response, self).__init__()
# self.has_error = has_error
# self.content = content
# self.code = code
# #---------------------------------------------------------------------------
# # json
# #---------------------------------------------------------------------------
# def json(self):
# return {
# 'has_error': self.has_error,
# 'content': self.content,
# 'code': self.code
# }
# #---------------------------------------------------------------------------
# # dumps
# #---------------------------------------------------------------------------
# def dumps(self, indent=None):
# return json.dumps(self.json(), indent=indent)
. Output only the next line. | resp = Response(has_error=True, code=code, content='') |
Given the code snippet: <|code_start|>
@task
def restart():
"""
Restarts application on remote server
"""
# read README.md
run('sudo monit restart -g nodejs_app_prod')
@deploy_task(on_success=restart)
def deploy():
"""
Runs deploy process on remote server
"""
git_clone()
link_shared_paths()
run('npm install')
run('npm run build')
@setup_task
def setup():
"""
Runs setup process on remote server
"""
<|code_end|>
, generate the next line using the imports in this file:
from py_mina import *
from py_mina.subtasks import git_clone, create_shared_paths, link_shared_paths, rollback_release
and context (functions, classes, or occasionally code) from other files:
# Path: py_mina/subtasks/setup.py
# def create_shared_paths():
# """
# Creates shared (+protected) files/dirs and sets unix owner/mode
# """
#
# global shared_path
# shared_path = fetch('shared_path')
#
# def create_dirs(directories, protected=False):
# global shared_path
#
# for sdir in directories:
# create_entity(
# '/'.join([shared_path, sdir]),
# entity_type='directory',
# protected=protected
# )
#
#
# def create_files(files, protected=False):
# global shared_path
#
# for sfile in files:
# directory, filename_ = os.path.split(sfile)
#
# if directory:
# create_entity(
# '/'.join([shared_path, directory]),
# entity_type='directory',
# protected=protected
# )
#
# filepath = '/'.join([shared_path, sfile])
# create_entity(filepath, entity_type='file', protected=protected)
#
# recommendation_tuple = (env.host_string, filepath)
# echo_status('\n=====> Don\'t forget to update shared file:\n[%s] %s\n' % recommendation_tuple, error=True)
#
#
# echo_subtask('Creating shared paths')
#
# # Shared
# create_dirs(fetch('shared_dirs', default_value=[]), protected=False)
# create_files(fetch('shared_files', default_value=[]), protected=False)
#
# # Protected
# create_dirs(fetch('protected_shared_dirs', default_value=[]), protected=True)
# create_files(fetch('protected_shared_files', default_value=[]), protected=True)
#
# Path: py_mina/subtasks/deploy.py
# def link_shared_paths():
# """
# Links shared paths to build folder
# """
#
# global build_to
# build_to = fetch('build_to')
#
# global shared
# shared = fetch('shared_path')
#
# def link_dirs(dirs):
# global shared
# global build_to
#
# for sdir in dirs:
# relative_path = '/'.join(['.', sdir])
# directory, filename_ = os.path.split(relative_path)
# shared_path = '/'.join([shared, sdir])
#
# with cd(build_to):
# create_entity(directory, entity_type='directory', protected=False) # create parent directory
# run('rm -rf %s' % relative_path) # remove directory if it conficts with shared
# run('ln -s %s %s' % (shared_path, relative_path)) # link shared to current folder
#
#
# def link_files(files):
# global shared
# global build_to
#
# for sfile in files:
# relative_path = '/'.join(['.', sfile])
# directory, filename_ = os.path.split(relative_path)
# shared_path = '/'.join([shared, sfile])
#
# with cd(build_to):
# create_entity(directory, entity_type='directory', protected=False) # create parent directory
# run('ln -sf %s %s' % (shared_path, relative_path)) # link shared to current folder
#
#
# shared_dirs = fetch('shared_dirs', default_value=[])
# shared_files = fetch('shared_files', default_value=[])
# any_shared_dir = len(shared_dirs) > 0
# any_shared_file = len(shared_files) > 0
#
# protected_shared_dirs = fetch('protected_shared_dirs', default_value=[])
# protected_shared_files = fetch('protected_shared_files', default_value=[])
# any_protected_shared_dir = len(protected_shared_dirs) > 0
# any_protected_shared_file = len(protected_shared_files) > 0
#
# if any_shared_dir or any_shared_file or any_protected_shared_dir or any_protected_shared_file:
# echo_subtask("Linking shared paths")
#
# if any_shared_dir: link_dirs(shared_dirs)
# if any_shared_file: link_files(shared_files)
#
# if any_protected_shared_dir: link_dirs(protected_shared_dirs)
# if any_protected_shared_file: link_files(protected_shared_files)
#
# def rollback_release():
# """
# Rollbacks latest release
# """
#
# ensure('current_path')
#
# releases_path = fetch('releases_path')
#
# with(settings(show('debug'))):
# with cd(releases_path):
# echo_subtask('Finding previous release for rollback')
# rollback_release_number = run('ls -1A | sort -n | tail -n 2 | head -n 1')
#
# if int(rollback_release_number) > 0:
# echo_subtask('Linking previous release to current')
# run('ln -nfs %s/%s %s' % (releases_path, rollback_release_number, fetch('current_path')))
#
# echo_subtask('Finding latest release')
# current_release = run('ls -1A | sort -n | tail -n 1')
#
# if int(current_release) > 0:
# echo_subtask('Removing latest release')
# run('rm -rf %s/%s' % (releases_path, current_release))
# else:
# abort('Can\'t find latest release for remove.')
# else:
# abort('Can\'t find previous release for rollback.')
#
# Path: py_mina/subtasks/git.py
# def git_clone():
# """
# Clones repository to tmp build dir
# """
#
# maybe_clone_git_repository()
# fetch_new_commits()
# use_git_branch()
. Output only the next line. | create_shared_paths() |
Given snippet: <|code_start|>
# Settings - shared
set('verbose', True)
set('shared_dirs', ['node_modules', 'tmp'])
set('shared_files', [])
# Tasks
@task
def restart():
"""
Restarts application on remote server
"""
# read README.md
run('sudo monit restart -g nodejs_app_prod')
@deploy_task(on_success=restart)
def deploy():
"""
Runs deploy process on remote server
"""
git_clone()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from py_mina import *
from py_mina.subtasks import git_clone, create_shared_paths, link_shared_paths, rollback_release
and context:
# Path: py_mina/subtasks/setup.py
# def create_shared_paths():
# """
# Creates shared (+protected) files/dirs and sets unix owner/mode
# """
#
# global shared_path
# shared_path = fetch('shared_path')
#
# def create_dirs(directories, protected=False):
# global shared_path
#
# for sdir in directories:
# create_entity(
# '/'.join([shared_path, sdir]),
# entity_type='directory',
# protected=protected
# )
#
#
# def create_files(files, protected=False):
# global shared_path
#
# for sfile in files:
# directory, filename_ = os.path.split(sfile)
#
# if directory:
# create_entity(
# '/'.join([shared_path, directory]),
# entity_type='directory',
# protected=protected
# )
#
# filepath = '/'.join([shared_path, sfile])
# create_entity(filepath, entity_type='file', protected=protected)
#
# recommendation_tuple = (env.host_string, filepath)
# echo_status('\n=====> Don\'t forget to update shared file:\n[%s] %s\n' % recommendation_tuple, error=True)
#
#
# echo_subtask('Creating shared paths')
#
# # Shared
# create_dirs(fetch('shared_dirs', default_value=[]), protected=False)
# create_files(fetch('shared_files', default_value=[]), protected=False)
#
# # Protected
# create_dirs(fetch('protected_shared_dirs', default_value=[]), protected=True)
# create_files(fetch('protected_shared_files', default_value=[]), protected=True)
#
# Path: py_mina/subtasks/deploy.py
# def link_shared_paths():
# """
# Links shared paths to build folder
# """
#
# global build_to
# build_to = fetch('build_to')
#
# global shared
# shared = fetch('shared_path')
#
# def link_dirs(dirs):
# global shared
# global build_to
#
# for sdir in dirs:
# relative_path = '/'.join(['.', sdir])
# directory, filename_ = os.path.split(relative_path)
# shared_path = '/'.join([shared, sdir])
#
# with cd(build_to):
# create_entity(directory, entity_type='directory', protected=False) # create parent directory
# run('rm -rf %s' % relative_path) # remove directory if it conficts with shared
# run('ln -s %s %s' % (shared_path, relative_path)) # link shared to current folder
#
#
# def link_files(files):
# global shared
# global build_to
#
# for sfile in files:
# relative_path = '/'.join(['.', sfile])
# directory, filename_ = os.path.split(relative_path)
# shared_path = '/'.join([shared, sfile])
#
# with cd(build_to):
# create_entity(directory, entity_type='directory', protected=False) # create parent directory
# run('ln -sf %s %s' % (shared_path, relative_path)) # link shared to current folder
#
#
# shared_dirs = fetch('shared_dirs', default_value=[])
# shared_files = fetch('shared_files', default_value=[])
# any_shared_dir = len(shared_dirs) > 0
# any_shared_file = len(shared_files) > 0
#
# protected_shared_dirs = fetch('protected_shared_dirs', default_value=[])
# protected_shared_files = fetch('protected_shared_files', default_value=[])
# any_protected_shared_dir = len(protected_shared_dirs) > 0
# any_protected_shared_file = len(protected_shared_files) > 0
#
# if any_shared_dir or any_shared_file or any_protected_shared_dir or any_protected_shared_file:
# echo_subtask("Linking shared paths")
#
# if any_shared_dir: link_dirs(shared_dirs)
# if any_shared_file: link_files(shared_files)
#
# if any_protected_shared_dir: link_dirs(protected_shared_dirs)
# if any_protected_shared_file: link_files(protected_shared_files)
#
# def rollback_release():
# """
# Rollbacks latest release
# """
#
# ensure('current_path')
#
# releases_path = fetch('releases_path')
#
# with(settings(show('debug'))):
# with cd(releases_path):
# echo_subtask('Finding previous release for rollback')
# rollback_release_number = run('ls -1A | sort -n | tail -n 2 | head -n 1')
#
# if int(rollback_release_number) > 0:
# echo_subtask('Linking previous release to current')
# run('ln -nfs %s/%s %s' % (releases_path, rollback_release_number, fetch('current_path')))
#
# echo_subtask('Finding latest release')
# current_release = run('ls -1A | sort -n | tail -n 1')
#
# if int(current_release) > 0:
# echo_subtask('Removing latest release')
# run('rm -rf %s/%s' % (releases_path, current_release))
# else:
# abort('Can\'t find latest release for remove.')
# else:
# abort('Can\'t find previous release for rollback.')
#
# Path: py_mina/subtasks/git.py
# def git_clone():
# """
# Clones repository to tmp build dir
# """
#
# maybe_clone_git_repository()
# fetch_new_commits()
# use_git_branch()
which might include code, classes, or functions. Output only the next line. | link_shared_paths() |
Continue the code snippet: <|code_start|>
@deploy_task(on_success=restart)
def deploy():
"""
Runs deploy process on remote server
"""
git_clone()
link_shared_paths()
run('npm install')
run('npm run build')
@setup_task
def setup():
"""
Runs setup process on remote server
"""
create_shared_paths()
@task
def rollback():
"""
Rollbacks to previous release
"""
<|code_end|>
. Use current file imports:
from py_mina import *
from py_mina.subtasks import git_clone, create_shared_paths, link_shared_paths, rollback_release
and context (classes, functions, or code) from other files:
# Path: py_mina/subtasks/setup.py
# def create_shared_paths():
# """
# Creates shared (+protected) files/dirs and sets unix owner/mode
# """
#
# global shared_path
# shared_path = fetch('shared_path')
#
# def create_dirs(directories, protected=False):
# global shared_path
#
# for sdir in directories:
# create_entity(
# '/'.join([shared_path, sdir]),
# entity_type='directory',
# protected=protected
# )
#
#
# def create_files(files, protected=False):
# global shared_path
#
# for sfile in files:
# directory, filename_ = os.path.split(sfile)
#
# if directory:
# create_entity(
# '/'.join([shared_path, directory]),
# entity_type='directory',
# protected=protected
# )
#
# filepath = '/'.join([shared_path, sfile])
# create_entity(filepath, entity_type='file', protected=protected)
#
# recommendation_tuple = (env.host_string, filepath)
# echo_status('\n=====> Don\'t forget to update shared file:\n[%s] %s\n' % recommendation_tuple, error=True)
#
#
# echo_subtask('Creating shared paths')
#
# # Shared
# create_dirs(fetch('shared_dirs', default_value=[]), protected=False)
# create_files(fetch('shared_files', default_value=[]), protected=False)
#
# # Protected
# create_dirs(fetch('protected_shared_dirs', default_value=[]), protected=True)
# create_files(fetch('protected_shared_files', default_value=[]), protected=True)
#
# Path: py_mina/subtasks/deploy.py
# def link_shared_paths():
# """
# Links shared paths to build folder
# """
#
# global build_to
# build_to = fetch('build_to')
#
# global shared
# shared = fetch('shared_path')
#
# def link_dirs(dirs):
# global shared
# global build_to
#
# for sdir in dirs:
# relative_path = '/'.join(['.', sdir])
# directory, filename_ = os.path.split(relative_path)
# shared_path = '/'.join([shared, sdir])
#
# with cd(build_to):
# create_entity(directory, entity_type='directory', protected=False) # create parent directory
# run('rm -rf %s' % relative_path) # remove directory if it conficts with shared
# run('ln -s %s %s' % (shared_path, relative_path)) # link shared to current folder
#
#
# def link_files(files):
# global shared
# global build_to
#
# for sfile in files:
# relative_path = '/'.join(['.', sfile])
# directory, filename_ = os.path.split(relative_path)
# shared_path = '/'.join([shared, sfile])
#
# with cd(build_to):
# create_entity(directory, entity_type='directory', protected=False) # create parent directory
# run('ln -sf %s %s' % (shared_path, relative_path)) # link shared to current folder
#
#
# shared_dirs = fetch('shared_dirs', default_value=[])
# shared_files = fetch('shared_files', default_value=[])
# any_shared_dir = len(shared_dirs) > 0
# any_shared_file = len(shared_files) > 0
#
# protected_shared_dirs = fetch('protected_shared_dirs', default_value=[])
# protected_shared_files = fetch('protected_shared_files', default_value=[])
# any_protected_shared_dir = len(protected_shared_dirs) > 0
# any_protected_shared_file = len(protected_shared_files) > 0
#
# if any_shared_dir or any_shared_file or any_protected_shared_dir or any_protected_shared_file:
# echo_subtask("Linking shared paths")
#
# if any_shared_dir: link_dirs(shared_dirs)
# if any_shared_file: link_files(shared_files)
#
# if any_protected_shared_dir: link_dirs(protected_shared_dirs)
# if any_protected_shared_file: link_files(protected_shared_files)
#
# def rollback_release():
# """
# Rollbacks latest release
# """
#
# ensure('current_path')
#
# releases_path = fetch('releases_path')
#
# with(settings(show('debug'))):
# with cd(releases_path):
# echo_subtask('Finding previous release for rollback')
# rollback_release_number = run('ls -1A | sort -n | tail -n 2 | head -n 1')
#
# if int(rollback_release_number) > 0:
# echo_subtask('Linking previous release to current')
# run('ln -nfs %s/%s %s' % (releases_path, rollback_release_number, fetch('current_path')))
#
# echo_subtask('Finding latest release')
# current_release = run('ls -1A | sort -n | tail -n 1')
#
# if int(current_release) > 0:
# echo_subtask('Removing latest release')
# run('rm -rf %s/%s' % (releases_path, current_release))
# else:
# abort('Can\'t find latest release for remove.')
# else:
# abort('Can\'t find previous release for rollback.')
#
# Path: py_mina/subtasks/git.py
# def git_clone():
# """
# Clones repository to tmp build dir
# """
#
# maybe_clone_git_repository()
# fetch_new_commits()
# use_git_branch()
. Output only the next line. | rollback_release() |
Given the code snippet: <|code_start|>
# Settings - shared
set('verbose', True)
set('shared_dirs', ['node_modules', 'tmp'])
set('shared_files', [])
# Tasks
@task
def restart():
"""
Restarts application on remote server
"""
# read README.md
run('sudo monit restart -g nodejs_app_prod')
@deploy_task(on_success=restart)
def deploy():
"""
Runs deploy process on remote server
"""
<|code_end|>
, generate the next line using the imports in this file:
from py_mina import *
from py_mina.subtasks import git_clone, create_shared_paths, link_shared_paths, rollback_release
and context (functions, classes, or occasionally code) from other files:
# Path: py_mina/subtasks/setup.py
# def create_shared_paths():
# """
# Creates shared (+protected) files/dirs and sets unix owner/mode
# """
#
# global shared_path
# shared_path = fetch('shared_path')
#
# def create_dirs(directories, protected=False):
# global shared_path
#
# for sdir in directories:
# create_entity(
# '/'.join([shared_path, sdir]),
# entity_type='directory',
# protected=protected
# )
#
#
# def create_files(files, protected=False):
# global shared_path
#
# for sfile in files:
# directory, filename_ = os.path.split(sfile)
#
# if directory:
# create_entity(
# '/'.join([shared_path, directory]),
# entity_type='directory',
# protected=protected
# )
#
# filepath = '/'.join([shared_path, sfile])
# create_entity(filepath, entity_type='file', protected=protected)
#
# recommendation_tuple = (env.host_string, filepath)
# echo_status('\n=====> Don\'t forget to update shared file:\n[%s] %s\n' % recommendation_tuple, error=True)
#
#
# echo_subtask('Creating shared paths')
#
# # Shared
# create_dirs(fetch('shared_dirs', default_value=[]), protected=False)
# create_files(fetch('shared_files', default_value=[]), protected=False)
#
# # Protected
# create_dirs(fetch('protected_shared_dirs', default_value=[]), protected=True)
# create_files(fetch('protected_shared_files', default_value=[]), protected=True)
#
# Path: py_mina/subtasks/deploy.py
# def link_shared_paths():
# """
# Links shared paths to build folder
# """
#
# global build_to
# build_to = fetch('build_to')
#
# global shared
# shared = fetch('shared_path')
#
# def link_dirs(dirs):
# global shared
# global build_to
#
# for sdir in dirs:
# relative_path = '/'.join(['.', sdir])
# directory, filename_ = os.path.split(relative_path)
# shared_path = '/'.join([shared, sdir])
#
# with cd(build_to):
# create_entity(directory, entity_type='directory', protected=False) # create parent directory
# run('rm -rf %s' % relative_path) # remove directory if it conficts with shared
# run('ln -s %s %s' % (shared_path, relative_path)) # link shared to current folder
#
#
# def link_files(files):
# global shared
# global build_to
#
# for sfile in files:
# relative_path = '/'.join(['.', sfile])
# directory, filename_ = os.path.split(relative_path)
# shared_path = '/'.join([shared, sfile])
#
# with cd(build_to):
# create_entity(directory, entity_type='directory', protected=False) # create parent directory
# run('ln -sf %s %s' % (shared_path, relative_path)) # link shared to current folder
#
#
# shared_dirs = fetch('shared_dirs', default_value=[])
# shared_files = fetch('shared_files', default_value=[])
# any_shared_dir = len(shared_dirs) > 0
# any_shared_file = len(shared_files) > 0
#
# protected_shared_dirs = fetch('protected_shared_dirs', default_value=[])
# protected_shared_files = fetch('protected_shared_files', default_value=[])
# any_protected_shared_dir = len(protected_shared_dirs) > 0
# any_protected_shared_file = len(protected_shared_files) > 0
#
# if any_shared_dir or any_shared_file or any_protected_shared_dir or any_protected_shared_file:
# echo_subtask("Linking shared paths")
#
# if any_shared_dir: link_dirs(shared_dirs)
# if any_shared_file: link_files(shared_files)
#
# if any_protected_shared_dir: link_dirs(protected_shared_dirs)
# if any_protected_shared_file: link_files(protected_shared_files)
#
# def rollback_release():
# """
# Rollbacks latest release
# """
#
# ensure('current_path')
#
# releases_path = fetch('releases_path')
#
# with(settings(show('debug'))):
# with cd(releases_path):
# echo_subtask('Finding previous release for rollback')
# rollback_release_number = run('ls -1A | sort -n | tail -n 2 | head -n 1')
#
# if int(rollback_release_number) > 0:
# echo_subtask('Linking previous release to current')
# run('ln -nfs %s/%s %s' % (releases_path, rollback_release_number, fetch('current_path')))
#
# echo_subtask('Finding latest release')
# current_release = run('ls -1A | sort -n | tail -n 1')
#
# if int(current_release) > 0:
# echo_subtask('Removing latest release')
# run('rm -rf %s/%s' % (releases_path, current_release))
# else:
# abort('Can\'t find latest release for remove.')
# else:
# abort('Can\'t find previous release for rollback.')
#
# Path: py_mina/subtasks/git.py
# def git_clone():
# """
# Clones repository to tmp build dir
# """
#
# maybe_clone_git_repository()
# fetch_new_commits()
# use_git_branch()
. Output only the next line. | git_clone() |
Predict the next line after this snippet: <|code_start|>"""
Git tasks
"""
from __future__ import with_statement
def git_clone():
"""
Clones repository to tmp build dir
"""
maybe_clone_git_repository()
fetch_new_commits()
use_git_branch()
def maybe_clone_git_repository():
"""
Clones bare git repository on first deploy
"""
ensure('repository')
scm_path = fetch('scm')
with settings(hide('warnings'), warn_only=True):
<|code_end|>
using the current file's imports:
import os
from fabric.api import settings, hide, run, cd, settings
from py_mina.echo import echo_subtask, echo_task
from py_mina.config import fetch, ensure
from py_mina.subtasks.setup import create_entity
and any relevant context from other files:
# Path: py_mina/echo.py
# def echo_subtask(message, error=False):
# color = red if error == True else cyan
#
# print(cyan('\n-----> %s' % message))
#
# def echo_task(message, error=False):
# color = red if error == True else yellow
#
# print(color('\n=====> %s' % message))
#
# Path: py_mina/config.py
# def fetch(key, default_value=None):
# """
# Gets and ensures config setting or returns `default_value` if provided
# """
#
# if key in config.keys():
# return config.get(key)
# else:
# if default_value != None:
# return default_value
# else:
# raise Exception('"%s" is not defined' % key)
#
# def ensure(key):
# """
# Ensures presence of config setting. Prevents from running unnecessary commands,
# before discovering, that config setting is not set
# """
#
# if not key in config.keys():
# raise Exception('"%s" must be defined' % key)
#
# Path: py_mina/subtasks/setup.py
# def create_entity(entity_path, entity_type = 'file', protected=False):
# """
# Creates directory/file and sets proper owner/mode.
# """
#
# chmod_sudo = 'sudo ' if fetch('sudo_on_chmod') else ''
# chown_sudo = 'sudo ' if fetch('sudo_on_chown') else ''
#
# def change_owner(owner_triple):
# """
# Changes unix owner/mode
# """
#
# run(chmod_sudo + 'chmod 0755 ' + entity_path)
# run(chown_sudo + 'chown %s:%s %s' % owner_triple)
#
#
# # 1) Create file/directory
#
# if entity_type == 'file':
# run('touch %s' % entity_path)
# else:
# run('mkdir -p %s' % entity_path)
#
# # 2) Change owner/mode
#
# if protected:
# protected_owner_user = fetch('protected_owner_user')
# protected_owner_group = fetch('protected_owner_group')
#
# change_owner((protected_owner_user, protected_owner_group, entity_path))
# else:
# owner_user = fetch('owner_user', default_value=False)
# owner_group = fetch('owner_group', default_value=False)
#
# if owner_user != False and owner_group != False:
# change_owner((owner_user, owner_group, entity_path))
# else:
# run(chmod_sudo + 'chmod 0755 ' + entity_path)
. Output only the next line. | echo_subtask('Ensuring git repository presence') |
Predict the next line after this snippet: <|code_start|>"""
Git tasks
"""
from __future__ import with_statement
def git_clone():
"""
Clones repository to tmp build dir
"""
maybe_clone_git_repository()
fetch_new_commits()
use_git_branch()
def maybe_clone_git_repository():
"""
Clones bare git repository on first deploy
"""
ensure('repository')
<|code_end|>
using the current file's imports:
import os
from fabric.api import settings, hide, run, cd, settings
from py_mina.echo import echo_subtask, echo_task
from py_mina.config import fetch, ensure
from py_mina.subtasks.setup import create_entity
and any relevant context from other files:
# Path: py_mina/echo.py
# def echo_subtask(message, error=False):
# color = red if error == True else cyan
#
# print(cyan('\n-----> %s' % message))
#
# def echo_task(message, error=False):
# color = red if error == True else yellow
#
# print(color('\n=====> %s' % message))
#
# Path: py_mina/config.py
# def fetch(key, default_value=None):
# """
# Gets and ensures config setting or returns `default_value` if provided
# """
#
# if key in config.keys():
# return config.get(key)
# else:
# if default_value != None:
# return default_value
# else:
# raise Exception('"%s" is not defined' % key)
#
# def ensure(key):
# """
# Ensures presence of config setting. Prevents from running unnecessary commands,
# before discovering, that config setting is not set
# """
#
# if not key in config.keys():
# raise Exception('"%s" must be defined' % key)
#
# Path: py_mina/subtasks/setup.py
# def create_entity(entity_path, entity_type = 'file', protected=False):
# """
# Creates directory/file and sets proper owner/mode.
# """
#
# chmod_sudo = 'sudo ' if fetch('sudo_on_chmod') else ''
# chown_sudo = 'sudo ' if fetch('sudo_on_chown') else ''
#
# def change_owner(owner_triple):
# """
# Changes unix owner/mode
# """
#
# run(chmod_sudo + 'chmod 0755 ' + entity_path)
# run(chown_sudo + 'chown %s:%s %s' % owner_triple)
#
#
# # 1) Create file/directory
#
# if entity_type == 'file':
# run('touch %s' % entity_path)
# else:
# run('mkdir -p %s' % entity_path)
#
# # 2) Change owner/mode
#
# if protected:
# protected_owner_user = fetch('protected_owner_user')
# protected_owner_group = fetch('protected_owner_group')
#
# change_owner((protected_owner_user, protected_owner_group, entity_path))
# else:
# owner_user = fetch('owner_user', default_value=False)
# owner_group = fetch('owner_group', default_value=False)
#
# if owner_user != False and owner_group != False:
# change_owner((owner_user, owner_group, entity_path))
# else:
# run(chmod_sudo + 'chmod 0755 ' + entity_path)
. Output only the next line. | scm_path = fetch('scm') |
Predict the next line after this snippet: <|code_start|>"""
Git tasks
"""
from __future__ import with_statement
def git_clone():
"""
Clones repository to tmp build dir
"""
maybe_clone_git_repository()
fetch_new_commits()
use_git_branch()
def maybe_clone_git_repository():
"""
Clones bare git repository on first deploy
"""
<|code_end|>
using the current file's imports:
import os
from fabric.api import settings, hide, run, cd, settings
from py_mina.echo import echo_subtask, echo_task
from py_mina.config import fetch, ensure
from py_mina.subtasks.setup import create_entity
and any relevant context from other files:
# Path: py_mina/echo.py
# def echo_subtask(message, error=False):
# color = red if error == True else cyan
#
# print(cyan('\n-----> %s' % message))
#
# def echo_task(message, error=False):
# color = red if error == True else yellow
#
# print(color('\n=====> %s' % message))
#
# Path: py_mina/config.py
# def fetch(key, default_value=None):
# """
# Gets and ensures config setting or returns `default_value` if provided
# """
#
# if key in config.keys():
# return config.get(key)
# else:
# if default_value != None:
# return default_value
# else:
# raise Exception('"%s" is not defined' % key)
#
# def ensure(key):
# """
# Ensures presence of config setting. Prevents from running unnecessary commands,
# before discovering, that config setting is not set
# """
#
# if not key in config.keys():
# raise Exception('"%s" must be defined' % key)
#
# Path: py_mina/subtasks/setup.py
# def create_entity(entity_path, entity_type = 'file', protected=False):
# """
# Creates directory/file and sets proper owner/mode.
# """
#
# chmod_sudo = 'sudo ' if fetch('sudo_on_chmod') else ''
# chown_sudo = 'sudo ' if fetch('sudo_on_chown') else ''
#
# def change_owner(owner_triple):
# """
# Changes unix owner/mode
# """
#
# run(chmod_sudo + 'chmod 0755 ' + entity_path)
# run(chown_sudo + 'chown %s:%s %s' % owner_triple)
#
#
# # 1) Create file/directory
#
# if entity_type == 'file':
# run('touch %s' % entity_path)
# else:
# run('mkdir -p %s' % entity_path)
#
# # 2) Change owner/mode
#
# if protected:
# protected_owner_user = fetch('protected_owner_user')
# protected_owner_group = fetch('protected_owner_group')
#
# change_owner((protected_owner_user, protected_owner_group, entity_path))
# else:
# owner_user = fetch('owner_user', default_value=False)
# owner_group = fetch('owner_group', default_value=False)
#
# if owner_user != False and owner_group != False:
# change_owner((owner_user, owner_group, entity_path))
# else:
# run(chmod_sudo + 'chmod 0755 ' + entity_path)
. Output only the next line. | ensure('repository') |
Predict the next line after this snippet: <|code_start|>Git tasks
"""
from __future__ import with_statement
def git_clone():
"""
Clones repository to tmp build dir
"""
maybe_clone_git_repository()
fetch_new_commits()
use_git_branch()
def maybe_clone_git_repository():
"""
Clones bare git repository on first deploy
"""
ensure('repository')
scm_path = fetch('scm')
with settings(hide('warnings'), warn_only=True):
echo_subtask('Ensuring git repository presence')
if run('test -d %s' % scm_path).failed:
<|code_end|>
using the current file's imports:
import os
from fabric.api import settings, hide, run, cd, settings
from py_mina.echo import echo_subtask, echo_task
from py_mina.config import fetch, ensure
from py_mina.subtasks.setup import create_entity
and any relevant context from other files:
# Path: py_mina/echo.py
# def echo_subtask(message, error=False):
# color = red if error == True else cyan
#
# print(cyan('\n-----> %s' % message))
#
# def echo_task(message, error=False):
# color = red if error == True else yellow
#
# print(color('\n=====> %s' % message))
#
# Path: py_mina/config.py
# def fetch(key, default_value=None):
# """
# Gets and ensures config setting or returns `default_value` if provided
# """
#
# if key in config.keys():
# return config.get(key)
# else:
# if default_value != None:
# return default_value
# else:
# raise Exception('"%s" is not defined' % key)
#
# def ensure(key):
# """
# Ensures presence of config setting. Prevents from running unnecessary commands,
# before discovering, that config setting is not set
# """
#
# if not key in config.keys():
# raise Exception('"%s" must be defined' % key)
#
# Path: py_mina/subtasks/setup.py
# def create_entity(entity_path, entity_type = 'file', protected=False):
# """
# Creates directory/file and sets proper owner/mode.
# """
#
# chmod_sudo = 'sudo ' if fetch('sudo_on_chmod') else ''
# chown_sudo = 'sudo ' if fetch('sudo_on_chown') else ''
#
# def change_owner(owner_triple):
# """
# Changes unix owner/mode
# """
#
# run(chmod_sudo + 'chmod 0755 ' + entity_path)
# run(chown_sudo + 'chown %s:%s %s' % owner_triple)
#
#
# # 1) Create file/directory
#
# if entity_type == 'file':
# run('touch %s' % entity_path)
# else:
# run('mkdir -p %s' % entity_path)
#
# # 2) Change owner/mode
#
# if protected:
# protected_owner_user = fetch('protected_owner_user')
# protected_owner_group = fetch('protected_owner_group')
#
# change_owner((protected_owner_user, protected_owner_group, entity_path))
# else:
# owner_user = fetch('owner_user', default_value=False)
# owner_group = fetch('owner_group', default_value=False)
#
# if owner_user != False and owner_group != False:
# change_owner((owner_user, owner_group, entity_path))
# else:
# run(chmod_sudo + 'chmod 0755 ' + entity_path)
. Output only the next line. | create_entity(scm_path, entity_type='directory', protected=False) |
Given the code snippet: <|code_start|>Setup tasks
"""
from __future__ import with_statement
################################################################################
# Check
################################################################################
def check_setup_config():
"""
Checks required config settings for setup task
"""
check_config(['user', 'hosts', 'deploy_to'])
################################################################################
# Create required and shared
################################################################################
def create_required_structure():
"""
Creates required folders (tmp, releases, shared) in `deploy_to` path
"""
<|code_end|>
, generate the next line using the imports in this file:
import timeit
import os
import re
from py_mina.config import fetch, ensure, check_config
from fabric.api import run, sudo, settings, env, cd, hide
from py_mina.echo import *
and context (functions, classes, or occasionally code) from other files:
# Path: py_mina/config.py
# def fetch(key, default_value=None):
# """
# Gets and ensures config setting or returns `default_value` if provided
# """
#
# if key in config.keys():
# return config.get(key)
# else:
# if default_value != None:
# return default_value
# else:
# raise Exception('"%s" is not defined' % key)
#
# def ensure(key):
# """
# Ensures presence of config setting. Prevents from running unnecessary commands,
# before discovering, that config setting is not set
# """
#
# if not key in config.keys():
# raise Exception('"%s" must be defined' % key)
#
# def check_config(required_settings=[]):
# """
# Ensures required settings in cofig
# """
#
# try:
# for setting in required_settings:
# ensure(setting)
# except EnsureConfigError:
# msg = 'Bad config!\nRequired settings: {0}\nCurrent config: {1}'
#
# raise Exception(msg.format(required_settings, config))
. Output only the next line. | deploy_to = fetch('deploy_to') |
Continue the code snippet: <|code_start|>
maybe_repository = fetch('repository', default_value='')
if maybe_repository:
# Parse repo host
repo_host_array = re.compile('(@|://)').split(maybe_repository)
repo_host_part = repo_host_array[-1] if repo_host_array else ''
repo_host_match = re.compile(':|\/').split(repo_host_part)
repo_host = repo_host_match[0] if repo_host_match else ''
# Exit if no host
if repo_host == '':
return
# Parse port
repo_port_match = re.search(r':([0-9]+)', maybe_repository)
repo_port = repo_port_match.group(1) if bool(repo_port_match) else 22
echo_subtask('Adding repository to known hosts')
add_to_known_hosts(repo_host, repo_port)
def add_host_to_known_hosts():
"""
Adds current host to the known hosts
`fabric3` library sets to `env.host_string` current host where task is executed
"""
<|code_end|>
. Use current file imports:
import timeit
import os
import re
from py_mina.config import fetch, ensure, check_config
from fabric.api import run, sudo, settings, env, cd, hide
from py_mina.echo import *
and context (classes, functions, or code) from other files:
# Path: py_mina/config.py
# def fetch(key, default_value=None):
# """
# Gets and ensures config setting or returns `default_value` if provided
# """
#
# if key in config.keys():
# return config.get(key)
# else:
# if default_value != None:
# return default_value
# else:
# raise Exception('"%s" is not defined' % key)
#
# def ensure(key):
# """
# Ensures presence of config setting. Prevents from running unnecessary commands,
# before discovering, that config setting is not set
# """
#
# if not key in config.keys():
# raise Exception('"%s" must be defined' % key)
#
# def check_config(required_settings=[]):
# """
# Ensures required settings in cofig
# """
#
# try:
# for setting in required_settings:
# ensure(setting)
# except EnsureConfigError:
# msg = 'Bad config!\nRequired settings: {0}\nCurrent config: {1}'
#
# raise Exception(msg.format(required_settings, config))
. Output only the next line. | ensure('hosts') |
Given the following code snippet before the placeholder: <|code_start|>"""
Setup tasks
"""
from __future__ import with_statement
################################################################################
# Check
################################################################################
def check_setup_config():
"""
Checks required config settings for setup task
"""
<|code_end|>
, predict the next line using imports from the current file:
import timeit
import os
import re
from py_mina.config import fetch, ensure, check_config
from fabric.api import run, sudo, settings, env, cd, hide
from py_mina.echo import *
and context including class names, function names, and sometimes code from other files:
# Path: py_mina/config.py
# def fetch(key, default_value=None):
# """
# Gets and ensures config setting or returns `default_value` if provided
# """
#
# if key in config.keys():
# return config.get(key)
# else:
# if default_value != None:
# return default_value
# else:
# raise Exception('"%s" is not defined' % key)
#
# def ensure(key):
# """
# Ensures presence of config setting. Prevents from running unnecessary commands,
# before discovering, that config setting is not set
# """
#
# if not key in config.keys():
# raise Exception('"%s" must be defined' % key)
#
# def check_config(required_settings=[]):
# """
# Ensures required settings in cofig
# """
#
# try:
# for setting in required_settings:
# ensure(setting)
# except EnsureConfigError:
# msg = 'Bad config!\nRequired settings: {0}\nCurrent config: {1}'
#
# raise Exception(msg.format(required_settings, config))
. Output only the next line. | check_config(['user', 'hosts', 'deploy_to']) |
Predict the next line after this snippet: <|code_start|>
# Settings - shared
set('verbose', True)
set('shared_dirs', ['storage', 'env', 'tmp'])
set('shared_files', ['my_drf_app/db_conf.py', 'my_drf_app/custom_conf.py'])
# Tasks
@task
def restart():
"""
Restarts application on remote server
"""
# read README.md
run('sudo monit restart -g my_drf_app_prod')
@deploy_task(on_success=restart)
def deploy():
"""
Runs deploy process on remote server
"""
git_clone()
<|code_end|>
using the current file's imports:
from py_mina import *
from py_mina.subtasks import git_clone, create_shared_paths, link_shared_paths, rollback_release
and any relevant context from other files:
# Path: py_mina/subtasks/setup.py
# def create_shared_paths():
# """
# Creates shared (+protected) files/dirs and sets unix owner/mode
# """
#
# global shared_path
# shared_path = fetch('shared_path')
#
# def create_dirs(directories, protected=False):
# global shared_path
#
# for sdir in directories:
# create_entity(
# '/'.join([shared_path, sdir]),
# entity_type='directory',
# protected=protected
# )
#
#
# def create_files(files, protected=False):
# global shared_path
#
# for sfile in files:
# directory, filename_ = os.path.split(sfile)
#
# if directory:
# create_entity(
# '/'.join([shared_path, directory]),
# entity_type='directory',
# protected=protected
# )
#
# filepath = '/'.join([shared_path, sfile])
# create_entity(filepath, entity_type='file', protected=protected)
#
# recommendation_tuple = (env.host_string, filepath)
# echo_status('\n=====> Don\'t forget to update shared file:\n[%s] %s\n' % recommendation_tuple, error=True)
#
#
# echo_subtask('Creating shared paths')
#
# # Shared
# create_dirs(fetch('shared_dirs', default_value=[]), protected=False)
# create_files(fetch('shared_files', default_value=[]), protected=False)
#
# # Protected
# create_dirs(fetch('protected_shared_dirs', default_value=[]), protected=True)
# create_files(fetch('protected_shared_files', default_value=[]), protected=True)
#
# Path: py_mina/subtasks/deploy.py
# def link_shared_paths():
# """
# Links shared paths to build folder
# """
#
# global build_to
# build_to = fetch('build_to')
#
# global shared
# shared = fetch('shared_path')
#
# def link_dirs(dirs):
# global shared
# global build_to
#
# for sdir in dirs:
# relative_path = '/'.join(['.', sdir])
# directory, filename_ = os.path.split(relative_path)
# shared_path = '/'.join([shared, sdir])
#
# with cd(build_to):
# create_entity(directory, entity_type='directory', protected=False) # create parent directory
# run('rm -rf %s' % relative_path) # remove directory if it conficts with shared
# run('ln -s %s %s' % (shared_path, relative_path)) # link shared to current folder
#
#
# def link_files(files):
# global shared
# global build_to
#
# for sfile in files:
# relative_path = '/'.join(['.', sfile])
# directory, filename_ = os.path.split(relative_path)
# shared_path = '/'.join([shared, sfile])
#
# with cd(build_to):
# create_entity(directory, entity_type='directory', protected=False) # create parent directory
# run('ln -sf %s %s' % (shared_path, relative_path)) # link shared to current folder
#
#
# shared_dirs = fetch('shared_dirs', default_value=[])
# shared_files = fetch('shared_files', default_value=[])
# any_shared_dir = len(shared_dirs) > 0
# any_shared_file = len(shared_files) > 0
#
# protected_shared_dirs = fetch('protected_shared_dirs', default_value=[])
# protected_shared_files = fetch('protected_shared_files', default_value=[])
# any_protected_shared_dir = len(protected_shared_dirs) > 0
# any_protected_shared_file = len(protected_shared_files) > 0
#
# if any_shared_dir or any_shared_file or any_protected_shared_dir or any_protected_shared_file:
# echo_subtask("Linking shared paths")
#
# if any_shared_dir: link_dirs(shared_dirs)
# if any_shared_file: link_files(shared_files)
#
# if any_protected_shared_dir: link_dirs(protected_shared_dirs)
# if any_protected_shared_file: link_files(protected_shared_files)
#
# def rollback_release():
# """
# Rollbacks latest release
# """
#
# ensure('current_path')
#
# releases_path = fetch('releases_path')
#
# with(settings(show('debug'))):
# with cd(releases_path):
# echo_subtask('Finding previous release for rollback')
# rollback_release_number = run('ls -1A | sort -n | tail -n 2 | head -n 1')
#
# if int(rollback_release_number) > 0:
# echo_subtask('Linking previous release to current')
# run('ln -nfs %s/%s %s' % (releases_path, rollback_release_number, fetch('current_path')))
#
# echo_subtask('Finding latest release')
# current_release = run('ls -1A | sort -n | tail -n 1')
#
# if int(current_release) > 0:
# echo_subtask('Removing latest release')
# run('rm -rf %s/%s' % (releases_path, current_release))
# else:
# abort('Can\'t find latest release for remove.')
# else:
# abort('Can\'t find previous release for rollback.')
#
# Path: py_mina/subtasks/git.py
# def git_clone():
# """
# Clones repository to tmp build dir
# """
#
# maybe_clone_git_repository()
# fetch_new_commits()
# use_git_branch()
. Output only the next line. | link_shared_paths() |
Using the snippet: <|code_start|>
# Settings - shared
set('verbose', True)
set('shared_dirs', ['storage', 'env', 'tmp'])
set('shared_files', ['my_drf_app/db_conf.py', 'my_drf_app/custom_conf.py'])
# Tasks
@task
def restart():
"""
Restarts application on remote server
"""
# read README.md
run('sudo monit restart -g my_drf_app_prod')
@deploy_task(on_success=restart)
def deploy():
"""
Runs deploy process on remote server
"""
<|code_end|>
, determine the next line of code. You have imports:
from py_mina import *
from py_mina.subtasks import git_clone, create_shared_paths, link_shared_paths, rollback_release
and context (class names, function names, or code) available:
# Path: py_mina/subtasks/setup.py
# def create_shared_paths():
# """
# Creates shared (+protected) files/dirs and sets unix owner/mode
# """
#
# global shared_path
# shared_path = fetch('shared_path')
#
# def create_dirs(directories, protected=False):
# global shared_path
#
# for sdir in directories:
# create_entity(
# '/'.join([shared_path, sdir]),
# entity_type='directory',
# protected=protected
# )
#
#
# def create_files(files, protected=False):
# global shared_path
#
# for sfile in files:
# directory, filename_ = os.path.split(sfile)
#
# if directory:
# create_entity(
# '/'.join([shared_path, directory]),
# entity_type='directory',
# protected=protected
# )
#
# filepath = '/'.join([shared_path, sfile])
# create_entity(filepath, entity_type='file', protected=protected)
#
# recommendation_tuple = (env.host_string, filepath)
# echo_status('\n=====> Don\'t forget to update shared file:\n[%s] %s\n' % recommendation_tuple, error=True)
#
#
# echo_subtask('Creating shared paths')
#
# # Shared
# create_dirs(fetch('shared_dirs', default_value=[]), protected=False)
# create_files(fetch('shared_files', default_value=[]), protected=False)
#
# # Protected
# create_dirs(fetch('protected_shared_dirs', default_value=[]), protected=True)
# create_files(fetch('protected_shared_files', default_value=[]), protected=True)
#
# Path: py_mina/subtasks/deploy.py
# def link_shared_paths():
# """
# Links shared paths to build folder
# """
#
# global build_to
# build_to = fetch('build_to')
#
# global shared
# shared = fetch('shared_path')
#
# def link_dirs(dirs):
# global shared
# global build_to
#
# for sdir in dirs:
# relative_path = '/'.join(['.', sdir])
# directory, filename_ = os.path.split(relative_path)
# shared_path = '/'.join([shared, sdir])
#
# with cd(build_to):
# create_entity(directory, entity_type='directory', protected=False) # create parent directory
# run('rm -rf %s' % relative_path) # remove directory if it conficts with shared
# run('ln -s %s %s' % (shared_path, relative_path)) # link shared to current folder
#
#
# def link_files(files):
# global shared
# global build_to
#
# for sfile in files:
# relative_path = '/'.join(['.', sfile])
# directory, filename_ = os.path.split(relative_path)
# shared_path = '/'.join([shared, sfile])
#
# with cd(build_to):
# create_entity(directory, entity_type='directory', protected=False) # create parent directory
# run('ln -sf %s %s' % (shared_path, relative_path)) # link shared to current folder
#
#
# shared_dirs = fetch('shared_dirs', default_value=[])
# shared_files = fetch('shared_files', default_value=[])
# any_shared_dir = len(shared_dirs) > 0
# any_shared_file = len(shared_files) > 0
#
# protected_shared_dirs = fetch('protected_shared_dirs', default_value=[])
# protected_shared_files = fetch('protected_shared_files', default_value=[])
# any_protected_shared_dir = len(protected_shared_dirs) > 0
# any_protected_shared_file = len(protected_shared_files) > 0
#
# if any_shared_dir or any_shared_file or any_protected_shared_dir or any_protected_shared_file:
# echo_subtask("Linking shared paths")
#
# if any_shared_dir: link_dirs(shared_dirs)
# if any_shared_file: link_files(shared_files)
#
# if any_protected_shared_dir: link_dirs(protected_shared_dirs)
# if any_protected_shared_file: link_files(protected_shared_files)
#
# def rollback_release():
# """
# Rollbacks latest release
# """
#
# ensure('current_path')
#
# releases_path = fetch('releases_path')
#
# with(settings(show('debug'))):
# with cd(releases_path):
# echo_subtask('Finding previous release for rollback')
# rollback_release_number = run('ls -1A | sort -n | tail -n 2 | head -n 1')
#
# if int(rollback_release_number) > 0:
# echo_subtask('Linking previous release to current')
# run('ln -nfs %s/%s %s' % (releases_path, rollback_release_number, fetch('current_path')))
#
# echo_subtask('Finding latest release')
# current_release = run('ls -1A | sort -n | tail -n 1')
#
# if int(current_release) > 0:
# echo_subtask('Removing latest release')
# run('rm -rf %s/%s' % (releases_path, current_release))
# else:
# abort('Can\'t find latest release for remove.')
# else:
# abort('Can\'t find previous release for rollback.')
#
# Path: py_mina/subtasks/git.py
# def git_clone():
# """
# Clones repository to tmp build dir
# """
#
# maybe_clone_git_repository()
# fetch_new_commits()
# use_git_branch()
. Output only the next line. | git_clone() |
Continue the code snippet: <|code_start|>
from __future__ import with_statement
def deploy_task(on_success=None):
"""
Deploy task arguments decorator
"""
def deploy_task_wrapper(wrapped_function):
"""
Deploy task decorator
"""
wrapped_function_name = wrapped_function.__name__
def _pre_deploy():
try:
check_lock()
lock()
create_build_path()
discover_latest_release()
set_state('pre_deploy', True)
except Exception as error:
set_state('pre_deploy', error)
raise error # escalate exception to 'deploy_wrapper' function
def _deploy(*args):
<|code_end|>
. Use current file imports:
import timeit
from fabric.api import task, settings
from py_mina.state import state, set_state
from py_mina.subtasks.deploy import *
from py_mina.echo import echo_task
and context (classes, functions, or code) from other files:
# Path: py_mina/state.py
# def set(key, value):
#
# Path: py_mina/echo.py
# def echo_task(message, error=False):
# color = red if error == True else yellow
#
# print(color('\n=====> %s' % message))
. Output only the next line. | if state.get('pre_deploy') == True: |
Next line prediction: <|code_start|>"""
Decorator for deploy task
"""
from __future__ import with_statement
def deploy_task(on_success=None):
"""
Deploy task arguments decorator
"""
def deploy_task_wrapper(wrapped_function):
"""
Deploy task decorator
"""
wrapped_function_name = wrapped_function.__name__
def _pre_deploy():
try:
check_lock()
lock()
create_build_path()
discover_latest_release()
<|code_end|>
. Use current file imports:
(import timeit
from fabric.api import task, settings
from py_mina.state import state, set_state
from py_mina.subtasks.deploy import *
from py_mina.echo import echo_task)
and context including class names, function names, or small code snippets from other files:
# Path: py_mina/state.py
# def set(key, value):
#
# Path: py_mina/echo.py
# def echo_task(message, error=False):
# color = red if error == True else yellow
#
# print(color('\n=====> %s' % message))
. Output only the next line. | set_state('pre_deploy', True) |
Continue the code snippet: <|code_start|> raise error # escalate exception to 'deploy_wrapper' function
def _deploy(*args):
if state.get('pre_deploy') == True:
try:
with cd(fetch('build_to')):
wrapped_function(*args)
set_state('deploy', True)
except Exception as error:
set_state('deploy', error)
raise error # escalate exception to 'deploy_wrapper' function
def _post_deploy():
if state.get('deploy') == True:
try:
move_build_to_releases()
link_release_to_current()
set_state('post_deploy', True)
except Exception as error:
set_state('post_deploy', error)
raise error # escalate exception to 'deploy_wrapper' function
def _finalize_deploy():
if not state.get('success') == True:
<|code_end|>
. Use current file imports:
import timeit
from fabric.api import task, settings
from py_mina.state import state, set_state
from py_mina.subtasks.deploy import *
from py_mina.echo import echo_task
and context (classes, functions, or code) from other files:
# Path: py_mina/state.py
# def set(key, value):
#
# Path: py_mina/echo.py
# def echo_task(message, error=False):
# color = red if error == True else yellow
#
# print(color('\n=====> %s' % message))
. Output only the next line. | echo_task('Cleaning up failed deploy') |
Given snippet: <|code_start|>################################################################################
# Config
################################################################################
def check_deploy_config():
"""
Check required config settings for deploy task
"""
check_config(['user', 'hosts', 'deploy_to'])
################################################################################
# [PRE] deploy hooks
################################################################################
def check_lock():
"""
Aborts deploy if lock file is found
"""
def run_abort():
abort("Another deploy in progress")
echo_subtask("Checking `deploy.lock` file presence")
with settings(hide('warnings'), warn_only=True):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
from fabric.colors import red, green, yellow
from fabric.api import *
from fabric.contrib.console import confirm
from py_mina.config import fetch, ensure, set, check_config
from py_mina.state import state
from py_mina.echo import *
from py_mina.subtasks.setup import create_entity
and context:
# Path: py_mina/config.py
# def fetch(key, default_value=None):
# """
# Gets and ensures config setting or returns `default_value` if provided
# """
#
# if key in config.keys():
# return config.get(key)
# else:
# if default_value != None:
# return default_value
# else:
# raise Exception('"%s" is not defined' % key)
#
# def ensure(key):
# """
# Ensures presence of config setting. Prevents from running unnecessary commands,
# before discovering, that config setting is not set
# """
#
# if not key in config.keys():
# raise Exception('"%s" must be defined' % key)
#
# def set(key, value):
# """
# Sets config setting (updates `fabric3` config if necessary)
# """
#
# if key in config.get('farbric_config_settings'):
# env.update({ key: value })
# config.update({ key: value })
# elif key == 'deploy_to':
# config.update({
# 'deploy_to': value,
# 'scm': '/'.join([value, 'scm']),
# 'shared_path': '/'.join([value, 'shared']),
# 'current_path': '/'.join([value, 'current']),
# 'releases_path': '/'.join([value, 'releases']),
# 'build_to': '/'.join([value, 'tmp', 'build-' + str(time.time())]),
# })
# else:
# config.update({ key: value })
#
# def check_config(required_settings=[]):
# """
# Ensures required settings in cofig
# """
#
# try:
# for setting in required_settings:
# ensure(setting)
# except EnsureConfigError:
# msg = 'Bad config!\nRequired settings: {0}\nCurrent config: {1}'
#
# raise Exception(msg.format(required_settings, config))
#
# Path: py_mina/state.py
# def set(key, value):
#
# Path: py_mina/subtasks/setup.py
# def create_entity(entity_path, entity_type = 'file', protected=False):
# """
# Creates directory/file and sets proper owner/mode.
# """
#
# chmod_sudo = 'sudo ' if fetch('sudo_on_chmod') else ''
# chown_sudo = 'sudo ' if fetch('sudo_on_chown') else ''
#
# def change_owner(owner_triple):
# """
# Changes unix owner/mode
# """
#
# run(chmod_sudo + 'chmod 0755 ' + entity_path)
# run(chown_sudo + 'chown %s:%s %s' % owner_triple)
#
#
# # 1) Create file/directory
#
# if entity_type == 'file':
# run('touch %s' % entity_path)
# else:
# run('mkdir -p %s' % entity_path)
#
# # 2) Change owner/mode
#
# if protected:
# protected_owner_user = fetch('protected_owner_user')
# protected_owner_group = fetch('protected_owner_group')
#
# change_owner((protected_owner_user, protected_owner_group, entity_path))
# else:
# owner_user = fetch('owner_user', default_value=False)
# owner_group = fetch('owner_group', default_value=False)
#
# if owner_user != False and owner_group != False:
# change_owner((owner_user, owner_group, entity_path))
# else:
# run(chmod_sudo + 'chmod 0755 ' + entity_path)
which might include code, classes, or functions. Output only the next line. | if run('test -f %s' % '/'.join([fetch('deploy_to'), 'deploy.lock'])).succeeded: |
Using the snippet: <|code_start|># [PRE] deploy hooks
################################################################################
def check_lock():
"""
Aborts deploy if lock file is found
"""
def run_abort():
abort("Another deploy in progress")
echo_subtask("Checking `deploy.lock` file presence")
with settings(hide('warnings'), warn_only=True):
if run('test -f %s' % '/'.join([fetch('deploy_to'), 'deploy.lock'])).succeeded:
if fetch('ask_unlock_if_locked', default_value=False):
if not confirm('Deploy lockfile exists. Continue?'):
run_abort()
else:
run_abort()
def lock():
"""
Locks deploy
Parallel deploys are not allowed
"""
<|code_end|>
, determine the next line of code. You have imports:
import os
from fabric.colors import red, green, yellow
from fabric.api import *
from fabric.contrib.console import confirm
from py_mina.config import fetch, ensure, set, check_config
from py_mina.state import state
from py_mina.echo import *
from py_mina.subtasks.setup import create_entity
and context (class names, function names, or code) available:
# Path: py_mina/config.py
# def fetch(key, default_value=None):
# """
# Gets and ensures config setting or returns `default_value` if provided
# """
#
# if key in config.keys():
# return config.get(key)
# else:
# if default_value != None:
# return default_value
# else:
# raise Exception('"%s" is not defined' % key)
#
# def ensure(key):
# """
# Ensures presence of config setting. Prevents from running unnecessary commands,
# before discovering, that config setting is not set
# """
#
# if not key in config.keys():
# raise Exception('"%s" must be defined' % key)
#
# def set(key, value):
# """
# Sets config setting (updates `fabric3` config if necessary)
# """
#
# if key in config.get('farbric_config_settings'):
# env.update({ key: value })
# config.update({ key: value })
# elif key == 'deploy_to':
# config.update({
# 'deploy_to': value,
# 'scm': '/'.join([value, 'scm']),
# 'shared_path': '/'.join([value, 'shared']),
# 'current_path': '/'.join([value, 'current']),
# 'releases_path': '/'.join([value, 'releases']),
# 'build_to': '/'.join([value, 'tmp', 'build-' + str(time.time())]),
# })
# else:
# config.update({ key: value })
#
# def check_config(required_settings=[]):
# """
# Ensures required settings in cofig
# """
#
# try:
# for setting in required_settings:
# ensure(setting)
# except EnsureConfigError:
# msg = 'Bad config!\nRequired settings: {0}\nCurrent config: {1}'
#
# raise Exception(msg.format(required_settings, config))
#
# Path: py_mina/state.py
# def set(key, value):
#
# Path: py_mina/subtasks/setup.py
# def create_entity(entity_path, entity_type = 'file', protected=False):
# """
# Creates directory/file and sets proper owner/mode.
# """
#
# chmod_sudo = 'sudo ' if fetch('sudo_on_chmod') else ''
# chown_sudo = 'sudo ' if fetch('sudo_on_chown') else ''
#
# def change_owner(owner_triple):
# """
# Changes unix owner/mode
# """
#
# run(chmod_sudo + 'chmod 0755 ' + entity_path)
# run(chown_sudo + 'chown %s:%s %s' % owner_triple)
#
#
# # 1) Create file/directory
#
# if entity_type == 'file':
# run('touch %s' % entity_path)
# else:
# run('mkdir -p %s' % entity_path)
#
# # 2) Change owner/mode
#
# if protected:
# protected_owner_user = fetch('protected_owner_user')
# protected_owner_group = fetch('protected_owner_group')
#
# change_owner((protected_owner_user, protected_owner_group, entity_path))
# else:
# owner_user = fetch('owner_user', default_value=False)
# owner_group = fetch('owner_group', default_value=False)
#
# if owner_user != False and owner_group != False:
# change_owner((owner_user, owner_group, entity_path))
# else:
# run(chmod_sudo + 'chmod 0755 ' + entity_path)
. Output only the next line. | ensure('build_to') |
Given snippet: <|code_start|> if run('test -d %s' % build_path).failed:
create_entity(build_path, entity_type='directory', protected=False)
def discover_latest_release():
"""
Connects to remote server and discovers next release number
"""
releases_path = fetch('releases_path')
echo_subtask("Discovering latest release number")
# Get latest release number
with settings(hide('warnings'), warn_only=True):
if run('test -d %s' % releases_path).failed:
last_release_number = 0
create_entity(releases_path, entity_type='directory', protected=False)
else:
releases_respond = run('ls -1p %s | sed "s/\///g"' % releases_path)
releases_dirs = list(filter(lambda x: len(x) != 0, releases_respond.split('\r\n')))
if len(releases_dirs) > 0:
last_release_number = max(map(lambda x: int(x), releases_dirs)) or 0
else:
last_release_number = 0
release_number = last_release_number + 1
# Set release info to config
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
from fabric.colors import red, green, yellow
from fabric.api import *
from fabric.contrib.console import confirm
from py_mina.config import fetch, ensure, set, check_config
from py_mina.state import state
from py_mina.echo import *
from py_mina.subtasks.setup import create_entity
and context:
# Path: py_mina/config.py
# def fetch(key, default_value=None):
# """
# Gets and ensures config setting or returns `default_value` if provided
# """
#
# if key in config.keys():
# return config.get(key)
# else:
# if default_value != None:
# return default_value
# else:
# raise Exception('"%s" is not defined' % key)
#
# def ensure(key):
# """
# Ensures presence of config setting. Prevents from running unnecessary commands,
# before discovering, that config setting is not set
# """
#
# if not key in config.keys():
# raise Exception('"%s" must be defined' % key)
#
# def set(key, value):
# """
# Sets config setting (updates `fabric3` config if necessary)
# """
#
# if key in config.get('farbric_config_settings'):
# env.update({ key: value })
# config.update({ key: value })
# elif key == 'deploy_to':
# config.update({
# 'deploy_to': value,
# 'scm': '/'.join([value, 'scm']),
# 'shared_path': '/'.join([value, 'shared']),
# 'current_path': '/'.join([value, 'current']),
# 'releases_path': '/'.join([value, 'releases']),
# 'build_to': '/'.join([value, 'tmp', 'build-' + str(time.time())]),
# })
# else:
# config.update({ key: value })
#
# def check_config(required_settings=[]):
# """
# Ensures required settings in cofig
# """
#
# try:
# for setting in required_settings:
# ensure(setting)
# except EnsureConfigError:
# msg = 'Bad config!\nRequired settings: {0}\nCurrent config: {1}'
#
# raise Exception(msg.format(required_settings, config))
#
# Path: py_mina/state.py
# def set(key, value):
#
# Path: py_mina/subtasks/setup.py
# def create_entity(entity_path, entity_type = 'file', protected=False):
# """
# Creates directory/file and sets proper owner/mode.
# """
#
# chmod_sudo = 'sudo ' if fetch('sudo_on_chmod') else ''
# chown_sudo = 'sudo ' if fetch('sudo_on_chown') else ''
#
# def change_owner(owner_triple):
# """
# Changes unix owner/mode
# """
#
# run(chmod_sudo + 'chmod 0755 ' + entity_path)
# run(chown_sudo + 'chown %s:%s %s' % owner_triple)
#
#
# # 1) Create file/directory
#
# if entity_type == 'file':
# run('touch %s' % entity_path)
# else:
# run('mkdir -p %s' % entity_path)
#
# # 2) Change owner/mode
#
# if protected:
# protected_owner_user = fetch('protected_owner_user')
# protected_owner_group = fetch('protected_owner_group')
#
# change_owner((protected_owner_user, protected_owner_group, entity_path))
# else:
# owner_user = fetch('owner_user', default_value=False)
# owner_group = fetch('owner_group', default_value=False)
#
# if owner_user != False and owner_group != False:
# change_owner((owner_user, owner_group, entity_path))
# else:
# run(chmod_sudo + 'chmod 0755 ' + entity_path)
which might include code, classes, or functions. Output only the next line. | set('release_number', release_number) |
Given the following code snippet before the placeholder: <|code_start|>"""
Deploy tasks
"""
from __future__ import with_statement
################################################################################
# Config
################################################################################
def check_deploy_config():
"""
Check required config settings for deploy task
"""
<|code_end|>
, predict the next line using imports from the current file:
import os
from fabric.colors import red, green, yellow
from fabric.api import *
from fabric.contrib.console import confirm
from py_mina.config import fetch, ensure, set, check_config
from py_mina.state import state
from py_mina.echo import *
from py_mina.subtasks.setup import create_entity
and context including class names, function names, and sometimes code from other files:
# Path: py_mina/config.py
# def fetch(key, default_value=None):
# """
# Gets and ensures config setting or returns `default_value` if provided
# """
#
# if key in config.keys():
# return config.get(key)
# else:
# if default_value != None:
# return default_value
# else:
# raise Exception('"%s" is not defined' % key)
#
# def ensure(key):
# """
# Ensures presence of config setting. Prevents from running unnecessary commands,
# before discovering, that config setting is not set
# """
#
# if not key in config.keys():
# raise Exception('"%s" must be defined' % key)
#
# def set(key, value):
# """
# Sets config setting (updates `fabric3` config if necessary)
# """
#
# if key in config.get('farbric_config_settings'):
# env.update({ key: value })
# config.update({ key: value })
# elif key == 'deploy_to':
# config.update({
# 'deploy_to': value,
# 'scm': '/'.join([value, 'scm']),
# 'shared_path': '/'.join([value, 'shared']),
# 'current_path': '/'.join([value, 'current']),
# 'releases_path': '/'.join([value, 'releases']),
# 'build_to': '/'.join([value, 'tmp', 'build-' + str(time.time())]),
# })
# else:
# config.update({ key: value })
#
# def check_config(required_settings=[]):
# """
# Ensures required settings in cofig
# """
#
# try:
# for setting in required_settings:
# ensure(setting)
# except EnsureConfigError:
# msg = 'Bad config!\nRequired settings: {0}\nCurrent config: {1}'
#
# raise Exception(msg.format(required_settings, config))
#
# Path: py_mina/state.py
# def set(key, value):
#
# Path: py_mina/subtasks/setup.py
# def create_entity(entity_path, entity_type = 'file', protected=False):
# """
# Creates directory/file and sets proper owner/mode.
# """
#
# chmod_sudo = 'sudo ' if fetch('sudo_on_chmod') else ''
# chown_sudo = 'sudo ' if fetch('sudo_on_chown') else ''
#
# def change_owner(owner_triple):
# """
# Changes unix owner/mode
# """
#
# run(chmod_sudo + 'chmod 0755 ' + entity_path)
# run(chown_sudo + 'chown %s:%s %s' % owner_triple)
#
#
# # 1) Create file/directory
#
# if entity_type == 'file':
# run('touch %s' % entity_path)
# else:
# run('mkdir -p %s' % entity_path)
#
# # 2) Change owner/mode
#
# if protected:
# protected_owner_user = fetch('protected_owner_user')
# protected_owner_group = fetch('protected_owner_group')
#
# change_owner((protected_owner_user, protected_owner_group, entity_path))
# else:
# owner_user = fetch('owner_user', default_value=False)
# owner_group = fetch('owner_group', default_value=False)
#
# if owner_user != False and owner_group != False:
# change_owner((owner_user, owner_group, entity_path))
# else:
# run(chmod_sudo + 'chmod 0755 ' + entity_path)
. Output only the next line. | check_config(['user', 'hosts', 'deploy_to']) |
Given the following code snippet before the placeholder: <|code_start|> with(settings(show('debug'))):
with cd(releases_path):
echo_subtask('Finding previous release for rollback')
rollback_release_number = run('ls -1A | sort -n | tail -n 2 | head -n 1')
if int(rollback_release_number) > 0:
echo_subtask('Linking previous release to current')
run('ln -nfs %s/%s %s' % (releases_path, rollback_release_number, fetch('current_path')))
echo_subtask('Finding latest release')
current_release = run('ls -1A | sort -n | tail -n 1')
if int(current_release) > 0:
echo_subtask('Removing latest release')
run('rm -rf %s/%s' % (releases_path, current_release))
else:
abort('Can\'t find latest release for remove.')
else:
abort('Can\'t find previous release for rollback.')
################################################################################
# Print
################################################################################
def get_error_states():
def find_error_states(x):
if x == 'success': return False
<|code_end|>
, predict the next line using imports from the current file:
import os
from fabric.colors import red, green, yellow
from fabric.api import *
from fabric.contrib.console import confirm
from py_mina.config import fetch, ensure, set, check_config
from py_mina.state import state
from py_mina.echo import *
from py_mina.subtasks.setup import create_entity
and context including class names, function names, and sometimes code from other files:
# Path: py_mina/config.py
# def fetch(key, default_value=None):
# """
# Gets and ensures config setting or returns `default_value` if provided
# """
#
# if key in config.keys():
# return config.get(key)
# else:
# if default_value != None:
# return default_value
# else:
# raise Exception('"%s" is not defined' % key)
#
# def ensure(key):
# """
# Ensures presence of config setting. Prevents from running unnecessary commands,
# before discovering, that config setting is not set
# """
#
# if not key in config.keys():
# raise Exception('"%s" must be defined' % key)
#
# def set(key, value):
# """
# Sets config setting (updates `fabric3` config if necessary)
# """
#
# if key in config.get('farbric_config_settings'):
# env.update({ key: value })
# config.update({ key: value })
# elif key == 'deploy_to':
# config.update({
# 'deploy_to': value,
# 'scm': '/'.join([value, 'scm']),
# 'shared_path': '/'.join([value, 'shared']),
# 'current_path': '/'.join([value, 'current']),
# 'releases_path': '/'.join([value, 'releases']),
# 'build_to': '/'.join([value, 'tmp', 'build-' + str(time.time())]),
# })
# else:
# config.update({ key: value })
#
# def check_config(required_settings=[]):
# """
# Ensures required settings in cofig
# """
#
# try:
# for setting in required_settings:
# ensure(setting)
# except EnsureConfigError:
# msg = 'Bad config!\nRequired settings: {0}\nCurrent config: {1}'
#
# raise Exception(msg.format(required_settings, config))
#
# Path: py_mina/state.py
# def set(key, value):
#
# Path: py_mina/subtasks/setup.py
# def create_entity(entity_path, entity_type = 'file', protected=False):
# """
# Creates directory/file and sets proper owner/mode.
# """
#
# chmod_sudo = 'sudo ' if fetch('sudo_on_chmod') else ''
# chown_sudo = 'sudo ' if fetch('sudo_on_chown') else ''
#
# def change_owner(owner_triple):
# """
# Changes unix owner/mode
# """
#
# run(chmod_sudo + 'chmod 0755 ' + entity_path)
# run(chown_sudo + 'chown %s:%s %s' % owner_triple)
#
#
# # 1) Create file/directory
#
# if entity_type == 'file':
# run('touch %s' % entity_path)
# else:
# run('mkdir -p %s' % entity_path)
#
# # 2) Change owner/mode
#
# if protected:
# protected_owner_user = fetch('protected_owner_user')
# protected_owner_group = fetch('protected_owner_group')
#
# change_owner((protected_owner_user, protected_owner_group, entity_path))
# else:
# owner_user = fetch('owner_user', default_value=False)
# owner_group = fetch('owner_group', default_value=False)
#
# if owner_user != False and owner_group != False:
# change_owner((owner_user, owner_group, entity_path))
# else:
# run(chmod_sudo + 'chmod 0755 ' + entity_path)
. Output only the next line. | return state.get(x) not in [True, None] |
Using the snippet: <|code_start|>def check_lock():
"""
Aborts deploy if lock file is found
"""
def run_abort():
abort("Another deploy in progress")
echo_subtask("Checking `deploy.lock` file presence")
with settings(hide('warnings'), warn_only=True):
if run('test -f %s' % '/'.join([fetch('deploy_to'), 'deploy.lock'])).succeeded:
if fetch('ask_unlock_if_locked', default_value=False):
if not confirm('Deploy lockfile exists. Continue?'):
run_abort()
else:
run_abort()
def lock():
"""
Locks deploy
Parallel deploys are not allowed
"""
ensure('build_to')
echo_subtask("Creating `deploy.lock` file")
<|code_end|>
, determine the next line of code. You have imports:
import os
from fabric.colors import red, green, yellow
from fabric.api import *
from fabric.contrib.console import confirm
from py_mina.config import fetch, ensure, set, check_config
from py_mina.state import state
from py_mina.echo import *
from py_mina.subtasks.setup import create_entity
and context (class names, function names, or code) available:
# Path: py_mina/config.py
# def fetch(key, default_value=None):
# """
# Gets and ensures config setting or returns `default_value` if provided
# """
#
# if key in config.keys():
# return config.get(key)
# else:
# if default_value != None:
# return default_value
# else:
# raise Exception('"%s" is not defined' % key)
#
# def ensure(key):
# """
# Ensures presence of config setting. Prevents from running unnecessary commands,
# before discovering, that config setting is not set
# """
#
# if not key in config.keys():
# raise Exception('"%s" must be defined' % key)
#
# def set(key, value):
# """
# Sets config setting (updates `fabric3` config if necessary)
# """
#
# if key in config.get('farbric_config_settings'):
# env.update({ key: value })
# config.update({ key: value })
# elif key == 'deploy_to':
# config.update({
# 'deploy_to': value,
# 'scm': '/'.join([value, 'scm']),
# 'shared_path': '/'.join([value, 'shared']),
# 'current_path': '/'.join([value, 'current']),
# 'releases_path': '/'.join([value, 'releases']),
# 'build_to': '/'.join([value, 'tmp', 'build-' + str(time.time())]),
# })
# else:
# config.update({ key: value })
#
# def check_config(required_settings=[]):
# """
# Ensures required settings in cofig
# """
#
# try:
# for setting in required_settings:
# ensure(setting)
# except EnsureConfigError:
# msg = 'Bad config!\nRequired settings: {0}\nCurrent config: {1}'
#
# raise Exception(msg.format(required_settings, config))
#
# Path: py_mina/state.py
# def set(key, value):
#
# Path: py_mina/subtasks/setup.py
# def create_entity(entity_path, entity_type = 'file', protected=False):
# """
# Creates directory/file and sets proper owner/mode.
# """
#
# chmod_sudo = 'sudo ' if fetch('sudo_on_chmod') else ''
# chown_sudo = 'sudo ' if fetch('sudo_on_chown') else ''
#
# def change_owner(owner_triple):
# """
# Changes unix owner/mode
# """
#
# run(chmod_sudo + 'chmod 0755 ' + entity_path)
# run(chown_sudo + 'chown %s:%s %s' % owner_triple)
#
#
# # 1) Create file/directory
#
# if entity_type == 'file':
# run('touch %s' % entity_path)
# else:
# run('mkdir -p %s' % entity_path)
#
# # 2) Change owner/mode
#
# if protected:
# protected_owner_user = fetch('protected_owner_user')
# protected_owner_group = fetch('protected_owner_group')
#
# change_owner((protected_owner_user, protected_owner_group, entity_path))
# else:
# owner_user = fetch('owner_user', default_value=False)
# owner_group = fetch('owner_group', default_value=False)
#
# if owner_user != False and owner_group != False:
# change_owner((owner_user, owner_group, entity_path))
# else:
# run(chmod_sudo + 'chmod 0755 ' + entity_path)
. Output only the next line. | create_entity( |
Using the snippet: <|code_start|>"""
Task decorator (wrapper for `fabric3` @task decorator)
"""
from __future__ import with_statement
def task(wrapped_function):
"""
Task function decorator
"""
wrapped_function_name = wrapped_function.__name__
def task_wrapper(*args):
"""
Runs task and prints stats at the end
"""
<|code_end|>
, determine the next line of code. You have imports:
import timeit
import fabric.api
from py_mina.echo import echo_task, print_task_stats
and context (class names, function names, or code) available:
# Path: py_mina/echo.py
# def echo_task(message, error=False):
# color = red if error == True else yellow
#
# print(color('\n=====> %s' % message))
#
# def print_task_stats(task_name, start_time, error=None):
# status_tuple = (task_name, time_string(start_time))
#
# if error:
# echo_comment(('\n[FATAL ERROR]\n\n%s' % error), error=True)
# echo_status(('\n=====> Task "%s" failed %s \n' % status_tuple), error=True)
# else:
# echo_status('\n=====> Task "%s" finished %s \n' % status_tuple)
. Output only the next line. | echo_task('Running "%s" task\n' % wrapped_function_name) |
Given snippet: <|code_start|>"""
Task decorator (wrapper for `fabric3` @task decorator)
"""
from __future__ import with_statement
def task(wrapped_function):
"""
Task function decorator
"""
wrapped_function_name = wrapped_function.__name__
def task_wrapper(*args):
"""
Runs task and prints stats at the end
"""
echo_task('Running "%s" task\n' % wrapped_function_name)
start_time = timeit.default_timer()
with fabric.api.settings(colorize_errors=True):
try:
wrapped_function(*args)
except Exception as e:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import timeit
import fabric.api
from py_mina.echo import echo_task, print_task_stats
and context:
# Path: py_mina/echo.py
# def echo_task(message, error=False):
# color = red if error == True else yellow
#
# print(color('\n=====> %s' % message))
#
# def print_task_stats(task_name, start_time, error=None):
# status_tuple = (task_name, time_string(start_time))
#
# if error:
# echo_comment(('\n[FATAL ERROR]\n\n%s' % error), error=True)
# echo_status(('\n=====> Task "%s" failed %s \n' % status_tuple), error=True)
# else:
# echo_status('\n=====> Task "%s" finished %s \n' % status_tuple)
which might include code, classes, or functions. Output only the next line. | print_task_stats(wrapped_function_name, start_time, e) |
Predict the next line for this snippet: <|code_start|>def setup_task(wrapped_function):
"""
Setup task function decorator
"""
wrapped_function_name = wrapped_function.__name__
def _pre_setup():
"""
Creates required structure and adds hosts to known hosts
"""
with settings(hide('output')):
create_required_structure()
add_repo_to_known_hosts()
add_host_to_known_hosts()
def setup_wrapper(*args):
"""
Runs setup process on remote server
1) check required settings (user, host, deploy_to)
2) creates required structure (releases, shared, tmp)
3) adds repo and host to known hosts if possible
4) runs wrpapped function
"""
check_setup_config()
start_time = timeit.default_timer()
<|code_end|>
with the help of current file imports:
import timeit
from fabric.api import task, settings, show, hide
from py_mina.subtasks.setup import *
from py_mina.echo import echo_task, print_task_stats
and context from other files:
# Path: py_mina/echo.py
# def echo_task(message, error=False):
# color = red if error == True else yellow
#
# print(color('\n=====> %s' % message))
#
# def print_task_stats(task_name, start_time, error=None):
# status_tuple = (task_name, time_string(start_time))
#
# if error:
# echo_comment(('\n[FATAL ERROR]\n\n%s' % error), error=True)
# echo_status(('\n=====> Task "%s" failed %s \n' % status_tuple), error=True)
# else:
# echo_status('\n=====> Task "%s" finished %s \n' % status_tuple)
, which may contain function names, class names, or code. Output only the next line. | echo_task('Running "%s" task' % wrapped_function_name) |
Using the snippet: <|code_start|> def _pre_setup():
"""
Creates required structure and adds hosts to known hosts
"""
with settings(hide('output')):
create_required_structure()
add_repo_to_known_hosts()
add_host_to_known_hosts()
def setup_wrapper(*args):
"""
Runs setup process on remote server
1) check required settings (user, host, deploy_to)
2) creates required structure (releases, shared, tmp)
3) adds repo and host to known hosts if possible
4) runs wrpapped function
"""
check_setup_config()
start_time = timeit.default_timer()
echo_task('Running "%s" task' % wrapped_function_name)
with settings(show('debug'), colorize_errors=True):
try:
_pre_setup()
wrapped_function(*args)
<|code_end|>
, determine the next line of code. You have imports:
import timeit
from fabric.api import task, settings, show, hide
from py_mina.subtasks.setup import *
from py_mina.echo import echo_task, print_task_stats
and context (class names, function names, or code) available:
# Path: py_mina/echo.py
# def echo_task(message, error=False):
# color = red if error == True else yellow
#
# print(color('\n=====> %s' % message))
#
# def print_task_stats(task_name, start_time, error=None):
# status_tuple = (task_name, time_string(start_time))
#
# if error:
# echo_comment(('\n[FATAL ERROR]\n\n%s' % error), error=True)
# echo_status(('\n=====> Task "%s" failed %s \n' % status_tuple), error=True)
# else:
# echo_status('\n=====> Task "%s" finished %s \n' % status_tuple)
. Output only the next line. | print_task_stats(wrapped_function_name, start_time) |
Predict the next line after this snippet: <|code_start|> backup_happened = True
os.rename(fullpath, backup_fullpath)
print(green('Created backup file %s' % yellow(backup_fullpath)))
create_file(filepath, content)
except Exception as error:
print(red(error))
def create_file(filepath, content):
"""
Writes content to file
"""
fullpath = os.path.join(os.path.realpath(os.curdir), filepath)
try:
with open(filepath, 'w') as f: f.write(content)
print(green('Deployfile successfully created in %s' % yellow(fullpath)))
except Exception as error:
print(red(error))
backup_happened = False
staged = args.get('staged')
backup_timestamp = time.time()
if staged == False:
<|code_end|>
using the current file's imports:
import os
import time
from fabric.main import load_fabfile
from fabric.tasks import execute
from fabric.colors import green, red, yellow
from fabric.contrib.console import confirm
from py_mina.cli.templates import base_template, generate_staged_templates
from py_mina.echo import cli_staged_init_warning
and any relevant context from other files:
# Path: py_mina/cli/templates.py
# def generate_staged_templates():
#
# Path: py_mina/echo.py
# def cli_staged_init_warning(default_directory = 'deploy'):
# notifictaion = red('\n[WARNING]\n\nDon\'t forget to specify %s %s' % (white('deployfile FILEPATH (-f)'), red('when running staged deployment')))
# prod_path = white('-f %s' % os.path.join(default_directory, 'production.py'))
# dev_path = white('-f %s' % os.path.join(default_directory, 'dev.py'))
#
# staged_deploy_notification = '''{0}
#
# Production:
# $ py_mina {1} run setup
# $ py_mina {1} run deploy
#
# Dev:
# $ py_mina {2} run setup
# $ py_mina {2} run deploy'''.format(notifictaion, prod_path, dev_path)
#
# print(staged_deploy_notification)
. Output only the next line. | create_or_backup(args.get('filename'), base_template, backup_timestamp) |
Here is a snippet: <|code_start|> print(green('Created backup file %s' % yellow(backup_fullpath)))
create_file(filepath, content)
except Exception as error:
print(red(error))
def create_file(filepath, content):
"""
Writes content to file
"""
fullpath = os.path.join(os.path.realpath(os.curdir), filepath)
try:
with open(filepath, 'w') as f: f.write(content)
print(green('Deployfile successfully created in %s' % yellow(fullpath)))
except Exception as error:
print(red(error))
backup_happened = False
staged = args.get('staged')
backup_timestamp = time.time()
if staged == False:
create_or_backup(args.get('filename'), base_template, backup_timestamp)
else:
default_directory = 'deploy/' if staged == None else staged
<|code_end|>
. Write the next line using the current file imports:
import os
import time
from fabric.main import load_fabfile
from fabric.tasks import execute
from fabric.colors import green, red, yellow
from fabric.contrib.console import confirm
from py_mina.cli.templates import base_template, generate_staged_templates
from py_mina.echo import cli_staged_init_warning
and context from other files:
# Path: py_mina/cli/templates.py
# def generate_staged_templates():
#
# Path: py_mina/echo.py
# def cli_staged_init_warning(default_directory = 'deploy'):
# notifictaion = red('\n[WARNING]\n\nDon\'t forget to specify %s %s' % (white('deployfile FILEPATH (-f)'), red('when running staged deployment')))
# prod_path = white('-f %s' % os.path.join(default_directory, 'production.py'))
# dev_path = white('-f %s' % os.path.join(default_directory, 'dev.py'))
#
# staged_deploy_notification = '''{0}
#
# Production:
# $ py_mina {1} run setup
# $ py_mina {1} run deploy
#
# Dev:
# $ py_mina {2} run setup
# $ py_mina {2} run deploy'''.format(notifictaion, prod_path, dev_path)
#
# print(staged_deploy_notification)
, which may include functions, classes, or code. Output only the next line. | templates_files = generate_staged_templates() |
Next line prediction: <|code_start|>
def create_file(filepath, content):
"""
Writes content to file
"""
fullpath = os.path.join(os.path.realpath(os.curdir), filepath)
try:
with open(filepath, 'w') as f: f.write(content)
print(green('Deployfile successfully created in %s' % yellow(fullpath)))
except Exception as error:
print(red(error))
backup_happened = False
staged = args.get('staged')
backup_timestamp = time.time()
if staged == False:
create_or_backup(args.get('filename'), base_template, backup_timestamp)
else:
default_directory = 'deploy/' if staged == None else staged
templates_files = generate_staged_templates()
for template_file_key in templates_files.keys():
filepath = os.path.join(default_directory, '%s.py' % template_file_key)
create_or_backup(filepath, templates_files[template_file_key], backup_timestamp)
<|code_end|>
. Use current file imports:
(import os
import time
from fabric.main import load_fabfile
from fabric.tasks import execute
from fabric.colors import green, red, yellow
from fabric.contrib.console import confirm
from py_mina.cli.templates import base_template, generate_staged_templates
from py_mina.echo import cli_staged_init_warning)
and context including class names, function names, or small code snippets from other files:
# Path: py_mina/cli/templates.py
# def generate_staged_templates():
#
# Path: py_mina/echo.py
# def cli_staged_init_warning(default_directory = 'deploy'):
# notifictaion = red('\n[WARNING]\n\nDon\'t forget to specify %s %s' % (white('deployfile FILEPATH (-f)'), red('when running staged deployment')))
# prod_path = white('-f %s' % os.path.join(default_directory, 'production.py'))
# dev_path = white('-f %s' % os.path.join(default_directory, 'dev.py'))
#
# staged_deploy_notification = '''{0}
#
# Production:
# $ py_mina {1} run setup
# $ py_mina {1} run deploy
#
# Dev:
# $ py_mina {2} run setup
# $ py_mina {2} run deploy'''.format(notifictaion, prod_path, dev_path)
#
# print(staged_deploy_notification)
. Output only the next line. | cli_staged_init_warning(default_directory) |
Predict the next line for this snippet: <|code_start|>#
# PyDvi - A Python Library to Process DVI Stream.
# Copyright (C) 2011 Salvaire Fabrice
#
####################################################################################################
####################################################################################################
#
# Audit
#
# - 01/12/2011 fabrice
#
####################################################################################################
####################################################################################################
####################################################################################################
####################################################################################################
class TestPkFont(unittest.TestCase):
def test_cmr10(self):
font_name = 'cmr10'
pk_file = kpsewhich(font_name, file_format='pk')
self.assertIsNotNone(pk_file)
<|code_end|>
with the help of current file imports:
import unittest
from PyDvi.Font.PkFont import PkFont
from PyDvi.Kpathsea import kpsewhich
from PyDvi.TeXUnit import *
from PyDvi.Tools.Stream import to_fix_word
and context from other files:
# Path: PyDvi/Font/PkFont.py
# class PkFont(Font):
#
# """This class implements the packed font type in the font manager.
#
# To create a packed font instance use::
#
# font = PkFont(font_manager, font_id, name)
#
# where *font_manager* is a :class:`PyDvi.FontManager.FontManager` instance, *font_id* is the font
# id provided by the font manager and *name* is the font name, "cmr10" for example. The packed
# font file is parsed using a :class:`PyDvi.PkFontParser.PkFontParser` instance.
#
# """
#
# font_type = font_types.Pk
# font_type_string = 'TeX Packed Font'
# extension = 'pk'
#
# ##############################################
#
# def __init__(self, font_manager, font_id, name):
#
# super(PkFont, self).__init__(font_manager, font_id, name)
#
# self._glyphs = {}
# PkFontParser.parse(self)
#
# ##############################################
#
# def __getitem__(self, char_code):
#
# """ Return the :class:`PyDvi.PkGlyph.PkGlyph` instance for the char code *char_code*. """
#
# return self._glyphs[char_code]
#
# ##############################################
#
# def __len__(self):
#
# """ Return the number of glyphs in the font. """
#
# return len(self._glyphs)
#
# ##############################################
#
# def _find_font(self):
#
# """ Find the font file location in the system using Kpathsea and build if it is not
# already done.
# """
#
# super(PkFont, self)._find_font(kpsewhich_options='-mktex=pk')
#
# ##############################################
#
# def _set_preambule_data(self,
# pk_id,
# comment,
# design_font_size,
# checksum,
# horizontal_dpi,
# vertical_dpi):
#
# """ Set the preambule data from the Packed Font Parser. """
#
# self.pk_id = pk_id
# self.comment = comment
# self.design_font_size = design_font_size
# self.checksum = checksum
# self.horizontal_dpi = horizontal_dpi
# self.vertical_dpi = vertical_dpi
#
# ##############################################
#
# def register_glyph(self, glyph):
#
# self._glyphs[glyph.char_code] = glyph
#
# ##############################################
#
# def get_glyph(self, glyph_index, size=None, resolution=None):
#
# return self._glyphs[glyph_index]
#
# ##############################################
#
# def print_summary(self):
#
# string_format = """
# Preambule
# - PK ID %u
# - Comment '%s'
# - Design size %.1f pt
# - Checksum %u
# - Resolution
# - Horizontal %.1f dpi
# - Vertical %.1f dpi """
#
# message = self.print_header() + string_format % (
# self.pk_id,
# self.comment,
# self.design_font_size,
# self.checksum,
# self.horizontal_dpi,
# self.vertical_dpi,
# )
#
# print_card(message)
#
# Path: PyDvi/Kpathsea.py
# def kpsewhich(filename, file_format=None, options=None):
#
# """Wrapper around the :command:`kpsewhich` command, cf. kpsewhich(1).
#
# *file_format*
# used to specify the file format, see :command:`kpsewhich` help for the file format list.
#
# *options*
# additional option for :command:`kpsewhich`.
#
# Examples::
#
# >>> kpsewhich('cmr10', file_format='tfm')
# '/usr/share/texmf/fonts/tfm/public/cm/cmr10.tfm'
# """
#
# key = '{}-{}-{}'.format(filename, file_format, options)
# if key in _cache:
# return _cache[key]
#
# command = ['kpsewhich']
# if file_format is not None:
# command.append("--format='%s'" % (file_format))
# if options is not None:
# command.append(options)
# command.append(filename)
#
# shell_command = ' '.join(command)
# _module_logger.debug('Run shell command: ' + shell_command)
# pipe = subprocess.Popen(shell_command, shell=True, stdout=subprocess.PIPE)
# stdout = pipe.communicate()[0]
# _module_logger.debug('stdout:\n' + stdout)
# path = stdout.rstrip()
# path = path if path else None # Fixme: could raise an exception
#
# _cache[key] = path
# return path
#
# Path: PyDvi/Tools/Stream.py
# def to_fix_word(x):
#
# """ Convert *x* to a fix word.
#
# A fix word is a 32-bit representation of a binary fraction. A fix word is a signed quantity,
# with the two's complement of the entire word used to represent negation. Of the 32 bits in a
# fix word, exactly 12 are to the left of the binary point; thus, the largest fix word value is
# 2048 - 2**-20, and the smallest is -2048.
#
# ``fix word = x / 2**20``
# """
#
# return FIX_WORD_SCALE*x
, which may contain function names, class names, or code. Output only the next line. | pk_font = PkFont(font_manager=None, font_id=0, name=font_name) |
Continue the code snippet: <|code_start|>####################################################################################################
#
# PyDvi - A Python Library to Process DVI Stream.
# Copyright (C) 2011 Salvaire Fabrice
#
####################################################################################################
####################################################################################################
#
# Audit
#
# - 01/12/2011 fabrice
#
####################################################################################################
####################################################################################################
####################################################################################################
####################################################################################################
class TestPkFont(unittest.TestCase):
def test_cmr10(self):
font_name = 'cmr10'
<|code_end|>
. Use current file imports:
import unittest
from PyDvi.Font.PkFont import PkFont
from PyDvi.Kpathsea import kpsewhich
from PyDvi.TeXUnit import *
from PyDvi.Tools.Stream import to_fix_word
and context (classes, functions, or code) from other files:
# Path: PyDvi/Font/PkFont.py
# class PkFont(Font):
#
# """This class implements the packed font type in the font manager.
#
# To create a packed font instance use::
#
# font = PkFont(font_manager, font_id, name)
#
# where *font_manager* is a :class:`PyDvi.FontManager.FontManager` instance, *font_id* is the font
# id provided by the font manager and *name* is the font name, "cmr10" for example. The packed
# font file is parsed using a :class:`PyDvi.PkFontParser.PkFontParser` instance.
#
# """
#
# font_type = font_types.Pk
# font_type_string = 'TeX Packed Font'
# extension = 'pk'
#
# ##############################################
#
# def __init__(self, font_manager, font_id, name):
#
# super(PkFont, self).__init__(font_manager, font_id, name)
#
# self._glyphs = {}
# PkFontParser.parse(self)
#
# ##############################################
#
# def __getitem__(self, char_code):
#
# """ Return the :class:`PyDvi.PkGlyph.PkGlyph` instance for the char code *char_code*. """
#
# return self._glyphs[char_code]
#
# ##############################################
#
# def __len__(self):
#
# """ Return the number of glyphs in the font. """
#
# return len(self._glyphs)
#
# ##############################################
#
# def _find_font(self):
#
# """ Find the font file location in the system using Kpathsea and build if it is not
# already done.
# """
#
# super(PkFont, self)._find_font(kpsewhich_options='-mktex=pk')
#
# ##############################################
#
# def _set_preambule_data(self,
# pk_id,
# comment,
# design_font_size,
# checksum,
# horizontal_dpi,
# vertical_dpi):
#
# """ Set the preambule data from the Packed Font Parser. """
#
# self.pk_id = pk_id
# self.comment = comment
# self.design_font_size = design_font_size
# self.checksum = checksum
# self.horizontal_dpi = horizontal_dpi
# self.vertical_dpi = vertical_dpi
#
# ##############################################
#
# def register_glyph(self, glyph):
#
# self._glyphs[glyph.char_code] = glyph
#
# ##############################################
#
# def get_glyph(self, glyph_index, size=None, resolution=None):
#
# return self._glyphs[glyph_index]
#
# ##############################################
#
# def print_summary(self):
#
# string_format = """
# Preambule
# - PK ID %u
# - Comment '%s'
# - Design size %.1f pt
# - Checksum %u
# - Resolution
# - Horizontal %.1f dpi
# - Vertical %.1f dpi """
#
# message = self.print_header() + string_format % (
# self.pk_id,
# self.comment,
# self.design_font_size,
# self.checksum,
# self.horizontal_dpi,
# self.vertical_dpi,
# )
#
# print_card(message)
#
# Path: PyDvi/Kpathsea.py
# def kpsewhich(filename, file_format=None, options=None):
#
# """Wrapper around the :command:`kpsewhich` command, cf. kpsewhich(1).
#
# *file_format*
# used to specify the file format, see :command:`kpsewhich` help for the file format list.
#
# *options*
# additional option for :command:`kpsewhich`.
#
# Examples::
#
# >>> kpsewhich('cmr10', file_format='tfm')
# '/usr/share/texmf/fonts/tfm/public/cm/cmr10.tfm'
# """
#
# key = '{}-{}-{}'.format(filename, file_format, options)
# if key in _cache:
# return _cache[key]
#
# command = ['kpsewhich']
# if file_format is not None:
# command.append("--format='%s'" % (file_format))
# if options is not None:
# command.append(options)
# command.append(filename)
#
# shell_command = ' '.join(command)
# _module_logger.debug('Run shell command: ' + shell_command)
# pipe = subprocess.Popen(shell_command, shell=True, stdout=subprocess.PIPE)
# stdout = pipe.communicate()[0]
# _module_logger.debug('stdout:\n' + stdout)
# path = stdout.rstrip()
# path = path if path else None # Fixme: could raise an exception
#
# _cache[key] = path
# return path
#
# Path: PyDvi/Tools/Stream.py
# def to_fix_word(x):
#
# """ Convert *x* to a fix word.
#
# A fix word is a 32-bit representation of a binary fraction. A fix word is a signed quantity,
# with the two's complement of the entire word used to represent negation. Of the 32 bits in a
# fix word, exactly 12 are to the left of the binary point; thus, the largest fix word value is
# 2048 - 2**-20, and the smallest is -2048.
#
# ``fix word = x / 2**20``
# """
#
# return FIX_WORD_SCALE*x
. Output only the next line. | pk_file = kpsewhich(font_name, file_format='pk') |
Predict the next line for this snippet: <|code_start|># GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
####################################################################################################
####################################################################################################
#
# Audit
#
# - 11/10/2011 fabrice
#
####################################################################################################
####################################################################################################
####################################################################################################
####################################################################################################
parser = argparse.ArgumentParser(description='Test Font Map.')
parser.add_argument('font_map', metavar='FontMap',
help='TeX font map, e.g. pdftex')
args = parser.parse_args()
####################################################################################################
<|code_end|>
with the help of current file imports:
import argparse
import sys
from PyDvi.Font.FontMap import *
from PyDvi.Kpathsea import kpsewhich
and context from other files:
# Path: PyDvi/Kpathsea.py
# def kpsewhich(filename, file_format=None, options=None):
#
# """Wrapper around the :command:`kpsewhich` command, cf. kpsewhich(1).
#
# *file_format*
# used to specify the file format, see :command:`kpsewhich` help for the file format list.
#
# *options*
# additional option for :command:`kpsewhich`.
#
# Examples::
#
# >>> kpsewhich('cmr10', file_format='tfm')
# '/usr/share/texmf/fonts/tfm/public/cm/cmr10.tfm'
# """
#
# key = '{}-{}-{}'.format(filename, file_format, options)
# if key in _cache:
# return _cache[key]
#
# command = ['kpsewhich']
# if file_format is not None:
# command.append("--format='%s'" % (file_format))
# if options is not None:
# command.append(options)
# command.append(filename)
#
# shell_command = ' '.join(command)
# _module_logger.debug('Run shell command: ' + shell_command)
# pipe = subprocess.Popen(shell_command, shell=True, stdout=subprocess.PIPE)
# stdout = pipe.communicate()[0]
# _module_logger.debug('stdout:\n' + stdout)
# path = stdout.rstrip()
# path = path if path else None # Fixme: could raise an exception
#
# _cache[key] = path
# return path
, which may contain function names, class names, or code. Output only the next line. | font_map_file = kpsewhich(args.font_map, file_format='map') |
Continue the code snippet: <|code_start|> raise NameError("Freetype can't open file %s" % (self.filename))
if self.tfm is None:
self._find_afm()
encodings = [charmap.encoding for charmap in self._face.charmaps]
if freetype.FT_ENCODING_ADOBE_CUSTOM in encodings:
encoding = freetype.FT_ENCODING_ADOBE_CUSTOM
elif freetype.FT_ENCODING_ADOBE_STANDARD in encodings:
encoding = freetype.FT_ENCODING_ADOBE_STANDARD
else:
# encoding = freetype.FT_ENCODING_UNICODE
raise NameError("Font %s doesn't have an Adobe encoding" % (self.name))
self._face.select_charmap(encoding)
self._init_index()
# self._log_face_information()
# self._log_glyph_table()
self._font_size = {}
##############################################
def _find_afm(self):
# try:
# super(Type1Font, self)._find_tfm()
# except FontMetricNotFound:
<|code_end|>
. Use current file imports:
import logging
import unicodedata
import numpy as np
import freetype
from ..Kpathsea import kpsewhich
from .Font import Font, font_types, FontMetricNotFound
and context (classes, functions, or code) from other files:
# Path: PyDvi/Kpathsea.py
# def kpsewhich(filename, file_format=None, options=None):
#
# """Wrapper around the :command:`kpsewhich` command, cf. kpsewhich(1).
#
# *file_format*
# used to specify the file format, see :command:`kpsewhich` help for the file format list.
#
# *options*
# additional option for :command:`kpsewhich`.
#
# Examples::
#
# >>> kpsewhich('cmr10', file_format='tfm')
# '/usr/share/texmf/fonts/tfm/public/cm/cmr10.tfm'
# """
#
# key = '{}-{}-{}'.format(filename, file_format, options)
# if key in _cache:
# return _cache[key]
#
# command = ['kpsewhich']
# if file_format is not None:
# command.append("--format='%s'" % (file_format))
# if options is not None:
# command.append(options)
# command.append(filename)
#
# shell_command = ' '.join(command)
# _module_logger.debug('Run shell command: ' + shell_command)
# pipe = subprocess.Popen(shell_command, shell=True, stdout=subprocess.PIPE)
# stdout = pipe.communicate()[0]
# _module_logger.debug('stdout:\n' + stdout)
# path = stdout.rstrip()
# path = path if path else None # Fixme: could raise an exception
#
# _cache[key] = path
# return path
#
# Path: PyDvi/Font/Font.py
# def sort_font_class(*args):
# def __init__(self, font_manager, font_id, name):
# def __repr__(self):
# def _find_font(self, kpsewhich_options=None):
# def _find_tfm(self):
# def basename(self):
# def is_virtual(self):
# def print_header(self):
# def print_summary(self):
# class FontNotFound(NameError):
# class FontMetricNotFound(NameError):
# class Font(object):
. Output only the next line. | afm_file = kpsewhich(self.name, file_format='afm') |
Predict the next line after this snippet: <|code_start|>
__all__ = ['Type1Font']
####################################################################################################
####################################################################################################
####################################################################################################
_module_logger = logging.getLogger(__name__)
####################################################################################################
def from_64th_point(x):
return x/64.
def to_64th_point(x):
return x*64
####################################################################################################
def test_bit(flags, mask):
return flags & mask == 1
####################################################################################################
<|code_end|>
using the current file's imports:
import logging
import unicodedata
import numpy as np
import freetype
from ..Kpathsea import kpsewhich
from .Font import Font, font_types, FontMetricNotFound
and any relevant context from other files:
# Path: PyDvi/Kpathsea.py
# def kpsewhich(filename, file_format=None, options=None):
#
# """Wrapper around the :command:`kpsewhich` command, cf. kpsewhich(1).
#
# *file_format*
# used to specify the file format, see :command:`kpsewhich` help for the file format list.
#
# *options*
# additional option for :command:`kpsewhich`.
#
# Examples::
#
# >>> kpsewhich('cmr10', file_format='tfm')
# '/usr/share/texmf/fonts/tfm/public/cm/cmr10.tfm'
# """
#
# key = '{}-{}-{}'.format(filename, file_format, options)
# if key in _cache:
# return _cache[key]
#
# command = ['kpsewhich']
# if file_format is not None:
# command.append("--format='%s'" % (file_format))
# if options is not None:
# command.append(options)
# command.append(filename)
#
# shell_command = ' '.join(command)
# _module_logger.debug('Run shell command: ' + shell_command)
# pipe = subprocess.Popen(shell_command, shell=True, stdout=subprocess.PIPE)
# stdout = pipe.communicate()[0]
# _module_logger.debug('stdout:\n' + stdout)
# path = stdout.rstrip()
# path = path if path else None # Fixme: could raise an exception
#
# _cache[key] = path
# return path
#
# Path: PyDvi/Font/Font.py
# def sort_font_class(*args):
# def __init__(self, font_manager, font_id, name):
# def __repr__(self):
# def _find_font(self, kpsewhich_options=None):
# def _find_tfm(self):
# def basename(self):
# def is_virtual(self):
# def print_header(self):
# def print_summary(self):
# class FontNotFound(NameError):
# class FontMetricNotFound(NameError):
# class Font(object):
. Output only the next line. | class Type1Font(Font): |
Given the following code snippet before the placeholder: <|code_start|>
####################################################################################################
####################################################################################################
_module_logger = logging.getLogger(__name__)
####################################################################################################
def from_64th_point(x):
return x/64.
def to_64th_point(x):
return x*64
####################################################################################################
def test_bit(flags, mask):
return flags & mask == 1
####################################################################################################
class Type1Font(Font):
_logger = _module_logger.getChild('Type1Font')
<|code_end|>
, predict the next line using imports from the current file:
import logging
import unicodedata
import numpy as np
import freetype
from ..Kpathsea import kpsewhich
from .Font import Font, font_types, FontMetricNotFound
and context including class names, function names, and sometimes code from other files:
# Path: PyDvi/Kpathsea.py
# def kpsewhich(filename, file_format=None, options=None):
#
# """Wrapper around the :command:`kpsewhich` command, cf. kpsewhich(1).
#
# *file_format*
# used to specify the file format, see :command:`kpsewhich` help for the file format list.
#
# *options*
# additional option for :command:`kpsewhich`.
#
# Examples::
#
# >>> kpsewhich('cmr10', file_format='tfm')
# '/usr/share/texmf/fonts/tfm/public/cm/cmr10.tfm'
# """
#
# key = '{}-{}-{}'.format(filename, file_format, options)
# if key in _cache:
# return _cache[key]
#
# command = ['kpsewhich']
# if file_format is not None:
# command.append("--format='%s'" % (file_format))
# if options is not None:
# command.append(options)
# command.append(filename)
#
# shell_command = ' '.join(command)
# _module_logger.debug('Run shell command: ' + shell_command)
# pipe = subprocess.Popen(shell_command, shell=True, stdout=subprocess.PIPE)
# stdout = pipe.communicate()[0]
# _module_logger.debug('stdout:\n' + stdout)
# path = stdout.rstrip()
# path = path if path else None # Fixme: could raise an exception
#
# _cache[key] = path
# return path
#
# Path: PyDvi/Font/Font.py
# def sort_font_class(*args):
# def __init__(self, font_manager, font_id, name):
# def __repr__(self):
# def _find_font(self, kpsewhich_options=None):
# def _find_tfm(self):
# def basename(self):
# def is_virtual(self):
# def print_header(self):
# def print_summary(self):
# class FontNotFound(NameError):
# class FontMetricNotFound(NameError):
# class Font(object):
. Output only the next line. | font_type = font_types.Type1 |
Given the code snippet: <|code_start|>#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
####################################################################################################
####################################################################################################
####################################################################################################
####################################################################################################
logging.basicConfig(level=logging.DEBUG)
####################################################################################################
parser = argparse.ArgumentParser(description='Test Virtual Font.')
parser.add_argument('font', metavar='VirtualFont',
help='Font name, e.g. phvr7t')
args = parser.parse_args()
####################################################################################################
vf_file = kpsewhich(args.font, file_format='vf')
if vf_file is None:
print 'VF file %s not found' % (args.font)
sys.exit(1)
<|code_end|>
, generate the next line using the imports in this file:
import argparse
import logging
import sys
from PyDvi.Font.VirtualFont import VirtualFont
from PyDvi.Kpathsea import kpsewhich
and context (functions, classes, or occasionally code) from other files:
# Path: PyDvi/Font/VirtualFont.py
# class VirtualFont(Font):
#
# """This class implements the virtual font type in the font manager. """
#
# font_type = font_types.Vf
# font_type_string = 'TeX Virtual Font'
# extension = 'vf'
#
# ##############################################
#
# def __init__(self, font_manager, font_id, name):
#
# super(VirtualFont, self).__init__(font_manager, font_id, name)
#
# self.dvi_fonts = {}
# self.first_font = None
# self.fonts = {}
# self.font_id_map = {}
# self._characters = {}
# VirtualFontParser.parse(self)
#
# ##############################################
#
# def __getitem__(self, char_code):
#
# # """ Return the :class:`PyDvi.PkGlyph.PkGlyph` instance for the char code *char_code*. """
#
# return self._characters[char_code]
#
# ##############################################
#
# def __len__(self):
#
# """ Return the number of characters in the font. """
#
# return len(self._characters)
#
# ##############################################
#
# def _set_preambule_data(self,
# vf_id,
# comment,
# design_font_size,
# checksum):
#
# """ Set the preambule data from the Virtual Font Parser. """
#
# self.vf_id = vf_id
# self.comment = comment
# self.design_font_size = design_font_size
# self.checksum = checksum
#
# ##############################################
#
# def register_font(self, font):
#
# """ Register a :class:`DviFont` instance. """
#
# if font.id not in self.dvi_fonts:
# self.dvi_fonts[font.id] = font
# if self.first_font is None:
# self.first_font = font.id
# # else:
# # print 'Font ID %u already registered' % (font.id)
#
# ##############################################
#
# def register_character(self, character):
#
# self._characters[character.char_code] = character
#
# ##############################################
#
# def print_summary(self):
#
# string_format = """
# Preambule
# - Vf ID %u
# - Comment '%s'
# - Design size %.1f pt
# - Checksum %u
# """
#
# message = self.print_header() + string_format % (
# self.vf_id,
# self.comment,
# self.design_font_size,
# self.checksum,
# )
#
# print_card(message)
#
# ##############################################
#
# def load_dvi_fonts(self):
#
# self.fonts = {font_id:self.font_manager[dvi_font.name]
# for font_id, dvi_font in self.dvi_fonts.iteritems()}
#
# ##############################################
#
# def update_font_id_map(self):
#
# self.font_id_map = {font_id:font.global_id
# for font_id, font in self.fonts.iteritems()}
#
# Path: PyDvi/Kpathsea.py
# def kpsewhich(filename, file_format=None, options=None):
#
# """Wrapper around the :command:`kpsewhich` command, cf. kpsewhich(1).
#
# *file_format*
# used to specify the file format, see :command:`kpsewhich` help for the file format list.
#
# *options*
# additional option for :command:`kpsewhich`.
#
# Examples::
#
# >>> kpsewhich('cmr10', file_format='tfm')
# '/usr/share/texmf/fonts/tfm/public/cm/cmr10.tfm'
# """
#
# key = '{}-{}-{}'.format(filename, file_format, options)
# if key in _cache:
# return _cache[key]
#
# command = ['kpsewhich']
# if file_format is not None:
# command.append("--format='%s'" % (file_format))
# if options is not None:
# command.append(options)
# command.append(filename)
#
# shell_command = ' '.join(command)
# _module_logger.debug('Run shell command: ' + shell_command)
# pipe = subprocess.Popen(shell_command, shell=True, stdout=subprocess.PIPE)
# stdout = pipe.communicate()[0]
# _module_logger.debug('stdout:\n' + stdout)
# path = stdout.rstrip()
# path = path if path else None # Fixme: could raise an exception
#
# _cache[key] = path
# return path
. Output only the next line. | vf_font = VirtualFont(font_manager=None, font_id=0, name=args.font) |
Next line prediction: <|code_start|>#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
####################################################################################################
####################################################################################################
####################################################################################################
####################################################################################################
logging.basicConfig(level=logging.DEBUG)
####################################################################################################
parser = argparse.ArgumentParser(description='Test Virtual Font.')
parser.add_argument('font', metavar='VirtualFont',
help='Font name, e.g. phvr7t')
args = parser.parse_args()
####################################################################################################
<|code_end|>
. Use current file imports:
(import argparse
import logging
import sys
from PyDvi.Font.VirtualFont import VirtualFont
from PyDvi.Kpathsea import kpsewhich)
and context including class names, function names, or small code snippets from other files:
# Path: PyDvi/Font/VirtualFont.py
# class VirtualFont(Font):
#
# """This class implements the virtual font type in the font manager. """
#
# font_type = font_types.Vf
# font_type_string = 'TeX Virtual Font'
# extension = 'vf'
#
# ##############################################
#
# def __init__(self, font_manager, font_id, name):
#
# super(VirtualFont, self).__init__(font_manager, font_id, name)
#
# self.dvi_fonts = {}
# self.first_font = None
# self.fonts = {}
# self.font_id_map = {}
# self._characters = {}
# VirtualFontParser.parse(self)
#
# ##############################################
#
# def __getitem__(self, char_code):
#
# # """ Return the :class:`PyDvi.PkGlyph.PkGlyph` instance for the char code *char_code*. """
#
# return self._characters[char_code]
#
# ##############################################
#
# def __len__(self):
#
# """ Return the number of characters in the font. """
#
# return len(self._characters)
#
# ##############################################
#
# def _set_preambule_data(self,
# vf_id,
# comment,
# design_font_size,
# checksum):
#
# """ Set the preambule data from the Virtual Font Parser. """
#
# self.vf_id = vf_id
# self.comment = comment
# self.design_font_size = design_font_size
# self.checksum = checksum
#
# ##############################################
#
# def register_font(self, font):
#
# """ Register a :class:`DviFont` instance. """
#
# if font.id not in self.dvi_fonts:
# self.dvi_fonts[font.id] = font
# if self.first_font is None:
# self.first_font = font.id
# # else:
# # print 'Font ID %u already registered' % (font.id)
#
# ##############################################
#
# def register_character(self, character):
#
# self._characters[character.char_code] = character
#
# ##############################################
#
# def print_summary(self):
#
# string_format = """
# Preambule
# - Vf ID %u
# - Comment '%s'
# - Design size %.1f pt
# - Checksum %u
# """
#
# message = self.print_header() + string_format % (
# self.vf_id,
# self.comment,
# self.design_font_size,
# self.checksum,
# )
#
# print_card(message)
#
# ##############################################
#
# def load_dvi_fonts(self):
#
# self.fonts = {font_id:self.font_manager[dvi_font.name]
# for font_id, dvi_font in self.dvi_fonts.iteritems()}
#
# ##############################################
#
# def update_font_id_map(self):
#
# self.font_id_map = {font_id:font.global_id
# for font_id, font in self.fonts.iteritems()}
#
# Path: PyDvi/Kpathsea.py
# def kpsewhich(filename, file_format=None, options=None):
#
# """Wrapper around the :command:`kpsewhich` command, cf. kpsewhich(1).
#
# *file_format*
# used to specify the file format, see :command:`kpsewhich` help for the file format list.
#
# *options*
# additional option for :command:`kpsewhich`.
#
# Examples::
#
# >>> kpsewhich('cmr10', file_format='tfm')
# '/usr/share/texmf/fonts/tfm/public/cm/cmr10.tfm'
# """
#
# key = '{}-{}-{}'.format(filename, file_format, options)
# if key in _cache:
# return _cache[key]
#
# command = ['kpsewhich']
# if file_format is not None:
# command.append("--format='%s'" % (file_format))
# if options is not None:
# command.append(options)
# command.append(filename)
#
# shell_command = ' '.join(command)
# _module_logger.debug('Run shell command: ' + shell_command)
# pipe = subprocess.Popen(shell_command, shell=True, stdout=subprocess.PIPE)
# stdout = pipe.communicate()[0]
# _module_logger.debug('stdout:\n' + stdout)
# path = stdout.rstrip()
# path = path if path else None # Fixme: could raise an exception
#
# _cache[key] = path
# return path
. Output only the next line. | vf_file = kpsewhich(args.font, file_format='vf') |
Given snippet: <|code_start|>
""" Is the interval included in i1?
"""
# print '(%f <= %f and %f <= %f)' % (i2.inf, i1.inf, i1.sup, i2.sup)
return i2.inf <= i1.inf and i1.sup <= i2.sup
##############################################
# Fixme: length -> size ?
def length(self):
""" Return sup - inf
"""
return self.sup - self.inf
##############################################
def zero_length(self):
""" Return sup == inf
"""
return self.sup == self.inf
##############################################
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from PyDvi.Tools.FuncTools import middle
and context:
# Path: PyDvi/Tools/FuncTools.py
# def middle(a, b):
# return .5 * (a + b)
which might include code, classes, or functions. Output only the next line. | def middle(self): |
Given snippet: <|code_start|>
for word in line.split('/'):
word = word.strip()
if word:
self._glyph_indexes.append(word)
##############################################
def to_name(self, i):
""" Return the symbolic name corresponding to the glyph index *i*. """
return self._glyph_indexes[i]
##############################################
def to_index(self, name):
""" Return the glyph index corresponding to the symbolic name. """
return self._glyph_names[name]
##############################################
def print_summary(self):
message = 'Encoding %s:\n\n' % (self.name)
for i in xrange(len(self)):
message += '| %3i | %s\n' % (i, self.to_name(i))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from ..Tools.Logging import print_card
from ..Tools.TexCommentedFile import TexCommentedFile
and context:
# Path: PyDvi/Tools/Logging.py
# def print_card(text, **kwargs):
#
# """ Print the string *text* formated by :meth:`format_card`. The remaining keyword arguments
# *kwargs* are passed to :meth:`format_card`.
# """
#
# print format_card(text, **kwargs)
#
# Path: PyDvi/Tools/TexCommentedFile.py
# class TexCommentedFile(file):
#
# """ This class permits to iterate over lines of a text file and to skip commented line by '%'.
# """
#
# ##############################################
#
# def __init__(self, filename):
#
# super(TexCommentedFile, self).__init__(filename, mode='r')
#
# ##############################################
#
# def __iter__(self):
#
# while True:
# line = self.readline()
# if not line:
# raise StopIteration()
# comment_start_index = line.find('%')
# if comment_start_index != -1:
# line = line[:comment_start_index]
# line = line.strip()
# if line:
# yield line
#
# ##############################################
#
# def concatenate_lines(self):
#
# """ Concatenate the lines and return the corresponding string. """
#
# return ''.join(self)
which might include code, classes, or functions. Output only the next line. | print_card(message) |
Predict the next line for this snippet: <|code_start|>
####################################################################################################
__all__ = ['Encoding']
####################################################################################################
####################################################################################################
class Encoding(object):
"""
Parse an encoding file and store the association between the index and the glyph's name.
Public attributes are:
``name``
"""
##############################################
def __init__(self, filename):
self.name = None
self._glyph_indexes = [] # Map glyph index to glyph name
self._glyph_names = {} # Map glyph name to glyph index
try:
<|code_end|>
with the help of current file imports:
from ..Tools.Logging import print_card
from ..Tools.TexCommentedFile import TexCommentedFile
and context from other files:
# Path: PyDvi/Tools/Logging.py
# def print_card(text, **kwargs):
#
# """ Print the string *text* formated by :meth:`format_card`. The remaining keyword arguments
# *kwargs* are passed to :meth:`format_card`.
# """
#
# print format_card(text, **kwargs)
#
# Path: PyDvi/Tools/TexCommentedFile.py
# class TexCommentedFile(file):
#
# """ This class permits to iterate over lines of a text file and to skip commented line by '%'.
# """
#
# ##############################################
#
# def __init__(self, filename):
#
# super(TexCommentedFile, self).__init__(filename, mode='r')
#
# ##############################################
#
# def __iter__(self):
#
# while True:
# line = self.readline()
# if not line:
# raise StopIteration()
# comment_start_index = line.find('%')
# if comment_start_index != -1:
# line = line[:comment_start_index]
# line = line.strip()
# if line:
# yield line
#
# ##############################################
#
# def concatenate_lines(self):
#
# """ Concatenate the lines and return the corresponding string. """
#
# return ''.join(self)
, which may contain function names, class names, or code. Output only the next line. | with TexCommentedFile(filename) as encoding_file: |
Based on the snippet: <|code_start|># Audit
#
# - 13/11/2011 Fabrice
# x
#
####################################################################################################
####################################################################################################
####################################################################################################
####################################################################################################
parser = argparse.ArgumentParser(description='Test Encoding.')
parser.add_argument('encoding', metavar='Encoding',
help='TeX encoding, e.g. cork')
args = parser.parse_args()
####################################################################################################
encoding_file = kpsewhich(args.encoding, file_format='enc files')
if encoding_file is None:
print 'Encoding %s not found' % (args.encoding)
sys.exit(1)
print 'Read %s encoding file' % (encoding_file)
<|code_end|>
, predict the immediate next line with the help of imports:
import argparse
import sys
from PyDvi.Font.Encoding import Encoding
from PyDvi.Kpathsea import kpsewhich
and context (classes, functions, sometimes code) from other files:
# Path: PyDvi/Font/Encoding.py
# class Encoding(object):
#
# """
# Parse an encoding file and store the association between the index and the glyph's name.
#
# Public attributes are:
#
# ``name``
# """
#
# ##############################################
#
# def __init__(self, filename):
#
# self.name = None
#
# self._glyph_indexes = [] # Map glyph index to glyph name
# self._glyph_names = {} # Map glyph name to glyph index
#
# try:
# with TexCommentedFile(filename) as encoding_file:
# content = encoding_file.concatenate_lines()
# open_braket_index = content.index('[')
# close_braket_index = content.index(']')
# self._parse_name(content[:open_braket_index])
# self._parse_glyph_names(content[open_braket_index+1:close_braket_index])
# except:
# raise NameError('Bad encoding file')
#
# # Init glyph_names dict
# for i in xrange(len(self._glyph_indexes)):
# self._glyph_names[self._glyph_indexes[i]] = i
#
# ##############################################
#
# def __len__(self):
#
# """ Return the number of glyphes. """
#
# return len(self._glyph_indexes)
#
# ##############################################
#
# def __getitem__(self, index):
#
# """ If *index* is a glyph index then return the corresponding symbolic name else try to
# return the glyph index corresponding to the symbolic name *index*.
# """
#
# try:
# return self.to_name(int(index))
# except ValueError:
# return self.to_index(index)
#
# ##############################################
#
# def _parse_name(self, line):
#
# """ Find the encoding name at the left of the line, as '/CorkEncoding'. """
#
# # try
# name_start_index = line.index('/')
# self.name = line[name_start_index +1:].strip()
#
# ##############################################
#
# def _parse_glyph_names(self, line):
#
# """ Find glyph names in *line*, as '/grave /acute /circumflex ...'. """
#
# for word in line.split('/'):
# word = word.strip()
# if word:
# self._glyph_indexes.append(word)
#
# ##############################################
#
# def to_name(self, i):
#
# """ Return the symbolic name corresponding to the glyph index *i*. """
#
# return self._glyph_indexes[i]
#
# ##############################################
#
# def to_index(self, name):
#
# """ Return the glyph index corresponding to the symbolic name. """
#
# return self._glyph_names[name]
#
# ##############################################
#
# def print_summary(self):
#
# message = 'Encoding %s:\n\n' % (self.name)
# for i in xrange(len(self)):
# message += '| %3i | %s\n' % (i, self.to_name(i))
#
# print_card(message)
#
# Path: PyDvi/Kpathsea.py
# def kpsewhich(filename, file_format=None, options=None):
#
# """Wrapper around the :command:`kpsewhich` command, cf. kpsewhich(1).
#
# *file_format*
# used to specify the file format, see :command:`kpsewhich` help for the file format list.
#
# *options*
# additional option for :command:`kpsewhich`.
#
# Examples::
#
# >>> kpsewhich('cmr10', file_format='tfm')
# '/usr/share/texmf/fonts/tfm/public/cm/cmr10.tfm'
# """
#
# key = '{}-{}-{}'.format(filename, file_format, options)
# if key in _cache:
# return _cache[key]
#
# command = ['kpsewhich']
# if file_format is not None:
# command.append("--format='%s'" % (file_format))
# if options is not None:
# command.append(options)
# command.append(filename)
#
# shell_command = ' '.join(command)
# _module_logger.debug('Run shell command: ' + shell_command)
# pipe = subprocess.Popen(shell_command, shell=True, stdout=subprocess.PIPE)
# stdout = pipe.communicate()[0]
# _module_logger.debug('stdout:\n' + stdout)
# path = stdout.rstrip()
# path = path if path else None # Fixme: could raise an exception
#
# _cache[key] = path
# return path
. Output only the next line. | encoding = Encoding(encoding_file) |
Predict the next line after this snippet: <|code_start|>#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
####################################################################################################
####################################################################################################
#
# Audit
#
# - 13/11/2011 Fabrice
# x
#
####################################################################################################
####################################################################################################
####################################################################################################
####################################################################################################
parser = argparse.ArgumentParser(description='Test Encoding.')
parser.add_argument('encoding', metavar='Encoding',
help='TeX encoding, e.g. cork')
args = parser.parse_args()
####################################################################################################
<|code_end|>
using the current file's imports:
import argparse
import sys
from PyDvi.Font.Encoding import Encoding
from PyDvi.Kpathsea import kpsewhich
and any relevant context from other files:
# Path: PyDvi/Font/Encoding.py
# class Encoding(object):
#
# """
# Parse an encoding file and store the association between the index and the glyph's name.
#
# Public attributes are:
#
# ``name``
# """
#
# ##############################################
#
# def __init__(self, filename):
#
# self.name = None
#
# self._glyph_indexes = [] # Map glyph index to glyph name
# self._glyph_names = {} # Map glyph name to glyph index
#
# try:
# with TexCommentedFile(filename) as encoding_file:
# content = encoding_file.concatenate_lines()
# open_braket_index = content.index('[')
# close_braket_index = content.index(']')
# self._parse_name(content[:open_braket_index])
# self._parse_glyph_names(content[open_braket_index+1:close_braket_index])
# except:
# raise NameError('Bad encoding file')
#
# # Init glyph_names dict
# for i in xrange(len(self._glyph_indexes)):
# self._glyph_names[self._glyph_indexes[i]] = i
#
# ##############################################
#
# def __len__(self):
#
# """ Return the number of glyphes. """
#
# return len(self._glyph_indexes)
#
# ##############################################
#
# def __getitem__(self, index):
#
# """ If *index* is a glyph index then return the corresponding symbolic name else try to
# return the glyph index corresponding to the symbolic name *index*.
# """
#
# try:
# return self.to_name(int(index))
# except ValueError:
# return self.to_index(index)
#
# ##############################################
#
# def _parse_name(self, line):
#
# """ Find the encoding name at the left of the line, as '/CorkEncoding'. """
#
# # try
# name_start_index = line.index('/')
# self.name = line[name_start_index +1:].strip()
#
# ##############################################
#
# def _parse_glyph_names(self, line):
#
# """ Find glyph names in *line*, as '/grave /acute /circumflex ...'. """
#
# for word in line.split('/'):
# word = word.strip()
# if word:
# self._glyph_indexes.append(word)
#
# ##############################################
#
# def to_name(self, i):
#
# """ Return the symbolic name corresponding to the glyph index *i*. """
#
# return self._glyph_indexes[i]
#
# ##############################################
#
# def to_index(self, name):
#
# """ Return the glyph index corresponding to the symbolic name. """
#
# return self._glyph_names[name]
#
# ##############################################
#
# def print_summary(self):
#
# message = 'Encoding %s:\n\n' % (self.name)
# for i in xrange(len(self)):
# message += '| %3i | %s\n' % (i, self.to_name(i))
#
# print_card(message)
#
# Path: PyDvi/Kpathsea.py
# def kpsewhich(filename, file_format=None, options=None):
#
# """Wrapper around the :command:`kpsewhich` command, cf. kpsewhich(1).
#
# *file_format*
# used to specify the file format, see :command:`kpsewhich` help for the file format list.
#
# *options*
# additional option for :command:`kpsewhich`.
#
# Examples::
#
# >>> kpsewhich('cmr10', file_format='tfm')
# '/usr/share/texmf/fonts/tfm/public/cm/cmr10.tfm'
# """
#
# key = '{}-{}-{}'.format(filename, file_format, options)
# if key in _cache:
# return _cache[key]
#
# command = ['kpsewhich']
# if file_format is not None:
# command.append("--format='%s'" % (file_format))
# if options is not None:
# command.append(options)
# command.append(filename)
#
# shell_command = ' '.join(command)
# _module_logger.debug('Run shell command: ' + shell_command)
# pipe = subprocess.Popen(shell_command, shell=True, stdout=subprocess.PIPE)
# stdout = pipe.communicate()[0]
# _module_logger.debug('stdout:\n' + stdout)
# path = stdout.rstrip()
# path = path if path else None # Fixme: could raise an exception
#
# _cache[key] = path
# return path
. Output only the next line. | encoding_file = kpsewhich(args.encoding, file_format='enc files') |
Using the snippet: <|code_start|>
####################################################################################################
####################################################################################################
platform_enum = EnumFactory('PlatformEnum', ('linux', 'windows', 'macosx'))
####################################################################################################
class Platform(object):
##############################################
def __init__(self):
self.python_version = platform.python_version()
self.qt_version = QtCore.QT_VERSION_STR
self.pyqt_version = QtCore.PYQT_VERSION_STR
self.os = self._get_os()
self.node = platform.node()
self.distribution = ' '.join(platform.dist())
self.machine = platform.machine()
self.architecture = platform.architecture()[0]
# CPU
self.cpu = self._get_cpu()
self.number_of_cores = self._get_number_of_cores()
self.cpu_khz = self._get_cpu_khz()
<|code_end|>
, determine the next line of code. You have imports:
import os
import platform
import sys
import OpenGL.GL as GL
from PyQt4 import QtCore, QtGui
from PyDvi.Tools.EnumFactory import EnumFactory
from .Math import rint
and context (class names, function names, or code) available:
# Path: PyDvi/Tools/EnumFactory.py
# def EnumFactory(cls_name, constant_names):
#
# """ Return an :class:`EnumMetaClass` instance, where *cls_name* is the class name and
# *constant_names* is an iterable of constant's names.
# """
#
# dict_ = {}
# dict_['_size'] = len(constant_names)
# for index, name in enumerate(constant_names):
# dict_[str(name)] = index
#
# return EnumMetaClass(cls_name, (), dict_)
#
# Path: PyDviGui/Tools/Math.py
# def rint(f):
# return int(round(f))
. Output only the next line. | self.cpu_mhz = rint(self._get_cpu_khz()/float(1000)) |
Using the snippet: <|code_start|> for y in xrange(self.height):
line = ''
for x in xrange(self.width):
if glyph_bitmap[y,x]:
line += 'x'
else:
line += ' '
print '%3u |%s|' % (y, line)
print axis
print_label_axis()
##############################################
def print_summary(self):
string_format = ''' Char %u
- TFM width: %.3f * design size
%.1f pt
%.1f mm
- dm: %3u px
- dx: %3u px
- dy: %3u px
- Height: %3u px
- Width: %3u px
- Horizontal Offset: %3u px
- Vertical Offset: %3u px
'''
width = self.get_scaled_width(self.pk_font.design_font_size)
<|code_end|>
, determine the next line of code. You have imports:
import math
import numpy as np
from ..TeXUnit import *
from ..Tools.Logging import print_card
and context (class names, function names, or code) available:
# Path: PyDvi/Tools/Logging.py
# def print_card(text, **kwargs):
#
# """ Print the string *text* formated by :meth:`format_card`. The remaining keyword arguments
# *kwargs* are passed to :meth:`format_card`.
# """
#
# print format_card(text, **kwargs)
. Output only the next line. | print_card(string_format % ( |
Next line prediction: <|code_start|> if self.first_font is None:
self.first_font = font.id
# else:
# print 'Font ID %u already registered' % (font.id)
##############################################
def register_character(self, character):
self._characters[character.char_code] = character
##############################################
def print_summary(self):
string_format = """
Preambule
- Vf ID %u
- Comment '%s'
- Design size %.1f pt
- Checksum %u
"""
message = self.print_header() + string_format % (
self.vf_id,
self.comment,
self.design_font_size,
self.checksum,
)
<|code_end|>
. Use current file imports:
(from ..Tools.Logging import print_card
from .Font import Font, font_types
from .VirtualFontParser import VirtualFontParser)
and context including class names, function names, or small code snippets from other files:
# Path: PyDvi/Tools/Logging.py
# def print_card(text, **kwargs):
#
# """ Print the string *text* formated by :meth:`format_card`. The remaining keyword arguments
# *kwargs* are passed to :meth:`format_card`.
# """
#
# print format_card(text, **kwargs)
#
# Path: PyDvi/Font/Font.py
# def sort_font_class(*args):
# def __init__(self, font_manager, font_id, name):
# def __repr__(self):
# def _find_font(self, kpsewhich_options=None):
# def _find_tfm(self):
# def basename(self):
# def is_virtual(self):
# def print_header(self):
# def print_summary(self):
# class FontNotFound(NameError):
# class FontMetricNotFound(NameError):
# class Font(object):
#
# Path: PyDvi/Font/VirtualFontParser.py
# class VirtualFontParser(object):
#
# _logger = _module_logger.getChild('VirtualFontParser')
#
# opcode_parser_set = OpcodeParserSet(opcode_definitions)
#
# ##############################################
#
# @staticmethod
# def parse(virtual_font):
#
# VirtualFontParser(virtual_font)
#
# ##############################################
#
# def __init__(self, virtual_font):
#
# self.virtual_font = virtual_font
#
# self.stream = FileStream(virtual_font.filename)
#
# self._process_preambule()
# self._process_file()
#
# ##############################################
#
# def _process_preambule(self):
#
# """ Process the preamble. """
#
# stream = self.stream
#
# stream.seek(0)
#
# if stream.read_unsigned_byte1() != vf_opcodes.PRE:
# raise NameError("Virtual font file don't start by PRE opcode")
#
# file_id = stream.read_unsigned_byte1()
# if file_id != VF_ID:
# raise NameError("Unknown file ID")
#
# comment = stream.read(stream.read_unsigned_byte1())
# checksum = stream.read_signed_byte4()
# design_font_size = stream.read_fix_word()
#
# # string_template = '''
# # Preambule
# # - Vf ID %u
# # - Comment '%s'
# # - Design size %.1f pt
# # - Checksum %u
# # '''
# # print string_template % (
# # file_id,
# # comment,
# # design_font_size,
# # checksum,
# # )
#
#
# self.virtual_font._set_preambule_data(file_id, comment, design_font_size, checksum)
#
# ##############################################
#
# def _process_file(self):
#
# """ Process the characters. """
#
# stream = self.stream
#
# # Fixme: to incorporate pre, check here pre is the first code
#
# while True:
# byte = stream.read_unsigned_byte1()
# if byte == vf_opcodes.POST:
# break
# else:
# # Fixme: self.opcode_parsers[byte]()
# opcode_parser = self.opcode_parser_set[byte]
# opcode_parser.read_parameters(self) # Fixme: return where
. Output only the next line. | print_card(message) |
Next line prediction: <|code_start|># but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
####################################################################################################
####################################################################################################
__all__ = ['VirtualFont']
####################################################################################################
####################################################################################################
class VirtualCharacter(object):
##############################################
def __init__(self, char_code, tfm, dvi):
self.char_code = char_code
self.tfm = tfm
self.dvi = dvi
####################################################################################################
<|code_end|>
. Use current file imports:
(from ..Tools.Logging import print_card
from .Font import Font, font_types
from .VirtualFontParser import VirtualFontParser)
and context including class names, function names, or small code snippets from other files:
# Path: PyDvi/Tools/Logging.py
# def print_card(text, **kwargs):
#
# """ Print the string *text* formated by :meth:`format_card`. The remaining keyword arguments
# *kwargs* are passed to :meth:`format_card`.
# """
#
# print format_card(text, **kwargs)
#
# Path: PyDvi/Font/Font.py
# def sort_font_class(*args):
# def __init__(self, font_manager, font_id, name):
# def __repr__(self):
# def _find_font(self, kpsewhich_options=None):
# def _find_tfm(self):
# def basename(self):
# def is_virtual(self):
# def print_header(self):
# def print_summary(self):
# class FontNotFound(NameError):
# class FontMetricNotFound(NameError):
# class Font(object):
#
# Path: PyDvi/Font/VirtualFontParser.py
# class VirtualFontParser(object):
#
# _logger = _module_logger.getChild('VirtualFontParser')
#
# opcode_parser_set = OpcodeParserSet(opcode_definitions)
#
# ##############################################
#
# @staticmethod
# def parse(virtual_font):
#
# VirtualFontParser(virtual_font)
#
# ##############################################
#
# def __init__(self, virtual_font):
#
# self.virtual_font = virtual_font
#
# self.stream = FileStream(virtual_font.filename)
#
# self._process_preambule()
# self._process_file()
#
# ##############################################
#
# def _process_preambule(self):
#
# """ Process the preamble. """
#
# stream = self.stream
#
# stream.seek(0)
#
# if stream.read_unsigned_byte1() != vf_opcodes.PRE:
# raise NameError("Virtual font file don't start by PRE opcode")
#
# file_id = stream.read_unsigned_byte1()
# if file_id != VF_ID:
# raise NameError("Unknown file ID")
#
# comment = stream.read(stream.read_unsigned_byte1())
# checksum = stream.read_signed_byte4()
# design_font_size = stream.read_fix_word()
#
# # string_template = '''
# # Preambule
# # - Vf ID %u
# # - Comment '%s'
# # - Design size %.1f pt
# # - Checksum %u
# # '''
# # print string_template % (
# # file_id,
# # comment,
# # design_font_size,
# # checksum,
# # )
#
#
# self.virtual_font._set_preambule_data(file_id, comment, design_font_size, checksum)
#
# ##############################################
#
# def _process_file(self):
#
# """ Process the characters. """
#
# stream = self.stream
#
# # Fixme: to incorporate pre, check here pre is the first code
#
# while True:
# byte = stream.read_unsigned_byte1()
# if byte == vf_opcodes.POST:
# break
# else:
# # Fixme: self.opcode_parsers[byte]()
# opcode_parser = self.opcode_parser_set[byte]
# opcode_parser.read_parameters(self) # Fixme: return where
. Output only the next line. | class VirtualFont(Font): |
Given the code snippet: <|code_start|># You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
####################################################################################################
####################################################################################################
__all__ = ['VirtualFont']
####################################################################################################
####################################################################################################
class VirtualCharacter(object):
##############################################
def __init__(self, char_code, tfm, dvi):
self.char_code = char_code
self.tfm = tfm
self.dvi = dvi
####################################################################################################
class VirtualFont(Font):
"""This class implements the virtual font type in the font manager. """
<|code_end|>
, generate the next line using the imports in this file:
from ..Tools.Logging import print_card
from .Font import Font, font_types
from .VirtualFontParser import VirtualFontParser
and context (functions, classes, or occasionally code) from other files:
# Path: PyDvi/Tools/Logging.py
# def print_card(text, **kwargs):
#
# """ Print the string *text* formated by :meth:`format_card`. The remaining keyword arguments
# *kwargs* are passed to :meth:`format_card`.
# """
#
# print format_card(text, **kwargs)
#
# Path: PyDvi/Font/Font.py
# def sort_font_class(*args):
# def __init__(self, font_manager, font_id, name):
# def __repr__(self):
# def _find_font(self, kpsewhich_options=None):
# def _find_tfm(self):
# def basename(self):
# def is_virtual(self):
# def print_header(self):
# def print_summary(self):
# class FontNotFound(NameError):
# class FontMetricNotFound(NameError):
# class Font(object):
#
# Path: PyDvi/Font/VirtualFontParser.py
# class VirtualFontParser(object):
#
# _logger = _module_logger.getChild('VirtualFontParser')
#
# opcode_parser_set = OpcodeParserSet(opcode_definitions)
#
# ##############################################
#
# @staticmethod
# def parse(virtual_font):
#
# VirtualFontParser(virtual_font)
#
# ##############################################
#
# def __init__(self, virtual_font):
#
# self.virtual_font = virtual_font
#
# self.stream = FileStream(virtual_font.filename)
#
# self._process_preambule()
# self._process_file()
#
# ##############################################
#
# def _process_preambule(self):
#
# """ Process the preamble. """
#
# stream = self.stream
#
# stream.seek(0)
#
# if stream.read_unsigned_byte1() != vf_opcodes.PRE:
# raise NameError("Virtual font file don't start by PRE opcode")
#
# file_id = stream.read_unsigned_byte1()
# if file_id != VF_ID:
# raise NameError("Unknown file ID")
#
# comment = stream.read(stream.read_unsigned_byte1())
# checksum = stream.read_signed_byte4()
# design_font_size = stream.read_fix_word()
#
# # string_template = '''
# # Preambule
# # - Vf ID %u
# # - Comment '%s'
# # - Design size %.1f pt
# # - Checksum %u
# # '''
# # print string_template % (
# # file_id,
# # comment,
# # design_font_size,
# # checksum,
# # )
#
#
# self.virtual_font._set_preambule_data(file_id, comment, design_font_size, checksum)
#
# ##############################################
#
# def _process_file(self):
#
# """ Process the characters. """
#
# stream = self.stream
#
# # Fixme: to incorporate pre, check here pre is the first code
#
# while True:
# byte = stream.read_unsigned_byte1()
# if byte == vf_opcodes.POST:
# break
# else:
# # Fixme: self.opcode_parsers[byte]()
# opcode_parser = self.opcode_parser_set[byte]
# opcode_parser.read_parameters(self) # Fixme: return where
. Output only the next line. | font_type = font_types.Vf |
Continue the code snippet: <|code_start|>
##############################################
def __init__(self, char_code, tfm, dvi):
self.char_code = char_code
self.tfm = tfm
self.dvi = dvi
####################################################################################################
class VirtualFont(Font):
"""This class implements the virtual font type in the font manager. """
font_type = font_types.Vf
font_type_string = 'TeX Virtual Font'
extension = 'vf'
##############################################
def __init__(self, font_manager, font_id, name):
super(VirtualFont, self).__init__(font_manager, font_id, name)
self.dvi_fonts = {}
self.first_font = None
self.fonts = {}
self.font_id_map = {}
self._characters = {}
<|code_end|>
. Use current file imports:
from ..Tools.Logging import print_card
from .Font import Font, font_types
from .VirtualFontParser import VirtualFontParser
and context (classes, functions, or code) from other files:
# Path: PyDvi/Tools/Logging.py
# def print_card(text, **kwargs):
#
# """ Print the string *text* formated by :meth:`format_card`. The remaining keyword arguments
# *kwargs* are passed to :meth:`format_card`.
# """
#
# print format_card(text, **kwargs)
#
# Path: PyDvi/Font/Font.py
# def sort_font_class(*args):
# def __init__(self, font_manager, font_id, name):
# def __repr__(self):
# def _find_font(self, kpsewhich_options=None):
# def _find_tfm(self):
# def basename(self):
# def is_virtual(self):
# def print_header(self):
# def print_summary(self):
# class FontNotFound(NameError):
# class FontMetricNotFound(NameError):
# class Font(object):
#
# Path: PyDvi/Font/VirtualFontParser.py
# class VirtualFontParser(object):
#
# _logger = _module_logger.getChild('VirtualFontParser')
#
# opcode_parser_set = OpcodeParserSet(opcode_definitions)
#
# ##############################################
#
# @staticmethod
# def parse(virtual_font):
#
# VirtualFontParser(virtual_font)
#
# ##############################################
#
# def __init__(self, virtual_font):
#
# self.virtual_font = virtual_font
#
# self.stream = FileStream(virtual_font.filename)
#
# self._process_preambule()
# self._process_file()
#
# ##############################################
#
# def _process_preambule(self):
#
# """ Process the preamble. """
#
# stream = self.stream
#
# stream.seek(0)
#
# if stream.read_unsigned_byte1() != vf_opcodes.PRE:
# raise NameError("Virtual font file don't start by PRE opcode")
#
# file_id = stream.read_unsigned_byte1()
# if file_id != VF_ID:
# raise NameError("Unknown file ID")
#
# comment = stream.read(stream.read_unsigned_byte1())
# checksum = stream.read_signed_byte4()
# design_font_size = stream.read_fix_word()
#
# # string_template = '''
# # Preambule
# # - Vf ID %u
# # - Comment '%s'
# # - Design size %.1f pt
# # - Checksum %u
# # '''
# # print string_template % (
# # file_id,
# # comment,
# # design_font_size,
# # checksum,
# # )
#
#
# self.virtual_font._set_preambule_data(file_id, comment, design_font_size, checksum)
#
# ##############################################
#
# def _process_file(self):
#
# """ Process the characters. """
#
# stream = self.stream
#
# # Fixme: to incorporate pre, check here pre is the first code
#
# while True:
# byte = stream.read_unsigned_byte1()
# if byte == vf_opcodes.POST:
# break
# else:
# # Fixme: self.opcode_parsers[byte]()
# opcode_parser = self.opcode_parser_set[byte]
# opcode_parser.read_parameters(self) # Fixme: return where
. Output only the next line. | VirtualFontParser.parse(self) |
Next line prediction: <|code_start|>#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
####################################################################################################
####################################################################################################
####################################################################################################
# import PyDviGui.Config.Config as Config
####################################################################################################
class ApplicationBase(QtGui.QApplication):
_logger = logging.getLogger(__name__)
##############################################
def __init__(self, args, **kwargs):
super(ApplicationBase, self).__init__(sys.argv)
sys.excepthook = self._exception_hook
self._args = args
<|code_end|>
. Use current file imports:
(import logging
import sys
import traceback
import PyDvi.Version as Version
import PyDviGui.Config.Messages as Messages
from PyQt4 import QtGui
from PyDviGui.Tools.Platform import Platform)
and context including class names, function names, or small code snippets from other files:
# Path: PyDviGui/Tools/Platform.py
# class Platform(object):
#
# ##############################################
#
# def __init__(self):
#
# self.python_version = platform.python_version()
# self.qt_version = QtCore.QT_VERSION_STR
# self.pyqt_version = QtCore.PYQT_VERSION_STR
#
# self.os = self._get_os()
# self.node = platform.node()
# self.distribution = ' '.join(platform.dist())
# self.machine = platform.machine()
# self.architecture = platform.architecture()[0]
#
# # CPU
# self.cpu = self._get_cpu()
# self.number_of_cores = self._get_number_of_cores()
# self.cpu_khz = self._get_cpu_khz()
# self.cpu_mhz = rint(self._get_cpu_khz()/float(1000))
#
# # RAM
# self.memory_size_kb = self._get_memory_size_kb()
# self.memory_size_mb = rint(self.memory_size_kb/float(1024))
#
# # Screen
# try:
# application = QtGui.QApplication.instance()
# self.desktop = application.desktop()
# self.number_of_screens = self.desktop.screenCount()
# except:
# self.desktop = None
# self.number_of_screens = 0
# self.screens = []
# for i in xrange(self.number_of_screens):
# self.screens.append(Screen(self, i))
#
# # OpenGL
# self.gl_renderer = None
# self.gl_version = None
# self.gl_vendor = None
# self.gl_extensions = None
#
# ##############################################
#
# def _get_os(self):
#
# if os.name in 'nt':
# return platform_enum.windows
# elif sys.platform in 'linux2':
# return platform_enum.linux
# else:
# raise RuntimeError('unknown platform')
#
# ##############################################
#
# def _get_cpu(self):
#
# if self.os == platform_enum.linux:
# with open('/proc/cpuinfo', 'rt') as cpuinfo:
# for line in cpuinfo:
# if 'model name' in line:
# s = line.split(':')[1]
# return s.strip().rstrip()
#
# elif self.os == platform_enum.windows:
# raise NotImplementedError
#
# ##############################################
#
# def _get_number_of_cores(self):
#
# if self.os == platform_enum.linux:
# number_of_cores = 0
# with open('/proc/cpuinfo', 'rt') as cpuinfo:
# for line in cpuinfo:
# if 'processor' in line:
# number_of_cores += 1
# return number_of_cores
#
# elif self.os == platform_enum.windows:
#
# return int(os.getenv('NUMBER_OF_PROCESSORS'))
#
# ##############################################
#
# def _get_cpu_khz(self):
#
# if self.os == platform_enum.linux:
# with open('/proc/cpuinfo', 'rt') as cpuinfo:
# for line in cpuinfo:
# if 'cpu MHz' in line:
# s = line.split(':')[1]
# return int(1000 * float(s))
#
# if self.os == platform_enum.windows:
# raise NotImplementedError
#
# ##############################################
#
# def _get_memory_size_kb(self):
#
# if self.os == platform_enum.linux:
# with open('/proc/meminfo', 'rt') as cpuinfo:
# for line in cpuinfo:
# if 'MemTotal' in line:
# s = line.split(':')[1][:-3]
# return int(s)
#
# if self.os == platform_enum.windows:
# raise NotImplementedError
#
# ##############################################
#
# def query_opengl(self):
#
# import OpenGL.GL as GL
#
# self.gl_renderer = GL.glGetString(GL.GL_RENDERER)
# self.gl_version = GL.glGetString(GL.GL_VERSION)
# self.gl_vendor = GL.glGetString(GL.GL_VENDOR)
# self.gl_extensions = GL.glGetString(GL.GL_EXTENSIONS)
#
# ##############################################
#
# def __str__(self):
#
# message_template = '''
# Platform %(node)s
# Hardware:
# Machine: %(machine)s
# Architecture: %(architecture)s
# CPU: %(cpu)s
# Number of Cores: %(number_of_cores)u
# CPU Frequence: %(cpu_mhz)u MHz
# Memory: %(memory_size_mb)u MB
# OpenGL
# Render: %(gl_renderer)s
# Version: %(gl_version)s
# Vendor: %(gl_vendor)s
# Number of Screens: %(number_of_screens)u
# '''
# message = message_template % self.__dict__
#
# for screen in self.screens:
# message += str(screen)
#
# message_template = '''
# Software Versions:
# OS: %(os)s
# Distribution: %(distribution)s
# Python: %(python_version)s
# Qt: %(qt_version)s
# PyQt: %(pyqt_version)s
# '''
# message += message_template % self.__dict__
#
# return message
. Output only the next line. | self._platform = Platform() |
Continue the code snippet: <|code_start|>__all__ = ['VirtualCharacter']
####################################################################################################
####################################################################################################
class VirtualCharacter(object):
##############################################
def __init__(self, char_code, width, dvi):
self.char_code = char_code
self.width = width
self._dvi = dvi
self._subroutine = None
##############################################
def __repr__(self):
return "Virtual Character {}".format(self.char_code)
##############################################
@property
def subroutine(self):
if self._subroutine is None:
<|code_end|>
. Use current file imports:
from ..Tools.Stream import ByteStream
from ..Dvi.DviParser import DviSubroutineParser # Fixme: circular import ?
and context (classes, functions, or code) from other files:
# Path: PyDvi/Tools/Stream.py
# class ByteStream(StandardStream):
#
# ##############################################
#
# def __init__(self, string_bytes):
#
# self._length = len(string_bytes)
# self.stream = io.BytesIO(string_bytes)
# # self.seek(0)
#
# ##############################################
#
# def end_of_stream(self):
# return self.tell() == self._length
. Output only the next line. | parser = DviSubroutineParser(ByteStream(self._dvi)) |
Continue the code snippet: <|code_start|> def __init__(self, tex_name, ps_font_name, ps_snippet, effects, encoding, pfb_filename):
self.tex_name = tex_name
self.ps_font_name = ps_font_name
self.ps_snippet = ps_snippet
self.effects = effects
self.encoding = encoding
self.pfb_filename = pfb_filename
##############################################
def print_summary(self):
message_pattern = '''Font Map Entry %s
- PS font name %s
- ps snippet "%s"
- effects %s
- encoding %s
- pfb_filename %s'''
message = message_pattern % (
self.tex_name,
self.ps_font_name,
self.ps_snippet,
self.effects,
self.encoding,
self.pfb_filename,
)
<|code_end|>
. Use current file imports:
import os
from ..Tools.Logging import print_card
from ..Tools.TexCommentedFile import TexCommentedFile
and context (classes, functions, or code) from other files:
# Path: PyDvi/Tools/Logging.py
# def print_card(text, **kwargs):
#
# """ Print the string *text* formated by :meth:`format_card`. The remaining keyword arguments
# *kwargs* are passed to :meth:`format_card`.
# """
#
# print format_card(text, **kwargs)
#
# Path: PyDvi/Tools/TexCommentedFile.py
# class TexCommentedFile(file):
#
# """ This class permits to iterate over lines of a text file and to skip commented line by '%'.
# """
#
# ##############################################
#
# def __init__(self, filename):
#
# super(TexCommentedFile, self).__init__(filename, mode='r')
#
# ##############################################
#
# def __iter__(self):
#
# while True:
# line = self.readline()
# if not line:
# raise StopIteration()
# comment_start_index = line.find('%')
# if comment_start_index != -1:
# line = line[:comment_start_index]
# line = line.strip()
# if line:
# yield line
#
# ##############################################
#
# def concatenate_lines(self):
#
# """ Concatenate the lines and return the corresponding string. """
#
# return ''.join(self)
. Output only the next line. | print_card(message) |
Given the code snippet: <|code_start|> - ps snippet "%s"
- effects %s
- encoding %s
- pfb_filename %s'''
message = message_pattern % (
self.tex_name,
self.ps_font_name,
self.ps_snippet,
self.effects,
self.encoding,
self.pfb_filename,
)
print_card(message)
####################################################################################################
class FontMap(object):
""" This class parses a font map file. """
##############################################
def __init__(self, filename):
self.name = os.path.basename(filename).replace('.map', '')
self._map = {}
# try:
<|code_end|>
, generate the next line using the imports in this file:
import os
from ..Tools.Logging import print_card
from ..Tools.TexCommentedFile import TexCommentedFile
and context (functions, classes, or occasionally code) from other files:
# Path: PyDvi/Tools/Logging.py
# def print_card(text, **kwargs):
#
# """ Print the string *text* formated by :meth:`format_card`. The remaining keyword arguments
# *kwargs* are passed to :meth:`format_card`.
# """
#
# print format_card(text, **kwargs)
#
# Path: PyDvi/Tools/TexCommentedFile.py
# class TexCommentedFile(file):
#
# """ This class permits to iterate over lines of a text file and to skip commented line by '%'.
# """
#
# ##############################################
#
# def __init__(self, filename):
#
# super(TexCommentedFile, self).__init__(filename, mode='r')
#
# ##############################################
#
# def __iter__(self):
#
# while True:
# line = self.readline()
# if not line:
# raise StopIteration()
# comment_start_index = line.find('%')
# if comment_start_index != -1:
# line = line[:comment_start_index]
# line = line.strip()
# if line:
# yield line
#
# ##############################################
#
# def concatenate_lines(self):
#
# """ Concatenate the lines and return the corresponding string. """
#
# return ''.join(self)
. Output only the next line. | with TexCommentedFile(filename) as font_map_file: |
Predict the next line after this snippet: <|code_start|> return char
else:
return self.char_code
##############################################
def print_summary(self):
string_format = '''TFM Char %u %s
- width %.3f
- height %.3f
- depth %.3f
- italic correction %.3f
- lig kern program index %s
- next larger char %s'''
message = string_format % (self.char_code, self.chr(),
self.width,
self.height,
self.depth,
self.italic_correction,
str(self.lig_kern_program_index),
str(self.next_larger_char),
)
first_lig_kern = self.get_lig_kern_program()
if first_lig_kern is not None:
for lig_kern in first_lig_kern:
message += '\n' + str(lig_kern)
<|code_end|>
using the current file's imports:
import string
from ..Tools.Logging import print_card
and any relevant context from other files:
# Path: PyDvi/Tools/Logging.py
# def print_card(text, **kwargs):
#
# """ Print the string *text* formated by :meth:`format_card`. The remaining keyword arguments
# *kwargs* are passed to :meth:`format_card`.
# """
#
# print format_card(text, **kwargs)
. Output only the next line. | print_card(message) |
Given snippet: <|code_start|>
class FieldTests(TestCase):
"""test model functionality"""
def test_init(self):
URLField()
def test_url(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from django.core.exceptions import ValidationError
from django.test import TestCase
from django_peeringdb.models import LG_URLField, URLField
from tests.models import FieldModel, LG_FieldModel
and context:
# Path: tests/models.py
# class FieldModel(models.Model):
# url = URLField(null=True, blank=True)
# multichoice = MultipleChoiceField(
# max_length=255,
# null=True,
# blank=True,
# choices=[("1", "1"), ("2", "2"), ("3", "3")],
# )
#
# class Meta:
# app_label = "django_peeringdb.tests"
#
# class LG_FieldModel(models.Model):
# url = LG_URLField(null=True, blank=True)
#
# class Meta:
# app_label = "django_peeringdb.tests"
which might include code, classes, or functions. Output only the next line. | model = FieldModel() |
Using the snippet: <|code_start|> with pytest.raises(ValidationError):
model.url = "invalid"
model.full_clean()
def test_multichoice(self):
model = FieldModel()
model.multichoice = ["1", "2"]
model.full_clean()
model.multichoice = "1"
model.full_clean()
assert model.multichoice == ["1"]
with pytest.raises(ValidationError):
model.multichoice = ["4"]
model.full_clean()
with pytest.raises(ValidationError):
model.multichoice = "4"
model.full_clean()
class LG_FieldTests(TestCase):
"""test model functionality"""
def test_init(self):
LG_URLField()
def test_url(self):
<|code_end|>
, determine the next line of code. You have imports:
import pytest
from django.core.exceptions import ValidationError
from django.test import TestCase
from django_peeringdb.models import LG_URLField, URLField
from tests.models import FieldModel, LG_FieldModel
and context (class names, function names, or code) available:
# Path: tests/models.py
# class FieldModel(models.Model):
# url = URLField(null=True, blank=True)
# multichoice = MultipleChoiceField(
# max_length=255,
# null=True,
# blank=True,
# choices=[("1", "1"), ("2", "2"), ("3", "3")],
# )
#
# class Meta:
# app_label = "django_peeringdb.tests"
#
# class LG_FieldModel(models.Model):
# url = LG_URLField(null=True, blank=True)
#
# class Meta:
# app_label = "django_peeringdb.tests"
. Output only the next line. | model = LG_FieldModel() |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
class BoardView(ListView):
"""List boards from Trello and create each board into database.
Create the trello Hook also.
Then returns the board template.
"""
<|code_end|>
, generate the next line using the imports in this file:
from os import getenv
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.utils.text import slugify
from django.views.generic import ListView
from django.views.generic.detail import DetailView
from django.utils.decorators import method_decorator
from trello import TrelloClient
from core.models import Board, Webhook
and context (functions, classes, or occasionally code) 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)
. Output only the next line. | model = Board |
Given the code snippet: <|code_start|> return super(BoardView, self).get(request)
def get_context_data(self, **kwargs):
"""Fishy way to ensure trello_client is configured."""
try:
context = super(BoardView, self).get_context_data(**kwargs)
token = self.request.GET.get("token")
if token is None:
context["board_list"] = None
trello_client = TrelloClient(
api_key=settings.TRELLO_APIKEY, token=token
)
trello_client.list_boards()
user = self.request.user
listboard = Board.objects.filter(trello_token=token)
context["board_list"] = listboard
context["trello_error"] = None
except Exception as e:
context["trello_error"] = "{} :: api_key={} :: token={}".format(
e, settings.TRELLO_APIKEY, settings.TRELLO_TOKEN
)
finally:
return context
class BoardDetailView(DetailView):
model = Board
def get_context_data(self, **kwargs):
context = super(BoardDetailView, self).get_context_data(**kwargs)
<|code_end|>
, generate the next line using the imports in this file:
from os import getenv
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.utils.text import slugify
from django.views.generic import ListView
from django.views.generic.detail import DetailView
from django.utils.decorators import method_decorator
from trello import TrelloClient
from core.models import Board, Webhook
and context (functions, classes, or occasionally code) 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)
. Output only the next line. | context["webhook_list"] = Webhook.objects.filter( |
Given 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
<|code_end|>
, continue by predicting the next line. Consider 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:
# 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 might include code, classes, or functions. Output only the next line. | form_class = BridgeCreateForm |
Given the following code snippet before the placeholder: <|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)
<|code_end|>
, predict the next line using imports from the current 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 including class names, function names, and sometimes 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. | context["board"] = Board.objects.get(id=board_id) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
class WebhookDetailView(DetailView):
model = Webhook
class WebhookCreateView(SuccessMessageMixin, CreateView):
model = Webhook
<|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. | form_class = WebhookCreateForm |
Using the snippet: <|code_start|>
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:
<|code_end|>
, determine the next line of code. You have 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 (class names, function names, or code) available:
# 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. | model = Webhook |
Continue the code snippet: <|code_start|> name. Valid values are: "name", "name asc", and
"name desc".
"""
parent = proto.Field(proto.STRING, number=1,)
page_size = proto.Field(proto.INT32, number=2,)
page_token = proto.Field(proto.STRING, number=3,)
filter = proto.Field(proto.STRING, number=4,)
order_by = proto.Field(proto.STRING, number=5,)
class ListMigrationJobsResponse(proto.Message):
r"""Response message for 'ListMigrationJobs' request.
Attributes:
migration_jobs (Sequence[google.cloud.clouddms_v1.types.MigrationJob]):
The list of migration jobs objects.
next_page_token (str):
A token, which can be sent as ``page_token`` to retrieve the
next page. If this field is omitted, there are no subsequent
pages.
unreachable (Sequence[str]):
Locations that could not be reached.
"""
@property
def raw_page(self):
return self
migration_jobs = proto.RepeatedField(
<|code_end|>
. Use current file imports:
import proto # type: ignore
from google.cloud.clouddms_v1.types import clouddms_resources
from google.protobuf import field_mask_pb2 # type: ignore
from google.protobuf import timestamp_pb2 # type: ignore
and context (classes, functions, or code) from other files:
# Path: google/cloud/clouddms_v1/types/clouddms_resources.py
# class DatabaseEngine(proto.Enum):
# class DatabaseProvider(proto.Enum):
# class SslConfig(proto.Message):
# class SslType(proto.Enum):
# class MySqlConnectionProfile(proto.Message):
# class PostgreSqlConnectionProfile(proto.Message):
# class CloudSqlConnectionProfile(proto.Message):
# class SqlAclEntry(proto.Message):
# class SqlIpConfig(proto.Message):
# class CloudSqlSettings(proto.Message):
# class SqlActivationPolicy(proto.Enum):
# class SqlDataDiskType(proto.Enum):
# class SqlDatabaseVersion(proto.Enum):
# class StaticIpConnectivity(proto.Message):
# class ReverseSshConnectivity(proto.Message):
# class VpcPeeringConnectivity(proto.Message):
# class DatabaseType(proto.Message):
# class MigrationJob(proto.Message):
# class State(proto.Enum):
# class Phase(proto.Enum):
# class Type(proto.Enum):
# class ConnectionProfile(proto.Message):
# class State(proto.Enum):
# class MigrationJobVerificationError(proto.Message):
# class ErrorCode(proto.Enum):
# DATABASE_ENGINE_UNSPECIFIED = 0
# MYSQL = 1
# POSTGRESQL = 2
# DATABASE_PROVIDER_UNSPECIFIED = 0
# CLOUDSQL = 1
# RDS = 2
# SSL_TYPE_UNSPECIFIED = 0
# SERVER_ONLY = 1
# SERVER_CLIENT = 2
# SQL_ACTIVATION_POLICY_UNSPECIFIED = 0
# ALWAYS = 1
# NEVER = 2
# SQL_DATA_DISK_TYPE_UNSPECIFIED = 0
# PD_SSD = 1
# PD_HDD = 2
# SQL_DATABASE_VERSION_UNSPECIFIED = 0
# MYSQL_5_6 = 1
# MYSQL_5_7 = 2
# POSTGRES_9_6 = 3
# POSTGRES_11 = 4
# POSTGRES_10 = 5
# MYSQL_8_0 = 6
# POSTGRES_12 = 7
# POSTGRES_13 = 8
# STATE_UNSPECIFIED = 0
# MAINTENANCE = 1
# DRAFT = 2
# CREATING = 3
# NOT_STARTED = 4
# RUNNING = 5
# FAILED = 6
# COMPLETED = 7
# DELETING = 8
# STOPPING = 9
# STOPPED = 10
# DELETED = 11
# UPDATING = 12
# STARTING = 13
# RESTARTING = 14
# RESUMING = 15
# PHASE_UNSPECIFIED = 0
# FULL_DUMP = 1
# CDC = 2
# PROMOTE_IN_PROGRESS = 3
# WAITING_FOR_SOURCE_WRITES_TO_STOP = 4
# PREPARING_THE_DUMP = 5
# TYPE_UNSPECIFIED = 0
# ONE_TIME = 1
# CONTINUOUS = 2
# STATE_UNSPECIFIED = 0
# DRAFT = 1
# CREATING = 2
# READY = 3
# UPDATING = 4
# DELETING = 5
# DELETED = 6
# FAILED = 7
# ERROR_CODE_UNSPECIFIED = 0
# CONNECTION_FAILURE = 1
# AUTHENTICATION_FAILURE = 2
# INVALID_CONNECTION_PROFILE_CONFIG = 3
# VERSION_INCOMPATIBILITY = 4
# CONNECTION_PROFILE_TYPES_INCOMPATIBILITY = 5
# NO_PGLOGICAL_INSTALLED = 7
# PGLOGICAL_NODE_ALREADY_EXISTS = 8
# INVALID_WAL_LEVEL = 9
# INVALID_SHARED_PRELOAD_LIBRARY = 10
# INSUFFICIENT_MAX_REPLICATION_SLOTS = 11
# INSUFFICIENT_MAX_WAL_SENDERS = 12
# INSUFFICIENT_MAX_WORKER_PROCESSES = 13
# UNSUPPORTED_EXTENSIONS = 14
# UNSUPPORTED_MIGRATION_TYPE = 15
# INVALID_RDS_LOGICAL_REPLICATION = 16
# UNSUPPORTED_GTID_MODE = 17
# UNSUPPORTED_TABLE_DEFINITION = 18
# UNSUPPORTED_DEFINER = 19
# CANT_RESTART_RUNNING_MIGRATION = 21
. Output only the next line. | proto.MESSAGE, number=1, message=clouddms_resources.MigrationJob, |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
class Command(BaseCommand):
help = 'Starts the GitServer for brigitte.'
def handle(self, *args, **options):
<|code_end|>
. Use current file imports:
from django.conf import settings
from django.core.management.base import BaseCommand
from twisted.conch.interfaces import ISession
from twisted.internet import reactor
from twisted.python import components
from brigitte.gitserver.server import GitSession, GitConchUser, GitServer
and context (classes, functions, or code) from other files:
# Path: brigitte/gitserver/server.py
# class GitSession(object):
# interface.implements(ISession)
#
# def __init__(self, user):
# self.user = user
#
# def writeErr(self, proto, message):
# proto.session.writeExtended(1, ('%s\n' % message).encode('UTF-8'))
#
# def execCommand(self, proto, cmd):
# self.writeErr(proto, 'Welcome to Brigitte.')
#
# argv = shlex.split(cmd)
#
# repo_url = argv[-1].strip('/')
# repo = self.get_repo(repo_url)
#
# close_connection = True
# if not repo:
# self.writeErr(proto, 'Invalid repository: %s' % repo_url)
# else:
# self.writeErr(proto, 'Trying to access repository: %s' % repo.slug)
# if self.validate_git_command(proto, argv, repo):
# close_connection = False
# self.execute_git_command(proto, argv, repo)
#
# if close_connection:
# proto.loseConnection()
#
# def validate_git_command(self, proto, argv, repo):
# command = argv[0]
#
# if command not in (
# 'git-upload-archive',
# 'git-receive-pack',
# 'git-upload-pack'
# ):
# self.writeErr(proto, 'Invalid command: %s' % command)
# return False
# else:
# # upload means receive, weird.
# want_write = not 'upload' in command
# self.writeErr(proto,
# 'Attempted access: %s' % ('write' if want_write else 'read'))
#
# db_user = User.objects.get(username=self.user.username)
# try:
# access = repo.repositoryuser_set.get(user__username=db_user)
# except RepositoryUser.DoesNotExist:
# self.writeErr(proto,
# 'No access configuration found for %s' % db_user.username)
# return False
#
# self.writeErr(proto, 'Access for %s - read: %s write: %s' % (
# db_user.username, access.can_read, access.can_write))
#
# if (
# (want_write and not access.can_write)
# or (not want_write and not access.can_read)
# ):
# self.writeErr(proto, 'Access denied!')
# return False
#
# return True
#
# def execute_git_command(self, proto, argv, repo):
# sh = self.user.shell
# command = ' '.join(argv[:-1] + ["'%s'" % (repo.path,)])
# reactor.spawnProcess(proto, sh, (sh, '-c', command))
#
# def eofReceived(self):
# pass
#
# def closed(self):
# pass
#
# def get_repo(self, reponame):
# log.msg('looking up repository %s' % reponame)
#
# username, slug = reponame.strip('/').split('/', 1)
# slug = slug.rsplit('.', 1)[0]
#
# try:
# repo = Repository.objects.get(
# user__username=username, slug=slug)
# return repo
# except Repository.DoesNotExist:
# return None
#
# class GitConchUser(ConchUser):
# shell = find_git_shell()
#
# def __init__(self, username):
# ConchUser.__init__(self)
# self.username = username
# self.channelLookup.update({"session": GitProcessProtocolSession})
#
# def logout(self):
# pass
#
# class GitServer(SSHFactory):
# portal = Portal(GitRealm())
# portal.registerChecker(GitPubKeyChecker())
#
# def __init__(self, priv_key):
# pub_key = '%s.pub' % priv_key
# self.privateKeys = {'ssh-rsa': Key.fromFile(priv_key)}
# self.publicKeys = {'ssh-rsa': Key.fromFile(pub_key)}
# self.primes = {2048: [(transport.DH_GENERATOR, transport.DH_PRIME)]}
. Output only the next line. | components.registerAdapter(GitSession, GitConchUser, ISession) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
class Command(BaseCommand):
help = 'Starts the GitServer for brigitte.'
def handle(self, *args, **options):
<|code_end|>
, predict the immediate next line with the help of imports:
from django.conf import settings
from django.core.management.base import BaseCommand
from twisted.conch.interfaces import ISession
from twisted.internet import reactor
from twisted.python import components
from brigitte.gitserver.server import GitSession, GitConchUser, GitServer
and context (classes, functions, sometimes code) from other files:
# Path: brigitte/gitserver/server.py
# class GitSession(object):
# interface.implements(ISession)
#
# def __init__(self, user):
# self.user = user
#
# def writeErr(self, proto, message):
# proto.session.writeExtended(1, ('%s\n' % message).encode('UTF-8'))
#
# def execCommand(self, proto, cmd):
# self.writeErr(proto, 'Welcome to Brigitte.')
#
# argv = shlex.split(cmd)
#
# repo_url = argv[-1].strip('/')
# repo = self.get_repo(repo_url)
#
# close_connection = True
# if not repo:
# self.writeErr(proto, 'Invalid repository: %s' % repo_url)
# else:
# self.writeErr(proto, 'Trying to access repository: %s' % repo.slug)
# if self.validate_git_command(proto, argv, repo):
# close_connection = False
# self.execute_git_command(proto, argv, repo)
#
# if close_connection:
# proto.loseConnection()
#
# def validate_git_command(self, proto, argv, repo):
# command = argv[0]
#
# if command not in (
# 'git-upload-archive',
# 'git-receive-pack',
# 'git-upload-pack'
# ):
# self.writeErr(proto, 'Invalid command: %s' % command)
# return False
# else:
# # upload means receive, weird.
# want_write = not 'upload' in command
# self.writeErr(proto,
# 'Attempted access: %s' % ('write' if want_write else 'read'))
#
# db_user = User.objects.get(username=self.user.username)
# try:
# access = repo.repositoryuser_set.get(user__username=db_user)
# except RepositoryUser.DoesNotExist:
# self.writeErr(proto,
# 'No access configuration found for %s' % db_user.username)
# return False
#
# self.writeErr(proto, 'Access for %s - read: %s write: %s' % (
# db_user.username, access.can_read, access.can_write))
#
# if (
# (want_write and not access.can_write)
# or (not want_write and not access.can_read)
# ):
# self.writeErr(proto, 'Access denied!')
# return False
#
# return True
#
# def execute_git_command(self, proto, argv, repo):
# sh = self.user.shell
# command = ' '.join(argv[:-1] + ["'%s'" % (repo.path,)])
# reactor.spawnProcess(proto, sh, (sh, '-c', command))
#
# def eofReceived(self):
# pass
#
# def closed(self):
# pass
#
# def get_repo(self, reponame):
# log.msg('looking up repository %s' % reponame)
#
# username, slug = reponame.strip('/').split('/', 1)
# slug = slug.rsplit('.', 1)[0]
#
# try:
# repo = Repository.objects.get(
# user__username=username, slug=slug)
# return repo
# except Repository.DoesNotExist:
# return None
#
# class GitConchUser(ConchUser):
# shell = find_git_shell()
#
# def __init__(self, username):
# ConchUser.__init__(self)
# self.username = username
# self.channelLookup.update({"session": GitProcessProtocolSession})
#
# def logout(self):
# pass
#
# class GitServer(SSHFactory):
# portal = Portal(GitRealm())
# portal.registerChecker(GitPubKeyChecker())
#
# def __init__(self, priv_key):
# pub_key = '%s.pub' % priv_key
# self.privateKeys = {'ssh-rsa': Key.fromFile(priv_key)}
# self.publicKeys = {'ssh-rsa': Key.fromFile(pub_key)}
# self.primes = {2048: [(transport.DH_GENERATOR, transport.DH_PRIME)]}
. Output only the next line. | components.registerAdapter(GitSession, GitConchUser, ISession) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
class Command(BaseCommand):
help = 'Starts the GitServer for brigitte.'
def handle(self, *args, **options):
components.registerAdapter(GitSession, GitConchUser, ISession)
reactor.listenTCP(settings.BRIGITTE_SSH_PORT,
<|code_end|>
, predict the immediate next line with the help of imports:
from django.conf import settings
from django.core.management.base import BaseCommand
from twisted.conch.interfaces import ISession
from twisted.internet import reactor
from twisted.python import components
from brigitte.gitserver.server import GitSession, GitConchUser, GitServer
and context (classes, functions, sometimes code) from other files:
# Path: brigitte/gitserver/server.py
# class GitSession(object):
# interface.implements(ISession)
#
# def __init__(self, user):
# self.user = user
#
# def writeErr(self, proto, message):
# proto.session.writeExtended(1, ('%s\n' % message).encode('UTF-8'))
#
# def execCommand(self, proto, cmd):
# self.writeErr(proto, 'Welcome to Brigitte.')
#
# argv = shlex.split(cmd)
#
# repo_url = argv[-1].strip('/')
# repo = self.get_repo(repo_url)
#
# close_connection = True
# if not repo:
# self.writeErr(proto, 'Invalid repository: %s' % repo_url)
# else:
# self.writeErr(proto, 'Trying to access repository: %s' % repo.slug)
# if self.validate_git_command(proto, argv, repo):
# close_connection = False
# self.execute_git_command(proto, argv, repo)
#
# if close_connection:
# proto.loseConnection()
#
# def validate_git_command(self, proto, argv, repo):
# command = argv[0]
#
# if command not in (
# 'git-upload-archive',
# 'git-receive-pack',
# 'git-upload-pack'
# ):
# self.writeErr(proto, 'Invalid command: %s' % command)
# return False
# else:
# # upload means receive, weird.
# want_write = not 'upload' in command
# self.writeErr(proto,
# 'Attempted access: %s' % ('write' if want_write else 'read'))
#
# db_user = User.objects.get(username=self.user.username)
# try:
# access = repo.repositoryuser_set.get(user__username=db_user)
# except RepositoryUser.DoesNotExist:
# self.writeErr(proto,
# 'No access configuration found for %s' % db_user.username)
# return False
#
# self.writeErr(proto, 'Access for %s - read: %s write: %s' % (
# db_user.username, access.can_read, access.can_write))
#
# if (
# (want_write and not access.can_write)
# or (not want_write and not access.can_read)
# ):
# self.writeErr(proto, 'Access denied!')
# return False
#
# return True
#
# def execute_git_command(self, proto, argv, repo):
# sh = self.user.shell
# command = ' '.join(argv[:-1] + ["'%s'" % (repo.path,)])
# reactor.spawnProcess(proto, sh, (sh, '-c', command))
#
# def eofReceived(self):
# pass
#
# def closed(self):
# pass
#
# def get_repo(self, reponame):
# log.msg('looking up repository %s' % reponame)
#
# username, slug = reponame.strip('/').split('/', 1)
# slug = slug.rsplit('.', 1)[0]
#
# try:
# repo = Repository.objects.get(
# user__username=username, slug=slug)
# return repo
# except Repository.DoesNotExist:
# return None
#
# class GitConchUser(ConchUser):
# shell = find_git_shell()
#
# def __init__(self, username):
# ConchUser.__init__(self)
# self.username = username
# self.channelLookup.update({"session": GitProcessProtocolSession})
#
# def logout(self):
# pass
#
# class GitServer(SSHFactory):
# portal = Portal(GitRealm())
# portal.registerChecker(GitPubKeyChecker())
#
# def __init__(self, priv_key):
# pub_key = '%s.pub' % priv_key
# self.privateKeys = {'ssh-rsa': Key.fromFile(priv_key)}
# self.publicKeys = {'ssh-rsa': Key.fromFile(pub_key)}
# self.primes = {2048: [(transport.DH_GENERATOR, transport.DH_PRIME)]}
. Output only the next line. | GitServer(settings.BRIGITTE_SSH_KEY_PATH)) |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
@login_required
def manage_list(request):
return render(request, 'repositories/manage_list.html', {
'repository_list': Repository.objects.manageable_repositories(
request.user),
})
@login_required
<|code_end|>
with the help of current file imports:
import json
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.db.models import Q
from django.http import Http404, HttpResponse
from django.shortcuts import render, redirect
from django.template.defaultfilters import slugify
from django.utils.translation import gettext_lazy as _
from django.views.decorators.csrf import csrf_exempt
from brigitte.repositories.decorators import repository_view
from brigitte.repositories.forms import RepositoryForm, RepositoryUserFormSet
from brigitte.repositories.models import Repository
and context from other files:
# Path: brigitte/repositories/decorators.py
# def repository_view(can_admin=False):
# def inner_repository_view(f):
# def wrapped(request, user, slug, *args, **kwargs):
# qs = Repository.objects.none()
#
# if request.user.is_authenticated():
# if can_admin:
# qs = Repository.objects.manageable_repositories(request.user)
# else:
# qs = Repository.objects.available_repositories(request.user)
# else:
# if not can_admin:
# qs = Repository.objects.public_repositories()
#
# repository = get_object_or_404(qs, user__username=user, slug=slug)
#
# return f(request, repository, *args, **kwargs)
# return wraps(f)(wrapped)
# return inner_repository_view
#
# Path: brigitte/repositories/forms.py
# class RepositoryForm(forms.ModelForm):
# class Meta:
# def __init__(self, user, *args, **kwargs):
# def clean(self):
#
# Path: brigitte/repositories/models.py
# class Repository(models.Model):
# user = models.ForeignKey(User, verbose_name=_('User'))
# slug = models.SlugField(_('Slug'), max_length=80, blank=False)
# title = models.CharField(_('Title'), max_length=80)
# description = models.TextField(_('Description'), blank=True)
# private = models.BooleanField(_('Private'), default=False)
# repo_type = models.CharField(_('Type'), max_length=4, choices=REPO_TYPES,
# default='git')
# last_commit_date = models.DateTimeField(blank=True, null=True)
#
# objects = RepositoryManager()
#
# def __unicode__(self):
# return self.title
#
# def get_last_commit(self):
# # TODO: cache self.last_commit with git hook ...
# last_commit = self.last_commit
# if not self.last_commit_date and last_commit:
# self.last_commit_date = last_commit.commit_date
# self.save()
# elif self.last_commit_date and last_commit and self.last_commit_date != last_commit.commit_date:
# self.last_commit_date = self.last_commit.commit_date
# self.save()
# return last_commit
#
# @property
# def private_html(self):
# if self.private:
# return mark_safe('✔')
# else:
# return mark_safe('✘')
#
# @property
# def path(self):
# if self.repo_type == 'git':
# return os.path.join(BRIGITTE_GIT_BASE_PATH, self.user.username,
# '%s.git' % self.slug)
#
# return None
#
# @property
# def short_path(self):
# if self.repo_type == 'git':
# return '%s/%s.git' % (self.user.username, self.slug)
#
# return None
#
# @property
# def _repo(self):
# if not hasattr(self, '_repo_obj'):
# self._repo_obj = get_backend(self.repo_type)(self)
# return self._repo_obj
#
# def recent_commits(self, count=10):
# return self._repo.get_commits(count=count)
#
# @property
# def last_commit(self):
# if not hasattr(self, '_last_commit'):
# self._last_commit = self._repo.last_commit
# return self._last_commit
#
# @property
# def tags(self):
# if not hasattr(self, '_tags'):
# self._tags = self._repo.tags
# return self._tags
#
# @property
# def branches(self):
# if not hasattr(self, '_branches'):
# self._branches = self._repo.branches
# return self._branches
#
# @property
# def rw_url(self):
# if self.repo_type == 'git':
# return 'git@%s:%s' % (
# Site.objects.get_current(), self.short_path)
#
# return None
#
# @property
# def ro_url(self):
# if self.repo_type == 'git':
# return 'git://%s/%s' % (Site.objects.get_current(), self.short_path)
#
# return None
#
# def get_commit(self, sha):
# return self._repo.get_commit(sha)
#
# def get_commits(self, count=10, skip=0, head=None):
# return self._repo.get_commits(count=count, skip=skip, head=head)
#
# @property
# def alterable_users(self):
# return self.repositoryuser_set.exclude(user=self.user)
#
# def save(self, *args, **kwargs):
# if not self.pk:
# self._repo.init_repo()
# self._repo.repo_settings_changed()
# super(Repository, self).save(*args, **kwargs)
#
# def delete(self, *args, **kwargs):
# self._repo.delete_repo(self.slug)
# super(Repository, self).delete(*args, **kwargs)
#
# class Meta:
# unique_together = ('user', 'slug')
# verbose_name = _('Repository')
# verbose_name_plural = _('Repositories')
, which may contain function names, class names, or code. Output only the next line. | @repository_view(can_admin=True) |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
@login_required
def manage_list(request):
return render(request, 'repositories/manage_list.html', {
<|code_end|>
. Use current file imports:
import json
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.db.models import Q
from django.http import Http404, HttpResponse
from django.shortcuts import render, redirect
from django.template.defaultfilters import slugify
from django.utils.translation import gettext_lazy as _
from django.views.decorators.csrf import csrf_exempt
from brigitte.repositories.decorators import repository_view
from brigitte.repositories.forms import RepositoryForm, RepositoryUserFormSet
from brigitte.repositories.models import Repository
and context (classes, functions, or code) from other files:
# Path: brigitte/repositories/decorators.py
# def repository_view(can_admin=False):
# def inner_repository_view(f):
# def wrapped(request, user, slug, *args, **kwargs):
# qs = Repository.objects.none()
#
# if request.user.is_authenticated():
# if can_admin:
# qs = Repository.objects.manageable_repositories(request.user)
# else:
# qs = Repository.objects.available_repositories(request.user)
# else:
# if not can_admin:
# qs = Repository.objects.public_repositories()
#
# repository = get_object_or_404(qs, user__username=user, slug=slug)
#
# return f(request, repository, *args, **kwargs)
# return wraps(f)(wrapped)
# return inner_repository_view
#
# Path: brigitte/repositories/forms.py
# class RepositoryForm(forms.ModelForm):
# class Meta:
# def __init__(self, user, *args, **kwargs):
# def clean(self):
#
# Path: brigitte/repositories/models.py
# class Repository(models.Model):
# user = models.ForeignKey(User, verbose_name=_('User'))
# slug = models.SlugField(_('Slug'), max_length=80, blank=False)
# title = models.CharField(_('Title'), max_length=80)
# description = models.TextField(_('Description'), blank=True)
# private = models.BooleanField(_('Private'), default=False)
# repo_type = models.CharField(_('Type'), max_length=4, choices=REPO_TYPES,
# default='git')
# last_commit_date = models.DateTimeField(blank=True, null=True)
#
# objects = RepositoryManager()
#
# def __unicode__(self):
# return self.title
#
# def get_last_commit(self):
# # TODO: cache self.last_commit with git hook ...
# last_commit = self.last_commit
# if not self.last_commit_date and last_commit:
# self.last_commit_date = last_commit.commit_date
# self.save()
# elif self.last_commit_date and last_commit and self.last_commit_date != last_commit.commit_date:
# self.last_commit_date = self.last_commit.commit_date
# self.save()
# return last_commit
#
# @property
# def private_html(self):
# if self.private:
# return mark_safe('✔')
# else:
# return mark_safe('✘')
#
# @property
# def path(self):
# if self.repo_type == 'git':
# return os.path.join(BRIGITTE_GIT_BASE_PATH, self.user.username,
# '%s.git' % self.slug)
#
# return None
#
# @property
# def short_path(self):
# if self.repo_type == 'git':
# return '%s/%s.git' % (self.user.username, self.slug)
#
# return None
#
# @property
# def _repo(self):
# if not hasattr(self, '_repo_obj'):
# self._repo_obj = get_backend(self.repo_type)(self)
# return self._repo_obj
#
# def recent_commits(self, count=10):
# return self._repo.get_commits(count=count)
#
# @property
# def last_commit(self):
# if not hasattr(self, '_last_commit'):
# self._last_commit = self._repo.last_commit
# return self._last_commit
#
# @property
# def tags(self):
# if not hasattr(self, '_tags'):
# self._tags = self._repo.tags
# return self._tags
#
# @property
# def branches(self):
# if not hasattr(self, '_branches'):
# self._branches = self._repo.branches
# return self._branches
#
# @property
# def rw_url(self):
# if self.repo_type == 'git':
# return 'git@%s:%s' % (
# Site.objects.get_current(), self.short_path)
#
# return None
#
# @property
# def ro_url(self):
# if self.repo_type == 'git':
# return 'git://%s/%s' % (Site.objects.get_current(), self.short_path)
#
# return None
#
# def get_commit(self, sha):
# return self._repo.get_commit(sha)
#
# def get_commits(self, count=10, skip=0, head=None):
# return self._repo.get_commits(count=count, skip=skip, head=head)
#
# @property
# def alterable_users(self):
# return self.repositoryuser_set.exclude(user=self.user)
#
# def save(self, *args, **kwargs):
# if not self.pk:
# self._repo.init_repo()
# self._repo.repo_settings_changed()
# super(Repository, self).save(*args, **kwargs)
#
# def delete(self, *args, **kwargs):
# self._repo.delete_repo(self.slug)
# super(Repository, self).delete(*args, **kwargs)
#
# class Meta:
# unique_together = ('user', 'slug')
# verbose_name = _('Repository')
# verbose_name_plural = _('Repositories')
. Output only the next line. | 'repository_list': Repository.objects.manageable_repositories( |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
admin.site.unregister(User)
class ProfileInline(admin.StackedInline):
model = Profile
extra = 1
max_num = 1
class SshPublicKeyInline(admin.TabularInline):
<|code_end|>
using the current file's imports:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from brigitte.accounts.models import Profile, SshPublicKey
and any relevant context from other files:
# Path: brigitte/accounts/models.py
# class Profile(models.Model):
# user = models.OneToOneField(User, unique=True)
# short_info = models.TextField(_('Short info'), blank=True)
#
# def __unicode__(self):
# return '%s %s' % (self.user.first_name, self.user.last_name)
#
# @property
# def first_name(self):
# return self.user.first_name
#
# @property
# def last_name(self):
# return self.user.last_name
#
# class Meta:
# verbose_name = _('Profile')
# verbose_name_plural = _('Profiles')
#
# class SshPublicKey(models.Model):
# user = models.ForeignKey(User, verbose_name=_('User'), blank=False)
# description = models.CharField(_('Description'), max_length=250, blank=True)
# can_read = models.BooleanField(_('Can read'), default=True)
# can_write = models.BooleanField(_('Can write'), default=False)
# key = models.TextField(_('Key'), blank=False, unique=True)
# key_parsed = models.TextField(_('Key (parsed)'), blank=True, unique=True, editable=False)
#
# def __unicode__(self):
# if self.description:
# return self.description
# else:
# return self.short_key
#
# def save(self, *args, **kwargs):
# self.key_parsed = self.key.split()[1]
# super(SshPublicKey, self).save(*args, **kwargs)
#
# @property
# def short_key(self):
# return self.key[:32] + '...'
#
# @property
# def can_read_html(self):
# if self.can_read:
# return mark_safe('✔')
# else:
# return mark_safe('✘')
#
# @property
# def can_write_html(self):
# if self.can_write:
# return mark_safe('✔')
# else:
# return mark_safe('✘')
#
# class Meta:
# verbose_name = _('SSH Public Key')
# verbose_name_plural = _('SSH Public Keys')
. Output only the next line. | model = SshPublicKey |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
def repository_view(can_admin=False):
def inner_repository_view(f):
def wrapped(request, user, slug, *args, **kwargs):
<|code_end|>
. Use current file imports:
from functools import wraps
from django.shortcuts import get_object_or_404
from brigitte.repositories.models import Repository
and context (classes, functions, or code) from other files:
# Path: brigitte/repositories/models.py
# class Repository(models.Model):
# user = models.ForeignKey(User, verbose_name=_('User'))
# slug = models.SlugField(_('Slug'), max_length=80, blank=False)
# title = models.CharField(_('Title'), max_length=80)
# description = models.TextField(_('Description'), blank=True)
# private = models.BooleanField(_('Private'), default=False)
# repo_type = models.CharField(_('Type'), max_length=4, choices=REPO_TYPES,
# default='git')
# last_commit_date = models.DateTimeField(blank=True, null=True)
#
# objects = RepositoryManager()
#
# def __unicode__(self):
# return self.title
#
# def get_last_commit(self):
# # TODO: cache self.last_commit with git hook ...
# last_commit = self.last_commit
# if not self.last_commit_date and last_commit:
# self.last_commit_date = last_commit.commit_date
# self.save()
# elif self.last_commit_date and last_commit and self.last_commit_date != last_commit.commit_date:
# self.last_commit_date = self.last_commit.commit_date
# self.save()
# return last_commit
#
# @property
# def private_html(self):
# if self.private:
# return mark_safe('✔')
# else:
# return mark_safe('✘')
#
# @property
# def path(self):
# if self.repo_type == 'git':
# return os.path.join(BRIGITTE_GIT_BASE_PATH, self.user.username,
# '%s.git' % self.slug)
#
# return None
#
# @property
# def short_path(self):
# if self.repo_type == 'git':
# return '%s/%s.git' % (self.user.username, self.slug)
#
# return None
#
# @property
# def _repo(self):
# if not hasattr(self, '_repo_obj'):
# self._repo_obj = get_backend(self.repo_type)(self)
# return self._repo_obj
#
# def recent_commits(self, count=10):
# return self._repo.get_commits(count=count)
#
# @property
# def last_commit(self):
# if not hasattr(self, '_last_commit'):
# self._last_commit = self._repo.last_commit
# return self._last_commit
#
# @property
# def tags(self):
# if not hasattr(self, '_tags'):
# self._tags = self._repo.tags
# return self._tags
#
# @property
# def branches(self):
# if not hasattr(self, '_branches'):
# self._branches = self._repo.branches
# return self._branches
#
# @property
# def rw_url(self):
# if self.repo_type == 'git':
# return 'git@%s:%s' % (
# Site.objects.get_current(), self.short_path)
#
# return None
#
# @property
# def ro_url(self):
# if self.repo_type == 'git':
# return 'git://%s/%s' % (Site.objects.get_current(), self.short_path)
#
# return None
#
# def get_commit(self, sha):
# return self._repo.get_commit(sha)
#
# def get_commits(self, count=10, skip=0, head=None):
# return self._repo.get_commits(count=count, skip=skip, head=head)
#
# @property
# def alterable_users(self):
# return self.repositoryuser_set.exclude(user=self.user)
#
# def save(self, *args, **kwargs):
# if not self.pk:
# self._repo.init_repo()
# self._repo.repo_settings_changed()
# super(Repository, self).save(*args, **kwargs)
#
# def delete(self, *args, **kwargs):
# self._repo.delete_repo(self.slug)
# super(Repository, self).delete(*args, **kwargs)
#
# class Meta:
# unique_together = ('user', 'slug')
# verbose_name = _('Repository')
# verbose_name_plural = _('Repositories')
. Output only the next line. | qs = Repository.objects.none() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.