Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Continue the code snippet: <|code_start|> def serve_data(): SocketServer.TCPServer.allow_reuse_address = True server = SocketServer.TCPServer(('127.0.0.1', 18081), SimpleRequestHandler) http_server_thread = threading.Thread(target=server.handle_request) #http_server_thread.setDaemon(True) http_serv...
assert isinstance(agent_instance, Agent)
Given snippet: <|code_start|> DOSSIER_COURANT = os.path.dirname(os.path.abspath(__file__)) DOSSIER_PARENT = os.path.dirname(DOSSIER_COURANT) sys.path.append(DOSSIER_PARENT) TEST_STRING = "hello" class SimpleRequestHandler(SocketServer.BaseRequestHandler): def handle(self): data = self.request.recv(10240...
a = Agent_Connections('testnode', "127.0.0.1", 1340, None, run=False)
Next line prediction: <|code_start|> DOSSIER_COURANT = os.path.dirname(os.path.abspath(__file__)) DOSSIER_PARENT = os.path.dirname(DOSSIER_COURANT) sys.path.append(DOSSIER_PARENT) sys.path.append("%s/vespa" % DOSSIER_PARENT) class TestInitModel(unittest.TestCase): @pytest.fixture(autouse=True) def initdir(se...
m = Model()
Based on the snippet: <|code_start|> def serve_data(): SocketServer.TCPServer.allow_reuse_address = True server = SocketServer.TCPServer(('127.0.0.1', 18081), SimpleRequestHandler) http_server_thread = threading.Thread(target=server.handle_request) #http_server_thread.setDaemon(True) http_server_th...
assert isinstance(agent_instance, Agent)
Next line prediction: <|code_start|> DOSSIER_COURANT = os.path.dirname(os.path.abspath(__file__)) DOSSIER_PARENT = os.path.dirname(DOSSIER_COURANT) sys.path.append(DOSSIER_PARENT) TEST_STRING = "hello" class SimpleRequestHandler(SocketServer.BaseRequestHandler): def handle(self): data = self.request.rec...
a = Agent_Bandwidth('testnode', "127.0.0.1", 1340, None, run=False)
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- # # Module name: agent_av.py # Version: 1.0 # Created: 29/04/2014 by Aurélien Wailly <aurelien.wailly@orange.com> # # Copyright (C) 2010-2014 Orange # # This file is part of VESPA. # # VESPA is free software: you can redistribute it and/or modify # it und...
class Agent_AV(Agent):
Continue the code snippet: <|code_start|>def agent_instance(): vm = ("test_vm", "127.0.0.1", 18081) a = Agent_AV('testnode', "127.0.0.1", 1348, None, vm) return a @pytest.fixture(scope='function') def serve_http(request): s = serve_data(SimpleRequestHandler) def fin(): s.server_close() ...
assert isinstance(agent_instance, Agent)
Here is a snippet: <|code_start|> self.request.close() class NoListRequestHandler(SocketServer.BaseRequestHandler): def handle(self): data = self.request.recv(102400) # token receive self.request.send("'%s'EndOfTransmission" % TEST_STRING.split("\\")[0]) time.sleep(0.1) # make sure i...
a = Agent_AV('testnode', "127.0.0.1", 1348, None, vm)
Given the following code snippet before the placeholder: <|code_start|> DOSSIER_COURANT = os.path.dirname(os.path.abspath(__file__)) DOSSIER_PARENT = os.path.dirname(DOSSIER_COURANT) sys.path.append(DOSSIER_PARENT) TEST_ARG1 = 'aloha:kikoo:lala' TEST_STRING = 'hello|ola:alo|%s\\r%s' % (TEST_ARG1, TEST_ARG1) HOST = '1...
s = Controller(Model_light(), None, testmode=True)
Given the code snippet: <|code_start|> DOSSIER_COURRANT = os.path.dirname(os.path.abspath(__file__)) DOSSIER_PARENT = os.path.dirname(DOSSIER_COURRANT) sys.path.append(DOSSIER_PARENT) sys.path.append("%s/vespa" % DOSSIER_PARENT) class TestInit(unittest.TestCase): @pytest.fixture(autouse=True) def initdir(sel...
m = Model()
Given the code snippet: <|code_start|> DOSSIER_COURRANT = os.path.dirname(os.path.abspath(__file__)) DOSSIER_PARENT = os.path.dirname(DOSSIER_COURRANT) sys.path.append(DOSSIER_PARENT) sys.path.append("%s/vespa" % DOSSIER_PARENT) class TestInit(unittest.TestCase): @pytest.fixture(autouse=True) def initdir(sel...
v = View(m)
Using the snippet: <|code_start|> pass def file_name(name, suffix=JSON_FILE_SUFFIX): """ Return file name based on name and suffix. """ return name + '.' + suffix class Manifest(FileJSON): """ Manifest file. """ def __init__(self, directory): super(Manifest, self).__init_...
raise DBLayoutError('Bad manifest: no ' + name + ' entry')
Based on the snippet: <|code_start|> for name, value in manifest.items(): if hash_file(os.path.join(self.directory, name), hashlib.md5()) != \ value: errors.append(name) if errors: result = False return (result, errors) def digest(sel...
raise DBStructureError('Empty category: ' + category)
Using the snippet: <|code_start|> hash_file(os.path.join(root, f), hashlib.md5()) self.write(manifest) class Metadata(FileJSON): """ Metadata file. """ def __init__(self, directory): super(Metadata, self).__init__(os.path.abspath(directory), ...
raise FileJSONError('lack of mandatory key: ' + key)
Predict the next line for this snippet: <|code_start|> categories.json: information about categories category1 packages.json: information about available packages category2 ... For DB layout v. 1: db dir manifest.json: database manifest categories.jso...
raise IntegrityError('Manifest error: ' + str(errors))
Using the snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ db_layout.py ~~~~~~~~~~~~ package database file layout :copyright: (c) 2013-2015 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ CATEGORIES_FILE_NAME = 'categories' MANIFEST_FILE_NAME = '...
class CategoryJSON(FileJSON):
Given the following code snippet before the placeholder: <|code_start|>def file_name(name, suffix=JSON_FILE_SUFFIX): """ Return file name based on name and suffix. """ return name + '.' + suffix class Manifest(FileJSON): """ Manifest file. """ def __init__(self, directory): su...
if hash_file(os.path.join(self.directory, name), hashlib.md5()) != \
Based on the snippet: <|code_start|> Returns: A dictionary with one entry. Key if a file name, content is content returned by parser. """ data = None if open_file: with open(f_name, open_mode) as f: data = parser(f) else: data = parser(f_name) return {os.p...
download_dir = TemporaryDirectory()
Here is a snippet: <|code_start|> def __init__(self, directory, name, mandatories=None): """ Args: directory: File directory. name: File name. mandatories: List of requiered keys. """ self.directory = os.path.abspath(directory) self.name = n...
raise FileJSONError('lack of mandatory key: ' + key)
Next line prediction: <|code_start|> content returned by parser. """ data = None if open_file: with open(f_name, open_mode) as f: data = parser(f) else: data = parser(f_name) return {os.path.basename(f_name): data} def load_remote_file(uri, parser, open_file = True, ...
raise DownloadingError("wget failed: " + uri)
Here is a snippet: <|code_start|> os.makedirs(self.directory) self.write_content(content) def write_content(self, content): """ Real write operation with serialization. Should be overridden. """ pass class FileJSON(FileJSONData): """ Class for JSON files...
json.dump(content, f, indent=2, sort_keys=True, cls=JSONSerializer)
Predict the next line after this snippet: <|code_start|> def write(self, content): """ Write file. """ for key in self.mandatories: if not key in content: raise FileJSONError('lack of mandatory key: ' + key) if not os.path.exists(self.directory): ...
content = json.load(f, object_hook=deserializeHook)
Given the following code snippet before the placeholder: <|code_start|> git_syncer.py ~~~~~~~~~~~~~ git sync helper :copyright: (c) 2015 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ class GITSyncer(Syncer): """ Class used to sync with git repos. """ ...
tmp_dir = TemporaryDirectory()
Predict the next line after this snippet: <|code_start|> Returns: SyncedData object that gives access to the directory with data. """ if self.persistent_datadir is None: tmp_dir = TemporaryDirectory() path = os.path.join(tmp_dir.name, "remote") else: ...
raise SyncError("sync failed (clonning): " + db_uri)
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ git_syncer.py ~~~~~~~~~~~~~ git sync helper :copyright: (c) 2015 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ <|code_end|> , predict the next li...
class GITSyncer(Syncer):
Based on the snippet: <|code_start|> Args: db_uri: URI for synchronization with remote source. repository_config: repository config. Returns: SyncedData object that gives access to the directory with data. """ if self.persistent_datadir is None: ...
return SyncedData(path)
Here is a snippet: <|code_start|> """ Synchronize local directory with remote source. Args: db_uri: URI for synchronization with remote source. repository_config: repository config. Returns: SyncedData object that gives access to the directory with da...
return TmpSyncedData(path, tmp_dir)
Given the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ mangler.py ~~~~~~~~~~ package manager interaction :copyright: (c) 2013 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ class PackageManager(object): """ Base class fo...
logger = Logger()
Next line prediction: <|code_start|> def generate(self, values): """ Generate an XML tree filled with values from a given dictionary. Args: values: Data dictionary. Returns: XML tree being an istance of xml.etree.ElementTree.Element ...
raise XMLGeneratorError('Required tag not found: ' + name)
Based on the snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ file_bson.py ~~~~~~~~~~~~ bson file format support :copyright: (c) 2015 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ class FileBSON(FileJSONData): """ Class for BSON files. ...
raise FileJSONError('failed to read: ', self.path)
Based on the snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ file_bson.py ~~~~~~~~~~~~ bson file format support :copyright: (c) 2015 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ <|code_end|> , predict the immediate next line with the help of ...
class FileBSON(FileJSONData):
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- """ file_bson.py ~~~~~~~~~~~~ bson file format support :copyright: (c) 2015 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ class FileBSON(FileJSONData): """ Class for BSON files. Supports custom JSON...
content = from_raw_serializable(rawcnt)
Using the snippet: <|code_start|> :copyright: (c) 2015 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ class FileBSON(FileJSONData): """ Class for BSON files. Supports custom JSON serialization provided by g_sorcery.serialization. """ def read_content(self): ...
rawcnt = to_raw_serializable(content)
Continue the code snippet: <|code_start|>""" def step_to_raw_serializable(obj): """ Make one step of convertion of object to the type that is serializable by the json library. None return value signifies an error. """ if hasattr(obj, "serialize"): if hasattr(obj, "deserialize"): ...
if isinstance(obj, basestring) \
Given snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ base.py ~~~~~~~ base class for tests :copyright: (c) 2013 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ class BaseTest(unittest.TestCase): def setUp(self): <|code_end|> , conti...
self.tempdir = TemporaryDirectory()
Next line prediction: <|code_start|> List of all eclasses with string entries. """ result = [] for directory in [self.eclass_dir, os.path.join(get_pkgpath(), 'data')]: if directory: for f_name in glob.iglob(os.path.join(directory, '*.eclass')): ...
raise EclassError('No eclass ' + eclass)
Continue the code snippet: <|code_start|> ~~~~~~~~~ eclass generation :copyright: (c) 2013 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ class EclassGenerator(object): """ Generates eclasses from files in a given dir. """ def __init__(self, eclass_d...
for directory in [self.eclass_dir, os.path.join(get_pkgpath(), 'data')]:
Based on the snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ server.py ~~~~~~~~~ test server :copyright: (c) 2013 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ <|code_end|> , predict the immediate next line with the help of imports: i...
if py2k:
Given the following code snippet before the placeholder: <|code_start|> cfg_path = path break if not cfg_path: logger.error('no config file for ' + name + ' backend\n') return -1 cfg_f = FileJSON(cfg_path, cfg, ['package']) try: config = cfg_f.read() except...
global_config = configparser.ConfigParser()
Given the code snippet: <|code_start|> """ g_sorcery.py ~~~~~~~~~~~~ the main module :copyright: (c) 2013 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ def main(): logger = Logger() if len(sys.argv) < 2: logger.error("no backend specified") ret...
cfg_f = FileJSON(cfg_path, cfg, ['package'])
Predict the next line after this snippet: <|code_start|> ~~~~~~~~~~~~ the main module :copyright: (c) 2013 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ def main(): logger = Logger() if len(sys.argv) < 2: logger.error("no backend specified") return ...
except FileJSONError as e:
Continue the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ g_sorcery.py ~~~~~~~~~~~~ the main module :copyright: (c) 2013 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ def main(): <|code_end|> . Use current file imports: import import...
logger = Logger()
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_eclass.py ~~~~~~~~~~~~~~ eclass test suite :copyright: (c) 2013 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ class TestEclassGenera...
eclass_g = EclassGenerator(self.tempdir.name)
Based on the snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_eclass.py ~~~~~~~~~~~~~~ eclass test suite :copyright: (c) 2013 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ <|code_end|> , predict the immediate next line with the h...
class TestEclassGenerator(BaseTest):
Given the following code snippet before the placeholder: <|code_start|> def sync(self, db_uri, repository_config): """ Synchronize local directory with remote source. Args: db_uri: URI for synchronization with remote source. repository_config: repository config. ...
download_dir = TemporaryDirectory()
Given the following code snippet before the placeholder: <|code_start|> Synchronize local directory with remote source. Args: db_uri: URI for synchronization with remote source. repository_config: repository config. Returns: SyncedData object that gives acces...
raise SyncError('sync failed: ' + db_uri)
Using the snippet: <|code_start|> """ Synchronize local directory with remote source. Args: db_uri: URI for synchronization with remote source. repository_config: repository config. Returns: SyncedData object that gives access to the directory with da...
if wget(db_uri, download_dir.name):
Continue the code snippet: <|code_start|> self.directory = os.path.join(self.tempdir.name, 'tst') self.name = 'tst.json' self.path = os.path.join(self.directory, self.name) def test_write_read(self): fj = FileBSON(self.directory, self.name, ["mandatory"]) ...
content = serializable_elist([content1, content2])
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_FileBSON.py ~~~~~~~~~~~~~~~~ FileBSON test suite :copyright: (c) 2013-2015 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ BSON_INSTALLED = Fal...
class TestFileJSON(BaseTest):
Predict the next line for this snippet: <|code_start|> BSON_INSTALLED = False try: BSON_INSTALLED = True except ImportError as e: pass if BSON_INSTALLED: class TestFileJSON(BaseTest): def setUp(self): super(TestFileJSON, self).setUp() self.directory = os.path.join(self.tem...
self.assertRaises(TypeError, fj.write, NonSerializableClass())
Based on the snippet: <|code_start|>""" BSON_INSTALLED = False try: BSON_INSTALLED = True except ImportError as e: pass if BSON_INSTALLED: class TestFileJSON(BaseTest): def setUp(self): super(TestFileJSON, self).setUp() self.directory = os.path.join(self.tempdir.name, ...
content = SerializableClass("1", "2")
Using the snippet: <|code_start|> BSON_INSTALLED = True except ImportError as e: pass if BSON_INSTALLED: class TestFileJSON(BaseTest): def setUp(self): super(TestFileJSON, self).setUp() self.directory = os.path.join(self.tempdir.name, 'tst') self.name = 'tst.json...
content = DeserializableClass("1", "2")
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_FileJSON.py ~~~~~~~~~~~~~~~~ FileJSON test suite :copyright: (c) 2013-2015 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ class TestFileJSON(BaseTest): def...
fj = FileJSON(self.directory, self.name, [])
Here is a snippet: <|code_start|> :license: GPL-2, see LICENSE for more details. """ class TestFileJSON(BaseTest): def setUp(self): super(TestFileJSON, self).setUp() self.directory = os.path.join(self.tempdir.name, 'tst') self.name = 'tst.json' self.path = os.path.join(self.di...
self.assertRaises(FileJSONError, fj.read)
Predict the next line for this snippet: <|code_start|> def test_write_luck_of_mandatory_key(self): fj = FileJSON(self.directory, self.name, ["mandatory"]) self.assertRaises(FileJSONError, fj.write, {"test":"test"}) def test_write_read(self): fj = FileJSON(self.directory, self.name, ["man...
content = serializable_elist([content1, content2])
Given the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_FileJSON.py ~~~~~~~~~~~~~~~~ FileJSON test suite :copyright: (c) 2013-2015 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ <|code_end|> , generate the next line using the impor...
class TestFileJSON(BaseTest):
Predict the next line after this snippet: <|code_start|> def test_read_nonexistent_mandatory_key(self): fj = FileJSON(self.directory, self.name, ["mandatory1", "mandatory2"]) content = fj.read() self.assertEqual(content, {"mandatory1":"", "mandatory2":""}) self.assertTrue(os.path.isfi...
self.assertRaises(TypeError, fj.write, NonSerializableClass())
Predict the next line for this snippet: <|code_start|> content = fj.read() self.assertEqual(content, {}) self.assertTrue(os.path.isfile(self.path)) def test_read_nonexistent_mandatory_key(self): fj = FileJSON(self.directory, self.name, ["mandatory1", "mandatory2"]) content = ...
content = SerializableClass("1", "2")
Given snippet: <|code_start|> self.assertTrue(os.path.isfile(self.path)) def test_read_luck_of_mandatory_key(self): fj = FileJSON(self.directory, self.name, ["mandatory"]) os.makedirs(self.directory) with open(self.path, 'w') as f: json.dump({"test":"test"}, f) se...
content = DeserializableClass("1", "2")
Using the snippet: <|code_start|> self.template.append("") if hasattr(layout, "vars_after_inherit"): self._append_vars_to_template(layout.vars_after_inherit) self.template.append("") self.template.append('DESCRIPTION="%(description)s"') self.template.append("...
if isinstance(var, basestring):
Predict the next line after this snippet: <|code_start|> A hook allowing changing ebuild_data before ebuild generation. Args: ebuild_data: Dictinary with ebuild data. Returns: Dictinary with ebuild data. """ return ebuild_data def process(self, ebuil...
raise DependencyError(error)
Given the following code snippet before the placeholder: <|code_start|> def _consume_done_putters(self): # Delete waiters at the head of the put() queue who've timed out. while self._putters and self._putters[0][1].done(): self._putters.popleft() def qsize(self): """Number o...
@coroutine
Based on the snippet: <|code_start|> fname_noext, ext = os.path.splitext(filename) for part in dirname.strip('/').split(os.path.sep)[2:][-2:] + [fname_noext]: for match in PATH_SPLIT.split(part): if match: yield match # FIXME: this is flawed. Can use placeholders by taking ...
fixed_items.append("'%s'" % tostr(item.replace("'", "''")))
Given the code snippet: <|code_start|>def win32_version_error(): """ Pops up a message box on Windows indicating the Python version is incompatible. """ if sys.hexversion >= 0x03000000: # Python 3 strings are unicode, so use the Unicode variant. MessageBox = windll.user32.Mess...
main()
Using the snippet: <|code_start|> idlen = struct.unpack('<B', s[pos:pos+1])[0] idstring = s[pos+1:pos+1+idlen] idstring = str(idstring, 'utf-16').replace('\0', '') log.debug("Language: %d/%d: %s" % (i+1, count, idstring)) self._languages.app...
class AsfAudio(audiocore.Audio):
Given the following code snippet before the placeholder: <|code_start|> def _do_close_connection(wr, connection=connection, msg=msg): warnings.warn(msg, ResourceWarning) connection.close() self._connection_wr = weakref.ref(self, _do_close_connection) @asyncio.coroutine ...
self.headers = CaseInsensitiveMultiDict(
Using the snippet: <|code_start|> if isinstance(params, dict): params = list(params.items()) # for GET request include data to query params if data and self.method in self.GET_METHODS: if isinstance(data, dict): data = data.items() params = lis...
elif isinstance(headers, MultiDict):
Given snippet: <|code_start|> scheme, netloc, path, query, fragment = urllib.parse.urlsplit(self.url) if not path: path = '/' if isinstance(params, dict): params = list(params.items()) # for GET request include data to query params if data and self.method...
self.headers = MutableMultiDict()
Next line prediction: <|code_start|>#!/usr/bin/env python3 NAME = 'stagehand' VERSION = '0.3.2' # Import a couple modules from the source tree needed to build, but disable # generation of spurious pyc files. sys.dont_write_bytecode = True sys.dont_write_bytecode = False if sys.hexversion < 0x03030000: print('fa...
xmlconfig.convert(f, outfile, package, 'stagehand.toolbox.config')
Using the snippet: <|code_start|> def _compile_coffee(self): # If the user extracts a tarball without preserving mtime, it may be possible # for a not-actually-stale compiled coffee file to have a slightly older mtime # than the source. Here we determine the mtimes of newest and oldest data...
coffee.cscompile(f, fc, is_html)
Given the code snippet: <|code_start|> with ASCII equivalents. """ if not u: return u # Double quotes u = u.replace('\u201c', '"').replace('\u201d', '"') # Single quotes u = u.replace('\u2018', "'").replace('\u2019', "'") # Endash u = u.replace('\u2014', '--') # Ellipses ...
desc = get_description(item)
Given snippet: <|code_start|># Please see the file AUTHORS for a complete list of authors. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option...
media = MEDIA_DISC
Predict the next line after this snippet: <|code_start|> ('uCallbackMessage', c_uint), ('hIcon', HICON), ('szTip', c_wchar * 128), ('dwState', DWORD), ('dwStateMask', DWORD), ('szInfo', c_wchar * 256), ('uVersion', c_uint), # unioned with uTimeout ('...
info, mtime, f = get_file_from_zip('data', 'win32tray.ico')
Predict the next line for this snippet: <|code_start|> ('dwStateMask', DWORD), ('szInfo', c_wchar * 256), ('uVersion', c_uint), # unioned with uTimeout ('szInfoTitle', c_wchar * 64), ('dwInfoFlags', DWORD), ('guidItem', GUID), ('hBalloonIcon', HICON) ] ...
path = os.path.join(get_temp_path('stagehand'), 'win32tray.ico')
Here is a snippet: <|code_start|> @asyncio.coroutine def parse_xml(what, nest=[]): results = [] def handle(element): info = {} attrs = dict((a, getattr(element, a)) for a in element.attributes) if element.content: results.append((element.tagname, attrs, element.content)) ...
status, data = yield from download(what, retry=4)
Using the snippet: <|code_start|> @asyncio.coroutine def parse_xml(what, nest=[]): results = [] def handle(element): info = {} attrs = dict((a, getattr(element, a)) for a in element.attributes) if element.content: results.append((element.tagname, attrs, element.content)) ...
e = ElementParser()
Given snippet: <|code_start|> return 'RemoteException({})'.format(repr(self._remote_exc)) class RPCError(Exception): pass class NotConnectedError(RPCError): """ Raised when an attempt is made to call a method on a channel that is not connected. """ pass class AuthenticationError(RPCErro...
self._auth_secret = tobytes(auth_secret)
Given snippet: <|code_start|> def __repr__(self): return 'RemoteException({})'.format(repr(self._remote_exc)) class RPCError(Exception): pass class NotConnectedError(RPCError): """ Raised when an attempt is made to call a method on a channel that is not connected. """ pass class Aut...
self.signals = Signals('client-connected')
Given the code snippet: <|code_start|> """ Strips punctutation and (optionally) parentheticals from a title to improve searching. :param title: the string to massage :param apostrophe: one of the CLEAN_APOSTROPHE_* constants (below) :param parens: if True, remove anything...
title = remove_stop_words(title)
Given the code snippet: <|code_start|># # file: gadgetize.py # input a file with a compiled circuit (h,s,CNOT,t) only # output stabilizer projectors g(x,y) and h(x) # # count the number of random bits to generate # this is the number of Ts plus measured ancillas # assumes circuit consists only of gates in the gate s...
gate = standardGate(line, lineMode=True)
Next line prediction: <|code_start|>checking is not being performed.""" _LOGGER = logging.getLogger(__name__) def do_nothing(): """Simple default callback.""" def header_required(response, name, get_headers, callback=do_nothing): """Checks that a specific header is in a headers dictionary. Args: ...
raise common.InvalidResponse(
Continue the code snippet: <|code_start|> Returns: object: The return value of ``func``. """ total_sleep = 0.0 num_retries = 0 # base_wait will be multiplied by the multiplier on the first retry. base_wait = float(retry_strategy.initial_delay) / retry_strategy.multiplier # Set the r...
base_wait, wait_time = _helpers.calculate_retry_wait(
Given the code snippet: <|code_start|> def test_do_nothing(): ret_val = _helpers.do_nothing() assert ret_val is None class Test_header_required(object): def _success_helper(self, **kwargs): name = "some-header" value = "The Right Hand Side" headers = {name: value, "other-name": "...
with pytest.raises(common.InvalidResponse) as exc_info:
Given the following code snippet before the placeholder: <|code_start|> class TestRawRequestsMixin(object): def test__get_body_wo_content_consumed(self): body = b"This is the payload." raw = mock.Mock(spec=["stream"]) raw.stream.return_value = iter([body]) response = mock.Mock(raw=r...
assert truthy not in common.RETRYABLE
Given snippet: <|code_start|># Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
assert status_code == _request_helpers.RequestsMixin._get_status_code(response)
Using the snippet: <|code_start|> def test_do_nothing(): ret_val = _helpers.do_nothing() assert ret_val is None class Test_header_required(object): def _success_helper(self, **kwargs): name = "some-header" value = "The Right Hand Side" headers = {name: value, "other-name": "oth...
with pytest.raises(common.InvalidResponse) as exc_info:
Here is a snippet: <|code_start|># Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
assert status_code == _helpers.RequestsMixin._get_status_code(response)
Given the following code snippet before the placeholder: <|code_start|># Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICE...
error = common.InvalidResponse(response, 1, "a", [b"m"], True)
Predict the next line for this snippet: <|code_start|> * the URL for the request * the body of the request (always :data:`None`) * headers for the request Raises: ValueError: If the current :class:`Download` has already finished. .. ...
_helpers.require_status_code(
Next line prediction: <|code_start|> class DownloadBase(object): """Base class for download helpers. Defines core shared behavior across different download types. Args: media_url (str): The URL containing the media to be downloaded. stream (IO[bytes]): A write-able stream (i.e. file-like o...
self._retry_strategy = common.RetryStrategy()
Predict the next line after this snippet: <|code_start|># Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unl...
download = _download.DownloadBase(EXAMPLE_URL)
Given snippet: <|code_start|> headers = {"spoonge": "borb"} download = _download.Download(EXAMPLE_URL, start=11, end=111, headers=headers) method, url, payload, new_headers = download._prepare_request() assert method == "GET" assert url == EXAMPLE_URL assert payload is Non...
with pytest.raises(common.InvalidResponse) as exc_info:
Given the code snippet: <|code_start|> ('willcom', extra_willcom_ips), ('crawler', extra_crawler_ips), ('nonmobile', None), ): extra = self._extra_ips.setdefault(carrier, []) if not...
hosts.append(IP(addr))
Predict the next line for this snippet: <|code_start|> # extra_ip is None or empty sequence continue if not isinstance(ips, (list, tuple)): ips = [ips] for addr in ips: self.add_ip(carrier, addr) # factary classes s...
def get_ip(self, carrier):
Here is a snippet: <|code_start|> 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 ...
return cidr.IP(remote_addr)
Here is a snippet: <|code_start|> assert ua.is_docomo() assert ua.is_bogus() ua = detect({'HTTP_USER_AGENT': 'DoCoMo/2.0 P01A(c100;TB;W24H15)', 'REMOTE_ADDR' : '127.0.0.1', 'HTTP_X_FORWARDED_FOR': 'unknown,210.153.84.0', }, context=contex...
class MyDoCoMoUserAgent(DoCoMoUserAgent):
Here is a snippet: <|code_start|> 'REMOTE_ADDR' : '127.0.0.1', 'HTTP_X_FORWARDED_FOR': 'unknown,210.153.84.0', }, context=context) assert ua.is_docomo() assert ua.is_bogus() def test_extra_ip(): ctxt1 = Context(extra_docomo_ips=['192.168....
class MyDoCoMoUserAgentFactory(DoCoMoUserAgentFactory):
Predict the next line after this snippet: <|code_start|> assert ua.is_softbank() res = ua.is_bogus() assert res == expected, '%s expected, actual %s' % (expected, res) for ip, expected in ( ('210.230.128.224', True), ('123.108.237.0', False), ): yield func, ip...
class MySoftBankUserAgent(SoftBankUserAgent):
Given snippet: <|code_start|># -*- coding: utf-8 -*- VODAFONE_VENDOR_RE = re.compile(r'V\d+([A-Z]+)') JPHONE_VENDOR_RE = re.compile(r'J-([A-Z]+)') SOFTBANK_CRAWLER_RE = re.compile(r'\([^)]+\)') <|code_end|> , continue by predicting the next line. Consider current file imports: import re from uamobile.parser.base im...
class SoftBankUserAgentParser(UserAgentParser):
Using the snippet: <|code_start|> """ try: return self.environ['HTTP_X_DCMGUID'] except KeyError: return None guid = property(get_guid) def get_ue_version(self): """ return UE-Version see http://www.nttdocomo.co.jp/service/imode/make/conten...
return Display(**params)