Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
9,900
def test_csv_export_extra_data(self): """Ensures exported CSV data matches source data""" qs_filter = { "pk__in": [x.pk for x in self.snapshots] } qs = BuildingSnapshot.objects.filter(**qs_filter) fields = list(_get_fields_from_queryset(qs)) fields.append("canonical_building__id...
AttributeError
dataset/ETHPy150Open buildingenergy/buildingenergy-platform/seed/tests/test_exporters.py/TestExporters.test_csv_export_extra_data
9,901
def main(self): """Main functionality """ try: # Set up logging log_fmt = '%(asctime)-15s %(levelname)-8s %(message)s' log_level = logging.INFO if sys.stdout.isatty(): # Connected to a real terminal - log to stdout ...
KeyboardInterrupt
dataset/ETHPy150Open rllynch/pi_garage_alert/bin/pi_garage_alert.py/PiGarageAlert.main
9,902
def _escaped_text_from_text(text, escapes="eol"): r"""Return escaped version of text. "escapes" is either a mapping of chars in the source text to replacement text for each such char or one of a set of strings identifying a particular escape style: eol ...
TypeError
dataset/ETHPy150Open an0/Letterpress/code/markdown2/test/test_markdown2.py/_escaped_text_from_text
9,903
def complete(self, area): """ """ try: self.seq.next() except __HOLE__: pass
StopIteration
dataset/ETHPy150Open iogf/vy/vyapp/plugins/quick_completion.py/QuickCompletion.complete
9,904
def import_matches(query, prefix=''): matches = set(re.findall(r"(%s[a-zA-Z_][a-zA-Z0-9_]*)\.?" % prefix, query)) for raw_module_name in matches: if re.match('np(\..*)?$', raw_module_name): module_name = re.sub('^np', 'numpy', raw_module_name) elif re.match('pd(\..*)?$', raw_module_n...
ImportError
dataset/ETHPy150Open Russell91/pythonpy/pythonpy/__main__.py/import_matches
9,905
def test_instance(self): Point = namedtuple('Point', 'x y') p = Point(11, 22) self.assertEqual(p, Point(x=11, y=22)) self.assertEqual(p, Point(11, y=22)) self.assertEqual(p, Point(y=22, x=11)) self.assertEqual(p, Point(*(11, 22))) self.assertEqual(p, Point(**dict(...
ValueError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_collections.py/TestNamedTuple.test_instance
9,906
@classmethod def from_row(cls, row_dict): tag = row_dict.get('table_id') or row_dict.get('tag') if tag is None: raise ExcelMalformatException(_(FAILURE_MESSAGES['has_no_column']).format(column_name='table_id')) field_names = row_dict.get('field') item_attributes = row_di...
KeyError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/fixtures/upload.py/FixtureTableDefinition.from_row
9,907
def __init__(self, file_or_filename): try: self.workbook = WorkbookJSONReader(file_or_filename) except __HOLE__: raise FixtureUploadError(_("Error processing your Excel (.xlsx) file")) except InvalidFileException: raise FixtureUploadError(_("Invalid file-forma...
AttributeError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/fixtures/upload.py/FixtureWorkbook.__init__
9,908
def run_upload(domain, workbook, replace=False, task=None): from corehq.apps.users.bulkupload import GroupMemoizer return_val = FixtureUploadResult() group_memoizer = GroupMemoizer(domain) get_location = get_memoized_location(domain) def diff_lists(list_a, list_b): set_a = set(list_a) ...
KeyError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/fixtures/upload.py/run_upload
9,909
def init_database(self): self.raw_db = create_engine(self.config['url'], echo=False) self.raw_conn = self.raw_db.connect() self.operations = Operations(self.raw_conn, self.config) try: self.raw_conn.connection.set_isolation_level(0) except __HOLE__: logge...
AttributeError
dataset/ETHPy150Open fastmonkeys/stellar/stellar/app.py/Stellar.init_database
9,910
def _process_response(self, response, message): """Process response from remote side.""" LOG.debug("Started processing response message '%s'", ku.DelayedPretty(message)) try: request_uuid = message.properties['correlation_id'] except __HOLE__: LO...
KeyError
dataset/ETHPy150Open openstack/taskflow/taskflow/engines/worker_based/executor.py/WorkerTaskExecutor._process_response
9,911
def _clean(self): if not self._ongoing_requests: return with self._ongoing_requests_lock: ongoing_requests_uuids = set(six.iterkeys(self._ongoing_requests)) waiting_requests = {} expired_requests = {} for request_uuid in ongoing_requests_uuids: ...
KeyError
dataset/ETHPy150Open openstack/taskflow/taskflow/engines/worker_based/executor.py/WorkerTaskExecutor._clean
9,912
def inlines(value, return_list=False): try: from BeautifulSoup import BeautifulSoup except __HOLE__: from beautifulsoup import BeautifulSoup content = BeautifulSoup(value, selfClosingTags=['inline','img','br','input','meta','link','hr']) inline_list = [] if return_list: for...
ImportError
dataset/ETHPy150Open issackelly/django-improved-inlines/improved_inlines/parser.py/inlines
9,913
def render_inline(inline): """ Replace inline markup with template markup that matches the appropriate app and model. """ # Look for inline model type, 'app.model' if inline.name == 'inline': model_string = inline.get('type', None) else: model_string = inline.get('data-inlin...
ValueError
dataset/ETHPy150Open issackelly/django-improved-inlines/improved_inlines/parser.py/render_inline
9,914
def DSQuery(dstype, objectname, attribute=None, node='.'): """DirectoryServices query. Args: dstype: The type of objects to query. user, group. objectname: the object to query. attribute: the optional attribute to query. node: the node to query. Returns: If an attribute is specified, the valu...
TypeError
dataset/ETHPy150Open google/macops/gmacpyutil/gmacpyutil/ds.py/DSQuery
9,915
def SyncShadowHash(username, shadow_name): """Sync the password hash for the shadow admin account with the user's.""" shadow_guid = UserAttribute(shadow_name, 'GeneratedUID') user_hash = '/var/db/shadow/hash/%s' % username if not os.path.exists(user_hash): user_guid = UserAttribute(username, 'GeneratedUID')...
OSError
dataset/ETHPy150Open google/macops/gmacpyutil/gmacpyutil/ds.py/SyncShadowHash
9,916
@classmethod def default_decoder(cls, value): try: return pyrfc3339.parse(value) except __HOLE__ as error: raise jose.DeserializationError(error)
ValueError
dataset/ETHPy150Open letsencrypt/letsencrypt/acme/acme/fields.py/RFC3339Field.default_decoder
9,917
def main(argv): if not validate_argv(argv): print(pysb.export.__doc__, end=' ') return 1 model_filename = argv[1] format = argv[2] # Make sure that the user has supplied an allowable format if format not in pysb.export.formats.keys(): raise Exception("The format must be one...
KeyError
dataset/ETHPy150Open pysb/pysb/pysb/export/__main__.py/main
9,918
def encode_text(text): if isinstance(text, six.text_type): return text.encode('utf-8') try: return text.decode('utf-8').encode('utf-8') except (__HOLE__, UnicodeEncodeError): return text.encode('ascii', 'replace')
UnicodeDecodeError
dataset/ETHPy150Open pudo/archivekit/archivekit/util.py/encode_text
9,919
def json_hook(obj): for k, v in obj.items(): if isinstance(v, basestring): try: obj[k] = datetime.strptime(v, "new Date(%Y-%m-%d)").date() except __HOLE__: pass try: obj[k] = datetime.strptime(v, "%Y-%m-%dT%H:%M:%S") ...
ValueError
dataset/ETHPy150Open pudo/archivekit/archivekit/util.py/json_hook
9,920
def _checkCPython(sys=sys, platform=platform): """ Checks if this implementation is CPython. On recent versions of Python, will use C{platform.python_implementation}. On 2.5, it will try to extract the implementation from sys.subversion. On older versions (currently the only supported older version...
AttributeError
dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/python/dist.py/_checkCPython
9,921
@auth def _POST(self, *param, **params): if not validates_icon(self): self.logger.debug("Create Icon is failed, Invalid input value") return web.badrequest(add_prefix(self.view.alert, "400")) icon_filevalue = self.input.multi_icon.value icon_filename = "%s.%s" % (uni...
IOError
dataset/ETHPy150Open karesansui/karesansui/karesansui/gadget/icon.py/Icon._POST
9,922
@auth def _DELETE(self, *param, **params): icon_filename = param[0] if is_path(icon_filename) is True: return web.badrequest("Not to include the path.") icon_realpath = ICON_DIR_TPL % (karesansui.dirname, icon_filename) if not os.path.exists(icon_realpath): ...
OSError
dataset/ETHPy150Open karesansui/karesansui/karesansui/gadget/icon.py/IconBy1._DELETE
9,923
def relativeairmass(zenith, model='kastenyoung1989'): ''' Gives the relative (not pressure-corrected) airmass. Gives the airmass at sea-level when given a sun zenith angle (in degrees). The ``model`` variable allows selection of different airmass models (described below). If ``model`` is not includ...
TypeError
dataset/ETHPy150Open pvlib/pvlib-python/pvlib/atmosphere.py/relativeairmass
9,924
@asyncio.coroutine def run_as_coroutine(self, stdin, callbacks): """ The input 'event loop'. """ # Note: We cannot use "yield from", because this package also # installs on Python 2. assert isinstance(callbacks, EventLoopCallbacks) if self.closed: ...
StopIteration
dataset/ETHPy150Open jonathanslenders/python-prompt-toolkit/prompt_toolkit/eventloop/asyncio_win32.py/Win32AsyncioEventLoop.run_as_coroutine
9,925
def authn_response(conf, return_addrs, outstanding_queries=None, timeslack=0, asynchop=True, allow_unsolicited=False, want_assertions_signed=False): sec = security_context(conf) if not timeslack: try: timeslack = int(conf.accepted_time_diff) exce...
TypeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/authn_response
9,926
def attribute_response(conf, return_addrs, timeslack=0, asynchop=False, test=False): sec = security_context(conf) if not timeslack: try: timeslack = int(conf.accepted_time_diff) except __HOLE__: timeslack = 0 return AttributeResponse(sec, conf....
TypeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/attribute_response
9,927
def _loads(self, xmldata, decode=True, origxml=None): # own copy self.xmlstr = xmldata[:] logger.debug("xmlstr: %s" % (self.xmlstr,)) if origxml: self.origxml = origxml else: self.origxml = self.xmlstr try: self.response = self.signat...
TypeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/StatusResponse._loads
9,928
def _verify(self): if self.request_id and self.in_response_to and \ self.in_response_to != self.request_id: logger.error("Not the id I expected: %s != %s" % ( self.in_response_to, self.request_id)) return None try: assert self....
AssertionError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/StatusResponse._verify
9,929
def verify(self, key_file=""): try: return self._verify() except __HOLE__: logger.exception("verify") return None
AssertionError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/StatusResponse.verify
9,930
def __init__(self, sec_context, attribute_converters, entity_id, return_addrs=None, outstanding_queries=None, timeslack=0, asynchop=True, allow_unsolicited=False, test=False, allow_unknown_attributes=False, want_assertions_signed=False, want_response_s...
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/AuthnResponse.__init__
9,931
def check_subject_confirmation_in_response_to(self, irp): for assertion in self.response.assertion: for _sc in assertion.subject.subject_confirmation: try: assert _sc.subject_confirmation_data.in_response_to == irp except __HOLE__: ...
AssertionError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/AuthnResponse.check_subject_confirmation_in_response_to
9,932
def loads(self, xmldata, decode=True, origxml=None): self._loads(xmldata, decode, origxml) if self.asynchop: if self.in_response_to in self.outstanding_queries: self.came_from = self.outstanding_queries[self.in_response_to] #del self.outstanding_queries[self....
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/AuthnResponse.loads
9,933
def authn_statement_ok(self, optional=False): try: # the assertion MUST contain one AuthNStatement assert len(self.assertion.authn_statement) == 1 except __HOLE__: if optional: return True else: logger.error("No AuthnStateme...
AssertionError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/AuthnResponse.authn_statement_ok
9,934
def condition_ok(self, lax=False): if self.test: lax = True # The Identity Provider MUST include a <saml:Conditions> element assert self.assertion.conditions conditions = self.assertion.conditions logger.debug("conditions: %s" % conditions) # if no sub-elem...
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/AuthnResponse.condition_ok
9,935
def get_subject(self): """ The assertion must contain a Subject """ assert self.assertion.subject subject = self.assertion.subject subjconf = [] for subject_confirmation in subject.subject_confirmation: _data = subject_confirmation.subject_confirmation_data ...
AssertionError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/AuthnResponse.get_subject
9,936
def parse_assertion(self, key_file=""): if self.context == "AuthnQuery": # can contain one or more assertions pass else: # This is a saml2int limitation try: assert len(self.response.assertion) == 1 or \ len(self.response.encrypted...
AssertionError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/AuthnResponse.parse_assertion
9,937
def verify(self, key_file=""): """ Verify that the assertion is syntactically correct and the signature is correct if present. :param key_file: If not the default key file should be used this is it. """ try: res = self._verify() except __HOLE__ as err: ...
AssertionError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/AuthnResponse.verify
9,938
def authn_info(self): res = [] for astat in self.assertion.authn_statement: context = astat.authn_context if context: try: aclass = context.authn_context_class_ref.text except __HOLE__: aclass = "" ...
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/AuthnResponse.authn_info
9,939
def response_factory(xmlstr, conf, return_addrs=None, outstanding_queries=None, timeslack=0, decode=True, request_id=0, origxml=None, asynchop=True, allow_unsolicited=False, want_assertions_signed=False): sec_context = security_context(conf) if not ...
TypeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/response_factory
9,940
def loads(self, xmldata, decode=True, origxml=None): # own copy self.xmlstr = xmldata[:] logger.debug("xmlstr: %s" % (self.xmlstr,)) self.origxml = origxml try: self.response = self.signature_check(xmldata, origdoc=origxml) self.assertion = self.response ...
TypeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/AssertionIDResponse.loads
9,941
def long_description(): """Return long description from README.rst if it's present because it doesn't get installed.""" try: return open(os.path.join( os.path.dirname(__file__), 'README.rst' )).read() except __HOLE__: return LONG_DESCRIPTION
IOError
dataset/ETHPy150Open wq/wq/setup.py/long_description
9,942
def test_can_get_record_values_by_slice_using_getslice(self): record = Record(["one", "two", "three"], ["eins", "zwei", "drei"]) try: s = record.__getslice__(0, 2) except __HOLE__: assert True else: assert s == Record(["one", "two"], ["eins", "zwei"])
AttributeError
dataset/ETHPy150Open nigelsmall/py2neo/test/test_cursor.py/RecordTestCase.test_can_get_record_values_by_slice_using_getslice
9,943
def writeWordIDs(featurefile, sep=None): """ The wordids are counted directly from the unigrams file. Filename: location of unigrams.txt sep: Delimiter. Defaults to None (whitespace), use this for tab- or comma-delimiting. """ output = open(".bookworm/texts/wordlist/wordlist....
KeyError
dataset/ETHPy150Open Bookworm-project/BookwormDB/bookwormDB/ingestFeatureCounts.py/writeWordIDs
9,944
def _translate2v2(ip, community, pdu): """Translate an SNMPv1 trap to an SNMPv2 trap per RFC2576. This is done so that the rest of the API only has to deal with V2 traps. """ varbinds = pdu.varbinds # 3.1.(1) varbinds.insert(0, sysUpTime(pdu.time_stamp).varbind) # 3.1.(2) if pdu.generic ...
AttributeError
dataset/ETHPy150Open kdart/pycopia/SNMP/pycopia/SNMP/traps.py/_translate2v2
9,945
def assert_fp_equal(x, y, err_msg="", nulp=50): """Assert two arrays are equal, up to some floating-point rounding error""" try: assert_array_almost_equal_nulp(x, y, nulp) except __HOLE__ as e: raise AssertionError("%s\n%s" % (e, err_msg))
AssertionError
dataset/ETHPy150Open scipy/scipy/scipy/optimize/tests/test_linesearch.py/assert_fp_equal
9,946
def execute_command(self, command_name, **kwargs): """Execute an agent command.""" with self.command_lock: LOG.debug('Executing command: %(name)s with args: %(args)s', {'name': command_name, 'args': kwargs}) extension_part, command_part = self.split_command(...
KeyError
dataset/ETHPy150Open openstack/ironic-python-agent/ironic_python_agent/extensions/base.py/ExecuteCommandMixin.execute_command
9,947
def get_user_profile(session_id): if session_id is None: return None try: djsession = djSession.objects.get(expire_date__gt=timezone.now(), session_key=session_id) except djSession.DoesNotExist: return None try: return UserProfi...
KeyError
dataset/ETHPy150Open zulip/zulip/zerver/lib/socket.py/get_user_profile
9,948
def on_open(self, info): log_data = dict(extra='[transport=%s]' % (self.session.transport_name,)) record_request_start_data(log_data) ioloop = tornado.ioloop.IOLoop.instance() self.authenticated = False self.session.user_profile = None self.close_info = None # type: Clo...
AttributeError
dataset/ETHPy150Open zulip/zulip/zerver/lib/socket.py/SocketConnection.on_open
9,949
def is_in_alphabet(self, uchr, alphabet): if self.no_memory: return alphabet in ud.name(uchr) try: return self.alphabet_letters[alphabet][uchr] except __HOLE__: return self.alphabet_letters[alphabet].setdefault( uchr, alphabet in ud.name(uchr))
KeyError
dataset/ETHPy150Open EliFinkelshteyn/alphabet-detector/alphabet_detector/alphabet_detector.py/AlphabetDetector.is_in_alphabet
9,950
def first(self): """ Returns the first object of a query, returns None if no match is found. """ qs = self if self.ordered else self.order_by('pk') try: return qs[0] except __HOLE__: return None
IndexError
dataset/ETHPy150Open ulule/django-courriers/courriers/core.py/QuerySet.first
9,951
def last(self): """ Returns the last object of a query, returns None if no match is found. """ qs = self.reverse() if self.ordered else self.order_by('-pk') try: return qs[0] except __HOLE__: return None
IndexError
dataset/ETHPy150Open ulule/django-courriers/courriers/core.py/QuerySet.last
9,952
def str_to_datetime_processor_factory(regexp, type_): rmatch = regexp.match # Even on python2.6 datetime.strptime is both slower than this code # and it does not support microseconds. has_named_groups = bool(regexp.groupindex) def process(value): if value is None: return None ...
TypeError
dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/processors.py/str_to_datetime_processor_factory
9,953
def build_manpages(): # Go into the docs directory and build the manpage. docdir = os.path.join(os.path.dirname(__file__), 'docs') curdir = os.getcwd() os.chdir(docdir) try: subprocess.check_call(['make', 'man']) except __HOLE__: print("Could not build manpages (make man failed)!...
OSError
dataset/ETHPy150Open beetbox/beets/setup.py/build_manpages
9,954
@jsexpose(body_cls=ActionAliasAPI, status_code=http_client.CREATED) @request_user_has_resource_api_permission(permission_type=PermissionType.ACTION_ALIAS_CREATE) def post(self, action_alias): """ Create a new ActionAlias. Handles requests: POST /actionalias/ ...
ValueError
dataset/ETHPy150Open StackStorm/st2/st2api/st2api/controllers/v1/actionalias.py/ActionAliasController.post
9,955
@request_user_has_resource_db_permission(permission_type=PermissionType.ACTION_MODIFY) @jsexpose(arg_types=[str], body_cls=ActionAliasAPI) def put(self, action_alias_ref_or_id, action_alias): action_alias_db = self._get_by_ref_or_id(ref_or_id=action_alias_ref_or_id) LOG.debug('PUT /actionalias/ ...
ValidationError
dataset/ETHPy150Open StackStorm/st2/st2api/st2api/controllers/v1/actionalias.py/ActionAliasController.put
9,956
def _stop(self, exit_exc=None, caller=None): if self._stopped: return self._stopped = True self._rloop.kill(block=True) self._wloop.kill(block=True) # handle clean disconnection from client try: self.sock.shutdown(socket.SHUT_RDWR) except...
AttributeError
dataset/ETHPy150Open simplecrypto/powerpool/powerpool/server.py/GenericClient._stop
9,957
def visit_Name(self, node): name = node.id if name.startswith('__'): raise ValueError("invalid name %r" % name) try: return self.scope[name] except __HOLE__: return symbol(name, self.dtypes[name])
KeyError
dataset/ETHPy150Open blaze/blaze/blaze/expr/parser.py/BlazeParser.visit_Name
9,958
def run(self, lines): """ Parse Meta-Data and store in Markdown.Meta. """ meta = {} key = None while lines: line = lines.pop(0) if line.strip() == '': break # blank line - done m1 = META_RE.match(line) if m1: ...
KeyError
dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/markdown/extensions/meta.py/MetaPreprocessor.run
9,959
def __getattr__(self, attr): if attr.startswith('_'): raise AttributeError("No such setting: {0}".format(attr)) else: try: return self._members[attr] except __HOLE__: raise AttributeError("No such setting: {0}".format(attr))
KeyError
dataset/ETHPy150Open glue-viz/glue/glue/config.py/SettingRegistry.__getattr__
9,960
def default_members(self): defaults = {} for viewer in qt_client.members: try: defaults[viewer] = viewer._get_default_tools() except __HOLE__: logger.info("could not get default tools for {0}".format(viewer.__name__)) defaults[viewe...
AttributeError
dataset/ETHPy150Open glue-viz/glue/glue/config.py/QtToolRegistry.default_members
9,961
def load_configuration(search_path=None): ''' Find and import a config.py file Returns: The module object Raises: Exception, if no module was found ''' search_order = search_path or _default_search_order() result = imp.new_module('config') for config_file in search_order: ...
IOError
dataset/ETHPy150Open glue-viz/glue/glue/config.py/load_configuration
9,962
def get_completions(self, document, complete_event): """ Get Python completions. """ # Do Path completions if complete_event.completion_requested or self._complete_path_while_typing(document): for c in self._path_completer.get_completions(document, complete_event): ...
UnicodeDecodeError
dataset/ETHPy150Open jonathanslenders/ptpython/ptpython/completer.py/PythonCompleter.get_completions
9,963
def pid_exists(pid): """Check whether pid exists in the current process table.""" if pid == 0: # According to "man 2 kill" PID 0 has a special meaning: # it refers to <<every process in the process group of the # calling process>> so we don't want to go any further. # If we get h...
OSError
dataset/ETHPy150Open giampaolo/psutil/psutil/_psposix.py/pid_exists
9,964
def wait_pid(pid, timeout=None): """Wait for process with pid 'pid' to terminate and return its exit status code as an integer. If pid is not a children of os.getpid() (current process) just waits until the process disappears and return None. If pid does not exist at all return None immediately. ...
OSError
dataset/ETHPy150Open giampaolo/psutil/psutil/_psposix.py/wait_pid
9,965
@memoize def _get_terminal_map(): ret = {} ls = glob.glob('/dev/tty*') + glob.glob('/dev/pts/*') for name in ls: assert name not in ret try: ret[os.stat(name).st_rdev] = name except __HOLE__ as err: if err.errno != errno.ENOENT: raise retur...
OSError
dataset/ETHPy150Open giampaolo/psutil/psutil/_psposix.py/_get_terminal_map
9,966
@classmethod def must_send_stats(cls, master_node_settings_data=None): """Checks if stats must be sent Stats must be sent if user saved the choice and sending anonymous statistics was selected. :param master_node_settings_data: dict with master node settings. If master_node...
AttributeError
dataset/ETHPy150Open openstack/fuel-web/nailgun/nailgun/objects/master_node_settings.py/MasterNodeSettings.must_send_stats
9,967
@classmethod def run_2to3(cls, path): from lib2to3.refactor import get_fixers_from_package, RefactoringTool rt = RefactoringTool(get_fixers_from_package('lib2to3.fixes')) with TRACER.timed('Translating %s' % path): for root, dirs, files in os.walk(path): for fn in files: full_fn = ...
IOError
dataset/ETHPy150Open pantsbuild/pex/pex/translator.py/SourceTranslator.run_2to3
9,968
def paasta_cook_image(args, service=None, soa_dir=None): """Build a docker image""" if service: service = service else: service = args.service if service and service.startswith('services-'): service = service.split('services-', 1)[1] validate_service_name(service, soa_dir) ...
KeyboardInterrupt
dataset/ETHPy150Open Yelp/paasta/paasta_tools/cli/cmds/cook_image.py/paasta_cook_image
9,969
def addComponent(self, c, index=None): """Add a component into this container. The component is added to the right or under the previous component or into the indexed position in this container. @param c: the component to be added. @param index: ...
ValueError
dataset/ETHPy150Open rwl/muntjac/muntjac/ui/abstract_ordered_layout.py/AbstractOrderedLayout.addComponent
9,970
def addComponentAsFirst(self, c): """Adds a component into this container. The component is added to the left or on top of the other components. @param c: the component to be added. """ self.components.insert(0, c) try: super(AbstractOrderedLayout, self).addC...
ValueError
dataset/ETHPy150Open rwl/muntjac/muntjac/ui/abstract_ordered_layout.py/AbstractOrderedLayout.addComponentAsFirst
9,971
def getComponentIndex(self, component): """Returns the index of the given component. @param component: The component to look up. @return: The index of the component or -1 if the component is not a child. """ try: return self.compone...
ValueError
dataset/ETHPy150Open rwl/muntjac/muntjac/ui/abstract_ordered_layout.py/AbstractOrderedLayout.getComponentIndex
9,972
def password_reset_confirm(request, uidb36=None, token=None, template_name='registration/password_reset_confirm.html', token_generator=default_token_generator, set_password_form=SetPasswordForm, post_reset_redirect=None): """ View that checks the hash in a p...
ValueError
dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/contrib/auth/views.py/password_reset_confirm
9,973
def _community(G, u, community): """Get the community of the given node.""" node_u = G.node[u] try: return node_u[community] except __HOLE__: raise nx.NetworkXAlgorithmError('No community information')
KeyError
dataset/ETHPy150Open networkx/networkx/networkx/algorithms/link_prediction.py/_community
9,974
@property def date(self): try: return datetime.date(self.created.year, self.created.month, self.created.day) except __HOLE__: # created may be None return None
AttributeError
dataset/ETHPy150Open mozilla/addons-server/src/olympia/stats/models.py/Contribution.date
9,975
@property def contributor(self): try: return u'%s %s' % (self.post_data['first_name'], self.post_data['last_name']) except (TypeError, __HOLE__): # post_data may be None or missing a key return None
KeyError
dataset/ETHPy150Open mozilla/addons-server/src/olympia/stats/models.py/Contribution.contributor
9,976
@property def email(self): try: return self.post_data['payer_email'] except (__HOLE__, KeyError): # post_data may be None or missing a key return None
TypeError
dataset/ETHPy150Open mozilla/addons-server/src/olympia/stats/models.py/Contribution.email
9,977
def __init__(self, *args, **kwds): if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) try: self.__end except __HOLE__: self.clear() self.update(*args, **kwds)
AttributeError
dataset/ETHPy150Open tanghaibao/jcvi/utils/orderedcollections.py/OrderedDict.__init__
9,978
def __getitem__(self, key): try: return OrderedDict.__getitem__(self, key) except __HOLE__: return self.__missing__(key)
KeyError
dataset/ETHPy150Open tanghaibao/jcvi/utils/orderedcollections.py/DefaultOrderedDict.__getitem__
9,979
def delete_hosts(hosts): while True: list_hosts(hosts) del_idx = click.prompt('Select host to delete, y/Y to confirm, ' \ 'or n/N to add more hosts', default='n') try: del_idx = int(del_idx) hosts.remove(hosts[del_idx]) except In...
ValueError
dataset/ETHPy150Open openshift/openshift-ansible/utils/src/ooinstall/cli_installer.py/delete_hosts
9,980
def confirm_hosts_facts(oo_cfg, callback_facts): hosts = oo_cfg.hosts click.clear() message = """ A list of the facts gathered from the provided hosts follows. Because it is often the case that the hostname for a system inside the cluster is different from the hostname that is resolveable from command line ...
KeyError
dataset/ETHPy150Open openshift/openshift-ansible/utils/src/ooinstall/cli_installer.py/confirm_hosts_facts
9,981
def get_installed_hosts(hosts, callback_facts): installed_hosts = [] # count nativeha lb as an installed host try: first_master = next(host for host in hosts if host.master) lb_hostname = callback_facts[first_master.connect_to]['master'].get('cluster_hostname', '') lb_host = \ ...
KeyError
dataset/ETHPy150Open openshift/openshift-ansible/utils/src/ooinstall/cli_installer.py/get_installed_hosts
9,982
def get_wallpapers(self): try: # get path of all files in the directory self.images = list( filter(os.path.isfile, map(self.get_path, os.listdir(self.directory)))) except __HOLE__ as e: logger.exception...
IOError
dataset/ETHPy150Open qtile/qtile/libqtile/widget/wallpaper.py/Wallpaper.get_wallpapers
9,983
def load_vars(path, vars): """Load variables from a pickle file. Arguments: * path: the path to the pickle file. * vars: a list of variable names. Returns: * cache: a dictionary {var_name: var_value}. """ with open(path, 'rb') as f: # Load the varia...
ValueError
dataset/ETHPy150Open rossant/ipycache/ipycache.py/load_vars
9,984
def load_captured_io(captured_io): try: return CapturedIO(captured_io.get('stdout', None), captured_io.get('stderr', None), outputs=captured_io.get('outputs', []), ) except __HOLE__: return CapturedIO(captured_io.get('...
TypeError
dataset/ETHPy150Open rossant/ipycache/ipycache.py/load_captured_io
9,985
def cache(cell, path, vars=[], # HACK: this function implementing the magic's logic is testable # without IPython, by giving mock functions here instead of IPython # methods. ip_user_ns={}, ip_run_cell=None, ip_push=None, ip_clear_output=lambda : None, force=False, read...
ValueError
dataset/ETHPy150Open rossant/ipycache/ipycache.py/cache
9,986
def view_detail(request, view): if not utils.docutils_is_available: return missing_docutils_page(request) mod, func = urlresolvers.get_mod_func(view) try: view_func = getattr(__import__(mod, {}, {}, ['']), func) except (ImportError, __HOLE__): raise Http404 title, body, meta...
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/contrib/admin/views/doc.py/view_detail
9,987
def model_detail(request, app_label, model_name): if not utils.docutils_is_available: return missing_docutils_page(request) # Get the model class. try: app_mod = models.get_app(app_label) except ImproperlyConfigured: raise Http404, _("App %r not found") % app_label model = N...
StopIteration
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/contrib/admin/views/doc.py/model_detail
9,988
def extract_views_from_urlpatterns(urlpatterns, base=''): """ Return a list of views from a list of urlpatterns. Each object in the returned list is a two-tuple: (view_func, regex) """ views = [] for p in urlpatterns: if hasattr(p, '_get_callback'): try: view...
ImportError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/contrib/admin/views/doc.py/extract_views_from_urlpatterns
9,989
def flush_django_cache(cache_instance=None): cache_instance = cache_instance if not cache_instance: from django.core.cache import cache cache_instance = cache try: cache_instance.clear() except __HOLE__: # Django < 1.2, backport backend_name = cache_instance.__mo...
AttributeError
dataset/ETHPy150Open Almad/django-sane-testing/djangosanetesting/cache.py/flush_django_cache
9,990
def get_model(self, name): try: return self.models[name] except __HOLE__: return None
KeyError
dataset/ETHPy150Open willhardy/django-seo/rollyourown/seo/options.py/Options.get_model
9,991
def handle(self, *args, **options): try: app, model = args[0].split('.') except __HOLE__: raise CommandError('Expected argument <app>.<model>') self.connection = connections['default'] # XXX: We cant use get_model because its now an abstract model # mode...
ValueError
dataset/ETHPy150Open disqus/sharding-example/sqlshards/management/commands/sqlpartition.py/Command.handle
9,992
def next(self): if self.tried is not None: raise Exception("no feedback received on last value generated") while True: self.tried = self.data[:] # make a copy try: rmd = self.tried.pop(self.i) if len(rmd) == 1 and rmd[0] == "\n": ...
IndexError
dataset/ETHPy150Open blackberry/ALF/alf/reduce.py/FeedbackIter.next
9,993
def generate_temp_url(path, seconds, key, method, absolute=False): """Generates a temporary URL that gives unauthenticated access to the Swift object. :param path: The full path to the Swift object. Example: /v1/AUTH_account/c/o. :param seconds: The amount of time in seconds the temporary URL w...
TypeError
dataset/ETHPy150Open openstack/python-swiftclient/swiftclient/utils.py/generate_temp_url
9,994
def report_traceback(): """ Reports a timestamp and full traceback for a given exception. :return: Full traceback and timestamp. """ try: formatted_lines = traceback.format_exc() now = time.time() return formatted_lines, now except __HOLE__: return None, None
AttributeError
dataset/ETHPy150Open openstack/python-swiftclient/swiftclient/utils.py/report_traceback
9,995
def __next__(self): """ Both ``__next__`` and ``next`` are provided to allow compatibility with python 2 and python 3 and their use of ``iterable.next()`` and ``next(iterable)`` respectively. """ chunk = self.content.read(self.chunk_size) if not chunk: ...
TypeError
dataset/ETHPy150Open openstack/python-swiftclient/swiftclient/utils.py/ReadableToIterable.__next__
9,996
def read(self, size=-1): if self._remaining <= 0: return '' to_read = self._remaining if size < 0 else min(size, self._remaining) chunk = self._readable.read(to_read) self._remaining -= len(chunk) try: self.md5sum.update(chunk) except __HOLE__: ...
TypeError
dataset/ETHPy150Open openstack/python-swiftclient/swiftclient/utils.py/LengthWrapper.read
9,997
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 CollabQ/CollabQ/vendor/django/db/models/fields/related.py/add_lazy_relation
9,998
def get_db_prep_lookup(self, lookup_type, value): # If we are doing a lookup on a Related Field, we must be # comparing object instances. The value should be the PK of value, # not value itself. def pk_trace(value): # Value may be a primary key, or an object held in a relatio...
AttributeError
dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/db/models/fields/related.py/RelatedField.get_db_prep_lookup
9,999
def __get__(self, instance, instance_type=None): if instance is None: return self try: return getattr(instance, self.cache_name) except __HOLE__: params = {'%s__pk' % self.related.field.name: instance._get_pk_val()} rel_obj = self.related.model._ba...
AttributeError
dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/db/models/fields/related.py/SingleRelatedObjectDescriptor.__get__