Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
5,700
@jsexpose(body_cls=ApiKeyAPI, status_code=http_client.CREATED) @request_user_has_resource_api_permission(permission_type=PermissionType.API_KEY_CREATE) def post(self, api_key_api): """ Create a new entry or update an existing one. """ api_key_db = None try: ap...
ValueError
dataset/ETHPy150Open StackStorm/st2/st2api/st2api/controllers/v1/auth.py/ApiKeyController.post
5,701
def __init__(self, args, operating_system): """Create an instance of the controller passing in the debug flag, the options and arguments from the cli parser. :param argparse.Namespace args: Command line arguments :param str operating_system: Operating system name from helper.platform ...
ValueError
dataset/ETHPy150Open gmr/helper/helper/controller.py/Controller.__init__
5,702
def __del__(self): import threading key = object.__getattribute__(self, '_local__key') try: threads = list(threading.enumerate()) except: return for thread in threads: try: __dict__ = thread.__dict__ except Att...
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/dist/_threading_local.py/local.__del__
5,703
def __init__(self, *args, **kwargs): """ Set up some defaults and check for a ``default_related_model`` attribute for the ``to`` argument. """ kwargs.setdefault("object_id_field", "object_pk") to = getattr(self, "default_related_model", None) # Avoid having both a...
AttributeError
dataset/ETHPy150Open stephenmcd/mezzanine/mezzanine/generic/fields.py/BaseGenericRelation.__init__
5,704
def related_items_changed(self, instance, related_manager): """ Stores the number of comments. A custom ``count_filter`` queryset gets checked for, allowing managers to implement custom count logic. """ try: count = related_manager.count_queryset() exc...
AttributeError
dataset/ETHPy150Open stephenmcd/mezzanine/mezzanine/generic/fields.py/CommentsField.related_items_changed
5,705
def contribute_to_class(self, cls, name): """ Swap out any reference to ``KeywordsField`` with the ``KEYWORDS_FIELD_string`` field in ``search_fields``. """ super(KeywordsField, self).contribute_to_class(cls, name) string_field_name = list(self.fields.keys())[0] % \ ...
TypeError
dataset/ETHPy150Open stephenmcd/mezzanine/mezzanine/generic/fields.py/KeywordsField.contribute_to_class
5,706
def get_redis_backend(): """Connect to redis from a string like CACHE_BACKEND.""" # From django-redis-cache. server, params = parse_backend_uri(settings.REDIS_BACKEND) db = params.pop('db', 0) try: db = int(db) except (ValueError, __HOLE__): db = 0 try: socket_timeout...
TypeError
dataset/ETHPy150Open django-cache-machine/django-cache-machine/caching/invalidation.py/get_redis_backend
5,707
def add_lazy_relation(cls, field, relation, operation): """ Adds a lookup on ``cls`` when a related field is defined using a string, i.e.:: class MyModel(Model): fk = ForeignKey("AnotherModel") This string can be: * RECURSIVE_RELATIONSHIP_CONSTANT (i.e. "self") to indicate...
ValueError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/db/models/fields/related.py/add_lazy_relation
5,708
def __get__(self, instance, instance_type=None): if instance is None: return self try: rel_obj = getattr(instance, self.cache_name) except __HOLE__: related_pk = instance._get_pk_val() if related_pk is None: rel_obj = None ...
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/db/models/fields/related.py/SingleRelatedObjectDescriptor.__get__
5,709
def __get__(self, instance, instance_type=None): if instance is None: return self try: rel_obj = getattr(instance, self.cache_name) except __HOLE__: val = self.field.get_local_related_value(instance) if None in val: rel_obj = None ...
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/db/models/fields/related.py/ReverseSingleRelatedObjectDescriptor.__get__
5,710
def __set__(self, instance, value): # If null=True, we can assign null here, but otherwise the value needs # to be an instance of the related class. if value is None and self.field.null == False: raise ValueError('Cannot assign None: "%s.%s" does not allow null values.' % ...
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/db/models/fields/related.py/ReverseSingleRelatedObjectDescriptor.__set__
5,711
@cached_property def related_manager_cls(self): # Dynamically create a class that subclasses the related model's default # manager. superclass = self.related.model._default_manager.__class__ rel_field = self.related.field rel_model = self.related.model class RelatedM...
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/db/models/fields/related.py/ForeignRelatedObjectsDescriptor.related_manager_cls
5,712
def create_many_related_manager(superclass, rel): """Creates a manager that subclasses 'superclass' (which is a Manager) and adds behavior for many-to-many related objects.""" class ManyRelatedManager(superclass): def __init__(self, model=None, query_field_name=None, instance=None, symmetrical=None,...
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/db/models/fields/related.py/create_many_related_manager
5,713
def __init__(self, field, to, related_name=None, limit_choices_to=None, parent_link=False, on_delete=None, related_query_name=None): try: to._meta except __HOLE__: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT assert isinstance(to, six....
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/db/models/fields/related.py/ForeignObjectRel.__init__
5,714
def __init__(self, to, to_field=None, rel_class=ManyToOneRel, db_constraint=True, **kwargs): try: to_name = to._meta.object_name.lower() except __HOLE__: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT assert isinstance(to, six.string_typ...
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/db/models/fields/related.py/ForeignKey.__init__
5,715
def __init__(self, to, db_constraint=True, **kwargs): try: assert not to._meta.abstract, "%s cannot define a relation with abstract class %s" % (self.__class__.__name__, to._meta.object_name) except __HOLE__: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT ...
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/db/models/fields/related.py/ManyToManyField.__init__
5,716
@defer.inlineCallbacks def _on_event(self, event_name): baton = dict(event=event_name, client=self) try: processor = yield self.dependencies.wait_for_resource(event_name) yield processor(baton) except __HOLE__ as ae: # we have no processor for this event ...
KeyError
dataset/ETHPy150Open foundit/Piped/contrib/zookeeper/piped_zookeeper/providers.py/PipedZookeeperClient._on_event
5,717
def __init__(self, *args, **kwargs): self.document = kwargs.pop('document', None) super(DocumentContentForm, self).__init__(*args, **kwargs) content = [] self.fields['contents'].initial = '' try: document_pages = self.document.pages.all() except __HOLE__: ...
AttributeError
dataset/ETHPy150Open mayan-edms/mayan-edms/mayan/apps/ocr/forms.py/DocumentContentForm.__init__
5,718
def dispatch(self, parameterName, value): """ When called in dispatch, do the coerce for C{value} and save the returned value. """ if value is None: raise UsageError("Parameter '%s' requires an argument." % (parameterName,)) try: ...
ValueError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/python/usage.py/CoerceParameter.dispatch
5,719
def parseOptions(self, options=None): """ The guts of the command-line parser. """ if options is None: options = sys.argv[1:] try: opts, args = getopt.getopt(options, self.shortOpt, self.longOpt) except getop...
TypeError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/python/usage.py/Options.parseOptions
5,720
def testStringKeys(self): d = {'a':1, 'b':2, '3':3, 3:4} self.assertEqual(d['a'], 1) self.assertEqual(d['b'], 2) # XXX: the length here is 3 because we have the same keys for "3" # and 3 #self.assertEqual(len(d), 4) # XXX: we have to have constant handling in th...
KeyError
dataset/ETHPy150Open anandology/pyjamas/examples/libtest/DictTest.py/DictTest.testStringKeys
5,721
def testPop(self): d = {'a': 1, 'b': 2, 'c': 3} item = d.pop('d', 4) self.assertEqual(item, 4) try: item = d.pop('d') self.fail("Failed to raise KeyError on d.pop('d')") except __HOLE__, e: self.assertEqual(e[0], "d") item = d.pop('b'...
KeyError
dataset/ETHPy150Open anandology/pyjamas/examples/libtest/DictTest.py/DictTest.testPop
5,722
def testEq(self): self.failUnlessEqual({}, {}) self.failUnlessEqual({'1':1}, {'1':1}) self.failIfEqual({},{'1':1}) self.failIfEqual({'1':1},{'1':2}) # test for bug 362 try: self.failIfEqual({'1':1}, [1,2], "Test for Bug 362") except __HOLE__: ...
TypeError
dataset/ETHPy150Open anandology/pyjamas/examples/libtest/DictTest.py/DictTest.testEq
5,723
def testUpdate(self): d1 = {1:2,3:4} d1.update({3:5,7:9}) self.assertEqual(d1[3],5) try: d1.update(((3,6),(9,12))) self.assertEqual(d1[3],6) except __HOLE__: self.fail("Couldn't dict.update(...) with a tuple of pairs.")
TypeError
dataset/ETHPy150Open anandology/pyjamas/examples/libtest/DictTest.py/DictTest.testUpdate
5,724
def startService(self): log.msg('Loading index') try: f = file(self._makeFilename('index'), 'rb') d = pickle.load(f) self._index = d['index'] self._nextOid = d['nextOid'] except __HOLE__: self._index = [] self._nextOid = 1
IOError
dataset/ETHPy150Open twisted/nevow/examples/pastebin/pastebin/service.py/FSPasteBinService.startService
5,725
def root_semrep(syntree, semkey='SEM'): """ Find the semantic representation at the root of a tree. :param syntree: a parse ``Tree`` :param semkey: the feature label to use for the root semantics in the tree :return: the semantic representation at the root of a ``Tree`` :rtype: sem.Expression ...
KeyError
dataset/ETHPy150Open nltk/nltk/nltk/sem/util.py/root_semrep
5,726
def get(self, field, default=None): try: return self.__get_field_value(field, [], original=field) except __HOLE__: return default
KeyError
dataset/ETHPy150Open spinnaker/spinnaker/pylib/spinnaker/yaml_util.py/YamlBindings.get
5,727
def __resolve_value(self, value, saw, original): expression_re = re.compile('\${([\._a-zA-Z0-9]+)(:.+?)?}') exact_match = expression_re.match(value) if exact_match and exact_match.group(0) == value: try: got = self.__get_field_value(exact_match.group(1), saw, original) return got ...
KeyError
dataset/ETHPy150Open spinnaker/spinnaker/pylib/spinnaker/yaml_util.py/YamlBindings.__resolve_value
5,728
def transform_yaml_source(self, source, key): """Transform the given yaml source so its value of key matches the binding. Has no effect if key is not among the bindings. But raises a KeyError if it is in the bindings but not in the source. Args: source [string]: A YAML document key [string...
KeyError
dataset/ETHPy150Open spinnaker/spinnaker/pylib/spinnaker/yaml_util.py/YamlBindings.transform_yaml_source
5,729
def _get_ri_id_of_network(self, oc_client, network_id): try: network = oc_client.show('Virtual Network', network_id) ri_fq_name = network['fq_name'] + [network['fq_name'][-1]] for ri_ref in network.get('routing_instances', []): if ri_ref['to'] == ri_fq_name: ...
IndexError
dataset/ETHPy150Open openstack/networking-bgpvpn/networking_bgpvpn/neutron/services/service_drivers/opencontrail/opencontrail.py/OpenContrailBGPVPNDriver._get_ri_id_of_network
5,730
def get_bgpvpns(self, context, filters=None, fields=None): LOG.debug("get_bgpvpns called, fields = %s, filters = %s" % (fields, filters)) oc_client = self._get_opencontrail_api_client(context) bgpvpns = [] for kv_dict in oc_client.kv_store('RETRIEVE'): try...
ValueError
dataset/ETHPy150Open openstack/networking-bgpvpn/networking_bgpvpn/neutron/services/service_drivers/opencontrail/opencontrail.py/OpenContrailBGPVPNDriver.get_bgpvpns
5,731
def _clean_bgpvpn_assoc(self, oc_client, bgpvpn_id): for kv_dict in oc_client.kv_store('RETRIEVE'): try: value = json.loads(kv_dict['value']) except __HOLE__: continue if (isinstance(value, dict) and 'bgpvpn_net_assoc' in va...
ValueError
dataset/ETHPy150Open openstack/networking-bgpvpn/networking_bgpvpn/neutron/services/service_drivers/opencontrail/opencontrail.py/OpenContrailBGPVPNDriver._clean_bgpvpn_assoc
5,732
def get_bgpvpn(self, context, id, fields=None): LOG.debug("get_bgpvpn called for id %s with fields = %s" % (id, fields)) oc_client = self._get_opencontrail_api_client(context) try: bgpvpn = json.loads(oc_client.kv_store('RETRIEVE', key=id)) except (oc_exc....
ValueError
dataset/ETHPy150Open openstack/networking-bgpvpn/networking_bgpvpn/neutron/services/service_drivers/opencontrail/opencontrail.py/OpenContrailBGPVPNDriver.get_bgpvpn
5,733
def get_net_assoc(self, context, assoc_id, bgpvpn_id, fields=None): LOG.debug("get_net_assoc called for %s for BGPVPN %s, with fields = %s" % (assoc_id, bgpvpn_id, fields)) oc_client = self._get_opencontrail_api_client(context) try: net_assoc = json.loads( ...
ValueError
dataset/ETHPy150Open openstack/networking-bgpvpn/networking_bgpvpn/neutron/services/service_drivers/opencontrail/opencontrail.py/OpenContrailBGPVPNDriver.get_net_assoc
5,734
def get_net_assocs(self, context, bgpvpn_id, filters=None, fields=None): LOG.debug("get_net_assocs called for bgpvpn %s, fields = %s, " "filters = %s" % (bgpvpn_id, fields, filters)) oc_client = self._get_opencontrail_api_client(context) get_fields = ['tenant_id', 'route_targ...
ValueError
dataset/ETHPy150Open openstack/networking-bgpvpn/networking_bgpvpn/neutron/services/service_drivers/opencontrail/opencontrail.py/OpenContrailBGPVPNDriver.get_net_assocs
5,735
def update_row(self, row_data): """Update Row (By ID). Only the fields supplied will be updated. :param row_data: A dictionary containing row data. The row will be updated according to the value in the ID_FIELD. :return: The updated row. """ ...
KeyError
dataset/ETHPy150Open yoavaviram/python-google-spreadsheet/google_spreadsheet/api.py/Worksheet.update_row
5,736
def delete_row(self, row): """Delete Row (By ID). Requires that the given row dictionary contains an ID_FIELD. :param row: A row dictionary to delete. """ try: id = row[ID_FIELD] except __HOLE__: raise WorksheetException("Row does not ...
KeyError
dataset/ETHPy150Open yoavaviram/python-google-spreadsheet/google_spreadsheet/api.py/Worksheet.delete_row
5,737
def render(self, name, value, attrs=None): # Update the template parameters with any attributes passed in. if attrs: self.params.update(attrs) # Defaulting the WKT value to a blank string -- this # will be tested in the JavaScript and the appropriate # interfaace will be constru...
ValueError
dataset/ETHPy150Open dcramer/django-compositepks/django/contrib/gis/admin/widgets.py/OpenLayersWidget.render
5,738
def form_valid(self, form): """ Store new flatpage from form data. Checks wether a site is specified for the flatpage or sets the current site by default. Additionally, if URL is left blank, a slugified version of the title will be used as URL after checking if it is vali...
ValidationError
dataset/ETHPy150Open django-oscar/django-oscar/src/oscar/apps/dashboard/pages/views.py/PageCreateView.form_valid
5,739
def post(self, request, *args, **kwargs): content = request.POST.get('content', '') markup = request.POST.get('markup') reader = get_reader(markup=markup) content_body, metadata = reader(content).read() image_id = metadata.get('image', '') try: image_url = Ent...
ValueError
dataset/ETHPy150Open gkmngrgn/radpress/radpress/views.py/PreviewView.post
5,740
def list_get(list_obj, index, default=None): """Like ``.get`` for list object. Args: list_obj (list): list to look up an index in index (int): index position to look up default (Optional[object]): default return value. Defaults to None. Returns: object: any object found at ...
IndexError
dataset/ETHPy150Open robinandeer/chanjo/chanjo/utils.py/list_get
5,741
def merge_collections_for_profile(): from totalimpact import item, tiredis view_name = "queues/by_type_and_id" view_rows = db.view(view_name, include_docs=True) row_count = 0 sql_statement_count = 0 page_size = 500 start_key = ["user", "00000000000"] end_key = ["user", "zzzzzzzzz"] ...
KeyError
dataset/ETHPy150Open Impactstory/total-impact-core/extras/db_housekeeping/migrate_user_docs.py/merge_collections_for_profile
5,742
def get_GenericForeignKey(): try: from django.contrib.contenttypes.fields import GenericForeignKey # For Django 1.6 and earlier except __HOLE__: from django.contrib.contenttypes.generic import GenericForeignKey return GenericForeignKey
ImportError
dataset/ETHPy150Open gregmuellegger/django-autofixture/autofixture/compat.py/get_GenericForeignKey
5,743
def get_GenericRelation(): try: from django.contrib.contenttypes.fields import GenericRelation # For Django 1.6 and earlier except __HOLE__: from django.contrib.contenttypes.generic import GenericRelation return GenericRelation
ImportError
dataset/ETHPy150Open gregmuellegger/django-autofixture/autofixture/compat.py/get_GenericRelation
5,744
def gunzip(data): """Gunzip the given data and return as much data as possible. This is resilient to CRC checksum errors. """ f = GzipFile(fileobj=BytesIO(data)) output = b'' chunk = b'.' while chunk: try: chunk = read1(f, 8196) output += chunk except...
IOError
dataset/ETHPy150Open scrapy/scrapy/scrapy/utils/gz.py/gunzip
5,745
def to_python(self, value): """Converts the DB-stored value into a Python value.""" if isinstance(value, base.StateWrapper): res = value else: if isinstance(value, base.State): state = value elif value is None: state = self.work...
KeyError
dataset/ETHPy150Open rbarrois/django_xworkflows/django_xworkflows/models.py/StateField.to_python
5,746
def testPasswordProtectedSite(self): support.requires('network') with support.transient_internet('mueblesmoraleda.com'): url = 'http://mueblesmoraleda.com' robots_url = url + "/robots.txt" # First check the URL is usable for our purposes, since the # test ...
HTTPError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_robotparser.py/NetworkTestCase.testPasswordProtectedSite
5,747
@register.filter(name="lookup") def lookup_filter(o, key): try: return o[key] except __HOLE__: return None
KeyError
dataset/ETHPy150Open timvideos/streaming-system/website/tracker/templatetags/lookup.py/lookup_filter
5,748
@main.command() @argument('source', required=False) @argument('destination', required=False) @option('-f', '--force', is_flag=True, help="Force the reprocessing of existing images") @option('-v', '--verbose', is_flag=True, help="Show all messages") @option('-d', '--debug', is_flag=True, help="Show all m...
ValueError
dataset/ETHPy150Open saimn/sigal/sigal/__init__.py/build
5,749
@main.command() @argument('destination', default='_build') @option('-p', '--port', help="Port to use", default=8000) @option('-c', '--config', default=_DEFAULT_CONFIG_FILE, show_default=True, help='Configuration file') def serve(destination, port, config): """Run a simple web server.""" if os.path.exist...
KeyboardInterrupt
dataset/ETHPy150Open saimn/sigal/sigal/__init__.py/serve
5,750
def discover_methods(iface): sniffers = [] for port in listening_ports(): sniff = discover_on_port(port, iface, MsgHandler(port)) sniffers.append(sniff) # done when all sniffers are done (or the user gets tired) try: while True: if all(not sniff.isAlive() for sniff i...
KeyboardInterrupt
dataset/ETHPy150Open pinterest/thrift-tools/examples/methods_per_port.py/discover_methods
5,751
def lookup_cik(ticker, name=None): # Given a ticker symbol, retrieves the CIK. good_read = False ticker = ticker.strip().upper() url = 'http://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK={cik}&count=10&output=xml'.format(cik=ticker) try: xmlFile = urlopen( url ) try: xmlData = xmlFile.read() ...
HTTPError
dataset/ETHPy150Open altova/sec-xbrl/valSECfilings.py/lookup_cik
5,752
def release_resources(self, article): path = os.path.join(self.config.local_storage_path, '%s_*' % article.link_hash) for fname in glob.glob(path): try: os.remove(fname) except __HOLE__: # TODO better log handeling pass
OSError
dataset/ETHPy150Open xiaoxu193/PyTeaser/goose/crawler.py/Crawler.release_resources
5,753
def calculate(self, cart, contact): """ Based on the chosen UPS method, we will do our call to UPS and see how much it will cost. We will also need to store the results for further parsing and return via the methods above """ from satchmo_store.shop.models import ...
AttributeError
dataset/ETHPy150Open dokterbob/satchmo/satchmo/apps/shipping/modules/ups/shipper.py/Shipper.calculate
5,754
def cmd(self, _func=_NO_FUNC, name=None, *args, **kwargs): """Decorator to create a command line subcommand for a function. By default, the name of the decorated function is used as the name of the subcommand, but this can be overridden by specifying the `name` argument. Additional argu...
KeyError
dataset/ETHPy150Open splunk/splunk-webframework/contrib/aaargh/aaargh.py/App.cmd
5,755
def validate_number(self, number): "Validates the given 1-based page number." try: number = int(number) except (__HOLE__, ValueError): raise PageNotAnInteger('That page number is not an integer') if number < 1: raise EmptyPage('That page number is less...
TypeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/core/paginator.py/Paginator.validate_number
5,756
def _get_count(self): "Returns the total number of objects, across all pages." if self._count is None: try: self._count = self.object_list.count() except (__HOLE__, TypeError): # AttributeError if object_list has no count() method. ...
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/core/paginator.py/Paginator._get_count
5,757
def __iter__(self): i = 0 try: while True: v = self[i] yield v i += 1 except __HOLE__: return
IndexError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/core/paginator.py/Page.__iter__
5,758
@classmethod def relpath(cls, path, start): """Wrapper for os.path.relpath for Python 2.4. Python 2.4 doesn't have the os.path.relpath function, so this approximates it well enough for our needs. ntpath.relpath() overflows and throws TypeError for paths containing atleast 5...
AttributeError
dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/scmtools/clearcase.py/ClearCaseTool.relpath
5,759
def client_relpath(self, filename): """Normalize any path sent from client view and return relative path against vobtag """ try: path, revision = filename.split("@@", 1) except __HOLE__: path = filename revision = None relpath = "" ...
ValueError
dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/scmtools/clearcase.py/ClearCaseDiffParser.client_relpath
5,760
def test_log(self): b = wspbus.Bus() self.log(b) self.assertLog([]) # Try a normal message. expected = [] for msg in ["O mah darlin'"] * 3 + ["Clementiiiiiiiine"]: b.log(msg) expected.append(msg) self.assertLog(expected) # Try...
NameError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/cherrypy/cherrypy/test/test_bus.py/BusMethodTests.test_log
5,761
def to_pydot(N, strict=True): """Return a pydot graph from a NetworkX graph N. Parameters ---------- N : NetworkX graph A graph created with NetworkX Examples -------- >>> import networkx as nx >>> K5 = nx.complete_graph(5) >>> P = nx.to_pydot(K5) Notes ----- "...
KeyError
dataset/ETHPy150Open openstack/fuel-web/nailgun/nailgun/orchestrator/graph_visualization.py/to_pydot
5,762
def test_module_import(self): """ Import base functionality. """ try: from split_settings import __version__ as _version from split_settings.tools import include as _include from split_settings.tools import optional as _optional self._assert_types(_versio...
ImportError
dataset/ETHPy150Open sobolevn/django-split-settings/example/tests/test_import.py/TestModuleImport.test_module_import
5,763
def test_wildcard_import(self): """ Imports all from all modules """ try: self._assert_types(__version__, include, optional) except __HOLE__ as import_error: self.fail(msg=import_error)
ImportError
dataset/ETHPy150Open sobolevn/django-split-settings/example/tests/test_import.py/TestModuleImport.test_wildcard_import
5,764
def run_mainloop_with(self, target): """Start the OS's main loop to process asyncronous BLE events and then run the specified target function in a background thread. Target function should be a function that takes no parameters and optionally return an integer response code. When the t...
KeyboardInterrupt
dataset/ETHPy150Open adafruit/Adafruit_Python_BluefruitLE/Adafruit_BluefruitLE/corebluetooth/provider.py/CoreBluetoothProvider.run_mainloop_with
5,765
def next_source_row(self, handle): """ Given a file handle, return the next row of data as a key value dict. Return None to denote the EOF Return False to skip this row of data entirely """ if not getattr(self, "detected_dialect", None): # Sniff for the dial...
StopIteration
dataset/ETHPy150Open potatolondon/osmosis/osmosis/models.py/AbstractImportTask.next_source_row
5,766
def process(self): meta = self.task.get_meta() task_model = get_model(*self.task.model_path.split(".")) this = ImportShard.objects.get(pk=self.pk) # Reload, self is pickled source_data = json.loads(this.source_data_json) # If there are no rows to process mark_shard_com...
ValidationError
dataset/ETHPy150Open potatolondon/osmosis/osmosis/models.py/ImportShard.process
5,767
def import_idmap(idmapdb, samba3, logger): """Import idmap data. :param idmapdb: Samba4 IDMAP database :param samba3_idmap: Samba3 IDMAP database to import from :param logger: Logger object """ try: samba3_idmap = samba3.get_idmap_db() except __HOLE__, e: logger.warn('Canno...
IOError
dataset/ETHPy150Open byt3bl33d3r/pth-toolkit/lib/python2.7/site-packages/samba/upgrade.py/import_idmap
5,768
def upgrade_from_samba3(samba3, logger, targetdir, session_info=None, useeadb=False, dns_backend=None, use_ntvfs=False): """Upgrade from samba3 database to samba4 AD database :param samba3: samba3 object :param logger: Logger object :param targetdir: samba4 database directory :param session...
KeyError
dataset/ETHPy150Open byt3bl33d3r/pth-toolkit/lib/python2.7/site-packages/samba/upgrade.py/upgrade_from_samba3
5,769
def main(): try: ascii_art = """\ ____ _ _ _ | _ \ | | | | | | | |_) | __ _ ___| |__ | |__ _ _| |__ ___ ___ _ __ ___ | _ < / _` / __| '_ \| '_ \| | | | '_ \ / __/ _ \| '_ ` _ \\ | |_) | (_| \__ \ | | | | | | ...
KeyboardInterrupt
dataset/ETHPy150Open rcaloras/bashhub-client/bashhub/bashhub_setup.py/main
5,770
def test_nonexistent(self): 'Test trying to use a genome with no Ensembl data at UCSC' badname = 'Nonexistent.Fake.Bogus' try: badiface = UCSCEnsemblInterface(badname) except __HOLE__: return raise ValueError("Bad sequence name %s has failed to return an e...
KeyError
dataset/ETHPy150Open cjlee112/pygr/tests/apps_ucscensembl_test.py/UCSCEnsembl_Test.test_nonexistent
5,771
def main(): """ Script main, parses arguments and invokes Dummy.setup indirectly. """ parser = ArgumentParser(description='Utility to read setup.py values from cmake macros. Creates a file with CMake set commands setting variables.') parser.add_argument('package_name', help='Name of catkin package')...
NameError
dataset/ETHPy150Open ros/catkin/cmake/interrogate_setup_dot_py.py/main
5,772
def _mathfun_real(f_real, f_complex): def f(x, **kwargs): if type(x) is float: return f_real(x) if type(x) is complex: return f_complex(x) try: x = float(x) return f_real(x) except (TypeError, __HOLE__): x = complex(x) ...
ValueError
dataset/ETHPy150Open fredrik-johansson/mpmath/mpmath/math2.py/_mathfun_real
5,773
def _mathfun(f_real, f_complex): def f(x, **kwargs): if type(x) is complex: return f_complex(x) try: return f_real(float(x)) except (TypeError, __HOLE__): return f_complex(complex(x)) f.__name__ = f_real.__name__ return f
ValueError
dataset/ETHPy150Open fredrik-johansson/mpmath/mpmath/math2.py/_mathfun
5,774
def _mathfun_n(f_real, f_complex): def f(*args, **kwargs): try: return f_real(*(float(x) for x in args)) except (TypeError, __HOLE__): return f_complex(*(complex(x) for x in args)) f.__name__ = f_real.__name__ return f # Workaround for non-raising log and sqrt in Pyt...
ValueError
dataset/ETHPy150Open fredrik-johansson/mpmath/mpmath/math2.py/_mathfun_n
5,775
def nthroot(x, n): r = 1./n try: return float(x) ** r except (ValueError, __HOLE__): return complex(x) ** r
TypeError
dataset/ETHPy150Open fredrik-johansson/mpmath/mpmath/math2.py/nthroot
5,776
def loggamma(x): if type(x) not in (float, complex): try: x = float(x) except (ValueError, TypeError): x = complex(x) try: xreal = x.real ximag = x.imag except AttributeError: # py2.5 xreal = x ximag = 0.0 # Reflection formula ...
AttributeError
dataset/ETHPy150Open fredrik-johansson/mpmath/mpmath/math2.py/loggamma
5,777
def ei(z, _e1=False): typez = type(z) if typez not in (float, complex): try: z = float(z) typez = float except (TypeError, __HOLE__): z = complex(z) typez = complex if not z: return -INF absz = abs(z) if absz > EI_ASYMP_CONVERGE...
ValueError
dataset/ETHPy150Open fredrik-johansson/mpmath/mpmath/math2.py/ei
5,778
def e1(z): # hack to get consistent signs if the imaginary part if 0 # and signed typez = type(z) if type(z) not in (float, complex): try: z = float(z) typez = float except (TypeError, __HOLE__): z = complex(z) typez = complex if typez ...
ValueError
dataset/ETHPy150Open fredrik-johansson/mpmath/mpmath/math2.py/e1
5,779
def zeta(s): """ Riemann zeta function, real argument """ if not isinstance(s, (float, int)): try: s = float(s) except (__HOLE__, TypeError): try: s = complex(s) if not s.imag: return complex(zeta(s.real)) ...
ValueError
dataset/ETHPy150Open fredrik-johansson/mpmath/mpmath/math2.py/zeta
5,780
def _get_addons(request, addons, addon_id, action): """Create a list of ``MenuItem``s for the activity feed.""" items = [] a = MenuItem() a.selected = (not addon_id) (a.text, a.url) = (_('All My Add-ons'), reverse('devhub.feed_all')) if action: a.url += '?action=' + action items.app...
ValueError
dataset/ETHPy150Open mozilla/addons-server/src/olympia/devhub/views.py/_get_addons
5,781
@dev_required @submit_step(7) def submit_done(request, addon_id, addon, step): # Bounce to the versions page if they don't have any versions. if not addon.versions.exists(): return redirect(addon.get_dev_url('versions')) sp = addon.current_version.supported_platforms is_platform_specific = sp !=...
IndexError
dataset/ETHPy150Open mozilla/addons-server/src/olympia/devhub/views.py/submit_done
5,782
def update_badges(overwrite=False): from django.utils.importlib import import_module for app in settings.INSTALLED_APPS: mod = import_module(app) try: badges_mod = import_module('%s.badges' % app) fixture_label = '%s_badges' % app.replace('.','_') call_comman...
ImportError
dataset/ETHPy150Open mozilla/django-badger/badger/management/__init__.py/update_badges
5,783
def parseStreamPacket(self): try: packet = mirror.Packet.Packet(self.rfile) except __HOLE__: return self.closeConnection() # TODO: Really? except EOFError: return self.closeConnection() except socket.timeout, e: self.log_error("Request timed out: %r", e) return self.closeConnection() self.handl...
IOError
dataset/ETHPy150Open tzwenn/PyOpenAirMirror/mirror/service.py/MirrorService.parseStreamPacket
5,784
def user_data(self, access_token, *args, **kwargs): """Loads user data from service""" data = self._user_data(access_token) if not data.get('email'): try: emails = self._user_data(access_token, '/emails') except (HTTPError, __HOLE__, TypeError): ...
ValueError
dataset/ETHPy150Open omab/python-social-auth/social/backends/github.py/GithubOAuth2.user_data
5,785
def user_data(self, access_token, *args, **kwargs): """Loads user data from service""" user_data = super(GithubMemberOAuth2, self).user_data( access_token, *args, **kwargs ) try: self.request(self.member_url(user_data), params={ 'access_token': acc...
HTTPError
dataset/ETHPy150Open omab/python-social-auth/social/backends/github.py/GithubMemberOAuth2.user_data
5,786
def definition_to_api_objects(definition): if 'objects' not in definition: raise PipelineDefinitionError('Missing "objects" key', definition) api_elements = [] # To convert to the structure expected by the service, # we convert the existing structure to a list of dictionaries. # Each diction...
KeyError
dataset/ETHPy150Open aws/aws-cli/awscli/customizations/datapipeline/translator.py/definition_to_api_objects
5,787
def definition_to_api_parameters(definition): if 'parameters' not in definition: return None parameter_objects = [] for element in definition['parameters']: try: parameter_id = element.pop('id') except __HOLE__: raise PipelineDefinitionError('Missing "id" key ...
KeyError
dataset/ETHPy150Open aws/aws-cli/awscli/customizations/datapipeline/translator.py/definition_to_api_parameters
5,788
def warmup(request): """ Provides default procedure for handling warmup requests on App Engine. Just add this view to your main urls.py. """ for app in settings.INSTALLED_APPS: for name in ('urls', 'views', 'models'): try: import_module('%s.%s' % (app, name)) ...
ImportError
dataset/ETHPy150Open adieu/djangoappengine/views.py/warmup
5,789
def clean_doi(input_doi): input_doi = remove_nonprinting_characters(input_doi) try: input_doi = input_doi.lower() if input_doi.startswith("http"): match = re.match("^https*://(dx\.)*doi.org/(10\..+)", input_doi) doi = match.group(2) elif "doi.org" in input_doi: ...
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-core/totalimpact/providers/crossref.py/clean_doi
5,790
def _lookup_issn_from_doi(self, id, url, cache_enabled): # try to get a response from the data provider response = self.http_get(url, cache_enabled=cache_enabled, allow_redirects=True, headers={"Accept": "application/json", "User-Agent": "impactstory.org"}) ...
TypeError
dataset/ETHPy150Open Impactstory/total-impact-core/totalimpact/providers/crossref.py/Crossref._lookup_issn_from_doi
5,791
def _lookup_biblio_from_doi(self, id, url, cache_enabled): # try to get a response from the data provider response = self.http_get(url, cache_enabled=cache_enabled, allow_redirects=True, headers={"Accept": "application/vnd.citationstyles.csl+json", "User-Age...
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-core/totalimpact/providers/crossref.py/Crossref._lookup_biblio_from_doi
5,792
def _extract_biblio(self, page, id=None): dict_of_keylists = { 'title' : ['title'], 'year' : ['issued'], 'repository' : ['publisher'], 'journal' : ['container-title'], 'authors_literal' : ['author'] } biblio_dict = provider._extract_fro...
IndexError
dataset/ETHPy150Open Impactstory/total-impact-core/totalimpact/providers/crossref.py/Crossref._extract_biblio
5,793
def _lookup_doi_from_biblio(self, biblio, cache_enabled): if not biblio: return [] try: if (biblio["journal"] == ""): # need to have journal or can't look up with current api call logger.info(u"%20s /biblio_print NO DOI because no journal in %s" %...
KeyError
dataset/ETHPy150Open Impactstory/total-impact-core/totalimpact/providers/crossref.py/Crossref._lookup_doi_from_biblio
5,794
def _lookup_urls_from_doi(self, doi, provider_url_template=None, cache_enabled=True): self.logger.debug(u"%s getting aliases for %s" % (self.provider_name, doi)) if not provider_url_template: provider_url_template = self.aliases_url_template #...
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-core/totalimpact/providers/crossref.py/Crossref._lookup_urls_from_doi
5,795
def parse(self, parse_until=None): if parse_until is None: parse_until = [] nodelist = self.create_nodelist() while self.tokens: token = self.next_token() # We only need to parse var and block tokens. if token.token_type == TOKEN_VAR: if not token.contents: self.empty_variable(token) ...
IndexError
dataset/ETHPy150Open ithinksw/philo/philo/validators.py/TemplateValidationParser.parse
5,796
def __call__(self, value): try: self.validate_template(value) except __HOLE__: raise except Exception, e: if hasattr(e, 'source') and isinstance(e, TemplateSyntaxError): origin, (start, end) = e.source template_source = origin.reload() upto = 0 for num, next in enumerate(linebreak_iter(te...
ValidationError
dataset/ETHPy150Open ithinksw/philo/philo/validators.py/TemplateValidator.__call__
5,797
def visualize(self, filename=None, tables_to_show=None): """Visualize databases and create an er-diagram Args: filename(str): filepath for saving the er-diagram tables_to_show(list): A list of tables to actually visualize. Tables not included in this list will no...
ImportError
dataset/ETHPy150Open coursera/dataduct/dataduct/database/database.py/Database.visualize
5,798
def get_datetime_now(): """ Returns datetime object with current point in time. In Django 1.4+ it uses Django's django.utils.timezone.now() which returns an aware or naive datetime that represents the current point in time when ``USE_TZ`` in project's settings is True or False respectively. In ...
ImportError
dataset/ETHPy150Open clione/django-kanban/src/core/userena/utils.py/get_datetime_now
5,799
def is_date(string): """ Check if input string is date-formatted. :param string: Input date :type string: ``str`` :rtype: ``bool`` """ try: dateutil.parser.parse(string) return True except __HOLE__: return False
ValueError
dataset/ETHPy150Open StackStorm/st2contrib/packs/trello/sensors/list_actions_sensor.py/is_date