Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
4,600
def _parse_text_rule(rule): """Parses policy to the tree. Translates a policy written in the policy language into a tree of Check objects. """ # Empty rule means always accept if not rule: return TrueCheck() # Parse the token stream state = ParseState() for tok, value in _...
ValueError
dataset/ETHPy150Open CiscoSystems/avos/openstack_dashboard/openstack/common/policy.py/_parse_text_rule
4,601
def __call__(self, target, creds, enforcer): """Recursively checks credentials based on the defined rules.""" try: return enforcer.rules[self.match](target, creds, enforcer) except __HOLE__: # We don't have any matching rule; fail closed return False
KeyError
dataset/ETHPy150Open CiscoSystems/avos/openstack_dashboard/openstack/common/policy.py/RuleCheck.__call__
4,602
def __call__(self, target, creds, enforcer): """Check an individual match. Matches look like: tenant:%(tenant_id)s role:compute:admin True:%(user.enabled)s 'Member':%(role.name)s """ try: match = self.match % target e...
KeyError
dataset/ETHPy150Open CiscoSystems/avos/openstack_dashboard/openstack/common/policy.py/GenericCheck.__call__
4,603
@classmethod def _CreateSchemaWithoutProperties(cls, api, name, def_dict, wire_name, parent): if parent: # code objects have __getitem__(), but not .get() try: pname = parent['id'] except __HOLE__: pname = '<unknown>' name_to_log = '%s.%...
KeyError
dataset/ETHPy150Open google/apis-client-generator/src/googleapis/codegen/schema.py/Schema._CreateSchemaWithoutProperties
4,604
def __init__(self, api, schema, name, def_dict, key_for_variants=None): """Construct a Property. A Property requires several elements in its template value dictionary which are set here: wireName: the string which labels this Property in the JSON serialization. dataType: the DataType of this pr...
KeyError
dataset/ETHPy150Open google/apis-client-generator/src/googleapis/codegen/schema.py/Property.__init__
4,605
def ParseFieldDescs(): global fields_to_derive global fields f = open('.bookworm/metadata/field_descriptions.json', 'r') try: fields = json.loads(f.read()) except __HOLE__: raise ValueError("Error parsing JSON: Check to make sure that your field_descriptions.json file is valid?") ...
ValueError
dataset/ETHPy150Open Bookworm-project/BookwormDB/bookwormDB/MetaParser.py/ParseFieldDescs
4,606
def ParseJSONCatalog(target="default",source = "default"): global fields_to_derive if target=="default": target=open(".bookworm/metadata/jsoncatalog_derived.txt", "w") if source=="default": source = open(".bookworm/metadata/jsoncatalog.txt", "r") f = target for data in sourc...
KeyError
dataset/ETHPy150Open Bookworm-project/BookwormDB/bookwormDB/MetaParser.py/ParseJSONCatalog
4,607
def get_env_setting(setting): """ Get the environment setting or return exception """ try: return os.environ[setting] except __HOLE__: error_msg = "Set the %s env variable" % setting raise ImproperlyConfigured(error_msg) # Your project root
KeyError
dataset/ETHPy150Open xenith/django-base-template/project_name/settings/base.py/get_env_setting
4,608
def getChild(self, name, request): if name == '': return self td = '.twistd' if name[-len(td):] == td: username = name[:-len(td)] sub = 1 else: username = name sub = 0 try: pw_name, pw_passwd, pw_uid, pw_gi...
KeyError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/web/distrib.py/UserDirectory.getChild
4,609
def test_failure(): # urllib tries 5 more times before it gives up server.accept(5) try: authfetch('bing','wrong') assert False, "this should raise an exception" except __HOLE__ as e: assert e.code == 401
HTTPError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Paste-2.0.1/tests/test_auth/test_auth_digest.py/test_failure
4,610
def test_strslice(self): try: str(self.annot) assert 0, "should not get here" except __HOLE__: pass
ValueError
dataset/ETHPy150Open cjlee112/pygr/tests/annotation_test.py/AnnotationSeq_Test.test_strslice
4,611
def test_setitem(self): try: self.db['foo'] = 'bar' # use 'add_annotation' instead assert 0, "should not reach this point" except __HOLE__: pass
KeyError
dataset/ETHPy150Open cjlee112/pygr/tests/annotation_test.py/AnnotationDB_Test.test_setitem
4,612
def test_readonly(self): "AnnotationDB readonly" try: self.db.copy() # what should 'copy' do on AD? assert 0, 'this method should raise NotImplementedError' except NotImplementedError: pass try: # what should 'set...
NotImplementedError
dataset/ETHPy150Open cjlee112/pygr/tests/annotation_test.py/AnnotationDB_Test.test_readonly
4,613
def test_bad_seqdict(self): "AnnotationDB bad seqdict" class Annotation(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) slicedb = dict(annot1=Annotation(id='seq', start=0, stop=10), annot2=Annotation(id='seq', start=5, sto...
KeyError
dataset/ETHPy150Open cjlee112/pygr/tests/annotation_test.py/AnnotationDB_Test.test_bad_seqdict
4,614
def pytest_configure(): from django.conf import settings settings.configure( DEBUG=True, USE_TZ=True, USE_I18N=True, ROOT_URLCONF="tests.urls", DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": "test.sqlit...
AttributeError
dataset/ETHPy150Open bennylope/django-addendum/conftest.py/pytest_configure
4,615
def import_teams(fileToImport): try: sh = xlrd.open_workbook(filename=None, file_contents=fileToImport.read()).sheet_by_index(0) except: return ['ERROR: Please upload an .xlsx file. This filetype is not compatible'] num_teams = 0 found_end = False team_errors = [] while found_end...
IndexError
dataset/ETHPy150Open jolynch/mit-tab/mittab/libs/data_import/import_teams.py/import_teams
4,616
def copy_template(template_name, copy_to, tag_library_name): """copies the specified template directory to the copy_to location""" import django_extensions import shutil template_dir = os.path.join(django_extensions.__path__[0], 'conf', template_name) # walks the template structure and copies it ...
OSError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/django-extensions-1.5.0/django_extensions/management/commands/create_template_tags.py/copy_template
4,617
def rst2tex(in_path, out_path): dir_util.copy_tree(in_path, out_path) base_dir = os.path.dirname(__file__) scipy_status = os.path.join(base_dir, '_static/status.sty') shutil.copy(scipy_status, out_path) scipy_style = os.path.join(base_dir, '_static/scipy.sty') shutil.copy(scipy_style, out_path...
ImportError
dataset/ETHPy150Open scipy-conference/scipy_proceedings/publisher/build_paper.py/rst2tex
4,618
def has_module(module): try: __import__(module) except __HOLE__: warn(module + ' module not available for testing, ' 'consider installing') return False return True
ImportError
dataset/ETHPy150Open jsonpickle/jsonpickle/tests/backend_test.py/has_module
4,619
def get_data_files(): # generate man pages using rst2man try: subprocess.call(["rst2man", "nipapd.man.rst", "nipapd.8"]) subprocess.call(["rst2man", "nipap-passwd.man.rst", "nipap-passwd.1"]) except __HOLE__ as exc: print >> sys.stderr, "rst2man failed to run:", str(exc) sys....
OSError
dataset/ETHPy150Open SpriteLink/NIPAP/nipap/setup.py/get_data_files
4,620
def main(): manager.connect() try: manager.loop.run_forever() except __HOLE__: manager.loop.close()
KeyboardInterrupt
dataset/ETHPy150Open gawel/panoramisk/examples/event_listener.py/main
4,621
def parse_html(self, r): alerts = [] if has_lxml: try: root = lxml.html.fromstring(r.response.content) content = ''.join([x for x in root.xpath("//text()") if x.getparent().tag != "script"]) except __HOLE__: alerts.append(stealthy("reponse.content-...
UnicodeDecodeError
dataset/ETHPy150Open securusglobal/abrupt/abrupt/alert.py/GenericAlerter.parse_html
4,622
def tearDown(self): try: os.environ = self.env except __HOLE__: pass
AttributeError
dataset/ETHPy150Open openelections/openelections-core/openelex/tests/test_config.py/TestSettings.tearDown
4,623
def plot_loss(self): try: from matplotlib import pyplot except __HOLE__: "Can not plot loss, matplotlib required" pyplot.plot(self.loss[1:]) pyplot.xlabel("Iteration") pyplot.ylabel("Loss") pyplot.show()
ImportError
dataset/ETHPy150Open sisl/Chimp/chimp/agents/dqn_agent.py/DQNAgent.plot_loss
4,624
def plot_eval_reward(self): try: from matplotlib import pyplot except __HOLE__: "Can not plot loss, matplotlib required" pyplot.plot(self.eval_every * np.arange(len(self.r_eval)), self.r_eval) pyplot.xlabel("Reward") pyplot.ylabel("Loss") pyplot.sh...
ImportError
dataset/ETHPy150Open sisl/Chimp/chimp/agents/dqn_agent.py/DQNAgent.plot_eval_reward
4,625
def compress(self, values): if not values: return None lower, upper = values if lower is not None and upper is not None and lower > upper: raise exceptions.ValidationError( self.error_messages['bound_ordering'], code='bound_ordering', ...
TypeError
dataset/ETHPy150Open django/django/django/contrib/postgres/forms/ranges.py/BaseRangeField.compress
4,626
def get_input( message = None, validator = None, suggestions = None, is_path = False, ): """ Gets input from the user Returns a valid value Keyword arguments: message -- printed first validator -- a function that returns True for a valid input ...
KeyboardInterrupt
dataset/ETHPy150Open NVIDIA/DIGITS/digits/config/prompt.py/get_input
4,627
def handle(self, *args, **kwargs): env = os.environ.copy() classpath = env.get('CLASSPATH', '').split(os.pathsep) jar = spark.conf.LIVY_ASSEMBLY_JAR.get() classpath.insert(0, jar) # Add the hadoop classpath if it's available. try: p = subprocess.Popen(['hadoop', 'classpath'], stdout=subp...
OSError
dataset/ETHPy150Open cloudera/hue/apps/spark/src/spark/management/commands/livy_server.py/Command.handle
4,628
def tearDown(self): try: self.conchFactory.proto.done = 1 except __HOLE__: pass else: self.conchFactory.proto.transport.loseConnection() return defer.gatherResults([ defer.maybeDeferred(self.conchServer.stopListening), d...
AttributeError
dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/conch/test/test_conch.py/ConchServerSetupMixin.tearDown
4,629
def _ext_service(self, entity_id, typ, service, binding): try: srvs = self[entity_id][typ] except __HOLE__: return None if not srvs: return srvs res = [] for srv in srvs: if "extensions" in srv: for elem in srv["ex...
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/mongo_store.py/MetadataMDB._ext_service
4,630
def get(self, key, default=None): try: return getattr(self.stats, key) except __HOLE__: return getattr(self, key, default)
AttributeError
dataset/ETHPy150Open ionelmc/pytest-benchmark/src/pytest_benchmark/stats.py/BenchmarkStats.get
4,631
def __getitem__(self, key): try: return getattr(self.stats, key) except __HOLE__: return getattr(self, key)
AttributeError
dataset/ETHPy150Open ionelmc/pytest-benchmark/src/pytest_benchmark/stats.py/BenchmarkStats.__getitem__
4,632
def metric_filter(self, metrics, filter=None): """from a list of metrics ie ['cpuStats', 'CPUs', 'usr'] it constructs a dictionary that can be sent to the metrics endpoint for consumption""" metrics = list(metrics) if not filter: filter = {} filter[metrics.pop()]...
IndexError
dataset/ETHPy150Open serverdensity/sdbot/limbo/plugins/common/basewrapper.py/BaseWrapper.metric_filter
4,633
def __init__(self, problems, stop, arrival_time=None, departure_time=None, stop_headsign=None, pickup_type=None, drop_off_type=None, shape_dist_traveled=None, arrival_secs=None, departure_secs=None, stop_time=None, stop_sequence=None, timepoint=...
ValueError
dataset/ETHPy150Open google/transitfeed/transitfeed/stoptime.py/StopTime.__init__
4,634
def update_wrapper(wrapper, wrapped, assigned = WRAPPER_ASSIGNMENTS, updated = WRAPPER_UPDATES): """Update a wrapper function to look like the wrapped function wrapper is the function to be updated wrapped is the original function assign...
TypeError
dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/utils/functional.py/update_wrapper
4,635
def get_pid_by_line_number(self, lineno): try: # Account for header return self.__command_window_line_map_order[lineno - 4] except __HOLE__: return None
IndexError
dataset/ETHPy150Open joonty/vim-do/autoload/python/rendering.py/ProcessRenderer.get_pid_by_line_number
4,636
def import_service(module_name): parts = module_name.split(":", 1) if len(parts) == 1: module_name, obj = module_name, None else: module_name, obj = parts[0], parts[1] try: __import__(module_name) except __HOLE__ as exc: if module_name.endswith(".py") and os.path.exi...
ImportError
dataset/ETHPy150Open onefinestay/nameko/nameko/cli/run.py/import_service
4,637
def run(services, config, backdoor_port=None): service_runner = ServiceRunner(config) for service_cls in services: service_runner.add_service(service_cls) def shutdown(signum, frame): # signal handlers are run by the MAINLOOP and cannot use eventlet # primitives, so we have to call ...
KeyboardInterrupt
dataset/ETHPy150Open onefinestay/nameko/nameko/cli/run.py/run
4,638
@requires_system_grains def test_groups_includes_primary(self, grains=None): # Let's create a user, which usually creates the group matching the # name uname = self.__random_string() if self.run_function('user.add', [uname]) is not True: # Skip because creating is not wha...
AssertionError
dataset/ETHPy150Open saltstack/salt/tests/integration/modules/useradd.py/UseraddModuleTest.test_groups_includes_primary
4,639
def get_best_run(self): try: return BestRun.objects.filter(map=self)[0] except __HOLE__: return None
IndexError
dataset/ETHPy150Open chaosk/teerace/teerace/race/models.py/Map.get_best_run
4,640
def test_get_pricing_invalid_file_path(self): try: libcloud.pricing.get_pricing(driver_type='compute', driver_name='bar', pricing_file_path='inexistent.json') except __HOLE__: pass else: self.fail('Invalid pricing file ...
IOError
dataset/ETHPy150Open apache/libcloud/libcloud/test/test_pricing.py/PricingTestCase.test_get_pricing_invalid_file_path
4,641
def test_get_pricing_invalid_driver_type(self): try: libcloud.pricing.get_pricing(driver_type='invalid_type', driver_name='bar', pricing_file_path='inexistent.json') except __HOLE__: pass else: self.fail('Invalid driver...
AttributeError
dataset/ETHPy150Open apache/libcloud/libcloud/test/test_pricing.py/PricingTestCase.test_get_pricing_invalid_driver_type
4,642
def test_get_pricing_not_in_cache(self): try: libcloud.pricing.get_pricing(driver_type='compute', driver_name='inexistent', pricing_file_path=PRICING_FILE_PATH) except __HOLE__: pass else: self.fail('Invalid driver prov...
KeyError
dataset/ETHPy150Open apache/libcloud/libcloud/test/test_pricing.py/PricingTestCase.test_get_pricing_not_in_cache
4,643
def __getitem__(self, name): try: return super(AutoAttrDict, self).__getitem__(name) except __HOLE__: d = AutoAttrDict() super(AutoAttrDict, self).__setitem__(name, d) return d
KeyError
dataset/ETHPy150Open kdart/pycopia/core/pycopia/jsonconfig.py/AutoAttrDict.__getitem__
4,644
def test_builder_raises_exception_with_undefined_method(self): builder = self.get_builder() try: builder.do_not_exist() self.fail('Builder did not raise and AttributeError exception') except __HOLE__: self.assertTrue(True)
AttributeError
dataset/ETHPy150Open sdispater/orator/tests/query/test_query_builder.py/QueryBuilderTestCase.test_builder_raises_exception_with_undefined_method
4,645
@staticmethod def _strft(dt_obj, null_on_none=False): """Convert datetime.datetime to ISO string. :param null_on_none: bool Occasionally, we will actually want to send an empty string where a datetime would typically go. For instance, if a strategy has an end_date set, but t...
AttributeError
dataset/ETHPy150Open MediaMath/t1-python/terminalone/entity.py/Entity._strft
4,646
def Modules(directory): """Creates modules from a plugin directory. Note that there can be many, if a plugin has standalone parts that merit their own helpfiles. Args: directory: The plugin directory. Yields: Module objects as necessary. """ directory = directory.rstrip(os.path.sep) addon_info...
IOError
dataset/ETHPy150Open google/vimdoc/vimdoc/module.py/Modules
4,647
@permission_required("core.manage_shop") def manage_property_groups(request): """The main view to manage properties. """ try: prop = PropertyGroup.objects.all()[0] url = reverse("lfs_manage_property_group", kwargs={"id": prop.id}) except __HOLE__: url = reverse("lfs_manage_no_pro...
IndexError
dataset/ETHPy150Open diefenbach/django-lfs/lfs/manage/property_groups/views.py/manage_property_groups
4,648
def generate(env): try: env['BUILDERS']['CopyTo'] env['BUILDERS']['CopyAs'] except __HOLE__, e: global copyToBuilder if copyToBuilder is None: copyToBuilder = SCons.Builder.Builder( action = copy_action, ...
KeyError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Tool/filesystem.py/generate
4,649
def default(self, obj): if isinstance(obj, Mapping): try: return dict(obj) except: pass if isinstance(obj, Sized) and isinstance(obj, Iterable): try: return list(obj) except: pass if c...
AttributeError
dataset/ETHPy150Open mahmoud/clastic/clastic/render/simple.py/ClasticJSONEncoder.default
4,650
def __init__(self, **kwargs): self.qp_name = kwargs.pop('qp_name', 'format') self.dev_mode = kwargs.pop('dev_mode', True) self.json_render = kwargs.pop('json_render', JSONRender(dev_mode=self.dev_mode)) try: table_type = kwargs.pop('table...
KeyError
dataset/ETHPy150Open mahmoud/clastic/clastic/render/simple.py/BasicRender.__init__
4,651
def __eq__(self, other): try: return self.startEA == other.startEA except __HOLE__: return False
AttributeError
dataset/ETHPy150Open tmr232/Sark/sark/code/function.py/Function.__eq__
4,652
def rate_limit(limit=100, window=60): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): key = "{0}: {1}".format(request.remote_addr, request.path) try: remaining = limit - int(redis.get(key)) except (ValueError, __HOLE__): ...
TypeError
dataset/ETHPy150Open projectweekend/Flask-PostgreSQL-API-Seed/app/utils/rate_limit.py/rate_limit
4,653
@app.after_request def add_rate_limit_headers(response): try: limit, remaining, expires = map(int, g.rate_limits) except (AttributeError, __HOLE__): return response else: response.headers.add('X-RateLimit-Remaining', remaining) response.headers.add('X-RateLimit-Limit', limit)...
ValueError
dataset/ETHPy150Open projectweekend/Flask-PostgreSQL-API-Seed/app/utils/rate_limit.py/add_rate_limit_headers
4,654
def check_iterator(self, it, seq, pickle=True): if pickle: self.check_pickle(it, seq) res = [] while 1: try: val = next(it) except __HOLE__: break res.append(val) self.assertEqual(res, seq) # Helper to c...
StopIteration
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_iter.py/TestCase.check_iterator
4,655
def check_pickle(self, itorg, seq): d = pickle.dumps(itorg) it = pickle.loads(d) # Cannot assert type equality because dict iterators unpickle as list # iterators. # self.assertEqual(type(itorg), type(it)) self.assertTrue(isinstance(it, collections.abc.Iterator)) ...
StopIteration
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_iter.py/TestCase.check_pickle
4,656
def test_exception_function(self): def spam(state=[0]): i = state[0] state[0] = i+1 if i == 10: raise RuntimeError return i res = [] try: for x in iter(spam, 20): res.append(x) except __HOLE__: ...
RuntimeError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_iter.py/TestCase.test_exception_function
4,657
def test_exception_sequence(self): class MySequenceClass(SequenceClass): def __getitem__(self, i): if i == 10: raise RuntimeError return SequenceClass.__getitem__(self, i) res = [] try: for x in MySequenceClass(20): ...
RuntimeError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_iter.py/TestCase.test_exception_sequence
4,658
def test_iter_file(self): f = open(TESTFN, "w") try: for i in range(5): f.write("%d\n" % i) finally: f.close() f = open(TESTFN, "r") try: self.check_for_loop(f, ["0\n", "1\n", "2\n", "3\n", "4\n"], pickle=False) self...
OSError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_iter.py/TestCase.test_iter_file
4,659
def test_builtin_list(self): self.assertEqual(list(SequenceClass(5)), list(range(5))) self.assertEqual(list(SequenceClass(0)), []) self.assertEqual(list(()), []) d = {"one": 1, "two": 2, "three": 3} self.assertEqual(list(d), list(d.keys())) self.assertRaises(TypeError, ...
OSError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_iter.py/TestCase.test_builtin_list
4,660
def test_builtin_tuple(self): self.assertEqual(tuple(SequenceClass(5)), (0, 1, 2, 3, 4)) self.assertEqual(tuple(SequenceClass(0)), ()) self.assertEqual(tuple([]), ()) self.assertEqual(tuple(()), ()) self.assertEqual(tuple("abc"), ("a", "b", "c")) d = {"one": 1, "two": 2,...
OSError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_iter.py/TestCase.test_builtin_tuple
4,661
def test_builtin_max_min(self): self.assertEqual(max(SequenceClass(5)), 4) self.assertEqual(min(SequenceClass(5)), 0) self.assertEqual(max(8, -1), 8) self.assertEqual(min(8, -1), -1) d = {"one": 1, "two": 2, "three": 3} self.assertEqual(max(d), "two") self.assert...
OSError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_iter.py/TestCase.test_builtin_max_min
4,662
def test_builtin_map(self): self.assertEqual(list(map(lambda x: x+1, SequenceClass(5))), list(range(1, 6))) d = {"one": 1, "two": 2, "three": 3} self.assertEqual(list(map(lambda k, d=d: (k, d[k]), d)), list(d.items())) dkeys = list(d.key...
OSError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_iter.py/TestCase.test_builtin_map
4,663
def test_builtin_zip(self): self.assertEqual(list(zip()), []) self.assertEqual(list(zip(*[])), []) self.assertEqual(list(zip(*[(1, 2), 'ab'])), [(1, 'a'), (2, 'b')]) self.assertRaises(TypeError, zip, None) self.assertRaises(TypeError, zip, range(10), 42) self.assertRaise...
OSError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_iter.py/TestCase.test_builtin_zip
4,664
def test_unicode_join_endcase(self): # This class inserts a Unicode object into its argument's natural # iteration, in the 3rd position. class OhPhooey: def __init__(self, seq): self.it = iter(seq) self.i = 0 def __iter__(self): ...
OSError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_iter.py/TestCase.test_unicode_join_endcase
4,665
def test_in_and_not_in(self): for sc5 in IteratingSequenceClass(5), SequenceClass(5): for i in range(5): self.assertIn(i, sc5) for i in "abc", -1, 5, 42.42, (3, 4), [], {1: 1}, 3-12j, sc5: self.assertNotIn(i, sc5) self.assertRaises(TypeError, lamb...
OSError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_iter.py/TestCase.test_in_and_not_in
4,666
def test_countOf(self): from operator import countOf self.assertEqual(countOf([1,2,2,3,2,5], 2), 3) self.assertEqual(countOf((1,2,2,3,2,5), 2), 3) self.assertEqual(countOf("122325", "2"), 3) self.assertEqual(countOf("122325", "6"), 0) self.assertRaises(TypeError, countOf...
OSError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_iter.py/TestCase.test_countOf
4,667
def test_indexOf(self): from operator import indexOf self.assertEqual(indexOf([1,2,2,3,2,5], 1), 0) self.assertEqual(indexOf((1,2,2,3,2,5), 2), 1) self.assertEqual(indexOf((1,2,2,3,2,5), 3), 3) self.assertEqual(indexOf((1,2,2,3,2,5), 5), 5) self.assertRaises(ValueError, i...
OSError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_iter.py/TestCase.test_indexOf
4,668
def test_writelines(self): f = open(TESTFN, "w") try: self.assertRaises(TypeError, f.writelines, None) self.assertRaises(TypeError, f.writelines, 42) f.writelines(["1\n", "2\n"]) f.writelines(("3\n", "4\n")) f.writelines({'5\n': None}) ...
OSError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_iter.py/TestCase.test_writelines
4,669
def test_unpack_iter(self): a, b = 1, 2 self.assertEqual((a, b), (1, 2)) a, b, c = IteratingSequenceClass(3) self.assertEqual((a, b, c), (0, 1, 2)) try: # too many values a, b = IteratingSequenceClass(3) except ValueError: pass else: ...
OSError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_iter.py/TestCase.test_unpack_iter
4,670
@cpython_only def test_ref_counting_behavior(self): class C(object): count = 0 def __new__(cls): cls.count += 1 return object.__new__(cls) def __del__(self): cls = self.__class__ assert cls.count > 0 ...
ValueError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_iter.py/TestCase.test_ref_counting_behavior
4,671
def test_3720(self): # Avoid a crash, when an iterator deletes its next() method. class BadIterator(object): def __iter__(self): return self def __next__(self): del BadIterator.__next__ return 1 try: for i in Ba...
TypeError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_iter.py/TestCase.test_3720
4,672
def _dispatch_channel_events(self): """Invoke the `_dispatch_events` method on open channels that requested it """ if not self._channels_pending_dispatch: return with self._acquire_event_dispatch() as dispatch_acquired: if not dispatch_acquired: ...
KeyError
dataset/ETHPy150Open pika/pika/pika/adapters/blocking_connection.py/BlockingConnection._dispatch_channel_events
4,673
def _dispatch_connection_events(self): """Dispatch ready connection events""" if not self._ready_events: return with self._acquire_event_dispatch() as dispatch_acquired: if not dispatch_acquired: # Nested dispatch or dispatch blocked higher in call stack ...
IndexError
dataset/ETHPy150Open pika/pika/pika/adapters/blocking_connection.py/BlockingConnection._dispatch_connection_events
4,674
def basic_cancel(self, consumer_tag): """This method cancels a consumer. This does not affect already delivered messages, but it does mean the server will not send any more messages for that consumer. The client may receive an arbitrary number of messages in between sending the cancel me...
KeyError
dataset/ETHPy150Open pika/pika/pika/adapters/blocking_connection.py/BlockingChannel.basic_cancel
4,675
def get_dock_json(self): """ return dock json from existing build json """ env_json = self.build_json['spec']['strategy']['customStrategy']['env'] try: p = [env for env in env_json if env["name"] == "ATOMIC_REACTOR_PLUGINS"] except __HOLE__: raise RuntimeError("\"...
TypeError
dataset/ETHPy150Open projectatomic/osbs-client/osbs/build/manipulate.py/DockJsonManipulator.get_dock_json
4,676
def dock_json_has_plugin_conf(self, plugin_type, plugin_name): """ Check whether a plugin is configured. """ try: self.dock_json_get_plugin_conf(plugin_type, plugin_name) return True except (__HOLE__, IndexError): return False
KeyError
dataset/ETHPy150Open projectatomic/osbs-client/osbs/build/manipulate.py/DockJsonManipulator.dock_json_has_plugin_conf
4,677
def _dock_json_get_plugin_conf_or_fail(self, plugin_type, plugin_name): try: conf = self.dock_json_get_plugin_conf(plugin_type, plugin_name) except __HOLE__: raise RuntimeError("Invalid dock json: plugin type '%s' misses" % plugin_type) except IndexError: rais...
KeyError
dataset/ETHPy150Open projectatomic/osbs-client/osbs/build/manipulate.py/DockJsonManipulator._dock_json_get_plugin_conf_or_fail
4,678
def test_intconversion(self): # Test __int__() class ClassicMissingMethods: pass if is_jython: self.assertRaises(TypeError, int, ClassicMissingMethods()) else: self.assertRaises(AttributeError, int, ClassicMissingMethods()) class MissingMethod...
TypeError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_int.py/IntTestCases.test_intconversion
4,679
def _get_from_read_queue(self): """Fetch a frame from the read queue and return it, otherwise return None :rtype: pamqp.specification.Frame """ try: frame_value = self._read_queue.get(False) except Queue.Empty: return None try: ...
ValueError
dataset/ETHPy150Open gmr/rabbitpy/rabbitpy/channel.py/Channel._get_from_read_queue
4,680
@property def title(self): titles = [m.value for m in self.meta if m.type == 'title'] try: return titles[0][0] except __HOLE__: return None
IndexError
dataset/ETHPy150Open hypothesis/h/h/api/models/document.py/Document.title
4,681
def mkdir_p(path): try: os.makedirs(path) except __HOLE__: if not os.path.isdir(path): raise
OSError
dataset/ETHPy150Open nitely/Spirit/spirit/core/utils/__init__.py/mkdir_p
4,682
def _json_to_flat_metrics(self, prefix, data): for key, value in data.items(): if isinstance(value, dict): for k, v in self._json_to_flat_metrics( "%s.%s" % (prefix, key), value): yield k, v else: try: ...
ValueError
dataset/ETHPy150Open BrightcoveOS/Diamond/src/collectors/httpjson/httpjson.py/HTTPJSONCollector._json_to_flat_metrics
4,683
def collect(self): url = self.config['url'] req = urllib2.Request(url) req.add_header('Content-type', 'application/json') try: resp = urllib2.urlopen(req) except urllib2.URLError as e: self.log.error("Can't open url %s. %s", url, e) else: ...
ValueError
dataset/ETHPy150Open BrightcoveOS/Diamond/src/collectors/httpjson/httpjson.py/HTTPJSONCollector.collect
4,684
def create_capture(source = 0, fallback = presets['chess']): '''source: <int> or '<int>|<filename>|synth [:<param_name>=<value> [:...]]' ''' source = str(source).strip() chunks = source.split(':') # hanlde drive letter ('c:', ...) if len(chunks) > 1 and len(chunks[0]) == 1 and chunks[0].isalpha(...
ValueError
dataset/ETHPy150Open bluquar/cubr/video.py/create_capture
4,685
def _file_exists(self): """ Check that the file exists. Also try to check the absolute path. If the file is found within the absolute path, then update the file path """ file_found = True if not os.path.exists(self.file): if os.path.exists(os.path.join(Constan...
OSError
dataset/ETHPy150Open appnexus/schema-tool/schematool/command/resolve.py/ResolveCommand._file_exists
4,686
def _relocate_files(self, old_filename, new_filename, new_ref, new_backref, direction): """ Move the file on disk. Not really a big task, but it might be nice in the future to go ahead and do a git mv command for the user. """ is_backref_line = re.compile('--\s*backref\s*:\s*(\d+...
OSError
dataset/ETHPy150Open appnexus/schema-tool/schematool/command/resolve.py/ResolveCommand._relocate_files
4,687
def clean_built(self, storage): """ Clear any static files that aren't from the apps. """ build_dirs, built_files = self.find_all(storage) found_files = set() for finder in finders.get_finders(): for path, s in finder.list([]): # Prefix the r...
OSError
dataset/ETHPy150Open hzdg/django-staticbuilder/staticbuilder/management/commands/collectforbuild.py/Command.clean_built
4,688
def _construct_form(self, i, **kwargs): """ Instantiates and returns the i-th form instance in a formset. """ defaults = {'auto_id': self.auto_id, 'prefix': self.add_prefix(i)} if self.data or self.files: defaults['data'] = self.data defaults['files'] = se...
IndexError
dataset/ETHPy150Open dcramer/django-compositepks/django/forms/formsets.py/BaseFormSet._construct_form
4,689
def full_clean(self): """ Cleans all of self.data and populates self._errors. """ self._errors = [] if not self.is_bound: # Stop further processing. return for i in range(0, self._total_form_count): form = self.forms[i] self._errors.app...
ValidationError
dataset/ETHPy150Open dcramer/django-compositepks/django/forms/formsets.py/BaseFormSet.full_clean
4,690
def _extract_retry_after_timeout(response): '''Returns the time in seconds that the server is asking us to wait. The information is deduced from the server http response.''' try: seconds_to_wait = int(response.headers.get('retry-after', DEFAULT_RETRY_AFTER_503_INTERVAL)) except __HOLE__: ...
ValueError
dataset/ETHPy150Open dnanexus/dx-toolkit/src/python/dxpy/__init__.py/_extract_retry_after_timeout
4,691
def DXHTTPRequest(resource, data, method='POST', headers=None, auth=True, timeout=DEFAULT_TIMEOUT, use_compression=None, jsonify_data=True, want_full_response=False, decode_response_body=True, prepend_srv=True, session_handler=None, max_retries=DEF...
UnicodeDecodeError
dataset/ETHPy150Open dnanexus/dx-toolkit/src/python/dxpy/__init__.py/DXHTTPRequest
4,692
def setOptions(self, options): """ Creates a config object from the options object. """ from bd2k.util.humanize import human2bytes #This import is used to convert #from human readable quantites to integers def setOption(varName, parsingFn=None, checkFn=None): ...
AssertionError
dataset/ETHPy150Open BD2KGenomics/toil/src/toil/common.py/Config.setOptions
4,693
@staticmethod def loadOrCreateJobStore(jobStoreString, config=None): """ Loads an existing jobStore if it already exists. Otherwise a new instance of a jobStore is created and returned. :param str jobStoreString: see exception message below :param toil.common.Config config: ...
ValueError
dataset/ETHPy150Open BD2KGenomics/toil/src/toil/common.py/Toil.loadOrCreateJobStore
4,694
@staticmethod def getWorkflowDir(workflowID, configWorkDir=None): """ Returns a path to the directory where worker directories and the cache will be located for this workflow. :param str workflowID: Unique identifier for the workflow :param str configWorkDir: Value passed to...
OSError
dataset/ETHPy150Open BD2KGenomics/toil/src/toil/common.py/Toil.getWorkflowDir
4,695
def parseSetEnv(l): """ Parses a list of strings of the form "NAME=VALUE" or just "NAME" into a dictionary. Strings of the latter from will result in dictionary entries whose value is None. :type l: list[str] :rtype: dict[str,str] >>> parseSetEnv([]) {} >>> parseSetEnv(['a']) {'a':...
ValueError
dataset/ETHPy150Open BD2KGenomics/toil/src/toil/common.py/parseSetEnv
4,696
def _run_env(self, name, *args): try: self.log.debug('Run function {}'.format(name)) return getattr(self, name)(*args) except __HOLE__ as e: self.log.debug('The function {} does not exist'.format(name)) except BaseException as e: self.log.warn( ...
AttributeError
dataset/ETHPy150Open onitu/onitu/tests/utils/benchmark.py/Benchmark._run_env
4,697
def __call__(self, env, dir=None, target=None, source=None, argument=None): import SCons.PathList try: path = env[self.variable] except __HOLE__: return () dir = dir or env.fs._cwd path = SCons.PathList.PathList(path).subst_path(env, target, source) ...
KeyError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Scanner/__init__.py/FindPathDirs.__call__
4,698
def __cmp__(self, other): try: return cmp(self.__dict__, other.__dict__) except __HOLE__: # other probably doesn't have a __dict__ return cmp(self.__dict__, other)
AttributeError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Scanner/__init__.py/Base.__cmp__
4,699
def select(self, node): if SCons.Util.is_Dict(self.function): key = node.scanner_key() try: return self.function[key] except __HOLE__: return None else: return self
KeyError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Scanner/__init__.py/Base.select