Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
2,800
def _run_validators(self, value): """ Execute all associated validators. """ errors = [] for v in self.validators: try: v(value) except __HOLE__, e: errors.extend(e.messages) if errors: raise ValidationError(errors)
ValidationError
dataset/ETHPy150Open wuher/devil/devil/fields/fields.py/NestedField._run_validators
2,801
@classmethod def setupClass(cls): global np try: import numpy as np import scipy except __HOLE__: raise SkipTest('SciPy not available.')
ImportError
dataset/ETHPy150Open networkx/networkx/networkx/algorithms/centrality/tests/test_eigenvector_centrality.py/TestEigenvectorCentrality.setupClass
2,802
@classmethod def setupClass(cls): global np try: import numpy as np import scipy except __HOLE__: raise SkipTest('SciPy not available.')
ImportError
dataset/ETHPy150Open networkx/networkx/networkx/algorithms/centrality/tests/test_eigenvector_centrality.py/TestEigenvectorCentralityDirected.setupClass
2,803
@classmethod def setupClass(cls): global np try: import numpy as np import scipy except __HOLE__: raise SkipTest('SciPy not available.')
ImportError
dataset/ETHPy150Open networkx/networkx/networkx/algorithms/centrality/tests/test_eigenvector_centrality.py/TestEigenvectorCentralityExceptions.setupClass
2,804
def _run_tests(self): secrets = pjoin(self._dir, 'test', 'secrets.py') if not os.path.isfile(secrets): print("Missing " + secrets) print("Maybe you forgot to copy it from -dist:") print(" cp test/secrets.py-dist test/secrets.py") sys.exit(1) pre_...
ImportError
dataset/ETHPy150Open racker/rackspace-monitoring/setup.py/TestCommand._run_tests
2,805
def run(self): try: import pep8 pep8 except __HOLE__: print ('Missing "pep8" library. You can install it using pip: ' 'pip install pep8') sys.exit(1) cwd = os.getcwd() retcode = call(('pep8 %s/rackspace_monitoring/ %s/tes...
ImportError
dataset/ETHPy150Open racker/rackspace-monitoring/setup.py/Pep8Command.run
2,806
def get_auth_from_conf(here): transifex_conf = os.path.join(here, '.transifex.ini') config = ConfigParser() try: with open(transifex_conf, 'r') as conf: config.readfp(conf) except __HOLE__ as ex: sys.exit('Failed to load authentication configuration file.\n' ...
IOError
dataset/ETHPy150Open mblayman/tappy/transifex.py/get_auth_from_conf
2,807
def GetGeneratorByLanguage(language_or_generator): """Return the appropriate generator for this language. Args: language_or_generator: (str) the language for which to return a generator, or the name of a specific generator. Raises: ValueError: If provided language isn't supported. Returns: ...
KeyError
dataset/ETHPy150Open google/apis-client-generator/src/googleapis/codegen/generator_lookup.py/GetGeneratorByLanguage
2,808
def parse(self, fileData=None, context=None): self.reset() if context is not None: self.context = context if fileData is not None: self.filedata = fileData for index, line in enumerate(self.filedata): line = line.strip() # Use 1-indexed l...
ValueError
dataset/ETHPy150Open sassoftware/conary/conary/conaryclient/cml.py/CML.parse
2,809
def run(self): # verify that given states are subset of allowed states unknown_states = set(self.send_on) - self.allowed_states if len(unknown_states) > 0: raise PluginFailedException('Unknown state(s) "%s" for sendmail plugin' % '", "'.join(so...
RuntimeError
dataset/ETHPy150Open projectatomic/atomic-reactor/atomic_reactor/plugins/exit_sendmail.py/SendMailPlugin.run
2,810
def __init__(self, parent, menu, item, controller): """ Creates a new menu item for an action item. """ self.item = item action = item.action # FIXME v3: This is a wx'ism and should be hidden in the toolkit code. self.control_id = None if action.image is None: ...
AttributeError
dataset/ETHPy150Open enthought/pyface/pyface/ui/qt4/action/action_item.py/_MenuItem.__init__
2,811
def __init__(self, parent, tool_bar, image_cache, item, controller, show_labels): """ Creates a new tool bar tool for an action item. """ self.item = item self.tool_bar = tool_bar action = item.action # FIXME v3: This is a wx'ism and should be hidden in the too...
AttributeError
dataset/ETHPy150Open enthought/pyface/pyface/ui/qt4/action/action_item.py/_Tool.__init__
2,812
@testhelp.context('trove-filter') def testBadTroveFilters(self): recipe = self.getRecipe() filt = trovefilter.AbstractFilter() self.assertRaises(NotImplementedError, filt.match) try: filt = trovefilter.TroveFilter(recipe, 'foo(') except __HOLE__, e: s...
RuntimeError
dataset/ETHPy150Open sassoftware/conary/conary_test/cvctest/buildtest/expansiontest.py/TroveFilterTest.testBadTroveFilters
2,813
def take_action(self, parsed_args): compute_client = self.app.client_manager.compute volume_client = self.app.client_manager.volume # Lookup parsed_args.image image = None if parsed_args.image: image = utils.find_resource( compute_client.images, ...
IOError
dataset/ETHPy150Open dtroyer/python-openstackclient/openstackclient/compute/v2/server.py/CreateServer.take_action
2,814
def load_state(name): global users, pending_users users = set() pending_users = set() try: loaded = yaml.load(open(name)) users = set(loaded['users']) pending_users = set(loaded['pending_users']) except __HOLE__: logger.warning('Could not load state, continuing.')
IOError
dataset/ETHPy150Open ebroder/anygit/anygit/client/spider.py/load_state
2,815
def github_com_spider(): state_file ='state.yml' load_state(state_file) if not pending_users: user = raw_input('Please enter in a GitHub user to bootstrap from: ').strip() pending_users.add(user) setup_proxies() while True: try: user = pending_users.pop() ...
KeyError
dataset/ETHPy150Open ebroder/anygit/anygit/client/spider.py/github_com_spider
2,816
def get_svn_revision(path=None): """ Returns the SVN revision in the form SVN-XXXX, where XXXX is the revision number. Returns SVN-unknown if anything goes wrong, such as an unexpected format of internal SVN files. If path is provided, it should be a directory whose SVN info you want to in...
IOError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/utils/version.py/get_svn_revision
2,817
def _from_json(self, datastring): try: return jsonutils.loads(datastring) except __HOLE__: msg = _("Cannot understand JSON") raise exception.MalformedResponseBody(reason=msg)
ValueError
dataset/ETHPy150Open openstack/python-neutronclient/neutronclient/common/serializer.py/JSONDeserializer._from_json
2,818
def prep_arg(arg): try: return float(arg) except __HOLE__: try: return int(arg) except ValueError: return arg
ValueError
dataset/ETHPy150Open ejeschke/ginga/ginga/util/grc.py/prep_arg
2,819
def isfloat(x): """ Check if argument is float """ try: a = float(x) except __HOLE__: return False else: return True
ValueError
dataset/ETHPy150Open tyiannak/pyAudioAnalysis/utilities.py/isfloat
2,820
def isint(x): """ Check if argument is int """ try: a = float(x) b = int(a) except __HOLE__: return False else: return a == b
ValueError
dataset/ETHPy150Open tyiannak/pyAudioAnalysis/utilities.py/isint
2,821
@classmethod def http(cls, status_code, msg="", err_list=None, headers=None): """Raise an HTTP status code. Useful for returning status codes like 401 Unauthorized or 403 Forbidden. :param status_code: the HTTP status code as an integer :param msg: the message to send along...
TypeError
dataset/ETHPy150Open openstack/fuel-web/nailgun/nailgun/api/v1/handlers/base.py/BaseHandler.http
2,822
@content def PUT(self, cluster_id): """:returns: JSONized Task object. :http: * 202 (task successfully executed) * 400 (invalid object data specified) * 404 (environment is not found) * 409 (task with such parameters already exists) """ c...
ValueError
dataset/ETHPy150Open openstack/fuel-web/nailgun/nailgun/api/v1/handlers/base.py/DeferredTaskHandler.PUT
2,823
def _build_custom_contracts(): """ Define some custom contracts if PyContracts is found """ from contracts import new_contract @new_contract def cid_like(value): """ Value is a ComponentID or a string """ from glue.core import ComponentID return isinstanc...
ValueError
dataset/ETHPy150Open glue-viz/glue/glue/core/contracts.py/_build_custom_contracts
2,824
def evaluate(ex, out=None, local_dict=None, global_dict=None, **kwargs): """Evaluate expression and return an array.""" # First, get the signature for the arrays in expression context = getContext(kwargs) names, _ = getExprNames(ex, context) # Get the arguments based on the names. call_frame =...
KeyError
dataset/ETHPy150Open PyTables/PyTables/bench/evaluate.py/evaluate
2,825
def __contains__(self, vertex): try: vals = [f['val'] for f in self.vertices.values()] except __HOLE__: vals = [] return vertex in self.vertices or vertex in vals
KeyError
dataset/ETHPy150Open christabor/MoAL/MOAL/data_structures/graphs/graphs.py/Graph.__contains__
2,826
def degree(self, vertex): """Return the number of edges for a given vertex. Only allows string/integer/tuple vertices.""" try: return len(self.vertices[vertex]['edges']) except __HOLE__: return 0
KeyError
dataset/ETHPy150Open christabor/MoAL/MOAL/data_structures/graphs/graphs.py/Graph.degree
2,827
def testInvalidSeek(self): """Tests that seeking fails for unsupported seek arguments.""" daisy_chain_wrapper = DaisyChainWrapper( self._dummy_url, self.test_data_file_len, self.MockDownloadCloudApi([])) try: # SEEK_CUR is invalid. daisy_chain_wrapper.seek(0, whence=os.SEEK_CUR) se...
IOError
dataset/ETHPy150Open GoogleCloudPlatform/gsutil/gslib/tests/test_daisy_chain_wrapper.py/TestDaisyChainWrapper.testInvalidSeek
2,828
def _test_transport_connectivity(self, direction, protocol, src_port, dst_port): nc_tester = self._create_nc_tester(direction, protocol, src_port, dst_port) try: nc_tester.test_connectivity() except __HOL...
RuntimeError
dataset/ETHPy150Open openstack/neutron/neutron/tests/common/conn_testers.py/ConnectionTester._test_transport_connectivity
2,829
def _test_icmp_connectivity(self, direction, protocol, src_port, dst_port): src_namespace, ip_address = self._get_namespace_and_address(direction) ip_version = ip_lib.get_ip_version(ip_address) icmp_timeout = ICMP_VERSION_TIMEOUTS[ip_version] try: net_helpers.assert_ping(src_...
RuntimeError
dataset/ETHPy150Open openstack/neutron/neutron/tests/common/conn_testers.py/ConnectionTester._test_icmp_connectivity
2,830
def _test_arp_connectivity(self, direction, protocol, src_port, dst_port): src_namespace, ip_address = self._get_namespace_and_address(direction) try: net_helpers.assert_arping(src_namespace, ip_address) except __HOLE__: raise ConnectionTesterException( "A...
RuntimeError
dataset/ETHPy150Open openstack/neutron/neutron/tests/common/conn_testers.py/ConnectionTester._test_arp_connectivity
2,831
@_validate_direction def assert_established_connection(self, direction, protocol, src_port=None, dst_port=None): nc_params = (direction, protocol, src_port, dst_port) nc_tester = self._nc_testers.get(nc_params) if nc_tester: if nc_tester.is_e...
RuntimeError
dataset/ETHPy150Open openstack/neutron/neutron/tests/common/conn_testers.py/ConnectionTester.assert_established_connection
2,832
def _get_pinger(self, direction): try: pinger = self._pingers[direction] except __HOLE__: src_namespace, dst_address = self._get_namespace_and_address( direction) pinger = net_helpers.Pinger(src_namespace, dst_address) self._pingers[directi...
KeyError
dataset/ETHPy150Open openstack/neutron/neutron/tests/common/conn_testers.py/ConnectionTester._get_pinger
2,833
def _pre_render(self): # split markup, words, and lines # result: list of word with position and width/height # during the first pass, we don't care about h/valign self._cached_lines = lines = [] self._refs = {} self._anchors = {} clipped = False w = h = 0...
ValueError
dataset/ETHPy150Open kivy/kivy/kivy/core/text/markup.py/MarkupLabel._pre_render
2,834
@phylip.sniffer() def _phylip_sniffer(fh): # Strategy: # Read the header and a single sequence; verify that the sequence length # matches the header information. Do not verify that the total number of # lines matches the header information, since that would require reading # the whole file....
StopIteration
dataset/ETHPy150Open biocore/scikit-bio/skbio/io/format/phylip.py/_phylip_sniffer
2,835
def _validate_header(header): header_vals = header.split() try: n_seqs, seq_len = [int(x) for x in header_vals] if n_seqs < 1 or seq_len < 1: raise PhylipFormatError( 'The number of sequences and the length must be positive.') except __HOLE__: raise Phylip...
ValueError
dataset/ETHPy150Open biocore/scikit-bio/skbio/io/format/phylip.py/_validate_header
2,836
def _parse_phylip_raw(fh): """Raw parser for PHYLIP files. Returns a list of raw (seq, id) values. It is the responsibility of the caller to construct the correct in-memory object to hold the data. """ # Note: this returns the full data instead of yielding each sequence, # because the header ...
StopIteration
dataset/ETHPy150Open biocore/scikit-bio/skbio/io/format/phylip.py/_parse_phylip_raw
2,837
def index(self, field): """Return index of a field""" try: index = self._field_names.index(unicode(field)) except __HOLE__: raise KeyError("Field list has no field with name '%s'" % unicode(field)) return index
ValueError
dataset/ETHPy150Open Stiivi/brewery/brewery/metadata.py/FieldList.index
2,838
def coalesce_value(value, storage_type, empty_values=None, strip=False): """Coalesces `value` to given storage `type`. `empty_values` is a dictionary where keys are storage type names and values are values to be used as empty value replacements.""" if empty_values is None: empty_values={} if...
ValueError
dataset/ETHPy150Open Stiivi/brewery/brewery/metadata.py/coalesce_value
2,839
def get_lock_pid(self): try: return int(open(self.lock_filename).read()) except __HOLE__: # If we can't read symbolic link, there are two possibilities: # 1. The symbolic link is dead (point to non existing file) # 2. Symbolic link is not there ...
IOError
dataset/ETHPy150Open ui/django-post_office/post_office/lockfile.py/FileLock.get_lock_pid
2,840
def valid_lock(self): """ See if the lock exists and is left over from an old process. """ lock_pid = self.get_lock_pid() # If we're unable to get lock_pid if lock_pid is None: return False # this is our process if self._pid == lock_pid: ...
OSError
dataset/ETHPy150Open ui/django-post_office/post_office/lockfile.py/FileLock.valid_lock
2,841
def release(self): """Try to delete the lock files. Doesn't matter if we fail""" if self.lock_filename != self.pid_filename: try: os.unlink(self.lock_filename) except OSError: pass try: os.remove(self.pid_filename) exce...
OSError
dataset/ETHPy150Open ui/django-post_office/post_office/lockfile.py/FileLock.release
2,842
def deserialize(self, source): """ Returns a model instance """ attrs = {} for k, v in source.iteritems(): try: attrs[k] = self.deserialize_field(source, k) except (__HOLE__, FieldDoesNotExist): # m2m, abstract ...
AttributeError
dataset/ETHPy150Open liberation/django-elasticsearch/django_elasticsearch/serializers.py/EsJsonToModelMixin.deserialize
2,843
def serialize_field(self, instance, field_name): method_name = 'serialize_{0}'.format(field_name) if hasattr(self, method_name): return getattr(self, method_name)(instance, field_name) try: field = self.model._meta.get_field(field_name) except FieldDoesNotExist: ...
AttributeError
dataset/ETHPy150Open liberation/django-elasticsearch/django_elasticsearch/serializers.py/EsModelToJsonMixin.serialize_field
2,844
@classmethod def setupClass(cls): global np try: import numpy as np except __HOLE__: raise SkipTest('NumPy not available.')
ImportError
dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/algorithms/centrality/tests/test_eigenvector_centrality.py/TestEigenvectorCentrality.setupClass
2,845
@classmethod def setupClass(cls): global np try: import numpy as np except __HOLE__: raise SkipTest('NumPy not available.')
ImportError
dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/algorithms/centrality/tests/test_eigenvector_centrality.py/TestEigenvectorCentralityDirected.setupClass
2,846
@classmethod def setupClass(cls): global np try: import numpy as np except __HOLE__: raise SkipTest('NumPy not available.')
ImportError
dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/algorithms/centrality/tests/test_eigenvector_centrality.py/TestEigenvectorCentralityExceptions.setupClass
2,847
def default_configure(host=None): """Configure BlueOx based on defaults Accepts a connection string override in the form `localhost:3514`. Respects environment variable BLUEOX_HOST """ host = ports.default_collect_host(host) hostname, port = host.split(':') try: int_port = int(port...
ValueError
dataset/ETHPy150Open rhettg/BlueOx/blueox/__init__.py/default_configure
2,848
def validate(output, resource): ''' Validate Pepa templates ''' try: import cerberus # pylint: disable=import-error except __HOLE__: log.critical('You need module cerberus in order to use validation') return roots = __opts__['pepa_roots'] valdir = join(roots['base'...
ImportError
dataset/ETHPy150Open saltstack/salt/salt/pillar/pepa.py/validate
2,849
def test_errors(self): size = 8 fmt = linuxaudiodev.AFMT_U8 rate = 8000 nchannels = 1 try: self.dev.setparameters(-1, size, nchannels, fmt) except ValueError, err: self.assertEqual(err.args[0], "expected rate >= 0, not -1") try: ...
ValueError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_linuxaudiodev.py/LinuxAudioDevTests.test_errors
2,850
def generate_stats(self, request, response): colors = contrasting_color_generator() trace_colors = defaultdict(lambda: next(colors)) query_duplicates = defaultdict(lambda: defaultdict(int)) if self._queries: width_ratio_tally = 0 factor = int(256.0 / (len(self._da...
KeyError
dataset/ETHPy150Open django-debug-toolbar/django-debug-toolbar/debug_toolbar/panels/sql/panel.py/SQLPanel.generate_stats
2,851
def main_cli(self, stdscr): # Block each getch() for 10 tenths of a second curses.halfdelay(10) # Visibility 0 is invisible curses.curs_set(0) try: while True: ps_str = self.get_ps_str() lines = ps_str.split('\n') max_...
KeyboardInterrupt
dataset/ETHPy150Open memsql/memsql-loader/memsql_loader/cli/ps.py/Processes.main_cli
2,852
def _make_progress(self, row, width): # formatted percent has a max length of 4 (100%) # _format_filesize can return at most a string of length 10 (1,024.0 KB) # _format_time can return at most a string of length 8 (23 hours) NO_PROGRESS_FORMAT_STR = "{:<4} {:>10}/{:<10}" PROGRES...
KeyError
dataset/ETHPy150Open memsql/memsql-loader/memsql_loader/cli/ps.py/Processes._make_progress
2,853
def _normalize_data(data, index): """normalize the data to a dict with tuples of strings as keys right now it works with: 0 - dictionary (or equivalent mappable) 1 - pandas.Series with simple or hierarchical indexes 2 - numpy.ndarrays 3 - everything that can be converted to a nu...
AttributeError
dataset/ETHPy150Open statsmodels/statsmodels/statsmodels/graphics/mosaicplot.py/_normalize_data
2,854
def require_dataset(handle, symbol): gid = symbol[:3] group = handle.require_group(gid) try: ds = group[symbol] except __HOLE__: ds = group.create_dataset(symbol, (240, ), DTYPE) return ds
KeyError
dataset/ETHPy150Open yinhm/datafeed/example/bench_dataset.py/require_dataset
2,855
def enter_filing(data_hash): filing_created=False related_committee = None try: thisobj = new_filing.objects.get(filing_number=data_hash['filing_number']) try: thisobj.filed_date except AttributeError: try: thisobj.filed_date...
KeyError
dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/fec_alerts/management/commands/scrape_rss_filings.py/enter_filing
2,856
def GenerateQueryUsingSession(self, criteria, target_id, for_stats=False): query = self.db.session.query(models.Transaction).filter_by( target_id=target_id) # If transaction search is being done if criteria.get('search', None): if criteria.get('url', None): ...
ValueError
dataset/ETHPy150Open owtf/owtf/framework/db/transaction_manager.py/TransactionManager.GenerateQueryUsingSession
2,857
def GetTransactionModel(self, transaction): try: response_body = transaction.GetRawResponseBody().encode("utf-8") binary_response = False except __HOLE__: response_body = base64.b64encode(transaction.GetRawResponseBody()) binary_response = True fin...
UnicodeDecodeError
dataset/ETHPy150Open owtf/owtf/framework/db/transaction_manager.py/TransactionManager.GetTransactionModel
2,858
def GetByID(self, ID): model_obj = None try: ID = int(ID) model_obj = self.db.session.query(models.Transaction).get(ID) except __HOLE__: pass finally: return(model_obj) # None returned if no such transaction.
ValueError
dataset/ETHPy150Open owtf/owtf/framework/db/transaction_manager.py/TransactionManager.GetByID
2,859
def find(self, only_visible=True, **kwargs): try: return self.__findcacheiter(only_visible, **kwargs).next() except __HOLE__: try: return self._finditer(only_visible, **kwargs).next() ...
StopIteration
dataset/ETHPy150Open F1ashhimself/UISoup/uisoup/win_soup/element.py/WinElement.find
2,860
def update_watchers(issue, created, comment=None): site = Site.objects.get(id=settings.SITE_ID) context = Context({'issue': issue, 'project': issue.project, 'site': site}) if comment: # issue commented context['comment'] = comment context['user_name'] = comment.user_name ...
ObjectDoesNotExist
dataset/ETHPy150Open f4nt/djtracker/djtracker/__init__.py/update_watchers
2,861
def scale_from_matrix(matrix): """Return scaling factor, origin and direction from scaling matrix. >>> factor = random.random() * 10 - 5 >>> origin = numpy.random.random(3) - 0.5 >>> direct = numpy.random.random(3) - 0.5 >>> S0 = scale_matrix(factor, origin) >>> factor, origin, direction = scal...
IndexError
dataset/ETHPy150Open omangin/multimodal/multimodal/lib/transformations.py/scale_from_matrix
2,862
def euler_matrix(ai, aj, ak, axes='sxyz'): """Return homogeneous rotation matrix from Euler angles and axis sequence. ai, aj, ak : Euler's roll, pitch and yaw angles axes : One of 24 axis sequences as string or encoded tuple >>> R = euler_matrix(1, 2, 3, 'syxz') >>> numpy.allclose(numpy.sum(R[0]),...
KeyError
dataset/ETHPy150Open omangin/multimodal/multimodal/lib/transformations.py/euler_matrix
2,863
def euler_from_matrix(matrix, axes='sxyz'): """Return Euler angles from rotation matrix for specified axis sequence. axes : One of 24 axis sequences as string or encoded tuple Note that many Euler angle triplets can describe one matrix. >>> R0 = euler_matrix(1, 2, 3, 'syxz') >>> al, be, ga = eule...
KeyError
dataset/ETHPy150Open omangin/multimodal/multimodal/lib/transformations.py/euler_from_matrix
2,864
def quaternion_from_euler(ai, aj, ak, axes='sxyz'): """Return quaternion from Euler angles and axis sequence. ai, aj, ak : Euler's roll, pitch and yaw angles axes : One of 24 axis sequences as string or encoded tuple >>> q = quaternion_from_euler(1, 2, 3, 'ryxz') >>> numpy.allclose(q, [0.310622, -...
KeyError
dataset/ETHPy150Open omangin/multimodal/multimodal/lib/transformations.py/quaternion_from_euler
2,865
def _import_module(module_name, warn=True, prefix='_py_', ignore='_'): """Try import all public attributes from module into global namespace. Existing attributes with name clashes are renamed with prefix. Attributes starting with underscore are ignored by default. Return True on successful import. ...
ImportError
dataset/ETHPy150Open omangin/multimodal/multimodal/lib/transformations.py/_import_module
2,866
def alive(self): try: os.kill(self.pid, 0) except __HOLE__: return False return True
OSError
dataset/ETHPy150Open coreemu/core/daemon/core/netns/vnode.py/SimpleLxcNode.alive
2,867
def startup(self): ''' Start a new namespace node by invoking the vnoded process that allocates a new namespace. Bring up the loopback device and set the hostname. ''' if self.up: raise Exception, "already up" vnoded = ["%s/vnoded" % CORE_SBIN_DIR, "-v...
OSError
dataset/ETHPy150Open coreemu/core/daemon/core/netns/vnode.py/SimpleLxcNode.startup
2,868
def shutdown(self): if not self.up: return while self._mounts: source, target = self._mounts.pop(-1) self.umount(target) for netif in self.netifs(): netif.shutdown() try: os.kill(self.pid, signal.SIGTERM) os.waitpid(...
OSError
dataset/ETHPy150Open coreemu/core/daemon/core/netns/vnode.py/SimpleLxcNode.shutdown
2,869
def newveth(self, ifindex = None, ifname = None, net = None): self.lock.acquire() try: if ifindex is None: ifindex = self.newifindex() if ifname is None: ifname = "eth%d" % ifindex sessionid = self.session.shortsessionid() t...
TypeError
dataset/ETHPy150Open coreemu/core/daemon/core/netns/vnode.py/SimpleLxcNode.newveth
2,870
def deladdr(self, ifindex, addr): try: self._netif[ifindex].deladdr(addr) except __HOLE__: self.warn("trying to delete unknown address: %s" % addr) if self.up: self.cmd([IP_BIN, "addr", "del", str(addr), "dev", self.ifname(ifindex)])
ValueError
dataset/ETHPy150Open coreemu/core/daemon/core/netns/vnode.py/SimpleLxcNode.deladdr
2,871
def startup(self): self.lock.acquire() try: self.makenodedir() super(LxcNode, self).startup() self.privatedir("/var/run") self.privatedir("/var/log") except __HOLE__, e: self.warn("Error with LxcNode.startup(): %s" % e) self...
OSError
dataset/ETHPy150Open coreemu/core/daemon/core/netns/vnode.py/LxcNode.startup
2,872
def privatedir(self, path): if path[0] != "/": raise ValueError, "path not fully qualified: " + path hostpath = os.path.join(self.nodedir, os.path.normpath(path).strip('/').replace('/', '.')) try: os.mkdir(hostpath) except __HOLE__:...
OSError
dataset/ETHPy150Open coreemu/core/daemon/core/netns/vnode.py/LxcNode.privatedir
2,873
def emit(self, record): try: msg = record.getMessage() log_data = "PLAINTEXT=" + urllib2.quote(simplejson.dumps( { 'msg':msg, 'localip':self.localip, 'publicip':self.publicip, 'tenant':'TODO :...
SystemExit
dataset/ETHPy150Open gosquadron/squadron/squadron/fileio/loghandlers/LogglyHandler.py/LogglyHandler.emit
2,874
def add_field(self, field): # Insert the given field in the order in which it was created, using # the "creation_counter" attribute of the field. # Move many-to-many related fields from self.fields into # self.many_to_many. if field.rel and isinstance(field.rel, ManyToManyRel): ...
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/db/models/options.py/Options.add_field
2,875
def _swapped(self): """ Has this model been swapped out for another? If so, return the model name of the replacement; otherwise, return None. For historical reasons, model name lookups using get_model() are case insensitive, so we make sure we are case insensitive here. ...
ValueError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/db/models/options.py/Options._swapped
2,876
@cached_property def fields(self): """ The getter for self.fields. This returns the list of field objects available to this model (including through parent models). Callers are not permitted to modify this list, since it's a reference to this instance (not a copy). "...
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/db/models/options.py/Options.fields
2,877
def get_fields_with_model(self): """ Returns a sequence of (field, model) pairs for all fields. The "model" element is None for fields on the current model. Mostly of use when constructing queries so that we know which model a field belongs to. """ try: self._...
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/db/models/options.py/Options.get_fields_with_model
2,878
def _many_to_many(self): try: self._m2m_cache except __HOLE__: self._fill_m2m_cache() return list(self._m2m_cache)
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/db/models/options.py/Options._many_to_many
2,879
def get_m2m_with_model(self): """ The many-to-many version of get_fields_with_model(). """ try: self._m2m_cache except __HOLE__: self._fill_m2m_cache() return list(six.iteritems(self._m2m_cache))
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/db/models/options.py/Options.get_m2m_with_model
2,880
def get_field_by_name(self, name): """ Returns the (field_object, model, direct, m2m), where field_object is the Field instance for the given name, model is the model containing this field (None for local fields), direct is True if the field exists on this model, and m2m is True ...
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/db/models/options.py/Options.get_field_by_name
2,881
def get_all_field_names(self): """ Returns a list of all field names that are possible for this model (including reverse relation names). This is used for pretty printing debugging output (a list of choices), so any internal-only field names are not included. """ ...
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/db/models/options.py/Options.get_all_field_names
2,882
def get_all_related_objects_with_model(self, local_only=False, include_hidden=False, include_proxy_eq=False): """ Returns a list of (related-object, model) pairs. Similar to get_fields_with_model(). """...
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/db/models/options.py/Options.get_all_related_objects_with_model
2,883
def get_all_related_many_to_many_objects(self, local_only=False): try: cache = self._related_many_to_many_cache except __HOLE__: cache = self._fill_related_many_to_many_cache() if local_only: return [k for k, v in cache.items() if not v] return list(ca...
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/db/models/options.py/Options.get_all_related_many_to_many_objects
2,884
def get_all_related_m2m_objects_with_model(self): """ Returns a list of (related-m2m-object, model) pairs. Similar to get_fields_with_model(). """ try: cache = self._related_many_to_many_cache except __HOLE__: cache = self._fill_related_many_to_man...
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/db/models/options.py/Options.get_all_related_m2m_objects_with_model
2,885
def allowed(request, file): try: addon = file.version.addon except __HOLE__: raise http.Http404 # General case: addon is listed. if addon.is_listed: if ((addon.view_source and addon.status in amo.REVIEWED_STATUSES) or acl.check_addons_reviewer(request) or ...
ObjectDoesNotExist
dataset/ETHPy150Open mozilla/addons-server/src/olympia/files/decorators.py/allowed
2,886
def file_view(func, **kwargs): @functools.wraps(func) def wrapper(request, file_id, *args, **kw): file_ = get_object_or_404(File, pk=file_id) result = allowed(request, file_) if result is not True: return result try: obj = FileViewer(file_,) except...
ObjectDoesNotExist
dataset/ETHPy150Open mozilla/addons-server/src/olympia/files/decorators.py/file_view
2,887
def compare_file_view(func, **kwargs): @functools.wraps(func) def wrapper(request, one_id, two_id, *args, **kw): one = get_object_or_404(File, pk=one_id) two = get_object_or_404(File, pk=two_id) for obj in [one, two]: result = allowed(request, obj) if result is no...
ObjectDoesNotExist
dataset/ETHPy150Open mozilla/addons-server/src/olympia/files/decorators.py/compare_file_view
2,888
def main(): client = Client(['localhost']) plugins = None if args.plugin: if args.category or args.component or args.health: lg.warn("Plugins specified by name, ignoring --category, --component and --health") plugins = client.get_plugins([args.plugin]) elif args.category or...
IndexError
dataset/ETHPy150Open gooddata/smoker/bin/check_smoker_plugin.py/main
2,889
def testInvalidColumnAlignmentStrings(self): t = TableGenerator.createTableWithDefaultContainer(3, 7) defaultAlignments = [Table.ALIGN_LEFT, Table.ALIGN_LEFT, Table.ALIGN_LEFT] try: t.setColumnAlignments(['a', 'b', 'c']) self.fail('No exception thrown for...
ValueError
dataset/ETHPy150Open rwl/muntjac/muntjac/test/server/component/table/table_column_alignments.py/TableColumnAlignments.testInvalidColumnAlignmentStrings
2,890
def testInvalidColumnAlignmentString(self): t = TableGenerator.createTableWithDefaultContainer(3, 7) defaultAlignments = [Table.ALIGN_LEFT, Table.ALIGN_LEFT, Table.ALIGN_LEFT] try: t.setColumnAlignment('Property 1', 'a') self.fail('No exception thrown for...
ValueError
dataset/ETHPy150Open rwl/muntjac/muntjac/test/server/component/table/table_column_alignments.py/TableColumnAlignments.testInvalidColumnAlignmentString
2,891
def testColumnAlignmentForPropertyNotInContainer(self): t = TableGenerator.createTableWithDefaultContainer(3, 7) defaultAlignments = [Table.ALIGN_LEFT, Table.ALIGN_LEFT, Table.ALIGN_LEFT] try: t.setColumnAlignment('Property 1200', Table.ALIGN_LEFT) # FIXM...
ValueError
dataset/ETHPy150Open rwl/muntjac/muntjac/test/server/component/table/table_column_alignments.py/TableColumnAlignments.testColumnAlignmentForPropertyNotInContainer
2,892
def testInvalidColumnAlignmentsLength(self): t = TableGenerator.createTableWithDefaultContainer(7, 7) defaultAlignments = [Table.ALIGN_LEFT, Table.ALIGN_LEFT, Table.ALIGN_LEFT, Table.ALIGN_LEFT, Table.ALIGN_LEFT, Table.ALIGN_LEFT, Table.ALIGN_LEFT] try: ...
ValueError
dataset/ETHPy150Open rwl/muntjac/muntjac/test/server/component/table/table_column_alignments.py/TableColumnAlignments.testInvalidColumnAlignmentsLength
2,893
def readme(): try: root = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(root, 'README.rst')) as f: return f.read() except __HOLE__: warnings.warn("Couldn't found README.rst", RuntimeWarning) return ''
IOError
dataset/ETHPy150Open Kroisse/flask-factory/setup.py/readme
2,894
def __init__(self, params, offset=0): agents.Agent.__init__(self, params, offset) try: self.avgprice = self.args[0] except (AttributeError, IndexError): raise MissingParameter, 'avgprice' try: self.maxfluct = self.args[1] except __HOLE__: ...
IndexError
dataset/ETHPy150Open jcbagneris/fms/fms/agents/randomtrader.py/RandomTrader.__init__
2,895
def act(self, world=None, market=None): """ Return random order as a dict with keys in (direction, price, quantity). """ if self.stocks > 0: direction = random.choice((BUY, SELL)) else: direction = BUY if self.avgprice == 0: try: ...
AttributeError
dataset/ETHPy150Open jcbagneris/fms/fms/agents/randomtrader.py/RandomTrader.act
2,896
@utils.memoize def get_font_files(): """Returns a list of all font files we could find Returned as a list of dir/files tuples:: get_font_files() -> [('/some/dir', ['font1.ttf', ...]), ...] For example:: >>> fabfonts = os.path.join(os.path.dirname(__file__), 'fonts') >>> 'IndUni-H...
OSError
dataset/ETHPy150Open jart/fabulous/fabulous/text.py/get_font_files
2,897
def _unpack_complex_cli_arg(argument_model, value, cli_name): type_name = argument_model.type_name if type_name == 'structure' or type_name == 'map': if value.lstrip()[0] == '{': try: return json.loads(value, object_pairs_hook=OrderedDict) except ValueError as e: ...
ValueError
dataset/ETHPy150Open aws/aws-cli/awscli/argprocess.py/_unpack_complex_cli_arg
2,898
def main(argv): """ Build the docs and serve them with an HTTP server. """ parser = argparse.ArgumentParser(description='Build and serve HTML Sphinx docs') parser.add_argument( '--port', help='Serve on this port, default 8000', type=int, default=8000) parser.add...
KeyboardInterrupt
dataset/ETHPy150Open robmadole/jig/salt/roots/salt/docs/httpdocs.py/main
2,899
def _get_error_message(self, resp): try: response_data = resp.json() message = response_data['title'] description = response_data.get('description') if description: message = '{0}: {1}'.format(message, description) except __HOLE__: ...
ValueError
dataset/ETHPy150Open openstack/python-barbicanclient/barbicanclient/client.py/_HTTPClient._get_error_message