Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
8,000
def _test_main(): import os import readline import atexit # Setup history and readline facility for remote q: histfile = os.path.join(os.environ['HOME'], '.pyhistory') try: readline.read_history_file(histfile) except __HOLE__: pass atexit.register(readline.write_history_file, histfile) conn = connect() print('"conn" is your handle to rserve. Type e.g. "conn(\'1\')" ' 'for string evaluation.') # r('x<-1:20; y<-x*2; lm(y~x)') sc = open('../testData/test-script.R').read() v = conn.r(sc) open('r-test-png.png', 'w').write(v[3]) conn.r.v = 'abc' conn.r('func0 <- function() { 3 }') conn.r('func1 <- function(a1) { a1 }') conn.r('func2 <- function(a1, a2) { list(a1, a2) }') conn.r('funcKW <- function(a1=1, a2=4) { list(a1, a2) }') conn.r('squared<-function(t) t^2')
IOError
dataset/ETHPy150Open ralhei/pyRserve/pyRserve/rconn.py/_test_main
8,001
def get_acl_groups_by_object(self, object, permission): """ return list of groups that have access to object on "permission" permission """ ct = ContentType.objects.get_for_model(object) acl_groups_permissions = cache.get(ACL_GROUPS_PERMISSIONS_CACHE) if acl_groups_permissions is None: acl_groups_permissions = self.cache_acl_groups(object) else: try: acl_groups_permissions[ct.pk][object.pk] except __HOLE__: acl_groups_permissions = self.cache_acl_groups(object) try: return acl_groups_permissions[ct.pk][object.id][permission] except: return []
KeyError
dataset/ETHPy150Open zorna/zorna/zorna/acl/models.py/ACLPermissionManager.get_acl_groups_by_object
8,002
def get_acl_objects_by_model(self, user, model, permission): """ return all objects of the specified model for which user "user" have permission "permission" """ contenttype = ContentType.objects.get_for_model(model) ret = [] user_id = 0 if user.is_anonymous() else user.id acl_users_permissions = cache.get(ACL_USERS_PERMISSIONS_CACHE) if acl_users_permissions is None: acl_users_permissions = self.cache_user_permissions(user) else: try: acl_users_permissions[user_id] except __HOLE__: acl_users_permissions = self.cache_user_permissions(user) try: for obj, perm in acl_users_permissions[user_id][contenttype.id].iteritems(): try: if perm[permission]: ret.append(obj) except: pass except: pass return ret
KeyError
dataset/ETHPy150Open zorna/zorna/zorna/acl/models.py/ACLPermissionManager.get_acl_objects_by_model
8,003
def user_permissions(self, user, obj, perm): """ try: return self.get(user=user, permission = perm, object=obj.id) except ACLPermission.DoesNotExist: return False """ user_id = 0 if user.is_anonymous() else user.id acl_users_permissions = cache.get(ACL_USERS_PERMISSIONS_CACHE) if acl_users_permissions is None: acl_users_permissions = self.cache_user_permissions(user) else: try: acl_users_permissions[user_id] except __HOLE__: acl_users_permissions = self.cache_user_permissions(user) try: ct = ContentType.objects.get_for_model(obj) return acl_users_permissions[user_id][ct.pk][obj.id][perm.codename] except: return False
KeyError
dataset/ETHPy150Open zorna/zorna/zorna/acl/models.py/ACLPermissionManager.user_permissions
8,004
def get_acl_groups_forms(self, request, object_id, **kwargs): extra_context = {} obj = self.model.objects.get(pk=object_id) ct = ContentType.objects.get_for_model(obj) extra_context["object_name"] = unicode(obj) try: exclude = kwargs['exclude'] ob_list = UserGroup.objects.exclude(pk__in=exclude).order_by('lft') except: ob_list = UserGroup.objects.all().order_by('lft') template = 'acl/acl_groups.html' extra_context["proto_perm"] = None perm_object = obj if request.method == 'POST': if 'bupdate' not in request.POST: pr = request.POST.get("proto_perm", None) if pr: perm_object = self.model.objects.get(pk=pr) extra_context["proto_perm"] = perm_object.pk else: # obj.aclpermission_set.filter(group__isnull=False).delete() ACLPermission.objects.filter( object_id=obj.pk, content_type=ct, group__isnull=False).delete() temp = {} for ac in request.POST: if ac[:5] == 'perm_' and request.POST[ac] != "": acc = ac.split('_') try: temp[int(acc[2])].append(( acc[1], request.POST[ac])) except __HOLE__: temp[int(acc[2])] = [] temp[int(acc[2])].append(( acc[1], request.POST[ac])) if len(temp): grp = UserGroup.objects.in_bulk(temp.keys()) for g_id, g in grp.iteritems(): for c in temp[g_id]: self.add_perm(c[0], obj, g, c[1]) perm_object = obj # invalidate cache cache.delete(ACL_USERS_PERMISSIONS_CACHE) cache.delete(ACL_GROUPS_PERMISSIONS_CACHE) redirect = request.POST.get('next', None) if redirect: if '?' not in redirect: redirect = redirect + '?object_id=' + str(object_id) else: redirect = redirect + '&object_id=' + str(object_id) return HttpResponseRedirect(redirect) extra_context["verbs"] = {} for k, v in self.perms.iteritems(): extra_context["verbs"][k] = {} extra_context["verbs"][k]['text'] = _(v.name) # perm = # perm_object.aclpermission_set.select_related().filter(group__isnull=False) perm = ACLPermission.objects.select_related().filter( object_id=perm_object.pk, content_type=ct, group__isnull=False) parentsid = [] for ob in ob_list: if ob.pk > defines.ZORNA_GROUP_REGISTERED: ob.show_members = True else: ob.show_members = False ob.verbs = {} for k, v in self.perms.iteritems(): ob.verbs[k] = '' for g in perm: if g.group_id == ob.id and k == g.permission.codename: ob.verbs[k] = g.acltype if ob.parent_id not in parentsid: ob.parent_id = 0 parentsid.append(ob.pk) # e = # ZornaEntity.objects.filter(aclpermission__object__content_type=ContentType.objects.get_for_model(obj)).distinct() extra_context['perm_objects'] = {} # for c in e: # c = c.as_leaf_class() #TODO A optimiser # extra_context['perm_objects'].append(c) perm = ACLPermission.objects.select_related().filter( content_type=ct, group__isnull=False).exclude(object_id=obj.pk) for p in perm: try: extra_context['perm_objects'][ p.content_object.pk] = p.content_object except: pass extra_context['next'] = request.REQUEST.get('next', '') extra_context['object'] = obj extra_context['object_list'] = ob_list context = RequestContext(request) return render_to_response(template, extra_context, context_instance=context)
KeyError
dataset/ETHPy150Open zorna/zorna/zorna/acl/models.py/BaseACL.get_acl_groups_forms
8,005
def get_acl_users_forms(self, request, object_id, template='acl/user_acl_users.html'): extra_context = {} obj = self.model.objects.get(pk=object_id) ct = ContentType.objects.get_for_model(obj) extra_context["object_name"] = unicode(obj) acl_template = 'acl/acl_users.html' if request.method == 'POST': selected = request.POST.getlist('_selected_action') selected_verbs = request.POST.getlist('_selected_verbs') # delete permission # obj.aclpermission_set.filter(object=obj, # user__isnull=False).delete() ACLPermission.objects.filter( object_id=obj.pk, content_type=ct, user__isnull=False).delete() # add permission for cchecked users ol = User.objects.filter(pk__in=selected) for u in ol: for ac in request.POST: if ac[:5] == 'perm_' and request.POST[ac] != "": acc = ac.split('_') if acc[2] in selected and long(acc[2]) == u.pk: self.add_perm(acc[1], obj, u, request.POST[ac]) # add permission for new user u = request.POST.get("u", "") if u: u = User.objects.get(pk=u) check = get_acl_for_model(obj) for v in selected_verbs: check.add_perm(v, obj, u, defines.ZORNA_PERMISSIONS_ALLOW) # invalidate cache cache.delete(ACL_USERS_PERMISSIONS_CACHE) redirect = request.POST.get('next', None) if redirect: if '?' not in redirect: redirect = redirect + '?object_id=' + str(object_id) else: redirect = redirect + '&object_id=' + str(object_id) return HttpResponseRedirect(redirect) extra_context["verbs"] = {} for k, v in self.perms.iteritems(): extra_context["verbs"][k] = {} extra_context["verbs"][k]['text'] = _(v.name) ob_list = User.objects.filter( aclpermission__user__isnull=False, aclpermission__object_id=obj.pk, aclpermission__content_type=ct).distinct() # perm = obj.aclpermission_set.select_related().filter(object=obj, # user__isnull=False) perm = ACLPermission.objects.select_related().filter( object_id=obj.pk, content_type=ct, user__isnull=False) dummy = ob_list for ob in dummy: ob.verbs = {} for k, v in self.perms.iteritems(): ob.verbs[k] = '' for g in perm: if g.user_id == ob.id and k == g.permission.codename: ob.verbs[k] = g.acltype extra_context['users_list'] = dummy extra_context['object'] = obj extra_context['next'] = request.REQUEST.get('next', '') paginate_by = 20 paginator = Paginator( ob_list._clone(), paginate_by, allow_empty_first_page=True) page = request.GET.get('page', 1) try: page_number = int(page) except __HOLE__: if page == 'last': page_number = paginator.num_pages else: # Page is not 'last', nor can it be converted to an int. raise Http404 try: page_obj = paginator.page(page_number) except InvalidPage: raise Http404 extra_context['paginator'] = paginator extra_context['page_obj'] = page_obj extra_context['acl_form'] = render_to_string( acl_template, extra_context, context_instance=RequestContext(request)) context = RequestContext(request) if template: return render_to_response(template, extra_context, context_instance=context) else: return extra_context
ValueError
dataset/ETHPy150Open zorna/zorna/zorna/acl/models.py/BaseACL.get_acl_users_forms
8,006
def get_queryset(self, obj): if self.queryset is not None: queryset = self.queryset if hasattr(queryset, '_clone'): queryset = queryset._clone() elif self.model is not None: queryset = self.model._default_manager.all() else: raise ImproperlyConfigured(u"'%s' must define 'queryset' or 'model'" % self.__class__.__name__) if hasattr(queryset, 'using_translations'): queryset = queryset.using_translations() obj_field = self.get_obj_field(obj) if hasattr(self.get_model(), obj_field): extra_filter = {obj_field: obj} queryset = queryset.filter(**extra_filter) # Sortable Items if self.sortable: queryset = queryset.order_by(self.sortable_field) else: # Ordering Items if self.ordering: if isinstance(self.ordering, tuple) \ or isinstance(self.ordering, list): queryset = queryset.order_by(*self.ordering) else: queryset = queryset.order_by(self.ordering) else: # If no specific ordering, we try to use default Meta.ordering field. try: meta_ordering = self.model._meta.ordering except __HOLE__: # Else we order by the primary key meta_ordering = None if meta_ordering: queryset = queryset.order_by(*meta_ordering) else: queryset = queryset.order_by('pk') return queryset
AttributeError
dataset/ETHPy150Open ionyse/ionyweb/ionyweb/administration/actions/views.py/ActionAdminListView.get_queryset
8,007
def get_context_data(self, **kwargs): context = super(ActionAdminListView, self).get_context_data(**kwargs) model = self.get_model() context['verbose_name'] = model._meta.verbose_name context['verbose_name_plural'] = model._meta.verbose_name_plural context['sortable'] = self.sortable # List Display Field if self.list_display: list_display_title = [] for attr in self.list_display: # We first try in attribute (methods of model). try: attr_obj = getattr(model, attr) if hasattr(attr_obj, 'action_short_description'): desc = getattr(attr_obj, 'action_short_description') elif hasattr(attr_obj, 'short_description'): desc = getattr(attr_obj, 'short_description') else: desc = attr_obj.__func__.__name__ except __HOLE__: # We now check in model fields if hasattr(model._meta, 'translations_model') and \ attr in model._meta.translations_model._meta.get_all_field_names(): desc = model._meta.translations_model._meta.get_field(attr).verbose_name elif attr in model._meta.get_all_field_names(): desc = model._meta.get_field(attr).verbose_name else: raise ValueError(_(u"Caught ImproperlyConfigured while rendering: " u"ActionAdminListView.list_display, '%(attr)s' is not a " u"callable or an attribute of the model '%(model)s'.") \ % {'attr': attr, 'model': model}) list_display_title.append(desc) context['list_display_title'] = list_display_title context['list_display'] = self.list_display return context
AttributeError
dataset/ETHPy150Open ionyse/ionyweb/ionyweb/administration/actions/views.py/ActionAdminListView.get_context_data
8,008
def post(self, request, relation_id, app_obj, action_obj_pk=None, *args, **kwargs): objects_order = request.POST.getlist('action_objects_order[]') order = 1 for object_id in objects_order: object_pk = object_id.split('action-object-')[1] obj = self.get_object(object_pk) try: setattr(obj, self.sortable_field, order) except __HOLE__: raise ErrorResponse(status.HTTP_400_BAD_REQUEST, {'msg': MESSAGES.get('default_error', "")}) obj.save() order += 1 return self.render_to_response_with_refresh(relation_id, app_obj, msg=MESSAGES.get('item_edit_success', ''))
AttributeError
dataset/ETHPy150Open ionyse/ionyweb/ionyweb/administration/actions/views.py/ActionAdminOrderView.post
8,009
def setUp(self): self.old_TZ = os.environ.get('TZ') os.environ['TZ'] = 'Europe/Copenhagen' translation.activate('en-us') try: # Check if a timezone has been set time.tzset() self.tz_tests = True except __HOLE__: # No timezone available. Don't run the tests that require a TZ self.tz_tests = False
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/tests/regressiontests/utils/dateformat.py/DateFormatTests.setUp
8,010
def versions_from_vcs(tag_prefix, versionfile_source, verbose=False): # this runs 'git' from the root of the source tree. That either means # someone ran a setup.py command (and this code is in versioneer.py, so # IN_LONG_VERSION_PY=False, thus the containing directory is the root of # the source tree), or someone ran a project-specific entry point (and # this code is in _version.py, so IN_LONG_VERSION_PY=True, thus the # containing directory is somewhere deeper in the source tree). This only # gets called if the git-archive 'subst' variables were *not* expanded, # and _version.py hasn't already been rewritten with a short version # string, meaning we're inside a checked out source tree. try: here = os.path.realpath(__file__) except NameError: # some py2exe/bbfreeze/non-CPython implementations don't do __file__ return {} # not always correct # versionfile_source is the relative path from the top of the source tree # (where the .git directory might live) to this file. Invert this to find # the root from __file__. root = here if IN_LONG_VERSION_PY: for i in range(len(versionfile_source.split("/"))): root = os.path.dirname(root) else: root = os.path.dirname(here) if not os.path.exists(os.path.join(root, ".git")): if verbose: print("no .git in %s" % root) return {} stdout = run_command([GIT, "describe", "--tags", "--dirty", "--always"], cwd=root) if stdout is None: return {} if not stdout.startswith(tag_prefix): if verbose: print("tag '%s' doesn't start with prefix '%s'" % (stdout, tag_prefix)) return {} tag = stdout[len(tag_prefix):] stdout = run_command([GIT, "rev-parse", "HEAD"], cwd=root) if stdout is None: return {} full = stdout.strip() if tag.endswith("-dirty"): full += "-dirty" # accomodate to our devel build process try: from bokeh.__conda_version__ import conda_version tag = conda_version.replace("'","") del conda_version except __HOLE__: pass return {"version": tag, "full": full}
ImportError
dataset/ETHPy150Open bokeh/bokeh/versioneer.py/versions_from_vcs
8,011
def versions_from_parentdir(parentdir_prefix, versionfile_source, verbose=False): if IN_LONG_VERSION_PY: # We're running from _version.py. If it's from a source tree # (execute-in-place), we can work upwards to find the root of the # tree, and then check the parent directory for a version string. If # it's in an installed application, there's no hope. try: here = os.path.realpath(__file__) except __HOLE__: # py2exe/bbfreeze/non-CPython don't have __file__ return {} # without __file__, we have no hope # versionfile_source is the relative path from the top of the source # tree to _version.py. Invert this to find the root from __file__. root = here for i in range(len(versionfile_source.split("/"))): root = os.path.dirname(root) else: # we're running from versioneer.py, which means we're running from # the setup.py in a source tree. sys.argv[0] is setup.py in the root. here = os.path.realpath(sys.argv[0]) root = os.path.dirname(here) # Source tarballs conventionally unpack into a directory that includes # both the project name and a version string. dirname = os.path.basename(root) if not dirname.startswith(parentdir_prefix): if verbose: print("guessing rootdir is '%s', but '%s' doesn't start with prefix '%s'" % (root, dirname, parentdir_prefix)) return None return {"version": dirname[len(parentdir_prefix):], "full": ""}
NameError
dataset/ETHPy150Open bokeh/bokeh/versioneer.py/versions_from_parentdir
8,012
def find_site(): """Find the site by looking at the environment.""" try: settings_module = os.environ['DJANGO_SETTINGS_MODULE'] except __HOLE__: raise AssertionError("DJANGO_SETTINGS_MODULE not set.") settingsl = settings_module.split('.') site = __import__(settingsl[0]) settings = __import__(settings_module, {}, {}, settingsl[-1]) return site, settings
KeyError
dataset/ETHPy150Open dokterbob/satchmo/satchmo/projects/load_data.py/find_site
8,013
def delete_db(settings): """Delete the old database.""" engine = settings.DATABASE_ENGINE if engine == 'sqlite3': try: os.unlink(settings.DATABASE_NAME) except __HOLE__: pass elif engine == 'mysql': import _mysql s = _mysql.connect(host=settings.DATABASE_HOST, user=settings.DATABASE_USER, passwd=settings.DATABASE_PASSWORD) for cmd in ['drop database if exists %s', 'create database %s CHARACTER SET utf8 COLLATE utf8_general_ci']: s.query(cmd % settings.DATABASE_NAME) elif engine in ('postgresql', 'postgresql_psycopg2'): if settings.DATABASE_NAME == '': raise AssertionError("You must specify a value for DATABASE_NAME in local_settings.py.") if settings.DATABASE_USER == '': raise AssertionError("You must specify a value for DATABASE_USER in local_settings.py.") params=" --username=%s --password" % settings.DATABASE_USER if settings.DATABASE_HOST: params += " --host=%s" % settings.DATABASE_HOST if settings.DATABASE_PORT: params += " --port=%s" % settings.DATABASE_PORT params += " %s" % settings.DATABASE_NAME print("""You will be prompted for the password for the user '%s' twice. Once to drop the existing database and then a second time to create the database.""" % settings.DATABASE_USER) for cmd in ['dropdb %s', 'createdb %s']: os.system(cmd % params) else: raise AssertionError("Unknown database engine %s" % engine)
OSError
dataset/ETHPy150Open dokterbob/satchmo/satchmo/projects/load_data.py/delete_db
8,014
def eraseDB(all=False): """Erase database and init it""" try: site, settings = find_site() if all: delete_db(settings) print "All data successfully deleted." else: delete_satchmo() print "Satchmo data successfully deleted." init_and_install() except __HOLE__, ex: print ex.args[0]
AssertionError
dataset/ETHPy150Open dokterbob/satchmo/satchmo/projects/load_data.py/eraseDB
8,015
def unregister(model_or_iterable, fail_silently=False): ''' Remove one or more models from the autofixture registry. ''' from django.db import models from .compat import get_model if issubclass(model_or_iterable, models.Model): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if isinstance(model, string_types): model = get_model(*model.split('.', 1)) try: del REGISTRY[model] except __HOLE__: if fail_silently: continue raise ValueError( u'The model %s.%s is not registered.' % ( model._meta.app_label, model._meta.object_name, ))
KeyError
dataset/ETHPy150Open gregmuellegger/django-autofixture/autofixture/__init__.py/unregister
8,016
def autodiscover(): ''' Auto-discover INSTALLED_APPS autofixtures.py and tests.py modules and fail silently when not present. This forces an import on them to register any autofixture bits they may want. ''' from .compat import importlib # Bail out if autodiscover didn't finish loading from a previous call so # that we avoid running autodiscover again when the URLconf is loaded by # the exception handler to resolve the handler500 view. This prevents an # autofixtures.py module with errors from re-registering models and raising a # spurious AlreadyRegistered exception (see #8245). global LOADING if LOADING: return LOADING = True app_paths = {} # For each app, we need to look for an autofixture.py inside that app's # package. We can't use os.path here -- recall that modules may be # imported different ways (think zip files) -- so we need to get # the app's __path__ and look for autofixture.py on that path. # Step 1: find out the app's __path__ Import errors here will (and # should) bubble up, but a missing __path__ (which is legal, but weird) # fails silently -- apps that do weird things with __path__ might # need to roll their own autofixture registration. import imp try: from django.apps import apps for app_config in apps.get_app_configs(): app_paths[app_config.name] = [app_config.path] except ImportError: # Django < 1.7 from django.conf import settings for app in settings.INSTALLED_APPS: mod = importlib.import_module(app) try: app_paths[app] = mod.__path__ except __HOLE__: continue for app, app_path in app_paths.items(): # Step 2: use imp.find_module to find the app's autofixtures.py. For some # reason imp.find_module raises ImportError if the app can't be found # but doesn't actually try to import the module. So skip this app if # its autofixtures.py doesn't exist try: file, _, _ = imp.find_module('autofixtures', app_path) except ImportError: continue else: if file: file.close() # Step 3: import the app's autofixtures file. If this has errors we want them # to bubble up. try: importlib.import_module("%s.autofixtures" % app) except Exception as e: warnings.warn(u'Error while importing %s.autofixtures: %r' % (app, e)) for app, app_path in app_paths.items(): try: file, _, _ = imp.find_module('tests', app_path) except ImportError: continue else: if file: file.close() try: importlib.import_module("%s.tests" % app) except Exception as e: warnings.warn(u'Error while importing %s.tests: %r' % (app, e)) # autodiscover was successful, reset loading flag. LOADING = False
AttributeError
dataset/ETHPy150Open gregmuellegger/django-autofixture/autofixture/__init__.py/autodiscover
8,017
def __init__( self, toklist=None, name=None, asList=True, modal=True, isinstance=isinstance ): if self.__doinit: self.__doinit = False self.__name = None self.__parent = None self.__accumNames = {} self.__asList = asList self.__modal = modal if toklist is None: toklist = [] if isinstance(toklist, list): self.__toklist = toklist[:] elif isinstance(toklist, _generatorType): self.__toklist = list(toklist) else: self.__toklist = [toklist] self.__tokdict = dict() if name is not None and name: if not modal: self.__accumNames[name] = 0 if isinstance(name,int): name = _ustr(name) # will always return a str, but use _ustr for consistency self.__name = name if not (isinstance(toklist, (type(None), basestring, list)) and toklist in (None,'',[])): if isinstance(toklist,basestring): toklist = [ toklist ] if asList: if isinstance(toklist,ParseResults): self[name] = _ParseResultsWithOffset(toklist.copy(),0) else: self[name] = _ParseResultsWithOffset(ParseResults(toklist[0]),0) self[name].__name = name else: try: self[name] = toklist[0] except (KeyError,__HOLE__,IndexError): self[name] = toklist
TypeError
dataset/ETHPy150Open pypa/pip/pip/_vendor/pyparsing.py/ParseResults.__init__
8,018
def __getattr__( self, name ): try: return self[name] except __HOLE__: return "" if name in self.__tokdict: if name not in self.__accumNames: return self.__tokdict[name][-1][0] else: return ParseResults([ v[0] for v in self.__tokdict[name] ]) else: return ""
KeyError
dataset/ETHPy150Open pypa/pip/pip/_vendor/pyparsing.py/ParseResults.__getattr__
8,019
def _trim_arity(func, maxargs=2): if func in singleArgBuiltins: return lambda s,l,t: func(t) limit = [0] foundArity = [False] def wrapper(*args): while 1: try: ret = func(*args[limit[0]:]) #~@$^*)+_(&%#!=-`~;:"[]{} foundArity[0] = True return ret except __HOLE__: # re-raise TypeErrors if they did not come from our arity testing if foundArity[0]: raise else: try: tb = sys.exc_info()[-1] exc_source_line = traceback.extract_tb(tb)[-1][-1] if not exc_source_line.endswith('#~@$^*)+_(&%#!=-`~;:"[]{}'): raise finally: del tb if limit[0] <= maxargs: limit[0] += 1 continue raise return wrapper
TypeError
dataset/ETHPy150Open pypa/pip/pip/_vendor/pyparsing.py/_trim_arity
8,020
def _parseNoCache( self, instring, loc, doActions=True, callPreParse=True ): debugging = ( self.debug ) #and doActions ) if debugging or self.failAction: #~ print ("Match",self,"at loc",loc,"(%d,%d)" % ( lineno(loc,instring), col(loc,instring) )) if (self.debugActions[0] ): self.debugActions[0]( instring, loc, self ) if callPreParse and self.callPreparse: preloc = self.preParse( instring, loc ) else: preloc = loc tokensStart = preloc try: try: loc,tokens = self.parseImpl( instring, preloc, doActions ) except __HOLE__: raise ParseException( instring, len(instring), self.errmsg, self ) except ParseBaseException as err: #~ print ("Exception raised:", err) if self.debugActions[2]: self.debugActions[2]( instring, tokensStart, self, err ) if self.failAction: self.failAction( instring, tokensStart, self, err ) raise else: if callPreParse and self.callPreparse: preloc = self.preParse( instring, loc ) else: preloc = loc tokensStart = preloc if self.mayIndexError or loc >= len(instring): try: loc,tokens = self.parseImpl( instring, preloc, doActions ) except IndexError: raise ParseException( instring, len(instring), self.errmsg, self ) else: loc,tokens = self.parseImpl( instring, preloc, doActions ) tokens = self.postParse( instring, loc, tokens ) retTokens = ParseResults( tokens, self.resultsName, asList=self.saveAsList, modal=self.modalResults ) if self.parseAction and (doActions or self.callDuringTry): if debugging: try: for fn in self.parseAction: tokens = fn( instring, tokensStart, retTokens ) if tokens is not None: retTokens = ParseResults( tokens, self.resultsName, asList=self.saveAsList and isinstance(tokens,(ParseResults,list)), modal=self.modalResults ) except ParseBaseException as err: #~ print "Exception raised in user parse action:", err if (self.debugActions[2] ): self.debugActions[2]( instring, tokensStart, self, err ) raise else: for fn in self.parseAction: tokens = fn( instring, tokensStart, retTokens ) if tokens is not None: retTokens = ParseResults( tokens, self.resultsName, asList=self.saveAsList and isinstance(tokens,(ParseResults,list)), modal=self.modalResults ) if debugging: #~ print ("Matched",self,"->",retTokens.asList()) if (self.debugActions[1] ): self.debugActions[1]( instring, tokensStart, loc, self, retTokens ) return loc, retTokens
IndexError
dataset/ETHPy150Open pypa/pip/pip/_vendor/pyparsing.py/ParserElement._parseNoCache
8,021
def canParseNext(self, instring, loc): try: self.tryParse(instring, loc) except (ParseException, __HOLE__): return False else: return True # this method gets repeatedly called during backtracking with the same arguments - # we can cache these arguments and save ourselves the trouble of re-parsing the contained expression
IndexError
dataset/ETHPy150Open pypa/pip/pip/_vendor/pyparsing.py/ParserElement.canParseNext
8,022
def parseFile( self, file_or_filename, parseAll=False ): """Execute the parse expression on the given file or filename. If a filename is specified (instead of a file object), the entire file is opened, read, and closed before parsing. """ try: file_contents = file_or_filename.read() except __HOLE__: f = open(file_or_filename, "r") file_contents = f.read() f.close() try: return self.parseString(file_contents, parseAll) except ParseBaseException as exc: if ParserElement.verbose_stacktrace: raise else: # catch and re-raise exception from here, clears out pyparsing internal stack trace raise exc
AttributeError
dataset/ETHPy150Open pypa/pip/pip/_vendor/pyparsing.py/ParserElement.parseFile
8,023
def __init__( self, matchString ): super(Literal,self).__init__() self.match = matchString self.matchLen = len(matchString) try: self.firstMatchChar = matchString[0] except __HOLE__: warnings.warn("null string passed to Literal; use Empty() instead", SyntaxWarning, stacklevel=2) self.__class__ = Empty self.name = '"%s"' % _ustr(self.match) self.errmsg = "Expected " + self.name self.mayReturnEmpty = False self.mayIndexError = False # Performance tuning: this routine gets called a *lot* # if this is a single character match string and the first character matches, # short-circuit as quickly as possible, and avoid calling startswith #~ @profile
IndexError
dataset/ETHPy150Open pypa/pip/pip/_vendor/pyparsing.py/Literal.__init__
8,024
def __init__( self, matchString, identChars=DEFAULT_KEYWORD_CHARS, caseless=False ): super(Keyword,self).__init__() self.match = matchString self.matchLen = len(matchString) try: self.firstMatchChar = matchString[0] except __HOLE__: warnings.warn("null string passed to Keyword; use Empty() instead", SyntaxWarning, stacklevel=2) self.name = '"%s"' % self.match self.errmsg = "Expected " + self.name self.mayReturnEmpty = False self.mayIndexError = False self.caseless = caseless if caseless: self.caselessmatch = matchString.upper() identChars = identChars.upper() self.identChars = set(identChars)
IndexError
dataset/ETHPy150Open pypa/pip/pip/_vendor/pyparsing.py/Keyword.__init__
8,025
def __init__( self, exprs, savelist = False ): super(ParseExpression,self).__init__(savelist) if isinstance( exprs, _generatorType ): exprs = list(exprs) if isinstance( exprs, basestring ): self.exprs = [ Literal( exprs ) ] elif isinstance( exprs, collections.Sequence ): # if sequence of strings provided, wrap with Literal if all(isinstance(expr, basestring) for expr in exprs): exprs = map(Literal, exprs) self.exprs = list(exprs) else: try: self.exprs = list( exprs ) except __HOLE__: self.exprs = [ exprs ] self.callPreparse = False
TypeError
dataset/ETHPy150Open pypa/pip/pip/_vendor/pyparsing.py/ParseExpression.__init__
8,026
def parseImpl( self, instring, loc, doActions=True ): # pass False as last arg to _parse for first element, since we already # pre-parsed the string as part of our And pre-parsing loc, resultlist = self.exprs[0]._parse( instring, loc, doActions, callPreParse=False ) errorStop = False for e in self.exprs[1:]: if isinstance(e, And._ErrorStop): errorStop = True continue if errorStop: try: loc, exprtokens = e._parse( instring, loc, doActions ) except ParseSyntaxException: raise except ParseBaseException as pe: pe.__traceback__ = None raise ParseSyntaxException(pe) except __HOLE__: raise ParseSyntaxException( ParseException(instring, len(instring), self.errmsg, self) ) else: loc, exprtokens = e._parse( instring, loc, doActions ) if exprtokens or exprtokens.haskeys(): resultlist += exprtokens return loc, resultlist
IndexError
dataset/ETHPy150Open pypa/pip/pip/_vendor/pyparsing.py/And.parseImpl
8,027
def parseImpl( self, instring, loc, doActions=True ): maxExcLoc = -1 maxException = None matches = [] for e in self.exprs: try: loc2 = e.tryParse( instring, loc ) except ParseException as err: err.__traceback__ = None if err.loc > maxExcLoc: maxException = err maxExcLoc = err.loc except __HOLE__: if len(instring) > maxExcLoc: maxException = ParseException(instring,len(instring),e.errmsg,self) maxExcLoc = len(instring) else: # save match among all matches, to retry longest to shortest matches.append((loc2, e)) if matches: matches.sort(key=lambda x: -x[0]) for _,e in matches: try: return e._parse( instring, loc, doActions ) except ParseException as err: err.__traceback__ = None if err.loc > maxExcLoc: maxException = err maxExcLoc = err.loc if maxException is not None: maxException.msg = self.errmsg raise maxException else: raise ParseException(instring, loc, "no defined alternatives to match", self)
IndexError
dataset/ETHPy150Open pypa/pip/pip/_vendor/pyparsing.py/Or.parseImpl
8,028
def parseImpl( self, instring, loc, doActions=True ): maxExcLoc = -1 maxException = None for e in self.exprs: try: ret = e._parse( instring, loc, doActions ) return ret except ParseException as err: if err.loc > maxExcLoc: maxException = err maxExcLoc = err.loc except __HOLE__: if len(instring) > maxExcLoc: maxException = ParseException(instring,len(instring),e.errmsg,self) maxExcLoc = len(instring) # only got here if no expression matched, raise exception for match that made it the furthest else: if maxException is not None: maxException.msg = self.errmsg raise maxException else: raise ParseException(instring, loc, "no defined alternatives to match", self)
IndexError
dataset/ETHPy150Open pypa/pip/pip/_vendor/pyparsing.py/MatchFirst.parseImpl
8,029
def parseImpl( self, instring, loc, doActions=True ): self_expr_parse = self.expr._parse self_skip_ignorables = self._skipIgnorables check_ender = self.not_ender is not None if check_ender: try_not_ender = self.not_ender.tryParse # must be at least one (but first see if we are the stopOn sentinel; # if so, fail) if check_ender: try_not_ender(instring, loc) loc, tokens = self_expr_parse( instring, loc, doActions, callPreParse=False ) try: hasIgnoreExprs = (not not self.ignoreExprs) while 1: if check_ender: try_not_ender(instring, loc) if hasIgnoreExprs: preloc = self_skip_ignorables( instring, loc ) else: preloc = loc loc, tmptokens = self_expr_parse( instring, preloc, doActions ) if tmptokens or tmptokens.haskeys(): tokens += tmptokens except (ParseException,__HOLE__): pass return loc, tokens
IndexError
dataset/ETHPy150Open pypa/pip/pip/_vendor/pyparsing.py/OneOrMore.parseImpl
8,030
def parseImpl( self, instring, loc, doActions=True ): try: return super(ZeroOrMore, self).parseImpl(instring, loc, doActions) except (ParseException,__HOLE__): return loc, []
IndexError
dataset/ETHPy150Open pypa/pip/pip/_vendor/pyparsing.py/ZeroOrMore.parseImpl
8,031
def parseImpl( self, instring, loc, doActions=True ): try: loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False ) except (ParseException,__HOLE__): if self.defaultValue is not _optionalNotMatched: if self.expr.resultsName: tokens = ParseResults([ self.defaultValue ]) tokens[self.expr.resultsName] = self.defaultValue else: tokens = [ self.defaultValue ] else: tokens = [] return loc, tokens
IndexError
dataset/ETHPy150Open pypa/pip/pip/_vendor/pyparsing.py/Optional.parseImpl
8,032
def parseImpl( self, instring, loc, doActions=True ): startloc = loc instrlen = len(instring) expr = self.expr expr_parse = self.expr._parse self_failOn_canParseNext = self.failOn.canParseNext if self.failOn is not None else None self_ignoreExpr_tryParse = self.ignoreExpr.tryParse if self.ignoreExpr is not None else None tmploc = loc while tmploc <= instrlen: if self_failOn_canParseNext is not None: # break if failOn expression matches if self_failOn.canParseNext(instring, tmploc): break if self_ignoreExpr_tryParse is not None: # advance past ignore expressions while 1: try: tmploc = self_ignoreExpr_tryParse(instring, tmploc) except ParseBaseException: break try: expr_parse(instring, tmploc, doActions=False, callPreParse=False) except (ParseException, __HOLE__): # no match, advance loc in string tmploc += 1 else: # matched skipto expr, done break else: # ran off the end of the input string without matching skipto expr, fail raise ParseException(instring, loc, self.errmsg, self) # build up return values loc = tmploc skiptext = instring[startloc:loc] skipresult = ParseResults(skiptext) if self.includeMatch: loc, mat = expr_parse(instring,loc,doActions,callPreParse=False) skipresult += mat return loc, skipresult
IndexError
dataset/ETHPy150Open pypa/pip/pip/_vendor/pyparsing.py/SkipTo.parseImpl
8,033
def traceParseAction(f): """Decorator for debugging parse actions.""" f = _trim_arity(f) def z(*paArgs): thisFunc = f.func_name s,l,t = paArgs[-3:] if len(paArgs)>3: thisFunc = paArgs[0].__class__.__name__ + '.' + thisFunc sys.stderr.write( ">>entering %s(line: '%s', %d, %s)\n" % (thisFunc,line(l,s),l,t) ) try: ret = f(*paArgs) except Exception as exc: sys.stderr.write( "<<leaving %s (exception: %s)\n" % (thisFunc,exc) ) raise sys.stderr.write( "<<leaving %s (ret: %s)\n" % (thisFunc,ret) ) return ret try: z.__name__ = f.__name__ except __HOLE__: pass return z # # global helpers #
AttributeError
dataset/ETHPy150Open pypa/pip/pip/_vendor/pyparsing.py/traceParseAction
8,034
def _format_status(self, image): """Update the status field to standardize format.""" status_mapping = { 'active': 'ACTIVE', 'queued': 'SAVING', 'saving': 'SAVING', 'deleted': 'DELETED', 'pending_delete': 'DELETED', 'killed': 'ERROR', } try: image['status'] = status_mapping[image['status']] except __HOLE__: image['status'] = 'UNKNOWN'
KeyError
dataset/ETHPy150Open nii-cloud/dodai-compute/nova/api/openstack/views/images.py/ViewBuilder._format_status
8,035
def _build_server(self, image, image_obj): try: image['serverId'] = int(image_obj['properties']['instance_id']) except (KeyError, __HOLE__): pass
ValueError
dataset/ETHPy150Open nii-cloud/dodai-compute/nova/api/openstack/views/images.py/ViewBuilderV10._build_server
8,036
def _build_image_id(self, image, image_obj): try: image['id'] = int(image_obj['id']) except __HOLE__: pass
ValueError
dataset/ETHPy150Open nii-cloud/dodai-compute/nova/api/openstack/views/images.py/ViewBuilderV10._build_image_id
8,037
def _build_server(self, image, image_obj): try: serverRef = image_obj['properties']['instance_ref'] image['server'] = { "id": common.get_id_from_href(serverRef), "links": [ { "rel": "self", "href": serverRef, }, { "rel": "bookmark", "href": common.remove_version_from_href(serverRef), }, ] } except __HOLE__: return
KeyError
dataset/ETHPy150Open nii-cloud/dodai-compute/nova/api/openstack/views/images.py/ViewBuilderV11._build_server
8,038
def vtk_version_changed(zipfile): """Checks the ZIP file's VTK build version versus the current installed version of VTK and returns `True` if the versions are different. """ result = True if os.path.exists(zipfile): import vtk vtk_version = vtk.vtkVersion().GetVTKVersion()[:3] sys.path.append(zipfile) try: from tvtk_classes.vtk_version import vtk_build_version except __HOLE__: result = True else: if vtk_version != vtk_build_version: result = True else: result = False sys.path.pop() return result
ImportError
dataset/ETHPy150Open enthought/mayavi/tvtk/setup.py/vtk_version_changed
8,039
def test_to_object_array_tuples(self): r = (5, 6) values = [r] result = lib.to_object_array_tuples(values) try: # make sure record array works from collections import namedtuple record = namedtuple('record', 'x y') r = record(5, 6) values = [r] result = lib.to_object_array_tuples(values) # noqa except __HOLE__: pass
ImportError
dataset/ETHPy150Open pydata/pandas/pandas/tests/test_tseries.py/TestTypeInference.test_to_object_array_tuples
8,040
@login_required def display_resource(request, id): res = Resource.objects.get(pk=id) file = res.content.path.split("/")[-1] opts = {'object':res,'file':file} ext = opts['file'].split(".")[-1] opts['type'] = 'file' if ext in IMAGE_EXTS: opts['type'] = "image" elif ext in ZIP_EXTS: try: opts['type'] = "zip" zf = ZipFile(res.content.path,'r') opts['files_list'] = zf.namelist() zf.close() except IOError: opts['type'] = "file" else: try: lexer = get_lexer_for_filename(file) f = open(res.content.path,'r') data = f.read() f.close() opts['highlighted_code'] = highlight(data,lexer,HtmlFormatter()) opts['type'] = "code" except ClassNotFound: opts['type'] = "file" except __HOLE__: opts['type'] = "file" return render_to_response('lifeflow/editor/resource.html',opts,RequestContext(request, {}))
IOError
dataset/ETHPy150Open lethain/lifeflow/editor/views.py/display_resource
8,041
@login_required def edited_to_published(request, id): def check(dict): complaints = [] if dict[u"title"] in [None, u""]: complaints.append("You need to give the entry a title first.") if dict[u"body"] in [None, u""]: complaints.append("You'll need to fill out the article a bit before publishing it.") if complaints == []: return True else: return "\n<br>\n".join(complaints) def transform(draft): dict = draft.__dict__.copy() del dict['id'] if dict['pub_date'] is None: dict['pub_date'] = datetime.datetime.now() del dict['edited'] if dict['slug'] is None and dict['title'] is not None: dict['slug'] = sluggify(dict['title']) entry = Entry(**dict) valid = check(entry.__dict__) if valid != True: return None, valid else: entry.save() for field in MANY_TO_MANY_FIELDS: getattr(entry, field).add(*getattr(draft, field).all()) return entry, True try: draft = Draft.objects.get(pk=id) entry, result = transform(draft) if result == True: draft.delete() return HttpResponse(u"%s" % entry.pk) else: return HttpResponseServerError(result) except __HOLE__: return HttpResponseServerError(u"The draft is missing required fields.") except: return HttpResponseServerError(u"The update made it to the server, but failed for unknown reasons.")
TypeError
dataset/ETHPy150Open lethain/lifeflow/editor/views.py/edited_to_published
8,042
def _send(self, message): try: message = self._copy_message(message) except (__HOLE__, aeemail.InvalidEmailError), err: import logging logging.warn(err) if not self.fail_silently: raise return False if self.can_defer: self._defer_message(message) return True try: message.send() except (aeemail.Error, apiproxy_errors.Error): if not self.fail_silently: raise return False return True
ValueError
dataset/ETHPy150Open adieu/djangoappengine/mail.py/EmailBackend._send
8,043
def CheckPrereq(self): """Check prerequisites. This checks that the instance and node names are valid. """ self.instance = self.cfg.GetInstanceInfoByName(self.op.instance_name) assert self.instance is not None, \ "Cannot retrieve locked instance %s" % self.op.instance_name CheckNodeOnline(self, self.instance.primary_node) if (self.op.remove_instance and self.instance.admin_state == constants.ADMINST_UP and not self.op.shutdown): raise errors.OpPrereqError("Can not remove instance without shutting it" " down before", errors.ECODE_STATE) if self.op.mode == constants.EXPORT_MODE_LOCAL: self.dst_node = self.cfg.GetNodeInfo(self.op.target_node_uuid) assert self.dst_node is not None CheckNodeOnline(self, self.dst_node.uuid) CheckNodeNotDrained(self, self.dst_node.uuid) self._cds = None self.dest_disk_info = None self.dest_x509_ca = None elif self.op.mode == constants.EXPORT_MODE_REMOTE: self.dst_node = None if len(self.op.target_node) != len(self.instance.disks): raise errors.OpPrereqError(("Received destination information for %s" " disks, but instance %s has %s disks") % (len(self.op.target_node), self.op.instance_name, len(self.instance.disks)), errors.ECODE_INVAL) cds = GetClusterDomainSecret() # Check X509 key name try: (key_name, hmac_digest, hmac_salt) = self.x509_key_name except (__HOLE__, ValueError), err: raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err, errors.ECODE_INVAL) if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt): raise errors.OpPrereqError("HMAC for X509 key name is wrong", errors.ECODE_INVAL) # Load and verify CA try: (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds) except OpenSSL.crypto.Error, err: raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" % (err, ), errors.ECODE_INVAL) (errcode, msg) = utils.VerifyX509Certificate(cert, None, None) if errcode is not None: raise errors.OpPrereqError("Invalid destination X509 CA (%s)" % (msg, ), errors.ECODE_INVAL) self.dest_x509_ca = cert # Verify target information disk_info = [] for idx, disk_data in enumerate(self.op.target_node): try: (host, port, magic) = \ masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data) except errors.GenericError, err: raise errors.OpPrereqError("Target info for disk %s: %s" % (idx, err), errors.ECODE_INVAL) disk_info.append((host, port, magic)) assert len(disk_info) == len(self.op.target_node) self.dest_disk_info = disk_info else: raise errors.ProgrammerError("Unhandled export mode %r" % self.op.mode) # Check prerequisites for zeroing if self.op.zero_free_space: # Check that user shutdown detection has been enabled hvparams = self.cfg.GetClusterInfo().FillHV(self.instance) if self.instance.hypervisor == constants.HT_KVM and \ not hvparams.get(constants.HV_KVM_USER_SHUTDOWN, False): raise errors.OpPrereqError("Instance shutdown detection must be " "enabled for zeroing to work", errors.ECODE_INVAL) # Check that the instance is set to boot from the disk if constants.HV_BOOT_ORDER in hvparams and \ hvparams[constants.HV_BOOT_ORDER] != constants.HT_BO_DISK: raise errors.OpPrereqError("Booting from disk must be set for zeroing " "to work", errors.ECODE_INVAL) # Check that the zeroing image is set if not self.cfg.GetZeroingImage(): raise errors.OpPrereqError("A zeroing image must be set for zeroing to" " work", errors.ECODE_INVAL) if self.op.zeroing_timeout_fixed is None: self.op.zeroing_timeout_fixed = constants.HELPER_VM_STARTUP if self.op.zeroing_timeout_per_mib is None: self.op.zeroing_timeout_per_mib = constants.ZEROING_TIMEOUT_PER_MIB else: if (self.op.zeroing_timeout_fixed is not None or self.op.zeroing_timeout_per_mib is not None): raise errors.OpPrereqError("Zeroing timeout options can only be used" " only with the --zero-free-space option", errors.ECODE_INVAL) if self.op.long_sleep and not self.op.shutdown: raise errors.OpPrereqError("The long sleep option only makes sense when" " the instance can be shut down.", errors.ECODE_INVAL) self.secondary_nodes = \ self.cfg.GetInstanceSecondaryNodes(self.instance.uuid) self.inst_disks = self.cfg.GetInstanceDisks(self.instance.uuid) # Check if the compression tool is whitelisted CheckCompressionTool(self, self.op.compress)
TypeError
dataset/ETHPy150Open ganeti/ganeti/lib/cmdlib/backup.py/LUBackupExport.CheckPrereq
8,044
def __contains__(self, key): # Don't use hasattr() because hasattr() catches any exception, not only # AttributeError. We want to passthrough SQLAlchemy exceptions # (ex: sqlalchemy.orm.exc.DetachedInstanceError). try: getattr(self, key) except __HOLE__: return False else: return True
AttributeError
dataset/ETHPy150Open openstack/oslo.db/oslo_db/sqlalchemy/models.py/ModelBase.__contains__
8,045
def __init__(self, value, unit=None, space=" "): self._space = space if unit is not None: self.value = float(value) self.unit = _findUnit(unit) else: if isinstance(value, basestring): match = PhysicalQuantity._NUMBER_RE.match(value) if match is None: raise TypeError('Not a number or number with unit') self.value = float(match.group(1)) self._space = match.group(2) self.unit = _findUnit(match.group(3)) elif isinstance(value, PhysicalQuantity): self.value = value.value self.unit = value.unit self._space = value._space elif isinstance(value, tuple): self.value = float(value[0]) self.unit = _findUnit(value[1]) try: self._space = value[2] except __HOLE__: pass else: raise ValueError("PhysicalQuantity can't use {!r}".format(value))
IndexError
dataset/ETHPy150Open kdart/pycopia/core/pycopia/physics/physical_quantities.py/PhysicalQuantity.__init__
8,046
def _findUnit(unit): if isinstance(unit, basestring): unit = eval(unit, _unit_table) for cruft in ['__builtins__', '__args__']: try: del _unit_table[cruft] except __HOLE__: pass if not isPhysicalUnit(unit): raise TypeError(str(unit) + ' is not a unit') return unit
KeyError
dataset/ETHPy150Open kdart/pycopia/core/pycopia/physics/physical_quantities.py/_findUnit
8,047
def neighbors(self, n): """Return an iterator over all neighbors of node n in the dense graph. """ try: return iter(set(self.adj) - set(self.adj[n]) - set([n])) except __HOLE__: raise NetworkXError("The node %s is not in the graph."%(n,))
KeyError
dataset/ETHPy150Open networkx/networkx/networkx/algorithms/approximation/kcomponents.py/_AntiGraph.neighbors
8,048
def execute(self): if self.goal not in PrepCommand.goals(): raise AssertionError('Got goal "{}". Expected goal to be one of {}'.format( self.goal, PrepCommand.goals())) targets = self.context.targets(postorder=True, predicate=self.runnable_prep_cmd) Cmdline = namedtuple('Cmdline', ['cmdline', 'environ']) def make_cmdline(target): executable = target.payload.get_field_value('prep_command_executable') args = target.payload.get_field_value('prep_command_args', []) prep_environ = target.payload.get_field_value('prep_environ') cmdline = [executable] cmdline.extend(args) return Cmdline(cmdline=tuple(cmdline), environ=prep_environ) def has_prep(target): return target.payload.get_field_value('prep_command_executable') cmdlines = [make_cmdline(target) for target in targets if has_prep(target)] if not cmdlines: return with self.context.new_workunit(name='prep_command', labels=[WorkUnitLabel.PREP]) as workunit: completed_cmdlines = set() for item in cmdlines: cmdline = item.cmdline environ = item.environ if not cmdline in completed_cmdlines: completed_cmdlines.add(cmdline) stderr = workunit.output('stderr') if workunit else None try: process = subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=stderr) except __HOLE__ as e: workunit.set_outcome(WorkUnit.FAILURE) raise TaskError('RunPrepCommand failed to execute {cmdline}: {error}'.format( cmdline=cmdline, error=e)) stdout, _ = process.communicate() if environ: if not process.returncode: environment_vars = stdout.split('\0') for kvpair in environment_vars: var, value = kvpair.split('=', 1) os.environ[var] = value else: if workunit: workunit.output('stdout').write(stdout) workunit.set_outcome(WorkUnit.FAILURE if process.returncode else WorkUnit.SUCCESS) if process.returncode: raise TaskError('RunPrepCommand failed to run {cmdline}'.format(cmdline=cmdline))
OSError
dataset/ETHPy150Open pantsbuild/pants/src/python/pants/core_tasks/run_prep_command.py/RunPrepCommandBase.execute
8,049
@convert.register(pd.DataFrame, (Temp(CSV), CSV), cost=20.0) def csv_to_dataframe(c, dshape=None, chunksize=None, nrows=None, **kwargs): try: return _csv_to_dataframe(c, dshape=dshape, chunksize=chunksize, nrows=nrows, **kwargs) except __HOLE__: if nrows: return _csv_to_dataframe(c, dshape=dshape, chunksize=chunksize, **kwargs) else: raise
StopIteration
dataset/ETHPy150Open blaze/odo/odo/backends/csv.py/csv_to_dataframe
8,050
def _csv_to_dataframe(c, dshape=None, chunksize=None, **kwargs): header = {False: None, True: 0}.get( kwargs.pop('has_header', c.has_header), 'infer') sep = kwargs.pop( 'sep', kwargs.pop('delimiter', c.dialect.get('delimiter', ','))) encoding = kwargs.pop('encoding', c.encoding) if dshape: dtypes, parse_dates = dshape_to_pandas(dshape) if isrecord(dshape.measure): names = kwargs.get('names', dshape.measure.names) else: names = kwargs.get('names') else: dtypes = parse_dates = names = None usecols = kwargs.pop('usecols', None) if parse_dates and usecols: parse_dates = [col for col in parse_dates if col in usecols] compression = kwargs.pop('compression', {'gz': 'gzip', 'bz2': 'bz2'}.get(ext(c.path))) # See read_csv docs for header for reasoning if names: try: found_names = pd.read_csv(c.path, encoding=encoding, compression=compression, nrows=1) except __HOLE__: found_names = pd.read_csv(c.path, encoding=encoding, compression=compression) if names and header == 'infer': if [n.strip() for n in found_names] == [n.strip() for n in names]: header = 0 elif (all(re.match('^\s*\D\w*\s*$', n) for n in found_names) and not all(dt == datashape.string for dt in dshape.measure.types)): header = 0 else: header = None kwargs = keyfilter(keywords(pd.read_csv).__contains__, kwargs) return pd.read_csv(c.path, header=header, sep=sep, encoding=encoding, dtype=dtypes, parse_dates=parse_dates, names=names, compression=compression, chunksize=chunksize, usecols=usecols, **kwargs)
StopIteration
dataset/ETHPy150Open blaze/odo/odo/backends/csv.py/_csv_to_dataframe
8,051
def _scale_inplace(a, x_gpu): """ Scale an array by a specified value in-place. """ # Cache the kernel to avoid invoking the compiler if the # specified scale factor and array type have already been encountered: try: func = _scale_inplace.cache[(a, x_gpu.dtype)] except __HOLE__: ctype = tools.dtype_to_ctype(x_gpu.dtype) func = el.ElementwiseKernel( "{ctype} a, {ctype} *x".format(ctype=ctype), "x[i] /= a") _scale_inplace.cache[(a, x_gpu.dtype)] = func func(x_gpu.dtype.type(a), x_gpu)
KeyError
dataset/ETHPy150Open lebedov/scikit-cuda/skcuda/fft.py/_scale_inplace
8,052
def simple_filter( data=None, attr=None, value=None, property_field=None, ): """Filter a list of dicts :param list data: The list to be filtered. The list is modified in-place and will be changed if any filtering occurs. :param string attr: The name of the attribute to filter. If attr does not exist no match will succeed and no rows will be returned. If attr is None no filtering will be performed and all rows will be returned. :param string value: The value to filter. None is considered to be a 'no filter' value. '' matches against a Python empty string. :param string property_field: The name of the data field containing a property dict to filter. If property_field is None, attr is a field name. If property_field is not None, attr is a property key name inside the named property field. :returns: Returns the filtered list :rtype list: This simple filter (one attribute, one exact-match value) searches a list of dicts to select items. It first searches the item dict for a matching ``attr`` then does an exact-match on the ``value``. If ``property_field`` is given, it will look inside that field (if it exists and is a dict) for a matching ``value``. """ # Take the do-nothing case shortcut if not data or not attr or value is None: return data # NOTE:(dtroyer): This filter modifies the provided list in-place using # list.remove() so we need to start at the end so the loop pointer does # not skip any items after a deletion. for d in reversed(data): if attr in d: # Searching data fields search_value = d[attr] elif (property_field and property_field in d and isinstance(d[property_field], dict)): # Searching a properties field - do this separately because # we don't want to fail over to checking the fields if a # property name is given. if attr in d[property_field]: search_value = d[property_field][attr] else: search_value = None else: search_value = None # could do regex here someday... if not search_value or search_value != value: # remove from list try: data.remove(d) except __HOLE__: # it's already gone! pass return data
ValueError
dataset/ETHPy150Open dtroyer/python-openstackclient/openstackclient/api/utils.py/simple_filter
8,053
def __getattr__(self, attr): if attr is None: return self.__data if self.__data is None: raise AttributeError('unreadable attribute') try: fget = getattr(self.__data, attr) except __HOLE__: raise TypeError('%s object does not have a %s attribute' % (type(self.__data).__name__, self.__data)) return fget
AttributeError
dataset/ETHPy150Open deepanshumehndiratta/reactive-py/examples/reactive.py/_.__getattr__
8,054
@property def param_names(self): """ (list of str) List of human readable parameter names (for parameters actually included in the model). """ if hasattr(self, '_param_names'): return self._param_names else: try: names = ['param.%d' % i for i in range(len(self.start_params))] except __HOLE__: names = [] return names
NotImplementedError
dataset/ETHPy150Open statsmodels/statsmodels/statsmodels/tsa/statespace/mlemodel.py/MLEModel.param_names
8,055
def get_prediction(self, start=None, end=None, dynamic=False, **kwargs): """ In-sample prediction and out-of-sample forecasting Parameters ---------- start : int, str, or datetime, optional Zero-indexed observation number at which to start forecasting, i.e., the first forecast is start. Can also be a date string to parse or a datetime type. Default is the the zeroth observation. end : int, str, or datetime, optional Zero-indexed observation number at which to end forecasting, i.e., the last forecast is end. Can also be a date string to parse or a datetime type. However, if the dates index does not have a fixed frequency, end must be an integer index if you want out of sample prediction. Default is the last observation in the sample. dynamic : boolean, int, str, or datetime, optional Integer offset relative to `start` at which to begin dynamic prediction. Can also be an absolute date string to parse or a datetime type (these are not interpreted as offsets). Prior to this observation, true endogenous values will be used for prediction; starting with this observation and continuing through the end of prediction, forecasted endogenous values will be used instead. **kwargs Additional arguments may required for forecasting beyond the end of the sample. See `FilterResults.predict` for more details. Returns ------- forecast : array Array of out of in-sample predictions and / or out-of-sample forecasts. An (npredict x k_endog) array. """ if start is None: start = 0 # Handle start and end (e.g. dates) start = self.model._get_predict_start(start) end, out_of_sample = self.model._get_predict_end(end) # Handle string dynamic dates = self.data.dates if isinstance(dynamic, str): if dates is None: raise ValueError("Got a string for dynamic and dates is None") dtdynamic = self.model._str_to_date(dynamic) try: dynamic_start = self.model._get_dates_loc(dates, dtdynamic) dynamic = dynamic_start - start except __HOLE__: raise ValueError("Dynamic must be in dates. Got %s | %s" % (str(dynamic), str(dtdynamic))) # Perform the prediction # This is a (k_endog x npredictions) array; don't want to squeeze in # case of npredictions = 1 prediction_results = self.filter_results.predict( start, end+out_of_sample+1, dynamic, **kwargs ) # Return a new mlemodel.PredictionResults object if self.data.dates is None: row_labels = self.data.row_labels else: row_labels = self.data.predict_dates return PredictionResultsWrapper( PredictionResults(self, prediction_results, row_labels=row_labels))
KeyError
dataset/ETHPy150Open statsmodels/statsmodels/statsmodels/tsa/statespace/mlemodel.py/MLEResults.get_prediction
8,056
@staticmethod def _extract_id(obj): """ Return obj.id, or obj if the object doesn't have an ID """ try: return obj.id except __HOLE__: return obj
AttributeError
dataset/ETHPy150Open photo/openphoto-python/trovebox/api/api_base.py/ApiBase._extract_id
8,057
@any_model.register_default def any_model_default(model_cls, **kwargs): result = model_cls() attempts = 10 while True: try: _fill_model_fields(result, **kwargs) result.full_clean() result.save() return result except (IntegrityError, __HOLE__): attempts -= 1 if not attempts: raise
ValidationError
dataset/ETHPy150Open kmmbvnr/django-any/django_any/models.py/any_model_default
8,058
def load(self): try: with open(self._filename, 'r') as f: settings = json.load(f) except __HOLE__: settings = {} settings.setdefault(self._section, {}) return settings
IOError
dataset/ETHPy150Open python273/vk_api/jconfig/jconfig.py/Config.load
8,059
def _save_level(handler, group, level, name=None, filters=None, idtable=None): _id = id(level) try: oldpath = idtable[_id] except __HOLE__: if _is_linkable(level): # store path to object: if group._v_pathname.endswith('/'): idtable[_id] = '{}{}'.format(group._v_pathname, name) else: idtable[_id] = '{}/{}'.format(group._v_pathname, name) else: # object already saved, so create soft link to it: handler.create_soft_link(group, name, target=oldpath) return if isinstance(level, Compression): custom_filters = _get_compression_filters(level.compression) return _save_level(handler, group, level.obj, name=name, filters=custom_filters, idtable=idtable) elif isinstance(level, ForcePickle): _save_pickled(handler, group, level, name=name) elif isinstance(level, dict) and _dict_native_ok(level): # First create a new group new_group = handler.create_group(group, name, "dict:{}".format(len(level))) for k, v in level.items(): if isinstance(k, six.string_types): _save_level(handler, new_group, v, name=k, filters=filters, idtable=idtable) elif (_sns and isinstance(level, SimpleNamespace) and _dict_native_ok(level.__dict__)): # Create a new group in same manner as for dict new_group = handler.create_group( group, name, "SimpleNamespace:{}".format(len(level.__dict__))) for k, v in level.__dict__.items(): if isinstance(k, six.string_types): _save_level(handler, new_group, v, name=k, filters=filters, idtable=idtable) elif isinstance(level, list) and len(level) < 256: # Lists can contain other dictionaries and numpy arrays, so we don't # want to serialize them. Instead, we will store each entry as i0, i1, # etc. new_group = handler.create_group(group, name, "list:{}".format(len(level))) for i, entry in enumerate(level): level_name = 'i{}'.format(i) _save_level(handler, new_group, entry, name=level_name, filters=filters, idtable=idtable) elif isinstance(level, tuple) and len(level) < 256: # Lists can contain other dictionaries and numpy arrays, so we don't # want to serialize them. Instead, we will store each entry as i0, i1, # etc. new_group = handler.create_group(group, name, "tuple:{}".format(len(level))) for i, entry in enumerate(level): level_name = 'i{}'.format(i) _save_level(handler, new_group, entry, name=level_name, filters=filters, idtable=idtable) elif isinstance(level, np.ndarray): _save_ndarray(handler, group, name, level, filters=filters) elif _pandas and isinstance(level, (pd.DataFrame, pd.Series, pd.Panel)): store = _HDFStoreWithHandle(handler) store.put(group._v_pathname + '/' + name, level) elif isinstance(level, (sparse.dok_matrix, sparse.lil_matrix)): raise NotImplementedError( 'deepdish.io.save does not support DOK or LIL matrices; ' 'please convert before saving to one of the following supported ' 'types: BSR, COO, CSR, CSC, DIA') elif isinstance(level, (sparse.csr_matrix, sparse.csc_matrix, sparse.bsr_matrix)): new_group = handler.create_group(group, name, "sparse:") _save_ndarray(handler, new_group, 'data', level.data, filters=filters) _save_ndarray(handler, new_group, 'indices', level.indices, filters=filters) _save_ndarray(handler, new_group, 'indptr', level.indptr, filters=filters) _save_ndarray(handler, new_group, 'shape', np.asarray(level.shape)) new_group._v_attrs.format = level.format new_group._v_attrs.maxprint = level.maxprint elif isinstance(level, sparse.dia_matrix): new_group = handler.create_group(group, name, "sparse:") _save_ndarray(handler, new_group, 'data', level.data, filters=filters) _save_ndarray(handler, new_group, 'offsets', level.offsets, filters=filters) _save_ndarray(handler, new_group, 'shape', np.asarray(level.shape)) new_group._v_attrs.format = level.format new_group._v_attrs.maxprint = level.maxprint elif isinstance(level, sparse.coo_matrix): new_group = handler.create_group(group, name, "sparse:") _save_ndarray(handler, new_group, 'data', level.data, filters=filters) _save_ndarray(handler, new_group, 'col', level.col, filters=filters) _save_ndarray(handler, new_group, 'row', level.row, filters=filters) _save_ndarray(handler, new_group, 'shape', np.asarray(level.shape)) new_group._v_attrs.format = level.format new_group._v_attrs.maxprint = level.maxprint elif isinstance(level, ATTR_TYPES): setattr(group._v_attrs, name, level) elif level is None: # Store a None as an empty group new_group = handler.create_group(group, name, "nonetype:") else: _save_pickled(handler, group, level, name=name)
KeyError
dataset/ETHPy150Open uchicago-cs/deepdish/deepdish/io/hdf5io.py/_save_level
8,060
def _load_level(handler, level, pathtable): """ Loads level and builds appropriate type, handling softlinks if necessary """ if isinstance(level, tables.link.SoftLink): # this is a link, so see if target is already loaded, return it pathname = level.target node = level() else: # not a link, but it might be a target that's already been # loaded ... if so, return it pathname = level._v_pathname node = level try: return pathtable[pathname] except __HOLE__: pathtable[pathname] = _load_nonlink_level(handler, node, pathtable, pathname) return pathtable[pathname]
KeyError
dataset/ETHPy150Open uchicago-cs/deepdish/deepdish/io/hdf5io.py/_load_level
8,061
@signals.task_prerun.connect def bind_event_context(sender=None, **kwargs): try: event_context = kwargs['kwargs'].pop('event_context') except __HOLE__: return set_event_context(event_context)
KeyError
dataset/ETHPy150Open opennode/nodeconductor/nodeconductor/server/celery.py/bind_event_context
8,062
def was_modified_since(self, file_instance, since): """Return True if ``file_instance`` was modified after ``since``. Uses file wrapper's ``was_modified_since`` if available, with value of ``since`` as positional argument. Else, fallbacks to default implementation, which uses :py:func:`django.views.static.was_modified_since`. Django's ``was_modified_since`` function needs a datetime and a size. It is passed ``modified_time`` and ``size`` attributes from file wrapper. If file wrapper does not support these attributes (``AttributeError`` or ``NotImplementedError`` is raised), then the file is considered as modified and ``True`` is returned. """ try: return file_instance.was_modified_since(since) except (__HOLE__, NotImplementedError): try: modification_time = calendar.timegm( file_instance.modified_time.utctimetuple()) size = file_instance.size except (AttributeError, NotImplementedError): return True else: return was_modified_since(since, modification_time, size)
AttributeError
dataset/ETHPy150Open benoitbryon/django-downloadview/django_downloadview/views/base.py/DownloadMixin.was_modified_since
8,063
def _url_for_fetch(self, mapping): try: return mapping['pre_processed_url'] except __HOLE__: return mapping['raw_url']
KeyError
dataset/ETHPy150Open openelections/openelections-core/openelex/us/or/datasource.py/Datasource._url_for_fetch
8,064
def token_split(text, quote_chars=QUOTE_CHARS): for char in [''] + quote_chars: try: return shlex.split(text + char) except __HOLE__: pass raise ValueError, "Quotation mismatch"
ValueError
dataset/ETHPy150Open tehmaze/nagios-cli/nagios_cli/util.py/token_split
8,065
def run(): logger = logs.prepare_submodule_logger('assassin', settings.ASSASSIN_LOG_PATH) logger.info('Running Assassind...') try: while True: update_nodes_status(settings.KEEPALIVE['timeout'], logger) time.sleep(settings.KEEPALIVE['interval']) except (__HOLE__, SystemExit): logger.info('Stopping Assassind...') sys.exit(1)
KeyboardInterrupt
dataset/ETHPy150Open openstack/fuel-web/nailgun/nailgun/assassin/assassind.py/run
8,066
def __init__(self, context): uri = context.config.storage name = uri.split('://', 1)[0] try: factory = self.backends[name] except __HOLE__: # pragma: no cover raise LookupError('No such backend %' % name) self.backend = factory(uri) self.context = context self.context.db = self
KeyError
dataset/ETHPy150Open gawel/irc3/irc3/plugins/storage.py/Storage.__init__
8,067
def __getitem__(self, key): """Get storage value for key""" key = getattr(key, '__module__', key) try: return self.backend.get(key) except __HOLE__: raise KeyError(key) except Exception as e: # pragma: no cover self.context.log.exception(e) raise
KeyError
dataset/ETHPy150Open gawel/irc3/irc3/plugins/storage.py/Storage.__getitem__
8,068
def _string_like(obj): try: obj + '' except (__HOLE__, ValueError): return 0 return 1
TypeError
dataset/ETHPy150Open enthought/mayavi/mayavi/tools/data_wizards/loadtxt.py/_string_like
8,069
def validate_range(number, min_value=None, max_value=None, allow_none=False): if number is None: if allow_none: return True else: logger.error('invalid value %s' % number) return False try: float(number) except __HOLE__: logger.error('invalid value %s' % number) return False if min_value is not None and number < min_value: logger.error('invalid value %s' % number) return False if max_value is not None and number > max_value: logger.error('invalid value %s' % number) return False return True
ValueError
dataset/ETHPy150Open NVIDIA/DIGITS/tools/parse_folder.py/validate_range
8,070
def template_hook_collect(module, hook_name, *args, **kwargs): """ Helper to include in your own templatetag, for static TemplateHooks Example:: import myhooks from hooks.templatetags import template_hook_collect @register.simple_tag(takes_context=True) def hook(context, name, *args, **kwargs): return template_hook_collect(myhooks, name, context, *args, **kwargs) :param module module: Module containing the template hook definitions :param str hook_name: The hook name to be dispatched :param \*args: Positional arguments, will be passed to hook callbacks :param \*\*kwargs: Keyword arguments, will be passed to hook callbacks :return: A concatenation of all callbacks\ responses marked as safe (conditionally) :rtype: str """ try: templatehook = getattr(module, hook_name) except __HOLE__: return "" return format_html_join( sep="\n", format_string="{}", args_generator=( (response, ) for response in templatehook(*args, **kwargs) ) )
AttributeError
dataset/ETHPy150Open nitely/django-hooks/hooks/templatetags/hooks_tags.py/template_hook_collect
8,071
def getUrlFd(url, headers=None, data=None, timeout=None): """getUrlFd(url, headers=None, data=None, timeout=None) Opens the given url and returns a file object. Headers and data are a dict and string, respectively, as per urllib.request.Request's arguments.""" if headers is None: headers = defaultHeaders if minisix.PY3 and isinstance(data, str): data = data.encode() try: if not isinstance(url, Request): (scheme, loc, path, query, frag) = urlsplit(url) (user, host) = splituser(loc) url = urlunsplit((scheme, host, path, query, '')) request = Request(url, headers=headers, data=data) if user: request.add_header('Authorization', 'Basic %s' % base64.b64encode(user)) else: request = url request.add_data(data) httpProxy = force(proxy) if httpProxy: request.set_proxy(httpProxy, 'http') fd = urlopen(request, timeout=timeout) return fd except socket.timeout as e: raise Error(TIMED_OUT) except sockerrors as e: raise Error(strError(e)) except InvalidURL as e: raise Error('Invalid URL: %s' % e) except HTTPError as e: raise Error(strError(e)) except URLError as e: raise Error(strError(e.reason)) # Raised when urllib doesn't recognize the url type except __HOLE__ as e: raise Error(strError(e))
ValueError
dataset/ETHPy150Open ProgVal/Limnoria/src/utils/web.py/getUrlFd
8,072
def write_color(self, text, attr=None): '''write text at current cursor position and interpret color escapes. return the number of characters written. ''' log('write_color("%s", %s)' % (text, attr)) chunks = self.terminal_escape.split(text) log('chunks=%s' % repr(chunks)) bg = self.savebg n = 0 # count the characters we actually write, omitting the escapes if attr is None:#use attribute from initial console attr = self.attr try: fg = self.trtable[(0x000f&attr)] bg = self.trtable[(0x00f0&attr)>>4] except __HOLE__: fg = attr for chunk in chunks: m = self.escape_parts.match(chunk) if m: log(m.group(1)) attr = ansicolor.get(m.group(1), self.attr) n += len(chunk) System.Console.ForegroundColor = fg System.Console.BackgroundColor = bg System.Console.Write(chunk) return n
TypeError
dataset/ETHPy150Open Ali-Razmjoo/OWASP-ZSC/module/readline_windows/pyreadline/console/ironpython_console.py/Console.write_color
8,073
def install_readline(hook): def hook_wrap(): try: res = hook() except __HOLE__ as x: #this exception does not seem to be caught res = "" except EOFError: return None if res[-1:] == "\n": return res[:-1] else: return res class IronPythonWrapper(IronPythonConsole.IConsole): def ReadLine(self, autoIndentSize): return hook_wrap() def Write(self, text, style): System.Console.Write(text) def WriteLine(self, text, style): System.Console.WriteLine(text) IronPythonConsole.PythonCommandLine.MyConsole = IronPythonWrapper()
KeyboardInterrupt
dataset/ETHPy150Open Ali-Razmjoo/OWASP-ZSC/module/readline_windows/pyreadline/console/ironpython_console.py/install_readline
8,074
@property def key(self): accessors = [] reversing = [] for order_by in self: accessors.append(Accessor(order_by.bare)) reversing.append(order_by.is_descending) @total_ordering class Comparator(object): def __init__(self, obj): self.obj = obj def __eq__(self, other): for accessor in accessors: a = accessor.resolve(self.obj, quiet=True) b = accessor.resolve(other.obj, quiet=True) if not a == b: return False return True def __lt__(self, other): for accessor, reverse in six.moves.zip(accessors, reversing): a = accessor.resolve(self.obj, quiet=True) b = accessor.resolve(other.obj, quiet=True) if a == b: continue if reverse: a, b = b, a # The rest of this should be refactored out into a util # function 'compare' that handles different types. try: return a < b except __HOLE__: # If the truth values differ, it's a good way to # determine ordering. if bool(a) is not bool(b): return bool(a) < bool(b) # Handle comparing different types, by falling back to # the string and id of the type. This at least groups # different types together. a_type = type(a) b_type = type(b) return (repr(a_type), id(a_type)) < (repr(b_type), id(b_type)) return False return Comparator
TypeError
dataset/ETHPy150Open bradleyayers/django-tables2/django_tables2/utils.py/OrderByTuple.key
8,075
def get(self, key, fallback): """ Identical to __getitem__, but supports fallback value. """ try: return self[key] except (__HOLE__, IndexError): return fallback
KeyError
dataset/ETHPy150Open bradleyayers/django-tables2/django_tables2/utils.py/OrderByTuple.get
8,076
def resolve(self, context, safe=True, quiet=False): """ Return an object described by the accessor by traversing the attributes of *context*. Example: .. code-block:: python >>> x = Accessor('__len__') >>> x.resolve('brad') 4 >>> x = Accessor('0.upper') >>> x.resolve('brad') 'B' :type context: `object` :param context: The root/first object to traverse. :type safe: `bool` :param safe: Don't call anything with ``alters_data = True`` :type quiet: bool :param quiet: Smother all exceptions and instead return `None` :returns: target object :raises: anything ``getattr(a, "b")`` raises, e.g. `TypeError`, `AttributeError`, `KeyError`, `ValueError` (unless *quiet* == `True`) `~.Accessor.resolve` attempts lookups in the following order: - dictionary (e.g. ``obj[related]``) - attribute (e.g. ``obj.related``) - list-index lookup (e.g. ``obj[int(related)]``) Callable objects are called, and their result is used, before proceeding with the resolving. """ try: current = context for bit in self.bits: try: # dictionary lookup current = current[bit] except (TypeError, __HOLE__, KeyError): try: # attribute lookup current = getattr(current, bit) except (TypeError, AttributeError): try: # list-index lookup current = current[int(bit)] except (IndexError, # list index out of range ValueError, # invalid literal for int() KeyError, # dict without `int(bit)` key TypeError, # unsubscriptable object ): raise ValueError('Failed lookup for key [%s] in %r' ', when resolving the accessor %s' % (bit, current, self) ) if callable(current): if safe and getattr(current, 'alters_data', False): raise ValueError('refusing to call %s() because `.alters_data = True`' % repr(current)) if not getattr(current, 'do_not_call_in_templates', False): current = current() # important that we break in None case, or a relationship # spanning across a null-key will raise an exception in the # next iteration, instead of defaulting. if current is None: break return current except: if not quiet: raise
AttributeError
dataset/ETHPy150Open bradleyayers/django-tables2/django_tables2/utils.py/Accessor.resolve
8,077
def watch(site_config, base_path): global _site_config, _base_path _site_config = site_config _base_path = base_path observe_path = os.path.join(_base_path, _site_config['source']) event_handler = YAPatternMatchingEventHandler() observer = Observer() observer.schedule(event_handler, observe_path, recursive=True) observer.start() try: while True: time.sleep(1) except (__HOLE__, SystemExit): logging.info("Shutting down watcher") observer.stop() observer.join()
KeyboardInterrupt
dataset/ETHPy150Open tankywoo/simiki/simiki/watcher.py/watch
8,078
def test_musicbrainz(self): # with HTTMock(*mock_functions): ids = [ '482c09c0-fe65-424f-b9e7-9ec08a999a2f', '6ac67c73-2833-4af3-b2e7-3bec5a7e3f85', 'b10bbbfc-cf9e-42e0-be17-e2c3e1d2600d', 'f2492c31-54a8-4347-a1fc-f81f72873bbf', '5f3c98a5-8cda-4a1e-a8f8-c41aab636b97', '4c48078c-af4e-4ca3-9838-5841d91826e1', '859d4c71-8baf-4987-91ac-a138c9bba81f', '6dd52e57-52a7-4618-972c-4f0de3dbcadf', '157aed6f-e861-4649-b838-41d11c2e5f0a', '0ef5eb85-fddb-443b-8a14-8b5da90be3e9', '3ff72a59-f39d-411d-9f93-2d4a86413013', 'adec1fc3-83c1-48f7-9e49-8347ac6d40b0', 'd98c8149-0c01-4151-93e1-48fdc3d5027f', 'c2f0fb92-4e5d-4136-97d9-043e10ee1154', 'cee3f961-4197-483b-a3ad-73242a97eb4a', '541bacd0-6aeb-4292-8d3a-882e85519953', '2f24f70e-c1ce-4fd4-a927-48fad3fe74e0', '8475297d-fb78-4630-8d74-9b87b6bb7cc8', '61dd30be-8e7b-4c85-9aa4-be66702c4644', '1cf5f079-706d-4b1f-9de9-0bf8e298cc97', '6c4faf49-a133-4465-a97d-6c68c52ad88b', '582748ae-a993-4b14-a2be-199fe8f418e6', '65cc77e1-45cf-4c2a-958c-c7cca472970c', '98e4bf9e-9e33-4f07-9962-f7c1c2d773ba', '93eb7110-0bc9-4d3f-816b-4b52ef982ec8', '8ca01f46-53ac-4af2-8516-55a909c0905e', '2819834e-4e08-47b0-a2c4-b7672318e8f0', 'd5cc67b8-1cc4-453b-96e8-44487acdebea', '9a6880e7-5795-4ed3-8c58-7fef968aaa61', '31e9c35b-2675-4632-8596-f9bd9286f6c8', '2dea8a55-623b-42bb-bda3-9fb784018b40', '2c1bc1cb-4ae8-427b-ba28-4a695e47388f', '0c502791-4ee9-4c5f-9696-0602b721ff3b', '5c9fefe7-7bbb-47f8-b54e-9b5361beed5c', '6821bf3f-5d5b-4b0f-8fa4-79d2ab2d9219', 'c213f661-70a8-42aa-b858-62f5bd2d72e9', 'e9fcd661-cf2f-4792-aa50-364e1a576ac3', '3a6d6481-142d-423f-91d4-55bbfff318ed', '0d8303d1-6653-43f1-a0ef-2fcd3835529f', '2af759f4-4c48-49eb-a512-ae463c40b99a', '1d45138d-c675-4016-87a7-7ad5cce5e1bc', '4e442c83-b547-4d6e-9270-cdd35e3c3195', '5b8a28ee-dc6b-48db-ae98-f4ef1f15ae6d', '18dc6bd7-9caa-4c2d-a2fc-e9546ebda6a4', '0e23b5e8-0f99-45f4-bb2d-a266d65f13f3', '381e8434-109a-439c-8acc-5d328359f2e0', '26fe7532-dc1e-45d1-bfcb-a7f83d4df98e', ] for id in ids: print '====================================================' try: artist = FreebaseMusicbrainzArtist.objects.get(pk=id) print artist.name print '---------------------------------------------------' if artist.origin_text: print artist.origin_text if artist.place_of_birth: print artist.place_of_birth except __HOLE__: print 'could not find musicbrainz id'
HTTPError
dataset/ETHPy150Open mbylstra/django-wham/wham/apis/freebase/tests.py/TestCase.test_musicbrainz
8,079
def try_int(s): try: return int(s) except __HOLE__: return s
ValueError
dataset/ETHPy150Open scoder/lupa/setup.py/try_int
8,080
def decode_path_output(s): if sys.version_info[0] < 3: return s # no need to decode, and safer not to do it # we don't really know in which encoding pkgconfig # outputs its results, so we try to guess for encoding in (sys.getfilesystemencoding(), sys.getdefaultencoding(), 'utf8'): try: return s.decode(encoding) except __HOLE__: pass return s.decode('iso8859-1') # try to find LuaJIT installation using pkgconfig
UnicodeDecodeError
dataset/ETHPy150Open scoder/lupa/setup.py/decode_path_output
8,081
def check_lua_installed(package='luajit', min_version='2'): try: cmd_output('pkg-config %s --exists' % package) except RuntimeError: # pkg-config gives no stdout when it is given --exists and it cannot # find the package, so we'll give it some better output error = sys.exc_info()[1] if not error.args[0]: raise RuntimeError("pkg-config cannot find an installed %s" % package) raise lua_version = cmd_output('pkg-config %s --modversion' % package).decode('iso8859-1') try: if tuple(map(try_int, lua_version.split('.'))) < tuple(map(try_int, min_version.split('.'))): raise PkgConfigError("Expected version %s+ of %s, but found %s" % (min_version, package, lua_version)) except (ValueError, __HOLE__): print("failed to parse version '%s' of installed %s package, minimum is %s" % ( lua_version, package, min_version)) else: print("pkg-config found %s version %s" % (package, lua_version))
TypeError
dataset/ETHPy150Open scoder/lupa/setup.py/check_lua_installed
8,082
def find_lua_build(no_luajit=False): # try to find local LuaJIT2 build os_path = os.path for filename in os.listdir(basedir): if not filename.lower().startswith('luajit'): continue filepath = os_path.join(basedir, filename, 'src') if not os_path.isdir(filepath): continue libfile = os_path.join(filepath, 'libluajit.a') if os_path.isfile(libfile): print("found LuaJIT build in %s" % filepath) print("building statically") return dict(extra_objects=[libfile], include_dirs=[filepath]) # also check for lua51.lib, the Windows equivalent of libluajit.a for libfile in iglob(os_path.join(filepath, 'lua5?.lib')): if os_path.isfile(libfile): print("found LuaJIT build in %s (%s)" % ( filepath, os.path.basename(libfile))) print("building statically") # And return the dll file name too, as we need to # include it in the install directory return dict(extra_objects=[libfile], include_dirs=[filepath], libfile=os.path.basename(libfile)) print("No local build of LuaJIT2 found in lupa directory") # try to find installed LuaJIT2 or Lua if no_luajit: packages = [] else: packages = [('luajit', '2')] packages += [ (name, lua_version) for lua_version in ('5.2', '5.1') for name in ('lua%s' % lua_version, 'lua-%s' % lua_version, 'lua') ] for package_name, min_version in packages: print("Checking for installed %s library using pkg-config" % package_name) try: check_lua_installed(package_name, min_version) return dict(extra_objects=lua_libs(package_name), include_dirs=lua_include(package_name)) except __HOLE__: print("Did not find %s using pkg-config: %s" % ( package_name, sys.exc_info()[1])) error = ("None of LuaJIT2, Lua 5.1 or Lua 5.2 were found. Please install " "Lua and its development packages, " "or put a local build into the lupa main directory.") print(error) return {}
RuntimeError
dataset/ETHPy150Open scoder/lupa/setup.py/find_lua_build
8,083
def __init__(self, *args, **kwargs): super(AbstractEntryBaseAdminForm, self).__init__(*args, **kwargs) # The admin's .save() method fills in a default: self.fields['publication_date'].required = False try: author_field = self.fields['author'] except __HOLE__: pass else: author_field.required = False self.initial.setdefault('author', author_field.user)
KeyError
dataset/ETHPy150Open edoburu/django-fluent-blogs/fluent_blogs/admin/forms.py/AbstractEntryBaseAdminForm.__init__
8,084
def clean(self): cleaned_data = super(AbstractEntryBaseAdminForm, self).clean() if 'slug' not in cleaned_data or 'publication_date' not in cleaned_data: return cleaned_data try: self.validate_unique_slug(cleaned_data) except __HOLE__ as e: self._errors['slug'] = self.error_class(e.messages) return cleaned_data
ValidationError
dataset/ETHPy150Open edoburu/django-fluent-blogs/fluent_blogs/admin/forms.py/AbstractEntryBaseAdminForm.clean
8,085
def _get_volume_instance(self, volume): try: pl = eval(volume.provider_location) except (SyntaxError, ValueError, TypeError): LOG.warning("Invalid provider location for volume '%s'", volume.id) return None try: return pywbem.CIMInstanceName( classname=pl['classname'], namespace=EMC_ROOT, keybindings=pl['keybindings']) except __HOLE__: LOG.warning("Unable to get volume instance from EMC ECOM") return None
NameError
dataset/ETHPy150Open MirantisWorkloadMobility/CloudFerry/cloudferry/lib/os/storage/plugins/iscsi/emc_vmax.py/EMCConnector._get_volume_instance
8,086
def download(self): """ Get the stream from RTMP """ args = [] if self.options.live: args.append("-v") if self.options.resume: args.append("-e") file_d = output(self.options, "flv", False) if file_d is None: return args += ["-o", self.options.output] if self.options.silent or self.options.output == "-": args.append("-q") if self.options.other: if is_py2: args += shlex.split(self.options.other.encode("utf-8")) else: args += shlex.split(self.options.other) if self.options.verbose: args.append("-V") command = ["rtmpdump", "-r", self.url] + args log.debug("Running: %s", " ".join(command)) try: subprocess.call(command) except __HOLE__ as e: log.error("Could not execute rtmpdump: " + e.strerror) return self.finished = True
OSError
dataset/ETHPy150Open spaam/svtplay-dl/lib/svtplay_dl/fetcher/rtmp.py/RTMP.download
8,087
def safe_copy(source, dest, overwrite=False): def do_copy(): temp_dest = dest + uuid4().hex shutil.copyfile(source, temp_dest) os.rename(temp_dest, dest) # If the platform supports hard-linking, use that and fall back to copying. # Windows does not support hard-linking. if hasattr(os, 'link'): try: os.link(source, dest) except __HOLE__ as e: if e.errno == errno.EEXIST: # File already exists. If overwrite=True, write otherwise skip. if overwrite: do_copy() elif e.errno == errno.EXDEV: # Hard link across devices, fall back on copying do_copy() else: raise elif os.path.exists(dest): if overwrite: do_copy() else: do_copy() # See http://stackoverflow.com/questions/2572172/referencing-other-modules-in-atexit
OSError
dataset/ETHPy150Open pantsbuild/pex/pex/common.py/safe_copy
8,088
def safe_mkdir(directory, clean=False): """Safely create a directory. Ensures a directory is present. If it's not there, it is created. If it is, it's a no-op. no-op. If clean is True, ensures the directory is empty. """ if clean: safe_rmtree(directory) try: os.makedirs(directory) except __HOLE__ as e: if e.errno != errno.EEXIST: raise
OSError
dataset/ETHPy150Open pantsbuild/pex/pex/common.py/safe_mkdir
8,089
def safe_delete(filename): """Delete a file safely. If it's not present, no-op.""" try: os.unlink(filename) except __HOLE__ as e: if e.errno != errno.ENOENT: raise
OSError
dataset/ETHPy150Open pantsbuild/pex/pex/common.py/safe_delete
8,090
def __init__(self, chroot_base): """Create the chroot. :chroot_base Directory for the creation of the target chroot. """ try: safe_mkdir(chroot_base) except __HOLE__ as e: raise self.ChrootException('Unable to create chroot in %s: %s' % (chroot_base, e)) self.chroot = chroot_base self.filesets = defaultdict(set)
OSError
dataset/ETHPy150Open pantsbuild/pex/pex/common.py/Chroot.__init__
8,091
def ask_initial(self, app_label): "Should we create an initial migration for the app?" # If it was specified on the command line, definitely true if app_label in self.specified_apps: return True # Otherwise, we look to see if it has a migrations module # without any Python files in it, apart from __init__.py. # Apps from the new app template will have these; the python # file check will ensure we skip South ones. try: app_config = apps.get_app_config(app_label) except LookupError: # It's a fake app. return self.defaults.get("ask_initial", False) migrations_import_path = MigrationLoader(None, load=False).migrations_module(app_config.label) if migrations_import_path is None: # It's an application with migrations disabled. return self.defaults.get("ask_initial", False) try: migrations_module = importlib.import_module(migrations_import_path) except __HOLE__: return self.defaults.get("ask_initial", False) else: if hasattr(migrations_module, "__file__"): filenames = os.listdir(os.path.dirname(migrations_module.__file__)) elif hasattr(migrations_module, "__path__"): if len(migrations_module.__path__) > 1: return False filenames = os.listdir(list(migrations_module.__path__)[0]) return not any(x.endswith(".py") for x in filenames if x != "__init__.py")
ImportError
dataset/ETHPy150Open django/django/django/db/migrations/questioner.py/MigrationQuestioner.ask_initial
8,092
def _choice_input(self, question, choices): print(question) for i, choice in enumerate(choices): print(" %s) %s" % (i + 1, choice)) result = input("Select an option: ") while True: try: value = int(result) if 0 < value <= len(choices): return value except __HOLE__: pass result = input("Please select a valid option: ")
ValueError
dataset/ETHPy150Open django/django/django/db/migrations/questioner.py/InteractiveMigrationQuestioner._choice_input
8,093
def _ask_default(self): print("Please enter the default value now, as valid Python") print("The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now") while True: if six.PY3: # Six does not correctly abstract over the fact that # py3 input returns a unicode string, while py2 raw_input # returns a bytestring. code = input(">>> ") else: code = input(">>> ").decode(sys.stdin.encoding) if not code: print("Please enter some code, or 'exit' (with no quotes) to exit.") elif code == "exit": sys.exit(1) else: try: return eval(code, {}, {"datetime": datetime_safe, "timezone": timezone}) except (SyntaxError, __HOLE__) as e: print("Invalid input: %s" % e)
NameError
dataset/ETHPy150Open django/django/django/db/migrations/questioner.py/InteractiveMigrationQuestioner._ask_default
8,094
def _create_folder(self, title, folder_or_uri=None): """Stolen from gdata-2.0.10 to make recursive directory upload work.""" try: return gdata.docs.service.DocsService.CreateFolder(self, title, folder_or_uri) except __HOLE__: import atom if folder_or_uri: try: uri = folder_or_uri.content.src except AttributeError: uri = folder_or_uri else: uri = '/feeds/documents/private/full' folder_entry = gdata.docs.DocumentListEntry() folder_entry.title = atom.Title(text=title) folder_entry.category.append(_make_kind_category( googlecl.docs.FOLDER_LABEL)) folder_entry = self.Post(folder_entry, uri, converter=gdata.docs.DocumentListEntryFromString) return folder_entry
AttributeError
dataset/ETHPy150Open vinitkumar/googlecl/src/googlecl/docs/service.py/DocsServiceCL._create_folder
8,095
def _determine_content_type(self, file_ext): from gdata.docs.service import SUPPORTED_FILETYPES try: return SUPPORTED_FILETYPES[file_ext.upper()] except __HOLE__: LOG.info('No supported filetype found for extension %s', file_ext) return None
KeyError
dataset/ETHPy150Open vinitkumar/googlecl/src/googlecl/docs/service.py/DocsServiceCL._determine_content_type
8,096
def _modify_entry(self, doc_entry, path_to_new_content, file_ext): """Replace content of a DocEntry. Args: doc_entry: DocEntry whose content will be replaced. path_to_new_content: str Path to file that has new content. file_ext: str Extension to use to determine MIME type of upload (e.g. 'txt', 'doc') """ from gdata.docs.service import SUPPORTED_FILETYPES try: content_type = SUPPORTED_FILETYPES[file_ext.upper()] except __HOLE__: print 'Could not find mimetype for ' + file_ext while file_ext not in SUPPORTED_FILETYPES.keys(): file_ext = raw_input('Please enter one of ' + SUPPORTED_FILETYPES.keys() + ' for a content type to upload as.') content_type = SUPPORTED_FILETYPES[file_ext.upper()] mediasource = gdata.MediaSource(file_path=path_to_new_content, content_type=content_type) return self.Put(mediasource, doc_entry.GetEditMediaLink().href)
KeyError
dataset/ETHPy150Open vinitkumar/googlecl/src/googlecl/docs/service.py/DocsServiceCL._modify_entry
8,097
def _transmit_doc(self, path, entry_title, post_uri, content_type, file_ext): """Upload a document. The final step in uploading a document. The process differs between versions of the gdata python client library, hence its definition here. Args: path: Path to the file to upload. entry_title: Name of the document. post_uri: URI to make request to. content_type: MIME type of request. file_ext: File extension that determined the content_type. Returns: Entry representing the document uploaded. """ media = gdata.MediaSource(file_path=path, content_type=content_type) try: # Upload() wasn't added until later versions of DocsService, so # we may not have it. return self.Upload(media, entry_title, post_uri) except __HOLE__: import atom entry = gdata.docs.DocumentListEntry() entry.title = atom.Title(text=entry_title) # Cover the supported filetypes in gdata-2.0.10 even though # they aren't listed in gdata 1.2.4... see what happens. if file_ext.lower() in ['csv', 'tsv', 'tab', 'ods', 'xls', 'xlsx']: category = _make_kind_category(googlecl.docs.SPREADSHEET_LABEL) elif file_ext.lower() in ['ppt', 'pps']: category = _make_kind_category( googlecl.docs.PRESENTATION_LABEL) elif file_ext.lower() in ['pdf']: category = _make_kind_category(googlecl.docs.PDF_LABEL) # Treat everything else as a document else: category = _make_kind_category(googlecl.docs.DOCUMENT_LABEL) entry.category.append(category) # To support uploading to folders for earlier # versions of the API, expose the lower-level Post return self.Post(entry, post_uri, media_source=media, extra_headers={'Slug': media.file_name}, converter=gdata.docs.DocumentListEntryFromString)
AttributeError
dataset/ETHPy150Open vinitkumar/googlecl/src/googlecl/docs/service.py/DocsServiceCL._transmit_doc
8,098
def show(self): """ Show this screen """ self.draw_screen() selection = None while selection is None: selection = self.screen.getch() try: selection = int(chr(selection)) except __HOLE__: selection = None if selection < 0 or selection > len(self.class_names) - 1: selection = None for index, class_name in enumerate(self.class_names): if index == selection: return self.generator.generate_creature(class_name)
ValueError
dataset/ETHPy150Open tuturto/pyherc/src/herculeum/ui/text/start_game.py/StartGameScreen.show
8,099
def setValueFilter(self, key, value): if key not in self.value_filters: raise jasminApiCredentialError('%s is not a valid Filter' % key) try: self.value_filters[key] = re.compile(value) except __HOLE__: raise jasminApiCredentialError('%s is not a regex pattern: %s' % (key, value))
TypeError
dataset/ETHPy150Open jookies/jasmin/jasmin/routing/jasminApi.py/CredentialGenerick.setValueFilter