Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
2,400 | def parse_index(value):
try:
return int(value)
except (ValueError, __HOLE__):
return value | TypeError | dataset/ETHPy150Open ombre42/robotframework-sudslibrary/src/SudsLibrary/utils.py/parse_index |
2,401 | def get_cache(self, instance, translation=None,
language=None, field_name=None,
field_value=None):
"""
Returns translation from cache.
"""
is_new = bool(instance.pk is None)
try:
cached_obj = instance._linguist_translations[field_n... | KeyError | dataset/ETHPy150Open ulule/django-linguist/linguist/fields.py/Linguist.get_cache |
2,402 | def __get__(self, instance, instance_type=None):
if instance is None:
return self
try:
return getattr(instance, '_linguist_cache')
except __HOLE__:
linguist = Linguist(instance=instance,
identifier=self.identifier,
... | AttributeError | dataset/ETHPy150Open ulule/django-linguist/linguist/fields.py/CacheDescriptor.__get__ |
2,403 | def GenerateOutput(target_list, target_dicts, data, params):
# Update target_dicts for iOS device builds.
target_dicts = gyp.xcode_emulation.CloneConfigurationForDeviceAndEmulator(
target_dicts)
user_config = params.get('generator_flags', {}).get('config', None)
if gyp.common.GetFlavor(params) == 'win':
... | KeyboardInterrupt | dataset/ETHPy150Open adblockplus/gyp/pylib/gyp/generator/ninja.py/GenerateOutput |
2,404 | @wand.setter
def wand(self, wand):
try:
self.resource = wand
except __HOLE__:
raise TypeError(repr(wand) + ' is not a MagickWand instance') | TypeError | dataset/ETHPy150Open dahlia/wand/wand/image.py/BaseImage.wand |
2,405 | def __getitem__(self, idx):
if (not isinstance(idx, string_type) and
isinstance(idx, collections.Iterable)):
idx = tuple(idx)
d = len(idx)
if not (1 <= d <= 2):
raise ValueError('index cannot be {0}-dimensional'.format(d))
elif d ==... | ValueError | dataset/ETHPy150Open dahlia/wand/wand/image.py/BaseImage.__getitem__ |
2,406 | @manipulative
def caption(self, text, left=0, top=0, width=None, height=None, font=None,
gravity=None):
"""Writes a caption ``text`` into the position.
:param text: text to write
:type text: :class:`basestring`
:param left: x offset in pixels
:type left: :cla... | TypeError | dataset/ETHPy150Open dahlia/wand/wand/image.py/BaseImage.caption |
2,407 | @manipulative
def resize(self, width=None, height=None, filter='undefined', blur=1):
"""Resizes the image.
:param width: the width in the scaled image. default is the original
width
:type width: :class:`numbers.Integral`
:param height: the height in the scaled ... | IndexError | dataset/ETHPy150Open dahlia/wand/wand/image.py/BaseImage.resize |
2,408 | @manipulative
def composite_channel(self, channel, image, operator, left=0, top=0):
"""Composite two images using the particular ``channel``.
:param channel: the channel type. available values can be found
in the :const:`CHANNELS` mapping
:param image: the composite... | IndexError | dataset/ETHPy150Open dahlia/wand/wand/image.py/BaseImage.composite_channel |
2,409 | @manipulative
def threshold(self, threshold=0.5, channel=None):
"""Changes the value of individual pixels based on the intensity
of each pixel compared to threshold. The result is a high-contrast,
two color image. It manipulates the image in place.
:param threshold: threshold as a f... | KeyError | dataset/ETHPy150Open dahlia/wand/wand/image.py/BaseImage.threshold |
2,410 | def negate(self, grayscale=False, channel=None):
"""Negate the colors in the reference image.
:param grayscale: if set, only negate grayscale pixels in the image.
:type grayscale: :class:`bool`
:param channel: the channel type. available values can be found
in t... | KeyError | dataset/ETHPy150Open dahlia/wand/wand/image.py/BaseImage.negate |
2,411 | def level(self, black=0.0, white=None, gamma=1.0, channel=None):
"""Adjusts the levels of an image by scaling the colors falling
between specified black and white points to the full available
quantum range.
If only ``black`` is given, ``white`` will be adjusted inward.
:param b... | KeyError | dataset/ETHPy150Open dahlia/wand/wand/image.py/Image.level |
2,412 | @manipulative
def auto_orient(self):
"""Adjusts an image so that its orientation is suitable
for viewing (i.e. top-left orientation). If available it uses
:c:func:`MagickAutoOrientImage` (was added in ImageMagick 6.8.9+)
if you have an older magick library,
it will use :attr:... | AttributeError | dataset/ETHPy150Open dahlia/wand/wand/image.py/Image.auto_orient |
2,413 | def normalize(self, channel=None):
"""Normalize color channels.
:param channel: the channel type. available values can be found
in the :const:`CHANNELS` mapping. If ``None``,
normalize all channels.
:type channel: :class:`basestring`
""... | KeyError | dataset/ETHPy150Open dahlia/wand/wand/image.py/Image.normalize |
2,414 | def __setitem__(self, key, value):
path = self._get_path(key)
pickled = self.encode(value)
try:
f = open(path, 'w')
try:
f.write(pickled)
finally:
f.close()
except __HOLE__:
pass | IOError | dataset/ETHPy150Open wecatch/app-turbo/turbo/session.py/DiskStore.__setitem__ |
2,415 | def download_data_file(href):
destination_path = data_file_destination_path(href)
try:
url = url_for_href(href)
response = urllib2.urlopen(url)
if response.code == 200:
destination_dir = os.path.dirname(destination_path)
if not os.path.exists(destination_dir):
... | KeyboardInterrupt | dataset/ETHPy150Open sunlightlabs/clearspending/timeliness/crawler.py/download_data_file |
2,416 | def crawl_main(startdate=None, enddate=None):
download_schedule = []
try:
for fy in FISCAL_YEARS:
listing = request_listing(fy, startdate, enddate)
update_download_schedule(download_schedule, listing)
log_inaccessible_files(download_schedule)
if confirm_download... | KeyboardInterrupt | dataset/ETHPy150Open sunlightlabs/clearspending/timeliness/crawler.py/crawl_main |
2,417 | def resume_main():
download_schedule = restore_schedule()
try:
if download_schedule and confirm_download_schedule(download_schedule):
exec_download_schedule(download_schedule)
except __HOLE__:
print
print "Exiting due to CTRL-C"
finally:
save_schedule(download... | KeyboardInterrupt | dataset/ETHPy150Open sunlightlabs/clearspending/timeliness/crawler.py/resume_main |
2,418 | def perform(self):
""" Performs the action. """
# Hack! Works tho.
try:
meth = getattr(self._window.scene, self.view)
meth()
except __HOLE__:
pass | AttributeError | dataset/ETHPy150Open enthought/mayavi/examples/tvtk/scene.py/SpecialViewAction.perform |
2,419 | def to_internal_value(self, value):
if value == '' or value is None:
return value
if isinstance(value, GEOSGeometry):
# value already has the correct representation
return value
if isinstance(value, dict):
value = json.dumps(value)
try:
... | ValueError | dataset/ETHPy150Open djangonauts/django-rest-framework-gis/rest_framework_gis/fields.py/GeometryField.to_internal_value |
2,420 | def parse(curl_command):
method = "get"
tokens = shlex.split(curl_command)
parsed_args = parser.parse_args(tokens)
base_indent = " " * 4
data_token = ''
post_data = parsed_args.data or parsed_args.data_binary
if post_data:
method = 'post'
try:
post_data_json = j... | ValueError | dataset/ETHPy150Open spulec/uncurl/uncurl/api.py/parse |
2,421 | def acquire(self, blocking=False):
import fcntl
self.fd = os.open(self.filename, os.O_CREAT | os.O_WRONLY)
mode = fcntl.LOCK_EX
if not blocking: mode |= fcntl.LOCK_NB
try:
fcntl.flock(self.fd, mode)
self.locked = True
return True
except... | IOError | dataset/ETHPy150Open dokipen/whoosh/src/whoosh/support/filelock.py/FcntlLock.acquire |
2,422 | def acquire(self, blocking=False):
import msvcrt
self.fd = os.open(self.filename, os.O_CREAT | os.O_WRONLY)
mode = msvcrt.LK_NBLCK
if blocking: mode = msvcrt.LK_LOCK
try:
msvcrt.locking(self.fd, mode, 1)
return True
except __HOLE__, e:
... | IOError | dataset/ETHPy150Open dokipen/whoosh/src/whoosh/support/filelock.py/MsvcrtLock.acquire |
2,423 | def has_next_election(self):
try:
if self.not_seeking_reelection or len(self.candidate_status) > 0:
return False
except __HOLE__:
pass
return True | TypeError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/summary_data/models.py/Candidate_Overlay.has_next_election |
2,424 | def show_candidate_status(self):
if self.cand_is_gen_winner and self.is_general_candidate:
return "Won General"
if self.cand_is_gen_winner == False and self.is_general_candidate:
return "Lost General"
if self.candidate_status:
try:
... | KeyError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/summary_data/models.py/Candidate_Overlay.show_candidate_status |
2,425 | def display_type(self):
key = self.ctype
returnval = ''
try:
returnval = type_hash[key]
except __HOLE__:
pass
if self.designation == 'D':
returnval += " (Leadership PAC)"
elif self.designation == 'J':
returnval += " (Joint F... | KeyError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/summary_data/models.py/Committee_Overlay.display_type |
2,426 | def display_designation(self):
key = self.designation
try:
return committee_designation_hash[key]
except __HOLE__:
return '' | KeyError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/summary_data/models.py/Committee_Overlay.display_designation |
2,427 | @group_only
def add_quote(self, msg, matches):
try:
quote = matches.group(1)
except __HOLE__:
quote = matches
if hasattr(msg.src, 'username'):
username = msg.src.username
self.insert(timestamp=msg.date,
uid=msg.src.id, username=... | AttributeError | dataset/ETHPy150Open datamachine/telex/plugins/quotes.py/QuotesPlugin.add_quote |
2,428 | def process(fp, outfp, env = {}):
lineno = 0
while 1:
line = fp.readline()
if not line: break
lineno = lineno + 1
match = p_define.match(line)
if match:
# gobble up continuation lines
while line[-2:] == '\\\n':
nextline = fp.readlin... | IOError | dataset/ETHPy150Open francelabs/datafari/windows/python/Tools/Scripts/h2py.py/process |
2,429 | def set_rot_preset(self, preset_name):
self.init_rot_matrix()
try:
r = self.rot_presets[preset_name]
except AttributeError:
raise ValueError(
"%s is not a valid rotation preset." % preset_name)
try:
self.euler_rotate(r[0], 1, 0, 0)
... | AttributeError | dataset/ETHPy150Open sympy/sympy/sympy/plotting/pygletplot/plot_camera.py/PlotCamera.set_rot_preset |
2,430 | def _parse_robots(self, response, netloc):
rp = robotparser.RobotFileParser(response.url)
body = ''
if hasattr(response, 'text'):
body = response.text
else: # last effort try
try:
body = response.body.decode('utf-8')
except __HOLE__:
... | UnicodeDecodeError | dataset/ETHPy150Open scrapy/scrapy/scrapy/downloadermiddlewares/robotstxt.py/RobotsTxtMiddleware._parse_robots |
2,431 | def get_object(self, request, object_id, from_field=None):
queryset = self.get_queryset(request)
if isinstance(queryset, TranslationQueryset): # will always be true once Django 1.9 is required
model = queryset.shared_model
if from_field is None:
field = model._met... | ValueError | dataset/ETHPy150Open KristianOellegaard/django-hvad/hvad/admin.py/TranslatableAdmin.get_object |
2,432 | def get_request(url, headers={}):
"""
Make a HTTP GET request to a url
"""
MAX_TRIES_ALLOWED = current.MAX_TRIES_ALLOWED
i = 0
while i < MAX_TRIES_ALLOWED:
try:
response = requests.get(url,
headers=headers,
... | RuntimeError | dataset/ETHPy150Open stopstalk/stopstalk-deployment/modules/sites/init.py/get_request |
2,433 | def test_bitfield():
try:
x = Bitfield(7, 'ab')
assert False
except ValueError:
pass
try:
x = Bitfield(7, 'ab')
assert False
except ValueError:
pass
try:
x = Bitfield(9, 'abc')
assert False
except ValueError:
pass
try:
... | ValueError | dataset/ETHPy150Open Cclleemm/FriendlyTorrent/src/tornado/BitTornado/bitfield.py/test_bitfield |
2,434 | def parse_defines(args):
"""
This parses a list of define argument in the form of -DNAME=VALUE or -DNAME (
which is treated as -DNAME=1).
"""
macros = {}
for arg in args:
try:
var, val = arg.split('=', 1)
except __HOLE__:
var = arg
val = '1'
... | ValueError | dataset/ETHPy150Open tonyfischetti/sake/sakelib/acts.py/parse_defines |
2,435 | def expand_macros(raw_text, macros):
"""
this gets called before the sakefile is parsed. it looks for
macros defined anywhere in the sakefile (the start of the line
is '#!') and then replaces all occurences of '$variable' with the
value defined in the macro. it then returns the contents of the
f... | IOError | dataset/ETHPy150Open tonyfischetti/sake/sakelib/acts.py/expand_macros |
2,436 | def find_fastq_pairs(fq1, fq2, out1, out2, tmpdir=None, quiet=False):
tmp1 = tempfile.NamedTemporaryFile(delete=False, prefix='.tmp', suffix='.gz', dir=tmpdir if tmpdir else os.path.dirname(fq1.fname))
tmp1_fname = tmp1.name
tmp1_out = gzip.GzipFile(fileobj=tmp1)
ngsutils.fastq.sort.fastq_sort(fq1, out... | StopIteration | dataset/ETHPy150Open ngsutils/ngsutils/ngsutils/fastq/properpairs.py/find_fastq_pairs |
2,437 | def __set_baudrate(self, baud):
"""setting baudrate if supported"""
log.info('Changing communication to %s baud', baud)
self.__writeln(UART_SETUP.format(baud=baud))
# Wait for the string to be sent before switching baud
time.sleep(0.1)
try:
self._port.setBaudr... | AttributeError | dataset/ETHPy150Open kmpm/nodemcu-uploader/nodemcu_uploader/uploader.py/Uploader.__set_baudrate |
2,438 | def __clear_buffers(self):
"""Clears the input and output buffers"""
try:
self._port.reset_input_buffer()
self._port.reset_output_buffer()
except __HOLE__:
#pySerial 2.7
self._port.flushInput()
self._port.flushOutput() | AttributeError | dataset/ETHPy150Open kmpm/nodemcu-uploader/nodemcu_uploader/uploader.py/Uploader.__clear_buffers |
2,439 | @register.filter
def highlight(value, language):
try:
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
except __HOLE__:
return value
# Can't use class-based colouring because the debug toolbar's css rul... | ImportError | dataset/ETHPy150Open hmarr/django-debug-toolbar-mongo/debug_toolbar_mongo/templatetags/mongo_debug_tags.py/highlight |
2,440 | def copy_except(self, src, exceptions):
dst = self.copy_none(src)
for name in dir(src):
setattr(dst, name, getattr(src, name))
for name in exceptions:
try:
delattr(dst, name)
except __HOLE__:
pass
return dst | AttributeError | dataset/ETHPy150Open ctxis/canape/CANAPE.Scripting/Lib/rexec.py/RExec.copy_except |
2,441 | def copy_only(self, src, names):
dst = self.copy_none(src)
for name in names:
try:
value = getattr(src, name)
except __HOLE__:
continue
setattr(dst, name, value)
return dst | AttributeError | dataset/ETHPy150Open ctxis/canape/CANAPE.Scripting/Lib/rexec.py/RExec.copy_only |
2,442 | def test():
import getopt, traceback
opts, args = getopt.getopt(sys.argv[1:], 'vt:')
verbose = 0
trusted = []
for o, a in opts:
if o == '-v':
verbose = verbose+1
if o == '-t':
trusted.append(a)
r = RExec(verbose=verbose)
if trusted:
r.ok_builti... | IOError | dataset/ETHPy150Open ctxis/canape/CANAPE.Scripting/Lib/rexec.py/test |
2,443 | def urlencode(query):
"""Encode a sequence of two-element tuples or dictionary into a URL query string.
This version is adapted from the standard library to understand operators in the
pyesgf.search.constraints module.
If the query arg is a sequence of two-element tuples, the order of the
paramete... | TypeError | dataset/ETHPy150Open stephenpascoe/esgf-pyclient/pyesgf/util.py/urlencode |
2,444 | def _iter_convert_to_object(self, iterable):
"""Iterable yields tuples of (binsha, mode, name), which will be converted
to the respective object representation"""
for binsha, mode, name in iterable:
path = join_path(self.path, name)
try:
yield self._map_id... | KeyError | dataset/ETHPy150Open gitpython-developers/GitPython/git/objects/tree.py/Tree._iter_convert_to_object |
2,445 | def start(self):
"""Starts the registry server (blocks)"""
if self.active:
raise ValueError("server is already running")
if self.sock is None:
raise ValueError("object disposed")
self.logger.debug("server started on %s:%s", *self.sock.getsockname())
try:
... | KeyboardInterrupt | dataset/ETHPy150Open sccn/SNAP/src/rpyc/utils/registry.py/RegistryServer.start |
2,446 | def get_content(response):
"Handle the incompatibilities between Django <=1.4 and 1.5+"
try:
return ''.join(chunk.decode() for chunk in response.streaming_content)
except __HOLE__:
return response.content | AttributeError | dataset/ETHPy150Open smartfile/django-transfer/django_transfer/tests.py/get_content |
2,447 | def _get_by_field(self, recs, k, v, return_singleton):
result = []
for ref, rec in recs.iteritems():
if rec.get(k) == v:
result.append(ref)
if return_singleton:
try:
return result[0]
except __HOLE__:
raise Failu... | IndexError | dataset/ETHPy150Open nii-cloud/dodai-compute/nova/virt/xenapi/fake.py/SessionBase._get_by_field |
2,448 | @PostOnly
def fetch_org_by_centroid(request):
try:
lat = float(request.POST.get('lat'))
lon = float(request.POST.get('lon'))
limit = float(request.POST.get('limit', 20))
except __HOLE__:
json_error(INVALID_CENTROID_ERROR)
orgs = Org.objects.filter(location__latitude__range =... | AttributeError | dataset/ETHPy150Open jumoconnect/openjumo/jumodjango/org/ajax/views.py/fetch_org_by_centroid |
2,449 | @PostOnly
def update_org(request):
try:
org = json.loads(request.POST.get('org', {}))
org_id = int(org['id'])
except __HOLE__:
json_error(INVALID_ORG_ID_ERROR)
str_fields = [
'name', 'email', 'phone_number', 'url', 'img_url',
'revenue', 'size'... | AttributeError | dataset/ETHPy150Open jumoconnect/openjumo/jumodjango/org/ajax/views.py/update_org |
2,450 | @PostOnly
def remove_org(request):
try:
id = getattr(request.POST, 'id')
org = Org.objects.get(id = id)
except __HOLE__, ObjectDoesNotExist:
return json_error(INVALID_ORG_ID_ERROR)
# TODO: so, uh, we need to figure out if the current user is authorized to do this?
org.delete()
... | AttributeError | dataset/ETHPy150Open jumoconnect/openjumo/jumodjango/org/ajax/views.py/remove_org |
2,451 | @PostOnly
def flag_org(request):
try:
org_id = getattr(request.POST, 'org_id')
org = Org.objects.get(id = org_id)
except __HOLE__, ObjectDoesNotExist:
return json_error(CANNOT_FLAG_ERROR)
# TODO: so, uh, we need to figure out if the current user is authorized to do this?
org.fla... | AttributeError | dataset/ETHPy150Open jumoconnect/openjumo/jumodjango/org/ajax/views.py/flag_org |
2,452 | def __call__(self, *args):
if not self.called:
self.called = True
cb, args, kw = self.tpl
try:
cb(*args, **kw)
finally:
try:
del self.tpl
except __HOLE__:
pass | AttributeError | dataset/ETHPy150Open veegee/guv/guv/hubs/timer.py/Timer.__call__ |
2,453 | def __init__(self, cardinal, config):
"""Registers a callback for URL detection."""
# Initialize logger
self.logger = logging.getLogger(__name__)
try:
self._max_description_length = config['max_description_length']
except KeyError:
self.logger.warning("No... | KeyError | dataset/ETHPy150Open JohnMaguire/Cardinal/plugins/wikipedia/plugin.py/WikipediaPlugin.__init__ |
2,454 | def get_signature(self, tip):
try:
with open(self.tip_path(tip), 'r') as fh:
data = fh.read()
if not data:
return ""
return (int(data),)
except __HOLE__:
return "" | IOError | dataset/ETHPy150Open richo/groundstation/groundstation/gref.py/Gref.get_signature |
2,455 | def get_obj(self, context):
if self.model and self.lookup:
if isinstance(self.lookup[1], template.Variable):
try:
lookup_val = self.lookup[1].resolve(context)
except template.VariableDoesNotExist, e:
log.warning('BoxNode: Templa... | AssertionError | dataset/ETHPy150Open ella/ella/ella/core/templatetags/core.py/BoxNode.get_obj |
2,456 | def catch_notimplementederror(f):
"""Decorator to simplify catching drivers raising NotImplementedError
If a particular call makes a driver raise NotImplementedError, we
log it so that we can extract this information afterwards to
automatically generate a hypervisor/feature support matrix."""
def w... | NotImplementedError | dataset/ETHPy150Open nii-cloud/dodai-compute/nova/tests/test_virt_drivers.py/catch_notimplementederror |
2,457 | def extractWord(text):
if not text:
return None
l = text.split(None, 1)
word = l[0]
try:
text = l[1]
except __HOLE__:
text = ''
return word, text | IndexError | dataset/ETHPy150Open twisted/ldaptor/ldaptor/schema.py/extractWord |
2,458 | def setup_module(module):
from nose import SkipTest
try:
import numpy
except __HOLE__:
raise SkipTest("segmentation.doctest requires numpy") | ImportError | dataset/ETHPy150Open nltk/nltk/nltk/test/segmentation_fixt.py/setup_module |
2,459 | def read_images(path, sz=None):
"""Reads the images in a given folder, resizes images on the fly if size is given.
Args:
path: Path to a folder with subfolders representing the subjects (persons).
sz: A tuple with the size Resizes
Returns:
A list [X,y]
X: The images, w... | IOError | dataset/ETHPy150Open fatcloud/PyCV-time/opencv-official-samples/2.4.9/facerec_demo.py/read_images |
2,460 | def float_list_to_int_dict(lst, bucket_size):
"""Takes a list of floats and a bucket size and return a dict of
{ n : count, ...} where the count is the number of floats that drop into
the range n * bucket_size to (n + 1) * bucket_size."""
ret = {}
for val in lst:
k = int(round(val / bucket_s... | KeyError | dataset/ETHPy150Open manahl/PythonTrainingExercises/Intermediate/Histogram/solution/DictHistogram.py/float_list_to_int_dict |
2,461 | def __get(self, name, obj, default=None):
try:
attr = getattr(self, name)
except __HOLE__:
return default
if callable(attr):
return attr(obj)
return attr | AttributeError | dataset/ETHPy150Open django/django/django/contrib/sitemaps/__init__.py/Sitemap.__get |
2,462 | def add_infos(self, *keyvals, **kwargs):
"""Adds the given info and returns a dict composed of just this added info."""
infos = dict(keyvals)
kv_pairs = []
for key, val in infos.items():
key = key.strip()
val = str(val).strip()
if ':' in key:
raise ValueError('info key "{}" mus... | IOError | dataset/ETHPy150Open pantsbuild/pants/src/python/pants/base/run_info.py/RunInfo.add_infos |
2,463 | def get_parsers(parsers_path):
parsers = {}
# For each directory in parsers path
for component_directory in parsers_path.split(os.path.pathsep):
# Add component directory to path
sys.path.insert(0, component_directory)
components_list = glob.glob(component_directory + '/*.py')
... | TypeError | dataset/ETHPy150Open ikotler/pythonect/pythonect/internal/parsers/__init__.py/get_parsers |
2,464 | def add_view(self, request, **kwargs):
kwargs['form_url'] = request.get_full_path() # Preserve GET parameters
if 'translation_of' in request.GET and 'language' in request.GET:
try:
original = self.model._tree_manager.get(
pk=request.GET.get('translation_o... | AttributeError | dataset/ETHPy150Open feincms/feincms/feincms/module/page/modeladmins.py/PageAdmin.add_view |
2,465 | def response_add(self, request, obj, *args, **kwargs):
response = super(PageAdmin, self).response_add(
request, obj, *args, **kwargs)
if ('parent' in request.GET
and '_addanother' in request.POST
and response.status_code in (301, 302)):
# Preserve ... | AttributeError | dataset/ETHPy150Open feincms/feincms/feincms/module/page/modeladmins.py/PageAdmin.response_add |
2,466 | def __getattr__(self, key):
try:
return self.__getitem__(key)
except __HOLE__:
# This lets you use dict-type attributes that aren't keys
return getattr(super(AttrDict, self), key) | KeyError | dataset/ETHPy150Open memsql/memsql-loader/memsql_loader/util/attr_dict.py/AttrDict.__getattr__ |
2,467 | def on_select_remote(self, remote_index):
"""
After the user selects a remote, display a panel of branches that are
present on that remote, then proceed to `on_select_branch`.
"""
# If the user pressed `esc` or otherwise cancelled.
if remote_index == -1:
retur... | ValueError | dataset/ETHPy150Open divmain/GitSavvy/github/commands/pull_request.py/GsCreatePullRequestCommand.on_select_remote |
2,468 | def changed(self, originally_changed):
Specification.changed(self, originally_changed)
try:
del self._v_attrs
except __HOLE__:
pass | AttributeError | dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/zope/interface/declarations.py/Declaration.changed |
2,469 | def implementedByFallback(cls):
"""Return the interfaces implemented for a class' instances
The value returned is an IDeclaration.
"""
try:
spec = cls.__dict__.get('__implemented__')
except AttributeError:
# we can't get the class dict. This is probably due to a
# securit... | AttributeError | dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/zope/interface/declarations.py/implementedByFallback |
2,470 | def __call__(self, ob):
if isinstance(ob, DescriptorAwareMetaClasses):
classImplements(ob, *self.interfaces)
return ob
spec = Implements(*self.interfaces)
try:
ob.__implemented__ = spec
except __HOLE__:
raise TypeError("Can't declare imple... | AttributeError | dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/zope/interface/declarations.py/implementer.__call__ |
2,471 | def getObjectSpecificationFallback(ob):
provides = getattr(ob, '__provides__', None)
if provides is not None:
if isinstance(provides, SpecificationBase):
return provides
try:
cls = ob.__class__
except __HOLE__:
# We can't get the class, so just consider provides
... | AttributeError | dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/zope/interface/declarations.py/getObjectSpecificationFallback |
2,472 | def providedByFallback(ob):
# Here we have either a special object, an old-style declaration
# or a descriptor
# Try to get __providedBy__
try:
r = ob.__providedBy__
except __HOLE__:
# Not set yet. Fall back to lower-level thing that computes it
return getObjectSpecificatio... | AttributeError | dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/zope/interface/declarations.py/providedByFallback |
2,473 | def __new__(cls, name, bases, attrs):
"""
Field shortcut creation:
Takes field names `db_*` and creates property wrappers named
without the `db_` prefix. So db_key -> key
This wrapper happens on the class level, so there is no
overhead when creating objects. If a class... | ObjectDoesNotExist | dataset/ETHPy150Open evennia/evennia/evennia/utils/idmapper/models.py/SharedMemoryModelBase.__new__ |
2,474 | @classmethod
def cache_instance(cls, instance, new=False):
"""
Method to store an instance in the cache.
Args:
instance (Class instance): the instance to cache.
new (bool, optional): this is the first time this instance is
cached (i.e. this is not an ... | AttributeError | dataset/ETHPy150Open evennia/evennia/evennia/utils/idmapper/models.py/SharedMemoryModel.cache_instance |
2,475 | @classmethod
def _flush_cached_by_key(cls, key, force=True):
"""
Remove the cached reference.
"""
try:
if force or not cls._idmapper_recache_protection:
del cls.__dbclass__.__instance_cache__[key]
except __HOLE__:
pass | KeyError | dataset/ETHPy150Open evennia/evennia/evennia/utils/idmapper/models.py/SharedMemoryModel._flush_cached_by_key |
2,476 | def import_model(self, name, path="floyd.db.models"):
"""imports a model of name from path, returning from local model
cache if it has been previously loaded otherwise importing"""
if name in self._model_cache:
return self._model_cache[name]
try:
model = getattr(__import__(path, None, Non... | ImportError | dataset/ETHPy150Open nikcub/floyd/floyd/db/__init__.py/DataStore.import_model |
2,477 | def jsonify(fnc):
def wrapper(*args, **kwargs):
ret = fnc(*args, **kwargs)
try:
json.loads(ret)
except __HOLE__:
# Value should already be JSON-encoded, but some operations
# may write raw sting values; this will catch those and
# properly enco... | ValueError | dataset/ETHPy150Open nii-cloud/dodai-compute/plugins/xenserver/xenapi/etc/xapi.d/plugins/xenstore.py/jsonify |
2,478 | @jsonify
def list_records(self, arg_dict):
"""Returns all the stored data at or below the given path for the
given dom_id. The data is returned as a json-ified dict, with the
path as the key and the stored value as the value. If the path
doesn't exist, an empty dict is returned.
"""
dirpath = "/... | ValueError | dataset/ETHPy150Open nii-cloud/dodai-compute/plugins/xenserver/xenapi/etc/xapi.d/plugins/xenstore.py/list_records |
2,479 | @view_config(route_name='admin_badge',
request_method='POST',
request_param='add',
renderer='h:templates/admin/badge.html.jinja2',
permission='admin_badge')
def badge_add(request):
try:
request.db.add(models.Blocklist(uri=request.params['add']))
except... | ValueError | dataset/ETHPy150Open hypothesis/h/h/admin/views/badge.py/badge_add |
2,480 | def compat_urllib_parse_unquote(string, encoding='utf-8', errors='replace'):
if string == '':
return string
res = string.split('%')
if len(res) == 1:
return string
if encoding is None:
encoding = 'utf-8'
if errors is None:
errors = ... | ValueError | dataset/ETHPy150Open yasoob/youtube-dl-GUI/youtube_dl/compat.py/compat_urllib_parse_unquote |
2,481 | def compat_expanduser(path):
"""Expand ~ and ~user constructions. If user or $HOME is unknown,
do nothing."""
if not path.startswith('~'):
return path
i = path.find('/', 1)
if i < 0:
i = len(path)
if i == 1:
... | KeyError | dataset/ETHPy150Open yasoob/youtube-dl-GUI/youtube_dl/compat.py/compat_expanduser |
2,482 | def compat_expanduser(path):
"""Expand ~ and ~user constructs.
If user or $HOME is unknown, do nothing."""
if path[:1] != '~':
return path
i, n = 1, len(path)
while i < n and path[i] not in '/\\':
i = i + 1
if 'HOM... | KeyError | dataset/ETHPy150Open yasoob/youtube-dl-GUI/youtube_dl/compat.py/compat_expanduser |
2,483 | def workaround_optparse_bug9161():
op = optparse.OptionParser()
og = optparse.OptionGroup(op, 'foo')
try:
og.add_option('-t')
except __HOLE__:
real_add_option = optparse.OptionGroup.add_option
def _compat_add_option(self, *args, **kwargs):
enc = lambda v: (
... | TypeError | dataset/ETHPy150Open yasoob/youtube-dl-GUI/youtube_dl/compat.py/workaround_optparse_bug9161 |
2,484 | def _mock_delete_addon(name, *args, **kwargs):
try:
active_addons.remove(name)
except __HOLE__:
pass | ValueError | dataset/ETHPy150Open CenterForOpenScience/osf.io/tests/test_registrations/test_archiver.py/_mock_delete_addon |
2,485 | def rm(path):
debg('Deleting %r' % path)
try:
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.remove(path)
except __HOLE__:
pass | OSError | dataset/ETHPy150Open kuri65536/python-for-android/python-build/build.py/rm |
2,486 | def settrace_and_raise(tracefunc):
try:
_settrace_and_raise(tracefunc)
except __HOLE__ as exc:
pass | RuntimeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_sys_settrace.py/settrace_and_raise |
2,487 | def tightloop_example():
items = range(0, 3)
try:
i = 0
while 1:
b = items[i]; i+=1
except __HOLE__:
pass | IndexError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_sys_settrace.py/tightloop_example |
2,488 | def tighterloop_example():
items = range(1, 4)
try:
i = 0
while 1: i = items[i]
except __HOLE__:
pass | IndexError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_sys_settrace.py/tighterloop_example |
2,489 | def run_test_for_event(self, event):
"""Tests that an exception raised in response to the given event is
handled OK."""
self.raiseOnEvent = event
try:
for i in range(sys.getrecursionlimit() + 1):
sys.settrace(self.trace)
try:
... | RuntimeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_sys_settrace.py/RaisingTraceFuncTestCase.run_test_for_event |
2,490 | def test_trash_stack(self):
def f():
for i in range(5):
print(i) # line tracing will raise an exception at this line
def g(frame, why, extra):
if (why == 'line' and
frame.f_lineno == f.__code__.co_firstlineno + 2):
raise RuntimeEr... | RuntimeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_sys_settrace.py/RaisingTraceFuncTestCase.test_trash_stack |
2,491 | def test_exception_arguments(self):
def f():
x = 0
# this should raise an error
x.no_such_attr
def g(frame, event, arg):
if (event == 'exception'):
type, exception, trace = arg
self.assertIsInstance(exception, Exception)
... | AttributeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_sys_settrace.py/RaisingTraceFuncTestCase.test_exception_arguments |
2,492 | def trace(self, frame, event, arg):
if not self.done and frame.f_code == self.function.__code__:
firstLine = frame.f_code.co_firstlineno
if event == 'line' and frame.f_lineno == firstLine + self.jumpFrom:
# Cope with non-integer self.jumpTo (because of
# n... | TypeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_sys_settrace.py/JumpTracer.trace |
2,493 | def no_jump_too_far_forwards(output):
try:
output.append(2)
output.append(3)
except __HOLE__ as e:
output.append('after' in str(e)) | ValueError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_sys_settrace.py/no_jump_too_far_forwards |
2,494 | def no_jump_too_far_backwards(output):
try:
output.append(2)
output.append(3)
except __HOLE__ as e:
output.append('before' in str(e)) | ValueError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_sys_settrace.py/no_jump_too_far_backwards |
2,495 | def no_jump_to_except_2(output):
try:
output.append(2)
except __HOLE__:
e = sys.exc_info()[1]
output.append('except' in str(e)) | ValueError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_sys_settrace.py/no_jump_to_except_2 |
2,496 | def no_jump_to_except_3(output):
try:
output.append(2)
except __HOLE__ as e:
output.append('except' in str(e)) | ValueError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_sys_settrace.py/no_jump_to_except_3 |
2,497 | def no_jump_to_except_4(output):
try:
output.append(2)
except (ValueError, __HOLE__) as e:
output.append('except' in str(e)) | RuntimeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_sys_settrace.py/no_jump_to_except_4 |
2,498 | def no_jump_forwards_into_block(output):
try:
output.append(2)
for i in 1, 2:
output.append(4)
except __HOLE__ as e:
output.append('into' in str(e)) | ValueError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_sys_settrace.py/no_jump_forwards_into_block |
2,499 | def no_jump_backwards_into_block(output):
try:
for i in 1, 2:
output.append(3)
output.append(4)
except __HOLE__ as e:
output.append('into' in str(e)) | ValueError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_sys_settrace.py/no_jump_backwards_into_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.