Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line after this snippet: <|code_start|> }) assert ua.is_willcom() res = ua.is_bogus() assert res == expected, '%s expected, actual %s' % (expected, res) for ip, expected in ( ('210.230.128.224', True), ('61.198.128.0', False), ): yield func, ip, expected def test_extra_ip(): ctxt1 = Context(extra_willcom_ips=['192.168.0.0/24']) ua = detect({'HTTP_USER_AGENT': 'Mozilla/3.0(WILLCOM;KYOCERA/WX310K/2;1.2.7.17.000000/0.1/C100) Opera 7.0', 'REMOTE_ADDR' : '192.168.0.1', }, context=ctxt1) assert ua.is_willcom() assert ua.is_bogus() is False ctxt2 = Context(extra_willcom_ips=[]) ua = detect({'HTTP_USER_AGENT': 'Mozilla/3.0(WILLCOM;KYOCERA/WX310K/2;1.2.7.17.000000/0.1/C100) Opera 7.0', 'REMOTE_ADDR' : '192.168.0.1', }, context=ctxt2) assert ua.is_willcom() assert ua.is_bogus() is True def test_my_factory(): <|code_end|> using the current file's imports: from tests import msg from uamobile import * from uamobile.willcom import WillcomUserAgent from uamobile.factory.willcom import WillcomUserAgentFactory and any relevant context from other files: # Path: uamobile/willcom.py # class WillcomUserAgent(UserAgent): # name = 'WILLCOM' # carrier = 'WILLCOM' # short_carrier = 'W' # # def __init__(self, *args, **kwds): # super(WillcomUserAgent, self).__init__(*args, **kwds) # self.serialnumber = None # self.model_version = None # self.browser_version = None # # def get_flash_version(self): # """ # returns Flash Lite version. # """ # return None # flash_version = property(get_flash_version) # # def supports_cookie(self): # # TODO # # I'm not sure All WILLCOM phones can handle HTTP cookie. # return True # # def make_display(self): # """ # create a new Display object. # """ # return Display() # # def is_willcom(self): # return True # # def is_airhphone(self): # return True # # Path: uamobile/factory/willcom.py # class WillcomUserAgentFactory(AbstractUserAgentFactory): # device_class = WillcomUserAgent # parser = CachingWillcomUserAgentParser() . Output only the next line.
class MyWillcomUserAgent(WillcomUserAgent):
Next line prediction: <|code_start|> for ip, expected in ( ('210.230.128.224', True), ('61.198.128.0', False), ): yield func, ip, expected def test_extra_ip(): ctxt1 = Context(extra_willcom_ips=['192.168.0.0/24']) ua = detect({'HTTP_USER_AGENT': 'Mozilla/3.0(WILLCOM;KYOCERA/WX310K/2;1.2.7.17.000000/0.1/C100) Opera 7.0', 'REMOTE_ADDR' : '192.168.0.1', }, context=ctxt1) assert ua.is_willcom() assert ua.is_bogus() is False ctxt2 = Context(extra_willcom_ips=[]) ua = detect({'HTTP_USER_AGENT': 'Mozilla/3.0(WILLCOM;KYOCERA/WX310K/2;1.2.7.17.000000/0.1/C100) Opera 7.0', 'REMOTE_ADDR' : '192.168.0.1', }, context=ctxt2) assert ua.is_willcom() assert ua.is_bogus() is True def test_my_factory(): class MyWillcomUserAgent(WillcomUserAgent): def get_my_attr(self): return self.environ.get('HTTP_X_DOCOMO_UID') <|code_end|> . Use current file imports: (from tests import msg from uamobile import * from uamobile.willcom import WillcomUserAgent from uamobile.factory.willcom import WillcomUserAgentFactory) and context including class names, function names, or small code snippets from other files: # Path: uamobile/willcom.py # class WillcomUserAgent(UserAgent): # name = 'WILLCOM' # carrier = 'WILLCOM' # short_carrier = 'W' # # def __init__(self, *args, **kwds): # super(WillcomUserAgent, self).__init__(*args, **kwds) # self.serialnumber = None # self.model_version = None # self.browser_version = None # # def get_flash_version(self): # """ # returns Flash Lite version. # """ # return None # flash_version = property(get_flash_version) # # def supports_cookie(self): # # TODO # # I'm not sure All WILLCOM phones can handle HTTP cookie. # return True # # def make_display(self): # """ # create a new Display object. # """ # return Display() # # def is_willcom(self): # return True # # def is_airhphone(self): # return True # # Path: uamobile/factory/willcom.py # class WillcomUserAgentFactory(AbstractUserAgentFactory): # device_class = WillcomUserAgent # parser = CachingWillcomUserAgentParser() . Output only the next line.
class MyWillcomUserAgentFactory(WillcomUserAgentFactory):
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- class NonMobileUserAgent(UserAgent): name = 'NonMobile' carrier = 'NonMobile' short_carrier = 'N' serialnumber = None def get_flash_version(self): """ returns Flash Lite version. """ return '3.1' flash_version = property(get_flash_version) def get_name(self): return 'NonMobile' def is_nonmobile(self): return True def supports_cookie(self): return True def make_display(self): """ create a new Display object. """ <|code_end|> . Write the next line using the current file imports: from uamobile.base import UserAgent, Display and context from other files: # Path: uamobile/base.py # class UserAgent(object): # """ # Base class representing HTTTP user agent. # """ # # def __init__(self, environ, context): # try: # self.useragent = environ['HTTP_USER_AGENT'] # except KeyError, e: # self.useragent = '' # self.environ = environ # self.context = context # # self.model = '' # self.version = '' # self._display = None # # def __repr__(self): # return '<%s "%s">' % (self.__class__.__name__, self.useragent) # # def __str__(self): # return self.useragent # # def strip_serialnumber(self): # """ # strip serialnumber such as FOMA card ID of docomo # adn return a normalized User-Agent string. # """ # return self.useragent # # def get_display(self): # """ # returns Display object. # """ # if self._display is None: # self._display = self.make_display() # return self._display # display = property(get_display) # # def make_display(self): # raise NotImplementedError # # def is_docomo(self): # """ # returns True if the agent is DoCoMo. # """ # return False # # def is_ezweb(self): # """ # returns True if the agent is EZweb. # """ # return False # # def is_tuka(self): # """ # returns True if the agent is TU-Ka. # """ # return False # # def is_softbank(self): # """ # returns True if the agent is Softbank. # """ # return False # # def is_vodafone(self): # """ # returns True if the agent is Vodafone (now SotBank). # """ # return False # # def is_jphone(self): # """ # returns True if the agent is J-PHONE (now softbank). # """ # return False # # def is_willcom(self): # """ # returns True if the agent is Willcom. # """ # return False # # def is_airhphone(self): # """ # returns True if the agent is AirH'PHONE. # """ # return False # # def is_wap1(self): # return False # # def is_wap2(self): # return False # # def is_nonmobile(self): # return False # # def supports_flash(self): # """ # returns True if the agent supports Flash # """ # return self.flash_version is not None # # def supports_cookie(self): # """ # returns True if the agent supports HTTP cookie. # """ # raise NotImplementedError # # def _get_real_ip(self): # """ # get real IP address of client from REMOTE_ADDR and # HTTP_X_FORWARDED_FOR variables # """ # try: # remote_addr = self.environ['REMOTE_ADDR'] # except KeyError: # return None # # forwared_for = self.environ.get('HTTP_X_FORWARDED_FOR') # proxy_ips = self.context.get_proxy_ips() # if forwared_for and proxy_ips: # forwared_for = forwared_for.split(',', 1)[0].strip() # # # check REMOTE_ADDR is included in trusted reverse # # proxy address # for addr in proxy_ips: # if remote_addr in addr: # # override remote addr # remote_addr = forwared_for # break # # try: # return cidr.IP(remote_addr) # except ValueError: # # invalid ip address, like 'unknown' # return None # # def get_real_ip(self): # try: # return self._real_ip # except AttributeError: # self._real_ip = self._get_real_ip() # return self._real_ip # # def is_crawler(self): # """ # return True if the client is a mobile crawler # """ # remote_addr = self.get_real_ip() # if remote_addr is None: # # who knows? # return False # # for addr in self.context.get_ip('crawler'): # if remote_addr in addr: # return True # # return False # # def is_bogus(self): # """ # return True if the client isn't accessing via gateways of # japanese mobile carrier # """ # remote_addr = self.get_real_ip() # if remote_addr is None: # return True # # for addr in self.context.get_ip(self.carrier): # if remote_addr in addr: # return False # # return True # # class Display(object): # """ # Display information for mobile devices. # """ # # def __init__(self, width=240, height=320, depth=262144, color=1, # width_bytes=None, height_bytes=None): # self.width = width # self.height = height # self.depth = depth # self.color = color # self.width_bytes = width_bytes # self.height_bytes = height_bytes # # def is_qvga(self): # return self.width >= 240 # # def is_vga(self): # return self.width >= 480 , which may include functions, classes, or code. Output only the next line.
return Display()
Based on the snippet: <|code_start|> return DATA[self.model] except KeyError: return '2.0' flash_version = property(get_flash_version) def supports_cookie(self): return True def make_display(self): """ create a Display object. """ env = self.environ try: width, height = map(int, env['HTTP_X_UP_DEVCAP_SCREENPIXELS'].split(',', 1)) except (KeyError, ValueError), e: width = None height = None try: color = env['HTTP_X_UP_DEVCAP_ISCOLOR'] == '1' except KeyError: color = False try: sd = env['HTTP_X_UP_DEVCAP_SCREENDEPTH'].split(',', 1) depth = sd[0] and (2 ** int(sd[0])) or 0 except (KeyError, ValueError): depth = None <|code_end|> , predict the immediate next line with the help of imports: from uamobile.base import UserAgent, Display from uamobile.data.flash.ezweb import DATA and context (classes, functions, sometimes code) from other files: # Path: uamobile/base.py # class UserAgent(object): # """ # Base class representing HTTTP user agent. # """ # # def __init__(self, environ, context): # try: # self.useragent = environ['HTTP_USER_AGENT'] # except KeyError, e: # self.useragent = '' # self.environ = environ # self.context = context # # self.model = '' # self.version = '' # self._display = None # # def __repr__(self): # return '<%s "%s">' % (self.__class__.__name__, self.useragent) # # def __str__(self): # return self.useragent # # def strip_serialnumber(self): # """ # strip serialnumber such as FOMA card ID of docomo # adn return a normalized User-Agent string. # """ # return self.useragent # # def get_display(self): # """ # returns Display object. # """ # if self._display is None: # self._display = self.make_display() # return self._display # display = property(get_display) # # def make_display(self): # raise NotImplementedError # # def is_docomo(self): # """ # returns True if the agent is DoCoMo. # """ # return False # # def is_ezweb(self): # """ # returns True if the agent is EZweb. # """ # return False # # def is_tuka(self): # """ # returns True if the agent is TU-Ka. # """ # return False # # def is_softbank(self): # """ # returns True if the agent is Softbank. # """ # return False # # def is_vodafone(self): # """ # returns True if the agent is Vodafone (now SotBank). # """ # return False # # def is_jphone(self): # """ # returns True if the agent is J-PHONE (now softbank). # """ # return False # # def is_willcom(self): # """ # returns True if the agent is Willcom. # """ # return False # # def is_airhphone(self): # """ # returns True if the agent is AirH'PHONE. # """ # return False # # def is_wap1(self): # return False # # def is_wap2(self): # return False # # def is_nonmobile(self): # return False # # def supports_flash(self): # """ # returns True if the agent supports Flash # """ # return self.flash_version is not None # # def supports_cookie(self): # """ # returns True if the agent supports HTTP cookie. # """ # raise NotImplementedError # # def _get_real_ip(self): # """ # get real IP address of client from REMOTE_ADDR and # HTTP_X_FORWARDED_FOR variables # """ # try: # remote_addr = self.environ['REMOTE_ADDR'] # except KeyError: # return None # # forwared_for = self.environ.get('HTTP_X_FORWARDED_FOR') # proxy_ips = self.context.get_proxy_ips() # if forwared_for and proxy_ips: # forwared_for = forwared_for.split(',', 1)[0].strip() # # # check REMOTE_ADDR is included in trusted reverse # # proxy address # for addr in proxy_ips: # if remote_addr in addr: # # override remote addr # remote_addr = forwared_for # break # # try: # return cidr.IP(remote_addr) # except ValueError: # # invalid ip address, like 'unknown' # return None # # def get_real_ip(self): # try: # return self._real_ip # except AttributeError: # self._real_ip = self._get_real_ip() # return self._real_ip # # def is_crawler(self): # """ # return True if the client is a mobile crawler # """ # remote_addr = self.get_real_ip() # if remote_addr is None: # # who knows? # return False # # for addr in self.context.get_ip('crawler'): # if remote_addr in addr: # return True # # return False # # def is_bogus(self): # """ # return True if the client isn't accessing via gateways of # japanese mobile carrier # """ # remote_addr = self.get_real_ip() # if remote_addr is None: # return True # # for addr in self.context.get_ip(self.carrier): # if remote_addr in addr: # return False # # return True # # class Display(object): # """ # Display information for mobile devices. # """ # # def __init__(self, width=240, height=320, depth=262144, color=1, # width_bytes=None, height_bytes=None): # self.width = width # self.height = height # self.depth = depth # self.color = color # self.width_bytes = width_bytes # self.height_bytes = height_bytes # # def is_qvga(self): # return self.width >= 240 # # def is_vga(self): # return self.width >= 480 . Output only the next line.
return Display(width=width, height=height, color=color, depth=depth)
Given snippet: <|code_start|># -*- coding: utf-8 -*- WILLCOM_RE = re.compile(r'^Mozilla/3\.0\((?:DDIPOCKET|WILLCOM);(.*)\)') WILLCOM_CACHE_RE = re.compile(r'^[Cc](\d+)') WINDOWS_CE_RE = re.compile(r'^Mozilla/4\.0 \((.*)\)') <|code_end|> , continue by predicting the next line. Consider current file imports: import re from uamobile.parser.base import UserAgentParser and context: # Path: uamobile/parser/base.py # class UserAgentParser(object): # def parse(self, useragent): # raise NotImplementedError() which might include code, classes, or functions. Output only the next line.
class WillcomUserAgentParser(UserAgentParser):
Next line prediction: <|code_start|># -*- coding: utf-8 -*- class WillcomUserAgent(UserAgent): name = 'WILLCOM' carrier = 'WILLCOM' short_carrier = 'W' def __init__(self, *args, **kwds): super(WillcomUserAgent, self).__init__(*args, **kwds) self.serialnumber = None self.model_version = None self.browser_version = None def get_flash_version(self): """ returns Flash Lite version. """ return None flash_version = property(get_flash_version) def supports_cookie(self): # TODO # I'm not sure All WILLCOM phones can handle HTTP cookie. return True def make_display(self): """ create a new Display object. """ <|code_end|> . Use current file imports: (from uamobile.base import UserAgent, Display) and context including class names, function names, or small code snippets from other files: # Path: uamobile/base.py # class UserAgent(object): # """ # Base class representing HTTTP user agent. # """ # # def __init__(self, environ, context): # try: # self.useragent = environ['HTTP_USER_AGENT'] # except KeyError, e: # self.useragent = '' # self.environ = environ # self.context = context # # self.model = '' # self.version = '' # self._display = None # # def __repr__(self): # return '<%s "%s">' % (self.__class__.__name__, self.useragent) # # def __str__(self): # return self.useragent # # def strip_serialnumber(self): # """ # strip serialnumber such as FOMA card ID of docomo # adn return a normalized User-Agent string. # """ # return self.useragent # # def get_display(self): # """ # returns Display object. # """ # if self._display is None: # self._display = self.make_display() # return self._display # display = property(get_display) # # def make_display(self): # raise NotImplementedError # # def is_docomo(self): # """ # returns True if the agent is DoCoMo. # """ # return False # # def is_ezweb(self): # """ # returns True if the agent is EZweb. # """ # return False # # def is_tuka(self): # """ # returns True if the agent is TU-Ka. # """ # return False # # def is_softbank(self): # """ # returns True if the agent is Softbank. # """ # return False # # def is_vodafone(self): # """ # returns True if the agent is Vodafone (now SotBank). # """ # return False # # def is_jphone(self): # """ # returns True if the agent is J-PHONE (now softbank). # """ # return False # # def is_willcom(self): # """ # returns True if the agent is Willcom. # """ # return False # # def is_airhphone(self): # """ # returns True if the agent is AirH'PHONE. # """ # return False # # def is_wap1(self): # return False # # def is_wap2(self): # return False # # def is_nonmobile(self): # return False # # def supports_flash(self): # """ # returns True if the agent supports Flash # """ # return self.flash_version is not None # # def supports_cookie(self): # """ # returns True if the agent supports HTTP cookie. # """ # raise NotImplementedError # # def _get_real_ip(self): # """ # get real IP address of client from REMOTE_ADDR and # HTTP_X_FORWARDED_FOR variables # """ # try: # remote_addr = self.environ['REMOTE_ADDR'] # except KeyError: # return None # # forwared_for = self.environ.get('HTTP_X_FORWARDED_FOR') # proxy_ips = self.context.get_proxy_ips() # if forwared_for and proxy_ips: # forwared_for = forwared_for.split(',', 1)[0].strip() # # # check REMOTE_ADDR is included in trusted reverse # # proxy address # for addr in proxy_ips: # if remote_addr in addr: # # override remote addr # remote_addr = forwared_for # break # # try: # return cidr.IP(remote_addr) # except ValueError: # # invalid ip address, like 'unknown' # return None # # def get_real_ip(self): # try: # return self._real_ip # except AttributeError: # self._real_ip = self._get_real_ip() # return self._real_ip # # def is_crawler(self): # """ # return True if the client is a mobile crawler # """ # remote_addr = self.get_real_ip() # if remote_addr is None: # # who knows? # return False # # for addr in self.context.get_ip('crawler'): # if remote_addr in addr: # return True # # return False # # def is_bogus(self): # """ # return True if the client isn't accessing via gateways of # japanese mobile carrier # """ # remote_addr = self.get_real_ip() # if remote_addr is None: # return True # # for addr in self.context.get_ip(self.carrier): # if remote_addr in addr: # return False # # return True # # class Display(object): # """ # Display information for mobile devices. # """ # # def __init__(self, width=240, height=320, depth=262144, color=1, # width_bytes=None, height_bytes=None): # self.width = width # self.height = height # self.depth = depth # self.color = color # self.width_bytes = width_bytes # self.height_bytes = height_bytes # # def is_qvga(self): # return self.width >= 240 # # def is_vga(self): # return self.width >= 480 . Output only the next line.
return Display()
Predict the next line after this snippet: <|code_start|> }) assert ua.is_ezweb() res = ua.is_bogus() assert res == expected, '%s expected, actual %s' % (expected, res) for ip, expected in ( ('210.230.128.224', False), ('210.153.84.0', True), ): yield func, ip, expected def test_extra_ip(): ctxt1 = Context(extra_ezweb_ips=['192.168.0.0/24']) ua = detect({'HTTP_USER_AGENT': 'KDDI-HI36 UP.Browser/6.2.0.10.4 (GUI) MMP/2.0', 'REMOTE_ADDR' : '192.168.0.1', }, context=ctxt1) assert ua.is_ezweb() assert ua.is_bogus() is False ctxt2 = Context(extra_ezweb_ips=[]) ua = detect({'HTTP_USER_AGENT': 'KDDI-HI36 UP.Browser/6.2.0.10.4 (GUI) MMP/2.0', 'REMOTE_ADDR' : '192.168.0.1', }, context=ctxt2) assert ua.is_ezweb() assert ua.is_bogus() is True def test_my_factory(): <|code_end|> using the current file's imports: from tests import msg from uamobile import * from uamobile.ezweb import EZwebUserAgent from uamobile.factory.ezweb import EZwebUserAgentFactory and any relevant context from other files: # Path: uamobile/ezweb.py # class EZwebUserAgent(UserAgent): # carrier = 'EZweb' # short_carrier = 'E' # # def get_flash_version(self): # """ # returns Flash Lite version. # """ # from uamobile.data.flash.ezweb import DATA # try: # return DATA[self.model] # except KeyError: # return '2.0' # flash_version = property(get_flash_version) # # def supports_cookie(self): # return True # # def make_display(self): # """ # create a Display object. # """ # env = self.environ # try: # width, height = map(int, env['HTTP_X_UP_DEVCAP_SCREENPIXELS'].split(',', 1)) # except (KeyError, ValueError), e: # width = None # height = None # # try: # color = env['HTTP_X_UP_DEVCAP_ISCOLOR'] == '1' # except KeyError: # color = False # # try: # sd = env['HTTP_X_UP_DEVCAP_SCREENDEPTH'].split(',', 1) # depth = sd[0] and (2 ** int(sd[0])) or 0 # except (KeyError, ValueError): # depth = None # # return Display(width=width, height=height, color=color, depth=depth) # # def is_ezweb(self): # return True # # def get_serialnumber(self): # """ # return the EZweb subscriber ID. # if no subscriber ID is available, returns None. # """ # try: # return self.environ['HTTP_X_UP_SUBNO'] # except KeyError: # return None # serialnumber = property(get_serialnumber) # # def is_xhtml_compliant(self): # """ # returns whether it's XHTML compliant or not. # """ # return self.xhtml_compliant # # def is_win(self): # """ # returns whether the agent is CDMA 1X WIN or not. # """ # return self.device_id[2:3] == '3' # # def is_wap1(self): # return not self.is_wap2() # # def is_wap2(self): # return self.xhtml_compliant # # Path: uamobile/factory/ezweb.py # class EZwebUserAgentFactory(AbstractUserAgentFactory): # device_class = EZwebUserAgent # parser = CachingEZwebUserAgentParser() . Output only the next line.
class MyEZwebUserAgent(EZwebUserAgent):
Given the code snippet: <|code_start|> for ip, expected in ( ('210.230.128.224', False), ('210.153.84.0', True), ): yield func, ip, expected def test_extra_ip(): ctxt1 = Context(extra_ezweb_ips=['192.168.0.0/24']) ua = detect({'HTTP_USER_AGENT': 'KDDI-HI36 UP.Browser/6.2.0.10.4 (GUI) MMP/2.0', 'REMOTE_ADDR' : '192.168.0.1', }, context=ctxt1) assert ua.is_ezweb() assert ua.is_bogus() is False ctxt2 = Context(extra_ezweb_ips=[]) ua = detect({'HTTP_USER_AGENT': 'KDDI-HI36 UP.Browser/6.2.0.10.4 (GUI) MMP/2.0', 'REMOTE_ADDR' : '192.168.0.1', }, context=ctxt2) assert ua.is_ezweb() assert ua.is_bogus() is True def test_my_factory(): class MyEZwebUserAgent(EZwebUserAgent): def get_my_attr(self): return self.environ.get('HTTP_X_DOCOMO_UID') <|code_end|> , generate the next line using the imports in this file: from tests import msg from uamobile import * from uamobile.ezweb import EZwebUserAgent from uamobile.factory.ezweb import EZwebUserAgentFactory and context (functions, classes, or occasionally code) from other files: # Path: uamobile/ezweb.py # class EZwebUserAgent(UserAgent): # carrier = 'EZweb' # short_carrier = 'E' # # def get_flash_version(self): # """ # returns Flash Lite version. # """ # from uamobile.data.flash.ezweb import DATA # try: # return DATA[self.model] # except KeyError: # return '2.0' # flash_version = property(get_flash_version) # # def supports_cookie(self): # return True # # def make_display(self): # """ # create a Display object. # """ # env = self.environ # try: # width, height = map(int, env['HTTP_X_UP_DEVCAP_SCREENPIXELS'].split(',', 1)) # except (KeyError, ValueError), e: # width = None # height = None # # try: # color = env['HTTP_X_UP_DEVCAP_ISCOLOR'] == '1' # except KeyError: # color = False # # try: # sd = env['HTTP_X_UP_DEVCAP_SCREENDEPTH'].split(',', 1) # depth = sd[0] and (2 ** int(sd[0])) or 0 # except (KeyError, ValueError): # depth = None # # return Display(width=width, height=height, color=color, depth=depth) # # def is_ezweb(self): # return True # # def get_serialnumber(self): # """ # return the EZweb subscriber ID. # if no subscriber ID is available, returns None. # """ # try: # return self.environ['HTTP_X_UP_SUBNO'] # except KeyError: # return None # serialnumber = property(get_serialnumber) # # def is_xhtml_compliant(self): # """ # returns whether it's XHTML compliant or not. # """ # return self.xhtml_compliant # # def is_win(self): # """ # returns whether the agent is CDMA 1X WIN or not. # """ # return self.device_id[2:3] == '3' # # def is_wap1(self): # return not self.is_wap2() # # def is_wap2(self): # return self.xhtml_compliant # # Path: uamobile/factory/ezweb.py # class EZwebUserAgentFactory(AbstractUserAgentFactory): # device_class = EZwebUserAgent # parser = CachingEZwebUserAgentParser() . Output only the next line.
class MyEZwebUserAgentFactory(EZwebUserAgentFactory):
Predict the next line after this snippet: <|code_start|> FOMA_SERIES_4DIGITS_RE = re.compile(r'\d{4}') FOMA_SERIES_3DIGITS_RE = re.compile(r'(\d{3}i|\d{2}[ABC][23]?)') DOCOMO_COMMENT_RE = re.compile(r'\((.+?)\)') DOCOMO_DISPLAY_BYTES_RE = re.compile(r'^W(\d+)H(\d+)$') DOCOMO_HTML_VERSION_LIST = [ (re.compile('[DFNP]501i'), '1.0'), (re.compile('502i|821i|209i|651|691i|(?:F|N|P|KO)210i|^F671i$'), '2.0'), (re.compile('(?:D210i|SO210i)|503i|211i|SH251i|692i|200[12]|2101V'), '3.0'), (re.compile('504i|251i|^F671iS$|212i|2051|2102V|661i|2701|672i|SO213i|850i'), '4.0'), (re.compile('eggy|P751v'), '3.2'), (re.compile('505i|252i|900i|506i|880i|253i|P213i|901i|700i|851i$|701i|881i|^SA800i$|600i|^L601i$|^M702i(?:S|G)$|^L602i$'), '5.0'), (re.compile('902i|702i|851iWM|882i|883i$|^N601i$|^D800iDS$|^P70[34]imyu$'), '6.0'), (re.compile('883iES|903i|703i|904i|704i'), '7.0'), (re.compile('905i|705i'), '7.1'), (re.compile('906i|[01][0-9]A[23]?'), '7.2'), ] def _get_docomo_html_version(model): """ returns supported HTML version like '3.0'. if unkwon, return None. """ for pattern, value in DOCOMO_HTML_VERSION_LIST: if pattern.search(model): return value return None <|code_end|> using the current file's imports: import re from uamobile.parser.base import UserAgentParser and any relevant context from other files: # Path: uamobile/parser/base.py # class UserAgentParser(object): # def parse(self, useragent): # raise NotImplementedError() . Output only the next line.
class DoCoMoUserAgentParser(UserAgentParser):
Given snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function def locate_discontinuity(grid, y, consider, trnsfm=lambda x: x, ntrail=2): y = np.asarray(y, dtype=np.float64) dy = np.diff(y) tg = trnsfm(grid) dtg = np.diff(tg) err = np.zeros(y.size) for d in ("fw", "bw"): <|code_end|> , continue by predicting the next line. Consider current file imports: import numpy as np from ..util import interpolate_ahead, avg_stddev and context: # Path: finitediff/util.py # def interpolate_ahead(x, y, n, direction="fw"): # if not np.all(np.diff(x) > 0): # raise ValueError("x not strictly monotonic.") # # if direction == "both": # y1, slc1 = interpolate_ahead(x, y, n, "fw") # y2, slc2 = interpolate_ahead(x, y, n, "bw") # y = np.zeros_like(x) # y[slc1] = y1 # y[slc2] += y2 # y[slc1.start : slc2.stop] /= 2 # return y, slice(None, None) # elif direction == "fw": # forward = True # elif direction == "bw": # forward = False # else: # raise ValueError("Unknown direction: %s" % direction) # # rev = slice(None, None, 1) if forward else slice(None, None, -1) # values = [] # for idx, (xv, yv) in enumerate(zip(x[rev][n:], y[rev][n:])): # _x = np.ascontiguousarray(x[rev][idx : idx + n], dtype=np.float64) # _y = np.ascontiguousarray(y[rev][idx : idx + n], dtype=np.float64) # _v = np.array([xv]) # values.append( # interpolate_by_finite_diff(_x, _y, _v, maxorder=0, ntail=n, nhead=0) # ) # return np.array(values[rev]).squeeze(), slice(n, None) if forward else slice( # None, -n # ) # # def avg_stddev(arr, w): # """Calculates the average and standard deviation. # # Parameters # ---------- # arr : array_like # Values. # w : array_like # Weights. # # Returns # ------- # tuple of 2 floats (average & standard deviation) # # """ # avg, wsum = np.average(arr, weights=w, returned=True) # res = arr - avg # stddev = np.sqrt(np.sum(np.dot(w, np.square(res)) / (res.size - 1) / wsum)) # return avg, stddev which might include code, classes, or functions. Output only the next line.
est, slc = interpolate_ahead(tg, y, ntrail, d)
Next line prediction: <|code_start|># -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function def locate_discontinuity(grid, y, consider, trnsfm=lambda x: x, ntrail=2): y = np.asarray(y, dtype=np.float64) dy = np.diff(y) tg = trnsfm(grid) dtg = np.diff(tg) err = np.zeros(y.size) for d in ("fw", "bw"): est, slc = interpolate_ahead(tg, y, ntrail, d) start = (ntrail - 1) if d == "fw" else 0 stop = -(ntrail - 1) if d == "bw" else None err[slc] += np.abs(y[slc] - est) / dtg[start:stop] * dy[start:stop] imax = np.argsort(err)[-consider:][::-1] return [(tg[m], err[m]) for m in imax] def pool_discontinuity_approx(loc_res, consistency_criterion=10): points = np.array(loc_res) w1 = np.abs(points[:, 1]) <|code_end|> . Use current file imports: (import numpy as np from ..util import interpolate_ahead, avg_stddev) and context including class names, function names, or small code snippets from other files: # Path: finitediff/util.py # def interpolate_ahead(x, y, n, direction="fw"): # if not np.all(np.diff(x) > 0): # raise ValueError("x not strictly monotonic.") # # if direction == "both": # y1, slc1 = interpolate_ahead(x, y, n, "fw") # y2, slc2 = interpolate_ahead(x, y, n, "bw") # y = np.zeros_like(x) # y[slc1] = y1 # y[slc2] += y2 # y[slc1.start : slc2.stop] /= 2 # return y, slice(None, None) # elif direction == "fw": # forward = True # elif direction == "bw": # forward = False # else: # raise ValueError("Unknown direction: %s" % direction) # # rev = slice(None, None, 1) if forward else slice(None, None, -1) # values = [] # for idx, (xv, yv) in enumerate(zip(x[rev][n:], y[rev][n:])): # _x = np.ascontiguousarray(x[rev][idx : idx + n], dtype=np.float64) # _y = np.ascontiguousarray(y[rev][idx : idx + n], dtype=np.float64) # _v = np.array([xv]) # values.append( # interpolate_by_finite_diff(_x, _y, _v, maxorder=0, ntail=n, nhead=0) # ) # return np.array(values[rev]).squeeze(), slice(n, None) if forward else slice( # None, -n # ) # # def avg_stddev(arr, w): # """Calculates the average and standard deviation. # # Parameters # ---------- # arr : array_like # Values. # w : array_like # Weights. # # Returns # ------- # tuple of 2 floats (average & standard deviation) # # """ # avg, wsum = np.average(arr, weights=w, returned=True) # res = arr - avg # stddev = np.sqrt(np.sum(np.dot(w, np.square(res)) / (res.size - 1) / wsum)) # return avg, stddev . Output only the next line.
return avg_stddev(points[:, 0], w1)
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function def plot_convergence(key, values, cb, metric=None, xstart=0, xstop=2, **kwargs): if key in kwargs: raise ValueError("Cannot have key=%s when given in kwargs" % key) fig, axes = plt.subplots( 1, len(values), figsize=(16, 5), sharey=True, gridspec_kw={"wspace": 0} ) scores, grid_sizes = [], [] if key is None and len(values) != 1: raise ValueError("Not considering key") for val, ax in zip(values, np.atleast_1d(axes)): if key is not None: kwargs[key] = val <|code_end|> . Use current file imports: import numpy as np import matplotlib.pyplot as plt from .make import adapted_grid and context (classes, functions, or code) from other files: # Path: finitediff/grid/make.py # def adapted_grid(xstart, xstop, cb, grid_additions=(50, 50), **kwargs): # """ " Creates an adapted (1D) grid by subsequent subgrid insertions. # # Parameters # ---------- # xstart : float # xstop : float # cb : callbable # Function to be evaluated (note that noise is handled poorly). # grid_additions : iterable of ints (even numbers) # Sequence specifying how many gridpoints to add each time. # \\*\\*kwargs : see :func:`refine_grid`. # """ # grid = np.linspace(xstart, xstop, grid_additions[0]) # return refine_grid(grid, cb, grid_additions=grid_additions[1:], **kwargs) . Output only the next line.
grid, results = adapted_grid(xstart, xstop, cb, metric=metric, **kwargs)
Next line prediction: <|code_start|> def test_locate_discontinuity__pool_discontinuity_approx(): for snr in [False, True]: loc_res = locate_discontinuity( <|code_end|> . Use current file imports: (from .. import adapted_grid from ..util import locate_discontinuity, pool_discontinuity_approx from ._common import g3) and context including class names, function names, or small code snippets from other files: # Path: finitediff/grid/make.py # def adapted_grid(xstart, xstop, cb, grid_additions=(50, 50), **kwargs): # """ " Creates an adapted (1D) grid by subsequent subgrid insertions. # # Parameters # ---------- # xstart : float # xstop : float # cb : callbable # Function to be evaluated (note that noise is handled poorly). # grid_additions : iterable of ints (even numbers) # Sequence specifying how many gridpoints to add each time. # \\*\\*kwargs : see :func:`refine_grid`. # """ # grid = np.linspace(xstart, xstop, grid_additions[0]) # return refine_grid(grid, cb, grid_additions=grid_additions[1:], **kwargs) # # Path: finitediff/grid/util.py # def locate_discontinuity(grid, y, consider, trnsfm=lambda x: x, ntrail=2): # y = np.asarray(y, dtype=np.float64) # dy = np.diff(y) # tg = trnsfm(grid) # dtg = np.diff(tg) # err = np.zeros(y.size) # for d in ("fw", "bw"): # est, slc = interpolate_ahead(tg, y, ntrail, d) # start = (ntrail - 1) if d == "fw" else 0 # stop = -(ntrail - 1) if d == "bw" else None # err[slc] += np.abs(y[slc] - est) / dtg[start:stop] * dy[start:stop] # imax = np.argsort(err)[-consider:][::-1] # return [(tg[m], err[m]) for m in imax] # # def pool_discontinuity_approx(loc_res, consistency_criterion=10): # points = np.array(loc_res) # w1 = np.abs(points[:, 1]) # return avg_stddev(points[:, 0], w1) # # Path: finitediff/grid/tests/_common.py # def sigm(x, m, o, n): # def g(x): # def g2(x): . Output only the next line.
*adapted_grid(0, 10, g3, grid_additions=(16,) * 8, snr=snr), consider=5
Given the code snippet: <|code_start|> def test_locate_discontinuity__pool_discontinuity_approx(): for snr in [False, True]: loc_res = locate_discontinuity( *adapted_grid(0, 10, g3, grid_additions=(16,) * 8, snr=snr), consider=5 ) <|code_end|> , generate the next line using the imports in this file: from .. import adapted_grid from ..util import locate_discontinuity, pool_discontinuity_approx from ._common import g3 and context (functions, classes, or occasionally code) from other files: # Path: finitediff/grid/make.py # def adapted_grid(xstart, xstop, cb, grid_additions=(50, 50), **kwargs): # """ " Creates an adapted (1D) grid by subsequent subgrid insertions. # # Parameters # ---------- # xstart : float # xstop : float # cb : callbable # Function to be evaluated (note that noise is handled poorly). # grid_additions : iterable of ints (even numbers) # Sequence specifying how many gridpoints to add each time. # \\*\\*kwargs : see :func:`refine_grid`. # """ # grid = np.linspace(xstart, xstop, grid_additions[0]) # return refine_grid(grid, cb, grid_additions=grid_additions[1:], **kwargs) # # Path: finitediff/grid/util.py # def locate_discontinuity(grid, y, consider, trnsfm=lambda x: x, ntrail=2): # y = np.asarray(y, dtype=np.float64) # dy = np.diff(y) # tg = trnsfm(grid) # dtg = np.diff(tg) # err = np.zeros(y.size) # for d in ("fw", "bw"): # est, slc = interpolate_ahead(tg, y, ntrail, d) # start = (ntrail - 1) if d == "fw" else 0 # stop = -(ntrail - 1) if d == "bw" else None # err[slc] += np.abs(y[slc] - est) / dtg[start:stop] * dy[start:stop] # imax = np.argsort(err)[-consider:][::-1] # return [(tg[m], err[m]) for m in imax] # # def pool_discontinuity_approx(loc_res, consistency_criterion=10): # points = np.array(loc_res) # w1 = np.abs(points[:, 1]) # return avg_stddev(points[:, 0], w1) # # Path: finitediff/grid/tests/_common.py # def sigm(x, m, o, n): # def g(x): # def g2(x): . Output only the next line.
avg, s = pool_discontinuity_approx(loc_res)
Given snippet: <|code_start|> def test_locate_discontinuity__pool_discontinuity_approx(): for snr in [False, True]: loc_res = locate_discontinuity( <|code_end|> , continue by predicting the next line. Consider current file imports: from .. import adapted_grid from ..util import locate_discontinuity, pool_discontinuity_approx from ._common import g3 and context: # Path: finitediff/grid/make.py # def adapted_grid(xstart, xstop, cb, grid_additions=(50, 50), **kwargs): # """ " Creates an adapted (1D) grid by subsequent subgrid insertions. # # Parameters # ---------- # xstart : float # xstop : float # cb : callbable # Function to be evaluated (note that noise is handled poorly). # grid_additions : iterable of ints (even numbers) # Sequence specifying how many gridpoints to add each time. # \\*\\*kwargs : see :func:`refine_grid`. # """ # grid = np.linspace(xstart, xstop, grid_additions[0]) # return refine_grid(grid, cb, grid_additions=grid_additions[1:], **kwargs) # # Path: finitediff/grid/util.py # def locate_discontinuity(grid, y, consider, trnsfm=lambda x: x, ntrail=2): # y = np.asarray(y, dtype=np.float64) # dy = np.diff(y) # tg = trnsfm(grid) # dtg = np.diff(tg) # err = np.zeros(y.size) # for d in ("fw", "bw"): # est, slc = interpolate_ahead(tg, y, ntrail, d) # start = (ntrail - 1) if d == "fw" else 0 # stop = -(ntrail - 1) if d == "bw" else None # err[slc] += np.abs(y[slc] - est) / dtg[start:stop] * dy[start:stop] # imax = np.argsort(err)[-consider:][::-1] # return [(tg[m], err[m]) for m in imax] # # def pool_discontinuity_approx(loc_res, consistency_criterion=10): # points = np.array(loc_res) # w1 = np.abs(points[:, 1]) # return avg_stddev(points[:, 0], w1) # # Path: finitediff/grid/tests/_common.py # def sigm(x, m, o, n): # def g(x): # def g2(x): which might include code, classes, or functions. Output only the next line.
*adapted_grid(0, 10, g3, grid_additions=(16,) * 8, snr=snr), consider=5
Predict the next line for this snippet: <|code_start|> ystart, ystop = 0, 0 for yslc in yslices: ystop += yslc.stop - yslc.start nextresults[yslc] = newresults[ystart:ystop] nexty[yslc] = newy[ystart:ystop] ystart = ystop return nextgrid, nextresults, nexty results = cb(grid) y = np.array( results if metric is None else [metric(r) for r in results], dtype=np.float64 ) for na in grid_additions: if extremum_refinement: extremum_cb, extremum_n, predicate_cb = extremum_refinement argext = extremum_cb(y) if predicate_cb(y, argext): additions = np.zeros(grid.size - 1, dtype=int) if argext > 0: # left of additions[argext - 1] = extremum_n elif argext < grid.size - 1: # right of additions[argext] = extremum_n grid, results, y = add_to(additions, grid, results, y) additions = np.zeros(grid.size - 1, dtype=int) done = True if atol is not None or rtol is not None else False slcs, errs = [], [] for direction in ("fw", "bw"): <|code_end|> with the help of current file imports: import numpy as np from ..util import interpolate_ahead and context from other files: # Path: finitediff/util.py # def interpolate_ahead(x, y, n, direction="fw"): # if not np.all(np.diff(x) > 0): # raise ValueError("x not strictly monotonic.") # # if direction == "both": # y1, slc1 = interpolate_ahead(x, y, n, "fw") # y2, slc2 = interpolate_ahead(x, y, n, "bw") # y = np.zeros_like(x) # y[slc1] = y1 # y[slc2] += y2 # y[slc1.start : slc2.stop] /= 2 # return y, slice(None, None) # elif direction == "fw": # forward = True # elif direction == "bw": # forward = False # else: # raise ValueError("Unknown direction: %s" % direction) # # rev = slice(None, None, 1) if forward else slice(None, None, -1) # values = [] # for idx, (xv, yv) in enumerate(zip(x[rev][n:], y[rev][n:])): # _x = np.ascontiguousarray(x[rev][idx : idx + n], dtype=np.float64) # _y = np.ascontiguousarray(y[rev][idx : idx + n], dtype=np.float64) # _v = np.array([xv]) # values.append( # interpolate_by_finite_diff(_x, _y, _v, maxorder=0, ntail=n, nhead=0) # ) # return np.array(values[rev]).squeeze(), slice(n, None) if forward else slice( # None, -n # ) , which may contain function names, class names, or code. Output only the next line.
est, slc = interpolate_ahead(grid, y, ntrail, direction)
Continue the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: delo # @Date: 2014-02-17 21:52:20 # @Email: deloeating@gmail.com # @Last modified by: Sai # @Last modified time: 2014-03-02 15:35:42 @fixture def confData(request): mpconfig.MoePadConfKey = "MoePadConfTest" <|code_end|> . Use current file imports: import moedjpack.moepad.mpconf as mpconfig from moedjpack.moepad.mputils import rs from pytest import fixture and context (classes, functions, or code) from other files: # Path: moedjpack/moepad/mputils.py # def sub_dict(somedict, somekeys, default=None): # def loggerInit(logfile): # def utcnow(): # def _deletePrefix(key): # def create_default_db(): . Output only the next line.
rs.hmset(mpconfig.MoePadConfKey,
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: delo # @Date: 2014-02-17 21:36:42 # @Email: deloeating@gmail.com # @Last modified by: Sai # @Last modified time: 2014-03-02 15:35:55 def test_subdict(): a = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'} keys = ['k1', 'k3'] <|code_end|> using the current file's imports: import logging import redis from moedjpack.moepad.mputils import sub_dict, loggerInit, rs, logger and any relevant context from other files: # Path: moedjpack/moepad/mputils.py # def sub_dict(somedict, somekeys, default=None): # def loggerInit(logfile): # def utcnow(): # def _deletePrefix(key): # def create_default_db(): . Output only the next line.
assert sub_dict(a, keys) == {'k1': 'v1', 'k3': 'v3'}
Here is a snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: delo # @Date: 2014-02-17 21:36:42 # @Email: deloeating@gmail.com # @Last modified by: Sai # @Last modified time: 2014-03-02 15:35:55 def test_subdict(): a = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'} keys = ['k1', 'k3'] assert sub_dict(a, keys) == {'k1': 'v1', 'k3': 'v3'} def test_loggerInit(): <|code_end|> . Write the next line using the current file imports: import logging import redis from moedjpack.moepad.mputils import sub_dict, loggerInit, rs, logger and context from other files: # Path: moedjpack/moepad/mputils.py # def sub_dict(somedict, somekeys, default=None): # def loggerInit(logfile): # def utcnow(): # def _deletePrefix(key): # def create_default_db(): , which may include functions, classes, or code. Output only the next line.
tlogger = loggerInit("test.log")
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- log = logging.getLogger('moepad') def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() # new user created return HttpResponseRedirect("/accounts/login/") else: form = UserCreationForm() return render_to_response("registration/register.html", {'form': form}, context_instance=RequestContext(request)) @login_required def index(request): if request.method == 'POST': form = MPConfigForm(request.POST) if form.is_valid(): <|code_end|> with the help of current file imports: import feedparser import datetime import logging import redis import json from django.http import HttpResponse, Http404 from django.shortcuts import * from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.forms import UserCreationForm from forms import MPConfigForm, ForbiddenForm from moedjpack.moepad.mputils import rs from moedjpack.moepad.mpdefs import * and context from other files: # Path: moedjpack/moepad/mputils.py # def sub_dict(somedict, somekeys, default=None): # def loggerInit(logfile): # def utcnow(): # def _deletePrefix(key): # def create_default_db(): , which may contain function names, class names, or code. Output only the next line.
rs.hmset("MoePadConf", request.POST)
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- _dir = os.path.join(os.path.dirname(__file__), os.path.pardir) logfile = os.path.join(_dir, "MoePad.log") def showlog(): os.system("tail -20 %s" % logfile) def show_verifying(): <|code_end|> using the current file's imports: import os from moedjpack.moepad.mputils import rs from moedjpack.moepad.mpdefs import * and any relevant context from other files: # Path: moedjpack/moepad/mputils.py # def sub_dict(somedict, somekeys, default=None): # def loggerInit(logfile): # def utcnow(): # def _deletePrefix(key): # def create_default_db(): . Output only the next line.
verifying_items = rs.zrange(VERIFYING_SET, 0, -1)
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- log = logging.getLogger('moepad') SinaAppKey = MPConf.SinaAppKey SinaAppSecret = MPConf.SinaAppSecret MoePadSite = MPConf.Domain <|code_end|> with the help of current file imports: import logging import redis import pickle from django.http import HttpResponse from django.shortcuts import * from django.contrib.auth.decorators import login_required from moedjpack import qqweibo from moedjpack.moepad.mpconf import MPConf from moedjpack.moepad.weibowrapper import WeiboAuthInfoRedis from moedjpack.moepad import weibo from moedjpack.moepad.mputils import rs and context from other files: # Path: moedjpack/moepad/mpconf.py # class MpConfig(object): # class MpConfigRedisHandler(MpConfig): # def __init__(self): # def getConfig(self): # def __init__(self): # def getConfig(self): # # Path: moedjpack/moepad/weibowrapper.py # class WeiboAuthInfoRedis(WeiboAuthInfo): # def __init__(self, user_type): # super(WeiboAuthInfoRedis, self).__init__(user_type) # self.mckey = "WeiboAuth" + user_type # # def load(self): # args = rs.get(self.mckey) # if args: # for key in args.keys(): # setattr(self, key, args[key]) # # def save(self): # print self.__dict__ # confs = sub_dict(self.__dict__, # ['uid', 'access_token', 'expires_in', 'user_type']) # rs.hmset(self.mckey, confs) # rs.expire(self.mckey, confs['expires_in']) # # def clean(self): # rs.hdel(self.mckey) # # Path: moedjpack/moepad/mputils.py # def sub_dict(somedict, somekeys, default=None): # def loggerInit(logfile): # def utcnow(): # def _deletePrefix(key): # def create_default_db(): , which may contain function names, class names, or code. Output only the next line.
OriWeiboAuth = WeiboAuthInfoRedis("original")
Using the snippet: <|code_start|># -*- coding: utf-8 -*- log = logging.getLogger('moepad') SinaAppKey = MPConf.SinaAppKey SinaAppSecret = MPConf.SinaAppSecret MoePadSite = MPConf.Domain OriWeiboAuth = WeiboAuthInfoRedis("original") RtWeiboAuth = WeiboAuthInfoRedis("retweet") def authSina(code): client = weibo.APIClient(SinaAppKey, SinaAppSecret, MoePadSite+"/sinacallback") r = client.request_access_token(code) client.set_access_token(r.access_token, r.expires_in) ruid = client.account.get_uid.get() #can get user type when callback from sina #so save the type in memcache, as long as #only on account get oauthed at a time, this works <|code_end|> , determine the next line of code. You have imports: import logging import redis import pickle from django.http import HttpResponse from django.shortcuts import * from django.contrib.auth.decorators import login_required from moedjpack import qqweibo from moedjpack.moepad.mpconf import MPConf from moedjpack.moepad.weibowrapper import WeiboAuthInfoRedis from moedjpack.moepad import weibo from moedjpack.moepad.mputils import rs and context (class names, function names, or code) available: # Path: moedjpack/moepad/mpconf.py # class MpConfig(object): # class MpConfigRedisHandler(MpConfig): # def __init__(self): # def getConfig(self): # def __init__(self): # def getConfig(self): # # Path: moedjpack/moepad/weibowrapper.py # class WeiboAuthInfoRedis(WeiboAuthInfo): # def __init__(self, user_type): # super(WeiboAuthInfoRedis, self).__init__(user_type) # self.mckey = "WeiboAuth" + user_type # # def load(self): # args = rs.get(self.mckey) # if args: # for key in args.keys(): # setattr(self, key, args[key]) # # def save(self): # print self.__dict__ # confs = sub_dict(self.__dict__, # ['uid', 'access_token', 'expires_in', 'user_type']) # rs.hmset(self.mckey, confs) # rs.expire(self.mckey, confs['expires_in']) # # def clean(self): # rs.hdel(self.mckey) # # Path: moedjpack/moepad/mputils.py # def sub_dict(somedict, somekeys, default=None): # def loggerInit(logfile): # def utcnow(): # def _deletePrefix(key): # def create_default_db(): . Output only the next line.
current_user_type = rs.get("current_user_type")
Here is a snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: delo # @Date: 2014-02-17 23:12:19 # @Email: deloeating@gmail.com # @Last modified by: Sai # @Last modified time: 2014-03-02 15:36:07 def test_getItemCategories(): possible_categories = ['R-18', 'R18'] real_categories = update.getItemCategories(u'Ahe颜') assert len(set(possible_categories).intersection(set(real_categories))) real_categories = update.getItemCategories(u'神原骏河') logger.info(str(type(real_categories[0]))) assert u"物语系列" in real_categories def test_filterForbiddenItems(): <|code_end|> . Write the next line using the current file imports: import time import moedjpack.moepad.update as update from moedjpack.moepad.mputils import rs, logger, _deletePrefix from moedjpack.moepad.mpdefs import * and context from other files: # Path: moedjpack/moepad/mputils.py # def sub_dict(somedict, somekeys, default=None): # def loggerInit(logfile): # def utcnow(): # def _deletePrefix(key): # def create_default_db(): , which may include functions, classes, or code. Output only the next line.
rs.sadd(FORBIDDENS, u"神原骏河".encode('utf-8'))
Given the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: delo # @Date: 2014-02-17 23:12:19 # @Email: deloeating@gmail.com # @Last modified by: Sai # @Last modified time: 2014-03-02 15:36:07 def test_getItemCategories(): possible_categories = ['R-18', 'R18'] real_categories = update.getItemCategories(u'Ahe颜') assert len(set(possible_categories).intersection(set(real_categories))) real_categories = update.getItemCategories(u'神原骏河') <|code_end|> , generate the next line using the imports in this file: import time import moedjpack.moepad.update as update from moedjpack.moepad.mputils import rs, logger, _deletePrefix from moedjpack.moepad.mpdefs import * and context (functions, classes, or occasionally code) from other files: # Path: moedjpack/moepad/mputils.py # def sub_dict(somedict, somekeys, default=None): # def loggerInit(logfile): # def utcnow(): # def _deletePrefix(key): # def create_default_db(): . Output only the next line.
logger.info(str(type(real_categories[0])))
Using the snippet: <|code_start|> possible_categories = ['R-18', 'R18'] real_categories = update.getItemCategories(u'Ahe颜') assert len(set(possible_categories).intersection(set(real_categories))) real_categories = update.getItemCategories(u'神原骏河') logger.info(str(type(real_categories[0]))) assert u"物语系列" in real_categories def test_filterForbiddenItems(): rs.sadd(FORBIDDENS, u"神原骏河".encode('utf-8')) rs.sadd(FORBIDDENS, u"R18".encode('utf-8')) rs.sadd(FORBIDDENS, u"R-18".encode('utf-8')) assert not update.filterForbiddenItems(u"Ahe颜") assert not update.filterForbiddenItems(u'援助交际') assert not update.filterForbiddenItems(u"神原骏河") assert update.filterForbiddenItems(u"猫物语") rs.srem(FORBIDDENS, u"神原骏河".encode('utf-8')) rs.srem(FORBIDDENS, u"R18".encode('utf-8')) rs.srem(FORBIDDENS, u"R-18".encode('utf-8')) def test_filterRedirectedItems(): assert not update.filterRedirectedItems(u"百合(消歧义)") assert update.filterRedirectedItems(u"NTR") def test_filterExistedItems(): <|code_end|> , determine the next line of code. You have imports: import time import moedjpack.moepad.update as update from moedjpack.moepad.mputils import rs, logger, _deletePrefix from moedjpack.moepad.mpdefs import * and context (class names, function names, or code) available: # Path: moedjpack/moepad/mputils.py # def sub_dict(somedict, somekeys, default=None): # def loggerInit(logfile): # def utcnow(): # def _deletePrefix(key): # def create_default_db(): . Output only the next line.
_deletePrefix(NEWITEM)
Here is a snippet: <|code_start|> def reportinfo(self): return ( self.fspath.dirpath(), None, self.fspath.relto(self.session.fspath), ) def _prunetraceback(self, excinfo): # Traceback implements __getitem__, but list implements __getslice__, # which wins in Python 2 excinfo.traceback = excinfo.traceback.cut(__file__) def runtest(self): scss_file = Path(str(self.fspath)) css_file = scss_file.with_suffix('.css') with css_file.open('rb') as fh: # Output is Unicode, so decode this here expected = fh.read().decode('utf8') scss.config.STATIC_ROOT = str(scss_file.parent / 'static') search_path = [] include = scss_file.parent / 'include' if include.exists(): search_path.append(include) search_path.append(scss_file.parent) try: <|code_end|> . Write the next line using the current file imports: import logging import pytest import scss import scss.config import fontforge from pathlib import Path from scss.compiler import compile_file from scss.errors import SassEvaluationError from scss.errors import SassMissingDependency from scss.extension.core import CoreExtension from scss.extension.extra import ExtraExtension from scss.extension.fonts import FontsExtension from scss.extension.compass import CompassExtension and context from other files: # Path: scss/compiler.py # def compile_file(filename, compiler_class=Compiler, **kwargs): # """Compile a single file (provided as a :class:`pathlib.Path`), and return # a string of CSS. # # Keyword arguments are passed along to the underlying `Compiler`. # # Note that the search path is set to the file's containing directory by # default, unless you explicitly pass a ``search_path`` kwarg. # # :param filename: Path to the file to compile. # :type filename: str, bytes, or :class:`pathlib.Path` # """ # filename = Path(filename) # if 'search_path' not in kwargs: # kwargs['search_path'] = [filename.parent.resolve()] # # compiler = compiler_class(**kwargs) # return compiler.compile(filename) # # Path: scss/extension/core.py # class CoreExtension(Extension): # name = 'core' # namespace = Namespace() # # def handle_import(self, name, compilation, rule): # """Implementation of the core Sass import mechanism, which just looks # for files on disk. # """ # # TODO this is all not terribly well-specified by Sass. at worst, # # it's unclear how far "upwards" we should be allowed to go. but i'm # # also a little fuzzy on e.g. how relative imports work from within a # # file that's not actually in the search path. # # TODO i think with the new origin semantics, i've made it possible to # # import relative to the current file even if the current file isn't # # anywhere in the search path. is that right? # path = PurePosixPath(name) # # search_exts = list(compilation.compiler.dynamic_extensions) # if path.suffix and path.suffix in search_exts: # basename = path.stem # else: # basename = path.name # relative_to = path.parent # search_path = [] # tuple of (origin, start_from) # if relative_to.is_absolute(): # relative_to = PurePosixPath(*relative_to.parts[1:]) # elif rule.source_file.origin: # # Search relative to the current file first, only if not doing an # # absolute import # search_path.append(( # rule.source_file.origin, # rule.source_file.relpath.parent / relative_to, # )) # search_path.extend( # (origin, relative_to) # for origin in compilation.compiler.search_path # ) # # for prefix, suffix in product(('_', ''), search_exts): # filename = prefix + basename + suffix # for origin, relative_to in search_path: # relpath = relative_to / filename # # Lexically (ignoring symlinks!) eliminate .. from the part # # of the path that exists within Sass-space. pathlib # # deliberately doesn't do this, but os.path does. # relpath = PurePosixPath(os.path.normpath(str(relpath))) # # if rule.source_file.key == (origin, relpath): # # Avoid self-import # # TODO is this what ruby does? # continue # # path = origin / relpath # if not path.exists(): # continue # # # All good! # # TODO if this file has already been imported, we'll do the # # source preparation twice. make it lazy. # return SourceFile.read(origin, relpath) # # Path: scss/extension/fonts.py # class FontsExtension(Extension): # """Functions for creating and manipulating fonts.""" # name = 'fonts' # namespace = Namespace() , which may include functions, classes, or code. Output only the next line.
actual = compile_file(
Here is a snippet: <|code_start|> self.fspath.relto(self.session.fspath), ) def _prunetraceback(self, excinfo): # Traceback implements __getitem__, but list implements __getslice__, # which wins in Python 2 excinfo.traceback = excinfo.traceback.cut(__file__) def runtest(self): scss_file = Path(str(self.fspath)) css_file = scss_file.with_suffix('.css') with css_file.open('rb') as fh: # Output is Unicode, so decode this here expected = fh.read().decode('utf8') scss.config.STATIC_ROOT = str(scss_file.parent / 'static') search_path = [] include = scss_file.parent / 'include' if include.exists(): search_path.append(include) search_path.append(scss_file.parent) try: actual = compile_file( scss_file, output_style='expanded', search_path=search_path, extensions=[ <|code_end|> . Write the next line using the current file imports: import logging import pytest import scss import scss.config import fontforge from pathlib import Path from scss.compiler import compile_file from scss.errors import SassEvaluationError from scss.errors import SassMissingDependency from scss.extension.core import CoreExtension from scss.extension.extra import ExtraExtension from scss.extension.fonts import FontsExtension from scss.extension.compass import CompassExtension and context from other files: # Path: scss/compiler.py # def compile_file(filename, compiler_class=Compiler, **kwargs): # """Compile a single file (provided as a :class:`pathlib.Path`), and return # a string of CSS. # # Keyword arguments are passed along to the underlying `Compiler`. # # Note that the search path is set to the file's containing directory by # default, unless you explicitly pass a ``search_path`` kwarg. # # :param filename: Path to the file to compile. # :type filename: str, bytes, or :class:`pathlib.Path` # """ # filename = Path(filename) # if 'search_path' not in kwargs: # kwargs['search_path'] = [filename.parent.resolve()] # # compiler = compiler_class(**kwargs) # return compiler.compile(filename) # # Path: scss/extension/core.py # class CoreExtension(Extension): # name = 'core' # namespace = Namespace() # # def handle_import(self, name, compilation, rule): # """Implementation of the core Sass import mechanism, which just looks # for files on disk. # """ # # TODO this is all not terribly well-specified by Sass. at worst, # # it's unclear how far "upwards" we should be allowed to go. but i'm # # also a little fuzzy on e.g. how relative imports work from within a # # file that's not actually in the search path. # # TODO i think with the new origin semantics, i've made it possible to # # import relative to the current file even if the current file isn't # # anywhere in the search path. is that right? # path = PurePosixPath(name) # # search_exts = list(compilation.compiler.dynamic_extensions) # if path.suffix and path.suffix in search_exts: # basename = path.stem # else: # basename = path.name # relative_to = path.parent # search_path = [] # tuple of (origin, start_from) # if relative_to.is_absolute(): # relative_to = PurePosixPath(*relative_to.parts[1:]) # elif rule.source_file.origin: # # Search relative to the current file first, only if not doing an # # absolute import # search_path.append(( # rule.source_file.origin, # rule.source_file.relpath.parent / relative_to, # )) # search_path.extend( # (origin, relative_to) # for origin in compilation.compiler.search_path # ) # # for prefix, suffix in product(('_', ''), search_exts): # filename = prefix + basename + suffix # for origin, relative_to in search_path: # relpath = relative_to / filename # # Lexically (ignoring symlinks!) eliminate .. from the part # # of the path that exists within Sass-space. pathlib # # deliberately doesn't do this, but os.path does. # relpath = PurePosixPath(os.path.normpath(str(relpath))) # # if rule.source_file.key == (origin, relpath): # # Avoid self-import # # TODO is this what ruby does? # continue # # path = origin / relpath # if not path.exists(): # continue # # # All good! # # TODO if this file has already been imported, we'll do the # # source preparation twice. make it lazy. # return SourceFile.read(origin, relpath) # # Path: scss/extension/fonts.py # class FontsExtension(Extension): # """Functions for creating and manipulating fonts.""" # name = 'fonts' # namespace = Namespace() , which may include functions, classes, or code. Output only the next line.
CoreExtension,
Given snippet: <|code_start|> def _prunetraceback(self, excinfo): # Traceback implements __getitem__, but list implements __getslice__, # which wins in Python 2 excinfo.traceback = excinfo.traceback.cut(__file__) def runtest(self): scss_file = Path(str(self.fspath)) css_file = scss_file.with_suffix('.css') with css_file.open('rb') as fh: # Output is Unicode, so decode this here expected = fh.read().decode('utf8') scss.config.STATIC_ROOT = str(scss_file.parent / 'static') search_path = [] include = scss_file.parent / 'include' if include.exists(): search_path.append(include) search_path.append(scss_file.parent) try: actual = compile_file( scss_file, output_style='expanded', search_path=search_path, extensions=[ CoreExtension, ExtraExtension, <|code_end|> , continue by predicting the next line. Consider current file imports: import logging import pytest import scss import scss.config import fontforge from pathlib import Path from scss.compiler import compile_file from scss.errors import SassEvaluationError from scss.errors import SassMissingDependency from scss.extension.core import CoreExtension from scss.extension.extra import ExtraExtension from scss.extension.fonts import FontsExtension from scss.extension.compass import CompassExtension and context: # Path: scss/compiler.py # def compile_file(filename, compiler_class=Compiler, **kwargs): # """Compile a single file (provided as a :class:`pathlib.Path`), and return # a string of CSS. # # Keyword arguments are passed along to the underlying `Compiler`. # # Note that the search path is set to the file's containing directory by # default, unless you explicitly pass a ``search_path`` kwarg. # # :param filename: Path to the file to compile. # :type filename: str, bytes, or :class:`pathlib.Path` # """ # filename = Path(filename) # if 'search_path' not in kwargs: # kwargs['search_path'] = [filename.parent.resolve()] # # compiler = compiler_class(**kwargs) # return compiler.compile(filename) # # Path: scss/extension/core.py # class CoreExtension(Extension): # name = 'core' # namespace = Namespace() # # def handle_import(self, name, compilation, rule): # """Implementation of the core Sass import mechanism, which just looks # for files on disk. # """ # # TODO this is all not terribly well-specified by Sass. at worst, # # it's unclear how far "upwards" we should be allowed to go. but i'm # # also a little fuzzy on e.g. how relative imports work from within a # # file that's not actually in the search path. # # TODO i think with the new origin semantics, i've made it possible to # # import relative to the current file even if the current file isn't # # anywhere in the search path. is that right? # path = PurePosixPath(name) # # search_exts = list(compilation.compiler.dynamic_extensions) # if path.suffix and path.suffix in search_exts: # basename = path.stem # else: # basename = path.name # relative_to = path.parent # search_path = [] # tuple of (origin, start_from) # if relative_to.is_absolute(): # relative_to = PurePosixPath(*relative_to.parts[1:]) # elif rule.source_file.origin: # # Search relative to the current file first, only if not doing an # # absolute import # search_path.append(( # rule.source_file.origin, # rule.source_file.relpath.parent / relative_to, # )) # search_path.extend( # (origin, relative_to) # for origin in compilation.compiler.search_path # ) # # for prefix, suffix in product(('_', ''), search_exts): # filename = prefix + basename + suffix # for origin, relative_to in search_path: # relpath = relative_to / filename # # Lexically (ignoring symlinks!) eliminate .. from the part # # of the path that exists within Sass-space. pathlib # # deliberately doesn't do this, but os.path does. # relpath = PurePosixPath(os.path.normpath(str(relpath))) # # if rule.source_file.key == (origin, relpath): # # Avoid self-import # # TODO is this what ruby does? # continue # # path = origin / relpath # if not path.exists(): # continue # # # All good! # # TODO if this file has already been imported, we'll do the # # source preparation twice. make it lazy. # return SourceFile.read(origin, relpath) # # Path: scss/extension/fonts.py # class FontsExtension(Extension): # """Functions for creating and manipulating fonts.""" # name = 'fonts' # namespace = Namespace() which might include code, classes, or functions. Output only the next line.
FontsExtension,
Continue the code snippet: <|code_start|> root = type(self)(self.combinator, root.tokens) selector = (root,) + selector[1:] return tuple(selector) def merge_into(self, other): """Merge two simple selectors together. This is expected to be the selector being injected into `other` -- that is, `other` is the selector for a block using ``@extend``, and `self` is a selector being extended. Element tokens must come first, and pseudo-element tokens must come last, and there can only be one of each. The final selector thus looks something like:: [element] [misc self tokens] [misc other tokens] [pseudo-element] This method does not check for duplicate tokens; those are assumed to have been removed earlier, during the search for a hinge. """ # TODO it shouldn't be possible to merge two elements or two pseudo # elements, /but/ it shouldn't just be a fatal error here -- it # shouldn't even be considered a candidate for extending! # TODO this is slightly inconsistent with ruby, which treats a trailing # set of self tokens like ':before.foo' as a single unit to be stuck at # the end. but that's completely bogus anyway. element = [] middle = [] pseudo = [] for token in self.tokens + other.tokens: <|code_end|> . Use current file imports: import re from warnings import warn from scss.cssdefs import CSS2_PSEUDO_ELEMENTS and context (classes, functions, or code) from other files: # Path: scss/cssdefs.py # CSS2_PSEUDO_ELEMENTS = frozenset(( # ':after', # ':before', # ':first-line', # ':first-letter', # )) . Output only the next line.
if token in CSS2_PSEUDO_ELEMENTS or token.startswith('::'):
Using the snippet: <|code_start|> def __repr__(self): return "<%s(%s) at 0x%x>" % (type(self).__name__, ', '.join(repr(map) for map in self.maps), id(self)) def __getitem__(self, key): for map in self.maps: if key in map: return map[key] raise KeyError(key) def __setitem__(self, key, value): self.set(key, value) def __contains__(self, key): for map in self.maps: if key in map: return True return False def keys(self): # For mapping interface keys = set() for map in self.maps: keys.update(map.keys()) return list(keys) def set(self, key, value, force_local=False): if not force_local: for map in self.maps: if key in map: <|code_end|> , determine the next line of code. You have imports: import inspect import logging import six from scss.types import Undefined from scss.types import Value and context (class names, function names, or code) available: # Path: scss/types.py # class Undefined(Null): # sass_type_name = 'undefined' # # def __init__(self, value=None): # pass # # def __add__(self, other): # return self # # def __radd__(self, other): # return self # # def __sub__(self, other): # return self # # def __rsub__(self, other): # return self # # def __div__(self, other): # return self # # def __rdiv__(self, other): # return self # # def __truediv__(self, other): # return self # # def __rtruediv__(self, other): # return self # # def __floordiv__(self, other): # return self # # def __rfloordiv__(self, other): # return self # # def __mul__(self, other): # return self # # def __rmul__(self, other): # return self # # def __pos__(self): # return self # # def __neg__(self): # return self # # Path: scss/types.py # class Value(object): # is_null = False # sass_type_name = 'unknown' # # def __repr__(self): # return "<{0}: {1!r}>".format(type(self).__name__, self.value) # # # Sass values are all true, except for booleans and nulls # def __bool__(self): # return True # # def __nonzero__(self): # # Py 2's name for __bool__ # return self.__bool__() # # # All Sass scalars also act like one-element spaced lists # use_comma = False # # def __iter__(self): # return iter((self,)) # # def __len__(self): # return 1 # # def __getitem__(self, key): # if key not in (-1, 0): # raise IndexError(key) # # return self # # def __contains__(self, item): # return self == item # # ### NOTE: From here on down, the operators are exposed to Sass code and # ### thus should ONLY return Sass types # # # Reasonable default for equality # def __eq__(self, other): # return Boolean( # type(self) == type(other) and self.value == other.value) # # def __ne__(self, other): # return Boolean(not self.__eq__(other)) # # # Only numbers support ordering # def __lt__(self, other): # raise TypeError("Can't compare %r with %r" % (self, other)) # # def __le__(self, other): # raise TypeError("Can't compare %r with %r" % (self, other)) # # def __gt__(self, other): # raise TypeError("Can't compare %r with %r" % (self, other)) # # def __ge__(self, other): # raise TypeError("Can't compare %r with %r" % (self, other)) # # # Math ops # def __add__(self, other): # # Default behavior is to treat both sides like strings # if isinstance(other, String): # return String(self.render() + other.value, quotes=other.quotes) # return String(self.render() + other.render()) # # def __sub__(self, other): # # Default behavior is to treat the whole expression like one string # return String.unquoted(self.render() + "-" + other.render()) # # def __div__(self, other): # return String.unquoted(self.render() + "/" + other.render()) # # # Sass types have no notion of floor vs true division # def __truediv__(self, other): # return self.__div__(other) # # def __floordiv__(self, other): # return self.__div__(other) # # def __mul__(self, other): # return NotImplemented # # def __pos__(self): # return String("+" + self.render()) # # def __neg__(self): # return String("-" + self.render()) # # def to_dict(self): # """Return the Python dict equivalent of this map. # # If this type can't be expressed as a map, raise. # """ # return dict(self.to_pairs()) # # def to_pairs(self): # """Return the Python list-of-tuples equivalent of this map. Note that # this is different from ``self.to_dict().items()``, because Sass maps # preserve order. # # If this type can't be expressed as a map, raise. # """ # raise ValueError("Not a map: {0!r}".format(self)) # # def render(self, compress=False): # """Return this value's CSS representation as a string (text, i.e. # unicode!). # # If `compress` is true, try hard to shorten the string at the cost of # readability. # """ # raise NotImplementedError # # def render_interpolated(self, compress=False): # """Return this value's string representation as appropriate for # returning from an interpolation. # """ # return self.render(compress) . Output only the next line.
if isinstance(map[key], Undefined):
Continue the code snippet: <|code_start|> def _auto_register_function(self, function, name, ignore_args=0): name = name.replace('_', '-').rstrip('-') argspec = inspect.getargspec(function) if argspec.varargs or argspec.keywords: # Accepts some arbitrary number of arguments arities = [None] else: # Accepts a fixed range of arguments if argspec.defaults: num_optional = len(argspec.defaults) else: num_optional = 0 num_args = len(argspec.args) - ignore_args arities = range(num_args - num_optional, num_args + 1) for arity in arities: self.set_function(name, arity, function) @property def variables(self): return dict((k, self._variables[k]) for k in self._variables.keys()) def variable(self, name, throw=False): name = normalize_var(name) return self._variables[name] def set_variable(self, name, value, local_only=False): self._assert_mutable() name = normalize_var(name) <|code_end|> . Use current file imports: import inspect import logging import six from scss.types import Undefined from scss.types import Value and context (classes, functions, or code) from other files: # Path: scss/types.py # class Undefined(Null): # sass_type_name = 'undefined' # # def __init__(self, value=None): # pass # # def __add__(self, other): # return self # # def __radd__(self, other): # return self # # def __sub__(self, other): # return self # # def __rsub__(self, other): # return self # # def __div__(self, other): # return self # # def __rdiv__(self, other): # return self # # def __truediv__(self, other): # return self # # def __rtruediv__(self, other): # return self # # def __floordiv__(self, other): # return self # # def __rfloordiv__(self, other): # return self # # def __mul__(self, other): # return self # # def __rmul__(self, other): # return self # # def __pos__(self): # return self # # def __neg__(self): # return self # # Path: scss/types.py # class Value(object): # is_null = False # sass_type_name = 'unknown' # # def __repr__(self): # return "<{0}: {1!r}>".format(type(self).__name__, self.value) # # # Sass values are all true, except for booleans and nulls # def __bool__(self): # return True # # def __nonzero__(self): # # Py 2's name for __bool__ # return self.__bool__() # # # All Sass scalars also act like one-element spaced lists # use_comma = False # # def __iter__(self): # return iter((self,)) # # def __len__(self): # return 1 # # def __getitem__(self, key): # if key not in (-1, 0): # raise IndexError(key) # # return self # # def __contains__(self, item): # return self == item # # ### NOTE: From here on down, the operators are exposed to Sass code and # ### thus should ONLY return Sass types # # # Reasonable default for equality # def __eq__(self, other): # return Boolean( # type(self) == type(other) and self.value == other.value) # # def __ne__(self, other): # return Boolean(not self.__eq__(other)) # # # Only numbers support ordering # def __lt__(self, other): # raise TypeError("Can't compare %r with %r" % (self, other)) # # def __le__(self, other): # raise TypeError("Can't compare %r with %r" % (self, other)) # # def __gt__(self, other): # raise TypeError("Can't compare %r with %r" % (self, other)) # # def __ge__(self, other): # raise TypeError("Can't compare %r with %r" % (self, other)) # # # Math ops # def __add__(self, other): # # Default behavior is to treat both sides like strings # if isinstance(other, String): # return String(self.render() + other.value, quotes=other.quotes) # return String(self.render() + other.render()) # # def __sub__(self, other): # # Default behavior is to treat the whole expression like one string # return String.unquoted(self.render() + "-" + other.render()) # # def __div__(self, other): # return String.unquoted(self.render() + "/" + other.render()) # # # Sass types have no notion of floor vs true division # def __truediv__(self, other): # return self.__div__(other) # # def __floordiv__(self, other): # return self.__div__(other) # # def __mul__(self, other): # return NotImplemented # # def __pos__(self): # return String("+" + self.render()) # # def __neg__(self): # return String("-" + self.render()) # # def to_dict(self): # """Return the Python dict equivalent of this map. # # If this type can't be expressed as a map, raise. # """ # return dict(self.to_pairs()) # # def to_pairs(self): # """Return the Python list-of-tuples equivalent of this map. Note that # this is different from ``self.to_dict().items()``, because Sass maps # preserve order. # # If this type can't be expressed as a map, raise. # """ # raise ValueError("Not a map: {0!r}".format(self)) # # def render(self, compress=False): # """Return this value's CSS representation as a string (text, i.e. # unicode!). # # If `compress` is true, try hard to shorten the string at the cost of # readability. # """ # raise NotImplementedError # # def render_interpolated(self, compress=False): # """Return this value's string representation as appropriate for # returning from an interpolation. # """ # return self.render(compress) . Output only the next line.
if not isinstance(value, Value):
Continue the code snippet: <|code_start|> IPC_CREAT = 0o1000 IPC_PRIVATE = 0 IPC_RMID = 0 SHM_RDONLY = 0o10000 SHM_RND = 0o20000 SHM_REMAP = 0o40000 SHM_EXEC = 0o100000 try: rt = ctypes.CDLL('librt.so', use_errno=True) shmget = rt.shmget shmget.argtypes = [ctypes.c_int, ctypes.c_size_t, ctypes.c_int] shmget.restype = ctypes.c_int shmat = rt.shmat shmat.argtypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_void_p), ctypes.c_int] shmat.restype = ctypes.c_void_p shmdt = rt.shmdt shmdt.argtypes = [ctypes.c_void_p] shmdt.restype = ctypes.c_int shmctl = rt.shmctl shmctl.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_void_p] shmctl.restype = ctypes.c_int except (OSError, AttributeError): raise ImportError("Shared memory is not supported") <|code_end|> . Use current file imports: import cairo import ctypes from .pixbuf import PixbufBase and context (classes, functions, or code) from other files: # Path: tilenol/xcb/pixbuf.py # class PixbufBase(object): # # def __init__(self, image, xcore): # self._image = image # self.width = image.get_width() # self.height = image.get_height() # self._context = cairo.Context(self._image) # self.xcore = xcore # # def context(self): # return self._context . Output only the next line.
class ShmPixbuf(PixbufBase):
Based on the snippet: <|code_start|> @has_dependencies class _Graph(Widget): fixed_upper_bound = False <|code_end|> , predict the immediate next line with the help of imports: import time import cairo from zorro import gethub, sleep from zorro.di import has_dependencies, dependency from .base import Widget from tilenol.theme import Theme from os import statvfs and context (classes, functions, sometimes code) from other files: # Path: tilenol/widgets/base.py # class Widget(metaclass=ABCMeta): # # bar = dependency(Bar, 'bar') # stretched = False # # def __init__(self, right=False): # self.right = right # # @abstractmethod # def draw(self, canvas, left, right): # return left, right # # Path: tilenol/theme.py # class Theme(SubTheme): # # def __init__(self): # # blue = 0x4c4c99 # dark_blue = 0x191933 # orange = 0x99994c # gray = 0x808080 # red = 0x994c4c # black = 0x000000 # white = 0xffffff # # self.window = SubTheme('window') # self.window.border_width = 2 # self.window.set_color('active_border', blue) # self.window.set_color('inactive_border', gray) # self.window.set_color('background', black) # # self.bar = SubTheme('bar') # self.bar.set_color('background', black) # self.bar.font = Font('Consolas', 18) # self.bar.box_padding = Padding(2, 2, 2, 2) # self.bar.text_padding = Padding(2, 4, 7, 4) # self.bar.icon_spacing = 2 # self.bar.set_color('text_color', white) # self.bar.set_color('dim_color', gray) # self.bar.set_color('bright_color', orange) # self.bar.set_color('active_border', blue) # self.bar.set_color('subactive_border', gray) # self.bar.set_color('urgent_border', red) # self.bar.border_width = 2 # self.bar.height = 24 # self.bar.set_color('graph_color', blue) # self.bar.set_color('graph_fill_color', dark_blue) # self.bar.graph_line_width = 2 # self.bar.separator_width = 1 # self.bar.set_color('separator_color', gray) # # self.menu = SubTheme('bar') # self.menu.set_color('background', gray) # self.menu.set_color('text', white) # self.menu.set_color('highlight', blue) # self.menu.set_color('selection', blue) # self.menu.set_color('selection_text', white) # self.menu.set_color('cursor', black) # self.menu.font = Font('Consolas', 18) # self.menu.padding = Padding(2, 4, 7, 4) # self.menu.line_height = 24 # # self.hint = SubTheme('hint') # self.hint.font = Font('Consolas', 18) # self.hint.set_color('background', black) # self.hint.set_color('border_color', gray) # self.hint.set_color('text_color', white) # self.hint.border_width = 2 # self.hint.padding = Padding(5, 6, 9, 6) # # self.tabs = SubTheme('tabs') # self.tabs.font = Font('Monofur', 12) # self.tabs.set_color('background', black) # self.tabs.set_color('inactive_title', gray) # self.tabs.set_color('inactive_bg', black) # self.tabs.set_color('active_title', white) # self.tabs.set_color('active_bg', blue) # self.tabs.set_color('urgent_title', white) # self.tabs.set_color('urgent_bg', orange) # self.tabs.section_font = Font('Monofur', 12) # self.tabs.set_color('section_color', gray) # self.tabs.padding = Padding(5, 6, 6, 4) # self.tabs.margin = Padding(4, 4, 4, 4) # self.tabs.border_radius = 5 # self.tabs.spacing = 2 # self.tabs.icon_size = 14 # self.tabs.icon_spacing = 6 # self.tabs.section_padding = Padding(6, 2, 2, 2) # # def update_from(self, dic): # for key, sub in self.__dict__.items(): # if isinstance(sub, SubTheme) and key in dic: # sub.update_from(dic[key]) . Output only the next line.
theme = dependency(Theme, 'theme')
Predict the next line for this snippet: <|code_start|> def __zorro_di_done__(self): inj = di(self) for i, scr in enumerate(self.screens): inj.inject(scr) self.commander['screen.{}'.format(i)] = scr def update(self, screens): # TODO(tailhook) try to guess which one turned off while len(self.screens) > len(screens): scr = self.screens.pop() idx = len(self.screens) del self.commander['screen.{}'.format(idx)] for i, s in enumerate(self.screens): s.set_bounds(screens[i]) while len(self.screens) < len(screens): idx = len(self.screens) scr = Screen() scr.set_bounds(screens[idx]) self.screens.append(scr) self.commander['screen.{}'.format(idx)] = scr class Screen(object): def __init__(self): self.topbars = [] self.bottombars = [] self.leftslices = [] self.rightslices = [] <|code_end|> with the help of current file imports: from zorro.di import di, has_dependencies, dependency from tilenol.event import Event from .xcb import Rectangle from tilenol.commands import CommandDispatcher and context from other files: # Path: tilenol/event.py # class Event(object): # # def __init__(self, name=None): # self.name = name # self._listeners = [] # self._worker = None # # def listen(self, fun): # self._listeners.append(fun) # # def unlisten(self, fun): # self._listeners.remove(fun) # # def emit(self): # log.debug("Emitting event %r", self.name) # if self._worker is None and self._listeners: # self._worker = gethub().do_spawn(self._do_work) # # def _do_work(self): # try: # log.debug("Processing event %r", self.name) # for l in self._listeners: # l() # finally: # self._worker = None # # Path: tilenol/xcb/core.py # class Rectangle(namedtuple('_Rectangle', 'x y width height')): # __slots__ = () # # Path: tilenol/commands.py # class CommandDispatcher(dict): # # def __init__(self): # self.events = Events() # # def __setitem__(self, name, value): # super().__setitem__(name, value) # ev = self.events.get(name) # if ev is not None: # ev.emit() # # def call(self, obj, meth, *args): # getattr(self[obj], 'cmd_' + meth)(*args) # # def callback(self, *args): # return partial(self.call, *args) , which may contain function names, class names, or code. Output only the next line.
self.updated = Event('screen.updated')
Continue the code snippet: <|code_start|>class Screen(object): def __init__(self): self.topbars = [] self.bottombars = [] self.leftslices = [] self.rightslices = [] self.updated = Event('screen.updated') self.bars_visible = True self.group_hooks = [] def add_group_hook(self, fun): self.group_hooks.append(fun) def remove_group_hook(self, fun): self.group_hooks.remove(fun) def set_group(self, group): self.group = group for h in self.group_hooks: h() def cmd_focus(self): self.group.focus() def set_bounds(self, rect): self.bounds = rect x, y, w, h = rect if self.bars_visible: for bar in self.topbars: <|code_end|> . Use current file imports: from zorro.di import di, has_dependencies, dependency from tilenol.event import Event from .xcb import Rectangle from tilenol.commands import CommandDispatcher and context (classes, functions, or code) from other files: # Path: tilenol/event.py # class Event(object): # # def __init__(self, name=None): # self.name = name # self._listeners = [] # self._worker = None # # def listen(self, fun): # self._listeners.append(fun) # # def unlisten(self, fun): # self._listeners.remove(fun) # # def emit(self): # log.debug("Emitting event %r", self.name) # if self._worker is None and self._listeners: # self._worker = gethub().do_spawn(self._do_work) # # def _do_work(self): # try: # log.debug("Processing event %r", self.name) # for l in self._listeners: # l() # finally: # self._worker = None # # Path: tilenol/xcb/core.py # class Rectangle(namedtuple('_Rectangle', 'x y width height')): # __slots__ = () # # Path: tilenol/commands.py # class CommandDispatcher(dict): # # def __init__(self): # self.events = Events() # # def __setitem__(self, name, value): # super().__setitem__(name, value) # ev = self.events.get(name) # if ev is not None: # ev.emit() # # def call(self, obj, meth, *args): # getattr(self[obj], 'cmd_' + meth)(*args) # # def callback(self, *args): # return partial(self.call, *args) . Output only the next line.
bar.set_bounds(Rectangle(x, y, w, bar.height))
Based on the snippet: <|code_start|> class LayoutMeta(type): @classmethod def __prepare__(cls, name, bases): return OrderedDict() def __init__(cls, name, bases, dic): cls.fields = list(dic.keys()) @has_dependencies class Layout(metaclass=LayoutMeta): def __init__(self): self.visible = False <|code_end|> , predict the immediate next line with the help of imports: from collections import OrderedDict from zorro.di import di, has_dependencies, dependency from tilenol.event import Event and context (classes, functions, sometimes code) from other files: # Path: tilenol/event.py # class Event(object): # # def __init__(self, name=None): # self.name = name # self._listeners = [] # self._worker = None # # def listen(self, fun): # self._listeners.append(fun) # # def unlisten(self, fun): # self._listeners.remove(fun) # # def emit(self): # log.debug("Emitting event %r", self.name) # if self._worker is None and self._listeners: # self._worker = gethub().do_spawn(self._do_work) # # def _do_work(self): # try: # log.debug("Processing event %r", self.name) # for l in self._listeners: # l() # finally: # self._worker = None . Output only the next line.
self.relayout = Event('layout.relayout')
Given snippet: <|code_start|> class BaseStack(object): """Single stack for tile layout It's customized by subclassing, not by instantiating :var size: size (e.g. width) of stack in pixels, if None weight is used :var min_size: minimum size of stack to start to ignore pixel sizes :var weight: the bigger weight is, the bigger part of screen this stack occupies (if width is unspecified or screen size is too small) :var limit: limit number of windows inside the stack :var priority: windows are placed into stacks with smaller priority first """ size = None min_size = 32 weight = 1 limit = None priority = 100 def __init__(self, parent): self.parent = parent self.windows = [] <|code_end|> , continue by predicting the next line. Consider current file imports: from collections import OrderedDict from math import floor from functools import wraps from zorro.di import has_dependencies, dependency, di from tilenol.xcb import Rectangle from tilenol.commands import CommandDispatcher from . import Layout and context: # Path: tilenol/xcb/core.py # class Rectangle(namedtuple('_Rectangle', 'x y width height')): # __slots__ = () # # Path: tilenol/commands.py # class CommandDispatcher(dict): # # def __init__(self): # self.events = Events() # # def __setitem__(self, name, value): # super().__setitem__(name, value) # ev = self.events.get(name) # if ev is not None: # ev.emit() # # def call(self, obj, meth, *args): # getattr(self[obj], 'cmd_' + meth)(*args) # # def callback(self, *args): # return partial(self.call, *args) # # Path: tilenol/layout/base.py # class Layout(metaclass=LayoutMeta): # # def __init__(self): # self.visible = False # self.relayout = Event('layout.relayout') # self.relayout.listen(self.check_relayout) # # def check_relayout(self): # if self.visible: # self.layout() # self.group.check_focus() # # @classmethod # def get_defined_classes(cls, base): # res = OrderedDict() # for k in cls.fields: # v = getattr(cls, k) # if isinstance(v, type) and issubclass(v, base): # res[k] = v # return res # # def dirty(self): # self.relayout.emit() # # def all_visible_windows(self): # for i in getattr(self, 'visible_windows', ()): # yield i # sub = getattr(self, 'sublayouts', None) # if sub: # for s in sub(): # for i in s.visible_windows: # yield i # # def hide(self): # self.visible = False # for i in self.all_visible_windows(): # i.hide() # # def show(self): # self.visible = True # for i in self.all_visible_windows(): # i.show() which might include code, classes, or functions. Output only the next line.
self.box = Rectangle(0, 0, 100, 100)
Using the snippet: <|code_start|> w.show() start = end def stackcommand(fun): @wraps(fun) def wrapper(self, *args): try: win = self.commander['window'] except KeyError: return stack = win.lprops.stack if stack is None: return return fun(self, self.stacks[stack], win, *args) return wrapper @has_dependencies class Split(Layout): """Split layout It's customized by subclassing, not by instantiating. Class definition should consist of at least one stack :var fixed: whether to skip empty stacks or reserve place for them """ fixed = False vertical = True <|code_end|> , determine the next line of code. You have imports: from collections import OrderedDict from math import floor from functools import wraps from zorro.di import has_dependencies, dependency, di from tilenol.xcb import Rectangle from tilenol.commands import CommandDispatcher from . import Layout and context (class names, function names, or code) available: # Path: tilenol/xcb/core.py # class Rectangle(namedtuple('_Rectangle', 'x y width height')): # __slots__ = () # # Path: tilenol/commands.py # class CommandDispatcher(dict): # # def __init__(self): # self.events = Events() # # def __setitem__(self, name, value): # super().__setitem__(name, value) # ev = self.events.get(name) # if ev is not None: # ev.emit() # # def call(self, obj, meth, *args): # getattr(self[obj], 'cmd_' + meth)(*args) # # def callback(self, *args): # return partial(self.call, *args) # # Path: tilenol/layout/base.py # class Layout(metaclass=LayoutMeta): # # def __init__(self): # self.visible = False # self.relayout = Event('layout.relayout') # self.relayout.listen(self.check_relayout) # # def check_relayout(self): # if self.visible: # self.layout() # self.group.check_focus() # # @classmethod # def get_defined_classes(cls, base): # res = OrderedDict() # for k in cls.fields: # v = getattr(cls, k) # if isinstance(v, type) and issubclass(v, base): # res[k] = v # return res # # def dirty(self): # self.relayout.emit() # # def all_visible_windows(self): # for i in getattr(self, 'visible_windows', ()): # yield i # sub = getattr(self, 'sublayouts', None) # if sub: # for s in sub(): # for i in s.visible_windows: # yield i # # def hide(self): # self.visible = False # for i in self.all_visible_windows(): # i.hide() # # def show(self): # self.visible = True # for i in self.all_visible_windows(): # i.show() . Output only the next line.
commander = dependency(CommandDispatcher, 'commander')
Predict the next line after this snippet: <|code_start|> else: rstart = start = self.box.x for n, w in enumerate(self.windows, 1): if self.vertical: end = rstart + int(floor(n/vc*self.box.height)) w.set_bounds(Rectangle( self.box.x, start, self.box.width, end-start)) else: end = rstart + int(floor(n/vc*self.box.width)) w.set_bounds(Rectangle( start, self.box.y, end-start, self.box.height)) w.show() start = end def stackcommand(fun): @wraps(fun) def wrapper(self, *args): try: win = self.commander['window'] except KeyError: return stack = win.lprops.stack if stack is None: return return fun(self, self.stacks[stack], win, *args) return wrapper @has_dependencies <|code_end|> using the current file's imports: from collections import OrderedDict from math import floor from functools import wraps from zorro.di import has_dependencies, dependency, di from tilenol.xcb import Rectangle from tilenol.commands import CommandDispatcher from . import Layout and any relevant context from other files: # Path: tilenol/xcb/core.py # class Rectangle(namedtuple('_Rectangle', 'x y width height')): # __slots__ = () # # Path: tilenol/commands.py # class CommandDispatcher(dict): # # def __init__(self): # self.events = Events() # # def __setitem__(self, name, value): # super().__setitem__(name, value) # ev = self.events.get(name) # if ev is not None: # ev.emit() # # def call(self, obj, meth, *args): # getattr(self[obj], 'cmd_' + meth)(*args) # # def callback(self, *args): # return partial(self.call, *args) # # Path: tilenol/layout/base.py # class Layout(metaclass=LayoutMeta): # # def __init__(self): # self.visible = False # self.relayout = Event('layout.relayout') # self.relayout.listen(self.check_relayout) # # def check_relayout(self): # if self.visible: # self.layout() # self.group.check_focus() # # @classmethod # def get_defined_classes(cls, base): # res = OrderedDict() # for k in cls.fields: # v = getattr(cls, k) # if isinstance(v, type) and issubclass(v, base): # res[k] = v # return res # # def dirty(self): # self.relayout.emit() # # def all_visible_windows(self): # for i in getattr(self, 'visible_windows', ()): # yield i # sub = getattr(self, 'sublayouts', None) # if sub: # for s in sub(): # for i in s.visible_windows: # yield i # # def hide(self): # self.visible = False # for i in self.all_visible_windows(): # i.hide() # # def show(self): # self.visible = True # for i in self.all_visible_windows(): # i.show() . Output only the next line.
class Split(Layout):
Next line prediction: <|code_start|># -*- coding: utf-8 -*- log = logging.getLogger(__name__) QUERY_URL = 'http://query.yahooapis.com/v1/public/yql' WEATHER_URL = 'http://weather.yahooapis.com/forecastrss?' WEATHER_NS = 'http://xml.weather.yahoo.com/ns/rss/1.0' DEFAULT_PIC = 'http://l.yimg.com/a/i/us/nws/weather/gr/{condition_code}d.png' @has_dependencies <|code_end|> . Use current file imports: (from urllib.parse import urlencode from xml.etree import ElementTree as ET from io import BytesIO from zorro import gethub, sleep from zorro.http import HTTPClient from zorro.di import has_dependencies, dependency from .base import Widget from tilenol.theme import Theme from tilenol.util import fetchurl import json import logging import cairo) and context including class names, function names, or small code snippets from other files: # Path: tilenol/widgets/base.py # class Widget(metaclass=ABCMeta): # # bar = dependency(Bar, 'bar') # stretched = False # # def __init__(self, right=False): # self.right = right # # @abstractmethod # def draw(self, canvas, left, right): # return left, right # # Path: tilenol/theme.py # class Theme(SubTheme): # # def __init__(self): # # blue = 0x4c4c99 # dark_blue = 0x191933 # orange = 0x99994c # gray = 0x808080 # red = 0x994c4c # black = 0x000000 # white = 0xffffff # # self.window = SubTheme('window') # self.window.border_width = 2 # self.window.set_color('active_border', blue) # self.window.set_color('inactive_border', gray) # self.window.set_color('background', black) # # self.bar = SubTheme('bar') # self.bar.set_color('background', black) # self.bar.font = Font('Consolas', 18) # self.bar.box_padding = Padding(2, 2, 2, 2) # self.bar.text_padding = Padding(2, 4, 7, 4) # self.bar.icon_spacing = 2 # self.bar.set_color('text_color', white) # self.bar.set_color('dim_color', gray) # self.bar.set_color('bright_color', orange) # self.bar.set_color('active_border', blue) # self.bar.set_color('subactive_border', gray) # self.bar.set_color('urgent_border', red) # self.bar.border_width = 2 # self.bar.height = 24 # self.bar.set_color('graph_color', blue) # self.bar.set_color('graph_fill_color', dark_blue) # self.bar.graph_line_width = 2 # self.bar.separator_width = 1 # self.bar.set_color('separator_color', gray) # # self.menu = SubTheme('bar') # self.menu.set_color('background', gray) # self.menu.set_color('text', white) # self.menu.set_color('highlight', blue) # self.menu.set_color('selection', blue) # self.menu.set_color('selection_text', white) # self.menu.set_color('cursor', black) # self.menu.font = Font('Consolas', 18) # self.menu.padding = Padding(2, 4, 7, 4) # self.menu.line_height = 24 # # self.hint = SubTheme('hint') # self.hint.font = Font('Consolas', 18) # self.hint.set_color('background', black) # self.hint.set_color('border_color', gray) # self.hint.set_color('text_color', white) # self.hint.border_width = 2 # self.hint.padding = Padding(5, 6, 9, 6) # # self.tabs = SubTheme('tabs') # self.tabs.font = Font('Monofur', 12) # self.tabs.set_color('background', black) # self.tabs.set_color('inactive_title', gray) # self.tabs.set_color('inactive_bg', black) # self.tabs.set_color('active_title', white) # self.tabs.set_color('active_bg', blue) # self.tabs.set_color('urgent_title', white) # self.tabs.set_color('urgent_bg', orange) # self.tabs.section_font = Font('Monofur', 12) # self.tabs.set_color('section_color', gray) # self.tabs.padding = Padding(5, 6, 6, 4) # self.tabs.margin = Padding(4, 4, 4, 4) # self.tabs.border_radius = 5 # self.tabs.spacing = 2 # self.tabs.icon_size = 14 # self.tabs.icon_spacing = 6 # self.tabs.section_padding = Padding(6, 2, 2, 2) # # def update_from(self, dic): # for key, sub in self.__dict__.items(): # if isinstance(sub, SubTheme) and key in dic: # sub.update_from(dic[key]) # # Path: tilenol/util.py # def fetchurl(url, query=None): # if query is not None: # assert '?' not in url, ("Either include query in url" # "or pass as parameter, but not both") # url += '?' + urlencode(query) # proto, tail = splittype(url) # if proto != 'http': # raise RuntimeError("Unsupported protocol HTTP") # host, tail = splithost(tail) # ip = gethub().dns_resolver.gethostbyname(host) # cli = HTTPClient(ip) # resp = cli.request(tail, headers={'Host': host}) # if resp.status.endswith('200 OK'): # return resp.body # raise RequestError(resp.status, resp) . Output only the next line.
class YahooWeather(Widget):
Given snippet: <|code_start|># -*- coding: utf-8 -*- log = logging.getLogger(__name__) QUERY_URL = 'http://query.yahooapis.com/v1/public/yql' WEATHER_URL = 'http://weather.yahooapis.com/forecastrss?' WEATHER_NS = 'http://xml.weather.yahoo.com/ns/rss/1.0' DEFAULT_PIC = 'http://l.yimg.com/a/i/us/nws/weather/gr/{condition_code}d.png' @has_dependencies class YahooWeather(Widget): tags_to_fetch = ( 'location', 'units', 'wind', 'atmosphere', 'astronomy', 'condition', ) <|code_end|> , continue by predicting the next line. Consider current file imports: from urllib.parse import urlencode from xml.etree import ElementTree as ET from io import BytesIO from zorro import gethub, sleep from zorro.http import HTTPClient from zorro.di import has_dependencies, dependency from .base import Widget from tilenol.theme import Theme from tilenol.util import fetchurl import json import logging import cairo and context: # Path: tilenol/widgets/base.py # class Widget(metaclass=ABCMeta): # # bar = dependency(Bar, 'bar') # stretched = False # # def __init__(self, right=False): # self.right = right # # @abstractmethod # def draw(self, canvas, left, right): # return left, right # # Path: tilenol/theme.py # class Theme(SubTheme): # # def __init__(self): # # blue = 0x4c4c99 # dark_blue = 0x191933 # orange = 0x99994c # gray = 0x808080 # red = 0x994c4c # black = 0x000000 # white = 0xffffff # # self.window = SubTheme('window') # self.window.border_width = 2 # self.window.set_color('active_border', blue) # self.window.set_color('inactive_border', gray) # self.window.set_color('background', black) # # self.bar = SubTheme('bar') # self.bar.set_color('background', black) # self.bar.font = Font('Consolas', 18) # self.bar.box_padding = Padding(2, 2, 2, 2) # self.bar.text_padding = Padding(2, 4, 7, 4) # self.bar.icon_spacing = 2 # self.bar.set_color('text_color', white) # self.bar.set_color('dim_color', gray) # self.bar.set_color('bright_color', orange) # self.bar.set_color('active_border', blue) # self.bar.set_color('subactive_border', gray) # self.bar.set_color('urgent_border', red) # self.bar.border_width = 2 # self.bar.height = 24 # self.bar.set_color('graph_color', blue) # self.bar.set_color('graph_fill_color', dark_blue) # self.bar.graph_line_width = 2 # self.bar.separator_width = 1 # self.bar.set_color('separator_color', gray) # # self.menu = SubTheme('bar') # self.menu.set_color('background', gray) # self.menu.set_color('text', white) # self.menu.set_color('highlight', blue) # self.menu.set_color('selection', blue) # self.menu.set_color('selection_text', white) # self.menu.set_color('cursor', black) # self.menu.font = Font('Consolas', 18) # self.menu.padding = Padding(2, 4, 7, 4) # self.menu.line_height = 24 # # self.hint = SubTheme('hint') # self.hint.font = Font('Consolas', 18) # self.hint.set_color('background', black) # self.hint.set_color('border_color', gray) # self.hint.set_color('text_color', white) # self.hint.border_width = 2 # self.hint.padding = Padding(5, 6, 9, 6) # # self.tabs = SubTheme('tabs') # self.tabs.font = Font('Monofur', 12) # self.tabs.set_color('background', black) # self.tabs.set_color('inactive_title', gray) # self.tabs.set_color('inactive_bg', black) # self.tabs.set_color('active_title', white) # self.tabs.set_color('active_bg', blue) # self.tabs.set_color('urgent_title', white) # self.tabs.set_color('urgent_bg', orange) # self.tabs.section_font = Font('Monofur', 12) # self.tabs.set_color('section_color', gray) # self.tabs.padding = Padding(5, 6, 6, 4) # self.tabs.margin = Padding(4, 4, 4, 4) # self.tabs.border_radius = 5 # self.tabs.spacing = 2 # self.tabs.icon_size = 14 # self.tabs.icon_spacing = 6 # self.tabs.section_padding = Padding(6, 2, 2, 2) # # def update_from(self, dic): # for key, sub in self.__dict__.items(): # if isinstance(sub, SubTheme) and key in dic: # sub.update_from(dic[key]) # # Path: tilenol/util.py # def fetchurl(url, query=None): # if query is not None: # assert '?' not in url, ("Either include query in url" # "or pass as parameter, but not both") # url += '?' + urlencode(query) # proto, tail = splittype(url) # if proto != 'http': # raise RuntimeError("Unsupported protocol HTTP") # host, tail = splithost(tail) # ip = gethub().dns_resolver.gethostbyname(host) # cli = HTTPClient(ip) # resp = cli.request(tail, headers={'Host': host}) # if resp.status.endswith('200 OK'): # return resp.body # raise RequestError(resp.status, resp) which might include code, classes, or functions. Output only the next line.
theme = dependency(Theme, 'theme')
Based on the snippet: <|code_start|> def __zorro_di_done__(self): bar = self.theme.bar self.font = bar.font self.color = bar.text_color_pat self.padding = bar.text_padding gethub().do_spawnhelper(self._update_handler) def _update_handler(self): try: woeid = int(self.location) except ValueError: woeid = self.fetch_woeid() self.uri = "{0}{1}".format( WEATHER_URL, urlencode({'w': woeid, 'u': self.metric and 'c' or 'f'}) ) while True: result = self.fetch() if result is not None: self.text = self.format.format_map(result) if self.picture_url is not None: self.fetch_image(result) sleep(600) def fetch_image(self, data): img_url = None try: img_url = self.picture_url.format_map(data) if img_url == self.oldimg_url and self.image: return <|code_end|> , predict the immediate next line with the help of imports: from urllib.parse import urlencode from xml.etree import ElementTree as ET from io import BytesIO from zorro import gethub, sleep from zorro.http import HTTPClient from zorro.di import has_dependencies, dependency from .base import Widget from tilenol.theme import Theme from tilenol.util import fetchurl import json import logging import cairo and context (classes, functions, sometimes code) from other files: # Path: tilenol/widgets/base.py # class Widget(metaclass=ABCMeta): # # bar = dependency(Bar, 'bar') # stretched = False # # def __init__(self, right=False): # self.right = right # # @abstractmethod # def draw(self, canvas, left, right): # return left, right # # Path: tilenol/theme.py # class Theme(SubTheme): # # def __init__(self): # # blue = 0x4c4c99 # dark_blue = 0x191933 # orange = 0x99994c # gray = 0x808080 # red = 0x994c4c # black = 0x000000 # white = 0xffffff # # self.window = SubTheme('window') # self.window.border_width = 2 # self.window.set_color('active_border', blue) # self.window.set_color('inactive_border', gray) # self.window.set_color('background', black) # # self.bar = SubTheme('bar') # self.bar.set_color('background', black) # self.bar.font = Font('Consolas', 18) # self.bar.box_padding = Padding(2, 2, 2, 2) # self.bar.text_padding = Padding(2, 4, 7, 4) # self.bar.icon_spacing = 2 # self.bar.set_color('text_color', white) # self.bar.set_color('dim_color', gray) # self.bar.set_color('bright_color', orange) # self.bar.set_color('active_border', blue) # self.bar.set_color('subactive_border', gray) # self.bar.set_color('urgent_border', red) # self.bar.border_width = 2 # self.bar.height = 24 # self.bar.set_color('graph_color', blue) # self.bar.set_color('graph_fill_color', dark_blue) # self.bar.graph_line_width = 2 # self.bar.separator_width = 1 # self.bar.set_color('separator_color', gray) # # self.menu = SubTheme('bar') # self.menu.set_color('background', gray) # self.menu.set_color('text', white) # self.menu.set_color('highlight', blue) # self.menu.set_color('selection', blue) # self.menu.set_color('selection_text', white) # self.menu.set_color('cursor', black) # self.menu.font = Font('Consolas', 18) # self.menu.padding = Padding(2, 4, 7, 4) # self.menu.line_height = 24 # # self.hint = SubTheme('hint') # self.hint.font = Font('Consolas', 18) # self.hint.set_color('background', black) # self.hint.set_color('border_color', gray) # self.hint.set_color('text_color', white) # self.hint.border_width = 2 # self.hint.padding = Padding(5, 6, 9, 6) # # self.tabs = SubTheme('tabs') # self.tabs.font = Font('Monofur', 12) # self.tabs.set_color('background', black) # self.tabs.set_color('inactive_title', gray) # self.tabs.set_color('inactive_bg', black) # self.tabs.set_color('active_title', white) # self.tabs.set_color('active_bg', blue) # self.tabs.set_color('urgent_title', white) # self.tabs.set_color('urgent_bg', orange) # self.tabs.section_font = Font('Monofur', 12) # self.tabs.set_color('section_color', gray) # self.tabs.padding = Padding(5, 6, 6, 4) # self.tabs.margin = Padding(4, 4, 4, 4) # self.tabs.border_radius = 5 # self.tabs.spacing = 2 # self.tabs.icon_size = 14 # self.tabs.icon_spacing = 6 # self.tabs.section_padding = Padding(6, 2, 2, 2) # # def update_from(self, dic): # for key, sub in self.__dict__.items(): # if isinstance(sub, SubTheme) and key in dic: # sub.update_from(dic[key]) # # Path: tilenol/util.py # def fetchurl(url, query=None): # if query is not None: # assert '?' not in url, ("Either include query in url" # "or pass as parameter, but not both") # url += '?' + urlencode(query) # proto, tail = splittype(url) # if proto != 'http': # raise RuntimeError("Unsupported protocol HTTP") # host, tail = splithost(tail) # ip = gethub().dns_resolver.gethostbyname(host) # cli = HTTPClient(ip) # resp = cli.request(tail, headers={'Host': host}) # if resp.status.endswith('200 OK'): # return resp.body # raise RequestError(resp.status, resp) . Output only the next line.
data = fetchurl(img_url)
Here is a snippet: <|code_start|> @has_dependencies class Title(Widget): dispatcher = dependency(CommandDispatcher, 'commander') <|code_end|> . Write the next line using the current file imports: from zorro.di import di, has_dependencies, dependency from cairo import SolidPattern from .base import Widget from tilenol.commands import CommandDispatcher from tilenol.theme import Theme from tilenol.ewmh import get_title import cairo and context from other files: # Path: tilenol/widgets/base.py # class Widget(metaclass=ABCMeta): # # bar = dependency(Bar, 'bar') # stretched = False # # def __init__(self, right=False): # self.right = right # # @abstractmethod # def draw(self, canvas, left, right): # return left, right # # Path: tilenol/commands.py # class CommandDispatcher(dict): # # def __init__(self): # self.events = Events() # # def __setitem__(self, name, value): # super().__setitem__(name, value) # ev = self.events.get(name) # if ev is not None: # ev.emit() # # def call(self, obj, meth, *args): # getattr(self[obj], 'cmd_' + meth)(*args) # # def callback(self, *args): # return partial(self.call, *args) # # Path: tilenol/theme.py # class Theme(SubTheme): # # def __init__(self): # # blue = 0x4c4c99 # dark_blue = 0x191933 # orange = 0x99994c # gray = 0x808080 # red = 0x994c4c # black = 0x000000 # white = 0xffffff # # self.window = SubTheme('window') # self.window.border_width = 2 # self.window.set_color('active_border', blue) # self.window.set_color('inactive_border', gray) # self.window.set_color('background', black) # # self.bar = SubTheme('bar') # self.bar.set_color('background', black) # self.bar.font = Font('Consolas', 18) # self.bar.box_padding = Padding(2, 2, 2, 2) # self.bar.text_padding = Padding(2, 4, 7, 4) # self.bar.icon_spacing = 2 # self.bar.set_color('text_color', white) # self.bar.set_color('dim_color', gray) # self.bar.set_color('bright_color', orange) # self.bar.set_color('active_border', blue) # self.bar.set_color('subactive_border', gray) # self.bar.set_color('urgent_border', red) # self.bar.border_width = 2 # self.bar.height = 24 # self.bar.set_color('graph_color', blue) # self.bar.set_color('graph_fill_color', dark_blue) # self.bar.graph_line_width = 2 # self.bar.separator_width = 1 # self.bar.set_color('separator_color', gray) # # self.menu = SubTheme('bar') # self.menu.set_color('background', gray) # self.menu.set_color('text', white) # self.menu.set_color('highlight', blue) # self.menu.set_color('selection', blue) # self.menu.set_color('selection_text', white) # self.menu.set_color('cursor', black) # self.menu.font = Font('Consolas', 18) # self.menu.padding = Padding(2, 4, 7, 4) # self.menu.line_height = 24 # # self.hint = SubTheme('hint') # self.hint.font = Font('Consolas', 18) # self.hint.set_color('background', black) # self.hint.set_color('border_color', gray) # self.hint.set_color('text_color', white) # self.hint.border_width = 2 # self.hint.padding = Padding(5, 6, 9, 6) # # self.tabs = SubTheme('tabs') # self.tabs.font = Font('Monofur', 12) # self.tabs.set_color('background', black) # self.tabs.set_color('inactive_title', gray) # self.tabs.set_color('inactive_bg', black) # self.tabs.set_color('active_title', white) # self.tabs.set_color('active_bg', blue) # self.tabs.set_color('urgent_title', white) # self.tabs.set_color('urgent_bg', orange) # self.tabs.section_font = Font('Monofur', 12) # self.tabs.set_color('section_color', gray) # self.tabs.padding = Padding(5, 6, 6, 4) # self.tabs.margin = Padding(4, 4, 4, 4) # self.tabs.border_radius = 5 # self.tabs.spacing = 2 # self.tabs.icon_size = 14 # self.tabs.icon_spacing = 6 # self.tabs.section_padding = Padding(6, 2, 2, 2) # # def update_from(self, dic): # for key, sub in self.__dict__.items(): # if isinstance(sub, SubTheme) and key in dic: # sub.update_from(dic[key]) # # Path: tilenol/ewmh.py # def get_title(win): # return (win.props.get('_NET_WM_VISIBLE_NAME') # or win.props.get('_NET_WM_NAME') # or win.props.get('WM_NAME')) , which may include functions, classes, or code. Output only the next line.
theme = dependency(Theme, 'theme')
Using the snippet: <|code_start|> def get_file( self, name ): with open( os.path.join( self.path, name ), 'rt' ) as f: return f.read().strip() @property def charge( self ): return self._now/self._full @property def time_to_full( self ): return int( ( self._full - self._now )/self._power*MIN_IN_HOUR ) @property def time_to_empty( self ): return int( self._now/self._power*MIN_IN_HOUR ) @property def is_charging( self ): return self._status == 'charging' @property def is_unknown_status( self ): return self._status == 'unknown' @property def has_full_charge( self ): return self.charge > 0.99 or self._power == 0 @has_dependencies <|code_end|> , determine the next line of code. You have imports: import os.path import threading import time import errno from cairo import SolidPattern from zorro.di import has_dependencies, dependency from .base import Widget from tilenol.theme import Theme and context (class names, function names, or code) available: # Path: tilenol/widgets/base.py # class Widget(metaclass=ABCMeta): # # bar = dependency(Bar, 'bar') # stretched = False # # def __init__(self, right=False): # self.right = right # # @abstractmethod # def draw(self, canvas, left, right): # return left, right # # Path: tilenol/theme.py # class Theme(SubTheme): # # def __init__(self): # # blue = 0x4c4c99 # dark_blue = 0x191933 # orange = 0x99994c # gray = 0x808080 # red = 0x994c4c # black = 0x000000 # white = 0xffffff # # self.window = SubTheme('window') # self.window.border_width = 2 # self.window.set_color('active_border', blue) # self.window.set_color('inactive_border', gray) # self.window.set_color('background', black) # # self.bar = SubTheme('bar') # self.bar.set_color('background', black) # self.bar.font = Font('Consolas', 18) # self.bar.box_padding = Padding(2, 2, 2, 2) # self.bar.text_padding = Padding(2, 4, 7, 4) # self.bar.icon_spacing = 2 # self.bar.set_color('text_color', white) # self.bar.set_color('dim_color', gray) # self.bar.set_color('bright_color', orange) # self.bar.set_color('active_border', blue) # self.bar.set_color('subactive_border', gray) # self.bar.set_color('urgent_border', red) # self.bar.border_width = 2 # self.bar.height = 24 # self.bar.set_color('graph_color', blue) # self.bar.set_color('graph_fill_color', dark_blue) # self.bar.graph_line_width = 2 # self.bar.separator_width = 1 # self.bar.set_color('separator_color', gray) # # self.menu = SubTheme('bar') # self.menu.set_color('background', gray) # self.menu.set_color('text', white) # self.menu.set_color('highlight', blue) # self.menu.set_color('selection', blue) # self.menu.set_color('selection_text', white) # self.menu.set_color('cursor', black) # self.menu.font = Font('Consolas', 18) # self.menu.padding = Padding(2, 4, 7, 4) # self.menu.line_height = 24 # # self.hint = SubTheme('hint') # self.hint.font = Font('Consolas', 18) # self.hint.set_color('background', black) # self.hint.set_color('border_color', gray) # self.hint.set_color('text_color', white) # self.hint.border_width = 2 # self.hint.padding = Padding(5, 6, 9, 6) # # self.tabs = SubTheme('tabs') # self.tabs.font = Font('Monofur', 12) # self.tabs.set_color('background', black) # self.tabs.set_color('inactive_title', gray) # self.tabs.set_color('inactive_bg', black) # self.tabs.set_color('active_title', white) # self.tabs.set_color('active_bg', blue) # self.tabs.set_color('urgent_title', white) # self.tabs.set_color('urgent_bg', orange) # self.tabs.section_font = Font('Monofur', 12) # self.tabs.set_color('section_color', gray) # self.tabs.padding = Padding(5, 6, 6, 4) # self.tabs.margin = Padding(4, 4, 4, 4) # self.tabs.border_radius = 5 # self.tabs.spacing = 2 # self.tabs.icon_size = 14 # self.tabs.icon_spacing = 6 # self.tabs.section_padding = Padding(6, 2, 2, 2) # # def update_from(self, dic): # for key, sub in self.__dict__.items(): # if isinstance(sub, SubTheme) and key in dic: # sub.update_from(dic[key]) . Output only the next line.
class Battery(Widget):
Next line prediction: <|code_start|> return f.read().strip() @property def charge( self ): return self._now/self._full @property def time_to_full( self ): return int( ( self._full - self._now )/self._power*MIN_IN_HOUR ) @property def time_to_empty( self ): return int( self._now/self._power*MIN_IN_HOUR ) @property def is_charging( self ): return self._status == 'charging' @property def is_unknown_status( self ): return self._status == 'unknown' @property def has_full_charge( self ): return self.charge > 0.99 or self._power == 0 @has_dependencies class Battery(Widget): <|code_end|> . Use current file imports: (import os.path import threading import time import errno from cairo import SolidPattern from zorro.di import has_dependencies, dependency from .base import Widget from tilenol.theme import Theme) and context including class names, function names, or small code snippets from other files: # Path: tilenol/widgets/base.py # class Widget(metaclass=ABCMeta): # # bar = dependency(Bar, 'bar') # stretched = False # # def __init__(self, right=False): # self.right = right # # @abstractmethod # def draw(self, canvas, left, right): # return left, right # # Path: tilenol/theme.py # class Theme(SubTheme): # # def __init__(self): # # blue = 0x4c4c99 # dark_blue = 0x191933 # orange = 0x99994c # gray = 0x808080 # red = 0x994c4c # black = 0x000000 # white = 0xffffff # # self.window = SubTheme('window') # self.window.border_width = 2 # self.window.set_color('active_border', blue) # self.window.set_color('inactive_border', gray) # self.window.set_color('background', black) # # self.bar = SubTheme('bar') # self.bar.set_color('background', black) # self.bar.font = Font('Consolas', 18) # self.bar.box_padding = Padding(2, 2, 2, 2) # self.bar.text_padding = Padding(2, 4, 7, 4) # self.bar.icon_spacing = 2 # self.bar.set_color('text_color', white) # self.bar.set_color('dim_color', gray) # self.bar.set_color('bright_color', orange) # self.bar.set_color('active_border', blue) # self.bar.set_color('subactive_border', gray) # self.bar.set_color('urgent_border', red) # self.bar.border_width = 2 # self.bar.height = 24 # self.bar.set_color('graph_color', blue) # self.bar.set_color('graph_fill_color', dark_blue) # self.bar.graph_line_width = 2 # self.bar.separator_width = 1 # self.bar.set_color('separator_color', gray) # # self.menu = SubTheme('bar') # self.menu.set_color('background', gray) # self.menu.set_color('text', white) # self.menu.set_color('highlight', blue) # self.menu.set_color('selection', blue) # self.menu.set_color('selection_text', white) # self.menu.set_color('cursor', black) # self.menu.font = Font('Consolas', 18) # self.menu.padding = Padding(2, 4, 7, 4) # self.menu.line_height = 24 # # self.hint = SubTheme('hint') # self.hint.font = Font('Consolas', 18) # self.hint.set_color('background', black) # self.hint.set_color('border_color', gray) # self.hint.set_color('text_color', white) # self.hint.border_width = 2 # self.hint.padding = Padding(5, 6, 9, 6) # # self.tabs = SubTheme('tabs') # self.tabs.font = Font('Monofur', 12) # self.tabs.set_color('background', black) # self.tabs.set_color('inactive_title', gray) # self.tabs.set_color('inactive_bg', black) # self.tabs.set_color('active_title', white) # self.tabs.set_color('active_bg', blue) # self.tabs.set_color('urgent_title', white) # self.tabs.set_color('urgent_bg', orange) # self.tabs.section_font = Font('Monofur', 12) # self.tabs.set_color('section_color', gray) # self.tabs.padding = Padding(5, 6, 6, 4) # self.tabs.margin = Padding(4, 4, 4, 4) # self.tabs.border_radius = 5 # self.tabs.spacing = 2 # self.tabs.icon_size = 14 # self.tabs.icon_spacing = 6 # self.tabs.section_padding = Padding(6, 2, 2, 2) # # def update_from(self, dic): # for key, sub in self.__dict__.items(): # if isinstance(sub, SubTheme) and key in dic: # sub.update_from(dic[key]) . Output only the next line.
theme = dependency(Theme, 'theme')
Here is a snippet: <|code_start|> def setter(win): win.ignore_hints = True return setter def ignore_protocols(*ignore): def setter(win): win.ignore_protocols.update(ignore) win.protocols -= win.ignore_protocols return setter def move_to_group_of(prop): def setter(win): wid = win.props[prop][0] other = di(win)['event-dispatcher'].all_windows[wid] win.lprops.group = other.lprops.group return setter def move_to_group(group): def setter(win): gman = di(win)['group-manager'] if group in gman.by_name: win.lprops.group = gman.groups.index(gman.by_name[group]) return setter all_conditions = { 'match-role': match_role, <|code_end|> . Write the next line using the current file imports: from zorro.di import di from .ewmh import match_type and context from other files: # Path: tilenol/ewmh.py # def match_type(*types): # types = tuple('_NET_WM_WINDOW_TYPE_' + typ.upper() for typ in types) # assert all(typ.isidentifier() for typ in types) # def type_checker(win): # for typ in types: # rtype = getattr(win.xcore.atom, typ) # if rtype in win.props.get('_NET_WM_WINDOW_TYPE', ()): # return True # return type_checker , which may include functions, classes, or code. Output only the next line.
'match-type': match_type,
Based on the snippet: <|code_start|>try: except ImportError: class Window(object): def set_bounds(self, rect): <|code_end|> , predict the immediate next line with the help of imports: import unittest import mock from unittest import mock # builtin mock in 3.3 from tilenol.xcb import Rectangle from tilenol.layout.examples import Tile from tilenol.layout import Split, Stack, TileStack from tilenol.layout import Split, Stack, TileStack and context (classes, functions, sometimes code) from other files: # Path: tilenol/xcb/core.py # class Rectangle(namedtuple('_Rectangle', 'x y width height')): # __slots__ = () . Output only the next line.
assert isinstance(rect, Rectangle)
Continue the code snippet: <|code_start|> else: ln = ln*4+32 if len(buf)-pos < ln: break val = buf[pos:pos+2] + buf[pos+8:pos+ln] pos += ln self.produce(seq, val) class Connection(object): def __init__(self, proto, display=None, auth_file=None, auth_type=None, auth_key=None): self.proto = proto if display is None: display = os.environ.get('DISPLAY', ':0') if auth_file is None and auth_type is None: auth_file = os.environ.get('XAUTHORITY') if auth_file is None: auth_file = os.path.expanduser('~/.XAuthority') host, port = display.split(':') if '.' in port: maj, min = map(int, port.split('.')) else: maj = int(port) min = 0 assert min == 0, 'Subdisplays are not not supported so far' if auth_type is None: if host != "": haddr = socket.inet_aton(socket.gethostbyname(host)) <|code_end|> . Use current file imports: import os.path import socket import re import errno import struct import traceback import logging from math import ceil from functools import partial from collections import namedtuple, deque from zorro import channel, Lock, gethub, Condition, Future from zorro.util import setcloexec from .auth import read_auth and context (classes, functions, or code) from other files: # Path: tilenol/xcb/auth.py # def read_auth(filename=os.path.expanduser("~/.Xauthority")): # def rstr(): # val, = struct.unpack('>H', f.read(2)) # return f.read(val) # with open(filename, 'rb') as f: # while True: # head = f.read(2) # if not head: # break # family, = struct.unpack('<H', head) # yield Auth(family, rstr(), int(rstr()), rstr(), rstr()) . Output only the next line.
for auth in read_auth():
Given snippet: <|code_start|> GRAD = pi/180 rotations = { 'up': 0*GRAD, 'upright': 45*GRAD, 'right': 90*GRAD, 'downright': 135*GRAD, 'down': 180*GRAD, 'downleft': -135*GRAD, 'left': -90*GRAD, 'upleft': -45*GRAD, } @has_dependencies <|code_end|> , continue by predicting the next line. Consider current file imports: from math import pi from zorro.di import dependency, has_dependencies from .base import Widget from tilenol.theme import Theme from tilenol import gestures as G and context: # Path: tilenol/widgets/base.py # class Widget(metaclass=ABCMeta): # # bar = dependency(Bar, 'bar') # stretched = False # # def __init__(self, right=False): # self.right = right # # @abstractmethod # def draw(self, canvas, left, right): # return left, right # # Path: tilenol/theme.py # class Theme(SubTheme): # # def __init__(self): # # blue = 0x4c4c99 # dark_blue = 0x191933 # orange = 0x99994c # gray = 0x808080 # red = 0x994c4c # black = 0x000000 # white = 0xffffff # # self.window = SubTheme('window') # self.window.border_width = 2 # self.window.set_color('active_border', blue) # self.window.set_color('inactive_border', gray) # self.window.set_color('background', black) # # self.bar = SubTheme('bar') # self.bar.set_color('background', black) # self.bar.font = Font('Consolas', 18) # self.bar.box_padding = Padding(2, 2, 2, 2) # self.bar.text_padding = Padding(2, 4, 7, 4) # self.bar.icon_spacing = 2 # self.bar.set_color('text_color', white) # self.bar.set_color('dim_color', gray) # self.bar.set_color('bright_color', orange) # self.bar.set_color('active_border', blue) # self.bar.set_color('subactive_border', gray) # self.bar.set_color('urgent_border', red) # self.bar.border_width = 2 # self.bar.height = 24 # self.bar.set_color('graph_color', blue) # self.bar.set_color('graph_fill_color', dark_blue) # self.bar.graph_line_width = 2 # self.bar.separator_width = 1 # self.bar.set_color('separator_color', gray) # # self.menu = SubTheme('bar') # self.menu.set_color('background', gray) # self.menu.set_color('text', white) # self.menu.set_color('highlight', blue) # self.menu.set_color('selection', blue) # self.menu.set_color('selection_text', white) # self.menu.set_color('cursor', black) # self.menu.font = Font('Consolas', 18) # self.menu.padding = Padding(2, 4, 7, 4) # self.menu.line_height = 24 # # self.hint = SubTheme('hint') # self.hint.font = Font('Consolas', 18) # self.hint.set_color('background', black) # self.hint.set_color('border_color', gray) # self.hint.set_color('text_color', white) # self.hint.border_width = 2 # self.hint.padding = Padding(5, 6, 9, 6) # # self.tabs = SubTheme('tabs') # self.tabs.font = Font('Monofur', 12) # self.tabs.set_color('background', black) # self.tabs.set_color('inactive_title', gray) # self.tabs.set_color('inactive_bg', black) # self.tabs.set_color('active_title', white) # self.tabs.set_color('active_bg', blue) # self.tabs.set_color('urgent_title', white) # self.tabs.set_color('urgent_bg', orange) # self.tabs.section_font = Font('Monofur', 12) # self.tabs.set_color('section_color', gray) # self.tabs.padding = Padding(5, 6, 6, 4) # self.tabs.margin = Padding(4, 4, 4, 4) # self.tabs.border_radius = 5 # self.tabs.spacing = 2 # self.tabs.icon_size = 14 # self.tabs.icon_spacing = 6 # self.tabs.section_padding = Padding(6, 2, 2, 2) # # def update_from(self, dic): # for key, sub in self.__dict__.items(): # if isinstance(sub, SubTheme) and key in dic: # sub.update_from(dic[key]) # # Path: tilenol/gestures.py # GRAD = pi/180 # SYNAPTICS_SHM = 23947 # START = marker_object('gestures.START') # PARTIAL = marker_object('gestures.PARTIAL') # FULL = marker_object('gestures.FULL') # COMMIT = marker_object('gestures.COMMIT') # UNDO = marker_object('gestures.UNDO') # CANCEL = marker_object('gestures.CANCEL') # class SynapticsSHM(ctypes.Structure): # class Gestures(object): # def __init__(self): # def __zorro_di_done__(self): # def add_callback(self, name, fun): # def active_gestures(self): # def _shm_checker(self): # def _shm_loop(self, ptr): which might include code, classes, or functions. Output only the next line.
class Gesture(Widget):
Here is a snippet: <|code_start|> GRAD = pi/180 rotations = { 'up': 0*GRAD, 'upright': 45*GRAD, 'right': 90*GRAD, 'downright': 135*GRAD, 'down': 180*GRAD, 'downleft': -135*GRAD, 'left': -90*GRAD, 'upleft': -45*GRAD, } @has_dependencies class Gesture(Widget): <|code_end|> . Write the next line using the current file imports: from math import pi from zorro.di import dependency, has_dependencies from .base import Widget from tilenol.theme import Theme from tilenol import gestures as G and context from other files: # Path: tilenol/widgets/base.py # class Widget(metaclass=ABCMeta): # # bar = dependency(Bar, 'bar') # stretched = False # # def __init__(self, right=False): # self.right = right # # @abstractmethod # def draw(self, canvas, left, right): # return left, right # # Path: tilenol/theme.py # class Theme(SubTheme): # # def __init__(self): # # blue = 0x4c4c99 # dark_blue = 0x191933 # orange = 0x99994c # gray = 0x808080 # red = 0x994c4c # black = 0x000000 # white = 0xffffff # # self.window = SubTheme('window') # self.window.border_width = 2 # self.window.set_color('active_border', blue) # self.window.set_color('inactive_border', gray) # self.window.set_color('background', black) # # self.bar = SubTheme('bar') # self.bar.set_color('background', black) # self.bar.font = Font('Consolas', 18) # self.bar.box_padding = Padding(2, 2, 2, 2) # self.bar.text_padding = Padding(2, 4, 7, 4) # self.bar.icon_spacing = 2 # self.bar.set_color('text_color', white) # self.bar.set_color('dim_color', gray) # self.bar.set_color('bright_color', orange) # self.bar.set_color('active_border', blue) # self.bar.set_color('subactive_border', gray) # self.bar.set_color('urgent_border', red) # self.bar.border_width = 2 # self.bar.height = 24 # self.bar.set_color('graph_color', blue) # self.bar.set_color('graph_fill_color', dark_blue) # self.bar.graph_line_width = 2 # self.bar.separator_width = 1 # self.bar.set_color('separator_color', gray) # # self.menu = SubTheme('bar') # self.menu.set_color('background', gray) # self.menu.set_color('text', white) # self.menu.set_color('highlight', blue) # self.menu.set_color('selection', blue) # self.menu.set_color('selection_text', white) # self.menu.set_color('cursor', black) # self.menu.font = Font('Consolas', 18) # self.menu.padding = Padding(2, 4, 7, 4) # self.menu.line_height = 24 # # self.hint = SubTheme('hint') # self.hint.font = Font('Consolas', 18) # self.hint.set_color('background', black) # self.hint.set_color('border_color', gray) # self.hint.set_color('text_color', white) # self.hint.border_width = 2 # self.hint.padding = Padding(5, 6, 9, 6) # # self.tabs = SubTheme('tabs') # self.tabs.font = Font('Monofur', 12) # self.tabs.set_color('background', black) # self.tabs.set_color('inactive_title', gray) # self.tabs.set_color('inactive_bg', black) # self.tabs.set_color('active_title', white) # self.tabs.set_color('active_bg', blue) # self.tabs.set_color('urgent_title', white) # self.tabs.set_color('urgent_bg', orange) # self.tabs.section_font = Font('Monofur', 12) # self.tabs.set_color('section_color', gray) # self.tabs.padding = Padding(5, 6, 6, 4) # self.tabs.margin = Padding(4, 4, 4, 4) # self.tabs.border_radius = 5 # self.tabs.spacing = 2 # self.tabs.icon_size = 14 # self.tabs.icon_spacing = 6 # self.tabs.section_padding = Padding(6, 2, 2, 2) # # def update_from(self, dic): # for key, sub in self.__dict__.items(): # if isinstance(sub, SubTheme) and key in dic: # sub.update_from(dic[key]) # # Path: tilenol/gestures.py # GRAD = pi/180 # SYNAPTICS_SHM = 23947 # START = marker_object('gestures.START') # PARTIAL = marker_object('gestures.PARTIAL') # FULL = marker_object('gestures.FULL') # COMMIT = marker_object('gestures.COMMIT') # UNDO = marker_object('gestures.UNDO') # CANCEL = marker_object('gestures.CANCEL') # class SynapticsSHM(ctypes.Structure): # class Gestures(object): # def __init__(self): # def __zorro_di_done__(self): # def add_callback(self, name, fun): # def active_gestures(self): # def _shm_checker(self): # def _shm_loop(self, ptr): , which may include functions, classes, or code. Output only the next line.
theme = dependency(Theme, 'theme')
Continue the code snippet: <|code_start|> GRAD = pi/180 rotations = { 'up': 0*GRAD, 'upright': 45*GRAD, 'right': 90*GRAD, 'downright': 135*GRAD, 'down': 180*GRAD, 'downleft': -135*GRAD, 'left': -90*GRAD, 'upleft': -45*GRAD, } @has_dependencies class Gesture(Widget): theme = dependency(Theme, 'theme') <|code_end|> . Use current file imports: from math import pi from zorro.di import dependency, has_dependencies from .base import Widget from tilenol.theme import Theme from tilenol import gestures as G and context (classes, functions, or code) from other files: # Path: tilenol/widgets/base.py # class Widget(metaclass=ABCMeta): # # bar = dependency(Bar, 'bar') # stretched = False # # def __init__(self, right=False): # self.right = right # # @abstractmethod # def draw(self, canvas, left, right): # return left, right # # Path: tilenol/theme.py # class Theme(SubTheme): # # def __init__(self): # # blue = 0x4c4c99 # dark_blue = 0x191933 # orange = 0x99994c # gray = 0x808080 # red = 0x994c4c # black = 0x000000 # white = 0xffffff # # self.window = SubTheme('window') # self.window.border_width = 2 # self.window.set_color('active_border', blue) # self.window.set_color('inactive_border', gray) # self.window.set_color('background', black) # # self.bar = SubTheme('bar') # self.bar.set_color('background', black) # self.bar.font = Font('Consolas', 18) # self.bar.box_padding = Padding(2, 2, 2, 2) # self.bar.text_padding = Padding(2, 4, 7, 4) # self.bar.icon_spacing = 2 # self.bar.set_color('text_color', white) # self.bar.set_color('dim_color', gray) # self.bar.set_color('bright_color', orange) # self.bar.set_color('active_border', blue) # self.bar.set_color('subactive_border', gray) # self.bar.set_color('urgent_border', red) # self.bar.border_width = 2 # self.bar.height = 24 # self.bar.set_color('graph_color', blue) # self.bar.set_color('graph_fill_color', dark_blue) # self.bar.graph_line_width = 2 # self.bar.separator_width = 1 # self.bar.set_color('separator_color', gray) # # self.menu = SubTheme('bar') # self.menu.set_color('background', gray) # self.menu.set_color('text', white) # self.menu.set_color('highlight', blue) # self.menu.set_color('selection', blue) # self.menu.set_color('selection_text', white) # self.menu.set_color('cursor', black) # self.menu.font = Font('Consolas', 18) # self.menu.padding = Padding(2, 4, 7, 4) # self.menu.line_height = 24 # # self.hint = SubTheme('hint') # self.hint.font = Font('Consolas', 18) # self.hint.set_color('background', black) # self.hint.set_color('border_color', gray) # self.hint.set_color('text_color', white) # self.hint.border_width = 2 # self.hint.padding = Padding(5, 6, 9, 6) # # self.tabs = SubTheme('tabs') # self.tabs.font = Font('Monofur', 12) # self.tabs.set_color('background', black) # self.tabs.set_color('inactive_title', gray) # self.tabs.set_color('inactive_bg', black) # self.tabs.set_color('active_title', white) # self.tabs.set_color('active_bg', blue) # self.tabs.set_color('urgent_title', white) # self.tabs.set_color('urgent_bg', orange) # self.tabs.section_font = Font('Monofur', 12) # self.tabs.set_color('section_color', gray) # self.tabs.padding = Padding(5, 6, 6, 4) # self.tabs.margin = Padding(4, 4, 4, 4) # self.tabs.border_radius = 5 # self.tabs.spacing = 2 # self.tabs.icon_size = 14 # self.tabs.icon_spacing = 6 # self.tabs.section_padding = Padding(6, 2, 2, 2) # # def update_from(self, dic): # for key, sub in self.__dict__.items(): # if isinstance(sub, SubTheme) and key in dic: # sub.update_from(dic[key]) # # Path: tilenol/gestures.py # GRAD = pi/180 # SYNAPTICS_SHM = 23947 # START = marker_object('gestures.START') # PARTIAL = marker_object('gestures.PARTIAL') # FULL = marker_object('gestures.FULL') # COMMIT = marker_object('gestures.COMMIT') # UNDO = marker_object('gestures.UNDO') # CANCEL = marker_object('gestures.CANCEL') # class SynapticsSHM(ctypes.Structure): # class Gestures(object): # def __init__(self): # def __zorro_di_done__(self): # def add_callback(self, name, fun): # def active_gestures(self): # def _shm_checker(self): # def _shm_loop(self, ptr): . Output only the next line.
gestures = dependency(G.Gestures, 'gestures')
Predict the next line for this snippet: <|code_start|> route = [ (r"/",Index.index), (r"/([0-9]+)/?",Img.category), (r"/addLink/?",Img.addLink), (r"/addCate/?",VIP.addCate), (r"/Admin/addviptime/?",Admin.AddVipTime), (r"/Admin/suggest/?",Admin.AdminSuggest), (r"/addKeyword/?",Img.addKeyword), (r"/album/?",Index.album), (r"/clearMessage/?",User.ClearMessage), (r"/comment/?",Img.comment), (r"/delComment/?",User.delComment), (r"/FollowUser/?",User.FollowUserAction), (r"/FollowCate/?",User.FollowCate), (r"/img/([0-9a-zA-Z\_\-]+)/?",Img.img), (r"/nextimg/(.+)/?",Img.next), (r"/message/?",SomePage.Message), (r"/myAlbum/?",VIP.myAlbum), (r"/myAlbum/edit/([0-9]+)/?",VIP.editMyAlbum), <|code_end|> with the help of current file imports: from handlers import Index from handlers import Img from handlers import Search from handlers import User from handlers import SomePage from handlers import Admin from handlers import VIP and context from other files: # Path: handlers/Index.py # class album(BaseHandler): # class index(BaseHandler): # class qiniu(BaseHandler): # class upjson(BaseHandler): # def get(self): # def get(self): # def get(self): # def get(self): # # Path: handlers/Img.py # class addKeyword(BaseHandler): # class addLink(BaseHandler): # class next(BaseHandler): # class comment(BaseHandler): # class img(BaseHandler): # class category(BaseHandler): # def post(self): # def post(self): # def get(self,img_url): # def get(self): # def post(self): # def get(self,img_url): # def get(self,cate_url): # # Path: handlers/Search.py # class search(BaseHandler): # class tags(BaseHandler): # def post(self): # def get(self,keyword): # # Path: handlers/User.py # class delComment(BaseHandler): # class QQ(BaseHandler): # class UserPage(BaseHandler): # class home(BaseHandler): # class editImg(BaseHandler): # class Reg(BaseHandler): # class login(BaseHandler): # class FollowCate(BaseHandler): # class QuitCate(BaseHandler): # class FollowUserAction(BaseHandler): # class QuitFollow(BaseHandler): # class ClearMessage(BaseHandler): # class logout(BaseHandler): # def put(self): # def get(self): # def post(self): # def get(self,pageuser): # def get(self): # def get(self,imgId): # def post(self,imgId): # def get(self): # def post(self): # def get(self): # def post(self): # def put(self): # def put(self): # def put(self): # def put(self): # def put(self): # def get(self): # # Path: handlers/SomePage.py # class VIP(BaseHandler): # class Message(BaseHandler): # class Suggest(BaseHandler): # class Rule(BaseHandler): # def get(self): # def get(self): # def post(self): # def get(self): # # Path: handlers/Admin.py # class AddVipTime(BaseHandler): # class AdminSuggest(BaseHandler): # def get(self): # def post(self): # def get(self): # # Path: handlers/VIP.py # class editMyAlbum(BaseHandler): # class myAlbum(BaseHandler): # class addCate(BaseHandler): # def get(self,cateId): # def post(self,cateId): # def get(self): # def post(self): , which may contain function names, class names, or code. Output only the next line.
(r"/search/?",Search.search),
Here is a snippet: <|code_start|> route = [ (r"/",Index.index), (r"/([0-9]+)/?",Img.category), (r"/addLink/?",Img.addLink), (r"/addCate/?",VIP.addCate), (r"/Admin/addviptime/?",Admin.AddVipTime), (r"/Admin/suggest/?",Admin.AdminSuggest), (r"/addKeyword/?",Img.addKeyword), (r"/album/?",Index.album), <|code_end|> . Write the next line using the current file imports: from handlers import Index from handlers import Img from handlers import Search from handlers import User from handlers import SomePage from handlers import Admin from handlers import VIP and context from other files: # Path: handlers/Index.py # class album(BaseHandler): # class index(BaseHandler): # class qiniu(BaseHandler): # class upjson(BaseHandler): # def get(self): # def get(self): # def get(self): # def get(self): # # Path: handlers/Img.py # class addKeyword(BaseHandler): # class addLink(BaseHandler): # class next(BaseHandler): # class comment(BaseHandler): # class img(BaseHandler): # class category(BaseHandler): # def post(self): # def post(self): # def get(self,img_url): # def get(self): # def post(self): # def get(self,img_url): # def get(self,cate_url): # # Path: handlers/Search.py # class search(BaseHandler): # class tags(BaseHandler): # def post(self): # def get(self,keyword): # # Path: handlers/User.py # class delComment(BaseHandler): # class QQ(BaseHandler): # class UserPage(BaseHandler): # class home(BaseHandler): # class editImg(BaseHandler): # class Reg(BaseHandler): # class login(BaseHandler): # class FollowCate(BaseHandler): # class QuitCate(BaseHandler): # class FollowUserAction(BaseHandler): # class QuitFollow(BaseHandler): # class ClearMessage(BaseHandler): # class logout(BaseHandler): # def put(self): # def get(self): # def post(self): # def get(self,pageuser): # def get(self): # def get(self,imgId): # def post(self,imgId): # def get(self): # def post(self): # def get(self): # def post(self): # def put(self): # def put(self): # def put(self): # def put(self): # def put(self): # def get(self): # # Path: handlers/SomePage.py # class VIP(BaseHandler): # class Message(BaseHandler): # class Suggest(BaseHandler): # class Rule(BaseHandler): # def get(self): # def get(self): # def post(self): # def get(self): # # Path: handlers/Admin.py # class AddVipTime(BaseHandler): # class AdminSuggest(BaseHandler): # def get(self): # def post(self): # def get(self): # # Path: handlers/VIP.py # class editMyAlbum(BaseHandler): # class myAlbum(BaseHandler): # class addCate(BaseHandler): # def get(self,cateId): # def post(self,cateId): # def get(self): # def post(self): , which may include functions, classes, or code. Output only the next line.
(r"/clearMessage/?",User.ClearMessage),
Next line prediction: <|code_start|> route = [ (r"/",Index.index), (r"/([0-9]+)/?",Img.category), (r"/addLink/?",Img.addLink), (r"/addCate/?",VIP.addCate), (r"/Admin/addviptime/?",Admin.AddVipTime), (r"/Admin/suggest/?",Admin.AdminSuggest), (r"/addKeyword/?",Img.addKeyword), (r"/album/?",Index.album), (r"/clearMessage/?",User.ClearMessage), (r"/comment/?",Img.comment), (r"/delComment/?",User.delComment), (r"/FollowUser/?",User.FollowUserAction), (r"/FollowCate/?",User.FollowCate), (r"/img/([0-9a-zA-Z\_\-]+)/?",Img.img), (r"/nextimg/(.+)/?",Img.next), <|code_end|> . Use current file imports: (from handlers import Index from handlers import Img from handlers import Search from handlers import User from handlers import SomePage from handlers import Admin from handlers import VIP) and context including class names, function names, or small code snippets from other files: # Path: handlers/Index.py # class album(BaseHandler): # class index(BaseHandler): # class qiniu(BaseHandler): # class upjson(BaseHandler): # def get(self): # def get(self): # def get(self): # def get(self): # # Path: handlers/Img.py # class addKeyword(BaseHandler): # class addLink(BaseHandler): # class next(BaseHandler): # class comment(BaseHandler): # class img(BaseHandler): # class category(BaseHandler): # def post(self): # def post(self): # def get(self,img_url): # def get(self): # def post(self): # def get(self,img_url): # def get(self,cate_url): # # Path: handlers/Search.py # class search(BaseHandler): # class tags(BaseHandler): # def post(self): # def get(self,keyword): # # Path: handlers/User.py # class delComment(BaseHandler): # class QQ(BaseHandler): # class UserPage(BaseHandler): # class home(BaseHandler): # class editImg(BaseHandler): # class Reg(BaseHandler): # class login(BaseHandler): # class FollowCate(BaseHandler): # class QuitCate(BaseHandler): # class FollowUserAction(BaseHandler): # class QuitFollow(BaseHandler): # class ClearMessage(BaseHandler): # class logout(BaseHandler): # def put(self): # def get(self): # def post(self): # def get(self,pageuser): # def get(self): # def get(self,imgId): # def post(self,imgId): # def get(self): # def post(self): # def get(self): # def post(self): # def put(self): # def put(self): # def put(self): # def put(self): # def put(self): # def get(self): # # Path: handlers/SomePage.py # class VIP(BaseHandler): # class Message(BaseHandler): # class Suggest(BaseHandler): # class Rule(BaseHandler): # def get(self): # def get(self): # def post(self): # def get(self): # # Path: handlers/Admin.py # class AddVipTime(BaseHandler): # class AdminSuggest(BaseHandler): # def get(self): # def post(self): # def get(self): # # Path: handlers/VIP.py # class editMyAlbum(BaseHandler): # class myAlbum(BaseHandler): # class addCate(BaseHandler): # def get(self,cateId): # def post(self,cateId): # def get(self): # def post(self): . Output only the next line.
(r"/message/?",SomePage.Message),
Here is a snippet: <|code_start|> route = [ (r"/",Index.index), (r"/([0-9]+)/?",Img.category), (r"/addLink/?",Img.addLink), (r"/addCate/?",VIP.addCate), <|code_end|> . Write the next line using the current file imports: from handlers import Index from handlers import Img from handlers import Search from handlers import User from handlers import SomePage from handlers import Admin from handlers import VIP and context from other files: # Path: handlers/Index.py # class album(BaseHandler): # class index(BaseHandler): # class qiniu(BaseHandler): # class upjson(BaseHandler): # def get(self): # def get(self): # def get(self): # def get(self): # # Path: handlers/Img.py # class addKeyword(BaseHandler): # class addLink(BaseHandler): # class next(BaseHandler): # class comment(BaseHandler): # class img(BaseHandler): # class category(BaseHandler): # def post(self): # def post(self): # def get(self,img_url): # def get(self): # def post(self): # def get(self,img_url): # def get(self,cate_url): # # Path: handlers/Search.py # class search(BaseHandler): # class tags(BaseHandler): # def post(self): # def get(self,keyword): # # Path: handlers/User.py # class delComment(BaseHandler): # class QQ(BaseHandler): # class UserPage(BaseHandler): # class home(BaseHandler): # class editImg(BaseHandler): # class Reg(BaseHandler): # class login(BaseHandler): # class FollowCate(BaseHandler): # class QuitCate(BaseHandler): # class FollowUserAction(BaseHandler): # class QuitFollow(BaseHandler): # class ClearMessage(BaseHandler): # class logout(BaseHandler): # def put(self): # def get(self): # def post(self): # def get(self,pageuser): # def get(self): # def get(self,imgId): # def post(self,imgId): # def get(self): # def post(self): # def get(self): # def post(self): # def put(self): # def put(self): # def put(self): # def put(self): # def put(self): # def get(self): # # Path: handlers/SomePage.py # class VIP(BaseHandler): # class Message(BaseHandler): # class Suggest(BaseHandler): # class Rule(BaseHandler): # def get(self): # def get(self): # def post(self): # def get(self): # # Path: handlers/Admin.py # class AddVipTime(BaseHandler): # class AdminSuggest(BaseHandler): # def get(self): # def post(self): # def get(self): # # Path: handlers/VIP.py # class editMyAlbum(BaseHandler): # class myAlbum(BaseHandler): # class addCate(BaseHandler): # def get(self,cateId): # def post(self,cateId): # def get(self): # def post(self): , which may include functions, classes, or code. Output only the next line.
(r"/Admin/addviptime/?",Admin.AddVipTime),
Given the code snippet: <|code_start|> route = [ (r"/",Index.index), (r"/([0-9]+)/?",Img.category), (r"/addLink/?",Img.addLink), <|code_end|> , generate the next line using the imports in this file: from handlers import Index from handlers import Img from handlers import Search from handlers import User from handlers import SomePage from handlers import Admin from handlers import VIP and context (functions, classes, or occasionally code) from other files: # Path: handlers/Index.py # class album(BaseHandler): # class index(BaseHandler): # class qiniu(BaseHandler): # class upjson(BaseHandler): # def get(self): # def get(self): # def get(self): # def get(self): # # Path: handlers/Img.py # class addKeyword(BaseHandler): # class addLink(BaseHandler): # class next(BaseHandler): # class comment(BaseHandler): # class img(BaseHandler): # class category(BaseHandler): # def post(self): # def post(self): # def get(self,img_url): # def get(self): # def post(self): # def get(self,img_url): # def get(self,cate_url): # # Path: handlers/Search.py # class search(BaseHandler): # class tags(BaseHandler): # def post(self): # def get(self,keyword): # # Path: handlers/User.py # class delComment(BaseHandler): # class QQ(BaseHandler): # class UserPage(BaseHandler): # class home(BaseHandler): # class editImg(BaseHandler): # class Reg(BaseHandler): # class login(BaseHandler): # class FollowCate(BaseHandler): # class QuitCate(BaseHandler): # class FollowUserAction(BaseHandler): # class QuitFollow(BaseHandler): # class ClearMessage(BaseHandler): # class logout(BaseHandler): # def put(self): # def get(self): # def post(self): # def get(self,pageuser): # def get(self): # def get(self,imgId): # def post(self,imgId): # def get(self): # def post(self): # def get(self): # def post(self): # def put(self): # def put(self): # def put(self): # def put(self): # def put(self): # def get(self): # # Path: handlers/SomePage.py # class VIP(BaseHandler): # class Message(BaseHandler): # class Suggest(BaseHandler): # class Rule(BaseHandler): # def get(self): # def get(self): # def post(self): # def get(self): # # Path: handlers/Admin.py # class AddVipTime(BaseHandler): # class AdminSuggest(BaseHandler): # def get(self): # def post(self): # def get(self): # # Path: handlers/VIP.py # class editMyAlbum(BaseHandler): # class myAlbum(BaseHandler): # class addCate(BaseHandler): # def get(self,cateId): # def post(self,cateId): # def get(self): # def post(self): . Output only the next line.
(r"/addCate/?",VIP.addCate),
Next line prediction: <|code_start|> class TestCuboid(TestCase): @classmethod def setUpClass(cls): <|code_end|> . Use current file imports: (from unittest import TestCase from HierMat.cuboid import Cuboid import numpy) and context including class names, function names, or small code snippets from other files: # Path: HierMat/cuboid.py # class Cuboid(object): # """Cuboid that is parallel to the axis in Cartesian coordinates. # # Characterized by two diagonal corners. # # - **Attributes**: # # low_corner: numpy.array with minimal values in each dimension # # high_corner: numpy.array with maximal values in each dimension # """ # def __init__(self, low_corner, high_corner): # """Build a cuboid. # # :param low_corner: low corner # :type low_corner: numpy.array # :param high_corner: high corner # :type high_corner: numpy.array # """ # if not hasattr(low_corner, '__len__'): # low_corner = (low_corner,) # if not hasattr(high_corner, '__len__'): # high_corner = (high_corner,) # if len(low_corner) != len(high_corner): # raise ValueError('corners must have same dimension') # self.low_corner = numpy.array(low_corner, float) # self.high_corner = numpy.array(high_corner, float) # # def __len__(self): # """Dimension of the corners # # :return: len(high_corner) # :rtype: int # """ # return len(self.high_corner) # # def __eq__(self, other): # """Test for equality # # :param other: other cuboid # :type other: Cuboid # :return: equal # :rtype: bool # """ # if len(self) != len(other): # return False # low_eq = self.low_corner == other.low_corner # high_eq = self.high_corner == other.high_corner # return low_eq.all() and high_eq.all() # # def __ne__(self, other): # """Test for inequality # # :param other: other cuboid # :type other: Cuboid # :return: equal # :rtype: bool # """ # return not self == other # # def __contains__(self, point): # """Check if point is inside the cuboid # # True if point is between low_corner and high_corner # # :param point: point of correct dimension # :type point: tuple(float) # # :return: contained # :rtype: bool # """ # lower = self.low_corner <= point # higher = point <= self.high_corner # return lower.all() and higher.all() # # def __repr__(self): # """Representation of Cuboid""" # return "Cuboid({0},{1})".format(str(self.low_corner), str(self.high_corner)) # # def __str__(self): # """Return string representation""" # return "Cuboid with:\n\tlow corner: {0},\n\thigh corner{1}.".format(str(self.low_corner), # str(self.high_corner)) # # def split(self, axis=None): # """Split the cuboid in half # # If axis is specified, the cuboid is restructure along the given axis, else the maximal axis is chosen. # # :param axis: axis along which to restructure (optional) # :type axis: int # :return: cuboid1, cuboid2 # :rtype: tuple(Cuboid, Cuboid) # """ # if axis: # index = axis # else: # # determine dimension in which to restructure # index = numpy.argmax(abs(self.high_corner - self.low_corner)) # # determine value at splitting point # split = (self.high_corner[index] + self.low_corner[index]) / 2 # low_corner1 = numpy.array(self.low_corner) # low_corner2 = numpy.array(self.low_corner) # low_corner2[index] = split # high_corner1 = numpy.array(self.high_corner) # high_corner2 = numpy.array(self.high_corner) # high_corner1[index] = split # return Cuboid(low_corner1, high_corner1), Cuboid(low_corner2, high_corner2) # # def diameter(self): # """Return the diameter of the cuboid. # # Diameter is the Euclidean distance between low_corner and high_corner. # # :return: diameter # :rtype: float # """ # return numpy.linalg.norm(self.high_corner - self.low_corner) # # def distance(self, other): # """Return distance to other Cuboid. # # Distance is the minimal Euclidean distance between points in self and points in other. # # :param other: other cuboid # :type other: Cuboid # # :return: distance # :rtype: float # """ # dimension = len(self.low_corner) # distance1 = self.low_corner - other.low_corner # distance2 = self.low_corner - other.high_corner # distance3 = self.high_corner - other.low_corner # distance4 = self.high_corner - other.high_corner # distance_matrix = numpy.array((distance1, distance2, distance3, distance4)) # checks = abs(numpy.sum(numpy.sign(distance_matrix), 0)) == 4 * numpy.ones(dimension) # distance_vector = numpy.array(checks, dtype=float) # min_vector = numpy.amin(abs(distance_matrix), axis=0) # return numpy.linalg.norm(min_vector * distance_vector) . Output only the next line.
cls.cub1 = Cuboid(numpy.array([0]), numpy.array([1]))
Next line prediction: <|code_start|> class TestGrid(TestCase): @classmethod def setUpClass(cls): cls.lim1 = 16 cls.lim2 = 4 cls.lim3 = 4 cls.link_num = 2 cls.points1 = [(float(i) / cls.lim1,) for i in xrange(cls.lim1)] cls.links1 = {p: [cls.points1[l] for l in [random.randint(0, cls.lim1 - 1) for x in xrange(cls.link_num)]] for p in cls.points1} cls.points2 = [(float(i) / cls.lim2, float(j) / cls.lim2) for i in xrange(cls.lim2) for j in xrange(cls.lim2)] cls.links2 = {p: [cls.points2[l] for l in [random.randint(0, cls.lim2 ** 2 - 1) for x in xrange(cls.link_num)]] for p in cls.points2} cls.points3 = [(float(i) / cls.lim3, float(j) / cls.lim3, float(k) / cls.lim3) for i in xrange(cls.lim3) for j in xrange(cls.lim3) for k in xrange(cls.lim3)] cls.links3 = {p: [cls.points3[l] for l in [random.randint(0, cls.lim3 ** 3 - 1) for x in xrange(cls.link_num)]] for p in cls.points3} <|code_end|> . Use current file imports: (import os import random import numpy from unittest import TestCase from HierMat.grid import Grid) and context including class names, function names, or small code snippets from other files: # Path: HierMat/grid.py # class Grid(object): # """Discretized grid characterized by points and supports # # :param points: list of coordinates # # The points of the discretized Grid. # # :type points: list[tuple(float)] # :param supports: dictionary mapping points with their supports # :type supports: dict{point: support} # :raise ValueError: if points and supports have different length # """ # def __init__(self, points, supports): # """Create a Grid""" # # check input # if len(points) != len(supports): # raise ValueError('points and supports must be of same length') # # fill instance # self.points = points # self.supports = supports # # def __len__(self): # """Return number of points # # :return: len(points) # :rtype: int # """ # return len(self.points) # # def __getitem__(self, item): # """Return point at item # # :param item: index to return # :type item: int # """ # return self.points[item] # # def __iter__(self): # """Iterate trough Grid # """ # return GridIterator(self) # # def __eq__(self, other): # """Test for equality # # :param other: other grid # :type other: Grid # :return: True on equality # :rtype: bool # """ # points_eq = numpy.array_equal(self.points, other.points) # links_eq = numpy.array_equal(self.supports, other.supports) # return points_eq and links_eq # # def __ne__(self, other): # """Test for inequality # # :param other: other grid # :type other: Grid # :return: True on inequality # :rtype: bool # """ # return not self == other # # def get_point(self, item): # """Return point at position item # # :param item: index # :type item: int # :return: point # """ # return self.points[item] # # def get_support(self, item): # """Return support for item # # :param item: point # :type item: float or tuple(float) # :return: support # """ # return self.supports[item] # # def get_support_by_index(self, index): # """Return support for the i-th item # # :param index: index # :type index: int # :return: support # """ # return self.supports[self.get_point(index)] # # def dim(self): # """Dimension of the Grid # # .. note:: # # this is the dimension of the first point # # if you store points of different dimensions, this will be misleading # # :return: dimension # :rtype: int # """ # return len(self[0]) . Output only the next line.
cls.grid1 = Grid(cls.points1, cls.links1)
Predict the next line for this snippet: <|code_start|># Author: Alex Ksikes # TODO: # - webpy session module is ineficient and makes 5 db calls per urls! # - because sessions are attached to an app, every user has sessions whether they atually need it or not. # - login required decorator should save intended user action before asking to login. def add_sessions_to_app(app): if web.config.get('_session') is None: store = web.session.DBStore(db, 'sessions') session = web.session.Session(app, store, initializer={'is_logged' : False}) web.config._session = session else: session = web.config._session def get_session(): return web.config._session def is_logged(): return get_session().is_logged def login(email): s = get_session() <|code_end|> with the help of current file imports: import web from config import db from app.models import users from app.models import applicants and context from other files: # Path: app/models/users.py # def create_account(email, password, nickname): # def get_user_by_email(email): # def is_email_available(email): # def is_valid_password(password): # def is_correct_password(email, password): # def update(id, **kw): # def get_user_by_id(id): # # Path: app/models/applicants.py # def get_where(context='', query=None, user_id=None): # def query(context='', query=None, offset=0, limit=50, order='creation_ts desc', user_id=None): # def get_by_id(id): # def admit(ids, user_id): # def reject(ids, user_id): # def undecide(ids, user_id): # def grant(user_id, id, amount): # def add_comment(id, comment): # def rate(ids, score): # def get_counts(): # def get_by_secret_md5(secret_md5): # def get_dummy_record(): # def get_stats(): , which may contain function names, class names, or code. Output only the next line.
for k, v in users.get_user_by_email(email).items():
Using the snippet: <|code_start|># Author: Alex Ksikes class refer: def GET(self, secret_md5): applicant = applicants.get_by_secret_md5(secret_md5) if not applicant and secret_md5 == '0' * 32: applicant = applicants.get_dummy_record() return view.reference_form(self.form(), applicant, web.input(success='').success) def POST(self, secret_md5): applicant = applicants.get_by_secret_md5(secret_md5) f = self.form() if not f.validates(web.input(_unicode=False)): return view.reference_form(f, applicant) else: success = True try: <|code_end|> , determine the next line of code. You have imports: import web import config from app.models import submissions from app.models import applicants from config import view from web import form and context (class names, function names, or code) available: # Path: app/models/submissions.py # def submit_application(resume, d, simple=False): # def clean_up_data(d): # def is_email_available(email): # def save_resume(resume, first_name, last_name): # def add_applicant(d): # def submit_reference(applicant, d): # def get_by_secret_md5(secret_md5): # def add_reference(secret_md5, d): # # Path: app/models/applicants.py # def get_where(context='', query=None, user_id=None): # def query(context='', query=None, offset=0, limit=50, order='creation_ts desc', user_id=None): # def get_by_id(id): # def admit(ids, user_id): # def reject(ids, user_id): # def undecide(ids, user_id): # def grant(user_id, id, amount): # def add_comment(id, comment): # def rate(ids, score): # def get_counts(): # def get_by_secret_md5(secret_md5): # def get_dummy_record(): # def get_stats(): . Output only the next line.
submissions.submit_reference(applicant, f.d)
Based on the snippet: <|code_start|># Author: Alex Ksikes resume_dir = 'public/resumes/' def submit_application(resume, d, simple=False): # clean up some fields clean_up_data(d) # handle the file upload d.resume_fn = save_resume(resume, d.first_name, d.last_name) # in simple mode, no reference is required if simple: # save the data in the db add_applicant(d) # email user and referee email_templates.to_applicant_simple(d) else: # make secret md5 <|code_end|> , predict the immediate next line with the help of imports: import web from config import db from app.helpers import utils from app.helpers import email_templates from cStringIO import StringIO from datetime import date and context (classes, functions, sometimes code) from other files: # Path: app/helpers/utils.py # def dict_remove(d, *keys): # def capitalize_first(str): # def make_unique_md5(): # def get_all_functions(module): # def sqlands(left, lst): # def get_ip(): # def store(tablename, _test=False, **values): # # Path: app/helpers/email_templates.py # def to_applicant(applicant): # def to_applicant_simple(applicant): # def to_referee(applicant): # def notify_applicant(applicant): # def notify_referee(applicant): # def resend_password(user): . Output only the next line.
d.secret_md5 = utils.make_unique_md5()
Using the snippet: <|code_start|># Author: Alex Ksikes resume_dir = 'public/resumes/' def submit_application(resume, d, simple=False): # clean up some fields clean_up_data(d) # handle the file upload d.resume_fn = save_resume(resume, d.first_name, d.last_name) # in simple mode, no reference is required if simple: # save the data in the db add_applicant(d) # email user and referee <|code_end|> , determine the next line of code. You have imports: import web from config import db from app.helpers import utils from app.helpers import email_templates from cStringIO import StringIO from datetime import date and context (class names, function names, or code) available: # Path: app/helpers/utils.py # def dict_remove(d, *keys): # def capitalize_first(str): # def make_unique_md5(): # def get_all_functions(module): # def sqlands(left, lst): # def get_ip(): # def store(tablename, _test=False, **values): # # Path: app/helpers/email_templates.py # def to_applicant(applicant): # def to_applicant_simple(applicant): # def to_referee(applicant): # def notify_applicant(applicant): # def notify_referee(applicant): # def resend_password(user): . Output only the next line.
email_templates.to_applicant_simple(d)
Predict the next line after this snippet: <|code_start|> '/reject', 'app.controllers.actions.reject', '/undecide', 'app.controllers.actions.undecide', '/rate', 'app.controllers.actions.rate', '/applicant/(\d+)/comment', 'app.controllers.actions.comment', '/delete_comment/(\d+)', 'app.controllers.actions.delete_comment', '/grant/(\d+)', 'app.controllers.actions.grant', '/account', 'app.controllers.account.index', '/account/register', 'app.controllers.account.register', '/account/login', 'app.controllers.account.login', '/account/logout', 'app.controllers.account.logout', '/account/resend_password', 'app.controllers.account.resend_password', '/account/help', 'app.controllers.account.help', '/settings', 'app.controllers.settings.index', '/settings/change_nickname', 'app.controllers.settings.change_nickname', '/settings/change_password', 'app.controllers.settings.change_password', '/settings/change_email', 'app.controllers.settings.change_email', '/(?:img|js|css)/.*', 'app.controllers.public.public', '/tests/session', 'app.tests.session', '/tests/upload', 'app.tests.upload', ) app = web.application(urls, globals()) if web.config.email_errors: app.internalerror = web.emailerrors(web.config.email_errors, web.webapi._InternalError) <|code_end|> using the current file's imports: import web import config import app.controllers from app.helpers import session and any relevant context from other files: # Path: app/helpers/session.py # def add_sessions_to_app(app): # def get_session(): # def is_logged(): # def login(email): # def logout(): # def reset(): # def get_user_id(): # def get_last_visited_url(): # def set_last_visited_url(): # def login_required(meth): # def new(*args): # def login_required_for_reviews(meth): # def new(*l): . Output only the next line.
session.add_sessions_to_app(app)
Here is a snippet: <|code_start|># Author: Alex Ksikes class admit: @session.login_required def POST(self): i = web.input(context='', id=[]) if i.id: <|code_end|> . Write the next line using the current file imports: import web import config from app.helpers import paging from app.helpers import session from app.models import applicants from app.models import comments from app.models import votes from config import view and context from other files: # Path: app/helpers/paging.py # def get_paging(start, max_results, query=False, results_per_page=15, window_size=15): # def get_paging_results(start, max_results, id, results, results_per_page): # # Path: app/helpers/session.py # def add_sessions_to_app(app): # def get_session(): # def is_logged(): # def login(email): # def logout(): # def reset(): # def get_user_id(): # def get_last_visited_url(): # def set_last_visited_url(): # def login_required(meth): # def new(*args): # def login_required_for_reviews(meth): # def new(*l): # # Path: app/models/applicants.py # def get_where(context='', query=None, user_id=None): # def query(context='', query=None, offset=0, limit=50, order='creation_ts desc', user_id=None): # def get_by_id(id): # def admit(ids, user_id): # def reject(ids, user_id): # def undecide(ids, user_id): # def grant(user_id, id, amount): # def add_comment(id, comment): # def rate(ids, score): # def get_counts(): # def get_by_secret_md5(secret_md5): # def get_dummy_record(): # def get_stats(): # # Path: app/models/comments.py # def add_comment(user_id, applicant_id, comment): # def delete_comment(user_id, id): # def get_comments(applicant_id): # # Path: app/models/votes.py # def add(ids, score, user_id): # def update_calculated_votes(applicant_id): # def get_votes(applicant_id): , which may include functions, classes, or code. Output only the next line.
applicants.admit(i.id, session.get_user_id())
Given the code snippet: <|code_start|> if i.id: applicants.reject(i.id, session.get_user_id()) raise web.seeother(web.ctx.environ['HTTP_REFERER']) class undecide: @session.login_required def POST(self): i = web.input(context='', id=[]) if i.id: applicants.undecide(i.id, session.get_user_id()) raise web.seeother(web.ctx.environ['HTTP_REFERER']) class rate: @session.login_required def POST(self): i = web.input(context='', id=[], score=[]) score = web.intget(i.score[0] or i.score[1], '') if i.id and score: # applicants.rate(i.id, score, session.get_user_id()) votes.add(i.id, score, session.get_user_id()) raise web.seeother(web.ctx.environ['HTTP_REFERER']) class comment: @session.login_required def POST(self, id): i = web.input(comment='') if i.id and i.comment: <|code_end|> , generate the next line using the imports in this file: import web import config from app.helpers import paging from app.helpers import session from app.models import applicants from app.models import comments from app.models import votes from config import view and context (functions, classes, or occasionally code) from other files: # Path: app/helpers/paging.py # def get_paging(start, max_results, query=False, results_per_page=15, window_size=15): # def get_paging_results(start, max_results, id, results, results_per_page): # # Path: app/helpers/session.py # def add_sessions_to_app(app): # def get_session(): # def is_logged(): # def login(email): # def logout(): # def reset(): # def get_user_id(): # def get_last_visited_url(): # def set_last_visited_url(): # def login_required(meth): # def new(*args): # def login_required_for_reviews(meth): # def new(*l): # # Path: app/models/applicants.py # def get_where(context='', query=None, user_id=None): # def query(context='', query=None, offset=0, limit=50, order='creation_ts desc', user_id=None): # def get_by_id(id): # def admit(ids, user_id): # def reject(ids, user_id): # def undecide(ids, user_id): # def grant(user_id, id, amount): # def add_comment(id, comment): # def rate(ids, score): # def get_counts(): # def get_by_secret_md5(secret_md5): # def get_dummy_record(): # def get_stats(): # # Path: app/models/comments.py # def add_comment(user_id, applicant_id, comment): # def delete_comment(user_id, id): # def get_comments(applicant_id): # # Path: app/models/votes.py # def add(ids, score, user_id): # def update_calculated_votes(applicant_id): # def get_votes(applicant_id): . Output only the next line.
comments.add_comment(session.get_user_id(), id, i.comment)
Next line prediction: <|code_start|> if i.id: applicants.admit(i.id, session.get_user_id()) raise web.seeother(web.ctx.environ['HTTP_REFERER']) class reject: @session.login_required def POST(self): i = web.input(context='', id=[]) if i.id: applicants.reject(i.id, session.get_user_id()) raise web.seeother(web.ctx.environ['HTTP_REFERER']) class undecide: @session.login_required def POST(self): i = web.input(context='', id=[]) if i.id: applicants.undecide(i.id, session.get_user_id()) raise web.seeother(web.ctx.environ['HTTP_REFERER']) class rate: @session.login_required def POST(self): i = web.input(context='', id=[], score=[]) score = web.intget(i.score[0] or i.score[1], '') if i.id and score: # applicants.rate(i.id, score, session.get_user_id()) <|code_end|> . Use current file imports: (import web import config from app.helpers import paging from app.helpers import session from app.models import applicants from app.models import comments from app.models import votes from config import view) and context including class names, function names, or small code snippets from other files: # Path: app/helpers/paging.py # def get_paging(start, max_results, query=False, results_per_page=15, window_size=15): # def get_paging_results(start, max_results, id, results, results_per_page): # # Path: app/helpers/session.py # def add_sessions_to_app(app): # def get_session(): # def is_logged(): # def login(email): # def logout(): # def reset(): # def get_user_id(): # def get_last_visited_url(): # def set_last_visited_url(): # def login_required(meth): # def new(*args): # def login_required_for_reviews(meth): # def new(*l): # # Path: app/models/applicants.py # def get_where(context='', query=None, user_id=None): # def query(context='', query=None, offset=0, limit=50, order='creation_ts desc', user_id=None): # def get_by_id(id): # def admit(ids, user_id): # def reject(ids, user_id): # def undecide(ids, user_id): # def grant(user_id, id, amount): # def add_comment(id, comment): # def rate(ids, score): # def get_counts(): # def get_by_secret_md5(secret_md5): # def get_dummy_record(): # def get_stats(): # # Path: app/models/comments.py # def add_comment(user_id, applicant_id, comment): # def delete_comment(user_id, id): # def get_comments(applicant_id): # # Path: app/models/votes.py # def add(ids, score, user_id): # def update_calculated_votes(applicant_id): # def get_votes(applicant_id): . Output only the next line.
votes.add(i.id, score, session.get_user_id())
Based on the snippet: <|code_start|># Author: Alex Ksikes # This is a sample config file. Complete it and rename the file config.py. # connect to database db = web.database(dbn='mysql', db='mlss', user='your username', passwd='your password') # in development debug error messages and reloader web.config.debug = True # in develpment template caching is set to false cache = False # global used template functions <|code_end|> , predict the immediate next line with the help of imports: import web, os from app.helpers import misc from app.helpers import utils and context (classes, functions, sometimes code) from other files: # Path: app/helpers/misc.py # def format_date(d, f): # def url_quote(url): # def html_quote(html): # def url_encode(query, clean=True, doseq=True, **kw): # def cut_length(s, max=40, tooltip=False): # def get_nice_url(url): # def capitalize_first(str): # def text2html(s): # def replace_breaks(s): # def replace_indents(s): # def replace_links(s): # def how_long(d): # def split(pattern, str): # def sub(pattern, rpl, str): # def render_form(form, from_input, to_input): # def index(inputs, name): # def get_site_domain(): # # Path: app/helpers/utils.py # def dict_remove(d, *keys): # def capitalize_first(str): # def make_unique_md5(): # def get_all_functions(module): # def sqlands(left, lst): # def get_ip(): # def store(tablename, _test=False, **values): . Output only the next line.
globals = utils.get_all_functions(misc)
Using the snippet: <|code_start|># Author: Alex Ksikes # This is a sample config file. Complete it and rename the file config.py. # connect to database db = web.database(dbn='mysql', db='mlss', user='your username', passwd='your password') # in development debug error messages and reloader web.config.debug = True # in develpment template caching is set to false cache = False # global used template functions <|code_end|> , determine the next line of code. You have imports: import web, os from app.helpers import misc from app.helpers import utils and context (class names, function names, or code) available: # Path: app/helpers/misc.py # def format_date(d, f): # def url_quote(url): # def html_quote(html): # def url_encode(query, clean=True, doseq=True, **kw): # def cut_length(s, max=40, tooltip=False): # def get_nice_url(url): # def capitalize_first(str): # def text2html(s): # def replace_breaks(s): # def replace_indents(s): # def replace_links(s): # def how_long(d): # def split(pattern, str): # def sub(pattern, rpl, str): # def render_form(form, from_input, to_input): # def index(inputs, name): # def get_site_domain(): # # Path: app/helpers/utils.py # def dict_remove(d, *keys): # def capitalize_first(str): # def make_unique_md5(): # def get_all_functions(module): # def sqlands(left, lst): # def get_ip(): # def store(tablename, _test=False, **values): . Output only the next line.
globals = utils.get_all_functions(misc)
Given the code snippet: <|code_start|># Author: Alex Ksikes # TODO: # - see for a better paging module # - no need to have two separate login_required_for_reviews and login_required results_per_page = 50 default_order = 'id' class list: @session.login_required_for_reviews def GET(self, context): i = web.input(start=0, order=default_order, desc='desc', query='') start = int(i.start) context = context or 'all' user_id = session.is_logged() and session.get_user_id() results, num_results = applicants.query(query=i.query, context=context, offset=start, limit=results_per_page, order=i.order + ' ' + i.desc, user_id=user_id) <|code_end|> , generate the next line using the imports in this file: import web import config from app.helpers import paging from app.helpers import session from app.models import applicants from app.models import comments from app.models import votes from config import view and context (functions, classes, or occasionally code) from other files: # Path: app/helpers/paging.py # def get_paging(start, max_results, query=False, results_per_page=15, window_size=15): # def get_paging_results(start, max_results, id, results, results_per_page): # # Path: app/helpers/session.py # def add_sessions_to_app(app): # def get_session(): # def is_logged(): # def login(email): # def logout(): # def reset(): # def get_user_id(): # def get_last_visited_url(): # def set_last_visited_url(): # def login_required(meth): # def new(*args): # def login_required_for_reviews(meth): # def new(*l): # # Path: app/models/applicants.py # def get_where(context='', query=None, user_id=None): # def query(context='', query=None, offset=0, limit=50, order='creation_ts desc', user_id=None): # def get_by_id(id): # def admit(ids, user_id): # def reject(ids, user_id): # def undecide(ids, user_id): # def grant(user_id, id, amount): # def add_comment(id, comment): # def rate(ids, score): # def get_counts(): # def get_by_secret_md5(secret_md5): # def get_dummy_record(): # def get_stats(): # # Path: app/models/comments.py # def add_comment(user_id, applicant_id, comment): # def delete_comment(user_id, id): # def get_comments(applicant_id): # # Path: app/models/votes.py # def add(ids, score, user_id): # def update_calculated_votes(applicant_id): # def get_votes(applicant_id): . Output only the next line.
pager = web.storage(paging.get_paging(start, num_results,
Predict the next line for this snippet: <|code_start|># Author: Alex Ksikes # TODO: # - see for a better paging module # - no need to have two separate login_required_for_reviews and login_required results_per_page = 50 default_order = 'id' class list: <|code_end|> with the help of current file imports: import web import config from app.helpers import paging from app.helpers import session from app.models import applicants from app.models import comments from app.models import votes from config import view and context from other files: # Path: app/helpers/paging.py # def get_paging(start, max_results, query=False, results_per_page=15, window_size=15): # def get_paging_results(start, max_results, id, results, results_per_page): # # Path: app/helpers/session.py # def add_sessions_to_app(app): # def get_session(): # def is_logged(): # def login(email): # def logout(): # def reset(): # def get_user_id(): # def get_last_visited_url(): # def set_last_visited_url(): # def login_required(meth): # def new(*args): # def login_required_for_reviews(meth): # def new(*l): # # Path: app/models/applicants.py # def get_where(context='', query=None, user_id=None): # def query(context='', query=None, offset=0, limit=50, order='creation_ts desc', user_id=None): # def get_by_id(id): # def admit(ids, user_id): # def reject(ids, user_id): # def undecide(ids, user_id): # def grant(user_id, id, amount): # def add_comment(id, comment): # def rate(ids, score): # def get_counts(): # def get_by_secret_md5(secret_md5): # def get_dummy_record(): # def get_stats(): # # Path: app/models/comments.py # def add_comment(user_id, applicant_id, comment): # def delete_comment(user_id, id): # def get_comments(applicant_id): # # Path: app/models/votes.py # def add(ids, score, user_id): # def update_calculated_votes(applicant_id): # def get_votes(applicant_id): , which may contain function names, class names, or code. Output only the next line.
@session.login_required_for_reviews
Given the code snippet: <|code_start|># Author: Alex Ksikes # TODO: # - see for a better paging module # - no need to have two separate login_required_for_reviews and login_required results_per_page = 50 default_order = 'id' class list: @session.login_required_for_reviews def GET(self, context): i = web.input(start=0, order=default_order, desc='desc', query='') start = int(i.start) context = context or 'all' user_id = session.is_logged() and session.get_user_id() <|code_end|> , generate the next line using the imports in this file: import web import config from app.helpers import paging from app.helpers import session from app.models import applicants from app.models import comments from app.models import votes from config import view and context (functions, classes, or occasionally code) from other files: # Path: app/helpers/paging.py # def get_paging(start, max_results, query=False, results_per_page=15, window_size=15): # def get_paging_results(start, max_results, id, results, results_per_page): # # Path: app/helpers/session.py # def add_sessions_to_app(app): # def get_session(): # def is_logged(): # def login(email): # def logout(): # def reset(): # def get_user_id(): # def get_last_visited_url(): # def set_last_visited_url(): # def login_required(meth): # def new(*args): # def login_required_for_reviews(meth): # def new(*l): # # Path: app/models/applicants.py # def get_where(context='', query=None, user_id=None): # def query(context='', query=None, offset=0, limit=50, order='creation_ts desc', user_id=None): # def get_by_id(id): # def admit(ids, user_id): # def reject(ids, user_id): # def undecide(ids, user_id): # def grant(user_id, id, amount): # def add_comment(id, comment): # def rate(ids, score): # def get_counts(): # def get_by_secret_md5(secret_md5): # def get_dummy_record(): # def get_stats(): # # Path: app/models/comments.py # def add_comment(user_id, applicant_id, comment): # def delete_comment(user_id, id): # def get_comments(applicant_id): # # Path: app/models/votes.py # def add(ids, score, user_id): # def update_calculated_votes(applicant_id): # def get_votes(applicant_id): . Output only the next line.
results, num_results = applicants.query(query=i.query, context=context,
Next line prediction: <|code_start|> counts = applicants.get_counts() user = session.get_session() stats = applicants.get_stats() return view.layout( view.applicants(results, context, pager, i), user, context, counts, i.query, stats) class show: @session.login_required_for_reviews def GET(self, id): i = web.input(context='all', start=0, order=default_order, desc='desc', query='') start = int(i.start) user_id = session.is_logged() and session.get_user_id() results, num_results = applicants.query(query=i.query, context=i.context, offset=start and start - 1, limit=results_per_page+2, order=i.order + ' ' + i.desc, user_id=user_id) pager = web.storage(paging.get_paging_results(start, num_results, int(id), results, results_per_page)) counts = applicants.get_counts() user = session.get_session() applicant = applicants.get_by_id(id) <|code_end|> . Use current file imports: (import web import config from app.helpers import paging from app.helpers import session from app.models import applicants from app.models import comments from app.models import votes from config import view) and context including class names, function names, or small code snippets from other files: # Path: app/helpers/paging.py # def get_paging(start, max_results, query=False, results_per_page=15, window_size=15): # def get_paging_results(start, max_results, id, results, results_per_page): # # Path: app/helpers/session.py # def add_sessions_to_app(app): # def get_session(): # def is_logged(): # def login(email): # def logout(): # def reset(): # def get_user_id(): # def get_last_visited_url(): # def set_last_visited_url(): # def login_required(meth): # def new(*args): # def login_required_for_reviews(meth): # def new(*l): # # Path: app/models/applicants.py # def get_where(context='', query=None, user_id=None): # def query(context='', query=None, offset=0, limit=50, order='creation_ts desc', user_id=None): # def get_by_id(id): # def admit(ids, user_id): # def reject(ids, user_id): # def undecide(ids, user_id): # def grant(user_id, id, amount): # def add_comment(id, comment): # def rate(ids, score): # def get_counts(): # def get_by_secret_md5(secret_md5): # def get_dummy_record(): # def get_stats(): # # Path: app/models/comments.py # def add_comment(user_id, applicant_id, comment): # def delete_comment(user_id, id): # def get_comments(applicant_id): # # Path: app/models/votes.py # def add(ids, score, user_id): # def update_calculated_votes(applicant_id): # def get_votes(applicant_id): . Output only the next line.
_comments = comments.get_comments(applicant.id)
Predict the next line after this snippet: <|code_start|> user = session.get_session() stats = applicants.get_stats() return view.layout( view.applicants(results, context, pager, i), user, context, counts, i.query, stats) class show: @session.login_required_for_reviews def GET(self, id): i = web.input(context='all', start=0, order=default_order, desc='desc', query='') start = int(i.start) user_id = session.is_logged() and session.get_user_id() results, num_results = applicants.query(query=i.query, context=i.context, offset=start and start - 1, limit=results_per_page+2, order=i.order + ' ' + i.desc, user_id=user_id) pager = web.storage(paging.get_paging_results(start, num_results, int(id), results, results_per_page)) counts = applicants.get_counts() user = session.get_session() applicant = applicants.get_by_id(id) _comments = comments.get_comments(applicant.id) <|code_end|> using the current file's imports: import web import config from app.helpers import paging from app.helpers import session from app.models import applicants from app.models import comments from app.models import votes from config import view and any relevant context from other files: # Path: app/helpers/paging.py # def get_paging(start, max_results, query=False, results_per_page=15, window_size=15): # def get_paging_results(start, max_results, id, results, results_per_page): # # Path: app/helpers/session.py # def add_sessions_to_app(app): # def get_session(): # def is_logged(): # def login(email): # def logout(): # def reset(): # def get_user_id(): # def get_last_visited_url(): # def set_last_visited_url(): # def login_required(meth): # def new(*args): # def login_required_for_reviews(meth): # def new(*l): # # Path: app/models/applicants.py # def get_where(context='', query=None, user_id=None): # def query(context='', query=None, offset=0, limit=50, order='creation_ts desc', user_id=None): # def get_by_id(id): # def admit(ids, user_id): # def reject(ids, user_id): # def undecide(ids, user_id): # def grant(user_id, id, amount): # def add_comment(id, comment): # def rate(ids, score): # def get_counts(): # def get_by_secret_md5(secret_md5): # def get_dummy_record(): # def get_stats(): # # Path: app/models/comments.py # def add_comment(user_id, applicant_id, comment): # def delete_comment(user_id, id): # def get_comments(applicant_id): # # Path: app/models/votes.py # def add(ids, score, user_id): # def update_calculated_votes(applicant_id): # def get_votes(applicant_id): . Output only the next line.
_votes = votes.get_votes(applicant.id)
Next line prediction: <|code_start|># Author: Alex Ksikes vemail = form.regexp(r'.+@.+', 'Please enter a valid email address') login_form = form.Form( form.Textbox('email', form.notnull, vemail, description='Your email:'), form.Password('password', form.notnull, description='Your password:'), form.Button('submit', type='submit', value='Login'), validators = [ form.Validator('Incorrect email / password combination.', <|code_end|> . Use current file imports: (import web from web import form from app.models import users from app.helpers import session from app.helpers import email_templates from config import view) and context including class names, function names, or small code snippets from other files: # Path: app/models/users.py # def create_account(email, password, nickname): # def get_user_by_email(email): # def is_email_available(email): # def is_valid_password(password): # def is_correct_password(email, password): # def update(id, **kw): # def get_user_by_id(id): # # Path: app/helpers/session.py # def add_sessions_to_app(app): # def get_session(): # def is_logged(): # def login(email): # def logout(): # def reset(): # def get_user_id(): # def get_last_visited_url(): # def set_last_visited_url(): # def login_required(meth): # def new(*args): # def login_required_for_reviews(meth): # def new(*l): # # Path: app/helpers/email_templates.py # def to_applicant(applicant): # def to_applicant_simple(applicant): # def to_referee(applicant): # def notify_applicant(applicant): # def notify_referee(applicant): # def resend_password(user): . Output only the next line.
lambda i: users.is_correct_password(i.email, i.password))
Predict the next line for this snippet: <|code_start|> form.Textbox('email', form.notnull, vemail, form.Validator('There is no record of this email in our database.', lambda x: not users.is_email_available(x)), description='Your email:'), form.Button('submit', type='submit', value='Register'), ) def render_account(show='all', login_form=login_form(), register_form=register_form(), forgot_password_form=forgot_password_form(), on_success_message=''): return view.base( view.account(show, login_form, register_form, forgot_password_form, on_success_message)) class index: def GET(self): return render_account(show='all') class login: def GET(self): return render_account(show='login_only') def POST(self): f = self.form() if not f.validates(web.input(_unicode=False)): show = web.input(show='all').show return render_account(show, login_form=f) else: <|code_end|> with the help of current file imports: import web from web import form from app.models import users from app.helpers import session from app.helpers import email_templates from config import view and context from other files: # Path: app/models/users.py # def create_account(email, password, nickname): # def get_user_by_email(email): # def is_email_available(email): # def is_valid_password(password): # def is_correct_password(email, password): # def update(id, **kw): # def get_user_by_id(id): # # Path: app/helpers/session.py # def add_sessions_to_app(app): # def get_session(): # def is_logged(): # def login(email): # def logout(): # def reset(): # def get_user_id(): # def get_last_visited_url(): # def set_last_visited_url(): # def login_required(meth): # def new(*args): # def login_required_for_reviews(meth): # def new(*l): # # Path: app/helpers/email_templates.py # def to_applicant(applicant): # def to_applicant_simple(applicant): # def to_referee(applicant): # def notify_applicant(applicant): # def notify_referee(applicant): # def resend_password(user): , which may contain function names, class names, or code. Output only the next line.
session.login(f.d.email)
Predict the next line after this snippet: <|code_start|> return login_form() class register: def GET(self): return render_account(show='register_only') def POST(self): f = self.form() if not f.validates(web.input(_unicode=False)): show = web.input(show='all').show return render_account(show, register_form=f) else: users.create_account(f.d.email, f.d.password, f.d.nickname) session.login(f.d.email) raise web.seeother('/') def form(self): return register_form() class resend_password: def GET(self): return render_account(show='forgot_password_only') def POST(self): f = self.form() show = web.input(show='all').show if not f.validates(web.input(_unicode=False)): return render_account(show, forgot_password_form=f) else: user = users.get_user_by_email(f.d.email) <|code_end|> using the current file's imports: import web from web import form from app.models import users from app.helpers import session from app.helpers import email_templates from config import view and any relevant context from other files: # Path: app/models/users.py # def create_account(email, password, nickname): # def get_user_by_email(email): # def is_email_available(email): # def is_valid_password(password): # def is_correct_password(email, password): # def update(id, **kw): # def get_user_by_id(id): # # Path: app/helpers/session.py # def add_sessions_to_app(app): # def get_session(): # def is_logged(): # def login(email): # def logout(): # def reset(): # def get_user_id(): # def get_last_visited_url(): # def set_last_visited_url(): # def login_required(meth): # def new(*args): # def login_required_for_reviews(meth): # def new(*l): # # Path: app/helpers/email_templates.py # def to_applicant(applicant): # def to_applicant_simple(applicant): # def to_referee(applicant): # def notify_applicant(applicant): # def notify_referee(applicant): # def resend_password(user): . Output only the next line.
email_templates.resend_password(user)
Given the following code snippet before the placeholder: <|code_start|> password_form = form.Form( form.Password('password', form.notnull, form.Validator('Your password must at least 5 characters long.', lambda x: users.is_valid_password(x)), description='Your new password:'), form.Button('submit', type='submit', value='Change password') ) nickname_form = form.Form( form.Textbox('nickname', form.notnull, description='Your new nickname:'), form.Button('submit', type='submit', value='Change your nickname') ) vemail = form.regexp(r'.+@.+', 'Please enter a valid email address') email_form = form.Form( form.Textbox('email', form.notnull, vemail, form.Validator('This email address is already taken.', lambda x: users.is_email_available(x)), description='Your new email:'), form.Button('submit', type='submit', value='Change your email') ) def render_settings(nickname_form=nickname_form(), email_form=email_form(), password_form=password_form(), on_success_message=''): <|code_end|> , predict the next line using imports from the current file: import web import config from web import form from app.models import applicants from app.models import users from app.helpers import session from config import view and context including class names, function names, and sometimes code from other files: # Path: app/models/applicants.py # def get_where(context='', query=None, user_id=None): # def query(context='', query=None, offset=0, limit=50, order='creation_ts desc', user_id=None): # def get_by_id(id): # def admit(ids, user_id): # def reject(ids, user_id): # def undecide(ids, user_id): # def grant(user_id, id, amount): # def add_comment(id, comment): # def rate(ids, score): # def get_counts(): # def get_by_secret_md5(secret_md5): # def get_dummy_record(): # def get_stats(): # # Path: app/models/users.py # def create_account(email, password, nickname): # def get_user_by_email(email): # def is_email_available(email): # def is_valid_password(password): # def is_correct_password(email, password): # def update(id, **kw): # def get_user_by_id(id): # # Path: app/helpers/session.py # def add_sessions_to_app(app): # def get_session(): # def is_logged(): # def login(email): # def logout(): # def reset(): # def get_user_id(): # def get_last_visited_url(): # def set_last_visited_url(): # def login_required(meth): # def new(*args): # def login_required_for_reviews(meth): # def new(*l): . Output only the next line.
counts = applicants.get_counts()
Continue the code snippet: <|code_start|># Author: Alex Ksikes password_form = form.Form( form.Password('password', form.notnull, form.Validator('Your password must at least 5 characters long.', <|code_end|> . Use current file imports: import web import config from web import form from app.models import applicants from app.models import users from app.helpers import session from config import view and context (classes, functions, or code) from other files: # Path: app/models/applicants.py # def get_where(context='', query=None, user_id=None): # def query(context='', query=None, offset=0, limit=50, order='creation_ts desc', user_id=None): # def get_by_id(id): # def admit(ids, user_id): # def reject(ids, user_id): # def undecide(ids, user_id): # def grant(user_id, id, amount): # def add_comment(id, comment): # def rate(ids, score): # def get_counts(): # def get_by_secret_md5(secret_md5): # def get_dummy_record(): # def get_stats(): # # Path: app/models/users.py # def create_account(email, password, nickname): # def get_user_by_email(email): # def is_email_available(email): # def is_valid_password(password): # def is_correct_password(email, password): # def update(id, **kw): # def get_user_by_id(id): # # Path: app/helpers/session.py # def add_sessions_to_app(app): # def get_session(): # def is_logged(): # def login(email): # def logout(): # def reset(): # def get_user_id(): # def get_last_visited_url(): # def set_last_visited_url(): # def login_required(meth): # def new(*args): # def login_required_for_reviews(meth): # def new(*l): . Output only the next line.
lambda x: users.is_valid_password(x)),
Here is a snippet: <|code_start|> password_form = form.Form( form.Password('password', form.notnull, form.Validator('Your password must at least 5 characters long.', lambda x: users.is_valid_password(x)), description='Your new password:'), form.Button('submit', type='submit', value='Change password') ) nickname_form = form.Form( form.Textbox('nickname', form.notnull, description='Your new nickname:'), form.Button('submit', type='submit', value='Change your nickname') ) vemail = form.regexp(r'.+@.+', 'Please enter a valid email address') email_form = form.Form( form.Textbox('email', form.notnull, vemail, form.Validator('This email address is already taken.', lambda x: users.is_email_available(x)), description='Your new email:'), form.Button('submit', type='submit', value='Change your email') ) def render_settings(nickname_form=nickname_form(), email_form=email_form(), password_form=password_form(), on_success_message=''): counts = applicants.get_counts() <|code_end|> . Write the next line using the current file imports: import web import config from web import form from app.models import applicants from app.models import users from app.helpers import session from config import view and context from other files: # Path: app/models/applicants.py # def get_where(context='', query=None, user_id=None): # def query(context='', query=None, offset=0, limit=50, order='creation_ts desc', user_id=None): # def get_by_id(id): # def admit(ids, user_id): # def reject(ids, user_id): # def undecide(ids, user_id): # def grant(user_id, id, amount): # def add_comment(id, comment): # def rate(ids, score): # def get_counts(): # def get_by_secret_md5(secret_md5): # def get_dummy_record(): # def get_stats(): # # Path: app/models/users.py # def create_account(email, password, nickname): # def get_user_by_email(email): # def is_email_available(email): # def is_valid_password(password): # def is_correct_password(email, password): # def update(id, **kw): # def get_user_by_id(id): # # Path: app/helpers/session.py # def add_sessions_to_app(app): # def get_session(): # def is_logged(): # def login(email): # def logout(): # def reset(): # def get_user_id(): # def get_last_visited_url(): # def set_last_visited_url(): # def login_required(meth): # def new(*args): # def login_required_for_reviews(meth): # def new(*l): , which may include functions, classes, or code. Output only the next line.
user = session.get_session()
Given the code snippet: <|code_start|># Author: Alex Ksikes vemail = form.regexp(r'.+@.+', 'Please enter a valid email address') vurl = form.regexp('(^\s*$)|(^http://.*$)', 'Please provide a valid website url (eg, http://www.example.com).') application_form = form.Form( form.Textbox('first_name', form.notnull, description='First Name *'), form.Textbox('last_name', form.notnull, description='Last Name *'), form.Radio('gender', ('Male', 'Female'), form.notnull, description='Gender *'), form.Textbox('nationality', form.notnull, description='Nationality *'), form.Textbox('country', form.notnull, description='Country of Current Affiliation *'), form.Textbox('email', form.notnull, vemail, form.Validator('This email address is already taken (Have you already submitted an application?)', <|code_end|> , generate the next line using the imports in this file: import web import config from app.models import submissions from config import view from web import form and context (functions, classes, or occasionally code) from other files: # Path: app/models/submissions.py # def submit_application(resume, d, simple=False): # def clean_up_data(d): # def is_email_available(email): # def save_resume(resume, first_name, last_name): # def add_applicant(d): # def submit_reference(applicant, d): # def get_by_secret_md5(secret_md5): # def add_reference(secret_md5, d): . Output only the next line.
lambda x: submissions.is_email_available(x)),
Here is a snippet: <|code_start|> def __init__(self, indent=0, quote='', indent_char=' '): self.indent = indent self.indent_char = indent_char self.indent_quote = quote if self.indent > 0: self.indent_string = ''.join(( str(quote), (self.indent_char * (indent - len(self.indent_quote))) )) else: self.indent_string = ''.join(( ('\x08' * (-1 * (indent - len(self.indent_quote)))), str(quote)) ) if len(self.indent_string): self.shared['indent_strings'].append(self.indent_string) def __enter__(self): return self def __exit__(self, type, value, traceback): self.shared['indent_strings'].pop() def __call__(self, s, newline=True, stream=STDOUT): if newline: <|code_end|> . Write the next line using the current file imports: import sys from .formatters import max_width, min_width from .cols import columns from ..utils import tsplit and context from other files: # Path: pkg/win32/Python27/Lib/site-packages/clint/textui/formatters.py # def max_width(string, cols, separator='\n'): # """Returns a freshly formatted """ # # is_color = isinstance(string, ColoredString) # # if is_color: # offset = 10 # string_copy = string._new('') # else: # offset = 0 # # stack = tsplit(string, NEWLINES) # # for i, substring in enumerate(stack): # stack[i] = substring.split() # # _stack = [] # # for row in stack: # _row = ['',] # _row_i = 0 # # for word in row: # if (len(_row[_row_i]) + len(word)) < (cols + offset): # _row[_row_i] += word # _row[_row_i] += ' ' # # elif len(word) > (cols - offset): # # # ensure empty row # if len(_row[_row_i]): # _row.append('') # _row_i += 1 # # chunks = schunk(word, (cols + offset)) # for i, chunk in enumerate(chunks): # if not (i + 1) == len(chunks): # _row[_row_i] += chunk # _row.append('') # _row_i += 1 # else: # _row[_row_i] += chunk # _row[_row_i] += ' ' # else: # _row.append('') # _row_i += 1 # _row[_row_i] += word # _row[_row_i] += ' ' # # _row = map(str, _row) # _stack.append(separator.join(_row)) # # _s = '\n'.join(_stack) # if is_color: # _s = string_copy._new(_s) # return _s # # def min_width(string, cols, padding=' '): # """Returns given string with right padding.""" # # is_color = isinstance(string, ColoredString) # # stack = tsplit(str(string), NEWLINES) # # for i, substring in enumerate(stack): # _sub = clean(substring).ljust((cols + 0), padding) # if is_color: # _sub = (_sub.replace(clean(substring), substring)) # stack[i] = _sub # # return '\n'.join(stack) # # Path: pkg/win32/Python27/Lib/site-packages/clint/textui/cols.py # def columns(*cols, **kwargs): # # columns = list(cols) # # cwidth = console_width(kwargs) # # _big_col = None # _total_cols = 0 # # # for i, (string, width) in enumerate(cols): # # if width is not None: # _total_cols += (width + 1) # cols[i][0] = max_width(string, width).split('\n') # else: # _big_col = i # # if _big_col: # cols[_big_col][1] = (cwidth - _total_cols) - len(cols) # cols[_big_col][0] = max_width(cols[_big_col][0], cols[_big_col][1]).split('\n') # # height = len(max([c[0] for c in cols], key=len)) # # for i, (strings, width) in enumerate(cols): # # for _ in range(height - len(strings)): # cols[i][0].append('') # # for j, string in enumerate(strings): # cols[i][0][j] = min_width(string, width) # # stack = [c[0] for c in cols] # _out = [] # # for i in range(height): # _row = '' # # for col in stack: # _row += col[i] # _row += ' ' # # _out.append(_row) # # try: # # pass # # except: # # pass # # # # # return '\n'.join(_out) # # Path: pkg/win32/Python27/Lib/site-packages/clint/utils.py # def tsplit(string, delimiters): # """Behaves str.split but supports tuples of delimiters.""" # # delimiters = tuple(delimiters) # stack = [string,] # # for delimiter in delimiters: # for i, substring in enumerate(stack): # substack = substring.split(delimiter) # stack.pop(i) # for j, _substring in enumerate(substack): # stack.insert(i+j, _substring) # # return stack , which may include functions, classes, or code. Output only the next line.
s = tsplit(s, NEWLINES)
Using the snippet: <|code_start|> self.path = path self._exists = False if path: self._create() def __repr__(self): return '<app-dir: %s>' % (self.path) def __getattribute__(self, name): if not name in ('_exists', 'path', '_create', '_raise_if_none'): if not self._exists: self._create() return object.__getattribute__(self, name) def _raise_if_none(self): """Raises if operations are carried out on an unconfigured AppDir.""" if not self.path: raise NotConfigured() def _create(self): """Creates current AppDir at AppDir.path.""" self._raise_if_none() if not self._exists: <|code_end|> , determine the next line of code. You have imports: import errno from os import remove, removedirs from os.path import isfile, join as path_join from .packages.appdirs import AppDirs, AppDirsError from .utils import mkdir_p, is_collection and context (class names, function names, or code) available: # Path: pkg/win32/Python27/Lib/site-packages/clint/utils.py # def mkdir_p(path): # """Emulates `mkdir -p` behavior.""" # try: # makedirs(path) # except OSError as exc: # Python >2.5 # if exc.errno == errno.EEXIST: # pass # else: # raise # # def is_collection(obj): # """Tests if an object is a collection. Strings don't count.""" # # if isinstance(obj, basestring): # return False # # return hasattr(obj, '__getitem__') . Output only the next line.
mkdir_p(self.path)
Predict the next line after this snippet: <|code_start|> removedirs(fn) except OSError as why: if why.errno == errno.ENOENT: pass else: raise why def read(self, filename, binary=False): """Returns contents of given file with AppDir. If file doesn't exist, returns None.""" self._raise_if_none() fn = path_join(self.path, filename) if binary: flags = 'br' else: flags = 'r' try: with open(fn, flags) as f: return f.read() except IOError: return None def sub(self, path): """Returns AppDir instance for given subdirectory name.""" <|code_end|> using the current file's imports: import errno from os import remove, removedirs from os.path import isfile, join as path_join from .packages.appdirs import AppDirs, AppDirsError from .utils import mkdir_p, is_collection and any relevant context from other files: # Path: pkg/win32/Python27/Lib/site-packages/clint/utils.py # def mkdir_p(path): # """Emulates `mkdir -p` behavior.""" # try: # makedirs(path) # except OSError as exc: # Python >2.5 # if exc.errno == errno.EEXIST: # pass # else: # raise # # def is_collection(obj): # """Tests if an object is a collection. Strings don't count.""" # # if isinstance(obj, basestring): # return False # # return hasattr(obj, '__getitem__') . Output only the next line.
if is_collection(path):
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- """ clint.textui.formatters ~~~~~~~~~~~~~~~~~~~~~~~ Core TextUI functionality for text formatting. """ from __future__ import absolute_import NEWLINES = ('\n', '\r', '\r\n') def min_width(string, cols, padding=' '): """Returns given string with right padding.""" <|code_end|> using the current file's imports: from .colored import ColoredString, clean from ..utils import tsplit, schunk and any relevant context from other files: # Path: pkg/win32/Python27/Lib/site-packages/clint/textui/colored.py # class ColoredString(object): # """Enhanced string for __len__ operations on Colored output.""" # def __init__(self, color, s): # super(ColoredString, self).__init__() # self.s = s # self.color = color # # @property # def color_str(self): # if sys.stdout.isatty() and not DISABLE_COLOR: # return '%s%s%s' % ( # getattr(colorama.Fore, self.color), self.s, colorama.Fore.RESET) # else: # return self.s # # # def __len__(self): # return len(self.s) # # def __repr__(self): # return "<%s-string: '%s'>" % (self.color, self.s) # # def __unicode__(self): # value = self.color_str # if isinstance(value, str) and hasattr(value, 'decode'): # return value.decode('utf8') # return value # # if PY3: # __str__ = __unicode__ # else: # def __str__(self): # return unicode(self).encode('utf8') # # def __iter__(self): # return iter(self.color_str) # # def __add__(self, other): # return str(self.color_str) + str(other) # # def __radd__(self, other): # return str(other) + str(self.color_str) # # def __mul__(self, other): # return (self.color_str * other) # # def split(self, sep=None): # return [self._new(s) for s in self.s.split(sep)] # # def _new(self, s): # return ColoredString(self.color, s) # # def clean(s): # strip = re.compile("([^-_a-zA-Z0-9!@#%&=,/'\";:~`\$\^\*\(\)\+\[\]\.\{\}\|\?\<\>\\]+|[^\s]+)") # txt = strip.sub('', str(s)) # # strip = re.compile(r'\[\d+m') # txt = strip.sub('', txt) # # return txt # # Path: pkg/win32/Python27/Lib/site-packages/clint/utils.py # def tsplit(string, delimiters): # """Behaves str.split but supports tuples of delimiters.""" # # delimiters = tuple(delimiters) # stack = [string,] # # for delimiter in delimiters: # for i, substring in enumerate(stack): # substack = substring.split(delimiter) # stack.pop(i) # for j, _substring in enumerate(substack): # stack.insert(i+j, _substring) # # return stack # # def schunk(string, size): # """Splits string into n sized chunks.""" # # stack = [] # # substack = [] # current_count = 0 # # for char in string: # if not current_count < size: # stack.append(''.join(substack)) # substack = [] # current_count = 0 # # substack.append(char) # current_count += 1 # # if len(substack): # stack.append(''.join(substack)) # # return stack . Output only the next line.
is_color = isinstance(string, ColoredString)
Next line prediction: <|code_start|># -*- coding: utf-8 -*- """ clint.textui.formatters ~~~~~~~~~~~~~~~~~~~~~~~ Core TextUI functionality for text formatting. """ from __future__ import absolute_import NEWLINES = ('\n', '\r', '\r\n') def min_width(string, cols, padding=' '): """Returns given string with right padding.""" is_color = isinstance(string, ColoredString) stack = tsplit(str(string), NEWLINES) for i, substring in enumerate(stack): <|code_end|> . Use current file imports: (from .colored import ColoredString, clean from ..utils import tsplit, schunk) and context including class names, function names, or small code snippets from other files: # Path: pkg/win32/Python27/Lib/site-packages/clint/textui/colored.py # class ColoredString(object): # """Enhanced string for __len__ operations on Colored output.""" # def __init__(self, color, s): # super(ColoredString, self).__init__() # self.s = s # self.color = color # # @property # def color_str(self): # if sys.stdout.isatty() and not DISABLE_COLOR: # return '%s%s%s' % ( # getattr(colorama.Fore, self.color), self.s, colorama.Fore.RESET) # else: # return self.s # # # def __len__(self): # return len(self.s) # # def __repr__(self): # return "<%s-string: '%s'>" % (self.color, self.s) # # def __unicode__(self): # value = self.color_str # if isinstance(value, str) and hasattr(value, 'decode'): # return value.decode('utf8') # return value # # if PY3: # __str__ = __unicode__ # else: # def __str__(self): # return unicode(self).encode('utf8') # # def __iter__(self): # return iter(self.color_str) # # def __add__(self, other): # return str(self.color_str) + str(other) # # def __radd__(self, other): # return str(other) + str(self.color_str) # # def __mul__(self, other): # return (self.color_str * other) # # def split(self, sep=None): # return [self._new(s) for s in self.s.split(sep)] # # def _new(self, s): # return ColoredString(self.color, s) # # def clean(s): # strip = re.compile("([^-_a-zA-Z0-9!@#%&=,/'\";:~`\$\^\*\(\)\+\[\]\.\{\}\|\?\<\>\\]+|[^\s]+)") # txt = strip.sub('', str(s)) # # strip = re.compile(r'\[\d+m') # txt = strip.sub('', txt) # # return txt # # Path: pkg/win32/Python27/Lib/site-packages/clint/utils.py # def tsplit(string, delimiters): # """Behaves str.split but supports tuples of delimiters.""" # # delimiters = tuple(delimiters) # stack = [string,] # # for delimiter in delimiters: # for i, substring in enumerate(stack): # substack = substring.split(delimiter) # stack.pop(i) # for j, _substring in enumerate(substack): # stack.insert(i+j, _substring) # # return stack # # def schunk(string, size): # """Splits string into n sized chunks.""" # # stack = [] # # substack = [] # current_count = 0 # # for char in string: # if not current_count < size: # stack.append(''.join(substack)) # substack = [] # current_count = 0 # # substack.append(char) # current_count += 1 # # if len(substack): # stack.append(''.join(substack)) # # return stack . Output only the next line.
_sub = clean(substring).ljust((cols + 0), padding)
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- """ clint.textui.formatters ~~~~~~~~~~~~~~~~~~~~~~~ Core TextUI functionality for text formatting. """ from __future__ import absolute_import NEWLINES = ('\n', '\r', '\r\n') def min_width(string, cols, padding=' '): """Returns given string with right padding.""" is_color = isinstance(string, ColoredString) <|code_end|> with the help of current file imports: from .colored import ColoredString, clean from ..utils import tsplit, schunk and context from other files: # Path: pkg/win32/Python27/Lib/site-packages/clint/textui/colored.py # class ColoredString(object): # """Enhanced string for __len__ operations on Colored output.""" # def __init__(self, color, s): # super(ColoredString, self).__init__() # self.s = s # self.color = color # # @property # def color_str(self): # if sys.stdout.isatty() and not DISABLE_COLOR: # return '%s%s%s' % ( # getattr(colorama.Fore, self.color), self.s, colorama.Fore.RESET) # else: # return self.s # # # def __len__(self): # return len(self.s) # # def __repr__(self): # return "<%s-string: '%s'>" % (self.color, self.s) # # def __unicode__(self): # value = self.color_str # if isinstance(value, str) and hasattr(value, 'decode'): # return value.decode('utf8') # return value # # if PY3: # __str__ = __unicode__ # else: # def __str__(self): # return unicode(self).encode('utf8') # # def __iter__(self): # return iter(self.color_str) # # def __add__(self, other): # return str(self.color_str) + str(other) # # def __radd__(self, other): # return str(other) + str(self.color_str) # # def __mul__(self, other): # return (self.color_str * other) # # def split(self, sep=None): # return [self._new(s) for s in self.s.split(sep)] # # def _new(self, s): # return ColoredString(self.color, s) # # def clean(s): # strip = re.compile("([^-_a-zA-Z0-9!@#%&=,/'\";:~`\$\^\*\(\)\+\[\]\.\{\}\|\?\<\>\\]+|[^\s]+)") # txt = strip.sub('', str(s)) # # strip = re.compile(r'\[\d+m') # txt = strip.sub('', txt) # # return txt # # Path: pkg/win32/Python27/Lib/site-packages/clint/utils.py # def tsplit(string, delimiters): # """Behaves str.split but supports tuples of delimiters.""" # # delimiters = tuple(delimiters) # stack = [string,] # # for delimiter in delimiters: # for i, substring in enumerate(stack): # substack = substring.split(delimiter) # stack.pop(i) # for j, _substring in enumerate(substack): # stack.insert(i+j, _substring) # # return stack # # def schunk(string, size): # """Splits string into n sized chunks.""" # # stack = [] # # substack = [] # current_count = 0 # # for char in string: # if not current_count < size: # stack.append(''.join(substack)) # substack = [] # current_count = 0 # # substack.append(char) # current_count += 1 # # if len(substack): # stack.append(''.join(substack)) # # return stack , which may contain function names, class names, or code. Output only the next line.
stack = tsplit(str(string), NEWLINES)
Based on the snippet: <|code_start|> if is_color: offset = 10 string_copy = string._new('') else: offset = 0 stack = tsplit(string, NEWLINES) for i, substring in enumerate(stack): stack[i] = substring.split() _stack = [] for row in stack: _row = ['',] _row_i = 0 for word in row: if (len(_row[_row_i]) + len(word)) < (cols + offset): _row[_row_i] += word _row[_row_i] += ' ' elif len(word) > (cols - offset): # ensure empty row if len(_row[_row_i]): _row.append('') _row_i += 1 <|code_end|> , predict the immediate next line with the help of imports: from .colored import ColoredString, clean from ..utils import tsplit, schunk and context (classes, functions, sometimes code) from other files: # Path: pkg/win32/Python27/Lib/site-packages/clint/textui/colored.py # class ColoredString(object): # """Enhanced string for __len__ operations on Colored output.""" # def __init__(self, color, s): # super(ColoredString, self).__init__() # self.s = s # self.color = color # # @property # def color_str(self): # if sys.stdout.isatty() and not DISABLE_COLOR: # return '%s%s%s' % ( # getattr(colorama.Fore, self.color), self.s, colorama.Fore.RESET) # else: # return self.s # # # def __len__(self): # return len(self.s) # # def __repr__(self): # return "<%s-string: '%s'>" % (self.color, self.s) # # def __unicode__(self): # value = self.color_str # if isinstance(value, str) and hasattr(value, 'decode'): # return value.decode('utf8') # return value # # if PY3: # __str__ = __unicode__ # else: # def __str__(self): # return unicode(self).encode('utf8') # # def __iter__(self): # return iter(self.color_str) # # def __add__(self, other): # return str(self.color_str) + str(other) # # def __radd__(self, other): # return str(other) + str(self.color_str) # # def __mul__(self, other): # return (self.color_str * other) # # def split(self, sep=None): # return [self._new(s) for s in self.s.split(sep)] # # def _new(self, s): # return ColoredString(self.color, s) # # def clean(s): # strip = re.compile("([^-_a-zA-Z0-9!@#%&=,/'\";:~`\$\^\*\(\)\+\[\]\.\{\}\|\?\<\>\\]+|[^\s]+)") # txt = strip.sub('', str(s)) # # strip = re.compile(r'\[\d+m') # txt = strip.sub('', txt) # # return txt # # Path: pkg/win32/Python27/Lib/site-packages/clint/utils.py # def tsplit(string, delimiters): # """Behaves str.split but supports tuples of delimiters.""" # # delimiters = tuple(delimiters) # stack = [string,] # # for delimiter in delimiters: # for i, substring in enumerate(stack): # substack = substring.split(delimiter) # stack.pop(i) # for j, _substring in enumerate(substack): # stack.insert(i+j, _substring) # # return stack # # def schunk(string, size): # """Splits string into n sized chunks.""" # # stack = [] # # substack = [] # current_count = 0 # # for char in string: # if not current_count < size: # stack.append(''.join(substack)) # substack = [] # current_count = 0 # # substack.append(char) # current_count += 1 # # if len(substack): # stack.append(''.join(substack)) # # return stack . Output only the next line.
chunks = schunk(word, (cols + offset))
Next line prediction: <|code_start|> if sys.platform.startswith('win'): console_width = _find_windows_console_width() else: console_width = _find_unix_console_width() _width = kwargs.get('width', None) if _width: console_width = _width else: if not console_width: console_width = 80 return console_width def columns(*cols, **kwargs): columns = list(cols) cwidth = console_width(kwargs) _big_col = None _total_cols = 0 for i, (string, width) in enumerate(cols): if width is not None: _total_cols += (width + 1) <|code_end|> . Use current file imports: (from .formatters import max_width, min_width from ..utils import tsplit from ctypes import windll, create_string_buffer import sys import termios, fcntl, struct, sys import struct) and context including class names, function names, or small code snippets from other files: # Path: pkg/win32/Python27/Lib/site-packages/clint/textui/formatters.py # def max_width(string, cols, separator='\n'): # """Returns a freshly formatted """ # # is_color = isinstance(string, ColoredString) # # if is_color: # offset = 10 # string_copy = string._new('') # else: # offset = 0 # # stack = tsplit(string, NEWLINES) # # for i, substring in enumerate(stack): # stack[i] = substring.split() # # _stack = [] # # for row in stack: # _row = ['',] # _row_i = 0 # # for word in row: # if (len(_row[_row_i]) + len(word)) < (cols + offset): # _row[_row_i] += word # _row[_row_i] += ' ' # # elif len(word) > (cols - offset): # # # ensure empty row # if len(_row[_row_i]): # _row.append('') # _row_i += 1 # # chunks = schunk(word, (cols + offset)) # for i, chunk in enumerate(chunks): # if not (i + 1) == len(chunks): # _row[_row_i] += chunk # _row.append('') # _row_i += 1 # else: # _row[_row_i] += chunk # _row[_row_i] += ' ' # else: # _row.append('') # _row_i += 1 # _row[_row_i] += word # _row[_row_i] += ' ' # # _row = map(str, _row) # _stack.append(separator.join(_row)) # # _s = '\n'.join(_stack) # if is_color: # _s = string_copy._new(_s) # return _s # # def min_width(string, cols, padding=' '): # """Returns given string with right padding.""" # # is_color = isinstance(string, ColoredString) # # stack = tsplit(str(string), NEWLINES) # # for i, substring in enumerate(stack): # _sub = clean(substring).ljust((cols + 0), padding) # if is_color: # _sub = (_sub.replace(clean(substring), substring)) # stack[i] = _sub # # return '\n'.join(stack) # # Path: pkg/win32/Python27/Lib/site-packages/clint/utils.py # def tsplit(string, delimiters): # """Behaves str.split but supports tuples of delimiters.""" # # delimiters = tuple(delimiters) # stack = [string,] # # for delimiter in delimiters: # for i, substring in enumerate(stack): # substack = substring.split(delimiter) # stack.pop(i) # for j, _substring in enumerate(substack): # stack.insert(i+j, _substring) # # return stack . Output only the next line.
cols[i][0] = max_width(string, width).split('\n')
Predict the next line after this snippet: <|code_start|>def columns(*cols, **kwargs): columns = list(cols) cwidth = console_width(kwargs) _big_col = None _total_cols = 0 for i, (string, width) in enumerate(cols): if width is not None: _total_cols += (width + 1) cols[i][0] = max_width(string, width).split('\n') else: _big_col = i if _big_col: cols[_big_col][1] = (cwidth - _total_cols) - len(cols) cols[_big_col][0] = max_width(cols[_big_col][0], cols[_big_col][1]).split('\n') height = len(max([c[0] for c in cols], key=len)) for i, (strings, width) in enumerate(cols): for _ in range(height - len(strings)): cols[i][0].append('') for j, string in enumerate(strings): <|code_end|> using the current file's imports: from .formatters import max_width, min_width from ..utils import tsplit from ctypes import windll, create_string_buffer import sys import termios, fcntl, struct, sys import struct and any relevant context from other files: # Path: pkg/win32/Python27/Lib/site-packages/clint/textui/formatters.py # def max_width(string, cols, separator='\n'): # """Returns a freshly formatted """ # # is_color = isinstance(string, ColoredString) # # if is_color: # offset = 10 # string_copy = string._new('') # else: # offset = 0 # # stack = tsplit(string, NEWLINES) # # for i, substring in enumerate(stack): # stack[i] = substring.split() # # _stack = [] # # for row in stack: # _row = ['',] # _row_i = 0 # # for word in row: # if (len(_row[_row_i]) + len(word)) < (cols + offset): # _row[_row_i] += word # _row[_row_i] += ' ' # # elif len(word) > (cols - offset): # # # ensure empty row # if len(_row[_row_i]): # _row.append('') # _row_i += 1 # # chunks = schunk(word, (cols + offset)) # for i, chunk in enumerate(chunks): # if not (i + 1) == len(chunks): # _row[_row_i] += chunk # _row.append('') # _row_i += 1 # else: # _row[_row_i] += chunk # _row[_row_i] += ' ' # else: # _row.append('') # _row_i += 1 # _row[_row_i] += word # _row[_row_i] += ' ' # # _row = map(str, _row) # _stack.append(separator.join(_row)) # # _s = '\n'.join(_stack) # if is_color: # _s = string_copy._new(_s) # return _s # # def min_width(string, cols, padding=' '): # """Returns given string with right padding.""" # # is_color = isinstance(string, ColoredString) # # stack = tsplit(str(string), NEWLINES) # # for i, substring in enumerate(stack): # _sub = clean(substring).ljust((cols + 0), padding) # if is_color: # _sub = (_sub.replace(clean(substring), substring)) # stack[i] = _sub # # return '\n'.join(stack) # # Path: pkg/win32/Python27/Lib/site-packages/clint/utils.py # def tsplit(string, delimiters): # """Behaves str.split but supports tuples of delimiters.""" # # delimiters = tuple(delimiters) # stack = [string,] # # for delimiter in delimiters: # for i, substring in enumerate(stack): # substack = substring.split(delimiter) # stack.pop(i) # for j, _substring in enumerate(substack): # stack.insert(i+j, _substring) # # return stack . Output only the next line.
cols[i][0][j] = min_width(string, width)
Continue the code snippet: <|code_start|> _args.append(arg) break else: if x not in arg: _args.append(arg) return Args(_args, no_argv=True) @property def flags(self): """Returns Arg object including only flagged arguments.""" return self.start_with('-') @property def not_flags(self): """Returns Arg object excluding flagged arguments.""" return self.all_without('-') @property def files(self, absolute=False): """Returns an expanded list of all valid paths that were passed in.""" _paths = [] for arg in self.all: <|code_end|> . Use current file imports: import os from sys import argv from collections import OrderedDict from .packages.ordereddict import OrderedDict from .utils import expand_path, is_collection and context (classes, functions, or code) from other files: # Path: pkg/win32/Python27/Lib/site-packages/clint/utils.py # def expand_path(path): # """Expands directories and globs in given path.""" # # paths = [] # path = os.path.expanduser(path) # path = os.path.expandvars(path) # # if os.path.isdir(path): # # for (dir, dirs, files) in os.walk(path): # for file in files: # paths.append(os.path.join(dir, file)) # else: # paths.extend(glob(path)) # # return paths # # def is_collection(obj): # """Tests if an object is a collection. Strings don't count.""" # # if isinstance(obj, basestring): # return False # # return hasattr(obj, '__getitem__') . Output only the next line.
for path in expand_path(arg):
Predict the next line after this snippet: <|code_start|> return self.all[i] except IndexError: return None def __contains__(self, x): return self.first(x) is not None def get(self, x): """Returns argument at given index, else none.""" try: return self.all[x] except IndexError: return None def get_with(self, x): """Returns first argument that contains given string.""" return self.all[self.first_with(x)] def remove(self, x): """Removes given arg (or list thereof) from Args object.""" def _remove(x): found = self.first(x) if found is not None: self._args.pop(found) <|code_end|> using the current file's imports: import os from sys import argv from collections import OrderedDict from .packages.ordereddict import OrderedDict from .utils import expand_path, is_collection and any relevant context from other files: # Path: pkg/win32/Python27/Lib/site-packages/clint/utils.py # def expand_path(path): # """Expands directories and globs in given path.""" # # paths = [] # path = os.path.expanduser(path) # path = os.path.expandvars(path) # # if os.path.isdir(path): # # for (dir, dirs, files) in os.walk(path): # for file in files: # paths.append(os.path.join(dir, file)) # else: # paths.extend(glob(path)) # # return paths # # def is_collection(obj): # """Tests if an object is a collection. Strings don't count.""" # # if isinstance(obj, basestring): # return False # # return hasattr(obj, '__getitem__') . Output only the next line.
if is_collection(x):
Based on the snippet: <|code_start|> """Read angles info from filename """ cpp_obj = CppObj() data = cci_nc.variables['ann_phase'][::] data = np.squeeze(data) setattr(cpp_obj, 'cpp_phase', data) # if hasattr(phase, 'mask'): # phase_out = np.where(phase.mask, -999, phase.data) # else: # phase_out = phase.data # print phase return cpp_obj def read_cci_lwp(cci_nc, cpp_obj): """ Read LWP from CCI file """ data = cci_nc.variables['cwp'][::] data = np.squeeze(data) # split LWP from CWP data = np.where(cpp_obj.cpp_phase == 2, ATRAIN_MATCH_NODATA, data) data = np.where(data < 1, ATRAIN_MATCH_NODATA, data) setattr(cpp_obj, 'cpp_lwp', data) return cpp_obj def read_cci_geoobj(cci_nc): """Read geolocation and time info from filename """ <|code_end|> , predict the immediate next line with the help of imports: from atrain_match.cloudproducts.read_pps import ( AllImagerData, CppObj, CtthObj, CmaObj, ImagerAngObj) from atrain_match.utils.runutils import do_some_geo_obj_logging import atrain_match.config as config import os import netCDF4 import numpy as np import calendar import datetime import logging and context (classes, functions, sometimes code) from other files: # Path: atrain_match/cloudproducts/read_pps.py # class AllImagerData(object): # """Class to hold all imager cloudproduct data.""" # # def __init__(self, array_dict=None): # """Init with data from array_dict, or empty.""" # self.latitude = None # self.longitude = None # self.nodata = None # latlon nodata # self.sec1970_end = None # self.sec1970_start = None # self.time = None # self.num_of_lines = None # self.instrument = "imager" # # self.imager_geo = None # self.imager_angles = None # self.imager_channeldata = None # self.ctype = None # self.cma = None # self.ctth = None # self.aux = AuxiliaryObj({'surftemp': None}) # self.cpp = None # self.nwp_segments = None # if array_dict is not None: # self.__dict__.update(array_dict) # # class CppObj: # """Class to hold imager data for CPP.""" # # def __init__(self): # """Init all datasets to None.""" # self.cpp_cot = None # self.cpp_cwp = None # self.cpp_dcot = None # self.cpp_dcwp = None # self.cpp_lwp = None # self.cpp_iwp = None # self.cpp_quality = None # self.cpp_status_flag = None # self.cpp_conditions = None # self.cpp_phase = None # self.cpp_phase_extended = None # self.cpp_reff = None # # class CtthObj: # """Class to hold imager data for CTTH.""" # # def __init__(self): # """Init all datasets to None.""" # self.height = None # self.height_corr = None # self.temperature = None # self.pressure = None # self.ctth_statusflag = None # # class CmaObj: # """Class to hold imager data for CMA and CMAPROB.""" # # def __init__(self): # """Init all datasets to None.""" # self.cma_ext = None # self.cma_quality = None # self.cma_bin = None # self.cma_prob = None # self.cma_aflag = None # self.cma_testlist0 = None # new in v2018 # self.cma_testlist1 = None # new in v2018 # self.cma_testlist2 = None # new in v2018 # self.cma_testlist3 = None # new in v2018 # self.cma_testlist4 = None # new in v2018 # self.cma_testlist5 = None # new in v2018 # # class ImagerAngObj(object): # """Class to hold imager angle data.""" # # def __init__(self): # self.satz = SmallDataObject() # self.sunz = SmallDataObject() # self.satazimuth = SmallDataObject() # self.sunazimuth = SmallDataObject() # self.azidiff = SmallDataObject() # # Path: atrain_match/utils/runutils.py # def do_some_geo_obj_logging(GeoObj): # import time # tim1 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_start)) # tim2 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_end)) # logger.debug("Starttime: %s, end time: %s", tim1, tim2) # logger.debug("Min lon: %f, max lon: %d", # np.min(np.where( # np.equal(GeoObj.longitude, GeoObj.nodata), # 99999, # GeoObj.longitude)), # np.max(GeoObj.longitude)) # logger.debug("Min lat: %d, max lat: %d", # np.min(np.where( # np.equal(GeoObj.latitude, GeoObj.nodata), # 99999, # GeoObj.latitude)), # np.max(GeoObj.latitude)) . Output only the next line.
cloudproducts = AllImagerData()
Here is a snippet: <|code_start|> def read_cci_cma(cci_nc): """Read cloudtype and flag info from filename """ cma = CmaObj() # cci_nc.variables['cc_total'][:]) # cci_nc.variables['ls_flag'][:]) # ctype = CtypeObj() # pps 0 cloudfree 3 cloudfree snow 1: cloudy, 2:cloudy # cci lsflag 0:sea 1:land cma.cma_ext = 0*cci_nc.variables['lsflag'][::] cma.cma_ext[cci_nc.variables['cc_total'][::] > 0.5] = 1 # ctype.landseaflag = cci_nc.variables['lsflag'][::] return cma def read_cci_angobj(cci_nc): """Read angles info from filename """ my_angle_obj = ImagerAngObj() my_angle_obj.satz.data = cci_nc.variables['satellite_zenith_view_no1'][::] my_angle_obj.sunz.data = cci_nc.variables['solar_zenith_view_no1'][::] my_angle_obj.azidiff = None # cci_nc.variables['rel_azimuth_view_no1']?? return my_angle_obj def read_cci_phase(cci_nc): """Read angles info from filename """ <|code_end|> . Write the next line using the current file imports: from atrain_match.cloudproducts.read_pps import ( AllImagerData, CppObj, CtthObj, CmaObj, ImagerAngObj) from atrain_match.utils.runutils import do_some_geo_obj_logging import atrain_match.config as config import os import netCDF4 import numpy as np import calendar import datetime import logging and context from other files: # Path: atrain_match/cloudproducts/read_pps.py # class AllImagerData(object): # """Class to hold all imager cloudproduct data.""" # # def __init__(self, array_dict=None): # """Init with data from array_dict, or empty.""" # self.latitude = None # self.longitude = None # self.nodata = None # latlon nodata # self.sec1970_end = None # self.sec1970_start = None # self.time = None # self.num_of_lines = None # self.instrument = "imager" # # self.imager_geo = None # self.imager_angles = None # self.imager_channeldata = None # self.ctype = None # self.cma = None # self.ctth = None # self.aux = AuxiliaryObj({'surftemp': None}) # self.cpp = None # self.nwp_segments = None # if array_dict is not None: # self.__dict__.update(array_dict) # # class CppObj: # """Class to hold imager data for CPP.""" # # def __init__(self): # """Init all datasets to None.""" # self.cpp_cot = None # self.cpp_cwp = None # self.cpp_dcot = None # self.cpp_dcwp = None # self.cpp_lwp = None # self.cpp_iwp = None # self.cpp_quality = None # self.cpp_status_flag = None # self.cpp_conditions = None # self.cpp_phase = None # self.cpp_phase_extended = None # self.cpp_reff = None # # class CtthObj: # """Class to hold imager data for CTTH.""" # # def __init__(self): # """Init all datasets to None.""" # self.height = None # self.height_corr = None # self.temperature = None # self.pressure = None # self.ctth_statusflag = None # # class CmaObj: # """Class to hold imager data for CMA and CMAPROB.""" # # def __init__(self): # """Init all datasets to None.""" # self.cma_ext = None # self.cma_quality = None # self.cma_bin = None # self.cma_prob = None # self.cma_aflag = None # self.cma_testlist0 = None # new in v2018 # self.cma_testlist1 = None # new in v2018 # self.cma_testlist2 = None # new in v2018 # self.cma_testlist3 = None # new in v2018 # self.cma_testlist4 = None # new in v2018 # self.cma_testlist5 = None # new in v2018 # # class ImagerAngObj(object): # """Class to hold imager angle data.""" # # def __init__(self): # self.satz = SmallDataObject() # self.sunz = SmallDataObject() # self.satazimuth = SmallDataObject() # self.sunazimuth = SmallDataObject() # self.azidiff = SmallDataObject() # # Path: atrain_match/utils/runutils.py # def do_some_geo_obj_logging(GeoObj): # import time # tim1 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_start)) # tim2 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_end)) # logger.debug("Starttime: %s, end time: %s", tim1, tim2) # logger.debug("Min lon: %f, max lon: %d", # np.min(np.where( # np.equal(GeoObj.longitude, GeoObj.nodata), # 99999, # GeoObj.longitude)), # np.max(GeoObj.longitude)) # logger.debug("Min lat: %d, max lat: %d", # np.min(np.where( # np.equal(GeoObj.latitude, GeoObj.nodata), # 99999, # GeoObj.latitude)), # np.max(GeoObj.latitude)) , which may include functions, classes, or code. Output only the next line.
cpp_obj = CppObj()
Given the following code snippet before the placeholder: <|code_start|> cci_nc.variables['lon'].valid_min), np.less_equal(cci_nc.variables['lon'][::], cci_nc.variables['lon'].valid_max)), cci_nc.variables['lon'][::], cloudproducts.nodata) # cloudproducts.latitude = cci_nc.variables['lat'][::] cloudproducts.latitude = np.where( np.logical_and( np.greater_equal(cci_nc.variables['lat'][::], cci_nc.variables['lat'].valid_min), np.less_equal(cci_nc.variables['lat'][::], cci_nc.variables['lat'].valid_max)), cci_nc.variables['lat'][::], cloudproducts.nodata) # For pps these are calculated in calipso.py, but better read them # from file because time are already available on arrays in the netcdf files # dsec = calendar.timegm((1993, 1, 1, 0, 0, 0, 0, 0, 0)) # TAI to UTC time_temp = daysafter4713bc_to_sec1970(cci_nc.variables['time'][::]) cloudproducts.time = time_temp[::] # [:, 0] # time_temp[:, 0] cloudproducts.sec1970_start = np.min(cloudproducts.time) cloudproducts.sec1970_end = np.max(cloudproducts.time) do_some_geo_obj_logging(cloudproducts) return cloudproducts def read_cci_ctth(cci_nc): """Read cloud top: temperature, height and pressure from filename """ <|code_end|> , predict the next line using imports from the current file: from atrain_match.cloudproducts.read_pps import ( AllImagerData, CppObj, CtthObj, CmaObj, ImagerAngObj) from atrain_match.utils.runutils import do_some_geo_obj_logging import atrain_match.config as config import os import netCDF4 import numpy as np import calendar import datetime import logging and context including class names, function names, and sometimes code from other files: # Path: atrain_match/cloudproducts/read_pps.py # class AllImagerData(object): # """Class to hold all imager cloudproduct data.""" # # def __init__(self, array_dict=None): # """Init with data from array_dict, or empty.""" # self.latitude = None # self.longitude = None # self.nodata = None # latlon nodata # self.sec1970_end = None # self.sec1970_start = None # self.time = None # self.num_of_lines = None # self.instrument = "imager" # # self.imager_geo = None # self.imager_angles = None # self.imager_channeldata = None # self.ctype = None # self.cma = None # self.ctth = None # self.aux = AuxiliaryObj({'surftemp': None}) # self.cpp = None # self.nwp_segments = None # if array_dict is not None: # self.__dict__.update(array_dict) # # class CppObj: # """Class to hold imager data for CPP.""" # # def __init__(self): # """Init all datasets to None.""" # self.cpp_cot = None # self.cpp_cwp = None # self.cpp_dcot = None # self.cpp_dcwp = None # self.cpp_lwp = None # self.cpp_iwp = None # self.cpp_quality = None # self.cpp_status_flag = None # self.cpp_conditions = None # self.cpp_phase = None # self.cpp_phase_extended = None # self.cpp_reff = None # # class CtthObj: # """Class to hold imager data for CTTH.""" # # def __init__(self): # """Init all datasets to None.""" # self.height = None # self.height_corr = None # self.temperature = None # self.pressure = None # self.ctth_statusflag = None # # class CmaObj: # """Class to hold imager data for CMA and CMAPROB.""" # # def __init__(self): # """Init all datasets to None.""" # self.cma_ext = None # self.cma_quality = None # self.cma_bin = None # self.cma_prob = None # self.cma_aflag = None # self.cma_testlist0 = None # new in v2018 # self.cma_testlist1 = None # new in v2018 # self.cma_testlist2 = None # new in v2018 # self.cma_testlist3 = None # new in v2018 # self.cma_testlist4 = None # new in v2018 # self.cma_testlist5 = None # new in v2018 # # class ImagerAngObj(object): # """Class to hold imager angle data.""" # # def __init__(self): # self.satz = SmallDataObject() # self.sunz = SmallDataObject() # self.satazimuth = SmallDataObject() # self.sunazimuth = SmallDataObject() # self.azidiff = SmallDataObject() # # Path: atrain_match/utils/runutils.py # def do_some_geo_obj_logging(GeoObj): # import time # tim1 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_start)) # tim2 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_end)) # logger.debug("Starttime: %s, end time: %s", tim1, tim2) # logger.debug("Min lon: %f, max lon: %d", # np.min(np.where( # np.equal(GeoObj.longitude, GeoObj.nodata), # 99999, # GeoObj.longitude)), # np.max(GeoObj.longitude)) # logger.debug("Min lat: %d, max lat: %d", # np.min(np.where( # np.equal(GeoObj.latitude, GeoObj.nodata), # 99999, # GeoObj.latitude)), # np.max(GeoObj.latitude)) . Output only the next line.
ctth = CtthObj()
Predict the next line for this snippet: <|code_start|> """ logger.info("Opening file %s", filename) cci_nc = netCDF4.Dataset(filename, 'r', format='NETCDF4') cloudproducts = read_cci_geoobj(cci_nc) logger.debug("Reading ctth ...") cloudproducts.ctth = read_cci_ctth(cci_nc) logger.debug("Reading angles ...") cloudproducts.imager_angles = read_cci_angobj(cci_nc) logger.debug("Reading cloud type ...") cloudproducts.cma = read_cci_cma(cci_nc) logger.debug("Reading longitude, latitude and time ...") cloudproducts.instrument = "imager" for imager in ["avhrr", "viirs", "modis", "seviri"]: if imager in os.path.basename(filename).lower(): cloudproducts.instrument = imager logger.debug("Not reading surface temperature") logger.debug("Reading cloud phase") cloudproducts.cpp = read_cci_phase(cci_nc) logger.debug("Reading LWP") cloudproducts.cpp = read_cci_lwp(cci_nc, cloudproducts.cpp) logger.debug("Not reading channel data") if cci_nc: cci_nc.close() return cloudproducts def read_cci_cma(cci_nc): """Read cloudtype and flag info from filename """ <|code_end|> with the help of current file imports: from atrain_match.cloudproducts.read_pps import ( AllImagerData, CppObj, CtthObj, CmaObj, ImagerAngObj) from atrain_match.utils.runutils import do_some_geo_obj_logging import atrain_match.config as config import os import netCDF4 import numpy as np import calendar import datetime import logging and context from other files: # Path: atrain_match/cloudproducts/read_pps.py # class AllImagerData(object): # """Class to hold all imager cloudproduct data.""" # # def __init__(self, array_dict=None): # """Init with data from array_dict, or empty.""" # self.latitude = None # self.longitude = None # self.nodata = None # latlon nodata # self.sec1970_end = None # self.sec1970_start = None # self.time = None # self.num_of_lines = None # self.instrument = "imager" # # self.imager_geo = None # self.imager_angles = None # self.imager_channeldata = None # self.ctype = None # self.cma = None # self.ctth = None # self.aux = AuxiliaryObj({'surftemp': None}) # self.cpp = None # self.nwp_segments = None # if array_dict is not None: # self.__dict__.update(array_dict) # # class CppObj: # """Class to hold imager data for CPP.""" # # def __init__(self): # """Init all datasets to None.""" # self.cpp_cot = None # self.cpp_cwp = None # self.cpp_dcot = None # self.cpp_dcwp = None # self.cpp_lwp = None # self.cpp_iwp = None # self.cpp_quality = None # self.cpp_status_flag = None # self.cpp_conditions = None # self.cpp_phase = None # self.cpp_phase_extended = None # self.cpp_reff = None # # class CtthObj: # """Class to hold imager data for CTTH.""" # # def __init__(self): # """Init all datasets to None.""" # self.height = None # self.height_corr = None # self.temperature = None # self.pressure = None # self.ctth_statusflag = None # # class CmaObj: # """Class to hold imager data for CMA and CMAPROB.""" # # def __init__(self): # """Init all datasets to None.""" # self.cma_ext = None # self.cma_quality = None # self.cma_bin = None # self.cma_prob = None # self.cma_aflag = None # self.cma_testlist0 = None # new in v2018 # self.cma_testlist1 = None # new in v2018 # self.cma_testlist2 = None # new in v2018 # self.cma_testlist3 = None # new in v2018 # self.cma_testlist4 = None # new in v2018 # self.cma_testlist5 = None # new in v2018 # # class ImagerAngObj(object): # """Class to hold imager angle data.""" # # def __init__(self): # self.satz = SmallDataObject() # self.sunz = SmallDataObject() # self.satazimuth = SmallDataObject() # self.sunazimuth = SmallDataObject() # self.azidiff = SmallDataObject() # # Path: atrain_match/utils/runutils.py # def do_some_geo_obj_logging(GeoObj): # import time # tim1 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_start)) # tim2 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_end)) # logger.debug("Starttime: %s, end time: %s", tim1, tim2) # logger.debug("Min lon: %f, max lon: %d", # np.min(np.where( # np.equal(GeoObj.longitude, GeoObj.nodata), # 99999, # GeoObj.longitude)), # np.max(GeoObj.longitude)) # logger.debug("Min lat: %d, max lat: %d", # np.min(np.where( # np.equal(GeoObj.latitude, GeoObj.nodata), # 99999, # GeoObj.latitude)), # np.max(GeoObj.latitude)) , which may contain function names, class names, or code. Output only the next line.
cma = CmaObj()
Based on the snippet: <|code_start|> cloudproducts.instrument = imager logger.debug("Not reading surface temperature") logger.debug("Reading cloud phase") cloudproducts.cpp = read_cci_phase(cci_nc) logger.debug("Reading LWP") cloudproducts.cpp = read_cci_lwp(cci_nc, cloudproducts.cpp) logger.debug("Not reading channel data") if cci_nc: cci_nc.close() return cloudproducts def read_cci_cma(cci_nc): """Read cloudtype and flag info from filename """ cma = CmaObj() # cci_nc.variables['cc_total'][:]) # cci_nc.variables['ls_flag'][:]) # ctype = CtypeObj() # pps 0 cloudfree 3 cloudfree snow 1: cloudy, 2:cloudy # cci lsflag 0:sea 1:land cma.cma_ext = 0*cci_nc.variables['lsflag'][::] cma.cma_ext[cci_nc.variables['cc_total'][::] > 0.5] = 1 # ctype.landseaflag = cci_nc.variables['lsflag'][::] return cma def read_cci_angobj(cci_nc): """Read angles info from filename """ <|code_end|> , predict the immediate next line with the help of imports: from atrain_match.cloudproducts.read_pps import ( AllImagerData, CppObj, CtthObj, CmaObj, ImagerAngObj) from atrain_match.utils.runutils import do_some_geo_obj_logging import atrain_match.config as config import os import netCDF4 import numpy as np import calendar import datetime import logging and context (classes, functions, sometimes code) from other files: # Path: atrain_match/cloudproducts/read_pps.py # class AllImagerData(object): # """Class to hold all imager cloudproduct data.""" # # def __init__(self, array_dict=None): # """Init with data from array_dict, or empty.""" # self.latitude = None # self.longitude = None # self.nodata = None # latlon nodata # self.sec1970_end = None # self.sec1970_start = None # self.time = None # self.num_of_lines = None # self.instrument = "imager" # # self.imager_geo = None # self.imager_angles = None # self.imager_channeldata = None # self.ctype = None # self.cma = None # self.ctth = None # self.aux = AuxiliaryObj({'surftemp': None}) # self.cpp = None # self.nwp_segments = None # if array_dict is not None: # self.__dict__.update(array_dict) # # class CppObj: # """Class to hold imager data for CPP.""" # # def __init__(self): # """Init all datasets to None.""" # self.cpp_cot = None # self.cpp_cwp = None # self.cpp_dcot = None # self.cpp_dcwp = None # self.cpp_lwp = None # self.cpp_iwp = None # self.cpp_quality = None # self.cpp_status_flag = None # self.cpp_conditions = None # self.cpp_phase = None # self.cpp_phase_extended = None # self.cpp_reff = None # # class CtthObj: # """Class to hold imager data for CTTH.""" # # def __init__(self): # """Init all datasets to None.""" # self.height = None # self.height_corr = None # self.temperature = None # self.pressure = None # self.ctth_statusflag = None # # class CmaObj: # """Class to hold imager data for CMA and CMAPROB.""" # # def __init__(self): # """Init all datasets to None.""" # self.cma_ext = None # self.cma_quality = None # self.cma_bin = None # self.cma_prob = None # self.cma_aflag = None # self.cma_testlist0 = None # new in v2018 # self.cma_testlist1 = None # new in v2018 # self.cma_testlist2 = None # new in v2018 # self.cma_testlist3 = None # new in v2018 # self.cma_testlist4 = None # new in v2018 # self.cma_testlist5 = None # new in v2018 # # class ImagerAngObj(object): # """Class to hold imager angle data.""" # # def __init__(self): # self.satz = SmallDataObject() # self.sunz = SmallDataObject() # self.satazimuth = SmallDataObject() # self.sunazimuth = SmallDataObject() # self.azidiff = SmallDataObject() # # Path: atrain_match/utils/runutils.py # def do_some_geo_obj_logging(GeoObj): # import time # tim1 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_start)) # tim2 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_end)) # logger.debug("Starttime: %s, end time: %s", tim1, tim2) # logger.debug("Min lon: %f, max lon: %d", # np.min(np.where( # np.equal(GeoObj.longitude, GeoObj.nodata), # 99999, # GeoObj.longitude)), # np.max(GeoObj.longitude)) # logger.debug("Min lat: %d, max lat: %d", # np.min(np.where( # np.equal(GeoObj.latitude, GeoObj.nodata), # 99999, # GeoObj.latitude)), # np.max(GeoObj.latitude)) . Output only the next line.
my_angle_obj = ImagerAngObj()
Next line prediction: <|code_start|> cloudproducts.longitude = cci_nc.variables['lon'][::] cloudproducts.longitude[cci_nc.variables['lon'][::] == in_fillvalue] = cloudproducts.nodata cloudproducts.latitude = cci_nc.variables['lon'][::] cloudproducts.latitude[cci_nc.variables['lon'][::] == in_fillvalue] = cloudproducts.nodata np.where( np.logical_and( np.greater_equal(cci_nc.variables['lon'][::], cci_nc.variables['lon'].valid_min), np.less_equal(cci_nc.variables['lon'][::], cci_nc.variables['lon'].valid_max)), cci_nc.variables['lon'][::], cloudproducts.nodata) # cloudproducts.latitude = cci_nc.variables['lat'][::] cloudproducts.latitude = np.where( np.logical_and( np.greater_equal(cci_nc.variables['lat'][::], cci_nc.variables['lat'].valid_min), np.less_equal(cci_nc.variables['lat'][::], cci_nc.variables['lat'].valid_max)), cci_nc.variables['lat'][::], cloudproducts.nodata) # For pps these are calculated in calipso.py, but better read them # from file because time are already available on arrays in the netcdf files # dsec = calendar.timegm((1993, 1, 1, 0, 0, 0, 0, 0, 0)) # TAI to UTC time_temp = daysafter4713bc_to_sec1970(cci_nc.variables['time'][::]) cloudproducts.time = time_temp[::] # [:, 0] # time_temp[:, 0] cloudproducts.sec1970_start = np.min(cloudproducts.time) cloudproducts.sec1970_end = np.max(cloudproducts.time) <|code_end|> . Use current file imports: (from atrain_match.cloudproducts.read_pps import ( AllImagerData, CppObj, CtthObj, CmaObj, ImagerAngObj) from atrain_match.utils.runutils import do_some_geo_obj_logging import atrain_match.config as config import os import netCDF4 import numpy as np import calendar import datetime import logging) and context including class names, function names, or small code snippets from other files: # Path: atrain_match/cloudproducts/read_pps.py # class AllImagerData(object): # """Class to hold all imager cloudproduct data.""" # # def __init__(self, array_dict=None): # """Init with data from array_dict, or empty.""" # self.latitude = None # self.longitude = None # self.nodata = None # latlon nodata # self.sec1970_end = None # self.sec1970_start = None # self.time = None # self.num_of_lines = None # self.instrument = "imager" # # self.imager_geo = None # self.imager_angles = None # self.imager_channeldata = None # self.ctype = None # self.cma = None # self.ctth = None # self.aux = AuxiliaryObj({'surftemp': None}) # self.cpp = None # self.nwp_segments = None # if array_dict is not None: # self.__dict__.update(array_dict) # # class CppObj: # """Class to hold imager data for CPP.""" # # def __init__(self): # """Init all datasets to None.""" # self.cpp_cot = None # self.cpp_cwp = None # self.cpp_dcot = None # self.cpp_dcwp = None # self.cpp_lwp = None # self.cpp_iwp = None # self.cpp_quality = None # self.cpp_status_flag = None # self.cpp_conditions = None # self.cpp_phase = None # self.cpp_phase_extended = None # self.cpp_reff = None # # class CtthObj: # """Class to hold imager data for CTTH.""" # # def __init__(self): # """Init all datasets to None.""" # self.height = None # self.height_corr = None # self.temperature = None # self.pressure = None # self.ctth_statusflag = None # # class CmaObj: # """Class to hold imager data for CMA and CMAPROB.""" # # def __init__(self): # """Init all datasets to None.""" # self.cma_ext = None # self.cma_quality = None # self.cma_bin = None # self.cma_prob = None # self.cma_aflag = None # self.cma_testlist0 = None # new in v2018 # self.cma_testlist1 = None # new in v2018 # self.cma_testlist2 = None # new in v2018 # self.cma_testlist3 = None # new in v2018 # self.cma_testlist4 = None # new in v2018 # self.cma_testlist5 = None # new in v2018 # # class ImagerAngObj(object): # """Class to hold imager angle data.""" # # def __init__(self): # self.satz = SmallDataObject() # self.sunz = SmallDataObject() # self.satazimuth = SmallDataObject() # self.sunazimuth = SmallDataObject() # self.azidiff = SmallDataObject() # # Path: atrain_match/utils/runutils.py # def do_some_geo_obj_logging(GeoObj): # import time # tim1 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_start)) # tim2 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_end)) # logger.debug("Starttime: %s, end time: %s", tim1, tim2) # logger.debug("Min lon: %f, max lon: %d", # np.min(np.where( # np.equal(GeoObj.longitude, GeoObj.nodata), # 99999, # GeoObj.longitude)), # np.max(GeoObj.longitude)) # logger.debug("Min lat: %d, max lat: %d", # np.min(np.where( # np.equal(GeoObj.latitude, GeoObj.nodata), # 99999, # GeoObj.latitude)), # np.max(GeoObj.latitude)) . Output only the next line.
do_some_geo_obj_logging(cloudproducts)
Here is a snippet: <|code_start|> if atrain_match_name in ["snow_ice_surface_type"]: atrain_match_name = "nsidc_surface_type" setattr(data_obj, atrain_match_name, group[dataset][...]) retv.diff_sec_1970 = h5file['diff_sec_1970'][...] h5file.close() return retv def read_files(files, truth='calipso', read_all=True, read_var=[], skip_var=[]): my_files = files.copy() tObj = read_truth_imager_match_obj(my_files.pop(), truth=truth, read_all=read_all, read_var=read_var, skip_var=skip_var) if len(my_files) > 0: for filename in my_files: tObj += read_truth_imager_match_obj(filename, truth=truth, read_all=read_all, read_var=read_var, skip_var=skip_var) return tObj # write matchup files def write_truth_imager_match_obj(filename, match_obj, SETTINGS=None, imager_obj_name='pps'): """Write *match_obj* to *filename*.""" datasets = {'diff_sec_1970': match_obj.diff_sec_1970} groups = {imager_obj_name: match_obj.imager.all_arrays} imager_attrs = {'imager_instrument': match_obj.imager_instrument} groups_attrs = {imager_obj_name: imager_attrs} for name in ['calipso', 'calipso_aerosol', 'iss', 'modis_lvl2', 'amsr', 'synop', 'mora', 'cloudsat', 'extra']: if hasattr(match_obj, name): groups[name] = getattr(match_obj, name).all_arrays <|code_end|> . Write the next line using the current file imports: import numpy as np import h5py import os.path from atrain_match.utils.common import write_match_objects from scipy.ndimage.filters import uniform_filter and context from other files: # Path: atrain_match/utils/common.py # def write_match_objects(filename, datasets, groups, group_attrs_dict, SETTINGS=None): # """Write match objects to HDF5 file *filename*. # # Arguments: # # *diff_sec_1970*: `numpy.ndarray` # time diff between matched satellites # *groups*: dict # each key/value pair should hold a list of `numpy.ndarray` instances # to be written under HDF5 group with the same name as the key # # E.g. to write a calipso match: # # >>> groups = {'calipso': ca_obj.calipso.all_arrays, # ... 'imager': ca_obj.imager.all_arrays} # >>> write_match_objects('match.h5', ca_obj.diff_sec_1970, groups) # # The match object data can then be read using `read_match_objects`: # # >>> diff_sec_1970, groups = read_match_objects('match.h5') # # """ # from atrain_match.config import COMPRESS_LVL # import h5py # from atrain_match.matchobject_io import the_used_variables # with h5py.File(filename, 'w') as f: # for name in datasets.keys(): # f.create_dataset(name, data=datasets[name], # compression=COMPRESS_LVL) # # for group_name, group_object in groups.items(): # if SETTINGS is not None and group_name in ['calipso', # 'calipso_aerosol' # 'cloudsat', # 'iss', # 'mora', # 'synop']: # skip_some = SETTINGS["WRITE_ONLY_THE_MOST_IMPORTANT_STUFF_TO_FILE"] # else: # #modis_lvl2, pps, oca, patmosx, or maia # skip_some = False # # try: # attrs_dict = group_attrs_dict[group_name] # except KeyError: # attrs_dict = {} # g = f.create_group(group_name) # for key in attrs_dict: # g.attrs[key] = attrs_dict[key] # for array_name, array in group_object.items(): # if array is None: # continue # if (skip_some and # array_name not in the_used_variables): # logger.debug("Not writing unimportant %s to file", # array_name) # continue # # if len(array) == 0: # continue # # Scalar data can't be compressed # # TODO: Write it as and attribute instead? # # g.create_dataset(array_name, data=array) # else: # # print("writing", array_name) # g.create_dataset(array_name, data=array, # compression=COMPRESS_LVL) , which may include functions, classes, or code. Output only the next line.
write_match_objects(filename, datasets, groups, groups_attrs, SETTINGS=SETTINGS)
Next line prediction: <|code_start|> ctype.ct_conditions = None return ctype, cma, ctth def read_patmosx_angobj(patmosx_nc): """Read angles info from filename.""" angle_obj = ImagerAngObj() angle_obj.satz.data = patmosx_nc.variables['sensor_zenith_angle'][0, :, :].astype(np.float) angle_obj.sunz.data = patmosx_nc.variables['solar_zenith_angle'][0, :, :].astype(np.float) angle_obj.azidiff.data = None return angle_obj def read_patmosx_geoobj(patmosx_nc, filename, cross, SETTINGS): """Read geolocation and time info from filename.""" cloudproducts = AllImagerData() latitude_v = patmosx_nc.variables['latitude'][:].astype(np.float) longitude_v = patmosx_nc.variables['longitude'][:].astype(np.float) cloudproducts.latitude = np.repeat(latitude_v[:, np.newaxis], len(longitude_v), axis=1) cloudproducts.longitude = np.repeat(longitude_v[np.newaxis, :], len(latitude_v), axis=0) cloudproducts.nodata = -999 date_time_start = cross.time date_time_end = cross.time + timedelta(seconds=SETTINGS['SAT_ORBIT_DURATION']) cloudproducts.sec1970_start = calendar.timegm(date_time_start.timetuple()) cloudproducts.sec1970_end = calendar.timegm(date_time_end.timetuple()) frac_hour = patmosx_nc.variables['scan_line_time'][0, :, :].astype(np.float) if np.ma.is_masked(frac_hour): frac_hour = frac_hour.data seconds = frac_hour*60*60.0 cloudproducts.time = seconds + patmosx_nc.variables['time'] <|code_end|> . Use current file imports: (import atrain_match.config as config import os import netCDF4 import numpy as np import calendar import logging from atrain_match.utils.runutils import do_some_geo_obj_logging from atrain_match.cloudproducts.read_pps import ( AllImagerData, CtypeObj, CtthObj, CmaObj, ImagerAngObj) from datetime import datetime from datetime import timedelta from pyhdf.SD import SD, SDC) and context including class names, function names, or small code snippets from other files: # Path: atrain_match/utils/runutils.py # def do_some_geo_obj_logging(GeoObj): # import time # tim1 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_start)) # tim2 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_end)) # logger.debug("Starttime: %s, end time: %s", tim1, tim2) # logger.debug("Min lon: %f, max lon: %d", # np.min(np.where( # np.equal(GeoObj.longitude, GeoObj.nodata), # 99999, # GeoObj.longitude)), # np.max(GeoObj.longitude)) # logger.debug("Min lat: %d, max lat: %d", # np.min(np.where( # np.equal(GeoObj.latitude, GeoObj.nodata), # 99999, # GeoObj.latitude)), # np.max(GeoObj.latitude)) # # Path: atrain_match/cloudproducts/read_pps.py # class AllImagerData(object): # """Class to hold all imager cloudproduct data.""" # # def __init__(self, array_dict=None): # """Init with data from array_dict, or empty.""" # self.latitude = None # self.longitude = None # self.nodata = None # latlon nodata # self.sec1970_end = None # self.sec1970_start = None # self.time = None # self.num_of_lines = None # self.instrument = "imager" # # self.imager_geo = None # self.imager_angles = None # self.imager_channeldata = None # self.ctype = None # self.cma = None # self.ctth = None # self.aux = AuxiliaryObj({'surftemp': None}) # self.cpp = None # self.nwp_segments = None # if array_dict is not None: # self.__dict__.update(array_dict) # # class CtypeObj: # """Class to hold imager data for cloud type.""" # # def __init__(self): # """Init all datasets to None.""" # self.cloudtype = None # self.ct_statusflag = None # self.ct_quality = None # self.ct_conditions = None # self.phaseflag = None # v2012 # # class CtthObj: # """Class to hold imager data for CTTH.""" # # def __init__(self): # """Init all datasets to None.""" # self.height = None # self.height_corr = None # self.temperature = None # self.pressure = None # self.ctth_statusflag = None # # class CmaObj: # """Class to hold imager data for CMA and CMAPROB.""" # # def __init__(self): # """Init all datasets to None.""" # self.cma_ext = None # self.cma_quality = None # self.cma_bin = None # self.cma_prob = None # self.cma_aflag = None # self.cma_testlist0 = None # new in v2018 # self.cma_testlist1 = None # new in v2018 # self.cma_testlist2 = None # new in v2018 # self.cma_testlist3 = None # new in v2018 # self.cma_testlist4 = None # new in v2018 # self.cma_testlist5 = None # new in v2018 # # class ImagerAngObj(object): # """Class to hold imager angle data.""" # # def __init__(self): # self.satz = SmallDataObject() # self.sunz = SmallDataObject() # self.satazimuth = SmallDataObject() # self.sunazimuth = SmallDataObject() # self.azidiff = SmallDataObject() . Output only the next line.
do_some_geo_obj_logging(cloudproducts)