Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
5,100
def has_c(): """Is the C extension installed?""" try: from pymongo import _cmessage return True except __HOLE__: return False
ImportError
dataset/ETHPy150Open mongodb/mongo-python-driver/pymongo/__init__.py/has_c
5,101
def get_queryset(self): """ Fixes get_query_set vs get_queryset for Django <1.6 """ try: qs = super(UserManager, self).get_queryset() except __HOLE__: # pragma: no cover qs = super(UserManager, self).get_query_set() return qs
AttributeError
dataset/ETHPy150Open mishbahr/django-users2/users/managers.py/UserManager.get_queryset
5,102
def testUnhashableKeys(self): try: a = {[1]:2} except TypeError: pass else: self.fail("list as dict key should raise TypeError") try: a = {{1:2}:3} except __HOLE__: pass else: self.fail("dict as dict...
TypeError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_dict_jy.py/DictInitTest.testUnhashableKeys
5,103
def get_objects(self): """ Returns a set of objects set for deletion. List of objects is retrived from a HTTP POST list called ``objects``. Returns ------- set Set of objects to delete """ try: return self._objs except AttributeEr...
AttributeError
dataset/ETHPy150Open thisissoon/Flask-Velox/flask_velox/mixins/sqla/delete.py/MultiDeleteObjectMixin.get_objects
5,104
def clean_rename_format(self): try: self.cleaned_data['rename_format'] % { 'original_filename': 'filename', 'original_basename': 'basename', 'original_extension': 'ext', 'current_filename': 'filename', 'current_basename'...
KeyError
dataset/ETHPy150Open divio/django-filer/filer/admin/forms.py/RenameFilesForm.clean_rename_format
5,105
def __contains__(self, item): """ Checks if the layer is inside the packet. :param item: name of the layer """ try: self[item] return True except __HOLE__: return False
KeyError
dataset/ETHPy150Open KimiNewt/pyshark/src/pyshark/packet/packet.py/Packet.__contains__
5,106
@property def sniff_time(self): try: timestamp = float(self.sniff_timestamp) except __HOLE__: # If the value after the decimal point is negative, discard it # Google: wireshark fractional second timestamp = float(self.sniff_timestamp.split(".")[0]) ...
ValueError
dataset/ETHPy150Open KimiNewt/pyshark/src/pyshark/packet/packet.py/Packet.sniff_time
5,107
def __contains__(self, key): try: self[key] return True except __HOLE__: return False
KeyError
dataset/ETHPy150Open brutasse/graphite-api/graphite_api/utils.py/RequestParams.__contains__
5,108
def get(self, key, default=None): try: return self[key] except __HOLE__: return default
KeyError
dataset/ETHPy150Open brutasse/graphite-api/graphite_api/utils.py/RequestParams.get
5,109
def _handle_server(self): server = self._server_socket data, r_addr = server.recvfrom(BUF_SIZE) if not data: logging.debug('UDP handle_server: data is empty') if self._stat_callback: self._stat_callback(self._listen_port, len(data)) if self._is_local: ...
IOError
dataset/ETHPy150Open ziggear/shadowsocks/shadowsocks/udprelay.py/UDPRelay._handle_server
5,110
def with_errorcheck_client(*features): def inner(f): def run(): try: return with_client(*features, connected=False)(f)() except __HOLE__ as e: assert False, e run.__name__ = f.__name__ return run return inner
TypeError
dataset/ETHPy150Open Shizmob/pydle/tests/test_featurize.py/with_errorcheck_client
5,111
def __init__(self, *args, **kwds): '''Initialize an ordered dictionary. Signature is the same as for regular dictionaries, but keyword arguments are not recommended because their insertion order is arbitrary. ''' if len(args) > 1: raise T...
AttributeError
dataset/ETHPy150Open xraypy/xraylarch/doc/sphinx/ext/backports.py/OrderedDict.__init__
5,112
def clear(self): 'od.clear() -> None. Remove all items from od.' try: for node in self.__map.itervalues(): del node[:] root = self.__root root[:] = [root, root, None] self.__map.clear() except __HOLE...
AttributeError
dataset/ETHPy150Open xraypy/xraylarch/doc/sphinx/ext/backports.py/OrderedDict.clear
5,113
def is_active(self, view_or_path): assert (isinstance(view_or_path, sublime.View) or isinstance(view_or_path, str)), "bad parameter" try: return is_active(view_or_path) except __HOLE__: return is_active_path(view_or_path)
AttributeError
dataset/ETHPy150Open guillermooo/dart-sublime-bundle/lib/analyzer/queue.py/AnalyzerQueue.is_active
5,114
def read_status(self): request = Connection() request.write_varint(0) # Request status self.connection.write_buffer(request) response = self.connection.read_buffer() if response.read_varint() != 0: raise IOError("Received invalid status response packet.") tr...
ValueError
dataset/ETHPy150Open Dinnerbone/mcstatus/mcstatus/pinger.py/ServerPinger.read_status
5,115
def tearDown(self): try: self.proxyServerFactory.protoInstance.transport.loseConnection() except __HOLE__: pass try: pi = self.proxyServerFactory.clientFactoryInstance.protoInstance pi.transport.loseConnection() except AttributeError: ...
AttributeError
dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/test/test_protocols.py/Portforwarding.tearDown
5,116
def close(self): for fd in self._fd_to_chan: try: self.poller.unregister(fd) except __HOLE__: pass self._channels.clear() self._fd_to_chan.clear() self.poller = None
KeyError
dataset/ETHPy150Open celery/kombu/kombu/transport/zmq.py/MultiChannelPoller.close
5,117
def __init__(self, uri='tcp://127.0.0.1', port=DEFAULT_PORT, hwm=DEFAULT_HWM, swap_size=None, enable_sink=True, context=None): try: scheme, parts = uri.split('://') except __HOLE__: scheme = 'tcp' parts = uri endpoints = parts...
ValueError
dataset/ETHPy150Open celery/kombu/kombu/transport/zmq.py/Client.__init__
5,118
def close(self): if not self.closed: self.connection.cycle.discard(self) try: self.__dict__['client'].close() except __HOLE__: pass super(Channel, self).close()
KeyError
dataset/ETHPy150Open celery/kombu/kombu/transport/zmq.py/Channel.close
5,119
def close_connection(self, connection): super(Transport, self).close_connection(connection) try: connection.__dict__['context'].term() except __HOLE__: pass
KeyError
dataset/ETHPy150Open celery/kombu/kombu/transport/zmq.py/Transport.close_connection
5,120
def handle_noargs(self, **kwargs): try: verbosity = int(kwargs['verbosity']) except (__HOLE__, TypeError, ValueError): verbosity = 1 feeds = Feed.objects.filter(approval_status=PENDING_FEED) to_email = [x.email for x in User.objects.filter(groups__name=settings.F...
KeyError
dataset/ETHPy150Open python/raspberryio/raspberryio/aggregator/management/commands/send_pending_approval_email.py/Command.handle_noargs
5,121
def _to_node(self, compute): try: state = self.NODE_STATE_MAP[compute.findtext("STATE")] except __HOLE__: state = NodeState.UNKNOWN networks = [] for element in compute.findall("NIC"): networks.append(element.attrib["ip"]) return Node(id=comp...
KeyError
dataset/ETHPy150Open cloudkick/libcloud/libcloud/compute/drivers/opennebula.py/OpenNebulaNodeDriver._to_node
5,122
def verifyCryptedPassword(crypted, pw): if crypted[0] == '$': # md5_crypt encrypted salt = '$1$' + crypted.split('$')[2] else: salt = crypted[:2] try: import crypt except __HOLE__: crypt = None if crypt is None: raise NotImplementedError("cred_unix not suppor...
ImportError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/plugins/cred_unix.py/verifyCryptedPassword
5,123
def checkPwd(self, pwd, username, password): try: cryptedPass = pwd.getpwnam(username)[1] except __HOLE__: return defer.fail(UnauthorizedLogin()) else: if cryptedPass in ('*', 'x'): # Allow checkSpwd to take over return None ...
KeyError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/plugins/cred_unix.py/UNIXChecker.checkPwd
5,124
def checkSpwd(self, spwd, username, password): try: cryptedPass = spwd.getspnam(username)[1] except __HOLE__: return defer.fail(UnauthorizedLogin()) else: if verifyCryptedPassword(cryptedPass, password): return defer.succeed(username)
KeyError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/plugins/cred_unix.py/UNIXChecker.checkSpwd
5,125
def requestAvatarId(self, credentials): username, password = credentials.username, credentials.password try: import pwd except __HOLE__: pwd = None if pwd is not None: checked = self.checkPwd(pwd, username, password) if checked is not Non...
ImportError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/plugins/cred_unix.py/UNIXChecker.requestAvatarId
5,126
@task def coverage(): """Run tests and show test coverage report.""" try: import pytest_cov # NOQA except __HOLE__: print_failure_message( 'Install the pytest coverage plugin to use this task, ' "i.e., `pip install pytest-cov'.") raise SystemExit(1) impor...
ImportError
dataset/ETHPy150Open calvinschmdt/EasyTensorflow/pavement.py/coverage
5,127
@task # NOQA def doc_watch(): """Watch for changes in the docs and rebuild HTML docs when changed.""" try: from watchdog.events import FileSystemEventHandler from watchdog.observers import Observer except ImportError: print_failure_message('Install the watchdog package to use this t...
KeyboardInterrupt
dataset/ETHPy150Open calvinschmdt/EasyTensorflow/pavement.py/doc_watch
5,128
def visit_field(self, node): # Remove the field from the tree. node.parent.remove(node) # Extract the field name & optional argument tag = node[0].astext().split(None, 1) tagname = tag[0] if len(tag)>1: arg = tag[1] else: arg = None # Handle special fiel...
ValueError
dataset/ETHPy150Open CollabQ/CollabQ/vendor/epydoc/markup/restructuredtext.py/_SplitFieldsTranslator.visit_field
5,129
def write_outstream(stream, *text): encoding = getattr(stream, 'encoding', 'ascii') or 'ascii' for t in text: if not isinstance(t, binary_type): t = t.encode(encoding, 'replace') t = t.decode(encoding) try: stream.write(t) except __HOLE__: # su...
IOError
dataset/ETHPy150Open goFrendiAsgard/kokoropy/kokoropy/packages/alembic/util.py/write_outstream
5,130
def shapeup(self, ob): if isinstance(ob, BaseGeometry): return ob else: try: return asShape(ob) except __HOLE__: return asLineString(ob)
ValueError
dataset/ETHPy150Open Toblerity/Shapely/shapely/ops.py/CollectionOperator.shapeup
5,131
def polygonize(self, lines): """Creates polygons from a source of lines The source may be a MultiLineString, a sequence of LineString objects, or a sequence of objects than can be adapted to LineStrings. """ source = getattr(lines, 'geoms', None) or lines try: ...
TypeError
dataset/ETHPy150Open Toblerity/Shapely/shapely/ops.py/CollectionOperator.polygonize
5,132
def polygonize_full(self, lines): """Creates polygons from a source of lines, returning the polygons and leftover geometries. The source may be a MultiLineString, a sequence of LineString objects, or a sequence of objects than can be adapted to LineStrings. Returns a tuple of o...
TypeError
dataset/ETHPy150Open Toblerity/Shapely/shapely/ops.py/CollectionOperator.polygonize_full
5,133
def linemerge(self, lines): """Merges all connected lines from a source The source may be a MultiLineString, a sequence of LineString objects, or a sequence of objects than can be adapted to LineStrings. Returns a LineString or MultiLineString when lines are not contiguous. """...
AttributeError
dataset/ETHPy150Open Toblerity/Shapely/shapely/ops.py/CollectionOperator.linemerge
5,134
def cascaded_union(self, geoms): """Returns the union of a sequence of geometries This is the most efficient method of dissolving many polygons. """ try: L = len(geoms) except __HOLE__: geoms = [geoms] L = 1 subs = (c_void_p * L)() ...
TypeError
dataset/ETHPy150Open Toblerity/Shapely/shapely/ops.py/CollectionOperator.cascaded_union
5,135
def unary_union(self, geoms): """Returns the union of a sequence of geometries This method replaces :meth:`cascaded_union` as the prefered method for dissolving many polygons. """ try: L = len(geoms) except __HOLE__: geoms = [geoms] L...
TypeError
dataset/ETHPy150Open Toblerity/Shapely/shapely/ops.py/CollectionOperator.unary_union
5,136
def transform(func, geom): """Applies `func` to all coordinates of `geom` and returns a new geometry of the same type from the transformed coordinates. `func` maps x, y, and optionally z to output xp, yp, zp. The input parameters may iterable types like lists or arrays or single values. The output ...
TypeError
dataset/ETHPy150Open Toblerity/Shapely/shapely/ops.py/transform
5,137
def main(): p = OptionParser(usage=__doc__.strip()) p.add_option("--clean", "-c", action="store_true", help="clean source directory") options, args = p.parse_args() if not args: p.error('no submodules given') else: dirs = ['numpy/%s' % x for x in map(os.path.basenam...
OSError
dataset/ETHPy150Open cournape/Bento/bento/private/_yaku/tools/py3tool.py/main
5,138
def sync_2to3(src, dst, patchfile=None, clean=False): import lib2to3.main from io import StringIO to_convert = [] for src_dir, dst_dir, dirs, files in walk_sync(src, dst): for fn in dirs + files: src_fn = os.path.join(src_dir, fn) dst_fn = os.path.join(dst_dir, fn) ...
OSError
dataset/ETHPy150Open cournape/Bento/bento/private/_yaku/tools/py3tool.py/sync_2to3
5,139
@register.tag def gravatar_url(parser, token): try: tag_name, email = token.split_contents() except __HOLE__: raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0] return GravatarUrlNode(email)
ValueError
dataset/ETHPy150Open darcyliu/storyboard/home/templatetags/filter.py/gravatar_url
5,140
@register.filter(name='limit') def limit(value, arg): """ Returns a slice of the list. Uses the same syntax as Python's list slicing; see http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice for an introduction. """ try: bits = [] for x in arg.spl...
TypeError
dataset/ETHPy150Open darcyliu/storyboard/home/templatetags/filter.py/limit
5,141
def _cursor(self): cursor = None if not self._valid_connection(): conn_string = convert_unicode(self._connect_string()) self.connection = Database.connect(conn_string, **self.settings_dict['DATABASE_OPTIONS']) cursor = FormatStylePlaceholderCursor(self.connection) ...
ValueError
dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/db/backends/oracle/base.py/DatabaseWrapper._cursor
5,142
def executemany(self, query, params=None): try: args = [(':arg%d' % i) for i in range(len(params[0]))] except (IndexError, __HOLE__): # No params given, nothing to do return None # cx_Oracle wants no trailing ';' for SQL statements. For PL/SQL, it # i...
TypeError
dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/db/backends/oracle/base.py/FormatStylePlaceholderCursor.executemany
5,143
def init_thrift_server(self, socket, processor): """ Creates a thrift server that listens in the given socket and uses the given processor """ try: os.unlink(socket) except __HOLE__ as oerr: if oerr.errno != errno.ENOENT: raise ...
OSError
dataset/ETHPy150Open alticelabs/meocloud-cli/meocloud/client/linux/thrift_utils.py/ThriftListener.init_thrift_server
5,144
def __getattr__(self, identifier): """ Allows creating sub OptionTree instances using attribute access, inheriting the group options. """ try: return super(AttrTree, self).__getattr__(identifier) except __HOLE__: pass if identifier.startswith('_'): ...
AttributeError
dataset/ETHPy150Open ioam/holoviews/holoviews/core/options.py/OptionTree.__getattr__
5,145
def _IsProcessRunnable(name): try: with open(os.devnull, 'w') as devnull: found = subprocess.call(['/usr/bin/which', name], stdout=devnull, stderr=devnull) == 0 return True except __HOLE__: return False
OSError
dataset/ETHPy150Open natduca/quickopen/src/find_based_db_indexer.py/_IsProcessRunnable
5,146
def extract_features(self, text): '''Extracts features from a body of text. :rtype: dictionary of features ''' # Feature extractor may take one or two arguments try: return self.feature_extractor(text, self.train_set) except (__HOLE__, AttributeError): ...
TypeError
dataset/ETHPy150Open sloria/TextBlob/textblob/classifiers.py/BaseClassifier.extract_features
5,147
@cached_property def classifier(self): """The classifier.""" try: return self.train() except __HOLE__: # nltk_class has not been defined raise ValueError("NLTKClassifier must have a nltk_class" " variable that is not None.")
AttributeError
dataset/ETHPy150Open sloria/TextBlob/textblob/classifiers.py/NLTKClassifier.classifier
5,148
def train(self, *args, **kwargs): """Train the classifier with a labeled feature set and return the classifier. Takes the same arguments as the wrapped NLTK class. This method is implicitly called when calling ``classify`` or ``accuracy`` methods and is included only to allow passing in ...
AttributeError
dataset/ETHPy150Open sloria/TextBlob/textblob/classifiers.py/NLTKClassifier.train
5,149
def update(self, new_data, *args, **kwargs): """Update the classifier with new training data and re-trains the classifier. :param new_data: New data as a list of tuples of the form ``(text, label)``. """ self.train_set += new_data self.train_features = [(self...
AttributeError
dataset/ETHPy150Open sloria/TextBlob/textblob/classifiers.py/NLTKClassifier.update
5,150
def _get_live_streams(self, params, swf_url): for key, quality in QUALITY_MAP.items(): key_url = "{0}URL".format(key) url = params.get(key_url) if not url: continue try: res = http.get(url, exception=IOError) except __...
IOError
dataset/ETHPy150Open chrippa/livestreamer/src/livestreamer/plugins/dailymotion.py/DailyMotion._get_live_streams
5,151
def check_xml_line_by_line(test_case, expected, actual): """Does what it's called, hopefully parameters are self-explanatory""" # this is totally wacky, but elementtree strips needless # whitespace that mindom will preserve in the original string parser = etree.XMLParser(remove_blank_text=True) pars...
AssertionError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/ex-submodules/casexml/apps/case/tests/util.py/check_xml_line_by_line
5,152
def normalize_asg_success(success): count = "1" duration = "PT15M" # if it's falsy, return defaults if not success: return [count, duration] # if it's int, use as instance count if isinstance(success, int): return [str(success), duration] try: # try to parse as int...
ValueError
dataset/ETHPy150Open zalando-stups/senza/senza/components/auto_scaling_group.py/normalize_asg_success
5,153
def normalize_network_threshold(threshold): unit = "Bytes" if threshold is None: return [] if isinstance(threshold, int): return [str(threshold), unit] amount = 1024 shortcuts = { "B": "Bytes", "KB": "Kilobytes", "MB": "Megabytes", "GB": "Gigabytes", ...
ValueError
dataset/ETHPy150Open zalando-stups/senza/senza/components/auto_scaling_group.py/normalize_network_threshold
5,154
def create(self, validated_data): request = self.context['request'] user = request.user auth = Auth(user) node = self.context['view'].get_node() target_node_id = validated_data['_id'] pointer_node = Node.load(target_node_id) if not pointer_node or pointer_node.is_...
ValueError
dataset/ETHPy150Open CenterForOpenScience/osf.io/api/nodes/serializers.py/NodeLinksSerializer.create
5,155
def run(self, result=None): orig_result = result if result is None: result = self.defaultTestResult() startTestRun = getattr(result, 'startTestRun', None) if startTestRun is not None: startTestRun() self._resultForDoCleanups = result ...
KeyboardInterrupt
dataset/ETHPy150Open randy3k/UnitTesting/unittesting/core/st3/case.py/DeferrableTestCase.run
5,156
def test_gevent_version(self): try: import gevent except __HOLE__: raise SkipTest('gevent not available.') env_version = os.environ.get('GEVENT_VERSION') if env_version: self.assertEqual(env_version, gevent.__version__)
ImportError
dataset/ETHPy150Open python-zk/kazoo/kazoo/tests/test_build.py/TestBuildEnvironment.test_gevent_version
5,157
def assertSubscriptionInTopic(self, subscription, topic_name): ret = self.run_function( 'boto_sns.get_all_subscriptions_by_topic', name=topic_name ) for _subscription in ret: try: self.assertDictContainsSubset(subscription, _subscription) ...
AssertionError
dataset/ETHPy150Open saltstack/salt/tests/integration/states/boto_sns.py/BotoSNSTest.assertSubscriptionInTopic
5,158
def ignore_not_implemented(func): def _inner(*args, **kwargs): try: return func(*args, **kwargs) except __HOLE__: return None update_wrapper(_inner, func) return _inner
NotImplementedError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/tests/regressiontests/introspection/tests.py/ignore_not_implemented
5,159
def render_GET(self, request): if self.representation is None: # we haven't been given a representation yet request.setResponseCode(500) return 'Resource has not yet been created/updated.' # check for if-modified-since header, and send 304 back if it is not been mod...
ValueError
dataset/ETHPy150Open NORDUnet/opennsa/opennsa/shared/modifiableresource.py/ModifiableResource.render_GET
5,160
def _RegistryQuery(key, value=None): r"""Use reg.exe to read a particular key through _RegistryQueryBase. First tries to launch from %WinDir%\Sysnative to avoid WoW64 redirection. If that fails, it falls back to System32. Sysnative is available on Vista and up and available on Windows Server 2003 and XP throu...
OSError
dataset/ETHPy150Open adblockplus/gyp/pylib/gyp/MSVSVersion.py/_RegistryQuery
5,161
def _RegistryGetValue(key, value): """Use _winreg or reg.exe to obtain the value of a registry key. Using _winreg is preferable because it solves an issue on some corporate environments where access to reg.exe is locked down. However, we still need to fallback to reg.exe for the case where the _winreg module i...
ImportError
dataset/ETHPy150Open adblockplus/gyp/pylib/gyp/MSVSVersion.py/_RegistryGetValue
5,162
def clean(self, value): if isinstance(value, decimal.Decimal): # Value is already an integer. return value if isinstance(value, six.string_types): # Strip the string of whitespace value = value.strip() if not value: # Value is nothing...
ValueError
dataset/ETHPy150Open armet/python-armet/armet/attributes/decimal.py/DecimalAttribute.clean
5,163
def test_custom_type_mongotype_dict_index_not_checked(self): class CustomObject(CustomType): mongo_type = dict python_type = float def to_bson(self, value): return {'f':unicode(value)} def to_python(self, value): return float(value[...
ValueError
dataset/ETHPy150Open namlook/mongokit/tests/test_custom_types.py/CustomTypesTestCase.test_custom_type_mongotype_dict_index_not_checked
5,164
@property def num_prev(self): try: return int(self.request.GET.get('num_prev')) except (__HOLE__, TypeError): pass return 12
ValueError
dataset/ETHPy150Open dimagi/commcare-hq/custom/_legacy/mvp/reports/va.py/VerbalAutopsyReport.num_prev
5,165
@property def current_month(self): try: return dateutil.parser.parse(self.request.GET.get('current_month')) except (__HOLE__, ValueError): pass
AttributeError
dataset/ETHPy150Open dimagi/commcare-hq/custom/_legacy/mvp/reports/va.py/VerbalAutopsyReport.current_month
5,166
@property def report_context(self): report_matrix = [] month_headers = None for category_group in self.indicator_slugs: category_indicators = [] total_rowspan = 0 for slug in category_group['indicator_slugs']: try: indic...
AttributeError
dataset/ETHPy150Open dimagi/commcare-hq/custom/_legacy/mvp/reports/va.py/VerbalAutopsyReport.report_context
5,167
def norm(x, ord=None, axis=None): """ Norm of a sparse matrix This function is able to return one of seven different matrix norms, depending on the value of the ``ord`` parameter. Parameters ---------- x : a sparse matrix Input sparse matrix. ord : {non-zero int, inf, -inf, 'fr...
TypeError
dataset/ETHPy150Open scipy/scipy/scipy/sparse/linalg/_norm.py/norm
5,168
def __init__(self, userdict): self.username = userdict["username"] self.password = userdict["password"] self.access = {} for realm, level in userdict.get("access", {}).items(): try: self.access[realm] = LEVELS.index(level) except __HOLE__: ...
ValueError
dataset/ETHPy150Open marchon/Flask-API-Server/apiserver/authentication.py/User.__init__
5,169
def test_support(file_list, source_tag): events = { 'MediaStarted': 0, 'MediaEnded': 0, 'MediaCompleted': 0, 'MediaFailed': 0, 'MediaQualityChange': 0, 'MediaQualityChangeAuto': 0, 'MediaQualityChangeProgramatically': 0, 'MediaInitialBufferStart': 0, ...
IOError
dataset/ETHPy150Open pbs/agora-proc/tests/goonhilly_support.py/test_support
5,170
def search_noteitems(self, search_object): for nw in self.all_items: if not search_object.search_notemodel(nw.notemodel): nw.setHidden(True) else: nw.setHidden(False) try: self.setCurrentItem(self.all_visible_items[0]) retur...
IndexError
dataset/ETHPy150Open akehrer/Motome/Motome/Models/NoteListWidget.py/NoteListWidget.search_noteitems
5,171
def get_config(path): try: with open(path) as f: data = f.read() except __HOLE__ as e: if e.errno == errno.ENOENT: data = None else: raise e if data is None: return {} else: # assume config is a dict return yaml.safe_lo...
IOError
dataset/ETHPy150Open rcbops/rpc-openstack/scripts/update-yaml.py/get_config
5,172
def __place_template_folder(group, src, dst, gbp=False): template_files = pkg_resources.resource_listdir(group, src) # For each template, place for template_file in template_files: if not gbp and os.path.basename(template_file) == 'gbp.conf.em': debug("Skipping template '{0}'".format(tem...
IOError
dataset/ETHPy150Open ros-infrastructure/bloom/bloom/generators/debian/generator.py/__place_template_folder
5,173
def get_package_from_branch(branch): with inbranch(branch): try: package_data = get_package_data(branch) except __HOLE__: return None if type(package_data) not in [list, tuple]: # It is a ret code DebianGenerator.exit(package_data) names, v...
SystemExit
dataset/ETHPy150Open ros-infrastructure/bloom/bloom/generators/debian/generator.py/get_package_from_branch
5,174
def _check_all_keys_are_valid(self, peer_packages): keys_to_resolve = [] key_to_packages_which_depends_on = collections.defaultdict(list) keys_to_ignore = set() for package in self.packages.values(): depends = package.run_depends + package.buildtool_export_depends ...
RuntimeError
dataset/ETHPy150Open ros-infrastructure/bloom/bloom/generators/debian/generator.py/DebianGenerator._check_all_keys_are_valid
5,175
def pre_modify(self): info("\nPre-verifying Debian dependency keys...") # Run rosdep update is needed if not self.has_run_rosdep: self.update_rosdep() peer_packages = [p.name for p in self.packages.values()] while not self._check_all_keys_are_valid(peer_packages): ...
KeyboardInterrupt
dataset/ETHPy150Open ros-infrastructure/bloom/bloom/generators/debian/generator.py/DebianGenerator.pre_modify
5,176
def __init__(self, to, chained_field=None, chained_model_field=None, auto_choose=False, **kwargs): """ examples: class Publication(models.Model): name = models.CharField(max_length=255) class Writer(models.Model): name = models.CharField(max_len...
NameError
dataset/ETHPy150Open digi604/django-smart-selects/smart_selects/db_fields.py/ChainedManyToManyField.__init__
5,177
def __getattr__(self, name): # I only over-ride portions of the os module try: return object.__getattr__(self, name) except __HOLE__: return getattr(os, name)
AttributeError
dataset/ETHPy150Open openstack/swift/test/unit/common/test_manager.py/MockOs.__getattr__
5,178
def test_setup_env(self): class MockResource(object): def __init__(self, error=None): self.error = error self.called_with_args = [] def setrlimit(self, resource, limits): if self.error: raise self.error ...
AttributeError
dataset/ETHPy150Open openstack/swift/test/unit/common/test_manager.py/TestManagerModule.test_setup_env
5,179
def test_watch_server_pids(self): class MockOs(object): WNOHANG = os.WNOHANG def __init__(self, pid_map=None): if pid_map is None: pid_map = {} self.pid_map = {} for pid, v in pid_map.items(): self.p...
StopIteration
dataset/ETHPy150Open openstack/swift/test/unit/common/test_manager.py/TestManagerModule.test_watch_server_pids
5,180
def test_wait(self): server = manager.Server('test') self.assertEqual(server.wait(), 0) class MockProcess(threading.Thread): def __init__(self, delay=0.1, fail_to_start=False): threading.Thread.__init__(self) # setup pipe rfd, wfd = os...
OSError
dataset/ETHPy150Open openstack/swift/test/unit/common/test_manager.py/TestServer.test_wait
5,181
def main(): args = docopt.docopt('\n'.join(__doc__.split('\n')[2:]), version=const.VERSION) logging.basicConfig( level=logging.DEBUG if args['--verbose'] else logging.INFO, stream=sys.stdout, ) connect_conf = config.new_context_from_file(args['--config-file'], ...
ValueError
dataset/ETHPy150Open Gentux/imap-cli/imap_cli/list_mail.py/main
5,182
def connect(self, username, password): # Try to use oauth2 first. It's much safer try: self._connect_oauth(username) except (TypeError, __HOLE__) as e: logger.warning("Couldn't do oauth2 because %s" % e) self.server = self.transport(self.hostname, self.port) ...
ValueError
dataset/ETHPy150Open coddingtonbear/django-mailbox/django_mailbox/transports/gmail.py/GmailImapTransport.connect
5,183
def _connect_oauth(self, username): # username should be an email address that has already been authorized # for gmail access try: from django_mailbox.google_utils import ( get_google_access_token, fetch_user_info, AccessTokenNotFound, ...
ImportError
dataset/ETHPy150Open coddingtonbear/django-mailbox/django_mailbox/transports/gmail.py/GmailImapTransport._connect_oauth
5,184
def format_currency(number, currency, format, locale=babel.numbers.LC_NUMERIC, force_frac=None, format_type='standard'): """Same as ``babel.numbers.format_currency``, but has ``force_frac`` argument instead of ``currency_digits``. If the ``force_frac`` argument is given, the argument is...
KeyError
dataset/ETHPy150Open Suor/django-easymoney/easymoney.py/format_currency
5,185
@staticmethod def load(collada, localscope, node): colornode = node.find( '%s/%s/%s'%(tag('technique_common'),tag('directional'), tag('color') ) ) if colornode is None: raise DaeIncompleteError('Missing color for directional light') try:...
ValueError
dataset/ETHPy150Open pycollada/pycollada/collada/light.py/DirectionalLight.load
5,186
@staticmethod def load(collada, localscope, node): colornode = node.find('%s/%s/%s' % (tag('technique_common'), tag('ambient'), tag('color'))) if colornode is None: raise DaeIncompleteError('Missing color for ambient light') try: color = tuple( [ float(v) ...
ValueError
dataset/ETHPy150Open pycollada/pycollada/collada/light.py/AmbientLight.load
5,187
@staticmethod def load(collada, localscope, node): pnode = node.find('%s/%s' % (tag('technique_common'), tag('point'))) colornode = pnode.find( tag('color') ) if colornode is None: raise DaeIncompleteError('Missing color for point light') try: color = tuple([f...
ValueError
dataset/ETHPy150Open pycollada/pycollada/collada/light.py/PointLight.load
5,188
@staticmethod def load(collada, localscope, node): pnode = node.find( '%s/%s'%(tag('technique_common'),tag('spot')) ) colornode = pnode.find( tag('color') ) if colornode is None: raise DaeIncompleteError('Missing color for spot light') try: color = tuple([floa...
ValueError
dataset/ETHPy150Open pycollada/pycollada/collada/light.py/SpotLight.load
5,189
def main(argv=None): """script main. parses command line options in sys.argv, unless *argv* is given. """ if not argv: argv = sys.argv # setup command line parser parser = E.OptionParser( version="%prog version: $Id: bed2graph.py 2861 2010-02-23 17:36:32Z andreas $", usage=glo...
IndexError
dataset/ETHPy150Open CGATOxford/cgat/scripts/bed2graph.py/main
5,190
def __init__(self, config): self._config = config self._relays = {} # (tcprelay, udprelay) self._loop = eventloop.EventLoop() self._dns_resolver = asyncdns.DNSResolver() self._dns_resolver.add_to_loop(self._loop) self._statistics = collections.defaultdict(int) s...
IOError
dataset/ETHPy150Open ziggear/shadowsocks/shadowsocks/manager.py/Manager.__init__
5,191
def _send_control_data(self, data): if self._control_client_addr: try: self._control_socket.sendto(data, self._control_client_addr) except (socket.error, OSError, __HOLE__) as e: error_no = eventloop.errno_from_exception(e) if error_no in (...
IOError
dataset/ETHPy150Open ziggear/shadowsocks/shadowsocks/manager.py/Manager._send_control_data
5,192
def __init__(self): try: settings_module = os.environ[ENVIRONMENT_VARIABLE] if not settings_module: raise KeyError except __HOLE__: raise ImportError("Flexisettings cannot be imported, " \ "because environment variable %s is undefined."...
KeyError
dataset/ETHPy150Open hrbonz/django-flexisettings/flexisettings/settings.py/FlexiSettingsProxy.__init__
5,193
def verify_json(filename): """ Checks that a JSON file is valid JSON """ try: with open(filename) as jsonfile: json.loads(jsonfile.read()) return True except __HOLE__: return False
ValueError
dataset/ETHPy150Open gosquadron/squadron/squadron/autotest.py/verify_json
5,194
def _detect_parse_error(self, date_formats, languages): """ Check following cases: * 2nd month in Hijri calendar can be 29 or 30 days whilst this is not possible for Gregorian calendar. """ for lang_shortname in languages: language = default_language_loader.g...
ValueError
dataset/ETHPy150Open scrapinghub/dateparser/dateparser/calendars/hijri.py/HijriCalendar._detect_parse_error
5,195
def __setstate__(self, d): if "restore_design_info" in d: # NOTE: there may be a more performant way to do this from patsy import dmatrices, PatsyError exc = [] try: data = d['frame'] except __HOLE__: data = d['orig_endo...
KeyError
dataset/ETHPy150Open statsmodels/statsmodels/statsmodels/base/data.py/ModelData.__setstate__
5,196
def _get_names(self, arr): if isinstance(arr, DataFrame): return list(arr.columns) elif isinstance(arr, Series): if arr.name: return [arr.name] else: return else: try: return arr.dtype.names ...
AttributeError
dataset/ETHPy150Open statsmodels/statsmodels/statsmodels/base/data.py/ModelData._get_names
5,197
def _get_row_labels(self, arr): try: return arr.index except __HOLE__: # if we've gotten here it's because endog is pandas and # exog is not, so just return the row labels from endog return self.orig_endog.index
AttributeError
dataset/ETHPy150Open statsmodels/statsmodels/statsmodels/base/data.py/PandasData._get_row_labels
5,198
def main(argv=None): if argv is None: argv = sys.argv try: args = vroom.args.Parse(argv[1:]) except __HOLE__ as e: sys.stderr.write('%s\n' % ', '.join(e.args)) return 1 if args.murder: try: output = subprocess.check_output(['ps', '-A']).decode('utf-8') except subprocess.CalledPro...
ValueError
dataset/ETHPy150Open google/vroom/vroom/__main__.py/main
5,199
@must_be_logged_in def watched_logs_get(**kwargs): user = kwargs['auth'].user try: page = int(request.args.get('page', 0)) except __HOLE__: raise HTTPError(http.BAD_REQUEST, data=dict( message_long='Invalid value for "page".' )) try: size = int(request.args.ge...
ValueError
dataset/ETHPy150Open CenterForOpenScience/osf.io/website/views.py/watched_logs_get