Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
5,400 | def set_picture(self, new_file):
uid = self.target.username
self.picture.error = None
error = None
# No value, exit
if new_file == '':
return None
try:
validator.validate_file(
new_file, self.assets_manager.max_size, _(u'File must... | ValueError | dataset/ETHPy150Open Net-ng/kansha/kansha/user/user_profile.py/UserForm.set_picture |
5,401 | def test_validates_local_url(self):
try:
self.validator('/')
except __HOLE__:
self.fail('ExtendedURLValidator raised ValidationError'
'unexpectedly!') | ValidationError | dataset/ETHPy150Open django-oscar/django-oscar/tests/integration/core/validator_tests.py/TestExtendedURLValidatorWithVerifications.test_validates_local_url |
5,402 | def test_validates_local_url_with_query_strings(self):
try:
self.validator('/?q=test') # Query strings shouldn't affect validation
except __HOLE__:
self.fail('ExtendedURLValidator raised ValidationError'
'unexpectedly!') | ValidationError | dataset/ETHPy150Open django-oscar/django-oscar/tests/integration/core/validator_tests.py/TestExtendedURLValidatorWithVerifications.test_validates_local_url_with_query_strings |
5,403 | def test_validates_urls_missing_preceding_slash(self):
try:
self.validator('catalogue/')
except __HOLE__:
self.fail('ExtendedURLValidator raised ValidationError'
'unexpectedly!') | ValidationError | dataset/ETHPy150Open django-oscar/django-oscar/tests/integration/core/validator_tests.py/TestExtendedURLValidatorWithVerifications.test_validates_urls_missing_preceding_slash |
5,404 | def test_validates_flatpages_urls(self):
FlatPage.objects.create(title='test page', url='/test/page/')
try:
self.validator('/test/page/')
except __HOLE__:
self.fail('ExtendedURLValidator raises ValidationError'
'unexpectedly!') | ValidationError | dataset/ETHPy150Open django-oscar/django-oscar/tests/integration/core/validator_tests.py/TestExtendedURLValidatorWithVerifications.test_validates_flatpages_urls |
5,405 | def returner(ret):
'''
Log outcome to sentry. The returner tries to identify errors and report
them as such. All other messages will be reported at info level.
'''
def connect_sentry(message, result):
'''
Connect to the Sentry server
'''
pillar_data = __salt__['pillar... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/returners/sentry_return.py/returner |
5,406 | def urlopen(self, path, method='GET', post='', env=None):
result = {'code':0, 'status':'error', 'header':{}, 'body':tob('')}
def start_response(status, header):
result['code'] = int(status.split()[0])
result['status'] = status.split(None, 1)[-1]
for name, value in hea... | TypeError | dataset/ETHPy150Open bottlepy/bottle/test/tools.py/ServerTestBase.urlopen |
5,407 | @register.filter(name='truncatechars')
@stringfilter
def truncatechars(value, arg):
"""
Truncates a string after a certain number of chars.
Argument: Number of chars to truncate after.
"""
try:
length = int(arg)
except __HOLE__: # Invalid literal for int().
return value # Fail s... | ValueError | dataset/ETHPy150Open disqus/overseer/overseer/templatetags/overseer_helpers.py/truncatechars |
5,408 | def butler(table_data):
try:
with open(CONFIG_PATH) as config:
movie_path = config.read()
except IOError:
print(Fore.RED, "\n\nRun `$moviemon PATH` to "
"index your movies directory.\n\n")
quit()
else:
table = AsciiTable(table_data)
try:
... | IOError | dataset/ETHPy150Open iCHAIT/moviemon/moviemon/moviemon.py/butler |
5,409 | def execute(cmd,
process_input=None,
check_exit_code=True,
cwd=None,
shell=False,
env_overrides=None,
stdout_fh=subprocess.PIPE,
stderr_fh=subprocess.PIPE):
"""Helper method to execute a command through subprocess.
:param cmd: ... | OSError | dataset/ETHPy150Open openstack/anvil/anvil/shell.py/execute |
5,410 | def execute_save_output(cmd, file_name, **kwargs):
"""Helper method to execute a command through subprocess and save stdout
and stderr into a file.
"""
kwargs = kwargs.copy()
mkdirslist(dirname(file_name))
try:
with open(file_name, 'wb') as fh:
return execute(cmd, stdout_fh=f... | IOError | dataset/ETHPy150Open openstack/anvil/anvil/shell.py/execute_save_output |
5,411 | def rmdir(path, quiet=True):
if not isdir(path):
return
try:
LOG.debug("Deleting directory %r with the cavet that we will fail if it's not empty." % (path))
os.rmdir(path)
LOG.debug("Deleted directory %r" % (path))
except __HOLE__:
if not quiet:
raise
... | OSError | dataset/ETHPy150Open openstack/anvil/anvil/shell.py/rmdir |
5,412 | def unlink(path, ignore_errors=True):
LOG.debug("Unlinking (removing) %r" % (path))
try:
os.unlink(path)
except __HOLE__:
if not ignore_errors:
raise
else:
pass | OSError | dataset/ETHPy150Open openstack/anvil/anvil/shell.py/unlink |
5,413 | @contextmanager
def exception_to_errormsg():
try:
yield
except exceptions.PyUniteWarning as e:
warn(str(e))
except exceptions.PyUniteError as e:
error(str(e))
except __HOLE__ as e:
# It's better to provide a stack trace than nothing
if not str(e):
rais... | AssertionError | dataset/ETHPy150Open azure-satellite/pyunite/pyunite/ui.py/exception_to_errormsg |
5,414 | def test_bad_sysname(self):
group = Group()
try:
group.add('0', ExecComp('y=x*2.0'), promotes=['x'])
except __HOLE__ as err:
self.assertEqual(str(err), ": '0' is not a valid system name.")
try:
group.add('foo:bar', ExecComp('y=x*2.0'), promotes=['x'])
... | NameError | dataset/ETHPy150Open OpenMDAO/OpenMDAO/openmdao/core/test/test_group.py/TestGroup.test_bad_sysname |
5,415 | def test_layout_getter_fixed(self):
tr = Layout()
tr.fixed = True
try:
tr.Test.Path
raise AssertionError
except __HOLE__ as e:
self.assertEqual(str(e), self.fixed_error) | AttributeError | dataset/ETHPy150Open ioam/holoviews/tests/testcollector.py/LayoutTest.test_layout_getter_fixed |
5,416 | def test_layout_setter_fixed(self):
tr = Layout()
tr.fixed = True
try:
tr.Test.Path = 42
raise AssertionError
except __HOLE__ as e:
self.assertEqual(str(e), self.fixed_error) | AttributeError | dataset/ETHPy150Open ioam/holoviews/tests/testcollector.py/LayoutTest.test_layout_setter_fixed |
5,417 | def test_layout_shallow_fixed_setter(self):
tr = Layout()
tr.fixed = True
try:
tr.Test = 42
raise AssertionError
except __HOLE__ as e:
self.assertEqual(str(e), self.fixed_error) | AttributeError | dataset/ETHPy150Open ioam/holoviews/tests/testcollector.py/LayoutTest.test_layout_shallow_fixed_setter |
5,418 | def test_layout_toggle_fixed(self):
tr = Layout()
tr.fixed = True
try:
tr.Test = 42
raise AssertionError
except __HOLE__ as e:
self.assertEqual(str(e), self.fixed_error)
tr.fixed = False
tr.Test = 42 | AttributeError | dataset/ETHPy150Open ioam/holoviews/tests/testcollector.py/LayoutTest.test_layout_toggle_fixed |
5,419 | def unregister(self, name):
try:
content_type = self.name_to_type[name]
self._decoders.pop(content_type, None)
self._encoders.pop(name, None)
self.type_to_name.pop(content_type, None)
self.name_to_type.pop(name, None)
except __HOLE__:
... | KeyError | dataset/ETHPy150Open celery/kombu/kombu/serialization.py/SerializerRegistry.unregister |
5,420 | def _set_default_serializer(self, name):
"""
Set the default serialization method used by this library.
:param name: The name of the registered serialization method.
For example, `json` (default), `pickle`, `yaml`, `msgpack`,
or any custom methods registered using :meth:... | KeyError | dataset/ETHPy150Open celery/kombu/kombu/serialization.py/SerializerRegistry._set_default_serializer |
5,421 | def register_yaml():
"""Register a encoder/decoder for YAML serialization.
It is slower than JSON, but allows for more data types
to be serialized. Useful if you need to send data such as dates"""
try:
import yaml
registry.register('yaml', yaml.safe_dump, yaml.safe_load,
... | ImportError | dataset/ETHPy150Open celery/kombu/kombu/serialization.py/register_yaml |
5,422 | def register_msgpack():
"""See http://msgpack.sourceforge.net/"""
pack = unpack = None
try:
import msgpack
if msgpack.version >= (0, 4):
from msgpack import packb, unpackb
def pack(s):
return packb(s, use_bin_type=True)
def unpack(s):
... | ValueError | dataset/ETHPy150Open celery/kombu/kombu/serialization.py/register_msgpack |
5,423 | def enable_insecure_serializers(choices=['pickle', 'yaml', 'msgpack']):
"""Enable serializers that are considered to be unsafe.
Will enable ``pickle``, ``yaml`` and ``msgpack`` by default,
but you can also specify a list of serializers (by name or content type)
to enable.
"""
for choice in cho... | KeyError | dataset/ETHPy150Open celery/kombu/kombu/serialization.py/enable_insecure_serializers |
5,424 | def getcolor(self, color):
# experimental: given an rgb tuple, allocate palette entry
if self.rawmode:
raise ValueError("palette contains raw palette data")
if Image.isTupleType(color):
try:
return self.colors[color]
except __HOLE__:
... | KeyError | dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/site-packages/PIL/ImagePalette.py/ImagePalette.getcolor |
5,425 | def load(filename):
# FIXME: supports GIMP gradients only
fp = open(filename, "rb")
lut = None
if not lut:
try:
import GimpPaletteFile
fp.seek(0)
p = GimpPaletteFile.GimpPaletteFile(fp)
lut = p.getpalette()
except (SyntaxError, ValueErr... | ValueError | dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/site-packages/PIL/ImagePalette.py/load |
5,426 | def test_power_representation():
tests = [(1729, 3, 2), (234, 2, 4), (2, 1, 2), (3, 1, 3), (5, 2, 2), (12352, 2, 4),
(32760, 2, 3)]
for test in tests:
n, p, k = test
f = power_representation(n, p, k)
while True:
try:
l = next(f)
... | StopIteration | dataset/ETHPy150Open sympy/sympy/sympy/solvers/tests/test_diophantine.py/test_power_representation |
5,427 | def handle_noargs(self, migrate_all=False, **options):
# Import the 'management' module within each installed app, to register
# dispatcher events.
# This is copied from Django, to fix bug #511.
try:
from django.utils.importlib import import_module
except Imp... | ImportError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/South-1.0.2/south/management/commands/syncdb.py/Command.handle_noargs |
5,428 | def _safe_log(log_func, msg, msg_data):
"""Sanitizes the msg_data field before logging."""
SANITIZE = {'set_admin_password': [('args', 'new_pass')],
'run_instance': [('args', 'admin_password')],
'route_message': [('args', 'message', 'args', 'method_info',
... | KeyError | dataset/ETHPy150Open Havate/havate-openstack/proto-build/gui/horizon/Horizon_GUI/openstack_dashboard/openstack/common/rpc/common.py/_safe_log |
5,429 | def deserialize_remote_exception(conf, data):
failure = jsonutils.loads(str(data))
trace = failure.get('tb', [])
message = failure.get('message', "") + "\n" + "\n".join(trace)
name = failure.get('class')
module = failure.get('module')
# NOTE(ameade): We DO NOT want to allow just any module to ... | AttributeError | dataset/ETHPy150Open Havate/havate-openstack/proto-build/gui/horizon/Horizon_GUI/openstack_dashboard/openstack/common/rpc/common.py/deserialize_remote_exception |
5,430 | def __getattr__(self, key):
try:
return self.values[key]
except __HOLE__:
raise AttributeError(key) | KeyError | dataset/ETHPy150Open Havate/havate-openstack/proto-build/gui/horizon/Horizon_GUI/openstack_dashboard/openstack/common/rpc/common.py/CommonRpcContext.__getattr__ |
5,431 | def _get_tag(config):
"""
Fetch the current deploy file from the repo on the deployment server and
return the current tag associated with it.
:param config: Config hash as fetched from get_config.
:type config: hash
:rtype: str
"""
# Fetch the .deploy file from the server and get the cu... | IOError | dataset/ETHPy150Open trebuchet-deploy/trebuchet/modules/deploy.py/_get_tag |
5,432 | def testGeoIP(self):
try:
import GeoIP
except __HOLE__:
print >> sys.stderr, "GeoIP Python package not available - skipping geoip unittest."
return
output = [(geocode, ip, line) for geocode, ip, line in geoip(fh=self.fh, **self.options)]
self.assertEq... | ImportError | dataset/ETHPy150Open adamhadani/logtools/logtools/test/test_logtools.py/GeoIPTestCase.testGeoIP |
5,433 | def testFilter(self):
"""Test GeoIP filtering functionality"""
try:
import GeoIP
except __HOLE__:
print >> sys.stderr, "GeoIP Python package not available - skipping geoip unittest."
return
# Check positive filter
self.... | ImportError | dataset/ETHPy150Open adamhadani/logtools/logtools/test/test_logtools.py/GeoIPTestCase.testFilter |
5,434 | def testGChart(self):
try:
import pygooglechart
except __HOLE__:
print >> sys.stderr, "pygooglechart Python package not available - skipping logplot gchart unittest."
return
options = AttrDict({
'backend': 'gchart',
'output': Fa... | ImportError | dataset/ETHPy150Open adamhadani/logtools/logtools/test/test_logtools.py/PlotTestCase.testGChart |
5,435 | def absent(name):
'''
Ensures that the user group does not exist, eventually delete user group.
.. versionadded:: 2016.3.0
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/states/zabbix_usergroup.py/absent |
5,436 | def render(self, context):
try:
request = template.resolve_variable(self.request, context)
obj = template.resolve_variable(self.obj, context)
field = getattr(obj, self.field_name)
except (template.VariableDoesNotExist, __HOLE__):
return ''
try:
... | AttributeError | dataset/ETHPy150Open dcramer/django-ratings/djangoratings/templatetags/ratings.py/RatingByRequestNode.render |
5,437 | def render(self, context):
try:
user = template.resolve_variable(self.request, context)
obj = template.resolve_variable(self.obj, context)
field = getattr(obj, self.field_name)
except template.VariableDoesNotExist:
return ''
try:
vote =... | ObjectDoesNotExist | dataset/ETHPy150Open dcramer/django-ratings/djangoratings/templatetags/ratings.py/RatingByUserNode.render |
5,438 | def checkAuth(ip, port, title, version):
"""
"""
if title == TINTERFACES.MAN:
url = "http://{0}:{1}/manager/html".format(ip, port)
# check with given auth
if state.usr_auth:
(usr, pswd) = state.usr_auth.split(":")
return _auth(usr, pswd, url)
# els... | KeyboardInterrupt | dataset/ETHPy150Open hatRiot/clusterd/src/platform/tomcat/authenticate.py/checkAuth |
5,439 | def __init__(self, workflow):
super(Step, self).__init__()
self.workflow = workflow
cls = self.__class__.__name__
if not (self.action_class and issubclass(self.action_class, Action)):
raise AttributeError("You must specify an action for %s." % cls)
self.slug = self.... | ImportError | dataset/ETHPy150Open Havate/havate-openstack/proto-build/gui/horizon/Horizon_GUI/horizon/workflows/base.py/Step.__init__ |
5,440 | def _order_steps(self):
steps = list(copy.copy(self.default_steps))
additional = self._registry.keys()
for step in additional:
try:
min_pos = steps.index(step.after)
except __HOLE__:
min_pos = 0
try:
max_pos = st... | ValueError | dataset/ETHPy150Open Havate/havate-openstack/proto-build/gui/horizon/Horizon_GUI/horizon/workflows/base.py/Workflow._order_steps |
5,441 | @classmethod
def unregister(cls, step_class):
"""Unregisters a :class:`~horizon.workflows.Step` from the workflow.
"""
try:
cls._cls_registry.remove(step_class)
except __HOLE__:
raise base.NotRegistered('%s is not registered' % cls)
return cls._unregis... | KeyError | dataset/ETHPy150Open Havate/havate-openstack/proto-build/gui/horizon/Horizon_GUI/horizon/workflows/base.py/Workflow.unregister |
5,442 | def add_resource_path_alias(self,
alias_resource_path, existing_resource_path):
"""Add resource path alias.
Once added, request to alias_resource_path would be handled by
handler registered for existing_resource_path.
Args:
alias_resource_pat... | KeyError | dataset/ETHPy150Open google/pywebsocket/mod_pywebsocket/dispatch.py/Dispatcher.add_resource_path_alias |
5,443 | @property
def json(self):
"""
Return deserialized JSON body, if one included in the output
and is parseable.
"""
if not hasattr(self, '_json'):
self._json = None
# De-serialize JSON body if possible.
if COLOR in self:
# Col... | ValueError | dataset/ETHPy150Open jkbrzt/httpie/tests/utils.py/StrCLIResponse.json |
5,444 | def http(*args, **kwargs):
# noinspection PyUnresolvedReferences
"""
Run HTTPie and capture stderr/out and exit status.
Invoke `httpie.core.main()` with `args` and `kwargs`,
and return a `CLIResponse` subclass instance.
The return value is either a `StrCLIResponse`, or `BytesCLIResponse`
i... | SystemExit | dataset/ETHPy150Open jkbrzt/httpie/tests/utils.py/http |
5,445 | def parse(self, img_info_output):
"""Returns dictionary based on human-readable output from
`qemu-img info`
Known problem: breaks if path contains opening parenthesis `(` or
colon `:`"""
result = {}
for l in img_info_output.split('\n'):
if not l.strip():
... | ValueError | dataset/ETHPy150Open MirantisWorkloadMobility/CloudFerry/cloudferry/lib/utils/qemu_img.py/TextQemuImgInfoParser.parse |
5,446 | def parse(self, img_info_output):
try:
return json.loads(img_info_output)
except __HOLE__:
LOG.debug('Unable to convert json data: %s', img_info_output)
return {} | TypeError | dataset/ETHPy150Open MirantisWorkloadMobility/CloudFerry/cloudferry/lib/utils/qemu_img.py/JsonQemuImgInfoParser.parse |
5,447 | def get_auth_url():
'''
Try and get the URL from the config, else return localhost
'''
try:
return __opts__['keystone.auth_url']
except __HOLE__:
return 'http://localhost:35357/v2.0' | KeyError | dataset/ETHPy150Open saltstack/salt/salt/auth/keystone.py/get_auth_url |
5,448 | def add(self, read):
if self.tag in ['LENGTH', 'LEN']:
val = len(read.seq)
elif self.tag == 'MAPQ':
val = read.mapq
elif self.tag == 'MISMATCH':
val = read_calc_mismatches(read)
else:
try:
val = read.opt(self.tag)
... | KeyError | dataset/ETHPy150Open ngsutils/ngsutils/ngsutils/bam/stats.py/FeatureBin.add |
5,449 | def __init__(self, bamfile, gtf=None, region=None, delim=None, tags=[], show_all=False):
regiontagger = None
flag_counts = FlagCounts()
ref = None
start = None
end = None
if gtf:
regiontagger = RegionTagger(gtf, bamfile.references, only_first_fragment=True)
... | KeyError | dataset/ETHPy150Open ngsutils/ngsutils/ngsutils/bam/stats.py/BamStats.__init__ |
5,450 | def bam_stats(infiles, gtf_file=None, region=None, delim=None, tags=[], show_all=False, fillin_stats=True):
if gtf_file:
gtf = GTF(gtf_file)
else:
gtf = None
sys.stderr.write('Calculating Read stats...\n')
stats = [BamStats(bam_open(x), gtf, region, delim, tags, show_all=show_all) for ... | StopIteration | dataset/ETHPy150Open ngsutils/ngsutils/ngsutils/bam/stats.py/bam_stats |
5,451 | def mkdir(path):
try:
os.mkdir(path)
except __HOLE__:
pass | OSError | dataset/ETHPy150Open lisa-lab/pylearn2/doc/scripts/docgen.py/mkdir |
5,452 | def poll_results_check(self):
"""Check the polling results by checking to see if the stats queue is
empty. If it is not, try and collect stats. If it is set a timer to
call ourselves in _POLL_RESULTS_INTERVAL.
"""
LOGGER.debug('Checking for poll results')
while True:
... | ValueError | dataset/ETHPy150Open gmr/rejected/rejected/mcp.py/MasterControlProgram.poll_results_check |
5,453 | def remove_consumer_process(self, consumer, name):
"""Remove all details for the specified consumer and process name.
:param str consumer: The consumer name
:param str name: The process name
"""
my_pid = os.getpid()
for conn in self.consumers[consumer].connections:
... | OSError | dataset/ETHPy150Open gmr/rejected/rejected/mcp.py/MasterControlProgram.remove_consumer_process |
5,454 | def stop_processes(self):
"""Iterate through all of the consumer processes shutting them down."""
self.set_state(self.STATE_SHUTTING_DOWN)
LOGGER.info('Stopping consumer processes')
signal.signal(signal.SIGABRT, signal.SIG_IGN)
signal.signal(signal.SIGALRM, signal.SIG_IGN)
... | KeyboardInterrupt | dataset/ETHPy150Open gmr/rejected/rejected/mcp.py/MasterControlProgram.stop_processes |
5,455 | @staticmethod
def parse(value):
"""
Parse ``Accept-*`` style header.
Return iterator of ``(value, quality)`` pairs.
``quality`` defaults to 1.
"""
for match in part_re.finditer(','+value):
name = match.group(1)
if name == 'q':
... | ValueError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/webob-1.1.1/webob/acceptparse.py/Accept.parse |
5,456 | @staticmethod
def parse(value):
for mask, q in Accept.parse(value):
try:
mask_major, mask_minor = mask.split('/')
except __HOLE__:
continue
if mask_major == '*' and mask_minor != '*':
continue
yield (mask, q) | ValueError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/webob-1.1.1/webob/acceptparse.py/MIMEAccept.parse |
5,457 | def collect_error_snapshots():
"""Scheduled task to collect error snapshots from files and push into Error Snapshot table"""
if frappe.conf.disable_error_snapshot:
return
try:
path = get_error_snapshot_path()
if not os.path.exists(path):
return
for fname in os.listdir(path):
fullpath = os.path.join(p... | ValueError | dataset/ETHPy150Open frappe/frappe/frappe/utils/error.py/collect_error_snapshots |
5,458 | @responses.activate
def test_retrier_does_not_catch_unwanted_exception(self):
# Prepare
client = HubstorageClient(auth=self.auth, endpoint=self.endpoint, max_retries=2, max_retry_time=1)
job_metadata = {'project': self.projectid, 'spider': self.spidername, 'state': 'pending'}
callbac... | HTTPError | dataset/ETHPy150Open scrapinghub/python-hubstorage/tests/test_retry.py/RetryTest.test_retrier_does_not_catch_unwanted_exception |
5,459 | @responses.activate
def test_api_delete_can_be_set_to_non_idempotent(self):
# Prepare
client = HubstorageClient(auth=self.auth, endpoint=self.endpoint, max_retries=3, max_retry_time=1)
job_metadata = {'project': self.projectid, 'spider': self.spidername, 'state': 'pending'}
callback_... | HTTPError | dataset/ETHPy150Open scrapinghub/python-hubstorage/tests/test_retry.py/RetryTest.test_api_delete_can_be_set_to_non_idempotent |
5,460 | @responses.activate
def test_push_job_does_not_retry(self):
# Prepare
client = HubstorageClient(auth=self.auth, endpoint=self.endpoint, max_retries=3)
callback, attempts_count = self.make_request_callback(2, {'key': '1/2/3'})
self.mock_api(POST, callback=callback)
# Act
... | HTTPError | dataset/ETHPy150Open scrapinghub/python-hubstorage/tests/test_retry.py/RetryTest.test_push_job_does_not_retry |
5,461 | @responses.activate
def test_get_job_does_fails_if_no_retries(self):
# Prepare
client = HubstorageClient(auth=self.auth, endpoint=self.endpoint, max_retries=0)
job_metadata = {'project': self.projectid, 'spider': self.spidername, 'state': 'pending'}
callback, attempts_count = self.ma... | HTTPError | dataset/ETHPy150Open scrapinghub/python-hubstorage/tests/test_retry.py/RetryTest.test_get_job_does_fails_if_no_retries |
5,462 | @responses.activate
def test_get_job_does_fails_on_too_many_retries(self):
# Prepare
client = HubstorageClient(auth=self.auth, endpoint=self.endpoint, max_retries=2, max_retry_time=1)
job_metadata = {'project': self.projectid, 'spider': self.spidername, 'state': 'pending'}
callback, ... | HTTPError | dataset/ETHPy150Open scrapinghub/python-hubstorage/tests/test_retry.py/RetryTest.test_get_job_does_fails_on_too_many_retries |
5,463 | def import_module(name, deprecated=False):
"""Import and return the module to be tested, raising SkipTest if
it is not available.
If deprecated is True, any module or package deprecation messages
will be suppressed."""
with _ignore_deprecated_imports(deprecated):
try:
return imp... | ImportError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/test/support.py/import_module |
5,464 | def _save_and_block_module(name, orig_modules):
"""Helper function to save and block a module in sys.modules
Return True if the module was in sys.modules, False otherwise.
"""
saved = True
try:
orig_modules[name] = sys.modules[name]
except __HOLE__:
saved = False
sys.modules... | KeyError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/test/support.py/_save_and_block_module |
5,465 | def import_fresh_module(name, fresh=(), blocked=(), deprecated=False):
"""Import and return a module, deliberately bypassing sys.modules.
This function imports and returns a fresh copy of the named Python module
by removing the named module from sys.modules before doing the import.
Note that unlike relo... | ImportError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/test/support.py/import_fresh_module |
5,466 | def get_attribute(obj, name):
"""Get an attribute, raising SkipTest if AttributeError is raised."""
try:
attribute = getattr(obj, name)
except __HOLE__:
raise unittest.SkipTest("object %r has no attribute %r" % (obj, name))
else:
return attribute | AttributeError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/test/support.py/get_attribute |
5,467 | def unload(name):
try:
del sys.modules[name]
except __HOLE__:
pass | KeyError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/test/support.py/unload |
5,468 | def unlink(filename):
try:
_unlink(filename)
except __HOLE__ as error:
# The filename need not exist.
if error.errno not in (errno.ENOENT, errno.ENOTDIR):
raise | OSError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/test/support.py/unlink |
5,469 | def rmdir(dirname):
try:
_rmdir(dirname)
except __HOLE__ as error:
# The directory need not exist.
if error.errno != errno.ENOENT:
raise | OSError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/test/support.py/rmdir |
5,470 | def rmtree(path):
try:
_rmtree(path)
except __HOLE__ as error:
if error.errno != errno.ENOENT:
raise | OSError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/test/support.py/rmtree |
5,471 | def _requires_unix_version(sysname, min_version):
"""Decorator raising SkipTest if the OS is `sysname` and the version is less
than `min_version`.
For example, @_requires_unix_version('FreeBSD', (7, 2)) raises SkipTest if
the FreeBSD version is less than 7.2.
"""
def decorator(func):
@f... | ValueError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/test/support.py/_requires_unix_version |
5,472 | def requires_mac_ver(*min_version):
"""Decorator raising SkipTest if the OS is Mac OS X and the OS X
version if less than min_version.
For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version
is lesser than 10.5.
"""
def decorator(func):
@functools.wraps(func)
d... | ValueError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/test/support.py/requires_mac_ver |
5,473 | @contextlib.contextmanager
def temp_cwd(name='tempcwd', quiet=False, path=None):
"""
Context manager that temporarily changes the CWD.
An existing path may be provided as *path*, in which case this
function makes no changes to the file system.
Otherwise, the new CWD is created in the current direc... | OSError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/test/support.py/temp_cwd |
5,474 | @contextlib.contextmanager
def transient_internet(resource_name, timeout=30.0, errnos=()):
"""Return a context manager that raises ResourceDenied when various issues
with the Internet connection manifest themselves as exceptions."""
default_errnos = [
('ECONNREFUSED', 111),
('ECONNRESET', 10... | IOError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/test/support.py/transient_internet |
5,475 | def run_with_locale(catstr, *locales):
def decorator(func):
def inner(*args, **kwds):
try:
import locale
category = getattr(locale, catstr)
orig_locale = locale.setlocale(category)
except __HOLE__:
# if the test author g... | AttributeError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/test/support.py/run_with_locale |
5,476 | def run_with_tz(tz):
def decorator(func):
def inner(*args, **kwds):
try:
tzset = time.tzset
except __HOLE__:
raise unittest.SkipTest("tzset required")
if 'TZ' in os.environ:
orig_tz = os.environ['TZ']
else:
... | AttributeError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/test/support.py/run_with_tz |
5,477 | def start(self):
try:
f = open(self.procfile, 'r')
except __HOLE__ as e:
warnings.warn('/proc not available for stats: {0}'.format(e),
RuntimeWarning)
sys.stderr.flush()
return
watchdog_script = findfile("memory_watchdog.... | OSError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/test/support.py/_MemoryWatchdog.start |
5,478 | def can_symlink():
global _can_symlink
if _can_symlink is not None:
return _can_symlink
symlink_path = TESTFN + "can_symlink"
try:
os.symlink(TESTFN, symlink_path)
can = True
except (__HOLE__, NotImplementedError, AttributeError):
can = False
else:
os.remo... | OSError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/test/support.py/can_symlink |
5,479 | def can_xattr():
global _can_xattr
if _can_xattr is not None:
return _can_xattr
if not hasattr(os, "setxattr"):
can = False
else:
tmp_fp, tmp_name = tempfile.mkstemp()
try:
with open(TESTFN, "wb") as fp:
try:
# TESTFN & temp... | OSError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/test/support.py/can_xattr |
5,480 | def patch(test_instance, object_to_patch, attr_name, new_value):
"""Override 'object_to_patch'.'attr_name' with 'new_value'.
Also, add a cleanup procedure to 'test_instance' to restore
'object_to_patch' value for 'attr_name'.
The 'attr_name' should be a valid attribute for 'object_to_patch'.
"""
... | KeyError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/test/support.py/patch |
5,481 | def _IndexedScan(self, i, max_records=None):
"""Scan records starting with index i."""
if not self._index:
self._ReadIndex()
# The record number that we will read next.
idx = 0
# The timestamp that we will start reading from.
start_ts = 0
if i >= self._max_indexed:
start_ts = ma... | KeyError | dataset/ETHPy150Open google/grr/grr/lib/aff4_objects/sequential_collection.py/IndexedSequentialCollection._IndexedScan |
5,482 | def decode(self, payload):
try:
self.reason = ord(payload[0])
if self.reason == 1:
self.data = ord(payload[1])
elif self.reason == 2:
self.data = struct.unpack(">L", payload[1:])[0]
elif self.reason == 3:
self.data =... | TypeError | dataset/ETHPy150Open javgh/greenaddress-pos-tools/nfc/ndef/handover.py/HandoverError.decode |
5,483 | def encode(self):
try: payload = chr(self.reason)
except __HOLE__: raise EncodeError("error reason out of limits")
try:
if self.reason == 1:
payload += chr(self.data)
elif self.reason == 2:
payload += struct.pack(">L", self.data)
... | ValueError | dataset/ETHPy150Open javgh/greenaddress-pos-tools/nfc/ndef/handover.py/HandoverError.encode |
5,484 | def connect(self, receiver, sender=None, weak=True, dispatch_uid=None):
"""
Connect receiver to sender for signal.
Arguments:
receiver
A function or an instance method which is to receive signals.
Receivers must be hashable objects.
... | TypeError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/dispatch/dispatcher.py/Signal.connect |
5,485 | @property
def tables_involved(self):
"""A rreally ather rudimentary way to work out tables involved in a query.
TODO: Can probably parse the SQL using sqlparse etc and pull out table info that way?"""
components = [x.strip() for x in self.query.split()]
tables = []
for idx, ... | IndexError | dataset/ETHPy150Open django-silk/silk/silk/models.py/SQLQuery.tables_involved |
5,486 | def _get_system_paths(executable):
"""Return lists of standard lib and site paths for executable.
"""
# We want to get a list of the site packages, which is not easy.
# The canonical way to do this is to use
# distutils.sysconfig.get_python_lib(), but that only returns a
# single path, which doe... | ValueError | dataset/ETHPy150Open moraes/tipfy/manage/easy_install.py/_get_system_paths |
5,487 | def _get_version(executable):
try:
return _versions[executable]
except __HOLE__:
cmd = _safe_arg(executable) + ' -V'
p = subprocess.Popen(cmd,
shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,... | KeyError | dataset/ETHPy150Open moraes/tipfy/manage/easy_install.py/_get_version |
5,488 | def _write_script(full_name, contents, logged_type):
"""Write contents of script in full_name, logging the action.
The only tricky bit in this function is that it supports Windows by
creating exe files using a pkg_resources helper.
"""
generated = []
script_name = full_name
if is_win32:
... | AttributeError | dataset/ETHPy150Open moraes/tipfy/manage/easy_install.py/_write_script |
5,489 | def render(self, context):
if not include_is_allowed(self.filepath):
if settings.DEBUG:
return "[Didn't have permission to include file]"
else:
return '' # Fail silently for invalid includes.
try:
fp = open(self.filepath, 'r')
... | IOError | dataset/ETHPy150Open dcramer/django-compositepks/django/template/defaulttags.py/SsiNode.render |
5,490 | def render(self, context):
try:
value = self.val_expr.resolve(context)
maxvalue = self.max_expr.resolve(context)
except VariableDoesNotExist:
return ''
try:
value = float(value)
maxvalue = float(maxvalue)
ratio = (value / ma... | ValueError | dataset/ETHPy150Open dcramer/django-compositepks/django/template/defaulttags.py/WidthRatioNode.render |
5,491 | def do_if(parser, token):
"""
The ``{% if %}`` tag evaluates a variable, and if that variable is "true"
(i.e., exists, is not empty, and is not a false boolean value), the
contents of the block are output:
::
{% if athlete_list %}
Number of athletes: {{ athlete_list|count }}
... | ValueError | dataset/ETHPy150Open dcramer/django-compositepks/django/template/defaulttags.py/do_if |
5,492 | def widthratio(parser, token):
"""
For creating bar charts and such, this tag calculates the ratio of a given
value to a maximum value, and then applies that ratio to a constant.
For example::
<img src='bar.gif' height='10' width='{% widthratio this_value max_value 100 %}' />
Above, if ``... | ValueError | dataset/ETHPy150Open dcramer/django-compositepks/django/template/defaulttags.py/widthratio |
5,493 | @classmethod
def get_object(self, desc, value):
klass = desc['klass']
attr = desc['attr']
try:
if desc['prefetch']:
# build up relation cache
if klass not in self.relation_cache:
self.buildup_relation_cache(klass, attr, value... | ObjectDoesNotExist | dataset/ETHPy150Open pboehm/django-data-migration/data_migration/migration.py/Migration.get_object |
5,494 | @classmethod
def import_all(self, excludes=[]):
"""
this does an `from X import *` for all existing migration specs
"""
for app in self.possible_existing_migrations():
matches = [ ex for ex in excludes if ex in app ]
if len(matches) > 0:
conti... | AttributeError | dataset/ETHPy150Open pboehm/django-data-migration/data_migration/migration.py/Importer.import_all |
5,495 | def _run_job_in_hadoop(self):
for step_num in range(self._num_steps()):
step_args = self._args_for_step(step_num)
# log this *after* _args_for_step(), which can start a search
# for the Hadoop streaming jar
log.info('Running step %d of %d...' %
... | OSError | dataset/ETHPy150Open Yelp/mrjob/mrjob/hadoop.py/HadoopJobRunner._run_job_in_hadoop |
5,496 | def get_tokens_unprocessed(self, text, stack=('root',)):
""" Split ``text`` into (tokentype, text) pairs.
Monkeypatched to store the final stack on the object itself.
"""
pos = 0
tokendefs = self._tokens
if hasattr(self, '_saved_state_stack'):
statestack = list(self._saved_state_sta... | IndexError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/modes/pygments_sh.py/get_tokens_unprocessed |
5,497 | def set_mime_type(self, mime_type):
"""
Update the highlighter lexer based on a mime type.
:param mime_type: mime type of the new lexer to setup.
"""
try:
self.set_lexer_from_mime_type(mime_type)
except ClassNotFound:
_logger().exception('failed t... | ImportError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/modes/pygments_sh.py/PygmentsSH.set_mime_type |
5,498 | def set_lexer_from_filename(self, filename):
"""
Change the lexer based on the filename (actually only the extension is
needed)
:param filename: Filename or extension
"""
self._lexer = None
if filename.endswith("~"):
filename = filename[0:len(filename... | IndexError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/modes/pygments_sh.py/PygmentsSH.set_lexer_from_filename |
5,499 | def _get_format_from_style(self, token, style):
""" Returns a QTextCharFormat for token by reading a Pygments style.
"""
result = QtGui.QTextCharFormat()
try:
style = style.style_for_token(token)
except __HOLE__:
# fallback to plain text
style ... | KeyError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/modes/pygments_sh.py/PygmentsSH._get_format_from_style |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.