Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
8,600 | def initial_context(self, request, *args, **kwargs):
context = super(ZoomableView, self).initial_context(request,
*args, **kwargs)
try:
zoom = int(request.GET['zoom'])
except (KeyError, __HOLE__):
zoom = self.def... | ValueError | dataset/ETHPy150Open mollyproject/mollyproject/molly/utils/views.py/ZoomableView.initial_context |
8,601 | def ReverseView(request):
from molly.auth.views import SecureView
try:
name = request.GET['name']
args = request.GET.getlist('arg')
path = reverse(name, args=args)
view, view_args, view_kwargs = resolve(path)
is_secure = isinstance(view, SecureView) and not sett... | KeyError | dataset/ETHPy150Open mollyproject/mollyproject/molly/utils/views.py/ReverseView |
8,602 | def Load(self, kind, data):
"""Parses CSV data, uses a Loader to convert to entities, and stores them.
On error, fails fast. Returns a "bad request" HTTP response code and
includes the traceback in the output.
Args:
kind: a string containing the entity kind that this loader handles
data: a... | KeyError | dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/google/appengine/ext/bulkload/__init__.py/BulkLoad.Load |
8,603 | def parse_isotime(timestr):
"""Parse time from ISO 8601 format."""
try:
return iso8601.parse_date(timestr)
except iso8601.ParseError as e:
raise ValueError(six.text_type(e))
except __HOLE__ as e:
raise ValueError(six.text_type(e)) | TypeError | dataset/ETHPy150Open openstack/python-monascaclient/monascaclient/openstack/common/timeutils.py/parse_isotime |
8,604 | def utcnow():
"""Overridable version of utils.utcnow."""
if utcnow.override_time:
try:
return utcnow.override_time.pop(0)
except __HOLE__:
return utcnow.override_time
return datetime.datetime.utcnow() | AttributeError | dataset/ETHPy150Open openstack/python-monascaclient/monascaclient/openstack/common/timeutils.py/utcnow |
8,605 | def advance_time_delta(timedelta):
"""Advance overridden time using a datetime.timedelta."""
assert(utcnow.override_time is not None)
try:
for dt in utcnow.override_time:
dt += timedelta
except __HOLE__:
utcnow.override_time += timedelta | TypeError | dataset/ETHPy150Open openstack/python-monascaclient/monascaclient/openstack/common/timeutils.py/advance_time_delta |
8,606 | def total_seconds(delta):
"""Return the total seconds of datetime.timedelta object.
Compute total seconds of datetime.timedelta, datetime.timedelta
doesn't have method total_seconds in Python2.6, calculate it manually.
"""
try:
return delta.total_seconds()
except __HOLE__:
retur... | AttributeError | dataset/ETHPy150Open openstack/python-monascaclient/monascaclient/openstack/common/timeutils.py/total_seconds |
8,607 | def update(self, request, *args, **kwargs):
"Reply to message"
if request.data is None:
return rc.BAD_REQUEST
pkfield = kwargs.get(self.model._meta.pk.name) or request.data.get(
self.model._meta.pk.name)
if not pkfield:
return rc.BAD_REQUEST
... | ObjectDoesNotExist | dataset/ETHPy150Open treeio/treeio/treeio/messaging/api/handlers.py/MessageHandler.update |
8,608 | def __init__(self, vcs_project, path, locales=None):
"""
Load the resource file for each enabled locale and store its
translations in VCSEntity instances.
"""
from pontoon.base.models import Locale
from pontoon.sync import formats # Avoid circular import.
self.v... | KeyError | dataset/ETHPy150Open mozilla/pontoon/pontoon/sync/vcs/models.py/VCSResource.__init__ |
8,609 | def default_patch_view(resource, request):
try:
data = request.json_body
except __HOLE__:
request.response.status_int = 400
return {'message': 'No JSON data provided.'}
resource.validate(data, partial=True)
resource.update_from_dict(data, replace=False)
return resource.to_dic... | ValueError | dataset/ETHPy150Open wichert/rest_toolkit/src/rest_toolkit/views.py/default_patch_view |
8,610 | def default_put_view(resource, request):
try:
data = request.json_body
except __HOLE__:
request.response.status_int = 400
return {'message': 'No JSON data provided.'}
resource.validate(data, partial=False)
resource.update_from_dict(data, replace=True)
return resource.to_dict(... | ValueError | dataset/ETHPy150Open wichert/rest_toolkit/src/rest_toolkit/views.py/default_put_view |
8,611 | def default_post_view(resource, request):
try:
data = request.json_body
except __HOLE__:
request.response.status_int = 400
return {'message': 'No JSON data provided.'}
resource.validate_child(data)
request.response.status_int = 201
return resource.add_child(data) | ValueError | dataset/ETHPy150Open wichert/rest_toolkit/src/rest_toolkit/views.py/default_post_view |
8,612 | def shortcut(request, content_type_id, object_id):
"""
Redirect to an object's page based on a content-type ID and an object ID.
"""
# Look up the object, making sure it's got a get_absolute_url() function.
try:
content_type = ContentType.objects.get(pk=content_type_id)
if not conten... | ValueError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/contrib/contenttypes/views.py/shortcut |
8,613 | def heap_merged(items_lists, combiner):
heap = []
def pushback(it):
try:
k,v = it.next()
# put i before value, so do not compare the value
heapq.heappush(heap, (k, i, v))
except __HOLE__:
pass
for i, it in enumerate(items_lists):
if isi... | StopIteration | dataset/ETHPy150Open douban/dpark/dpark/shuffle.py/heap_merged |
8,614 | def _configure_section(self, f, section, items):
target = getattr(self.module, section, None)
if target is None:
# silently ignore
self._handle_missing_section(section, f)
notify('Configuring section "{}" from "{}"'.format(section, f))
for k, v in items:
... | AttributeError | dataset/ETHPy150Open EverythingMe/click-config/click_config/__init__.py/Parser._configure_section |
8,615 | def _calculate(self, data):
x = pop(data, 'x', None)
y = pop(data, 'y', None)
# intercept and slope may be one of:
# - aesthetics to geom_abline or
# - parameter settings to stat_abline
slope = pop(data, 'slope', self.params['slope'])
intercept = pop(data, 'i... | TypeError | dataset/ETHPy150Open yhat/ggplot/ggplot/stats/stat_abline.py/stat_abline._calculate |
8,616 | def get_instance_port(self, instance_id):
"""Returns the port of the HTTP server for an instance."""
try:
instance_id = int(instance_id)
except __HOLE__:
raise request_info.InvalidInstanceIdError()
with self._condition:
if 0 <= instance_id < len(self._instances):
wsgi_servr = s... | ValueError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/tools/devappserver2/server.py/ManualScalingServer.get_instance_port |
8,617 | def get_instance(self, instance_id):
"""Returns the instance with the provided instance ID."""
try:
with self._condition:
return self._instances[int(instance_id)]
except (ValueError, __HOLE__):
raise request_info.InvalidInstanceIdError() | IndexError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/tools/devappserver2/server.py/ManualScalingServer.get_instance |
8,618 | def get_instance_port(self, instance_id):
"""Returns the port of the HTTP server for an instance."""
try:
instance_id = int(instance_id)
except __HOLE__:
raise request_info.InvalidInstanceIdError()
with self._condition:
if 0 <= instance_id < len(self._instances):
wsgi_servr = s... | ValueError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/tools/devappserver2/server.py/BasicScalingServer.get_instance_port |
8,619 | def get_instance(self, instance_id):
"""Returns the instance with the provided instance ID."""
try:
with self._condition:
return self._instances[int(instance_id)]
except (ValueError, __HOLE__):
raise request_info.InvalidInstanceIdError() | IndexError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/tools/devappserver2/server.py/BasicScalingServer.get_instance |
8,620 | def add_boundaries_for_layer(self, config, layer, bset, database):
# Get spatial reference system for the postgis geometry field
geometry_field = Boundary._meta.get_field_by_name(GEOMETRY_COLUMN)[0]
SpatialRefSys = connections[database].ops.spatial_ref_sys()
db_srs = SpatialRefSys.object... | AttributeError | dataset/ETHPy150Open newsapps/django-boundaryservice/boundaryservice/management/commands/loadshapefiles.py/Command.add_boundaries_for_layer |
8,621 | def onReload(self,moduleName="ParenchymaAnalysis"):
"""Generic reload method for any scripted module.
ModuleWizard will subsitute correct default moduleName.
"""
import imp, sys, os, slicer
widgetName = moduleName + "Widget"
# reload the source code
# - set source file path
... | AttributeError | dataset/ETHPy150Open acil-bwh/SlicerCIP/Scripted/attic/ParenchymaAnalysis/ParenchymaAnalysis.py/ParenchymaAnalysisWidget.onReload |
8,622 | def find_python_module(self, name, mark):
if not name:
raise ConstructorError("while constructing a Python module", mark,
"expected non-empty name appended to the tag", mark)
try:
__import__(name)
except __HOLE__ as exc:
raise ConstructorEr... | ImportError | dataset/ETHPy150Open NicoSantangelo/sublime-text-i18n-rails/pyyaml/constructor.py/Constructor.find_python_module |
8,623 | def find_python_name(self, name, mark):
if not name:
raise ConstructorError("while constructing a Python object", mark,
"expected non-empty name appended to the tag", mark)
if '.' in name:
module_name, object_name = name.rsplit('.', 1)
else:
... | ImportError | dataset/ETHPy150Open NicoSantangelo/sublime-text-i18n-rails/pyyaml/constructor.py/Constructor.find_python_name |
8,624 | def outgoing (self, msg):
try:
channel = msg.irc_channel
except __HOLE__:
channel = self.channels[0]
if channel:
target = channel
else:
target = msg.connection.identity
response = "%s: %s" % (msg.connection.identity, msg.text)
... | AttributeError | dataset/ETHPy150Open rapidsms/rapidsms-core-dev/lib/rapidsms/backends/irc.py/Backend.outgoing |
8,625 | def pubmsg (self, connection, event):
self.debug("%s -> %s: %r", event.source(), event.target(), event.arguments())
try:
nick, txt = map(str.strip, event.arguments()[0].split(":"))
except __HOLE__:
return # not for me
nick = nick.split("!")[0]
if nick == s... | ValueError | dataset/ETHPy150Open rapidsms/rapidsms-core-dev/lib/rapidsms/backends/irc.py/Backend.pubmsg |
8,626 | def main(world_folder):
world = AnvilWorldFolder(world_folder) # Not supported for McRegion
if not world.nonempty(): # likely still a McRegion file
sys.stderr.write("World folder %r is empty or not an Anvil formatted world\n" % world_folder)
return 65 # EX_DATAERR
biome_totals = [0]*256 #... | KeyboardInterrupt | dataset/ETHPy150Open twoolie/NBT/examples/biome_analysis.py/main |
8,627 | def _rerequest_single(self, t, s, l, callback):
try:
closer = [None]
def timedout(self = self, l = l, closer = closer):
if self.lock.trip(l):
self.errorcodes['troublecode'] = 'Problem connecting to tracker - timeout exceeded'
... | ValueError | dataset/ETHPy150Open lg/murder/dist/BitTornado/BT1/Rerequester.py/Rerequester._rerequest_single |
8,628 | def download_directory(url, target, insecure=False):
def mkdir():
if not mkdir.done:
try:
os.mkdir(target)
except __HOLE__:
pass
mkdir.done = True
mkdir.done = False
opener = build_opener(insecure=insecure)
response = opener.op... | OSError | dataset/ETHPy150Open VisTrails/VisTrails/vistrails/packages/URL/http_directory.py/download_directory |
8,629 | def init():
import nova.conf
CONF = nova.conf.CONF
# NOTE(markmc): gracefully handle the CLI options not being registered
if 'remote_debug' not in CONF:
return
if not (CONF.remote_debug.host and CONF.remote_debug.port):
return
import logging
from nova.i18n import _LW
L... | ImportError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/debugger.py/init |
8,630 | def main():
parser = argparse.ArgumentParser()
parser.add_argument('keys', metavar='KEY', nargs='+', default=None,
help='keys associated with values to be selected')
args = parser.parse_args()
if sys.stdin.isatty():
parser.error('no input, pipe another btc command output... | KeyError | dataset/ETHPy150Open bittorrent/btc/btc/btc_select.py/main |
8,631 | def __getitem__(self, key):
for mapping in self.maps:
try:
return mapping[key] # can't use 'key in mapping' with defaultdict
except __HOLE__:
pass
return self.__missing__(key) # support subclasses that define __missing__ | KeyError | dataset/ETHPy150Open ionelmc/python-aspectlib/src/aspectlib/py2chainmap.py/ChainMap.__getitem__ |
8,632 | def __delitem__(self, key):
try:
del self.maps[0][key]
except __HOLE__:
raise KeyError('Key not found in the first mapping: {!r}'.format(key)) | KeyError | dataset/ETHPy150Open ionelmc/python-aspectlib/src/aspectlib/py2chainmap.py/ChainMap.__delitem__ |
8,633 | def popitem(self):
'Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.'
try:
return self.maps[0].popitem()
except __HOLE__:
raise KeyError('No keys found in the first mapping.') | KeyError | dataset/ETHPy150Open ionelmc/python-aspectlib/src/aspectlib/py2chainmap.py/ChainMap.popitem |
8,634 | def pop(self, key, *args):
'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].'
try:
return self.maps[0].pop(key, *args)
except __HOLE__:
raise KeyError('Key not found in the first mapping: {!r}'.format(key)) | KeyError | dataset/ETHPy150Open ionelmc/python-aspectlib/src/aspectlib/py2chainmap.py/ChainMap.pop |
8,635 | @then(u'we should get exit code {expected_exit_code:d}')
def check_exit_code(context, expected_exit_code):
try:
assert context.exit_code == expected_exit_code, \
"expected %d, got %d" % (expected_exit_code, context.exit_code)
except __HOLE__:
# behave likes to back up by two lines an... | AssertionError | dataset/ETHPy150Open Yelp/paasta/paasta_itests/steps/setup_chronos_job_steps.py/check_exit_code |
8,636 | def create_structure(struct, prefix=None, update=False):
"""
Manifests a directory structure in the filesystem
:param struct: directory structure as dictionary of dictionaries
:param prefix: prefix path for the structure
:param update: update an existing directory structure as boolean
"""
i... | OSError | dataset/ETHPy150Open blue-yonder/pyscaffold/pyscaffold/structure.py/create_structure |
8,637 | def diff_map(self, incolls):
"""Generate SQL to transform existing collations
:param incolls: a YAML map defining the new collations
:return: list of SQL statements
Compares the existing collation definitions, as fetched from
the catalogs, to the input map and generates SQL sta... | KeyError | dataset/ETHPy150Open perseas/Pyrseas/pyrseas/dbobject/collation.py/CollationDict.diff_map |
8,638 | def _update_voi(self):
if len(self.inputs) == 0:
return
plane = self.plane
extents = (self.x_min, self.x_max,
self.y_min, self.y_max,
self.z_min, self.z_max)
try:
plane.set_extent(extents)
except __HOLE__:
... | AttributeError | dataset/ETHPy150Open enthought/mayavi/mayavi/components/custom_grid_plane.py/CustomGridPlane._update_voi |
8,639 | def __missing__(self, key):
try:
value = raw_input(prompt_str.format(key))
except __HOLE__:
# Catch the sigint here, since the user's pretty likely to
# Ctrl-C and go fix the options mapping input file
raise SystemExit
if not value:
va... | KeyboardInterrupt | dataset/ETHPy150Open seandst/cfn-pyplates/cfn_pyplates/options.py/OptionsMapping.__missing__ |
8,640 | def jar_run(debugger):
# Set up the root Tk context
root = Tk()
# Construct a window debugging the nominated program
view = MainWindow(root, debugger)
# Run the main loop
try:
view.mainloop()
except __HOLE__:
view.on_quit() | KeyboardInterrupt | dataset/ETHPy150Open pybee/bugjar/bugjar/main.py/jar_run |
8,641 | def _to_nodes(self, object):
nodes = []
for element in object.findall('devices/device'):
if element.findtext("type") == "Virtual Server":
try:
state = self.NODE_STATE_MAP[element.attrib['status']]
except __HOLE__:
state ... | KeyError | dataset/ETHPy150Open secondstory/dewpoint/libcloud/drivers/voxel.py/VoxelNodeDriver._to_nodes |
8,642 | def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
video_id = mobj.group('videoid')
url = mobj.group('proto') + 'www.' + mobj.group('url')
req = compat_urllib_request.Request(url)
req.add_header('Cookie', 'age_verified=1')
webpage = self._download_webpag... | KeyError | dataset/ETHPy150Open yasoob/youtube-dl-GUI/youtube_dl/extractor/youporn.py/YouPornIE._real_extract |
8,643 | def _init_vintageous(view, new_session=False):
"""
Initializes global data. Runs at startup and every time a view gets
activated, loaded, etc.
@new_session
Whether we're starting up Sublime Text. If so, volatile data must be
wiped.
"""
_logger.debug("running init for view %d", view... | AttributeError | dataset/ETHPy150Open guillermooo/Vintageous/state.py/_init_vintageous |
8,644 | def plugin_unloaded():
view = sublime.active_window().active_view()
try:
view.settings().set('command_mode', False)
view.settings().set('inverse_caret_state', False)
except __HOLE__:
_logger.warn(
'could not access sublime.active_window().active_view().settings '
... | AttributeError | dataset/ETHPy150Open guillermooo/Vintageous/state.py/plugin_unloaded |
8,645 | def cpu_count():
"""Returns the number of processors on this machine."""
try:
return multiprocessing.cpu_count()
except NotImplementedError:
pass
try:
return os.sysconf("SC_NPROCESSORS_CONF")
except __HOLE__:
pass
gen_log.error("Could not detect number of processo... | ValueError | dataset/ETHPy150Open D-L/SimpleBookMarks/src/tornado/process.py/cpu_count |
8,646 | def _reseed_random():
if 'random' not in sys.modules:
return
import random
# If os.urandom is available, this method does the same thing as
# random.seed (at least as of python 2.6). If os.urandom is not
# available, we mix in the pid in addition to a timestamp.
try:
seed = long... | NotImplementedError | dataset/ETHPy150Open D-L/SimpleBookMarks/src/tornado/process.py/_reseed_random |
8,647 | def fork_processes(num_processes, max_restarts=100):
"""Starts multiple worker processes.
If ``num_processes`` is None or <= 0, we detect the number of cores
available on this machine and fork that number of child
processes. If ``num_processes`` is given and > 0, we fork that
specific number of sub... | OSError | dataset/ETHPy150Open D-L/SimpleBookMarks/src/tornado/process.py/fork_processes |
8,648 | @classmethod
def _try_cleanup_process(cls, pid):
try:
ret_pid, status = os.waitpid(pid, os.WNOHANG)
except __HOLE__ as e:
if e.args[0] == errno.ECHILD:
return
if ret_pid == 0:
return
assert ret_pid == pid
subproc = cls._wait... | OSError | dataset/ETHPy150Open D-L/SimpleBookMarks/src/tornado/process.py/Subprocess._try_cleanup_process |
8,649 | def test_transaction_hook(self):
run_hook = []
class RootController(object):
@expose()
def index(self):
run_hook.append('inside')
return 'Hello, World!'
@expose()
def redirect(self):
redirect('/')
... | IndexError | dataset/ETHPy150Open pecan/pecan/pecan/tests/test_hooks.py/TestTransactionHook.test_transaction_hook |
8,650 | def test_transaction_hook_with_transactional_decorator(self):
run_hook = []
class RootController(object):
@expose()
def index(self):
run_hook.append('inside')
return 'Hello, World!'
@expose()
def redirect(self):
... | IndexError | dataset/ETHPy150Open pecan/pecan/pecan/tests/test_hooks.py/TestTransactionHook.test_transaction_hook_with_transactional_decorator |
8,651 | def test_transaction_hook_with_transactional_class_decorator(self):
run_hook = []
@transactional()
class RootController(object):
@expose()
def index(self):
run_hook.append('inside')
return 'Hello, World!'
@expose()
... | IndexError | dataset/ETHPy150Open pecan/pecan/pecan/tests/test_hooks.py/TestTransactionHook.test_transaction_hook_with_transactional_class_decorator |
8,652 | @defer.inlineCallbacks
def _check_recaptcha(self, authdict, clientip):
try:
user_response = authdict["response"]
except __HOLE__:
# Client tried to provide captcha but didn't give the parameter:
# bad request.
raise LoginError(
400, "Ca... | KeyError | dataset/ETHPy150Open matrix-org/synapse/synapse/handlers/auth.py/AuthHandler._check_recaptcha |
8,653 | def validate_short_term_login_token_and_get_user_id(self, login_token):
try:
macaroon = pymacaroons.Macaroon.deserialize(login_token)
auth_api = self.hs.get_auth()
auth_api.validate_macaroon(macaroon, "login", True)
return self.get_user_from_macaroon(macaroon)
... | TypeError | dataset/ETHPy150Open matrix-org/synapse/synapse/handlers/auth.py/AuthHandler.validate_short_term_login_token_and_get_user_id |
8,654 | def testDefFile(self):
l = Parser.parseSource(testHeader)
# FIXME: hardcode the function pointer since we don't parse those yet
l.functions["funcPointer"] = Library.Function("funcPointer", "void")
for function, ordinal in Parser.parseDefFile(testDefFile):
l.functions[function].ordinal = ordi... | ValueError | dataset/ETHPy150Open skyostil/tracy/src/generator/ParserTest.py/ParserTest.testDefFile |
8,655 | def test_channel_close_does_not_raise_an_exception_with_no_socket(self):
try:
self.channel.close()
except __HOLE__:
self.fail("Attempted to remove a socketless channel from the engine.") | TypeError | dataset/ETHPy150Open ecdavis/pants/pants/test/core/test_channel.py/TestChannelClose.test_channel_close_does_not_raise_an_exception_with_no_socket |
8,656 | def main():
args = docopt.docopt('\n'.join(__doc__.split('\n')[2:]),
version=const.VERSION)
logging.basicConfig(
level=logging.DEBUG if args['--verbose'] else logging.INFO,
stream=sys.stdout,
)
conf = config.new_context_from_file(args['--config-file'], section='... | KeyboardInterrupt | dataset/ETHPy150Open Gentux/imap-cli/imap_cli/delete.py/main |
8,657 | def bug_role(role, rawtext, text, linenum, inliner, options={}, content=[]):
try:
bugnum = int(text)
if bugnum <= 0:
raise ValueError
except __HOLE__:
msg = inliner.reporter.error(
'Bug number must be a number greater than or equal to 1; '
'"%s" is inv... | ValueError | dataset/ETHPy150Open reviewboard/reviewboard/docs/releasenotes/_ext/extralinks.py/bug_role |
8,658 | def _find_checkers():
try:
from pkg_resources import working_set
except __HOLE__:
return [num_plurals, python_format]
checkers = []
for entry_point in working_set.iter_entry_points('babel.checkers'):
checkers.append(entry_point.load())
return checkers | ImportError | dataset/ETHPy150Open IanLewis/kay/kay/lib/babel/messages/checkers.py/_find_checkers |
8,659 | @transaction.atomic
def handle_project_locale(self, project, locale):
# Match locale code inconsistencies
pootle_locale = locale.replace('-', '_')
if pootle_locale == 'ga_IE':
pootle_locale = 'ga'
# Match project slug inconsistencies
pootle_project = {
... | ValueError | dataset/ETHPy150Open mozilla/pontoon/pontoon/sync/management/commands/import_pootle.py/Command.handle_project_locale |
8,660 | @property
def _provider(self):
from libcloud.storage.types import Provider
try:
provider_name = self.LIBCLOUD_S3_PROVIDERS_BY_REGION[self._region]
return getattr(Provider, provider_name)
except __HOLE__:
raise ArgumentError(
'Invalid value ... | KeyError | dataset/ETHPy150Open jpvanhal/siilo/siilo/storages/amazon_s3.py/AmazonS3Storage._provider |
8,661 | def fetchone(self, delete_flag=False):
try:
result = self.last_select_command.results.next()
if isinstance(result, (int, long)):
return (result,)
query = self.last_select_command.query
row = []
# Prepend extra select values to the r... | StopIteration | dataset/ETHPy150Open potatolondon/djangae/djangae/db/backends/appengine/base.py/Cursor.fetchone |
8,662 | def prep_lookup_key(self, model, value, field):
if isinstance(value, basestring):
value = value[:500]
left = value[500:]
if left:
warnings.warn("Truncating primary key that is over 500 characters. "
"THIS IS AN ERROR IN YOUR PROGR... | TypeError | dataset/ETHPy150Open potatolondon/djangae/djangae/db/backends/appengine/base.py/DatabaseOperations.prep_lookup_key |
8,663 | def main(namespace):
# parse args
command = ' '.join(sys.argv[1:])
if not command:
# console (interactive)
try: reinit(namespace)
except __HOLE__:
pass
# ignore Ctrl-C (interferes with gevent)
signal.signal(signal.SIGINT, lambda signum, frame: None)
else:
# call (non-interactive)
reinit(namespace... | KeyboardInterrupt | dataset/ETHPy150Open alexcepoi/pyscale/pyscale/tools/console.py/main |
8,664 | def _get_level_name_dict(self):
'''
Returns level_name_dict for pre-set lookup_scheme_name, tile_type_id, satellite_tag, sensor_name & level_name
Returns None if not found
'''
assert self.lookup_scheme_name, 'lookup_scheme_name not set'
assert self.tile_type_id, 'ti... | KeyError | dataset/ETHPy150Open GeoscienceAustralia/agdc/src/band_lookup.py/BandLookup._get_level_name_dict |
8,665 | def __getitem__(self, alias):
try:
return self._connections.connections[alias]
except __HOLE__:
self._connections.connections = {}
except KeyError:
pass
try:
backend = get_backend(alias)
except KeyError:
raise KeyError(... | AttributeError | dataset/ETHPy150Open ui/django-post_office/post_office/connections.py/ConnectionHandler.__getitem__ |
8,666 | def parse_driver_info(node):
"""Checks for the required properties and values validity.
:param node: the target node.
:raises: MissingParameterValue if one or more required properties are
missing.
:raises: InvalidParameterValue if a parameter value is invalid.
"""
driver_info = node.dri... | ValueError | dataset/ETHPy150Open openstack/ironic/ironic/drivers/modules/msftocs/common.py/parse_driver_info |
8,667 | def indented_short_title(self, item):
"""
Generate a short title for an object, indent it depending on
the object's depth in the hierarchy.
"""
mptt_opts = item._mptt_meta
r = ''
try:
url = item.get_absolute_url()
except (__HOLE__,):
... | AttributeError | dataset/ETHPy150Open feincms/feincms/feincms/admin/tree_editor.py/TreeEditor.indented_short_title |
8,668 | def _collect_editable_booleans(self):
"""
Collect all fields marked as editable booleans. We do not
want the user to be able to edit arbitrary fields by crafting
an AJAX request by hand.
"""
if hasattr(self, '_ajax_editable_booleans'):
return
self._aj... | TypeError | dataset/ETHPy150Open feincms/feincms/feincms/admin/tree_editor.py/TreeEditor._collect_editable_booleans |
8,669 | def __init__(self, config_file=None):
'''Attempt to initialize a config dictionary from a yaml file.
Error out if loading the yaml file fails for any reason.
:param config_file: The Bandit yaml config file
:raises bandit.utils.ConfigError: If the config is invalid or
unread... | IOError | dataset/ETHPy150Open openstack/bandit/bandit/core/config.py/BanditConfig.__init__ |
8,670 | def test_no_exception_on_select(self):
"""
no exception on SELECT for numeric column name
"""
try:
self.session.execute('SELECT * FROM test1rf.table_num_col')
except __HOLE__ as e:
self.fail("Unexpected ValueError exception: %s" % e.message) | ValueError | dataset/ETHPy150Open datastax/python-driver/tests/integration/standard/test_row_factories.py/NamedTupleFactoryAndNumericColNamesTests.test_no_exception_on_select |
8,671 | def test_can_select_using_alias(self):
"""
can SELECT "<numeric col name>" AS aliases
"""
if self._cass_version < (2, 0, 0):
raise unittest.SkipTest("Alias in SELECT not supported before 2.0")
try:
self.session.execute('SELECT key, "626972746864617465" AS... | ValueError | dataset/ETHPy150Open datastax/python-driver/tests/integration/standard/test_row_factories.py/NamedTupleFactoryAndNumericColNamesTests.test_can_select_using_alias |
8,672 | def test_can_select_with_dict_factory(self):
"""
can SELECT numeric column using dict_factory
"""
self.session.row_factory = dict_factory
try:
self.session.execute('SELECT * FROM test1rf.table_num_col')
except __HOLE__ as e:
self.fail("Unexpected... | ValueError | dataset/ETHPy150Open datastax/python-driver/tests/integration/standard/test_row_factories.py/NamedTupleFactoryAndNumericColNamesTests.test_can_select_with_dict_factory |
8,673 | def _getconftestmodules(self, path):
if self._noconftest:
return []
try:
return self._path2confmods[path]
except __HOLE__:
if path.isfile():
clist = self._getconftestmodules(path.dirpath())
else:
# XXX these days we ... | KeyError | dataset/ETHPy150Open pytest-dev/pytest/_pytest/config.py/PytestPluginManager._getconftestmodules |
8,674 | def _rget_with_confmod(self, name, path):
modules = self._getconftestmodules(path)
for mod in reversed(modules):
try:
return mod, getattr(mod, name)
except __HOLE__:
continue
raise KeyError(name) | AttributeError | dataset/ETHPy150Open pytest-dev/pytest/_pytest/config.py/PytestPluginManager._rget_with_confmod |
8,675 | def _importconftest(self, conftestpath):
try:
return self._conftestpath2mod[conftestpath]
except __HOLE__:
pkgpath = conftestpath.pypkgpath()
if pkgpath is None:
_ensure_removed_sysmodule(conftestpath.purebasename)
try:
mod ... | KeyError | dataset/ETHPy150Open pytest-dev/pytest/_pytest/config.py/PytestPluginManager._importconftest |
8,676 | def import_plugin(self, modname):
# most often modname refers to builtin modules, e.g. "pytester",
# "terminal" or "capture". Those plugins are registered under their
# basename for historic purposes but must be imported with the
# _pytest prefix.
assert isinstance(modname, str)... | ImportError | dataset/ETHPy150Open pytest-dev/pytest/_pytest/config.py/PytestPluginManager.import_plugin |
8,677 | def __init__(self, *names, **attrs):
"""store parms in private vars for use in add_argument"""
self._attrs = attrs
self._short_opts = []
self._long_opts = []
self.dest = attrs.get('dest')
if self.TYPE_WARN:
try:
help = attrs['help']
... | KeyError | dataset/ETHPy150Open pytest-dev/pytest/_pytest/config.py/Argument.__init__ |
8,678 | def attrs(self):
# update any attributes set by processopt
attrs = 'default dest help'.split()
if self.dest:
attrs.append(self.dest)
for attr in attrs:
try:
self._attrs[attr] = getattr(self, attr)
except __HOLE__:
pass
... | AttributeError | dataset/ETHPy150Open pytest-dev/pytest/_pytest/config.py/Argument.attrs |
8,679 | def _ensure_removed_sysmodule(modname):
try:
del sys.modules[modname]
except __HOLE__:
pass | KeyError | dataset/ETHPy150Open pytest-dev/pytest/_pytest/config.py/_ensure_removed_sysmodule |
8,680 | def _preparse(self, args, addopts=True):
self._initini(args)
if addopts:
args[:] = shlex.split(os.environ.get('PYTEST_ADDOPTS', '')) + args
args[:] = self.getini("addopts") + args
self._checkversion()
self.pluginmanager.consider_preparse(args)
try:
... | ImportError | dataset/ETHPy150Open pytest-dev/pytest/_pytest/config.py/Config._preparse |
8,681 | def getini(self, name):
""" return configuration value from an :ref:`ini file <inifiles>`. If the
specified name hasn't been registered through a prior
:py:func:`parser.addini <pytest.config.Parser.addini>`
call (usually from a plugin), a ValueError is raised. """
try:
... | KeyError | dataset/ETHPy150Open pytest-dev/pytest/_pytest/config.py/Config.getini |
8,682 | def _getini(self, name):
try:
description, type, default = self._parser._inidict[name]
except __HOLE__:
raise ValueError("unknown configuration value: %r" %(name,))
try:
value = self.inicfg[name]
except KeyError:
if default is not None:
... | KeyError | dataset/ETHPy150Open pytest-dev/pytest/_pytest/config.py/Config._getini |
8,683 | def _getconftest_pathlist(self, name, path):
try:
mod, relroots = self.pluginmanager._rget_with_confmod(name, path)
except __HOLE__:
return None
modpath = py.path.local(mod.__file__).dirpath()
l = []
for relroot in relroots:
if not isinstance(r... | KeyError | dataset/ETHPy150Open pytest-dev/pytest/_pytest/config.py/Config._getconftest_pathlist |
8,684 | def getoption(self, name, default=notset, skip=False):
""" return command line option value.
:arg name: name of the option. You may also specify
the literal ``--OPT`` option instead of the "dest" option name.
:arg default: default value if no option of that name exists.
:ar... | AttributeError | dataset/ETHPy150Open pytest-dev/pytest/_pytest/config.py/Config.getoption |
8,685 | def determine_setup(inifile, args):
if inifile:
iniconfig = py.iniconfig.IniConfig(inifile)
try:
inicfg = iniconfig["pytest"]
except __HOLE__:
inicfg = None
rootdir = get_common_ancestor(args)
else:
ancestor = get_common_ancestor(args)
root... | KeyError | dataset/ETHPy150Open pytest-dev/pytest/_pytest/config.py/determine_setup |
8,686 | def create_client(self, name, app_id, valid_facets):
ensure_valid_name(name)
try:
self.get_client(name)
raise ValueError('Client already exists: %s' % name)
except __HOLE__:
client = Client(name, app_id, valid_facets)
self._session.add(client)
... | KeyError | dataset/ETHPy150Open Yubico/u2fval/u2fval/client/controller.py/ClientController.create_client |
8,687 | def library_paths():
"""Iterates for library paths to try loading. The result paths are not
guaranteed that they exist.
:returns: a pair of libwand and libmagick paths. they can be the same.
path can be ``None`` as well
:rtype: :class:`tuple`
"""
libwand = None
libmagick = ... | OSError | dataset/ETHPy150Open dahlia/wand/wand/api.py/library_paths |
8,688 | def load_library():
"""Loads the MagickWand library.
:returns: the MagickWand library and the ImageMagick library
:rtype: :class:`ctypes.CDLL`
"""
tried_paths = []
for libwand_path, libmagick_path in library_paths():
if libwand_path is None or libmagick_path is None:
contin... | IOError | dataset/ETHPy150Open dahlia/wand/wand/api.py/load_library |
8,689 | def _parse_version(self, raw_version):
err_msg = 'Unsupported version %r' % raw_version
try:
version = float(raw_version.lstrip('v'))
except __HOLE__:
raise ValueError(err_msg)
if not any(version == v for v in RESPONSE_VERSIONS):
raise ValueError(err_m... | ValueError | dataset/ETHPy150Open openstack/swift/swift/common/middleware/list_endpoints.py/ListEndpointsMiddleware._parse_version |
8,690 | def _parse_path(self, request):
"""
Parse path parts of request into a tuple of version, account,
container, obj. Unspecified path parts are filled in as None,
except version which is always returned as a float using the
configured default response version if not specified in th... | ValueError | dataset/ETHPy150Open openstack/swift/swift/common/middleware/list_endpoints.py/ListEndpointsMiddleware._parse_path |
8,691 | def __call__(self, env, start_response):
request = Request(env)
if not request.path.startswith(self.endpoints_path):
return self.app(env, start_response)
if request.method != 'GET':
return HTTPMethodNotAllowed(
req=request, headers={"Allow": "GET"})(env, ... | ValueError | dataset/ETHPy150Open openstack/swift/swift/common/middleware/list_endpoints.py/ListEndpointsMiddleware.__call__ |
8,692 | def ext_pillar(minion_id,
pillar, # pylint: disable=W0613
conf):
'''
Check vault for all data
'''
comps = conf.split()
profile = {}
if comps[0]:
profile_name = comps[0]
profile = __opts__.get(profile_name, {})
path = '/'
if len(comps) > 1 ... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/pillar/vault.py/ext_pillar |
8,693 | def main():
global config, stream, observer, git_sync, notifier
config = parse_config()
stream = Stream(callback, config['local_path'], file_events=True)
observer.schedule(stream)
(git_sync, notifier) = gitsynclib.GitSync.setup_git_sync(config)
git_sync.run_initial_sync()
observer.start... | KeyboardInterrupt | dataset/ETHPy150Open jachin/GitSync/src/gitsync/GitSync.py/main |
8,694 | def setUp(self):
self.patcher = patch('ffmpegwrapper.ffmpeg.Popen')
popen = self.patcher.start()
self.instance = popen.return_value
read_value = bytearray(b'this is a line\nthis too\n')
poll = lambda: None if read_value else 0
def read(*args):
try:
... | IndexError | dataset/ETHPy150Open interru/ffmpegwrapper/test.py/FFmpegTestCase.setUp |
8,695 | def _connect(self):
self._connection.connect()
full_path = None
try:
full_path = self.path + '?' + urllib.urlencode(self.query_parameters)
except __HOLE__:
full_path = self.path + '?' + urllib.parse.urlencode(self.query_parameters)
self._connection.putr... | AttributeError | dataset/ETHPy150Open api-ai/api-ai-python/apiai/requests/request.py/Request._connect |
8,696 | def get_category(self):
if 'pk' in self.kwargs:
# Usual way to reach a category page. We just look at the primary
# key, which is easy on the database. If the slug changed, get()
# will redirect appropriately.
# WARNING: Category.get_absolute_url needs to look up ... | IndexError | dataset/ETHPy150Open django-oscar/django-oscar/src/oscar/apps/catalogue/views.py/ProductCategoryView.get_category |
8,697 | def __getitem__(self, k):
try:
return getattr(self, k)
except __HOLE__:
raise KeyError | AttributeError | dataset/ETHPy150Open kbandla/dpkt/dpkt/dpkt.py/Packet.__getitem__ |
8,698 | def prompt():
while True:
try:
term = float(input('+ '))
except __HOLE__:
break
yield term | ValueError | dataset/ETHPy150Open fluentpython/example-code/attic/control/adder/coroadder_deco.py/prompt |
8,699 | def main(get_terms):
adder = adder_coro()
for term in get_terms:
adder.send(term)
try:
adder.send(None)
except __HOLE__ as exc:
result = exc.value
print(result) | StopIteration | dataset/ETHPy150Open fluentpython/example-code/attic/control/adder/coroadder_deco.py/main |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.