Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
2,500 | def test_patchobject_wont_create_by_default(self):
try:
@patch.object(SomeClass, 'ord', sentinel.Frooble)
def test():
self.fail('Patching non existent attributes should fail')
test()
except __HOLE__:
pass
else:
self.fai... | AttributeError | dataset/ETHPy150Open testing-cabal/mock/mock/tests/testpatch.py/PatchTest.test_patchobject_wont_create_by_default |
2,501 | def test_patch_with_exception(self):
foo = {}
@patch.dict(foo, {'a': 'b'})
def test():
raise NameError('Konrad')
try:
test()
except __HOLE__:
pass
else:
self.fail('NameError not raised by test')
self.assertEqual(fo... | NameError | dataset/ETHPy150Open testing-cabal/mock/mock/tests/testpatch.py/PatchTest.test_patch_with_exception |
2,502 | def get_contents(self):
if not settings.AWS_ENABLED:
try:
return open(self.local_filename).read()
except __HOLE__:
return ''
else:
return s3.read_file('source', self.s3_path) | IOError | dataset/ETHPy150Open pebble/cloudpebble/ide/models/files.py/SourceFile.get_contents |
2,503 | def copy_to_path(self, path):
if not settings.AWS_ENABLED:
try:
shutil.copy(self.local_filename, path)
except __HOLE__ as err:
if err.errno == 2:
open(path, 'w').close() # create the file if it's missing.
else:
... | IOError | dataset/ETHPy150Open pebble/cloudpebble/ide/models/files.py/SourceFile.copy_to_path |
2,504 | @receiver(post_delete)
def delete_file(sender, instance, **kwargs):
if sender == SourceFile or sender == ResourceVariant:
if settings.AWS_ENABLED:
try:
s3.delete_file('source', instance.s3_path)
except:
traceback.print_exc()
else:
t... | OSError | dataset/ETHPy150Open pebble/cloudpebble/ide/models/files.py/delete_file |
2,505 | @classmethod
def setupClass(cls):
global np
try:
import numpy as np
except __HOLE__:
raise SkipTest('NumPy not available.') | ImportError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/algorithms/centrality/tests/test_katz_centrality.py/TestKatzCentralityNumpy.setupClass |
2,506 | @classmethod
def setupClass(cls):
global np
try:
import numpy as np
except __HOLE__:
raise SkipTest('NumPy not available.') | ImportError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/algorithms/centrality/tests/test_katz_centrality.py/TestKatzCentralityDirectedNumpy.setupClass |
2,507 | @classmethod
def setupClass(cls):
global np
global eigvals
try:
import numpy as np
from numpy.linalg import eigvals
except __HOLE__:
raise SkipTest('NumPy not available.') | ImportError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/algorithms/centrality/tests/test_katz_centrality.py/TestKatzEigenvectorVKatz.setupClass |
2,508 | def save(self, **kwargs):
title = self.metadata.get('title')
slug = self.metadata.get('slug')
content = self.cleaned_data.get('content')
is_published = self.metadata.get('published')
image_id = self.metadata.get('image', '')
if self.instance.pk is not None:
a... | TypeError | dataset/ETHPy150Open gkmngrgn/radpress/radpress/forms.py/ZenModeForm.save |
2,509 | def setUp(self):
super(BaseTestCase, self).setUp()
self.app = create_app(test_settings)
self.client = self.app.test_client()
for app in self.app.installed_apps:
try:
__import__('%s.models' % app)
except __HOLE__:
pass
db = g... | ImportError | dataset/ETHPy150Open mozilla/standup/standup/tests/__init__.py/BaseTestCase.setUp |
2,510 | def testRmtreeNonExistingDir(self):
directory = 'nonexisting'
self.assertRaises(IOError, self.shutil.rmtree, directory)
try:
self.shutil.rmtree(directory, ignore_errors=True)
except __HOLE__:
self.fail('rmtree raised despite ignore_errors True') | IOError | dataset/ETHPy150Open jmcgeheeiv/pyfakefs/fake_filesystem_shutil_test.py/FakeShutilModuleTest.testRmtreeNonExistingDir |
2,511 | def testRmtreeNonExistingDirWithHandler(self):
class NonLocal: pass
def error_handler(_, path, error_info):
NonLocal.errorHandled = True
NonLocal.errorPath = path
directory = 'nonexisting'
NonLocal.errorHandled = False
NonLocal.errorPath = ''
try:
self.shutil.rmtree(directory,... | IOError | dataset/ETHPy150Open jmcgeheeiv/pyfakefs/fake_filesystem_shutil_test.py/FakeShutilModuleTest.testRmtreeNonExistingDirWithHandler |
2,512 | def main():
"""
Parse arguments and start the program
"""
# Iterate over all lines in all files
# listed in sys.argv[1:]
# or stdin if no args given.
try:
for line in fileinput.input():
# Look for an INSERT statement and parse it.
if is_insert(line):
... | KeyboardInterrupt | dataset/ETHPy150Open jamesmishra/mysqldump-to-csv/mysqldump_to_csv.py/main |
2,513 | def load_backend(self, name,
dumps='dumps', loads='loads', loads_exc=ValueError):
"""Load a JSON backend by name.
This method loads a backend and sets up references to that
backend's loads/dumps functions and exception classes.
:param dumps: is the name of the bac... | AttributeError | dataset/ETHPy150Open jsonpickle/jsonpickle/jsonpickle/backend.py/JSONBackend.load_backend |
2,514 | def _store(self, dct, backend, obj, name):
try:
dct[backend] = getattr(obj, name)
except __HOLE__:
self.remove_backend(backend)
return False
return True | AttributeError | dataset/ETHPy150Open jsonpickle/jsonpickle/jsonpickle/backend.py/JSONBackend._store |
2,515 | def create_structure_from_variable(self, dir_structure):
'''
create directory structure via given list of tuples (filename, content,)
content being None means it is directory
'''
for filename, content in dir_structure:
if content is None:
try:
... | OSError | dataset/ETHPy150Open ella/citools/tests/test_debian/__init__.py/TestVersionedStatic.create_structure_from_variable |
2,516 | @slow
@network
def test_wdi_download_w_retired_indicator(self):
cntry_codes = ['CA', 'MX', 'US']
# Despite showing up in the search feature, and being listed online,
# the api calls to GDPPCKD don't work in their own query builder, nor
# pandas module. GDPPCKD used to be a comm... | ValueError | dataset/ETHPy150Open pydata/pandas/pandas/io/tests/test_wb.py/TestWB.test_wdi_download_w_retired_indicator |
2,517 | @slow
@network
def test_wdi_download_w_crash_inducing_countrycode(self):
cntry_codes = ['CA', 'MX', 'US', 'XXX']
inds = ['NY.GDP.PCAP.CD']
try:
result = download(country=cntry_codes, indicator=inds,
start=2003, end=2004, errors='ignore')
... | ValueError | dataset/ETHPy150Open pydata/pandas/pandas/io/tests/test_wb.py/TestWB.test_wdi_download_w_crash_inducing_countrycode |
2,518 | def inner_run(self, *args, **options):
# If an exception was silenced in ManagementUtility.execute in order
# to be raised in the child process, raise it now.
autoreload.raise_last_exception()
threading = options['use_threading']
# 'shutdown_message' is a stealth option.
... | KeyError | dataset/ETHPy150Open django/django/django/core/management/commands/runserver.py/Command.inner_run |
2,519 | @staff_member_required
def view_detail(request, view):
if not utils.docutils_is_available:
return missing_docutils_page(request)
mod, func = urlresolvers.get_mod_func(view)
try:
view_func = getattr(import_module(mod), func)
except (ImportError, __HOLE__):
raise Http404
title... | AttributeError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/admindocs/views.py/view_detail |
2,520 | @staff_member_required
def model_detail(request, app_label, model_name):
if not utils.docutils_is_available:
return missing_docutils_page(request)
# Get the model class.
try:
app_mod = models.get_app(app_label)
except ImproperlyConfigured:
raise Http404(_("App %r not found") % a... | StopIteration | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/admindocs/views.py/model_detail |
2,521 | def load_all_installed_template_libraries():
# Load/register all template tag libraries from installed apps.
for module_name in template.get_templatetags_modules():
mod = import_module(module_name)
try:
libraries = [
os.path.splitext(p)[0]
for p in os.... | OSError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/admindocs/views.py/load_all_installed_template_libraries |
2,522 | def extract_views_from_urlpatterns(urlpatterns, base=''):
"""
Return a list of views from a list of urlpatterns.
Each object in the returned list is a two-tuple: (view_func, regex)
"""
views = []
for p in urlpatterns:
if hasattr(p, 'url_patterns'):
try:
patte... | ImportError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/admindocs/views.py/extract_views_from_urlpatterns |
2,523 | def __call__(self, environ, start_response):
"""Resolves the URL in PATH_INFO, and uses wsgi.routing_args
to pass on URL resolver results."""
old_method = None
if self.use_method_override:
req = None
# In some odd cases, there's no query string
try:
... | KeyError | dataset/ETHPy150Open bbangert/routes/routes/middleware.py/RoutesMiddleware.__call__ |
2,524 | def __getattr__(self, name):
try:
return object.__getattribute__(self, name)
except __HOLE__:
log.debug("No attribute called %s found on c object, returning "
"empty string", name)
return '' | AttributeError | dataset/ETHPy150Open Pylons/pylons/pylons/util.py/AttribSafeContextObj.__getattr__ |
2,525 | def path_hook(nvim):
def _get_paths():
return discover_runtime_directories(nvim)
def _find_module(fullname, oldtail, path):
idx = oldtail.find('.')
if idx > 0:
name = oldtail[:idx]
tail = oldtail[idx + 1:]
fmr = imp.find_module(name, path)
... | ImportError | dataset/ETHPy150Open neovim/python-client/neovim/plugin/script_host.py/path_hook |
2,526 | def check_fun_data(self, testfunc, targfunc, testarval, targarval,
targarnanval, **kwargs):
for axis in list(range(targarval.ndim)) + [None]:
for skipna in [False, True]:
targartempval = targarval if skipna else targarnanval
try:
... | ValueError | dataset/ETHPy150Open pydata/pandas/pandas/tests/test_nanops.py/TestnanopsDataFrame.check_fun_data |
2,527 | def check_funs(self, testfunc, targfunc, allow_complex=True,
allow_all_nan=True, allow_str=True, allow_date=True,
allow_tdelta=True, allow_obj=True, **kwargs):
self.check_fun(testfunc, targfunc, 'arr_float', **kwargs)
self.check_fun(testfunc, targfunc, 'arr_float_na... | TypeError | dataset/ETHPy150Open pydata/pandas/pandas/tests/test_nanops.py/TestnanopsDataFrame.check_funs |
2,528 | def check_nancomp(self, checkfun, targ0):
arr_float = self.arr_float
arr_float1 = self.arr_float1
arr_nan = self.arr_nan
arr_nan_nan = self.arr_nan_nan
arr_float_nan = self.arr_float_nan
arr_float1_nan = self.arr_float1_nan
arr_nan_float1 = self.arr_nan_float1
... | ValueError | dataset/ETHPy150Open pydata/pandas/pandas/tests/test_nanops.py/TestnanopsDataFrame.check_nancomp |
2,529 | def check_bool(self, func, value, correct, *args, **kwargs):
while getattr(value, 'ndim', True):
try:
res0 = func(value, *args, **kwargs)
if correct:
self.assertTrue(res0)
else:
self.assertFalse(res0)
... | ValueError | dataset/ETHPy150Open pydata/pandas/pandas/tests/test_nanops.py/TestnanopsDataFrame.check_bool |
2,530 | def get_config(self, connection_info, disk_info):
"""Returns xml for libvirt."""
conf = super(LibvirtNetVolumeDriver,
self).get_config(connection_info, disk_info)
netdisk_properties = connection_info['data']
conf.source_type = "network"
conf.source_protocol ... | KeyError | dataset/ETHPy150Open openstack/nova/nova/virt/libvirt/volume/net.py/LibvirtNetVolumeDriver.get_config |
2,531 | def install(self, plugin):
archive = self._download(plugin)
prefix = archive.getnames()[0]
dirname = ''.join((self._path, plugin))
directories = conf.supybot.directories.plugins()
directory = self._getWritableDirectoryFromList(directories)
assert directory is not None, \
... | ImportError | dataset/ETHPy150Open ProgVal/Limnoria/plugins/PluginDownloader/plugin.py/GithubRepository.install |
2,532 | def _write_options(name, configuration):
'''
Writes a new OPTIONS file
'''
_check_portname(name)
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
dirname = _options_dir(name)
if not os.path.isdir(dirname):
try:
os.makedirs(dirname)
except __HOLE... | OSError | dataset/ETHPy150Open saltstack/salt/salt/modules/freebsdports.py/_write_options |
2,533 | def showconfig(name, default=False, dict_return=False):
'''
Show the configuration options for a given port.
default : False
Show the default options for a port (not necessarily the same as the
current configuration)
dict_return : False
Instead of returning the output of ``make... | IndexError | dataset/ETHPy150Open saltstack/salt/salt/modules/freebsdports.py/showconfig |
2,534 | def config(name, reset=False, **kwargs):
'''
Modify configuration options for a given port. Multiple options can be
specified. To see the available options for a port, use
:mod:`ports.showconfig <salt.modules.freebsdports.showconfig>`.
name
The port name, in ``category/name`` format
re... | TypeError | dataset/ETHPy150Open saltstack/salt/salt/modules/freebsdports.py/config |
2,535 | def update(extract=False):
'''
Update the ports tree
extract : False
If ``True``, runs a ``portsnap extract`` after fetching, should be used
for first-time installation of the ports tree.
CLI Example:
.. code-block:: bash
salt '*' ports.update
'''
result = __salt_... | AttributeError | dataset/ETHPy150Open saltstack/salt/salt/modules/freebsdports.py/update |
2,536 | def get_object(self, request, object_id):
"""
Returns an instance matching the primary key provided. ``None`` is
returned if no match is found (or the object_id failed validation
against the primary key field).
"""
queryset = self.get_queryset(request)
model = qu... | ValidationError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/contrib/admin/options.py/ModelAdmin.get_object |
2,537 | def get_action(self, action):
"""
Return a given action from a parameter, which can either be a callable,
or the name of a method on the ModelAdmin. Return is a tuple of
(callable, name, description).
"""
# If the action is a callable, just use it.
if callable(ac... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/contrib/admin/options.py/ModelAdmin.get_action |
2,538 | def message_user(self, request, message, level=messages.INFO, extra_tags='',
fail_silently=False):
"""
Send a message to the user. The default implementation
posts a message using the django.contrib.messages backend.
Exposes almost the same API as messages.add_messa... | AttributeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/contrib/admin/options.py/ModelAdmin.message_user |
2,539 | def response_action(self, request, queryset):
"""
Handle an admin action. This is called if a request is POSTed to the
changelist; it returns an HttpResponse if the action was handled, and
None otherwise.
"""
# There can be multiple action forms on the page (at the top
... | ValueError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/contrib/admin/options.py/ModelAdmin.response_action |
2,540 | def add(path, index=0):
'''
Add the directory to the SYSTEM path in the index location
Returns:
boolean True if successful, False if unsuccessful
CLI Example:
.. code-block:: bash
# Will add to the beginning of the path
salt '*' win_path.add 'c:\\python27' 0
# Wi... | ValueError | dataset/ETHPy150Open saltstack/salt/salt/modules/win_path.py/add |
2,541 | def remove(path):
r'''
Remove the directory from the SYSTEM path
Returns:
boolean True if successful, False if unsuccessful
CLI Example:
.. code-block:: bash
# Will remove C:\Python27 from the path
salt '*' win_path.remove 'c:\\python27'
'''
path = _normalize_dir(... | ValueError | dataset/ETHPy150Open saltstack/salt/salt/modules/win_path.py/remove |
2,542 | def drain_consumer(consumer, limit=1, timeout=None, callbacks=None):
acc = deque()
def on_message(body, message):
acc.append((body, message))
consumer.callbacks = [on_message] + (callbacks or [])
with consumer:
for _ in eventloop(consumer.channel.connection.client,
... | IndexError | dataset/ETHPy150Open celery/kombu/kombu/common.py/drain_consumer |
2,543 | def test_builtin_sequence_types(self):
# a collection of tests on builtin sequence types
a = range(10)
for i in a:
self.assertIn(i, a)
self.assertNotIn(16, a)
self.assertNotIn(a, a)
a = tuple(a)
for i in a:
self.assertIn(i, a)
self... | TypeError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_contains.py/TestContains.test_builtin_sequence_types |
2,544 | def to_number(self, value):
"""
Transform categorical value to the ordinal. Raises ValueError if value is not in self.value_list
"""
try:
return list(self.value_list).index(value)
except __HOLE__ as e:
if self.map_missing_to:
return self.ma... | ValueError | dataset/ETHPy150Open alex-pirozhenko/sklearn-pmml/sklearn_pmml/convert/features.py/CategoricalFeature.to_number |
2,545 | def mayaInit(forversion=None) :
""" Try to init Maya standalone module, use when running pymel from an external Python inerpreter,
it is possible to pass the desired Maya version number to define which Maya to initialize
Part of the complexity of initializing maya in standalone mode is that maya does not ... | ImportError | dataset/ETHPy150Open CountZer0/PipelineConstructionSet/python/maya/site-packages/pymel-1.0.3/pymel/internal/startup.py/mayaInit |
2,546 | def initMEL():
if 'PYMEL_SKIP_MEL_INIT' in os.environ or pymel_options.get( 'skip_mel_init', False ) :
_logger.info( "Skipping MEL initialization" )
return
_logger.debug( "initMEL" )
mayaVersion = versions.installName()
prefsDir = getUserPrefsDir()
if prefsDir is None:
_logg... | RuntimeError | dataset/ETHPy150Open CountZer0/PipelineConstructionSet/python/maya/site-packages/pymel-1.0.3/pymel/internal/startup.py/initMEL |
2,547 | def initAE():
try:
pkg = __import__('AETemplates')
except __HOLE__:
return False
except Exception:
import traceback
traceback.print_exc()
return False
else:
# import subpackages
for data in subpackages(pkg):
pass
return True | ImportError | dataset/ETHPy150Open CountZer0/PipelineConstructionSet/python/maya/site-packages/pymel-1.0.3/pymel/internal/startup.py/initAE |
2,548 | def encodeFix():
if mayaInit() :
from maya.cmds import about
mayaEncode = about(cs=True)
pyEncode = sys.getdefaultencoding() # Encoding tel que defini par sitecustomize
if mayaEncode != pyEncode : # s'il faut redefinir l'encoding
#reload (sys) ... | ImportError | dataset/ETHPy150Open CountZer0/PipelineConstructionSet/python/maya/site-packages/pymel-1.0.3/pymel/internal/startup.py/encodeFix |
2,549 | def DownloadDir(aff4_path, output_dir, bufsize=8192, preserve_path=True):
"""Take an aff4 path and download all files in it to output_dir.
Args:
aff4_path: Any aff4 path as a string
output_dir: A local directory to write to, will be created if not there.
bufsize: Buffer size to use.
preserve_path: ... | IOError | dataset/ETHPy150Open google/grr/grr/lib/console_utils.py/DownloadDir |
2,550 | @staticmethod
def FindPathByUuid(path, uuid, arch):
def ViewfinderPath(uuid):
p = os.path.join(_VIEWFINDER_DSYMS_UUID_PATH, uuid)
if not os.path.exists(p):
return None
p = open(p).read().strip();
if not p:
return None
return os.path.join(_VIEWFINDER_DSYMS_PATH, p, _VI... | StopIteration | dataset/ETHPy150Open viewfinderco/viewfinder/clients/ios/scripts/symbolicator.py/Symbolicator.FindPathByUuid |
2,551 | @staticmethod
def ParseBinaryImageLine(line):
elements = iter(line.split())
start_address = elements.next()
elements.next() # Hyphen
end_address = elements.next()
# The main(?) executable has plus sign before its bundle ID. Strip this off.
bundle_id = elements.next().strip('+')
arch = elem... | StopIteration | dataset/ETHPy150Open viewfinderco/viewfinder/clients/ios/scripts/symbolicator.py/Symbolicator.ParseBinaryImageLine |
2,552 | def start(self):
'''
Start the magic!!
'''
if self.opts['master_too']:
master_swarm = MasterSwarm(self.opts)
master_swarm.start()
minions = MinionSwarm(self.opts)
minions.start_minions()
print('Starting minions...')
#self.start_mini... | KeyboardInterrupt | dataset/ETHPy150Open saltstack/salt/tests/minionswarm.py/Swarm.start |
2,553 | def clean_configs(self):
'''
Clean up the config files
'''
for path in self.confs:
pidfile = '{0}.pid'.format(path)
try:
try:
pid = int(open(pidfile).read().strip())
os.kill(pid, signal.SIGTERM)
... | ValueError | dataset/ETHPy150Open saltstack/salt/tests/minionswarm.py/Swarm.clean_configs |
2,554 | def load(self, file_obj, header=True, **kwargs):
count = 0
reader = csv.reader(file_obj, **kwargs)
if header:
try:
header_keys = next(reader)
except __HOLE__:
return count
if self.strict:
header_fields = []
... | StopIteration | dataset/ETHPy150Open coleifer/peewee/playhouse/dataset.py/CSVImporter.load |
2,555 | def parse_request(self, request):
try:
request = anyjson.deserialize(request['data'])
except __HOLE__, e:
logging.error("Request dictionary contains no 'data' key")
return self.encode_result((500, "Internal error with request"))
except Exception, e:
... | KeyError | dataset/ETHPy150Open rackerlabs/openstack-guest-agents-unix/plugins/jsonparser.py/JsonParser.parse_request |
2,556 | def _import_hook(self, fqname, globals=None, locals=None, fromlist=None,
level=-1):
"""Python calls this hook to locate and import a module."""
parts = fqname.split('.')
#print "_import_hook", parts
# pyjamas-gtk hack
if parts[0] in ['gtk', 'gdk', 'py... | KeyError | dataset/ETHPy150Open anandology/pyjamas/pyjd/imputil.py/ImportManager._import_hook |
2,557 | def _import_one(self, parent, modname, fqname):
"Import a single module."
# has the module already been imported?
try:
return sys.modules[fqname]
except __HOLE__:
pass
# load the module's code, or fetch the module itself
result = self.get_code(pa... | KeyError | dataset/ETHPy150Open anandology/pyjamas/pyjd/imputil.py/Importer._import_one |
2,558 | def _compile(pathname, timestamp):
"""Compile (and cache) a Python source file.
The file specified by <pathname> is compiled to a code object and
returned.
Presuming the appropriate privileges exist, the bytecodes will be
saved back to the filesystem for future imports. The source file's
modif... | IOError | dataset/ETHPy150Open anandology/pyjamas/pyjd/imputil.py/_compile |
2,559 | def _os_path_isdir(pathname):
"Local replacement for os.path.isdir()."
try:
s = _os_stat(pathname)
except __HOLE__:
return None
return (s.st_mode & 0170000) == 0040000 | OSError | dataset/ETHPy150Open anandology/pyjamas/pyjd/imputil.py/_os_path_isdir |
2,560 | def _timestamp(pathname):
"Return the file modification time as a Long."
try:
s = _os_stat(pathname)
except __HOLE__:
return None
return long(s.st_mtime)
######################################################################
#
# Emulate the import mechanism for builtin and frozen modul... | OSError | dataset/ETHPy150Open anandology/pyjamas/pyjd/imputil.py/_timestamp |
2,561 | def _import_pathname(self, pathname, fqname):
if _os_path_isdir(pathname):
result = self._import_pathname(_os_path_join(pathname, '__init__'),
fqname)
if result:
values = result[2]
values['__pkgdir__'] = pathname
... | OSError | dataset/ETHPy150Open anandology/pyjamas/pyjd/imputil.py/_FilesystemImporter._import_pathname |
2,562 | def get_wordfile():
for fn in WORDFILES:
try:
wordfile = UserFile.open(fn, "r")
except __HOLE__:
pass
else:
return wordfile
raise ValueError("cannot find file of words.") | IOError | dataset/ETHPy150Open kdart/pycopia/aid/pycopia/words.py/get_wordfile |
2,563 | def set_logging(log, loglevelnum, logfile, verbose_console=False):
"""Configure standard logging for the application. One ERROR level handler to stderr and one file handler with specified loglevelnum to logfile.
log argument is the main (parent) application logger.
"""
# Prevent common error in usin... | IOError | dataset/ETHPy150Open securitykiss-com/rfw/rfw/config.py/set_logging |
2,564 | def get_task_args(self):
try:
body = self.request.body
options = json_decode(body) if body else {}
except __HOLE__ as e:
raise HTTPError(400, str(e))
args = options.pop('args', [])
kwargs = options.pop('kwargs', {})
if not isinstance(args, (li... | ValueError | dataset/ETHPy150Open mher/flower/flower/api/tasks.py/BaseTaskHandler.get_task_args |
2,565 | def normalize_options(self, options):
if 'eta' in options:
options['eta'] = datetime.strptime(options['eta'],
self.DATE_FORMAT)
if 'countdown' in options:
options['countdown'] = float(options['countdown'])
if 'expires' in opt... | ValueError | dataset/ETHPy150Open mher/flower/flower/api/tasks.py/BaseTaskHandler.normalize_options |
2,566 | def safe_result(self, result):
"returns json encodable result"
try:
json.dumps(result)
except __HOLE__:
return repr(result)
else:
return result | TypeError | dataset/ETHPy150Open mher/flower/flower/api/tasks.py/BaseTaskHandler.safe_result |
2,567 | @web.authenticated
@web.asynchronous
def post(self, taskname):
"""
Execute a task by name and wait results
**Example request**:
.. sourcecode:: http
POST /api/task/apply/tasks.add HTTP/1.1
Accept: application/json
Accept-Encoding: gzip, deflate, compress
Content-Length: 16
Content-Type: app... | ValueError | dataset/ETHPy150Open mher/flower/flower/api/tasks.py/TaskApply.post |
2,568 | @web.authenticated
def post(self, taskname):
"""
Execute a task
**Example request**:
.. sourcecode:: http
POST /api/task/async-apply/tasks.add HTTP/1.1
Accept: application/json
Accept-Encoding: gzip, deflate, compress
Content-Length: 16
Content-Type: application/json; charset=utf-8
Host: loca... | ValueError | dataset/ETHPy150Open mher/flower/flower/api/tasks.py/TaskAsyncApply.post |
2,569 | def _volume_offset_changed(self, event):
"""
Called when the user inputs text in this panel to
change the volume offset.
"""
new_value = self._volume_offset_text.GetValue()
try:
new_value = int(new_value)
self._model.set_volume_offset(new_value)
... | ValueError | dataset/ETHPy150Open williballenthin/INDXParse/MFTView.py/DiskGeometryWarningPanel._volume_offset_changed |
2,570 | def _cluster_size_changed(self, event):
"""
Called when the user inputs text in this panel to
change the cluster size.
"""
new_value = self._cluster_size_text.GetValue()
try:
new_value = int(new_value)
self._model.set_cluster_size(new_value)
... | ValueError | dataset/ETHPy150Open williballenthin/INDXParse/MFTView.py/DiskGeometryWarningPanel._cluster_size_changed |
2,571 | def __init__(self, *args, **kwargs):
self._model = kwargs.get("model", None)
try:
del kwargs["model"]
except __HOLE__:
pass
super(RecordPane, self).__init__(*args, **kwargs)
self._sizer = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self._sizer)
... | KeyError | dataset/ETHPy150Open williballenthin/INDXParse/MFTView.py/RecordPane.__init__ |
2,572 | def unicode_strings(buf, n=4):
reg = b"((?:[%s]\x00){4,})" % (ascii_byte)
ascii_re = re.compile(reg)
for match in ascii_re.finditer(buf):
try:
yield match.group().decode("utf-16")
except __HOLE__:
print "unicode find error: " + str(match.group())
pass | UnicodeDecodeError | dataset/ETHPy150Open williballenthin/INDXParse/MFTView.py/unicode_strings |
2,573 | def update(self, event):
self._sizer.Clear()
self.DestroyChildren()
has_runlists = False
for attr in self._model.record().attributes():
if attr.type() == ATTR_TYPE.DATA:
if attr.non_resident():
for (_, __) in attr.runlist().runs():
... | IndexError | dataset/ETHPy150Open williballenthin/INDXParse/MFTView.py/RecordDataPane.update |
2,574 | @_lazy_load
def _get_sendfile():
try:
from importlib import import_module
except __HOLE__:
from django.utils.importlib import import_module
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
backend = getattr(settings, 'SENDFILE_BACKEND', None)
... | ImportError | dataset/ETHPy150Open johnsensible/django-sendfile/sendfile/__init__.py/_get_sendfile |
2,575 | def sendfile(request, filename, attachment=False, attachment_filename=None, mimetype=None, encoding=None):
'''
create a response to send file using backend configured in SENDFILE_BACKEND
If attachment is True the content-disposition header will be set.
This will typically prompt the user to download th... | ImportError | dataset/ETHPy150Open johnsensible/django-sendfile/sendfile/__init__.py/sendfile |
2,576 | def get_object_fallback(cls, title, locale, default=None, **kwargs):
"""Return an instance of cls matching title and locale, or fall
back to the default locale.
When falling back to the default locale, follow any wiki redirects
internally.
If the fallback fails, the return value is `default`.
... | IOError | dataset/ETHPy150Open mozilla/kitsune/kitsune/sumo/parser.py/get_object_fallback |
2,577 | def feed(request, url, feed_dict=None):
"""Provided for backwards compatibility."""
if not feed_dict:
raise Http404(_("No feeds are registered."))
slug = url.partition('/')[0]
try:
f = feed_dict[slug]
except __HOLE__:
raise Http404(_("Slug %r isn't registered.") % slug)
... | KeyError | dataset/ETHPy150Open django/django/django/contrib/gis/views.py/feed |
2,578 | def get_ordered_insertion_target(self, node, parent):
"""
Attempts to retrieve a suitable right sibling for ``node``
underneath ``parent`` (which may be ``None`` in the case of root
nodes) so that ordering by the fields specified by the node's class'
``order_insertion_by`` option... | IndexError | dataset/ETHPy150Open django-mptt/django-mptt/mptt/models.py/MPTTOptions.get_ordered_insertion_target |
2,579 | def __new__(meta, class_name, bases, class_dict):
"""
Create subclasses of MPTTModel. This:
- adds the MPTT fields to the class
- adds a TreeManager to the model
"""
if class_name == 'NewBase' and class_dict == {}:
return super(MPTTModelBase, meta).__new__(m... | NameError | dataset/ETHPy150Open django-mptt/django-mptt/mptt/models.py/MPTTModelBase.__new__ |
2,580 | @classmethod
def register(meta, cls, **kwargs):
"""
For the weird cases when you need to add tree-ness to an *existing*
class. For other cases you should subclass MPTTModel instead of calling this.
"""
if not issubclass(cls, models.Model):
raise ValueError(_("reg... | NameError | dataset/ETHPy150Open django-mptt/django-mptt/mptt/models.py/MPTTModelBase.register |
2,581 | def save(self, *args, **kwargs):
"""
If this is a new node, sets tree fields up before it is inserted
into the database, making room in the tree structure as neccessary,
defaulting to making the new node the last child of its parent.
It the node's left and right edge indicators ... | IndexError | dataset/ETHPy150Open django-mptt/django-mptt/mptt/models.py/MPTTModel.save |
2,582 | @blueprint.route("/magic/<pattern>.jpg")
def image(pattern):
"""Get the first matching image."""
# TODO: share this logic
text = Text(pattern)
items = []
for template in app.template_service.all():
ratio, path = template.match(str(text).lower())
if not ratio:
continue
... | ValueError | dataset/ETHPy150Open jacebrowning/memegen/memegen/routes/magic.py/image |
2,583 | def test(self):
self.assertTrue('/test_var/structure variable' in self.h5file)
self.h5file.close()
# Do a copy to a temporary to avoid modifying the original file
h5fname_copy = tempfile.mktemp(".h5")
shutil.copy(self.h5fname, h5fname_copy)
# Reopen in 'a'ppend mode
... | IOError | dataset/ETHPy150Open PyTables/PyTables/tables/tests/test_hdf5compat.py/ContiguousCompoundAppendTestCase.test |
2,584 | @task
def watch_docs():
"""Run build the docs when a file changes."""
try:
import sphinx_autobuild # noqa
except __HOLE__:
print('ERROR: watch task requires the sphinx_autobuild package.')
print('Install it with:')
print(' pip install sphinx-autobuild')
sys.exit(1... | ImportError | dataset/ETHPy150Open marshmallow-code/marshmallow/tasks.py/watch_docs |
2,585 | def test_backend(self):
b = DatabaseBackend(app=app)
tid = gen_unique_id()
self.assertEqual(b.get_status(tid), states.PENDING)
self.assertIsNone(b.get_result(tid))
b.mark_as_done(tid, 42)
self.assertEqual(b.get_status(tid), states.SUCCESS)
self.assertEqual(b.get... | KeyError | dataset/ETHPy150Open celery/django-celery/djcelery/tests/test_backends/test_database.py/TestDatabaseBackend.test_backend |
2,586 | def tearDown(self):
if self.timing:
elapsed = time.time() - self.begun
with open(TIMING_FILE, "r") as jj:
try:
times = json.load(jj)
except __HOLE__:
times = []
times.append((elapsed, self._testMethod... | ValueError | dataset/ETHPy150Open rackspace/pyrax/tests/unit/base_test.py/BaseTest.tearDown |
2,587 | def __init__(self, request):
super(CMSToolbar, self).__init__()
self.right_items = []
self.left_items = []
self.populated = False
self.post_template_populated = False
self.menus = {}
self.obj = None
self.redirect_url = None
self.request = None
... | TypeError | dataset/ETHPy150Open divio/django-cms/cms/toolbar/toolbar.py/CMSToolbar.__init__ |
2,588 | def handle(self, *args, **options):
if not options["tos"]:
raise CommandError("""You must confirm that this user has accepted the
Terms of Service by passing --this-user-has-accepted-the-tos.""")
if not options["domain"]:
raise CommandError("""Please specify a realm by passing -... | KeyError | dataset/ETHPy150Open zulip/zulip/zerver/management/commands/create_user.py/Command.handle |
2,589 | def _check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None,
profile=None):
data = __salt__['boto_vpc.get_id'](name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
try:
return data.get('id')
except __HOLE__:
... | TypeError | dataset/ETHPy150Open saltstack/salt/salt/modules/boto_secgroup.py/_check_vpc |
2,590 | def get_python_exec(ver):
"""Return the executable of python for the given version."""
# XXX Check that the file actually exists
try:
return PYEXECS[ver]
except __HOLE__:
raise ValueError("Version %s not supported/recognized" % ver) | KeyError | dataset/ETHPy150Open scipy/scipy/tools/win32/build_scripts/pavement.py/get_python_exec |
2,591 | def raw_build_sdist(cwd):
cmd = ["python", "setup.py", "sdist", "--format=zip"]
build_log = "sdist.log"
f = open(build_log, 'w')
try:
try:
st = subprocess.call(cmd, #shell = True,
stderr = subprocess.STDOUT, stdout = f,
cwd=cwd... | RuntimeError | dataset/ETHPy150Open scipy/scipy/tools/win32/build_scripts/pavement.py/raw_build_sdist |
2,592 | def raw_build_arch(pyver, arch, src_root):
scipy_verstr = get_scipy_version(src_root)
bdir = bootstrap_dir(pyver)
print "Building scipy (version %s) binary for python %s, arch is %s" % \
(scipy_verstr, get_python_exec(pyver), arch)
if BUILD_MSI:
cmd = [get_python_exec(pyver), "setup.... | RuntimeError | dataset/ETHPy150Open scipy/scipy/tools/win32/build_scripts/pavement.py/raw_build_arch |
2,593 | def pick(self): # <5>
try:
return self._items.pop()
except __HOLE__:
raise LookupError('pick from empty BingoCage') | IndexError | dataset/ETHPy150Open fluentpython/example-code/11-iface-abc/bingo.py/BingoCage.pick |
2,594 | def seed(self, a=None):
# """Initialize internal state from hashable object.
# None or no argument seeds from current time or from an operating
# system specific randomness source if available.
# If a is not None or an int or long, hash(a) is used instead.
# """
if a is ... | NotImplementedError | dataset/ETHPy150Open anandology/pyjamas/pyjs/src/pyjs/lib/random.py/Random.seed |
2,595 | def setstate(self, state):
# """Restore internal state from object returned by getstate()."""
version = state[0]
if version == 3:
version, internalstate, self.gauss_next = state
super(Random, self).setstate(internalstate)
elif version == 2:
version, in... | ValueError | dataset/ETHPy150Open anandology/pyjamas/pyjs/src/pyjs/lib/random.py/Random.setstate |
2,596 | def _randbelow(self, n, _log=_log, fint=int, _maxwidth=1L<<BPF):
#def _randbelow(self, n, _log=_log, int=int, _maxwidth=1L<<BPF,
# _Method=_MethodType, _BuiltinMethod=_BuiltinMethodType):
# """Return a random int in the range [0,n)
# Handles the case where n has more bits than retu... | AttributeError | dataset/ETHPy150Open anandology/pyjamas/pyjs/src/pyjs/lib/random.py/Random._randbelow |
2,597 | def seed(self, a=None):
# """Initialize internal state from hashable object.
#
# None or no argument seeds from current time or from an operating
# system specific randomness source if available.
#
# If a is not None or an int or long, hash(a) is used instead.
#
# If a is an i... | NotImplementedError | dataset/ETHPy150Open anandology/pyjamas/pyjs/src/pyjs/lib/random.py/WichmannHill.seed |
2,598 | def guess_external_ip():
gateways = netifaces.gateways()
try:
ifnet = gateways['default'][netifaces.AF_INET][1]
return netifaces.ifaddresses(ifnet)[netifaces.AF_INET][0]['addr']
except (__HOLE__, IndexError):
return | KeyError | dataset/ETHPy150Open deliveryhero/lymph/lymph/utils/sockets.py/guess_external_ip |
2,599 | def create_socket(host, family=socket.AF_INET, type=socket.SOCK_STREAM,
backlog=2048, blocking=True, inheritable=False):
if family == socket.AF_UNIX and not host.startswith('unix:'):
raise ValueError('Your host needs to have the unix:/path form')
if host.startswith('unix:'):
fa... | OSError | dataset/ETHPy150Open deliveryhero/lymph/lymph/utils/sockets.py/create_socket |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.