Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
4,700 | def is_zipfile(filename):
"""Quickly see if file is a ZIP file by checking the magic number."""
try:
fpin = open(filename, "rb")
endrec = _EndRecData(fpin)
fpin.close()
if endrec:
return True # file has correct magic number
except __HOLE__:... | IOError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/zipfile.py/is_zipfile |
4,701 | def __init__(self, file, mode="r", compression=ZIP_STORED, allowZip64=False):
"""Open the ZIP file with mode read "r", write "w" or append "a"."""
if mode not in ("r", "w", "a"):
raise RuntimeError('ZipFile() requires mode "r", "w", or "a"')
if compression == ZIP_STORED:
... | IOError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/zipfile.py/ZipFile.__init__ |
4,702 | def _LookupDiskIndex(self, idx):
"""Looks up uuid or name of disk if necessary."""
try:
return int(idx)
except __HOLE__:
pass
for i, d in enumerate(self.cfg.GetInstanceDisks(self.instance.uuid)):
if d.name == idx or d.uuid == idx:
return i
raise errors.OpPrereqError("Lookup... | ValueError | dataset/ETHPy150Open ganeti/ganeti/lib/cmdlib/instance_set_params.py/LUInstanceSetParams._LookupDiskIndex |
4,703 | def _ModifyDisk(self, idx, disk, params, _):
"""Modifies a disk.
"""
changes = []
if constants.IDISK_MODE in params:
disk.mode = params.get(constants.IDISK_MODE)
changes.append(("disk.mode/%d" % idx, disk.mode))
if constants.IDISK_NAME in params:
disk.name = params.get(constants.... | KeyError | dataset/ETHPy150Open ganeti/ganeti/lib/cmdlib/instance_set_params.py/LUInstanceSetParams._ModifyDisk |
4,704 | def clean_acls(self, req):
if 'swift.clean_acl' in req.environ:
for header in ('x-container-read', 'x-container-write'):
if header in req.headers:
try:
req.headers[header] = \
req.environ['swift.clean_acl'](heade... | ValueError | dataset/ETHPy150Open openstack/swift/swift/proxy/controllers/container.py/ContainerController.clean_acls |
4,705 | def test_creation(self):
rd = self.create_domain(name='130', ip_type='4')
rd.save()
try:
ip = Ip(ip_str="130.193.1.2") # Forget the ip_type
ip.clean_ip()
except __HOLE__, e:
pass
self.assertEqual(ValidationError, type(e))
ip = Ip(ip_... | ValidationError | dataset/ETHPy150Open mozilla/inventory/mozdns/ip/tests.py/SimpleTest.test_creation |
4,706 | def subhelper():
# 8 calls
# 10 ticks total: 8 ticks local, 2 ticks in subfunctions
global ticks
ticks += 2
for i in range(2): # 0
try:
C().foo # 1 x 2
except __HOLE__:
ticks += 3 # 3 x 2 | AttributeError | dataset/ETHPy150Open babble/babble/include/jython/Lib/test/test_profile.py/subhelper |
4,707 | @fbuild.db.caches
def guess_platform(ctx, arch=None):
"""L{guess_platform} returns a platform set that describes the various
features of the specified I{platform}. If I{platform} is I{None}, try to
determine which platform the system is and return that value. If the
platform cannot be determined, return... | KeyError | dataset/ETHPy150Open felix-lang/fbuild/lib/fbuild/builders/platform.py/guess_platform |
4,708 | def to_python(self, value):
"""Convert a MongoDB-compatible type to a Python type.
"""
if isinstance(value, basestring):
return value
if hasattr(value, 'to_python'):
return value.to_python()
is_list = False
if not hasattr(value, 'items'):
... | TypeError | dataset/ETHPy150Open MongoEngine/mongoengine/mongoengine/base/fields.py/ComplexBaseField.to_python |
4,709 | def to_mongo(self, value, **kwargs):
"""Convert a Python type to a MongoDB-compatible type.
"""
Document = _import_class("Document")
EmbeddedDocument = _import_class("EmbeddedDocument")
GenericReferenceField = _import_class("GenericReferenceField")
if isinstance(value, b... | TypeError | dataset/ETHPy150Open MongoEngine/mongoengine/mongoengine/base/fields.py/ComplexBaseField.to_mongo |
4,710 | def validate(self, value):
"""If field is provided ensure the value is valid.
"""
errors = {}
if self.field:
if hasattr(value, 'iteritems') or hasattr(value, 'items'):
sequence = value.iteritems()
else:
sequence = enumerate(value)
... | ValueError | dataset/ETHPy150Open MongoEngine/mongoengine/mongoengine/base/fields.py/ComplexBaseField.validate |
4,711 | def _validate_polygon(self, value, top_level=True):
if not isinstance(value, (list, tuple)):
return 'Polygons must contain list of linestrings'
# Quick and dirty validator
try:
value[0][0][0]
except (__HOLE__, IndexError):
return "Invalid Polygon must... | TypeError | dataset/ETHPy150Open MongoEngine/mongoengine/mongoengine/base/fields.py/GeoJsonBaseField._validate_polygon |
4,712 | def _validate_linestring(self, value, top_level=True):
"""Validates a linestring"""
if not isinstance(value, (list, tuple)):
return 'LineStrings must contain list of coordinate pairs'
# Quick and dirty validator
try:
value[0][0]
except (TypeError, __HOLE_... | IndexError | dataset/ETHPy150Open MongoEngine/mongoengine/mongoengine/base/fields.py/GeoJsonBaseField._validate_linestring |
4,713 | def _validate_multipoint(self, value):
if not isinstance(value, (list, tuple)):
return 'MultiPoint must be a list of Point'
# Quick and dirty validator
try:
value[0][0]
except (__HOLE__, IndexError):
return "Invalid MultiPoint must contain at least on... | TypeError | dataset/ETHPy150Open MongoEngine/mongoengine/mongoengine/base/fields.py/GeoJsonBaseField._validate_multipoint |
4,714 | def _validate_multilinestring(self, value, top_level=True):
if not isinstance(value, (list, tuple)):
return 'MultiLineString must be a list of LineString'
# Quick and dirty validator
try:
value[0][0][0]
except (TypeError, __HOLE__):
return "Invalid Mu... | IndexError | dataset/ETHPy150Open MongoEngine/mongoengine/mongoengine/base/fields.py/GeoJsonBaseField._validate_multilinestring |
4,715 | def _validate_multipolygon(self, value):
if not isinstance(value, (list, tuple)):
return 'MultiPolygon must be a list of Polygon'
# Quick and dirty validator
try:
value[0][0][0][0]
except (__HOLE__, IndexError):
return "Invalid MultiPolygon must conta... | TypeError | dataset/ETHPy150Open MongoEngine/mongoengine/mongoengine/base/fields.py/GeoJsonBaseField._validate_multipolygon |
4,716 | def delete(self, name):
try:
super(BuiltFileStorage, self).delete(name)
except __HOLE__:
name = self.path(name)
if os.path.isdir(name):
os.rmdir(name)
else:
raise | OSError | dataset/ETHPy150Open hzdg/django-staticbuilder/staticbuilder/storage.py/BuiltFileStorage.delete |
4,717 | def detectPthImportedPackages():
if not hasattr(sys.modules["site"], "getsitepackages"):
return ()
pth_imports = set()
for prefix in sys.modules["site"].getsitepackages():
if not Utils.isDir(prefix):
continue
for path, filename in Utils.listDir(prefix):
if ... | OSError | dataset/ETHPy150Open kayhayen/Nuitka/nuitka/importing/PreloadedPackages.py/detectPthImportedPackages |
4,718 | def __getitem__(self, key):
try:
value_record = super(NearCache, self).__getitem__(key)
if value_record.is_expired(self.max_idle_seconds):
super(NearCache, self).__delitem__(key)
raise KeyError
except __HOLE__ as ke:
self._cache_miss +=... | KeyError | dataset/ETHPy150Open hazelcast/hazelcast-python-client/hazelcast/near_cache.py/NearCache.__getitem__ |
4,719 | def get_template_sources(self, template_name, template_dirs=None):
template_name = self.prepare_template_name(template_name)
for loader in self.template_source_loaders:
if hasattr(loader, 'get_template_sources'):
try:
for result in loader.get_template_sour... | UnicodeDecodeError | dataset/ETHPy150Open gregmuellegger/django-mobile/django_mobile/loader.py/Loader.get_template_sources |
4,720 | def _convert_value(value):
"""Parse string as python literal if possible and fallback to string."""
try:
return ast.literal_eval(value)
except (__HOLE__, SyntaxError):
# use as string if nothing else worked
return value | ValueError | dataset/ETHPy150Open IDSIA/sacred/sacred/arg_parser.py/_convert_value |
4,721 | def skip_without(*names):
"""skip a test if some names are not importable"""
@decorator
def skip_without_names(f, *args, **kwargs):
"""decorator to skip tests in the absence of numpy."""
for name in names:
try:
__import__(name)
except __HOLE__:
... | ImportError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/parallel/tests/clienttest.py/skip_without |
4,722 | @classmethod
def convert(cls, value):
if isinstance(value, cls):
return value
try:
return cls(value.upper())
except (__HOLE__, AttributeError):
valids = [cls.VERY_HIGH, cls.HIGH, cls.NORMAL,
cls.LOW, cls.VERY_LOW]
valids =... | ValueError | dataset/ETHPy150Open openstack/taskflow/taskflow/jobs/base.py/JobPriority.convert |
4,723 | def get_logs(self, decode_logs=True):
"""
:param decode_logs: bool, docker by default output logs in simple json structure:
{ "stream": "line" }
if this arg is set to True, it decodes logs to human readable form
:return: str
"""
logs = graceful_chain_get(s... | ValueError | dataset/ETHPy150Open projectatomic/osbs-client/osbs/build/build_response.py/BuildResponse.get_logs |
4,724 | def search_entries(module_list, ops = None, constructors = None, seen = None):
if ops is None: ops = []
if constructors is None: constructors = []
if seen is None: seen = set()
modules = []
for module in module_list:
symbol_name_list = [s for s in dir(module) if not s[0] == '_']
... | TypeError | dataset/ETHPy150Open RDFLib/rdfextras/docs/scripts/gen_oplist.py/search_entries |
4,725 | def payday():
# Wire things up.
# ===============
env = wireup.env()
wireup.db(env)
wireup.billing(env)
# Lazily import the billing module.
# =================================
# This dodges a problem where db in billing is None if we import it from
# gratipay before calling wireu... | KeyboardInterrupt | dataset/ETHPy150Open gratipay/gratipay.com/gratipay/cli.py/payday |
4,726 | def __call__(self):
import zmq
context = zmq.Context()
sock = context.socket(zmq.SUB)
sock.setsockopt(zmq.SUBSCRIBE, '')
sock.connect('tcp://' + self.hostname +':'+str(self.port))
# Get progress via socket
percent = None
while True:
try:
... | KeyboardInterrupt | dataset/ETHPy150Open ioam/holoviews/holoviews/ipython/widgets.py/RemoteProgress.__call__ |
4,727 | def tryToCloseStream(self, out):
try:
# try to close output stream (e.g. file handle)
if out is not None:
out.close()
except __HOLE__:
pass # NOP | IOError | dataset/ETHPy150Open rwl/muntjac/muntjac/terminal/gwt/server/abstract_communication_manager.py/AbstractCommunicationManager.tryToCloseStream |
4,728 | def writeUidlResponce(self, callback, repaintAll, outWriter, window,
analyzeLayouts):
outWriter.write('\"changes\":[')
paintables = None
invalidComponentRelativeSizes = None
paintTarget = JsonPaintTarget(self, outWriter, not repaintAll)
windowCache = self._cur... | AttributeError | dataset/ETHPy150Open rwl/muntjac/muntjac/terminal/gwt/server/abstract_communication_manager.py/AbstractCommunicationManager.writeUidlResponce |
4,729 | def decodeVariableValue(self, encodedValue):
"""Decode encoded burst, record, field and array item separator
characters in a variable value String received from the client.
This protects from separator injection attacks.
@param encodedValue: value to decode
@return: decoded valu... | StopIteration | dataset/ETHPy150Open rwl/muntjac/muntjac/terminal/gwt/server/abstract_communication_manager.py/AbstractCommunicationManager.decodeVariableValue |
4,730 | def printLocaleDeclarations(self, outWriter):
"""Prints the queued (pending) locale definitions to a PrintWriter
in a (UIDL) format that can be sent to the client and used there in
formatting dates, times etc.
"""
# Send locale informations to client
outWriter.write(', \"... | KeyError | dataset/ETHPy150Open rwl/muntjac/muntjac/terminal/gwt/server/abstract_communication_manager.py/AbstractCommunicationManager.printLocaleDeclarations |
4,731 | def CheckAccess(self, token):
"""Enforce a dual approver policy for access."""
namespace, _ = self.urn.Split(2)
if namespace != "ACL":
raise access_control.UnauthorizedAccess(
"Approval object has invalid urn %s." % self.urn,
subject=self.urn, requested_access=token.requested_acce... | IOError | dataset/ETHPy150Open google/grr/grr/lib/aff4_objects/security.py/ApprovalWithApproversAndReason.CheckAccess |
4,732 | @flow.StateHandler()
def Start(self):
"""Create the Approval object and notify the Approval Granter."""
approval_urn = self.BuildApprovalUrn()
subject_title = self.BuildSubjectTitle()
access_urn = self.BuildAccessUrl()
# This object must already exist.
try:
approval_request = aff4.FACTO... | IOError | dataset/ETHPy150Open google/grr/grr/lib/aff4_objects/security.py/GrantApprovalWithReasonFlow.Start |
4,733 | @systemcall
def process_input(self):
"""Attempt to read a single Record from the socket and process it."""
# Currently, any children Request process notify this Connection
# that it is no longer needed by closing the Connection's socket.
# We need to put a timeout on select, otherwis... | ValueError | dataset/ETHPy150Open kdart/pycopia/core/pycopia/inet/fcgi.py/Connection.process_input |
4,734 | def _setupSocket(self):
if self._bindAddress is None: # Run as a normal FastCGI?
sock = socket.fromfd(FCGI_LISTENSOCK_FILENO, socket.AF_INET,
socket.SOCK_STREAM)
try:
sock.getpeername()
except socket.error, e:
... | OSError | dataset/ETHPy150Open kdart/pycopia/core/pycopia/inet/fcgi.py/FCGIServer._setupSocket |
4,735 | def pandas_dtype(dtype):
"""
Converts input into a pandas only dtype object or a numpy dtype object.
Parameters
----------
dtype : object to be converted
Returns
-------
np.dtype or a pandas dtype
"""
if isinstance(dtype, string_types):
try:
return DatetimeT... | TypeError | dataset/ETHPy150Open pydata/pandas/pandas/types/api.py/pandas_dtype |
4,736 | def testCannotEraseFile(self):
def failedUnlink(path):
if '/contents0' in path:
raise OSError(errno.EACCES, 'Permission denied', path)
origUnlink(path)
origUnlink = os.unlink
os.unlink = failedUnlink
try:
foo = self.addComponent('foo:... | OSError | dataset/ETHPy150Open sassoftware/conary/conary_test/updatetest.py/UpdateTest.testCannotEraseFile |
4,737 | def _getOpenFiles(self):
fddir = os.path.join('/proc', str(os.getpid()), 'fd')
ret = []
for fdnum in os.listdir(fddir):
try:
rf = os.readlink(os.path.join(fddir, fdnum))
except __HOLE__:
continue
if rf.startswith(self.tmpDir):
... | OSError | dataset/ETHPy150Open sassoftware/conary/conary_test/updatetest.py/UpdateTest._getOpenFiles |
4,738 | def testGroupByDefault(self):
# CNY-1476
def fooVer():
return [x.asString() for x in client.db.getTroveVersionList('group-foo')]
for v in [1, 2]:
self.addComponent('foo:lib', str(v), filePrimer=4*v)
groupFooContents = ['foo:lib']
if v == 2:
... | AssertionError | dataset/ETHPy150Open sassoftware/conary/conary_test/updatetest.py/UpdateTest.testGroupByDefault |
4,739 | def _get_dates_loc(self, dates, date):
if hasattr(dates, 'indexMap'): # 0.7.x
date = dates.indexMap[date]
else:
date = dates.get_loc(date)
try: # pandas 0.8.0 returns a boolean array
len(date)
from numpy import where
dat... | TypeError | dataset/ETHPy150Open statsmodels/statsmodels/statsmodels/tsa/base/tsa_model.py/TimeSeriesModel._get_dates_loc |
4,740 | def _get_predict_start(self, start):
"""
Returns the index of the given start date. Subclasses should define
default behavior for start = None. That isn't handled here.
Start can be a string or an integer if self.data.dates is None.
"""
dates = self.data.dates
if... | KeyError | dataset/ETHPy150Open statsmodels/statsmodels/statsmodels/tsa/base/tsa_model.py/TimeSeriesModel._get_predict_start |
4,741 | def _get_predict_end(self, end):
"""
See _get_predict_start for more information. Subclasses do not
need to define anything for this.
"""
out_of_sample = 0 # will be overwritten if needed
if end is None: # use data for ARIMA - endog changes
end = len(self.dat... | KeyError | dataset/ETHPy150Open statsmodels/statsmodels/statsmodels/tsa/base/tsa_model.py/TimeSeriesModel._get_predict_end |
4,742 | def _make_predict_dates(self):
data = self.data
dtstart = data.predict_start
dtend = data.predict_end
freq = data.freq
if freq is not None:
pandas_freq = _freq_to_pandas[freq]
try:
from pandas import DatetimeIndex
dates = D... | ImportError | dataset/ETHPy150Open statsmodels/statsmodels/statsmodels/tsa/base/tsa_model.py/TimeSeriesModel._make_predict_dates |
4,743 | def get_by_project_and_user(self, context, project_id, user_id, resource):
self.called.append(('get_by_project_and_user',
context, project_id, user_id, resource))
try:
return self.by_user[user_id][resource]
except __HOLE__:
raise exception.Proj... | KeyError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/tests/unit/test_quota.py/FakeDriver.get_by_project_and_user |
4,744 | def get_by_project(self, context, project_id, resource):
self.called.append(('get_by_project', context, project_id, resource))
try:
return self.by_project[project_id][resource]
except __HOLE__:
raise exception.ProjectQuotaNotFound(project_id=project_id) | KeyError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/tests/unit/test_quota.py/FakeDriver.get_by_project |
4,745 | def get_by_class(self, context, quota_class, resource):
self.called.append(('get_by_class', context, quota_class, resource))
try:
return self.by_class[quota_class][resource]
except __HOLE__:
raise exception.QuotaClassNotFound(class_name=quota_class) | KeyError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/tests/unit/test_quota.py/FakeDriver.get_by_class |
4,746 | def run(self, exe='monolithic'):
"""
Make system call to run one or more of the stand-alone executables,
writing a log file to the folder containing the input file.
"""
if self.feffinp == None:
raise Exception("no feff.inp file was specified")
if not isfile(... | NameError | dataset/ETHPy150Open xraypy/xraylarch/plugins/xafs/feffrunner.py/FeffRunner.run |
4,747 | @app.route('/add', methods=['POST'])
def add():
storm_ = app.get_storm()
try:
name = request.json['name']
connection_uri = request.json['connection_uri']
if 'id_file' in request.json:
id_file = request.json['id_file']
else:
id_file = ''
if '@' in... | KeyError | dataset/ETHPy150Open emre/storm/storm/web.py/add |
4,748 | @app.route('/edit', methods=['PUT'])
def edit():
storm_ = app.get_storm()
try:
name = request.json['name']
connection_uri = request.json['connection_uri']
if 'id_file' in request.json:
id_file = request.json['id_file']
else:
id_file = ''
user, ho... | KeyError | dataset/ETHPy150Open emre/storm/storm/web.py/edit |
4,749 | @app.route('/delete', methods=['POST'])
def delete():
storm_ = app.get_storm()
try:
name = request.json['name']
storm_.delete_entry(name)
return response()
except __HOLE__ as exc:
return jsonify(message=exc.message), 404
except (TypeError, ValueError):
return res... | ValueError | dataset/ETHPy150Open emre/storm/storm/web.py/delete |
4,750 | def pid_from_str(s):
id_ = -1
try:
id_ = int(s)
except __HOLE__:
pass
return id_ | ValueError | dataset/ETHPy150Open kashefy/nideep/nideep/eval/log_utils.py/pid_from_str |
4,751 | def process(self, d):
if d is None:
# Special case for when no doc could be found and that is OK
return None
try:
value = _lookup_keys(self.keys, d)
except __HOLE__:
if self.if_missing is not None:
Exc, args = self.if_missing[0], s... | KeyError | dataset/ETHPy150Open wiki-ai/revscoring/revscoring/extractors/api/util.py/key.process |
4,752 | def _lookup_keys(keys, d):
if isinstance(keys, str) or not hasattr(keys, "__iter__"):
keys = [keys]
try:
for key in keys:
d = d[key]
except __HOLE__:
raise KeyError(keys)
return d | KeyError | dataset/ETHPy150Open wiki-ai/revscoring/revscoring/extractors/api/util.py/_lookup_keys |
4,753 | def run_async(self):
log_output = self.git(
"log",
"-{}".format(self._limit) if self._limit else None,
"--skip={}".format(self._pagination) if self._pagination else None,
"--author={}".format(self._author) if self._author else None,
'--format=%h%n%H%n%... | ValueError | dataset/ETHPy150Open divmain/GitSavvy/core/commands/log.py/GsLogCommand.run_async |
4,754 | def get_pyserial_version(self, pyserial_version):
"""! Retrieve pyserial module version
@return Returns float with pyserial module number
"""
version = 3.0
m = self.re_float.search(pyserial_version)
if m:
try:
version = float(m.group(0))
... | ValueError | dataset/ETHPy150Open ARMmbed/htrun/mbed_host_tests/host_tests_plugins/module_reset_mbed.py/HostTestPluginResetMethod_Mbed.get_pyserial_version |
4,755 | def set_content_length(self):
"""Compute Content-Length or switch to chunked encoding if possible"""
try:
blocks = len(self.result)
except (TypeError, __HOLE__, NotImplementedError):
pass
else:
if blocks==1:
self.headers['Content-Length... | AttributeError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/core/servers/basehttp.py/ServerHandler.set_content_length |
4,756 | def __call__(self, environ, start_response):
import os.path
# Ignore requests that aren't under ADMIN_MEDIA_PREFIX. Also ignore
# all requests if ADMIN_MEDIA_PREFIX isn't a relative URL.
if self.media_url.startswith('http://') or self.media_url.startswith('https://') \
or no... | IOError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/core/servers/basehttp.py/AdminMediaHandler.__call__ |
4,757 | def get_instance_port(self, instance_id):
"""Returns the port of the HTTP server for an instance."""
try:
instance_id = int(instance_id)
except __HOLE__:
raise request_info.InvalidInstanceIdError()
with self._condition:
if 0 <= instance_id < len(self._instances):
wsgi_servr = s... | ValueError | dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/tools/devappserver2/module.py/ManualScalingModule.get_instance_port |
4,758 | def get_instance(self, instance_id):
"""Returns the instance with the provided instance ID."""
try:
with self._condition:
return self._instances[int(instance_id)]
except (ValueError, __HOLE__):
raise request_info.InvalidInstanceIdError() | IndexError | dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/tools/devappserver2/module.py/ManualScalingModule.get_instance |
4,759 | def get_instance_port(self, instance_id):
"""Returns the port of the HTTP server for an instance."""
try:
instance_id = int(instance_id)
except __HOLE__:
raise request_info.InvalidInstanceIdError()
with self._condition:
if 0 <= instance_id < len(self._instances):
wsgi_servr = s... | ValueError | dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/tools/devappserver2/module.py/BasicScalingModule.get_instance_port |
4,760 | def get_instance(self, instance_id):
"""Returns the instance with the provided instance ID."""
try:
with self._condition:
return self._instances[int(instance_id)]
except (ValueError, __HOLE__):
raise request_info.InvalidInstanceIdError() | IndexError | dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/tools/devappserver2/module.py/BasicScalingModule.get_instance |
4,761 | def Browser(driver_name='firefox', *args, **kwargs):
"""
Returns a driver instance for the given name.
When working with ``firefox``, it's possible to provide a profile name
and a list of extensions.
If you don't provide any driver_name, then ``firefox`` will be used.
If there is no driver re... | KeyError | dataset/ETHPy150Open cobrateam/splinter/splinter/browser.py/Browser |
4,762 | def FindFileByName(self, file_name):
"""Gets a FileDescriptor by file name.
Args:
file_name: The path to the file to get a descriptor for.
Returns:
A FileDescriptor for the named file.
Raises:
KeyError: if the file can not be found in the pool.
"""
try:
return self._f... | KeyError | dataset/ETHPy150Open sklearn-theano/sklearn-theano/sklearn_theano/externals/google/protobuf/descriptor_pool.py/DescriptorPool.FindFileByName |
4,763 | def FindFileContainingSymbol(self, symbol):
"""Gets the FileDescriptor for the file containing the specified symbol.
Args:
symbol: The name of the symbol to search for.
Returns:
A FileDescriptor that contains the specified symbol.
Raises:
KeyError: if the file can not be found in th... | KeyError | dataset/ETHPy150Open sklearn-theano/sklearn-theano/sklearn_theano/externals/google/protobuf/descriptor_pool.py/DescriptorPool.FindFileContainingSymbol |
4,764 | def get_item_types(self):
if hasattr(self, "_item_types"):
return self._item_types
url = self._build_url('itemtypes')
options = {
'apikey': self._api_key,
'tenantid': self._tenant
}
try:
response = self._fetch_response(url, params=o... | KeyError | dataset/ETHPy150Open snowball-one/django-oscar-easyrec/easyrec/gateway.py/EasyRec.get_item_types |
4,765 | def __init__(self, mapping=(), fvars={}, autoreload=None):
if autoreload is None:
autoreload = web.config.get('debug', False)
self.init_mapping(mapping)
self.fvars = fvars
self.processors = []
self.add_processor(loadhook(self._load))
self.add_processo... | ImportError | dataset/ETHPy150Open joxeankoret/nightmare/runtime/web/application.py/application.__init__ |
4,766 | def handle_with_processors(self):
def process(processors):
try:
if processors:
p, processors = processors[0], processors[1:]
return p(lambda: process(processors))
else:
return self.handle()
except... | SystemExit | dataset/ETHPy150Open joxeankoret/nightmare/runtime/web/application.py/application.handle_with_processors |
4,767 | def wsgifunc(self, *middleware):
"""Returns a WSGI-compatible function for this application."""
def peep(iterator):
"""Peeps into an iterator by doing an iteration
and returns an equivalent iterator.
"""
# wsgi requires the headers first
# so w... | StopIteration | dataset/ETHPy150Open joxeankoret/nightmare/runtime/web/application.py/application.wsgifunc |
4,768 | def cgirun(self, *middleware):
"""
Return a CGI handler. This is mostly useful with Google App Engine.
There you can just do:
main = app.cgirun()
"""
wsgiapp = self.wsgifunc(*middleware)
try:
from google.appengine.ext.webapp.util import r... | ImportError | dataset/ETHPy150Open joxeankoret/nightmare/runtime/web/application.py/application.cgirun |
4,769 | def autodelegate(prefix=''):
"""
Returns a method that takes one argument and calls the method named prefix+arg,
calling `notfound()` if there isn't one. Example:
urls = ('/prefs/(.*)', 'prefs')
class prefs:
GET = autodelegate('GET_')
def GET_password(self): pass
... | TypeError | dataset/ETHPy150Open joxeankoret/nightmare/runtime/web/application.py/autodelegate |
4,770 | def check(self, mod):
# jython registers java packages as modules but they either
# don't have a __file__ attribute or its value is None
if not (mod and hasattr(mod, '__file__') and mod.__file__):
return
try:
mtime = os.stat(mod.__file__).st_mtime
except... | OSError | dataset/ETHPy150Open joxeankoret/nightmare/runtime/web/application.py/Reloader.check |
4,771 | def accept_ride_request(self,person):
print "#" * 80
print self.username + ": ACCEPTING A RIDE REQUEST..."
print "#" * 80
if isinstance(person,str):
username = person
else:
try:
username = person['username']
except __HOLE__:
... | KeyError | dataset/ETHPy150Open dgraziotin/dycapo/tests/classes.py/Driver.accept_ride_request |
4,772 | def for_name(fq_name, recursive=False):
"""Find class/function/method specified by its fully qualified name.
Fully qualified can be specified as:
* <module_name>.<class_name>
* <module_name>.<function_name>
* <module_name>.<class_name>.<method_name> (an unbound method will be
returned in this cas... | ImportError | dataset/ETHPy150Open livid/v2ex/mapreduce/util.py/for_name |
4,773 | def ugly_tree_creation_test():
tree = LookupTree()
error_values = []
for i in range(10000):
tree.insert(hash(i), (i, i))
n = 0
try:
for k, v in tree:
n += 1
if n != i+1:
error_values.append(i)
except __HOLE__:
... | TypeError | dataset/ETHPy150Open zhemao/funktown/unittest.py/ugly_tree_creation_test |
4,774 | def _select_binary_base_path(self, supportdir, version, name, uname_func=None):
"""Calculate the base path.
Exposed for associated unit tests.
:param supportdir: the path used to make a path under --pants_bootstrapdir.
:param version: the version number of the tool used to make a path under --pants-boo... | KeyError | dataset/ETHPy150Open pantsbuild/pants/src/python/pants/binaries/binary_util.py/BinaryUtil._select_binary_base_path |
4,775 | @contextmanager
def _select_binary_stream(self, name, binary_path, fetcher=None):
"""Select a binary matching the current os and architecture.
:param string binary_path: The path to the binary to fetch.
:param fetcher: Optional argument used only for testing, to 'pretend' to open urls.
:returns: a 's... | IOError | dataset/ETHPy150Open pantsbuild/pants/src/python/pants/binaries/binary_util.py/BinaryUtil._select_binary_stream |
4,776 | def ranking(self, dimfun, groupby, ftarget=10**-8):
"""
Produce a set of function evaluation ranks over all algorithms
and strategies.
Returns a set of rows where each row contains a budget as first
element and ranks for individual algorithms and strategies
as the second... | IndexError | dataset/ETHPy150Open pasky/cocopf/pproc.py/PortfolioDataSets.ranking |
4,777 | def resolve_fid(fid):
"""
Convert a given "function id" string to a number of list of numbers,
with the ability to resolve symbolic names for a variety of function
classes.
XXX: So far, the classes are fixed as determined on the scipy+CMA
portfolio. Instead, determine them dynamically.
"""
... | ValueError | dataset/ETHPy150Open pasky/cocopf/pproc.py/resolve_fid |
4,778 | def maybe_asynchronous(f):
def wrapped(*args, **kwargs):
try:
callback = kwargs.pop('callback')
except __HOLE__:
callback = None
result = f(*args, **kwargs)
if callback is not None:
callback(result)
else:
return result
ret... | KeyError | dataset/ETHPy150Open Lothiraldan/ZeroServices/zeroservices/utils.py/maybe_asynchronous |
4,779 | @property
def username(self):
try:
return self._thread_local.user
except __HOLE__:
return DEFAULT_USER.get() | AttributeError | dataset/ETHPy150Open cloudera/hue/desktop/libs/hadoop/src/hadoop/yarn/mapreduce_api.py/MapreduceApi.username |
4,780 | def test_convolutional_network():
"""Test smaller version of convolutional_network.ipynb"""
skip.skip_if_no_data()
yaml_file_path = os.path.abspath(os.path.join(os.path.dirname(__file__),
'..'))
save_path = os.path.dirname(os.path.realpath(__file__))
... | OSError | dataset/ETHPy150Open lisa-lab/pylearn2/pylearn2/scripts/tutorials/convolutional_network/tests/test_convnet.py/test_convolutional_network |
4,781 | def _call_agent(session, instance, vm_ref, method, addl_args=None,
timeout=None, success_codes=None):
"""Abstracts out the interaction with the agent xenapi plugin."""
if addl_args is None:
addl_args = {}
if timeout is None:
timeout = CONF.xenserver.agent_timeout
if succe... | TypeError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/virt/xenapi/agent.py/_call_agent |
4,782 | def should_use_agent(instance):
sys_meta = utils.instance_sys_meta(instance)
if USE_AGENT_SM_KEY not in sys_meta:
return CONF.xenserver.use_agent_default
else:
use_agent_raw = sys_meta[USE_AGENT_SM_KEY]
try:
return strutils.bool_from_string(use_agent_raw, strict=True)
... | ValueError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/virt/xenapi/agent.py/should_use_agent |
4,783 | def update_proxy_settings(self, *args, **kwargs):
"""
When the network configuration changes, this updates the SOCKS proxy
settings based the current IP address(es)
"""
# Open a SystemConfiguration preferences session:
sc_prefs = SCPreferences()
# We want to enab... | RuntimeError | dataset/ETHPy150Open MacSysadmin/pymacadmin/examples/crankd/socks-proxy/ProxyManager.py/ProxyManager.update_proxy_settings |
4,784 | @db.listens_for(db.Session, "after_flush")
def store_purge_keys(config, session, flush_context):
cache_keys = config.registry["cache_keys"]
# We'll (ab)use the session.info dictionary to store a list of pending
# purges to the session.
purges = session.info.setdefault("warehouse.cache.origin.purges", s... | KeyError | dataset/ETHPy150Open pypa/warehouse/warehouse/cache/origin/__init__.py/store_purge_keys |
4,785 | @db.listens_for(db.Session, "after_commit")
def execute_purge(config, session):
purges = session.info.pop("warehouse.cache.origin.purges", set())
try:
cacher_factory = config.find_service_factory(IOriginCache)
except __HOLE__:
return
cacher = cacher_factory(None, config)
cacher.pur... | ValueError | dataset/ETHPy150Open pypa/warehouse/warehouse/cache/origin/__init__.py/execute_purge |
4,786 | def origin_cache(seconds, keys=None, stale_while_revalidate=None,
stale_if_error=None):
if keys is None:
keys = []
def inner(view):
@functools.wraps(view)
def wrapped(context, request):
cache_keys = request.registry["cache_keys"]
context_keys = ... | ValueError | dataset/ETHPy150Open pypa/warehouse/warehouse/cache/origin/__init__.py/origin_cache |
4,787 | def __iter__(self):
while True:
if self._current_iter:
for o in self._current_iter:
yield o
try:
k_range = self._key_ranges.next()
self._current_iter = self._key_range_iter_cls(k_range,
self._query_spec)
excep... | StopIteration | dataset/ETHPy150Open GoogleCloudPlatform/appengine-mapreduce/python/src/mapreduce/datastore_range_iterators.py/_KeyRangesIterator.__iter__ |
4,788 | @defer.inlineCallbacks
def call_py(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in python
object format or None if there is none.
This method is same as call() except the return value is a python
object instead of JSON string. This method ... | ValueError | dataset/ETHPy150Open flowroute/txjason/txjason/service.py/JSONRPCService.call_py |
4,789 | def __getattribute__(self, attrname):
# get attribute of the SoftLink itself
if (attrname in SoftLink._link_attrnames
or attrname[:3] in SoftLink._link_attrprefixes):
return object.__getattribute__(self, attrname)
# get attribute of the target node
elif not self... | AttributeError | dataset/ETHPy150Open PyTables/PyTables/tables/link.py/SoftLink.__getattribute__ |
4,790 | def _run_worker():
LOG.info('(PID=%s) Results tracker started.', os.getpid())
tracker = resultstracker.get_tracker()
try:
tracker.start(wait=True)
except (KeyboardInterrupt, __HOLE__):
LOG.info('(PID=%s) Results tracker stopped.', os.getpid())
tracker.shutdown()
except:
... | SystemExit | dataset/ETHPy150Open StackStorm/st2/st2actions/st2actions/cmd/st2resultstracker.py/_run_worker |
4,791 | def main():
try:
_setup()
return _run_worker()
except __HOLE__ as exit_code:
sys.exit(exit_code)
except:
LOG.exception('(PID=%s) Results tracker quit due to exception.', os.getpid())
return 1
finally:
_teardown() | SystemExit | dataset/ETHPy150Open StackStorm/st2/st2actions/st2actions/cmd/st2resultstracker.py/main |
4,792 | def backup_config_file(env, suffix):
try:
backup, f = create_unique_file(env.config.filename + suffix)
f.close()
shutil.copyfile(env.config.filename, backup)
env.log.info("Saved backup of configuration file in %s", backup)
except __HOLE__ as e:
env.log.warn("Couldn't save... | IOError | dataset/ETHPy150Open edgewall/trac/trac/upgrades/__init__.py/backup_config_file |
4,793 | def __pysal_choro(values, scheme, k=5):
""" Wrapper for choropleth schemes from PySAL for use with plot_dataframe
Parameters
----------
values
Series to be plotted
scheme
pysal.esda.mapclassify classificatin scheme
['Equal_interval'|'Quantiles'|... | ImportError | dataset/ETHPy150Open geopandas/geopandas/geopandas/plotting.py/__pysal_choro |
4,794 | def authenticateUserAPOP(self, user, digest):
# Override the default lookup scheme to allow virtual domains
user, domain = self.lookupDomain(user)
try:
portal = self.service.lookupPortal(domain)
except __HOLE__:
return defer.fail(cred.error.UnauthorizedLogin())
... | KeyError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/mail/protocols.py/VirtualPOP3.authenticateUserAPOP |
4,795 | def authenticateUserPASS(self, user, password):
user, domain = self.lookupDomain(user)
try:
portal = self.service.lookupPortal(domain)
except __HOLE__:
return defer.fail(cred.error.UnauthorizedLogin())
else:
return portal.login(
cred.cr... | KeyError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/mail/protocols.py/VirtualPOP3.authenticateUserPASS |
4,796 | def lookupDomain(self, user):
try:
user, domain = user.split(self.domainSpecifier, 1)
except __HOLE__:
domain = ''
if domain not in self.service.domains:
raise pop3.POP3Error("no such domain %s" % domain)
return user, domain | ValueError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/mail/protocols.py/VirtualPOP3.lookupDomain |
4,797 | def main():
try:
#Read config file
settings=Settings()
#Set up logger
logger=Logger(settings)
#Create scanner
server=Server(settings,logger)
#Begin scanning
server.start()
except __HOLE__:
server.stop() | KeyboardInterrupt | dataset/ETHPy150Open SteveAbb/Vestigo/Vestigo Base/vestigo_base.py/main |
4,798 | def find_applications(self):
self.applications = {}
for application in all_apps():
if self.local_names and not application in self.local_names:
continue
try:
search_module_name = '%s.search' % application.application_name
... | ImportError | dataset/ETHPy150Open mollyproject/mollyproject/molly/apps/search/providers/application_search.py/ApplicationSearchProvider.find_applications |
4,799 | def get_queryset(self):
request = self.request
# Allow pages to be filtered to a specific type
try:
models = page_models_from_string(request.GET.get('type', 'wagtailcore.Page'))
except (LookupError, __HOLE__):
raise BadRequestError("type doesn't exist")
... | ValueError | dataset/ETHPy150Open torchbox/wagtail/wagtail/api/v2/endpoints.py/PagesAPIEndpoint.get_queryset |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.