Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
4,000
def Port(port): """Sanitize a port value. Args: port: a port value Returns: port: a port value Raises: BadPortValue: port is not valid integer or string BadPortRange: port is outside valid range """ pval = -1 try: pval = int(port) except __HOLE__: raise BadPortValue('port %...
ValueError
dataset/ETHPy150Open google/capirca/lib/port.py/Port
4,001
def _handle_message(self, opcode, data): if self.client_terminated: return if opcode == 0x1: # UTF-8 data try: decoded = data.decode("utf-8") except __HOLE__: self._abort() return self._async_cal...
UnicodeDecodeError
dataset/ETHPy150Open jbalogh/tornado-websocket-client/websocket.py/WebSocket._handle_message
4,002
def main(url, message='hello, world'): class HelloSocket(WebSocket): def on_open(self): self.ping() print '>>', message self.write_message(message) def on_message(self, data): print 'on_message:', data msg = raw_input('>> ') ...
KeyboardInterrupt
dataset/ETHPy150Open jbalogh/tornado-websocket-client/websocket.py/main
4,003
def run(self, address, credopts=None, sambaopts=None, versionopts=None): lp = sambaopts.get_loadparm() try: res = netcmd_get_domain_infos_via_cldap(lp, None, address) except __HOLE__: raise CommandError("Invalid IP address '" + address + "'!") self.outf.write("For...
RuntimeError
dataset/ETHPy150Open byt3bl33d3r/pth-toolkit/lib/python2.7/site-packages/samba/netcmd/domain.py/cmd_domain_info.run
4,004
def run(self, sambaopts=None, credopts=None, versionopts=None, interactive=None, domain=None, domain_guid=None, domain_sid=None, ntds_guid=None, invocationid=None, host_name=None, host_ip=None, host_ip6=None, ...
IndexError
dataset/ETHPy150Open byt3bl33d3r/pth-toolkit/lib/python2.7/site-packages/samba/netcmd/domain.py/cmd_domain_provision.run
4,005
def run(self, subcommand, H=None, forest_level=None, domain_level=None, quiet=False, credopts=None, sambaopts=None, versionopts=None): lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp, fallback_machine=True) samdb = SamDB(url=H, session_info=system_session(), ...
KeyError
dataset/ETHPy150Open byt3bl33d3r/pth-toolkit/lib/python2.7/site-packages/samba/netcmd/domain.py/cmd_domain_level.run
4,006
def decode_body(content_type, response): """Headers: A dict of key value Content: str returns files dict filename: body """ if not content_type.startswith("multipart/mixed"): raise ValueError("Invalid content type") boundary = content_type.split("boundary=")[1] #charset = ...
KeyError
dataset/ETHPy150Open conan-io/conan/conans/client/rest/multipart_decode.py/decode_body
4,007
def __init__(self, message, status_code, *args, **kwargs): super(OsbsResponseException, self).__init__(message, *args, **kwargs) self.status_code = status_code # try decoding openshift Status object # https://docs.openshift.org/latest/rest_api/openshift_v1.html#v1-status try: ...
ValueError
dataset/ETHPy150Open projectatomic/osbs-client/osbs/exceptions.py/OsbsResponseException.__init__
4,008
def term_width(): """ Return the column width of the terminal, or None if it can't be determined. """ if fcntl and termios: try: winsize = fcntl.ioctl(0, termios.TIOCGWINSZ, ' ') _, width = struct.unpack('hh', winsize) return width except __HOLE__:...
IOError
dataset/ETHPy150Open araile/see/see.py/term_width
4,009
def see(obj=_LOCALS, pattern=None, r=None): """ Inspect an object. Like the dir() builtin, but easier on the eyes. Keyword arguments (all optional): obj -- object to be inspected pattern -- shell-style search pattern (e.g. '*len*') r -- regular expression If obj is omitted, objects in the ...
AttributeError
dataset/ETHPy150Open araile/see/see.py/see
4,010
def test_suite(): suite = unittest.TestSuite() try: import cssselect except __HOLE__: # no 'cssselect' installed print("Skipping tests in lxml.cssselect - external cssselect package is not installed") return suite import lxml.cssselect suite.addTests(doctest.DocTestS...
ImportError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/lxml-3.3.6/src/lxml/tests/test_css.py/test_suite
4,011
def _GenerateSection( self, template_filename, template_mappings, output_writer, output_filename, access_mode='wb'): """Generates a section from template filename. Args: template_filename: a string containing the name of the template file. template_mpppings: a dictionary containing the ...
ValueError
dataset/ETHPy150Open libyal/libyal/scripts/source-generate.py/SourceFileGenerator._GenerateSection
4,012
def read(self): try: end = self.items.pop() except __HOLE__: cmd_title('All items have been read.') return None if DEBUG: print('Reading new item from stream... {}\n'.format(end)) print('[CURRENT STREAM] {}\n'.format(' -- '.join(self.it...
IndexError
dataset/ETHPy150Open christabor/MoAL/MOAL/data_structures/abstract/stream.py/Stream.read
4,013
def _initialize(): global _initialized def _init_simplejson(): global _decode, _encode import simplejson _decode = lambda string, loads=simplejson.loads: loads(string) _encode = lambda obj, dumps=simplejson.dumps: \ dumps(obj, allow_nan=False, ensure_ascii=False) ...
ImportError
dataset/ETHPy150Open djc/couchdb-python/couchdb/json.py/_initialize
4,014
@capabilities.check def add(self, image_id, image_file, image_size, context=None, verifier=None): """ Stores an image file with supplied identifier to the backend storage system and returns a tuple containing information about the stored image. :param image_id: T...
IOError
dataset/ETHPy150Open openstack/glance_store/glance_store/_drivers/cinder.py/Store.add
4,015
def _run(self, scanObject, result, depth, args): ''' Arguments: unixsocket -- Path to the clamd unix socket (str) maxbytes -- Maximum number of bytes to scan (0 is unlimited) (int) Returns: Flags -- Virus name hits Metadata -- Unix sock...
IOError
dataset/ETHPy150Open lmco/laikaboss/laikaboss/modules/scan_clamav.py/SCAN_CLAMAV._run
4,016
def get_src_parts(self, bundle): try: return bundle.src_parts except __HOLE__: parts = ['',''] bill = bundle.obj try: ps = bill.proposals.order_by('-date')[0] if ps.content_html: parts = ps.content_html.s...
AttributeError
dataset/ETHPy150Open ofri/Open-Knesset/laws/api.py/BillResource.get_src_parts
4,017
def get_int_arg(request, field, default=None): """Try to get an integer value from a query arg.""" try: val = int(request.arguments.get(field, [default])[0]) except (ValueError, __HOLE__): val = default return val
TypeError
dataset/ETHPy150Open YelpArchive/pushmanager/pushmanager/core/util.py/get_int_arg
4,018
def get_servlet_urlspec(servlet): try: return (servlet.regexp, servlet) except __HOLE__: name = servlet.__name__ regexp = r"/%s" % name[:-len("Servlet")].lower() return (regexp, servlet)
AttributeError
dataset/ETHPy150Open YelpArchive/pushmanager/pushmanager/core/util.py/get_servlet_urlspec
4,019
def get_data_directory(): FONTBAKERY_DATA_DIRNAME = 'fontbakery' try: #Windows code: d = op.join(os.environ["FONTBAKERY_DATA_DIRNAME"], FONTBAKERY_DATA_DIRNAME) except __HOLE__: #GNU/Linux and Mac code: d = op.join(op.expanduser("~"), "...
KeyError
dataset/ETHPy150Open googlefonts/fontbakery/bakery_cli/utils.py/get_data_directory
4,020
def runtests(*test_args): parent = dirname(abspath(__file__)) sys.path.insert(0, parent) try: from django.test.runner import DiscoverRunner def run_tests(test_args, verbosity, interactive): runner = DiscoverRunner( verbosity=verbosity, interactive=interactive, fa...
ImportError
dataset/ETHPy150Open carljm/django-localeurl/runtests.py/runtests
4,021
def request_spectra(self): cmd = struct.pack('<B', 0x09) self.log_debug('Requesting spectra') self.usb_send_ep.write(cmd) data = np.zeros(shape=(3840,), dtype='<u2') try: data_lo = self._spec_lo.read(512*4, timeout=100) data_hi = self._sp...
AssertionError
dataset/ETHPy150Open LabPy/lantz/lantz/drivers/oceanoptics/usb4000.py/USB4000.request_spectra
4,022
def main(): try: _setup() collection_interval = cfg.CONF.garbagecollector.collection_interval garbage_collector = GarbageCollectorService(collection_interval=collection_interval) exit_code = garbage_collector.run() except __HOLE__ as exit_code: return exit_code excep...
SystemExit
dataset/ETHPy150Open StackStorm/st2/st2reactor/st2reactor/cmd/garbagecollector.py/main
4,023
def _GetQueryImplementation(name): """Returns the implementation for a query type. @param name: Query type, must be one of L{constants.QR_VIA_OP} """ try: return _QUERY_IMPL[name] except __HOLE__: raise errors.OpPrereqError("Unknown query resource '%s'" % name, errors....
KeyError
dataset/ETHPy150Open ganeti/ganeti/lib/cmdlib/query.py/_GetQueryImplementation
4,024
def is_ipv4(ip): try: socket.inet_aton(ip) except (__HOLE__, socket.error): return False return True
ValueError
dataset/ETHPy150Open abusesa/abusehelper/abusehelper/bots/experts/geoipexpert.py/is_ipv4
4,025
def load_geodb(path, log=None): def geoip(reader, ip): try: record = reader.city(ip) except (AddressNotFoundError, __HOLE__): return {} if record is None: return {} result = {} geoip_cc = record.country.iso_code if geoip_cc: ...
ValueError
dataset/ETHPy150Open abusesa/abusehelper/abusehelper/bots/experts/geoipexpert.py/load_geodb
4,026
def tearDown(self): for recorder in self.top.recorders: recorder.close() os.chdir(self.startdir) if not os.environ.get('OPENMDAO_KEEPDIRS', False): try: shutil.rmtree(self.tempdir) except __HOLE__: pass
OSError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.lib/src/openmdao/lib/casehandlers/test/test_csv_post_processor.py/CSVPostProcessorTestCase.tearDown
4,027
def generate_and_compare(self, name): directory = os.path.abspath(os.path.dirname(__file__)) name = os.path.join(directory, name) cds = CaseDataset(name + '.json', 'json') data = cds.data.fetch() caseset_query_to_csv(data, self.filename_csv) with open(name + '.csv', '...
TypeError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.lib/src/openmdao/lib/casehandlers/test/test_csv_post_processor.py/CSVPostProcessorTestCase.generate_and_compare
4,028
@permission_required("core.manage_shop") def manage_accessories_inline(request, product_id, as_string=False, template_name="manage/product/accessories_inline.html"): """View which shows all accessories for the product with the passed id. """ product = Product.objects.get(pk=product_id) product_accessori...
TypeError
dataset/ETHPy150Open diefenbach/django-lfs/lfs/manage/product/accessories.py/manage_accessories_inline
4,029
def decode(self, encoded_packet): """Decode a transmitted package. The return value indicates how many binary attachment packets are necessary to fully decode the packet. """ ep = encoded_packet try: self.packet_type = int(ep[0:1]) except __HOLE__: ...
TypeError
dataset/ETHPy150Open miguelgrinberg/python-socketio/socketio/packet.py/Packet.decode
4,030
def generate_tokens(readline): """ The generate_tokens() generator requires one argment, readline, which must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as a string. Alterna...
StopIteration
dataset/ETHPy150Open Southpaw-TACTIC/TACTIC/src/context/client/tactic-api-python-4.0.api04/Lib/tokenize.py/generate_tokens
4,031
def check_exists(fips_dir) : try : subprocess.check_output(['python2', '--version'], stderr=subprocess.STDOUT) return True except (__HOLE__, subprocess.CalledProcessError) : return False
OSError
dataset/ETHPy150Open floooh/fips/mod/tools/python2.py/check_exists
4,032
def start(self): self.log.info("Refreshing existing files.") for root, dirs, files in os.walk(self.data_dir): for filename in files: self._maybe_queue_file(os.path.join(root, filename), enqueue=not(self.ignore_existing)) # watch if configured ...
KeyboardInterrupt
dataset/ETHPy150Open amorton/cassback/cassback/subcommands/backup_subcommand.py/WatchdogWatcher.start
4,033
def get_fields(obj): try: return obj._meta.fields except __HOLE__: return []
AttributeError
dataset/ETHPy150Open davedash/django-fixture-magic/fixture_magic/utils.py/get_fields
4,034
def create(self, req, body): """Creates an aggregate, given its name and optional availability zone. """ context = _get_context(req) authorize(context) if len(body) != 1: raise exc.HTTPBadRequest() try: host_aggregate = body["aggregate"] ...
KeyError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/api/openstack/compute/legacy_v2/contrib/aggregates.py/AggregateController.create
4,035
def update(self, req, id, body): """Updates the name and/or availability_zone of given aggregate.""" context = _get_context(req) authorize(context) if len(body) != 1: raise exc.HTTPBadRequest() try: updates = body["aggregate"] except __HOLE__: ...
KeyError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/api/openstack/compute/legacy_v2/contrib/aggregates.py/AggregateController.update
4,036
def _set_metadata(self, req, id, body): """Replaces the aggregate's existing metadata with new metadata.""" context = _get_context(req) authorize(context) if len(body) != 1: raise exc.HTTPBadRequest() try: metadata = body["metadata"] except __HOLE...
KeyError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/api/openstack/compute/legacy_v2/contrib/aggregates.py/AggregateController._set_metadata
4,037
def _doClone(self, source, cloneSource, branch, repo, dbLog): args = ('git', 'ls-remote', cloneSource, branch) output = check_output(args, cwd=repo, stderr=DEVNULL) if len(output) == 0: syslog(LOG_WARNING, "No branch '%s' in '%s'" % (branch, source)) return [] # For Git versions <1.9 clone of a shallow r...
TypeError
dataset/ETHPy150Open seoester/Git-Deployment-Handler/gitdh/modules/external.py/External._doClone
4,038
def __enter__(self): matchObj = SSHEnvironment.gitSshUrlPattern.match(self.source) if matchObj is None: self.isSshUrl = False return None self.isSshUrl = True sshUser = matchObj.group('user') sshHost = matchObj.group('host') sshPort = matchObj.group('port') sshRepositoryPath = matchObj.group('rep...
TypeError
dataset/ETHPy150Open seoester/Git-Deployment-Handler/gitdh/modules/external.py/SSHEnvironment.__enter__
4,039
def _getFileNums(self): base = self.base confFileNums = [] for f in os.listdir(self.dir): if f[:len(base)] == base: try: confFileNums.append(int(f[len(base):])) except __HOLE__: pass confFileNums.sort() return confFileNums
ValueError
dataset/ETHPy150Open seoester/Git-Deployment-Handler/gitdh/modules/external.py/TmpOrigFile._getFileNums
4,040
def run(self): s = self.source t = self.target cs = self.chunk_size ccm = self.chunk_count_max kr = self.keep_reading da = self.data_added go = self.go try: b = s.read(cs) except __HOLE__: b = '' while b and go.is_...
ValueError
dataset/ETHPy150Open codeinn/vcs/vcs/subprocessio.py/InputStreamChunker.run
4,041
def close(self): try: self.worker.stop() self.throw(GeneratorExit) except (GeneratorExit, __HOLE__): pass
StopIteration
dataset/ETHPy150Open codeinn/vcs/vcs/subprocessio.py/BufferedGenerator.close
4,042
def __exists(self, path): """Return True if the remote path exists """ try: self.__sftp.stat(path) except __HOLE__, e: if e.errno == errno.ENOENT: return False raise else: return True
IOError
dataset/ETHPy150Open saga-project/BigJob/pilot/filemanagement/globusonline_adaptor.py/GlobusOnlineFileAdaptor.__exists
4,043
def path(self, name): try: path = safe_join(getattr(settings, 'MEDIA_ROOT'), name) except __HOLE__: raise SuspiciousOperation( "Attempted access to '%s' denied." % name) return os.path.normpath(path)
ValueError
dataset/ETHPy150Open treeio/treeio/treeio/documents/files.py/FileStorage.path
4,044
def _edit_task_config(env, task_config, confirm): """ Launches text editor to edit provided task configuration file. `env` Runtime ``Environment`` instance. `task_config` Path to task configuration file. `confirm` If task config is invalid after edit, pr...
KeyboardInterrupt
dataset/ETHPy150Open xtrementl/focus/focus/plugin/modules/tasks.py/_edit_task_config
4,045
def execute(self, env, args): """ Removes a task. `env` Runtime ``Environment`` instance. `args` Arguments object from arg parser. """ # extract args task_name = args.task_name force = args.force if env.task.a...
KeyboardInterrupt
dataset/ETHPy150Open xtrementl/focus/focus/plugin/modules/tasks.py/TaskRemove.execute
4,046
def get(self, key, default=None): """Returns an item from the template context, if it doesn't exist `default` is returned. """ try: return self[key] except __HOLE__: return default
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/jinja2-2.6/jinja2/runtime.py/Context.get
4,047
@internalcode def call(__self, __obj, *args, **kwargs): """Call the callable with the arguments and keyword arguments provided but inject the active context or environment as first argument if the callable is a :func:`contextfunction` or :func:`environmentfunction`. """ ...
StopIteration
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/jinja2-2.6/jinja2/runtime.py/Context.call
4,048
def __init__(self, iterable, recurse=None): self._iterator = iter(iterable) self._recurse = recurse self.index0 = -1 # try to get the length of the iterable early. This must be done # here because there are some broken iterators around where there # __len__ is the numbe...
TypeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/jinja2-2.6/jinja2/runtime.py/LoopContext.__init__
4,049
@internalcode def __call__(self, *args, **kwargs): # try to consume the positional arguments arguments = list(args[:self._argument_count]) off = len(arguments) # if the number of arguments consumed is not the number of # arguments expected we start filling in keyword argumen...
IndexError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/jinja2-2.6/jinja2/runtime.py/Macro.__call__
4,050
def restore(self, fileContents, root, target, journal=None, sha1 = None, nameLookup=True, **kwargs): keepTempfile = kwargs.get('keepTempfile', False) destTarget = target if fileContents is not None: # this is first to let us copy the contents of a file #...
OSError
dataset/ETHPy150Open sassoftware/conary/conary/files.py/RegularFile.restore
4,051
def FileFromFilesystem(path, pathId, possibleMatch = None, inodeInfo = False, assumeRoot=False, statBuf=None, sha1FailOk=False): if statBuf: s = statBuf else: s = os.lstat(path) global userCache, groupCache, _havePrelink if assumeRoot: owner = 'root' group = 'ro...
KeyError
dataset/ETHPy150Open sassoftware/conary/conary/files.py/FileFromFilesystem
4,052
def lookupName(self, root, name): theId = self.nameCache.get(name, None) if theId is not None: return theId # if not root, cannot chroot and so fall back to system ids getChrootIds = root and root != '/' and not os.getuid() if getChrootIds: if root[0] !=...
ValueError
dataset/ETHPy150Open sassoftware/conary/conary/files.py/UserGroupIdCache.lookupName
4,053
@classmethod def upload_app(cls, options): """Uploads the given App Engine application into AppScale. Args: options: A Namespace that has fields for each parameter that can be passed in via the command-line interface. Returns: A tuple containing the host and port where the application...
KeyError
dataset/ETHPy150Open AppScale/appscale-tools/lib/appscale_tools.py/AppScaleTools.upload_app
4,054
def determine_clipboard(): # Determine the OS/platform and set the copy() and paste() functions accordingly. if 'cygwin' in platform.system().lower(): return init_windows_clipboard(cygwin=True) if os.name == 'nt' or platform.system() == 'Windows': return init_windows_clipboard() if os.na...
ImportError
dataset/ETHPy150Open BergWerkGIS/QGIS-CKAN-Browser/CKAN-Browser/pyperclip/__init__.py/determine_clipboard
4,055
def getCurrentEntry(self): try: return self.ordering[self.currentIndex] except __HOLE__: # This happens when the diff is empty raise NoCurrentEntryError()
IndexError
dataset/ETHPy150Open facebookarchive/git-review/src/gitreview/review/__init__.py/Review.getCurrentEntry
4,056
def expandCommitName(self, name): # Split apart the commit name from any suffix commit_name, suffix = git.commit.split_rev_name(name) try: real_commit = self.commitAliases[commit_name] except __HOLE__: real_commit = commit_name return real_commit + suffi...
KeyError
dataset/ETHPy150Open facebookarchive/git-review/src/gitreview/review/__init__.py/Review.expandCommitName
4,057
def readRoot(self): result = None self.reset() # Get the header, make sure it's a valid file. if not is_stream_binary_plist(self.file): raise NotBinaryPlistException() self.file.seek(0) self.contents = self.file.read() if len(self.contents) < 32: ...
TypeError
dataset/ETHPy150Open pascalw/Airplayer/airplayer/lib/biplist/__init__.py/PlistReader.readRoot
4,058
def main(): """ main method """ # initialize parser usage = "usage: %prog [-u USER] [-p PASSWORD] [-t TITLE] [-s selection] url" parser = OptionParser(usage, version="%prog "+instapaperlib.__version__) parser.add_option("-u", "--user", action="store", dest="user", m...
IOError
dataset/ETHPy150Open mrtazz/InstapaperLibrary/bin/instapaper.py/main
4,059
def getJob(conn): """ Get the next available sandbox request and set its status to pending. """ cur = conn.execute("SELECT cocreate_sandboxrequest.id, cocreate_sandboxrequest.sandbox_id, cocreate_sandboxrequest.requested_by_id, cocreate_sandboxrequest.sandbox_name, cocreate_sandboxtemplate.recipe FROM c...
TypeError
dataset/ETHPy150Open ngageoint/cocreate/ccl-cookbook/files/default/cocreatelite/cocreate/worker.py/getJob
4,060
def updateProgress(request_id, percent_complete, message, url=None): """ Update the progress of the sandbox request in the database. """ cur = conn.execute("SELECT sandbox_id, sandbox_name, requested_by_id FROM cocreate_sandboxrequest WHERE id = ?", (request_id,)) try: sandbox_id, sandbo...
TypeError
dataset/ETHPy150Open ngageoint/cocreate/ccl-cookbook/files/default/cocreatelite/cocreate/worker.py/updateProgress
4,061
def celery_check(): try: from celery import Celery from django.conf import settings app = Celery() app.config_from_object(settings) i = app.control.inspect() ping = i.ping() if not ping: chk = (False, 'No running Celery workers were found.') ...
IOError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/hqwebapp/views.py/celery_check
4,062
def redis_check(): try: redis = cache.caches['redis'] result = redis.set('serverup_check_key', 'test') except (InvalidCacheBackendError, __HOLE__): result = True # redis not in use, ignore except: result = False return (result, None)
ValueError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/hqwebapp/views.py/redis_check
4,063
@require_GET def redirect_to_default(req, domain=None): if not req.user.is_authenticated(): if domain != None: url = reverse('domain_login', args=[domain]) else: if settings.ENABLE_PRELOGIN_SITE: try: from corehq.apps.prelogin.views import ...
ImportError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/hqwebapp/views.py/redirect_to_default
4,064
def _safe_escape(self, expression, default): try: return expression() except __HOLE__: return default
ValueError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/hqwebapp/views.py/CRUDPaginatedViewMixin._safe_escape
4,065
@property def item_id(self): try: return self.parameters['itemId'] except __HOLE__: raise PaginatedItemException(_("The item's ID was not passed to the server."))
KeyError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/hqwebapp/views.py/CRUDPaginatedViewMixin.item_id
4,066
def main(args): usage = "usage: %prog [options] <html directory>" parser = op.OptionParser(usage=usage) parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Provides verbose output") opts, args = parser.parse_args(args) try: path = args...
IndexError
dataset/ETHPy150Open benoitc/dj-webmachine/doc/sphinxtogithub.py/main
4,067
def _on_connection_socket_select(self, fd): try: conn = self.connections[fd] except __HOLE__: # fd could have already been removed if the other end of the socket closed # and was handled before fd. fd has already been handled so # move along re...
KeyError
dataset/ETHPy150Open google/nogotofail/nogotofail/mitm/connection/server.py/Server._on_connection_socket_select
4,068
def wait(self): """Wait until all servers have completed running.""" try: self._server.wait() except __HOLE__: pass
KeyboardInterrupt
dataset/ETHPy150Open openstack/neutron/neutron/wsgi.py/Server.wait
4,069
def get_body_serializer(self, content_type): try: return self.body_serializers[content_type] except (KeyError, __HOLE__): raise exception.InvalidContentType(content_type=content_type)
TypeError
dataset/ETHPy150Open openstack/neutron/neutron/wsgi.py/ResponseSerializer.get_body_serializer
4,070
def _from_json(self, datastring): try: return jsonutils.loads(datastring) except __HOLE__: msg = _("Cannot understand JSON") raise n_exc.MalformedRequestBody(reason=msg)
ValueError
dataset/ETHPy150Open openstack/neutron/neutron/wsgi.py/JSONDeserializer._from_json
4,071
def get_body_deserializer(self, content_type): try: return self.body_deserializers[content_type] except (__HOLE__, TypeError): raise exception.InvalidContentType(content_type=content_type)
KeyError
dataset/ETHPy150Open openstack/neutron/neutron/wsgi.py/RequestDeserializer.get_body_deserializer
4,072
def get_action_args(self, request_environment): """Parse dictionary created by routes library.""" try: args = request_environment['wsgiorg.routing_args'][1].copy() except Exception: return {} try: del args['controller'] except __HOLE__: ...
KeyError
dataset/ETHPy150Open openstack/neutron/neutron/wsgi.py/RequestDeserializer.get_action_args
4,073
@webob.dec.wsgify(RequestClass=Request) def __call__(self, request): """WSGI method that controls (de)serialization and method dispatch.""" LOG.info(_LI("%(method)s %(url)s"), {"method": request.method, "url": request.url}) try: action, args, accept = self.dese...
AttributeError
dataset/ETHPy150Open openstack/neutron/neutron/wsgi.py/Resource.__call__
4,074
def dispatch(self, request, action, action_args): """Find action-specific method on controller and call it.""" controller_method = getattr(self.controller, action) try: #NOTE(salvatore-orlando): the controller method must have # an argument whose name is 'request' ...
TypeError
dataset/ETHPy150Open openstack/neutron/neutron/wsgi.py/Resource.dispatch
4,075
def refreshHistory(self): output = '' for line in self.history: try: output += self.lineFilter( *line ) except __HOLE__: pass self.bufferLength = len(output) cmd = 'scrollField -e -text \"%s\" "%s";' % ( output, self.name ) self.executeComm...
TypeError
dataset/ETHPy150Open CountZer0/PipelineConstructionSet/python/maya/site-packages/pymel-1.0.3/pymel/tools/scriptEditor/pymelScrollFieldReporter.py/Reporter.refreshHistory
4,076
def cmdCallback( nativeMsg, messageType, data ): global callbackState #outputFile = open( '/var/tmp/commandOutput', 'a') #outputFile.write( '============\n%s\n%s %s, length %s \n' % (nativeMsg, messageType, callbackState, len(nativeMsg)) ) #outputFile.close() if callbackState == 'ignoreCommand':...
KeyError
dataset/ETHPy150Open CountZer0/PipelineConstructionSet/python/maya/site-packages/pymel-1.0.3/pymel/tools/scriptEditor/pymelScrollFieldReporter.py/cmdCallback
4,077
def run_cmd(dir, args, with_retcode=False, with_stderr=False, raise_error=False, input=None, env={}, run_bg=False, setup_askpass=False): # Check args if type(args) in [str, unicode]: args = [args] args = [str(a) for a in args] # Check directory if not os.path.isdir(dir): raise GitEr...
OSError
dataset/ETHPy150Open gyim/stupidgit/stupidgit_gui/git.py/run_cmd
4,078
def __init__(self, repodir, name='Main module', parent=None): self.name = name self.parent = parent # Search for .git directory in repodir ancestors repodir = os.path.abspath(repodir) try: if parent: if not os.path.isdir(os.path.join(repodir, '.git'))...
OSError
dataset/ETHPy150Open gyim/stupidgit/stupidgit_gui/git.py/Repository.__init__
4,079
def load_refs(self): self.refs = {} self.branches = {} self.remote_branches = {} self.tags = {} # HEAD, current branch self.head = self.run_cmd(['rev-parse', 'HEAD']).strip() self.current_branch = None try: f = open(os.path.join(self.dir, '.gi...
OSError
dataset/ETHPy150Open gyim/stupidgit/stupidgit_gui/git.py/Repository.load_refs
4,080
def commit(self, author_name, author_email, msg, amend=False): if amend: # Get details of current HEAD is_merge_resolve = False output = self.run_cmd(['log', '-1', '--pretty=format:%P%n%an%n%ae%n%aD']) if not output.strip(): raise GitError, "Canno...
OSError
dataset/ETHPy150Open gyim/stupidgit/stupidgit_gui/git.py/Repository.commit
4,081
def update_head(self, content): try: f = open(os.path.join(self.dir, '.git', 'HEAD'), 'w') f.write(content) f.close() except __HOLE__: raise GitError, "Write error:\nCannot write into .git/HEAD"
OSError
dataset/ETHPy150Open gyim/stupidgit/stupidgit_gui/git.py/Repository.update_head
4,082
def diff_for_untracked_file(filename): # Start "diff" text diff_text = 'New file: %s\n' % filename # Detect whether file is binary if is_binary_file(filename): diff_text += "@@ File is binary.\n\n" else: # Text file => show lines newfile_text = '' try: f ...
OSError
dataset/ETHPy150Open gyim/stupidgit/stupidgit_gui/git.py/diff_for_untracked_file
4,083
def to_normalized(self, doc): # make the new dict actually contain real items normed = {} do_not_include = ['docID', 'doc', 'filetype', 'timestamps', 'source', 'versions', 'key'] for key, value in dict(doc).items(): if value and key not in do_not_include: try:...
TypeError
dataset/ETHPy150Open CenterForOpenScience/scrapi/scrapi/processing/cassandra.py/CassandraProcessor.to_normalized
4,084
def get(self, source, docID): documents = DocumentModel.objects(source=source, docID=docID) try: doc = documents[0] except __HOLE__: return None raw = self.to_raw(doc) normalized = self.to_normalized(doc) return DocumentTuple(raw, normalized)
IndexError
dataset/ETHPy150Open CenterForOpenScience/scrapi/scrapi/processing/cassandra.py/CassandraProcessor.get
4,085
def user_agent(): """Return a string representing the user agent.""" _implementation = platform.python_implementation() if _implementation == 'CPython': _implementation_version = platform.python_version() elif _implementation == 'PyPy': _implementation_version = '%s.%s.%s' % (sys.pypy_v...
IOError
dataset/ETHPy150Open GeekTrainer/Flask/Work/Trivia - Module 5/env/Lib/site-packages/pip/download.py/user_agent
4,086
def get_file_content(url, comes_from=None, session=None): """Gets the content of a file; it may be a filename, file: URL, or http: URL. Returns (location, content). Content is unicode.""" if session is None: session = PipSession() match = _scheme_re.search(url) if match: scheme = ...
IOError
dataset/ETHPy150Open GeekTrainer/Flask/Work/Trivia - Module 5/env/Lib/site-packages/pip/download.py/get_file_content
4,087
def _get_hash_from_file(target_file, link): try: download_hash = hashlib.new(link.hash_name) except (ValueError, __HOLE__): logger.warn("Unsupported hash name %s for package %s" % (link.hash_name, link)) return None fp = open(target_file, 'rb') while True: chunk = fp.rea...
TypeError
dataset/ETHPy150Open GeekTrainer/Flask/Work/Trivia - Module 5/env/Lib/site-packages/pip/download.py/_get_hash_from_file
4,088
def _download_url(resp, link, temp_location): fp = open(temp_location, 'wb') download_hash = None if link.hash and link.hash_name: try: download_hash = hashlib.new(link.hash_name) except ValueError: logger.warn("Unsupported hash name %s for package %s" % (link.hash_na...
ValueError
dataset/ETHPy150Open GeekTrainer/Flask/Work/Trivia - Module 5/env/Lib/site-packages/pip/download.py/_download_url
4,089
def import_module(name, required=True): """ Import module by name :param name: Module name :param required: If set to `True` and module was not found - will throw exception. If set to `False` and module was not found - will return None. Defaul...
ImportError
dataset/ETHPy150Open flask-admin/flask-admin/flask_admin/tools.py/import_module
4,090
def rec_getattr(obj, attr, default=None): """ Recursive getattr. :param attr: Dot delimited attribute name :param default: Default value Example:: rec_getattr(obj, 'a.b.c') """ try: return reduce(getattr, attr.split('.'), obj) ...
AttributeError
dataset/ETHPy150Open flask-admin/flask-admin/flask_admin/tools.py/rec_getattr
4,091
def cleanup(self): try: self.shutdown() self.server_close() except __HOLE__: pass logging.info('Stopped %s server. Total time processing requests: %dms', self.protocol, self.total_request_time)
KeyboardInterrupt
dataset/ETHPy150Open chromium/web-page-replay/httpproxy.py/HttpProxyServer.cleanup
4,092
def cleanup(self): try: self.shutdown() self.server_close() except __HOLE__: pass
KeyboardInterrupt
dataset/ETHPy150Open chromium/web-page-replay/httpproxy.py/HttpsProxyServer.cleanup
4,093
def __init__(self, var): self.var = var try: # django.template.base.Variable self.literal = self.var.literal except __HOLE__: # django.template.base.FilterExpression self.literal = self.var.token
AttributeError
dataset/ETHPy150Open ojii/django-classy-tags/classytags/values.py/StringValue.__init__
4,094
def clean(self, value): try: return int(value) except __HOLE__: return self.error(value, "clean")
ValueError
dataset/ETHPy150Open ojii/django-classy-tags/classytags/values.py/IntegerValue.clean
4,095
def _open(self, devpath, mode, max_speed, bit_order, bits_per_word, extra_flags): if not isinstance(devpath, str): raise TypeError("Invalid devpath type, should be string.") elif not isinstance(mode, int): raise TypeError("Invalid mode type, should be integer.") elif not ...
OSError
dataset/ETHPy150Open vsergeev/python-periphery/periphery/spi.py/SPI._open
4,096
def transfer(self, data): """Shift out `data` and return shifted in data. Args: data (bytes, bytearray, list): a byte array or list of 8-bit integers to shift out. Returns: bytes, bytearray, list: data shifted in. Raises: SPIError: if an I/O or OS e...
OSError
dataset/ETHPy150Open vsergeev/python-periphery/periphery/spi.py/SPI.transfer
4,097
def close(self): """Close the spidev SPI device. Raises: SPIError: if an I/O or OS error occurs. """ if self._fd is None: return try: os.close(self._fd) except __HOLE__ as e: raise SPIError(e.errno, "Closing SPI device: "...
OSError
dataset/ETHPy150Open vsergeev/python-periphery/periphery/spi.py/SPI.close
4,098
def _get_mode(self): buf = array.array('B', [0]) # Get mode try: fcntl.ioctl(self._fd, SPI._SPI_IOC_RD_MODE, buf, True) except __HOLE__ as e: raise SPIError(e.errno, "Getting SPI mode: " + e.strerror) return buf[0] & 0x3
OSError
dataset/ETHPy150Open vsergeev/python-periphery/periphery/spi.py/SPI._get_mode
4,099
def _set_mode(self, mode): if not isinstance(mode, int): raise TypeError("Invalid mode type, should be integer.") if mode not in [0, 1, 2, 3]: raise ValueError("Invalid mode, can be 0, 1, 2, 3.") # Read-modify-write mode, because the mode contains bits for other settings...
OSError
dataset/ETHPy150Open vsergeev/python-periphery/periphery/spi.py/SPI._set_mode