Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
3,800
def __init__(self, typemap=None, namespace=None, nsmap=None, makeelement=None): if namespace is not None: self._namespace = '{' + namespace + '}' else: self._namespace = None if nsmap: self._nsmap = dict(nsmap) else: self....
IndexError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/lxml-3.3.6/src/lxml/builder.py/ElementMaker.__init__
3,801
def centerOn(self, name): return """ if set, keeps camera to the given ODE object name. """ try: self.getRenderer().setCenterObj(self.root.namedChild(name).getODEObject()) except __HOLE__: # name not found, unset centerObj print(("Warning: Cannot cente...
KeyError
dataset/ETHPy150Open pybrain/pybrain/pybrain/rl/environments/ode/environment.py/ODEEnvironment.centerOn
3,802
def loadXODE(self, filename, reload=False): """ loads an XODE file (xml format) and parses it. """ f = open(filename) self._currentXODEfile = filename p = xode.parser.Parser() self.root = p.parseFile(f) f.close() try: # filter all xode "world" objects ...
IndexError
dataset/ETHPy150Open pybrain/pybrain/pybrain/rl/environments/ode/environment.py/ODEEnvironment.loadXODE
3,803
def loadConfig(self, filename, reload=False): # parameters are given in (our own brand of) config-file syntax self.config = ConfigGrabber(filename, sectionId="<!--odeenvironment parameters", delim=("<", ">")) # <passpairs> self.passpairs = [] for passpairstring in self.config.ge...
IndexError
dataset/ETHPy150Open pybrain/pybrain/pybrain/rl/environments/ode/environment.py/ODEEnvironment.loadConfig
3,804
def _parseBodies(self, node): """ parses through the xode tree recursively and finds all bodies and geoms for drawing. """ # body (with nested geom) if isinstance(node, xode.body.Body): body = node.getODEObject() body.name = node.getName() try: ...
IndexError
dataset/ETHPy150Open pybrain/pybrain/pybrain/rl/environments/ode/environment.py/ODEEnvironment._parseBodies
3,805
def getSensorByName(self, name): try: idx = self.getSensorNames().index(name) except __HOLE__: warnings.warn('sensor ' + name + ' is not in sensor list.') return [] return self.sensors[idx].getValues()
ValueError
dataset/ETHPy150Open pybrain/pybrain/pybrain/rl/environments/ode/environment.py/ODEEnvironment.getSensorByName
3,806
def build(self): # If there is a docker file or url hand off to Docker builder if 'buildspec' in self.config: if self.config['buildspec']: if 'dockerfile' in self.config['buildspec']: self._build(dockerfile=self.config['buildspec']['dockerfile']) elif 'url' in self.config['bu...
KeyError
dataset/ETHPy150Open toscanini/maestro/maestro/template.py/Template.build
3,807
def _apply_patch(source, patch_text, forwards, name): # Cached ? try: return _patching_cache.retrieve(source, patch_text, forwards) except __HOLE__: pass # Write out files tempdir = mkdtemp(prefix='patchy') try: source_path = os.path.join(tempdir, name + '.py') w...
KeyError
dataset/ETHPy150Open adamchainz/patchy/patchy/api.py/_apply_patch
3,808
def _get_source(func): real_func = _get_real_func(func) try: return _source_map[real_func] except __HOLE__: source = inspect.getsource(func) source = dedent(source) return source
KeyError
dataset/ETHPy150Open adamchainz/patchy/patchy/api.py/_get_source
3,809
def _Run(self, argv): result = 0 name = None glob = [] for i in range(len(argv)): if not argv[i].startswith('-'): name = argv[i] if i > 0: glob = argv[:i] argv = argv[i + 1:] break if not name: glob = argv name = 'help' argv = [] ...
KeyError
dataset/ETHPy150Open esrlabs/git-repo/main.py/_Repo._Run
3,810
def _AddPasswordFromUserInput(handler, msg, req): # If repo could not find auth info from netrc, try to get it from user input url = req.get_full_url() user, password = handler.passwd.find_user_password(None, url) if user is None: print(msg) try: user = input('User: ') password = getpass.get...
KeyboardInterrupt
dataset/ETHPy150Open esrlabs/git-repo/main.py/_AddPasswordFromUserInput
3,811
def init_http(): handlers = [_UserAgentHandler()] mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm() try: n = netrc.netrc() for host in n.hosts: p = n.hosts[host] mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2]) mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2]) exce...
IOError
dataset/ETHPy150Open esrlabs/git-repo/main.py/init_http
3,812
def _Main(argv): result = 0 opt = optparse.OptionParser(usage="repo wrapperinfo -- ...") opt.add_option("--repo-dir", dest="repodir", help="path to .repo/") opt.add_option("--wrapper-version", dest="wrapper_version", help="version of the wrapper script") opt.add_option("--wr...
KeyboardInterrupt
dataset/ETHPy150Open esrlabs/git-repo/main.py/_Main
3,813
def connect(self, name, fn): """ Connect a function ``fn`` to the template hook ``name``. An example hook could look like this:: function my_hook(sender, **kwargs): # Get the request from context request = kwargs['context']['request'] ...
KeyError
dataset/ETHPy150Open weluse/django-templatehooks/templatehooks/registry.py/HookRegistry.connect
3,814
def get_content(self, name, context): """ Get the content of a template hook. Used internally by the hook templatetag. If the referenced hook name has not been manually registered and there are no hooks attached to it, a warning is issued. """ try: s...
KeyError
dataset/ETHPy150Open weluse/django-templatehooks/templatehooks/registry.py/HookRegistry.get_content
3,815
def on_button_release(self, vtk_picker, event): """ If the mouse has not moved, pick with our pickers. """ if self._mouse_no_mvt: x, y = vtk_picker.GetEventPosition() for picker in self._active_pickers.values(): try: picker.pick((x, y, ...
TypeError
dataset/ETHPy150Open enthought/mayavi/mayavi/core/mouse_pick_dispatcher.py/MousePickDispatcher.on_button_release
3,816
@cache_page(60 * 30) def detail(request, slug=None, year=None, month=None, day=None, id=None): """Show a particular episode.""" # strip = get_object_or_404(ComicStrip, slug=slug) try: id = int(id) if year: year = int(year) if month: month = int(month) ...
ValueError
dataset/ETHPy150Open albatrossandco/brubeck_cms/brubeck/comics/views.py/detail
3,817
def deserialize_upload(value, url): """ Restore file and name and storage from serialized value and the upload url. """ result = {'name': None, 'storage': None} try: result = signing.loads(value, salt=url) except signing.BadSignature: # TODO: Log invalid signature pass ...
ImportError
dataset/ETHPy150Open caktus/django-sticky-uploads/stickyuploads/utils.py/deserialize_upload
3,818
@dec.slow def test_inline(self): #TODO: THIS NEEDS TO MOVE TO THE INLINE TEST SUITE a = Foo() a.b = 12345 code = """ throw_error(PyExc_AttributeError,"bummer"); """ try: before = sys.getrefcount(a) inline_tools.inline(code...
AttributeError
dataset/ETHPy150Open scipy/scipy/scipy/weave/tests/test_scxx_object.py/TestObjectHasattr.test_inline
3,819
@dec.slow def test_noargs_with_args_not_instantiated(self): # calling a function that doesn't take args with args should fail. # Note: difference between this test add ``test_noargs_with_args`` # below is that here Foo is not instantiated. def Foo(): return "blah" ...
TypeError
dataset/ETHPy150Open scipy/scipy/scipy/weave/tests/test_scxx_object.py/TestObjectCall.test_noargs_with_args_not_instantiated
3,820
@dec.slow def test_noargs_with_args(self): # calling a function that doesn't take args with args should fail. a = Foo() code = """ py::tuple args(2); args[0] = 1; args[1] = "hello"; return_val = a.mcall("bar",args); "...
TypeError
dataset/ETHPy150Open scipy/scipy/scipy/weave/tests/test_scxx_object.py/TestObjectMcall.test_noargs_with_args
3,821
def authenticate(self, request): try: payload = jwt.decode( jwe.decrypt(request.body, settings.JWE_SECRET), settings.JWT_SECRET, options={'verify_exp': False}, algorithm='HS256' ) except (jwt.InvalidTokenError, __HOL...
TypeError
dataset/ETHPy150Open CenterForOpenScience/osf.io/api/institutions/authentication.py/InstitutionAuthentication.authenticate
3,822
@jit.unroll_safe def UNPACK_SEQUENCE(self, space, bytecode, frame, pc, n_items): w_obj = frame.pop() items_w = space.listview(w_obj) for i in xrange(n_items - 1, -1, -1): try: w_obj = items_w[i] except __HOLE__: w_obj = space.w_nil ...
IndexError
dataset/ETHPy150Open topazproject/topaz/topaz/interpreter.py/Interpreter.UNPACK_SEQUENCE
3,823
def __init__(self, *args, **config): super(ResourceWatcher, self).__init__(*args, **config) self.watcher = config.get("watcher", None) self.service = config.get("service", None) if self.service is not None: warnings.warn("ResourceWatcher.service is deprecated " ...
ValueError
dataset/ETHPy150Open circus-tent/circus/circus/plugins/resource_watcher.py/ResourceWatcher.__init__
3,824
def list_updated ( self, values ): """ Handles updates to the list of legal checklist values. """ sv = self.string_value if (len( values ) > 0) and isinstance( values[0], basestring ): values = [ ( x, sv( x, capitalize ) ) for x in values ] self.values = valid_values =...
TypeError
dataset/ETHPy150Open enthought/traitsui/traitsui/wx/check_list_editor.py/SimpleEditor.list_updated
3,825
@staticmethod def convert(filename): try: from hashlib import md5 except __HOLE__: from md5 import md5 _f, ext = os.path.splitext(filename) f = md5( md5("%f%s%f%s" % (time.time(), id({}), random.random(), ...
ImportError
dataset/ETHPy150Open limodou/uliweb/uliweb/contrib/upload/__init__.py/MD5FilenameConverter.convert
3,826
def normalize_column_type(l, normal_type=None, blanks_as_nulls=True): """ Attempts to normalize a list (column) of string values to booleans, integers, floats, dates, times, datetimes, or strings. NAs and missing values are converted to empty strings. Empty strings are converted to nulls in the case of ...
ValueError
dataset/ETHPy150Open wireservice/csvkit/csvkit/typeinference.py/normalize_column_type
3,827
def _open_local_shell(self): imported_objects = self.get_imported_objects() try: import IPython except __HOLE__: IPython = None if IPython: IPython.start_ipython( argv=[], user_ns=imported_objects, banne...
ImportError
dataset/ETHPy150Open deliveryhero/lymph/lymph/cli/shell.py/ShellCommand._open_local_shell
3,828
def _get_backdoor_endpoint(self, service_fullname): try: name, identity_prefix = service_fullname.split(':') except __HOLE__: sys.exit("Malformed argument it should be in the format 'name:identity'") service = self.client.container.lookup(name) instance = service....
ValueError
dataset/ETHPy150Open deliveryhero/lymph/lymph/cli/shell.py/ShellCommand._get_backdoor_endpoint
3,829
def _calculate(self, data): x = data.pop('x') try: float(x.iloc[0]) except: try: # try to use it as a pandas.tslib.Timestamp x = [ts.toordinal() for ts in x] except: raise GgplotError("stat_density(): aesthetic ...
KeyError
dataset/ETHPy150Open yhat/ggplot/ggplot/stats/stat_density.py/stat_density._calculate
3,830
def multiplicity(p, n): """ Find the greatest integer m such that p**m divides n. Examples ======== >>> from sympy.ntheory import multiplicity >>> from sympy.core.numbers import Rational as R >>> [multiplicity(5, n) for n in [8, 5, 25, 125, 250]] [0, 1, 2, 3, 3] >>> multiplicity(3,...
AttributeError
dataset/ETHPy150Open sympy/sympy/sympy/ntheory/factor_.py/multiplicity
3,831
def factorint(n, limit=None, use_trial=True, use_rho=True, use_pm1=True, verbose=False, visual=None): r""" Given a positive integer ``n``, ``factorint(n)`` returns a dict containing the prime factors of ``n`` as keys and their respective multiplicities as values. For example: >>> from...
StopIteration
dataset/ETHPy150Open sympy/sympy/sympy/ntheory/factor_.py/factorint
3,832
def __str__(self): if self.msg: return self.msg try: return str(self.__dict__) except (NameError, __HOLE__, KeyError), e: return 'Unprintable exception %s: %s' \ % (self.__class__.__name__, str(e))
ValueError
dataset/ETHPy150Open benoitc/restkit/restkit/errors.py/ResourceError.__str__
3,833
def get_value(self, report, row): val = self.mapfunc(report, self.key, row) if self.format is not None: val = self.format % val elif val is None: val = "" if type(val) != str: try: val = val.encode('utf-8') except __HOLE__:...
AttributeError
dataset/ETHPy150Open berrange/gerrymander/gerrymander/reports.py/ReportOutputColumn.get_value
3,834
def error_for_errno(space, errno): try: name = _errno_for_oserror_map[errno] except __HOLE__: w_type = space.w_SystemCallError else: w_type = space.find_const(space.find_const(space.w_object, "Errno"), name) return space.error( w_type, os.strerror(errno), ...
KeyError
dataset/ETHPy150Open topazproject/topaz/topaz/error.py/error_for_errno
3,835
def watcher(task, *args, **kwargs): while True: run('clear') kwargs['warn'] = True task(*args, **kwargs) try: run( 'inotifywait -q -e create -e modify -e delete ' '--exclude ".*\.(pyc|sw.)" -r docs/ mopidy/ tests/') except __HOLE__:...
KeyboardInterrupt
dataset/ETHPy150Open mopidy/mopidy/tasks.py/watcher
3,836
def choose(rects, lines = [], gauges = [None], trace=''): def induce(r): if trace == 'induce': pdb.set_trace() uncommons = r.get_uncommons() if len(uncommons) < 2: return irs = [] for s in rects: if s.dir != r.dir: continue pss = [] uncs = s.get_uncommons(pickednos) lnos = s.lno...
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/guppy-0.1.10/guppy/etc/RE_Rect.py/choose
3,837
def validate_json_file(file): try: data = generics_utils.check_json_syntax(file) if data is None: return #check manadatory fields if "stack" in data: stack=check_mandatory_stack(data["stack"]) if stack is None: return #else:...
ValueError
dataset/ETHPy150Open usharesoft/hammr/src/hammr/utils/hammr_utils.py/validate_json_file
3,838
def request(self, method, url, headers, post_data=None): kwargs = {} if self._verify_ssl_certs: kwargs['verify'] = os.path.join( os.path.dirname(__file__), 'data/ca-certificates.crt') else: kwargs['verify'] = False try: try: ...
NotImplementedError
dataset/ETHPy150Open goshippo/shippo-python-client/shippo/http_client.py/RequestsClient.request
3,839
def run(self, config, args): appname = self.default_appname(config, args) server, procfile = config.get('server', 'procfile') if not args['<jobs>'] and not args['--from-file']: # unload from a procfile if not args["--no-input"]: if not self.confirm("Do yo...
KeyError
dataset/ETHPy150Open benoitc/gaffer/gaffer/cli/commands/reload.py/Reload.run
3,840
def handle(self, doc_types, *args, **options): input = raw_input('\n'.join([ '\n\nReally delete documents of the following types: {}?', 'This operation is not reversible. Enter a number N to delete the first ' 'N found, or type "delete all" to delete everything.', ...
ValueError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/cleanup/management/commands/purge_docs.py/Command.handle
3,841
def __init__(self, prototype , elements): """ Constructor, needs the prototype and the elements of the clustering. TODO: change it by (elements, [prototype]). Prototype must be calculated on demand and use bookkeeping """ self.set_elements(elements) self.id = "" ...
TypeError
dataset/ETHPy150Open victor-gil-sepulveda/pyProCT/pyproct/clustering/cluster.py/Cluster.__init__
3,842
def expanduser(path): """Expand ~ and ~user constructs. If user or $HOME is unknown, do nothing.""" if path[:1] != '~': return path i, n = 1, len(path) while i < n and path[i] not in '/\\': i = i + 1 if 'HOME' in os.environ: userhome = os.environ['HOME'] elif 'USERP...
KeyError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/ntpath.py/expanduser
3,843
def expandvars(path): """Expand shell variables of the forms $var, ${var} and %var%. Unknown variables are left unchanged.""" if '$' not in path and '%' not in path: return path import string varchars = string.ascii_letters + string.digits + '_-' res = '' index = 0 pathlen = len...
ValueError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/ntpath.py/expandvars
3,844
def net(self, irc, msg, args): """takes no arguments Returns some interesting network-related statistics. """ try: elapsed = time.time() - self.connected[irc.getRealIrc()] timeElapsed = utils.timeElapsed(elapsed) except __HOLE__: timeElapsed =...
KeyError
dataset/ETHPy150Open ProgVal/Limnoria/plugins/Status/plugin.py/Status.net
3,845
@internationalizeDocstring def cpu(self, irc, msg, args): """takes no arguments Returns some interesting CPU-related statistics on the bot. """ (user, system, childUser, childSystem, elapsed) = os.times() now = time.time() target = msg.args[0] timeRunning = n...
OSError
dataset/ETHPy150Open ProgVal/Limnoria/plugins/Status/plugin.py/Status.cpu
3,846
def get_version(self): try: return str(self.cookie_set.all()[0].get_version()) except __HOLE__: return ""
IndexError
dataset/ETHPy150Open bmihelac/django-cookie-consent/cookie_consent/models.py/CookieGroup.get_version
3,847
def _cleanup_response_queue(self, message): """Stop tracking the response queue either because we're done receiving responses, or we've timed out. """ try: del self.response_queues[message.uuid] except __HOLE__: # Ignore if queue is gone already somehow. ...
KeyError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/cells/messaging.py/MessageRunner._cleanup_response_queue
3,848
def deserialize_remote_exception(data, allowed_remote_exmods): failure = jsonutils.loads(str(data)) trace = failure.get('tb', []) message = failure.get('message', "") + "\n" + "\n".join(trace) name = failure.get('class') module = failure.get('module') # NOTE(ameade): We DO NOT want to allow ju...
TypeError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/cells/messaging.py/deserialize_remote_exception
3,849
def run(self): self.socket = self.context.socket(zmq.REP) self.socket.connect(self.uri) try: while True: cmd, uid, args = protocol.msg.extract_request( self.socket.recv() ) try: if cmd in self.db...
RuntimeError
dataset/ETHPy150Open onitu/onitu/onitu/escalator/server/worker.py/Worker.run
3,850
def handle_cmd(self, db, commands, cmd, args): cb = commands.get(cmd) if cb: try: resp = cb(db, *args) if db is not None else cb(*args) except __HOLE__ as e: self.logger.warning("Invalid arguments: {}", e) resp = protocol.msg.format...
TypeError
dataset/ETHPy150Open onitu/onitu/onitu/escalator/server/worker.py/Worker.handle_cmd
3,851
def extract_views_from_urlpatterns(urlpatterns, base='', namespace=None, ignored_modules=None): """ Return a list of views from a list of urlpatterns. Each object in the returned list is a tuple: (view_func, regex, name) """ ignored_modules = ignored_modules if ignored_modules else [] views = [...
ImportError
dataset/ETHPy150Open potatolondon/djangae/djangae/contrib/security/commands_utils.py/extract_views_from_urlpatterns
3,852
def analyse_commit(self, commit, ref_id, repo_id): message = commit.message author_name = commit.author.name author_email = commit.author.email committer_name = commit.committer.name committer_email = commit.committer.email size = commit.size sha = commit.hexsha ...
AttributeError
dataset/ETHPy150Open SOM-Research/Gitana/git2db.py/Git2Db.analyse_commit
3,853
def _check_backend(): from ..utils import _check_pyface_backend try: from pyface.api import warning except __HOLE__: warning = None backend, status = _check_pyface_backend() if status == 0: return elif status == 1: msg = ("The currently selected Pyface backend %s...
ImportError
dataset/ETHPy150Open mne-tools/mne-python/mne/gui/_backend.py/_check_backend
3,854
def getTexcoordToImgMapping(mesh): #get a list of all texture coordinate sets all_texcoords = {} for geom in mesh.geometries: for prim_index, prim in enumerate(geom.primitives): inputs = prim.getInputList().getList() texindex = 0 for offset, semantic, srcid, seti...
ValueError
dataset/ETHPy150Open pycollada/meshtool/meshtool/filters/atlas_filters/make_atlases.py/getTexcoordToImgMapping
3,855
def do_longs(opts, opt, longopts, args): try: i = opt.index('=') except __HOLE__: optarg = None else: opt, optarg = opt[:i], opt[i + 1:] has_arg, opt = long_has_args(opt, longopts) if has_arg: if optarg is None: if not args: raise GetoptEr...
ValueError
dataset/ETHPy150Open CountZer0/PipelineConstructionSet/python/common/diagnostic/pydevDebug/runfiles.py/do_longs
3,856
def filter_tests(self, test_objs): """ based on a filter name, only return those tests that have the test case names that match """ test_suite = [] for test_obj in test_objs: if isinstance(test_obj, unittest.TestSuite): if test_obj._tests: ...
AttributeError
dataset/ETHPy150Open CountZer0/PipelineConstructionSet/python/common/diagnostic/pydevDebug/runfiles.py/PydevTestRunner.filter_tests
3,857
def run(self, cmd, code): """Attempt to parse code as JSON, return '' if it succeeds, the error message if it fails.""" # Use ST's loose parser for its setting files. strict = os.path.splitext(self.filename)[1] not in self.extensions try: if strict: self.__c...
ValueError
dataset/ETHPy150Open SublimeLinter/SublimeLinter-json/linter.py/JSON.run
3,858
def update_user(self, user, attributes, attribute_mapping, force_save=False): """Update a user with a set of attributes and returns the updated user. By default it uses a mapping defined in the settings constant SAML_ATTRIBUTE_MAPPING. For each attribute, if the user object ...
ObjectDoesNotExist
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/djangosaml2-0.13.0/djangosaml2/backends.py/Saml2Backend.update_user
3,859
@use_bootstrap3 @retry_resource(3) def view_generic(request, domain, app_id=None, module_id=None, form_id=None, copy_app_form=None): """ This is the main view for the app. All other views redirect to here. """ if form_id and not module_id: return bail(request, domain, app_id) ...
IndexError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/app_manager/views/view_generic.py/view_generic
3,860
def CMDreindex(parser): """Begins to reindex the quickopen database""" (options, args) = parser.parse_args() db = open_db(options) try: db.begin_reindex() print "Reindexing has begun." except __HOLE__: print "%s." % DBStatus.not_running_string()
IOError
dataset/ETHPy150Open natduca/quickopen/src/quickopen.py/CMDreindex
3,861
def CMDedit(parser): """Searches for <query> then opens it in $EDITOR""" parser.add_option('--current-filename', dest='current_filename', action='store', default=None, help="Hints quickopen about the current buffer to improve search relevance.") parser.add_option('--open-filenames', dest='open_filenames', action=...
KeyboardInterrupt
dataset/ETHPy150Open natduca/quickopen/src/quickopen.py/CMDedit
3,862
def run(verbosity=1,doctest=False,numpy=True): """Run NetworkX tests. Parameters ---------- verbosity: integer, optional Level of detail in test reports. Higher numbers provide more detail. doctest: bool, optional True to run doctests in code modules numpy: bool, optional ...
ImportError
dataset/ETHPy150Open networkx/networkx/networkx/tests/test.py/run
3,863
def push_data(self, item, key, data): if self.postprocessor is not None: result = self.postprocessor(self.path, key, data) if result is None: return item key, data = result if item is None: item = self.dict_constructor() try: ...
KeyError
dataset/ETHPy150Open haukurk/flask-restapi-recipe/restapi/utils/conversion/xmltodict.py/_DictSAXHandler.push_data
3,864
def parse(xml_input, encoding=None, expat=expat, process_namespaces=False, namespace_separator=':', **kwargs): """Parse the given XML input and convert it into a dictionary. `xml_input` can either be a `string` or a file-like object. If `xml_attribs` is `True`, element attributes are put in the ...
AttributeError
dataset/ETHPy150Open haukurk/flask-restapi-recipe/restapi/utils/conversion/xmltodict.py/parse
3,865
def unparse(input_dict, output=None, encoding='utf-8', **kwargs): """Emit an XML document for the given `input_dict` (reverse of `parse`). The resulting XML document is returned as a string, but if `output` (a file-like object) is specified, it is written there instead. Dictionary keys prefixed with `...
AttributeError
dataset/ETHPy150Open haukurk/flask-restapi-recipe/restapi/utils/conversion/xmltodict.py/unparse
3,866
def resolve_selection ( self, selection_list ): """ Returns a list of (row, col) grid-cell coordinates that correspond to the objects in *selection_list*. For each coordinate, if the row is -1, it indicates that the entire column is selected. Likewise coordinates with a colum...
ValueError
dataset/ETHPy150Open enthought/traitsui/traitsui/wx/table_model.py/TableModel.resolve_selection
3,867
def _generate_filename_to_mtime(self): filename_to_mtime = {} num_files = 0 for dirname, dirnames, filenames in os.walk(self._directory, followlinks=True): for filename in filenames + dirnames: if num_files == 10000: warnings.warn( ...
OSError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/tools/devappserver2/mtime_file_watcher.py/MtimeFileWatcher._generate_filename_to_mtime
3,868
def _json_payload(request): """ Return a parsed JSON payload for the request. :raises PayloadError: if the body has no valid JSON body """ try: return request.json_body except __HOLE__: raise PayloadError()
ValueError
dataset/ETHPy150Open hypothesis/h/h/api/views.py/_json_payload
3,869
def get_validation_errors(outfile, app=None): """ Validates all models that are part of the specified app. If no app name is provided, validates all models of all installed apps. Writes errors, if any, to outfile. Returns number of errors. """ from django.conf import settings from django.db ...
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/core/management/validation.py/get_validation_errors
3,870
def missing_or_empty(obj, key): try: if not obj[key]: return True except __HOLE__: return True return False
KeyError
dataset/ETHPy150Open upconsulting/IsisCB/isiscb/zotero/admin.py/missing_or_empty
3,871
def is_valid(self): """ Enforce validation for ``value`` based on ``type_controlled``. """ val = super(AttributeForm, self).is_valid() if all(x in self.cleaned_data for x in ['value', 'type_controlled']): value = self.cleaned_data['value'] attr_type = sel...
ValidationError
dataset/ETHPy150Open upconsulting/IsisCB/isiscb/zotero/admin.py/AttributeForm.is_valid
3,872
def match(request, draftmodel, choicemodel): """ Load selected draft and production instances based on user selection. See :meth:`.DraftCitationAdmin.match` and :meth:`.DraftAuthorityAdmin.match`\. """ chosen = [] for field in request.POST.keys(): if not field.startswith('suggestion...
ValueError
dataset/ETHPy150Open upconsulting/IsisCB/isiscb/zotero/admin.py/match
3,873
def create_authority(self, request, draftauthority_id): """ A staff user can create a new :class:`isisdata.Authority` record using data from a :class:`zotero.DraftAuthority` instance. """ context = dict(self.admin_site.each_context(request)) context.update({'title': 'Crea...
KeyError
dataset/ETHPy150Open upconsulting/IsisCB/isiscb/zotero/admin.py/DraftAuthorityAdmin.create_authority
3,874
def get_txt(name): """Return a TXT record associated with a DNS name. @param name: The bytestring domain name to look up. """ # pydns needs Unicode, but DKIM's d= is ASCII (already punycoded). try: unicode_name = name.decode('ascii') except __HOLE__: return None txt = _get_t...
UnicodeDecodeError
dataset/ETHPy150Open Flolagale/mailin/python/dkim/dnsplug.py/get_txt
3,875
@conf def get_python_variables(self, variables, imports=None): """ Spawn a new python process to dump configuration variables :param variables: variables to print :type variables: list of string :param imports: one import by element :type imports: list of string :return: the variable values :rtype: list of str...
KeyError
dataset/ETHPy150Open cournape/Bento/bento/backends/waf_tools/custom_python.py/get_python_variables
3,876
@conf def check_python_headers(conf): """ Check for headers and libraries necessary to extend or embed python by using the module *distutils*. On success the environment variables xxx_PYEXT and xxx_PYEMBED are added: * PYEXT: for compiling python extensions * PYEMBED: for embedding a python interpreter """ # F...
RuntimeError
dataset/ETHPy150Open cournape/Bento/bento/backends/waf_tools/custom_python.py/check_python_headers
3,877
@feature('pyext') @before_method('propagate_uselib_vars', 'apply_link') @after_method('apply_bundle') def init_pyext(self): """ Change the values of *cshlib_PATTERN* and *cxxshlib_PATTERN* to remove the *lib* prefix from library names. """ self.uselib = self.to_list(getattr(self, 'uselib', [])) if not 'PYEXT' in ...
AttributeError
dataset/ETHPy150Open cournape/Bento/bento/backends/waf_tools/custom_python.py/init_pyext
3,878
def _Cmd(self, command, mode=None, merge_stderr_first=False, send=None, require_low_chanid=False): response = '' retries_left = 1 while True: try: chan = self._ssh_client.get_transport().open_session() chan.settimeout(self.timeout_response) if require_low_chanid and ...
AttributeError
dataset/ETHPy150Open google/capirca/tools/ldpush/paramiko_device.py/ParamikoDevice._Cmd
3,879
@classmethod def get_all_metadata(cls, config_providers=default_settings.PROVIDERS): ret = {} providers = cls.get_providers(config_providers) for provider in providers: provider_data = {} provider_data["provides_metrics"] = provider.provides_metrics provid...
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpact/providers/provider.py/ProviderFactory.get_all_metadata
3,880
def _get_error(self, status_code, response=None): try: headers = response.headers except __HOLE__: headers = {} try: text = response.text except (AttributeError, TypeError): text = "" if response: url = response....
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpact/providers/provider.py/Provider._get_error
3,881
def _get_templated_url(self, template, id, method=None): try: id_unicode = unicode(id, "UTF-8") except __HOLE__: id_unicode = id id_utf8 = id_unicode.encode("UTF-8") substitute_id = id_utf8 if template != "%s": substitute_id = urllib.quote(id_u...
TypeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpact/providers/provider.py/Provider._get_templated_url
3,882
def metric_names(self): try: metric_names = self.static_meta_dict.keys() except __HOLE__: metric_names = [] return(metric_names) # default method; providers can override
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpact/providers/provider.py/Provider.metric_names
3,883
def member_items(self, query_string, provider_url_template=None, cache_enabled=True): if not self.provides_members: raise NotImplementedError() self.logger.debug(u"%s getting member_items for %s" % (self.provider_name, query_string)) if not p...
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpact/providers/provider.py/Provider.member_items
3,884
def get_biblio_for_id(self, id, provider_url_template=None, cache_enabled=True): if not self.provides_biblio: return {} self.logger.debug(u"%s getting biblio for %s" % (self.provider_name, id)) if not provider_url_template: provide...
TypeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpact/providers/provider.py/Provider.get_biblio_for_id
3,885
def _get_aliases_for_id(self, id, provider_url_template=None, cache_enabled=True): if not self.provides_aliases: return [] self.logger.debug(u"%s getting aliases for %s" % (self.provider_name, id)) if not provider_url_template: pr...
TypeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpact/providers/provider.py/Provider._get_aliases_for_id
3,886
def get_metrics_for_id(self, id, provider_url_template=None, cache_enabled=True, url_override=None, extract_metrics_method=None): if not self.provides_metrics: return {} if not extract_metrics_method: extract_metri...
TypeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpact/providers/provider.py/Provider.get_metrics_for_id
3,887
def http_get(self, url, headers={}, timeout=20, cache_enabled=True, allow_redirects=False): """ Returns a requests.models.Response object or raises exception on failure. Will cache requests to the same URL. """ headers["User-Agent"] = USER_AGENT if cache_enabled: cache ...
UnicodeDecodeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpact/providers/provider.py/Provider.http_get
3,888
def _lookup_json(data, keylist): for mykey in keylist: try: data = data[mykey] except (KeyError, __HOLE__): return None return(data)
TypeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpact/providers/provider.py/_lookup_json
3,889
def _get_doc_from_xml(page): try: try: doc = minidom.parseString(page.strip().encode('utf-8')) except __HOLE__: doc = minidom.parseString(page.strip()) lookup_function = _lookup_xml_from_dom except ExpatError, e: doc = BeautifulSoup.BeautifulSt...
UnicodeDecodeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpact/providers/provider.py/_get_doc_from_xml
3,890
def _find_all_in_xml(page, mykey): (doc, lookup_function) = _get_doc_from_xml(page) if not doc: return None try: doc_list = doc.getElementsByTagName(mykey) except (KeyError, IndexError, __HOLE__): return None return(doc_list)
TypeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpact/providers/provider.py/_find_all_in_xml
3,891
def _lookup_xml_from_dom(doc, keylist): response = None for mykey in keylist: if not doc: return None try: doc_list = doc.getElementsByTagName(mykey) # just takes the first one for now doc = doc_list[0] except (__HOLE__, IndexError): ...
KeyError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpact/providers/provider.py/_lookup_xml_from_dom
3,892
def _lookup_xml_from_soup(soup, keylist): smaller_bowl_of_soup = soup for mykey in keylist: if not smaller_bowl_of_soup: return None try: # BeautifulSoup forces all keys to lowercase smaller_bowl_of_soup = smaller_bowl_of_soup.find(mykey.lower()) e...
KeyError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpact/providers/provider.py/_lookup_xml_from_soup
3,893
def _extract_from_xml(page, dict_of_keylists): (doc, lookup_function) = _get_doc_from_xml(page) return_dict = {} if dict_of_keylists: for (metric, keylist) in dict_of_keylists.iteritems(): value = lookup_function(doc, keylist) # only set metrics for non-zero and non-null met...
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpact/providers/provider.py/_extract_from_xml
3,894
def doi_from_url_string(url): logger.info(u"%s parsing url %s" %("doi_from_url_string", url)) result = re.findall("(10\.\d+.[0-9a-wA-W_/\.\-%]+)" , url, re.DOTALL) try: doi = urllib.unquote(result[0]) except __HOLE__: doi = None return(doi)
IndexError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpact/providers/provider.py/doi_from_url_string
3,895
def _get_shebang(self, encoding, post_interp=b'', options=None): enquote = True if self.executable: executable = self.executable enquote = False # assume this will be taken care of elif not sysconfig.is_python_build(): executable = get_executable() ...
UnicodeDecodeError
dataset/ETHPy150Open francelabs/datafari/windows/python/Lib/site-packages/pip/_vendor/distlib/scripts.py/ScriptMaker._get_shebang
3,896
def _copy_script(self, script, filenames): adjust = False script = os.path.join(self.source_dir, convert_path(script)) outname = os.path.join(self.target_dir, os.path.basename(script)) if not self.force and not self._fileop.newer(script, outname): logger.debug('not copying %s...
IOError
dataset/ETHPy150Open francelabs/datafari/windows/python/Lib/site-packages/pip/_vendor/distlib/scripts.py/ScriptMaker._copy_script
3,897
def show_samples(m, model_path): """ Show samples given a DBM model. Parameters ---------- m: int rows * cols model_path: str Path of the model. """ model = load_model(model_path, m) print('Loading data (used for setting up visualization ' 'and seeding gib...
ValueError
dataset/ETHPy150Open lisa-lab/pylearn2/pylearn2/scripts/dbm/show_samples.py/show_samples
3,898
def main(opts): try: # Load a context with initialization ctx = Context.load(opts.workspace, strict=True) # Initialize the workspace if necessary if ctx: print('Catkin workspace `%s` is already initialized. No action taken.' % (ctx.workspace)) else: p...
IOError
dataset/ETHPy150Open catkin/catkin_tools/catkin_tools/verbs/catkin_init/cli.py/main
3,899
def _get_data_from_resource_manager(resource_manager, attrs_white_list_rules, additional_display_options): data = [] display_options = {} display_options.update(additional_display_options) instances_list = resource_manager.list(**display_options) for inst in ins...
KeyError
dataset/ETHPy150Open openstack/fuel-web/nailgun/nailgun/statistics/oswl/helpers.py/_get_data_from_resource_manager