Unnamed: 0
int64 0
10k
| function
stringlengths 79
138k
| label
stringclasses 20
values | info
stringlengths 42
261
|
|---|---|---|---|
8,200
|
@patch('prestoadmin.main.crawl')
@patch('prestoadmin.fabric_patches.crawl')
def test_too_many_args_has_optionals(self, crawl_mock, crawl_mock_main):
def task(optional=None):
"""This is my task"""
pass
crawl_mock.return_value = task
crawl_mock_main.return_value = task
state.env.nodeps = False
try:
main.run_tasks([('my task', ['arg1', 'arg2'], {}, [], [], [])])
except __HOLE__ as e:
self.assertEqual(e.code, 2)
self.assertEqual('Incorrect number of arguments to task.\n\n'
'Displaying detailed information for task '
'\'my task\':\n\n This is my task\n\n',
self.test_stdout.getvalue())
|
SystemExit
|
dataset/ETHPy150Open prestodb/presto-admin/tests/unit/test_main.py/TestMain.test_too_many_args_has_optionals
|
8,201
|
@patch('prestoadmin.main.crawl')
@patch('prestoadmin.fabric_patches.crawl')
def test_too_few_args_has_optionals(self, crawl_mock, crawl_mock_main):
def task(arg1, optional=None):
"""This is my task"""
pass
crawl_mock.return_value = task
crawl_mock_main.return_value = task
state.env.nodeps = False
try:
main.run_tasks([('my task', [], {}, [], [], [])])
except __HOLE__ as e:
self.assertEqual(e.code, 2)
self.assertEqual('Incorrect number of arguments to task.\n\n'
'Displaying detailed information for task '
'\'my task\':\n\n This is my task\n\n',
self.test_stdout.getvalue())
|
SystemExit
|
dataset/ETHPy150Open prestodb/presto-admin/tests/unit/test_main.py/TestMain.test_too_few_args_has_optionals
|
8,202
|
@patch('prestoadmin.main.load_config', side_effect=mock_load_topology())
def test_nodeps_check(self, unused_mock_load):
env.nodeps = True
try:
main.main(['topology', 'show', '--nodeps'])
except __HOLE__ as e:
self.assertEqual(e.code, 2)
self.assertTrue('Invalid argument --nodeps to task: topology.show\n'
in self.test_stderr.getvalue())
self.assertTrue('Displaying detailed information for task '
'\'topology show\':\n\n Shows the current topology '
'configuration for the cluster (including the\n '
'coordinators, workers, SSH port, and SSH username)'
'\n\n' in self.test_stdout.getvalue())
|
SystemExit
|
dataset/ETHPy150Open prestodb/presto-admin/tests/unit/test_main.py/TestMain.test_nodeps_check
|
8,203
|
def get_zk_locations_string():
""" Returns the ZooKeeper connection host string.
Returns:
A string containing one or more host:port listings, separated by commas.
None is returned if there was a problem getting the location string.
"""
try:
info = file_io.read(constants.ZK_LOCATIONS_JSON_FILE)
zk_json = json.loads(info)
return ":2181,".join(zk_json['locations']) + ":2181"
except IOError, io_error:
logging.exception(io_error)
return constants.ZK_DEFAULT_CONNECTION_STR
except ValueError, value_error:
logging.exception(value_error)
return constants.ZK_DEFAULT_CONNECTION_STR
except TypeError, type_error:
logging.exception(type_error)
return constants.ZK_DEFAULT_CONNECTION_STR
except __HOLE__, key_error:
logging.exception(key_error)
return constants.ZK_DEFAULT_CONNECTION_STR
|
KeyError
|
dataset/ETHPy150Open AppScale/appscale/lib/appscale_info.py/get_zk_locations_string
|
8,204
|
def get_zk_node_ips():
""" Returns a list of zookeeper node IPs.
Returns:
A list containing the hosts that run zookeeper roles in the current
AppScale deployment.
"""
try:
info = file_io.read(constants.ZK_LOCATIONS_JSON_FILE)
zk_json = json.loads(info)
return zk_json['locations']
except __HOLE__, io_error:
logging.exception(io_error)
return []
except ValueError, value_error:
logging.exception(value_error)
return []
except TypeError, type_error:
logging.exception(type_error)
return []
except KeyError, key_error:
logging.exception(key_error)
return []
|
IOError
|
dataset/ETHPy150Open AppScale/appscale/lib/appscale_info.py/get_zk_node_ips
|
8,205
|
def get_search_location():
""" Returns the IP and port of where the search service is running.
Returns:
A str, the IP and port in the format: IP:PORT. Empty string if the service
is not available.
"""
try:
return file_io.read(constants.SEARCH_FILE_LOC).rstrip()
except __HOLE__:
logging.warning("Search role is not configured.")
return ""
|
IOError
|
dataset/ETHPy150Open AppScale/appscale/lib/appscale_info.py/get_search_location
|
8,206
|
def _service_is_sysv(name):
'''
Return True if the service is a System V service (includes those managed by
chkconfig); otherwise return False.
'''
try:
# Look for user-execute bit in file mode.
return bool(os.stat(
os.path.join('/etc/init.d', name)).st_mode & stat.S_IXUSR)
except __HOLE__:
return False
|
OSError
|
dataset/ETHPy150Open saltstack/salt/salt/modules/rh_service.py/_service_is_sysv
|
8,207
|
def _sysv_services():
'''
Return list of sysv services.
'''
_services = []
output = __salt__['cmd.run'](['chkconfig', '--list'], python_shell=False)
for line in output.splitlines():
comps = line.split()
try:
if comps[1].startswith('0:'):
_services.append(comps[0])
except __HOLE__:
continue
# Return only the services that have an initscript present
return [x for x in _services if _service_is_sysv(x)]
|
IndexError
|
dataset/ETHPy150Open saltstack/salt/salt/modules/rh_service.py/_sysv_services
|
8,208
|
def get_router():
"""Return router defined by RAPIDSMS_ROUTER setting."""
router = getattr(settings, 'RAPIDSMS_ROUTER',
'rapidsms.router.blocking.BlockingRouter')
if isinstance(router, string_types):
try:
router = import_class(router)()
except __HOLE__ as e:
raise ImproperlyConfigured(e)
return router
|
ImportError
|
dataset/ETHPy150Open rapidsms/rapidsms/rapidsms/router/api.py/get_router
|
8,209
|
@login_required
@ajax_only
def gallery_image_delete(request, project_image_id):
project_image = get_object_or_404(ProjectImage, id=project_image_id)
try:
project_step = project_image.projectstep_set.all()[0]
except __HOLE__:
# If the image doesn't belong to a project step, no need to check for
# permission (and it isn't possible)
pass
else:
if not project_step.is_editable(request):
return HttpResponseForbidden('You are not the owner of this image.')
# Remove the actual file, then the database record and return True
project_image.file.delete()
project_image.delete()
return AjaxResponse(request, True)
|
IndexError
|
dataset/ETHPy150Open python/raspberryio/raspberryio/project/views.py/gallery_image_delete
|
8,210
|
def subst(self, string, dictionary=None):
"""
Substitutes (via the format operator) the values in the specified
dictionary into the specified command.
The command can be an (action, string) tuple. In all cases, we
perform substitution on strings and don't worry if something isn't
a string. (It's probably a Python function to be executed.)
"""
if dictionary is None:
dictionary = self._subst_dictionary
if dictionary:
try:
string = string % dictionary
except __HOLE__:
pass
return string
|
TypeError
|
dataset/ETHPy150Open adblockplus/gyp/gyptest.py/CommandRunner.subst
|
8,211
|
def getitem(self, obj, argument):
"""Subscribe an object from sandboxed code."""
try:
return obj[argument]
except (TypeError, LookupError):
if isinstance(argument, basestring):
try:
attr = str(argument)
except Exception:
pass
else:
try:
value = getattr(obj, attr)
except __HOLE__:
pass
else:
if self.is_safe_attribute(obj, argument, value):
return value
return self.unsafe_undefined(obj, argument)
return self.undefined(obj=obj, name=argument)
|
AttributeError
|
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/jinja2-2.6/jinja2/sandbox.py/SandboxedEnvironment.getitem
|
8,212
|
def getattr(self, obj, attribute):
"""Subscribe an object from sandboxed code and prefer the
attribute. The attribute passed *must* be a bytestring.
"""
try:
value = getattr(obj, attribute)
except __HOLE__:
try:
return obj[attribute]
except (TypeError, LookupError):
pass
else:
if self.is_safe_attribute(obj, attribute, value):
return value
return self.unsafe_undefined(obj, attribute)
return self.undefined(obj=obj, name=attribute)
|
AttributeError
|
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/jinja2-2.6/jinja2/sandbox.py/SandboxedEnvironment.getattr
|
8,213
|
def bufconvert(fmt, nums):
buf = io.BytesIO()
bufstack = []
fmt = str(fmt)
while len(fmt) > 0:
step, fmt = fmt[0], fmt[1:]
if step == '{':
bufstack.append(buf)
buf = io.BytesIO()
continue
if step == '}':
bufstack[-1].write(buf.getvalue())
buf = bufstack.pop()
continue
if step == ':':
# transform
step, fmt = fmt[0], fmt[1:]
buf = buftransform(buf, step)
continue
if step == '%':
# urldecode
step, fmt = fmt[0:2], fmt[2:]
# print '%:', repr(step), 'remain:', repr(fmt)
buf.write(chr(int(step, 16)))
continue
if step in ("'", '"'):
step, fmt = fmt.split(step, 1)
buf.write(step.encode('UTF-8'))
continue
try:
step = out_ops[step]
except __HOLE__:
raise KeyError('Unsupported output format', step)
step(buf, nums.pop(0))
assert len(bufstack) == 0, 'Too many buffers on stack'
return buf
|
KeyError
|
dataset/ETHPy150Open blixt/py-starbound/sbon-numconv.py/bufconvert
|
8,214
|
def makeClone(self):
try:
# Using star dictionary arguments here for generic use.
result = self.__class__(
source_ref = self.source_ref,
**self.getDetails()
)
except __HOLE__:
print("Problem cloning", self.__class__)
raise
effective_source_ref = self.getCompatibleSourceReference()
if effective_source_ref is not self.source_ref:
result.setCompatibleSourceReference(effective_source_ref)
return result
|
TypeError
|
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/nodes/NodeBases.py/NodeBase.makeClone
|
8,215
|
def makeClone(self):
values = {}
for key, value in self.child_values.items():
assert type(value) is not list, key
if value is None:
values[key] = None
elif type(value) is tuple:
values[key] = tuple(
v.makeClone()
for v in
value
)
else:
values[key] = value.makeClone()
values.update(
self.getDetails()
)
try:
# Using star dictionary arguments here for generic use,
# pylint: disable=E1123
result = self.__class__(
source_ref = self.source_ref,
**values
)
except __HOLE__:
print("Problem cloning", self.__class__)
raise
effective_source_ref = self.getCompatibleSourceReference()
if effective_source_ref is not self.source_ref:
result.setCompatibleSourceReference(effective_source_ref)
return result
|
TypeError
|
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/nodes/NodeBases.py/ChildrenHavingMixin.makeClone
|
8,216
|
def fromXML(xml, source_ref = None):
assert xml.tag == "node", xml
kind = xml.attrib["kind"]
node_class = NodeCheckMetaClass.kinds[kind]
args = dict(xml.attrib)
del args["kind"]
if source_ref is None:
source_ref = SourceCodeReference.fromFilenameAndLine(args["filename"], int(args["line"]), None)
del args["filename"]
del args["line"]
else:
source_ref = source_ref.atLineNumber(int(args["line"]))
del args["line"]
for child in xml:
assert child.tag == "role", child.tag
child_name = child.attrib["name"]
if child.attrib.get("type") == "list":
value = [
fromXML(sub_child, source_ref)
for sub_child in
child
]
else:
value = fromXML(child[0], source_ref)
args[child_name] = value
try:
return node_class( source_ref = source_ref, **args )
except __HOLE__:
Tracing.printLine(node_class)
raise
|
TypeError
|
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/nodes/NodeBases.py/fromXML
|
8,217
|
def get_db(self):
_db = self.params.get('db', self.options.get('DB', 1))
try:
return int(_db)
except (ValueError, __HOLE__):
raise ImproperlyConfigured("db value must be an integer")
|
TypeError
|
dataset/ETHPy150Open sebleier/django-redis-cache/redis_cache/backends/base.py/BaseRedisCache.get_db
|
8,218
|
def get_pickle_version(self):
"""
Get the pickle version from the settings and save it for future use
"""
_pickle_version = self.options.get('PICKLE_VERSION', -1)
try:
return int(_pickle_version)
except (ValueError, __HOLE__):
raise ImproperlyConfigured(
"pickle version value must be an integer"
)
|
TypeError
|
dataset/ETHPy150Open sebleier/django-redis-cache/redis_cache/backends/base.py/BaseRedisCache.get_pickle_version
|
8,219
|
def get_value(self, original):
try:
value = int(original)
except (ValueError, __HOLE__):
value = self.decompress(original)
value = self.deserialize(value)
return value
|
TypeError
|
dataset/ETHPy150Open sebleier/django-redis-cache/redis_cache/backends/base.py/BaseRedisCache.get_value
|
8,220
|
def _check_timers(self):
now = time.time()
while not self._timers.empty():
try:
_, timer = self._timers.queue[0]
except __HOLE__:
return
if timer.check_timer(now):
self._timers.get_nowait()
else:
return
|
IndexError
|
dataset/ETHPy150Open hazelcast/hazelcast-python-client/hazelcast/reactor.py/AsyncoreReactor._check_timers
|
8,221
|
def shutdown(self):
for connection in self._map.values():
try:
connection.close(HazelcastError("Client is shutting down"))
except __HOLE__, connection:
if connection.args[0] == socket.EBADF:
pass
else:
raise
self._map.clear()
self._is_live = False
self._thread.join()
|
OSError
|
dataset/ETHPy150Open hazelcast/hazelcast-python-client/hazelcast/reactor.py/AsyncoreReactor.shutdown
|
8,222
|
def _cleanup_timer(self, timer):
try:
self._timers.queue.remove((timer.end, timer))
except __HOLE__:
pass
|
ValueError
|
dataset/ETHPy150Open hazelcast/hazelcast-python-client/hazelcast/reactor.py/AsyncoreReactor._cleanup_timer
|
8,223
|
def handle_write(self):
with self._write_lock:
try:
data = self._write_queue.popleft()
except __HOLE__:
return
sent = self.send(data)
self.sent_protocol_bytes = True
if sent < len(data):
self._write_queue.appendleft(data[sent:])
|
IndexError
|
dataset/ETHPy150Open hazelcast/hazelcast-python-client/hazelcast/reactor.py/AsyncoreConnection.handle_write
|
8,224
|
def test_error_message(self):
field = DjangoModelField(MyModel2, pk="other_pk")
myModel2 = MyModel2.objects.create(other_pk=999)
try:
field.to_python(666)
except __HOLE__, e:
self.assertEquals(e.message, 'No match found for MyModel2')
else:
self.assertTrue(False, "No exception raised")
self.assertEquals(field.to_python(myModel2.other_pk), myModel2)
|
ValueError
|
dataset/ETHPy150Open anthony-tresontani/django-adaptors/tests/csv_tests.py/TestFields.test_error_message
|
8,225
|
def __repr__(self):
try:
name = '%s %s' % (self.method, self.url)
except __HOLE__:
name = '(invalid WSGI environ)'
msg = '<%s at 0x%x %s>' % (
self.__class__.__name__,
abs(id(self)), name)
return msg
|
KeyError
|
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/webob-1.2.3/webob/request.py/BaseRequest.__repr__
|
8,226
|
@classmethod
def from_file(cls, fp):
"""Read a request from a file-like object (it must implement
``.read(size)`` and ``.readline()``).
It will read up to the end of the request, not the end of the
file (unless the request is a POST or PUT and has no
Content-Length, in that case, the entire file is read).
This reads the request as represented by ``str(req)``; it may
not read every valid HTTP request properly.
"""
start_line = fp.readline()
is_text = isinstance(start_line, text_type)
if is_text:
crlf = '\r\n'
colon = ':'
else:
crlf = b'\r\n'
colon = b':'
try:
header = start_line.rstrip(crlf)
method, resource, http_version = header.split(None, 2)
method = native_(method, 'utf-8')
resource = native_(resource, 'utf-8')
http_version = native_(http_version, 'utf-8')
except __HOLE__:
raise ValueError('Bad HTTP request line: %r' % start_line)
r = cls(environ_from_url(resource),
http_version=http_version,
method=method.upper()
)
del r.environ['HTTP_HOST']
while 1:
line = fp.readline()
if not line.strip():
# end of headers
break
hname, hval = line.split(colon, 1)
hname = native_(hname, 'utf-8')
hval = native_(hval, 'utf-8').strip()
if hname in r.headers:
hval = r.headers[hname] + ', ' + hval
r.headers[hname] = hval
if r.method in ('PUT', 'POST'):
clen = r.content_length
if clen is None:
body = fp.read()
else:
body = fp.read(clen)
if is_text:
body = bytes_(body, 'utf-8')
r.body = body
return r
|
ValueError
|
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/webob-1.2.3/webob/request.py/BaseRequest.from_file
|
8,227
|
def make_default_send_app(self):
global _client
try:
client = _client
except __HOLE__:
from webob import client
_client = client
return client.send_request_app
|
NameError
|
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/webob-1.2.3/webob/request.py/BaseRequest.make_default_send_app
|
8,228
|
def __getattr__(self, attr, DEFAULT=object()):
try:
return self.environ['webob.adhoc_attrs'][attr]
except __HOLE__:
raise AttributeError(attr)
|
KeyError
|
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/webob-1.2.3/webob/request.py/AdhocAttrMixin.__getattr__
|
8,229
|
def __delattr__(self, attr, DEFAULT=object()):
if getattr(self.__class__, attr, DEFAULT) is not DEFAULT:
return object.__delattr__(self, attr)
try:
del self.environ['webob.adhoc_attrs'][attr]
except __HOLE__:
raise AttributeError(attr)
|
KeyError
|
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/webob-1.2.3/webob/request.py/AdhocAttrMixin.__delattr__
|
8,230
|
def get_indicator_model(name, indicator_doc):
columns = [
sqlalchemy.Column(
'doc_id',
sqlalchemy.Unicode(255),
nullable=False,
primary_key=True),
sqlalchemy.Column(
'date',
sqlalchemy.Date,
nullable=False,
primary_key=True),
]
try:
flat_fields = indicator_doc._flat_fields
for flat_name in flat_fields.keys():
columns.append(sqlalchemy.Column(
flat_name,
sqlalchemy.String,
nullable=True
))
except __HOLE__:
pass
group_types = indicator_doc.get_group_types()
for group_name in indicator_doc.get_group_names():
columns.append(sqlalchemy.Column(
group_name,
get_column_type(group_types[group_name]),
nullable=False,
primary_key=True
))
calculators = indicator_doc._calculators
for calc_name in sorted(calculators.keys()):
for emitter_name in calculators[calc_name]._fluff_emitters:
col_name = '{0}_{1}'.format(calc_name, emitter_name)
columns.append(sqlalchemy.Column(
col_name,
sqlalchemy.Integer,
nullable=True,
))
return sqlalchemy.Table('fluff_{0}'.format(name), metadata, *columns)
|
AttributeError
|
dataset/ETHPy150Open dimagi/commcare-hq/corehq/ex-submodules/fluff/util.py/get_indicator_model
|
8,231
|
def parse_authorization_header(authorization_header):
"""Parse an OAuth authorization header into a list of 2-tuples"""
auth_scheme = u'OAuth '
if authorization_header.startswith(auth_scheme):
authorization_header = authorization_header.replace(auth_scheme, u'', 1)
items = parse_http_list(authorization_header)
try:
return parse_keqv_list(items).items()
except __HOLE__:
raise ValueError('Malformed authorization header')
|
ValueError
|
dataset/ETHPy150Open hzlf/openbroadcast/services/bcmon/requests/packages/oauthlib/oauth1/rfc5849/utils.py/parse_authorization_header
|
8,232
|
@classmethod
def _factory(cls, lookup, synchronize_session, *arg):
try:
klass = lookup[synchronize_session]
except __HOLE__:
raise sa_exc.ArgumentError(
"Valid strategies for session synchronization "
"are %s" % (", ".join(sorted(repr(x)
for x in lookup))))
else:
return klass(*arg)
|
KeyError
|
dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/orm/persistence.py/BulkUD._factory
|
8,233
|
@classmethod
def validate_hmac(cls, params):
if 'hmac' not in params:
return False
hmac_calculated = cls.calculate_hmac(params).encode('utf-8')
hmac_to_verify = params['hmac'].encode('utf-8')
# Try to use compare_digest() to reduce vulnerability to timing attacks.
# If it's not available, just fall back to regular string comparison.
try:
return hmac.compare_digest(hmac_calculated, hmac_to_verify)
except __HOLE__:
return hmac_calculated == hmac_to_verify
|
AttributeError
|
dataset/ETHPy150Open Shopify/shopify_python_api/shopify/session.py/Session.validate_hmac
|
8,234
|
def test_ssl_connection(self):
try:
import ssl
queuename = '/queue/test4-%s' % self.timestamp
conn = stomp.Connection(get_default_ssl_host())
conn.set_ssl(get_default_ssl_host())
conn.set_listener('', self.listener)
conn.start()
conn.connect('admin', 'password', wait=True)
conn.subscribe(destination=queuename, id=1, ack='auto')
conn.send(body='this is a test', destination=queuename, receipt='123')
self.listener.wait_on_receipt()
conn.disconnect(receipt=None)
self.assertTrue(self.listener.connections == 1, 'should have received 1 connection acknowledgement')
self.assertTrue(self.listener.messages == 1, 'should have received 1 message')
self.assertTrue(self.listener.errors == 0, 'should not have received any errors')
except __HOLE__:
pass
|
ImportError
|
dataset/ETHPy150Open jasonrbriggs/stomp.py/stomp/test/ssl_test.py/TestSSL.test_ssl_connection
|
8,235
|
def determine_socket(path=default_path):
"""Determine the socket with which to connect."""
sockets = list_sockets(path)
if not len(sockets):
return None
if len(sockets) == 1:
return os.path.join(path, sockets[0])
try:
import dialog
# If we aren't running from within TM use the first socket found.
except __HOLE__:
sock = sockets[0]
else:
sock = dialog.menu(sockets)
return os.path.join(path, sock)
|
ImportError
|
dataset/ETHPy150Open mattfoster/ipython-tmbundle/Support/lib/ipythonClient.py/determine_socket
|
8,236
|
def __eq__(self, other):
"""
:param other: an `IPAddress` or `IPNetwork` object.
:return: ``True`` if this `IPAddress` or `IPNetwork` object is
equivalent to ``other``, ``False`` otherwise.
"""
try:
return self.key() == other.key()
except (__HOLE__, TypeError):
return NotImplemented
|
AttributeError
|
dataset/ETHPy150Open drkjam/netaddr/netaddr/ip/__init__.py/BaseIP.__eq__
|
8,237
|
def __ne__(self, other):
"""
:param other: an `IPAddress` or `IPNetwork` object.
:return: ``True`` if this `IPAddress` or `IPNetwork` object is
not equivalent to ``other``, ``False`` otherwise.
"""
try:
return self.key() != other.key()
except (AttributeError, __HOLE__):
return NotImplemented
|
TypeError
|
dataset/ETHPy150Open drkjam/netaddr/netaddr/ip/__init__.py/BaseIP.__ne__
|
8,238
|
def __lt__(self, other):
"""
:param other: an `IPAddress` or `IPNetwork` object.
:return: ``True`` if this `IPAddress` or `IPNetwork` object is
less than ``other``, ``False`` otherwise.
"""
try:
return self.sort_key() < other.sort_key()
except (__HOLE__, TypeError):
return NotImplemented
|
AttributeError
|
dataset/ETHPy150Open drkjam/netaddr/netaddr/ip/__init__.py/BaseIP.__lt__
|
8,239
|
def __le__(self, other):
"""
:param other: an `IPAddress` or `IPNetwork` object.
:return: ``True`` if this `IPAddress` or `IPNetwork` object is
less than or equal to ``other``, ``False`` otherwise.
"""
try:
return self.sort_key() <= other.sort_key()
except (__HOLE__, TypeError):
return NotImplemented
|
AttributeError
|
dataset/ETHPy150Open drkjam/netaddr/netaddr/ip/__init__.py/BaseIP.__le__
|
8,240
|
def __gt__(self, other):
"""
:param other: an `IPAddress` or `IPNetwork` object.
:return: ``True`` if this `IPAddress` or `IPNetwork` object is
greater than ``other``, ``False`` otherwise.
"""
try:
return self.sort_key() > other.sort_key()
except (__HOLE__, TypeError):
return NotImplemented
|
AttributeError
|
dataset/ETHPy150Open drkjam/netaddr/netaddr/ip/__init__.py/BaseIP.__gt__
|
8,241
|
def __ge__(self, other):
"""
:param other: an `IPAddress` or `IPNetwork` object.
:return: ``True`` if this `IPAddress` or `IPNetwork` object is
greater than or equal to ``other``, ``False`` otherwise.
"""
try:
return self.sort_key() >= other.sort_key()
except (__HOLE__, TypeError):
return NotImplemented
|
AttributeError
|
dataset/ETHPy150Open drkjam/netaddr/netaddr/ip/__init__.py/BaseIP.__ge__
|
8,242
|
def __init__(self, addr, version=None, flags=0):
"""
Constructor.
:param addr: an IPv4 or IPv6 address which may be represented in an
accepted string format, as an unsigned integer or as another
IPAddress object (copy construction).
:param version: (optional) optimizes version detection if specified
and distinguishes between IPv4 and IPv6 for addresses with an
equivalent integer value.
:param flags: (optional) decides which rules are applied to the
interpretation of the addr value. Supported constants are
INET_PTON and ZEROFILL. See the netaddr.core docs for further
details.
"""
super(IPAddress, self).__init__()
if isinstance(addr, BaseIP):
# Copy constructor.
if version is not None and version != addr._module.version:
raise ValueError('cannot switch IP versions using '
'copy constructor!')
self._value = addr._value
self._module = addr._module
else:
# Explicit IP address version.
if version is not None:
if version == 4:
self._module = _ipv4
elif version == 6:
self._module = _ipv6
else:
raise ValueError('%r is an invalid IP version!' % version)
if _is_str(addr) and '/' in addr:
raise ValueError('%s() does not support netmasks or subnet' \
' prefixes! See documentation for details.'
% self.__class__.__name__)
if self._module is None:
# IP version is implicit, detect it from addr.
if isinstance(addr, _int_type):
try:
if 0 <= int(addr) <= _ipv4.max_int:
self._value = int(addr)
self._module = _ipv4
elif _ipv4.max_int < int(addr) <= _ipv6.max_int:
self._value = int(addr)
self._module = _ipv6
except __HOLE__:
pass
else:
for module in _ipv4, _ipv6:
try:
self._value = module.str_to_int(addr, flags)
except:
continue
else:
self._module = module
break
if self._module is None:
raise AddrFormatError('failed to detect a valid IP ' \
'address from %r' % addr)
else:
# IP version is explicit.
if _is_str(addr):
try:
self._value = self._module.str_to_int(addr, flags)
except AddrFormatError:
raise AddrFormatError('base address %r is not IPv%d'
% (addr, self._module.version))
else:
if 0 <= int(addr) <= self._module.max_int:
self._value = int(addr)
else:
raise AddrFormatError('bad address format: %r' % addr)
|
ValueError
|
dataset/ETHPy150Open drkjam/netaddr/netaddr/ip/__init__.py/IPAddress.__init__
|
8,243
|
def __getitem__(self, index):
"""
:return: The IP address(es) in this `IPNetwork` object referenced by
index or slice. As slicing can produce large sequences of objects
an iterator is returned instead of the more usual `list`.
"""
item = None
if hasattr(index, 'indices'):
if self._module.version == 6:
raise TypeError('IPv6 slices are not supported!')
(start, stop, step) = index.indices(self.size)
if (start + step < 0) or (step > stop):
# step value exceeds start and stop boundaries.
item = iter([IPAddress(self.first, self._module.version)])
else:
start_ip = IPAddress(self.first + start, self._module.version)
end_ip = IPAddress(self.first + stop - step, self._module.version)
item = iter_iprange(start_ip, end_ip, step)
else:
try:
index = int(index)
if (- self.size) <= index < 0:
# negative index.
item = IPAddress(self.last + index + 1, self._module.version)
elif 0 <= index <= (self.size - 1):
# Positive index or zero index.
item = IPAddress(self.first + index, self._module.version)
else:
raise IndexError('index out range for address range size!')
except __HOLE__:
raise TypeError('unsupported index type %r!' % index)
return item
|
ValueError
|
dataset/ETHPy150Open drkjam/netaddr/netaddr/ip/__init__.py/IPListMixin.__getitem__
|
8,244
|
def parse_ip_network(module, addr, implicit_prefix=False, flags=0):
if isinstance(addr, tuple):
# CIDR integer tuple
if len(addr) != 2:
raise AddrFormatError('invalid %s tuple!' % module.family_name)
value, prefixlen = addr
if not(0 <= value <= module.max_int):
raise AddrFormatError('invalid address value for %s tuple!'
% module.family_name)
if not(0 <= prefixlen <= module.width):
raise AddrFormatError('invalid prefix for %s tuple!' \
% module.family_name)
elif isinstance(addr, _str_type):
# CIDR-like string subnet
if implicit_prefix:
#TODO: deprecate this option in netaddr 0.8.x
addr = cidr_abbrev_to_verbose(addr)
if '/' in addr:
val1, val2 = addr.split('/', 1)
else:
val1 = addr
val2 = None
try:
ip = IPAddress(val1, module.version, flags=INET_PTON)
except AddrFormatError:
if module.version == 4:
# Try a partial IPv4 network address...
expanded_addr = _ipv4.expand_partial_address(val1)
ip = IPAddress(expanded_addr, module.version, flags=INET_PTON)
else:
raise AddrFormatError('invalid IPNetwork address %s!' % addr)
value = ip._value
try:
# Integer CIDR prefix.
prefixlen = int(val2)
except __HOLE__:
if val2 is None:
# No prefix was specified.
prefixlen = module.width
except ValueError:
# Not an integer prefix, try a netmask/hostmask prefix.
mask = IPAddress(val2, module.version, flags=INET_PTON)
if mask.is_netmask():
prefixlen = module.netmask_to_prefix[mask._value]
elif mask.is_hostmask():
prefixlen = module.hostmask_to_prefix[mask._value]
else:
raise AddrFormatError('addr %r is not a valid IPNetwork!' \
% addr)
if not 0 <= prefixlen <= module.width:
raise AddrFormatError('invalid prefix for %s address!' \
% module.family_name)
else:
raise TypeError('unexpected type %s for addr arg' % type(addr))
if flags & NOHOST:
# Remove host bits.
netmask = module.prefix_to_netmask[prefixlen]
value = value & netmask
return value, prefixlen
|
TypeError
|
dataset/ETHPy150Open drkjam/netaddr/netaddr/ip/__init__.py/parse_ip_network
|
8,245
|
def cidr_abbrev_to_verbose(abbrev_cidr):
"""
A function that converts abbreviated IPv4 CIDRs to their more verbose
equivalent.
:param abbrev_cidr: an abbreviated CIDR.
Uses the old-style classful IP address rules to decide on a default
subnet prefix if one is not explicitly provided.
Only supports IPv4 addresses.
Examples ::
10 - 10.0.0.0/8
10/16 - 10.0.0.0/16
128 - 128.0.0.0/16
128/8 - 128.0.0.0/8
192.168 - 192.168.0.0/16
:return: A verbose CIDR from an abbreviated CIDR or old-style classful \
network address. The original value if it was not recognised as a \
supported abbreviation.
"""
# Internal function that returns a prefix value based on the old IPv4
# classful network scheme that has been superseded (almost) by CIDR.
def classful_prefix(octet):
octet = int(octet)
if not 0 <= octet <= 255:
raise IndexError('Invalid octet: %r!' % octet)
if 0 <= octet <= 127: # Legacy class 'A' classification.
return 8
elif 128 <= octet <= 191: # Legacy class 'B' classification.
return 16
elif 192 <= octet <= 223: # Legacy class 'C' classification.
return 24
elif 224 <= octet <= 239: # Multicast address range.
return 4
return 32 # Default.
if _is_str(abbrev_cidr):
if ':' in abbrev_cidr or abbrev_cidr == '':
return abbrev_cidr
try:
# Single octet partial integer or string address.
i = int(abbrev_cidr)
return "%s.0.0.0/%s" % (i, classful_prefix(i))
except ValueError:
# Multi octet partial string address with optional prefix.
if '/' in abbrev_cidr:
part_addr, prefix = abbrev_cidr.split('/', 1)
# Check prefix for validity.
try:
if not 0 <= int(prefix) <= 32:
raise ValueError('prefixlen in address %r out of range' \
' for IPv4!' % abbrev_cidr)
except ValueError:
return abbrev_cidr
else:
part_addr = abbrev_cidr
prefix = None
tokens = part_addr.split('.')
if len(tokens) > 4:
# Not a recognisable format.
return abbrev_cidr
for i in range(4 - len(tokens)):
tokens.append('0')
if prefix is None:
try:
prefix = classful_prefix(tokens[0])
except ValueError:
return abbrev_cidr
return "%s/%s" % ('.'.join(tokens), prefix)
except (__HOLE__, IndexError):
# Not a recognisable format.
return abbrev_cidr
|
TypeError
|
dataset/ETHPy150Open drkjam/netaddr/netaddr/ip/__init__.py/cidr_abbrev_to_verbose
|
8,246
|
def _run_revision(self, rev):
need_to_run = self._get_benchmarks_for_rev(rev)
if not need_to_run:
log.info('No benchmarks need running at %s' % rev)
return 0, {}
log.info('Running %d benchmarks for revision %s' % (len(need_to_run), rev))
for bm in need_to_run:
log.debug(bm.name)
self.bench_repo.switch_to_revision(rev)
pickle_path = os.path.join(self.tmp_dir, 'benchmarks.pickle')
results_path = os.path.join(self.tmp_dir, 'results.pickle')
if os.path.exists(results_path):
os.remove(results_path)
pickle.dump(need_to_run, open(pickle_path, 'w'))
# run the process
cmd = 'python vb_run_benchmarks.py %s %s' % (pickle_path, results_path)
log.debug("CMD: %s" % cmd)
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
cwd=self.tmp_dir)
stdout, stderr = proc.communicate()
if stdout:
log.debug('stdout: %s' % stdout)
if proc.returncode:
log.warn("Returned with non-0 code: %d" % proc.returncode)
if stderr:
log.warn("stderr: %s" % stderr)
if ("object has no attribute" in stderr or
'ImportError' in stderr):
log.warn('HARD CLEANING!')
self.bench_repo.hard_clean()
if not os.path.exists(results_path):
log.warn('Failed for revision %s' % rev)
return len(need_to_run), {}
results = pickle.load(open(results_path, 'r'))
try:
os.remove(pickle_path)
except __HOLE__:
pass
return len(need_to_run), results
|
OSError
|
dataset/ETHPy150Open pydata/vbench/vbench/runner.py/BenchmarkRunner._run_revision
|
8,247
|
def func_set_api_key():
try:
if ( os.path.exists(os.path.expanduser('~') + '/.virustotal' ) ):
with open( os.path.expanduser('~') + '/.virustotal' ) as handle_api_file:
return func_parse_api_key(handle_api_file.readlines())
elif ( os.path.exists('.virustotal' ) ):
with open( '.virustotal' ) as handle_api_file:
return func_parse_api_key(handle_api_file.readlines())
else:
sys.exit(" [X] Please Put API Key in ~/.virustotal or .virustotal")
except __HOLE__:
sys.exit(" [X] Please Put API Key in ~/.virustotal or .virustotal")
# Parse the API key and exit if the API key contains any non [A-Za-z0-9]+
|
IOError
|
dataset/ETHPy150Open CrowdStrike/CrowdFMS/lib/core.py/func_set_api_key
|
8,248
|
def func_pull_feed(str_api_key):
req_user_agent = {'User-agent': 'VirusTotal FMS 1.0'}
try:
vt_request_results = requests.get("https://www.virustotal.com/intelligence/hunting/notifications-feed/?key=%s" % str_api_key, headers=req_user_agent)
except:
return 0
try:
return json.loads(vt_request_results.content)
except __HOLE__:
print vt_request_results.content
return 0
# Convert VT timestamps to Epoch Timestamp
|
ValueError
|
dataset/ETHPy150Open CrowdStrike/CrowdFMS/lib/core.py/func_pull_feed
|
8,249
|
def skipUnlessPG94(test):
try:
PG_VERSION = connection.pg_version
except __HOLE__:
PG_VERSION = 0
if PG_VERSION < 90400:
return unittest.skip('PostgreSQL >= 9.4 required')(test)
return test
|
AttributeError
|
dataset/ETHPy150Open django/django/tests/postgres_tests/test_json.py/skipUnlessPG94
|
8,250
|
def create(self, spider_name, **spider_kwargs):
try:
spcls = self._spiders[spider_name]
except __HOLE__:
raise KeyError("Spider not found: %s" % spider_name)
if hasattr(self, 'crawler') and hasattr(spcls, 'from_crawler'):
return spcls.from_crawler(self.crawler, **spider_kwargs)
else:
return spcls(**spider_kwargs)
|
KeyError
|
dataset/ETHPy150Open wcong/ants/ants/crawl/spidermanager.py/SpiderManager.create
|
8,251
|
def __execute_test(self, coroutine):
"""Executes given test coroutine and returns
a set of "tags" that have been assigned to
the test case by the property.
"""
res = []
try:
while True:
obj = next(coroutine)
if obj is not None:
value = obj.value if isinstance(obj, Tag) else obj
res.append(value)
except __HOLE__:
return frozenset(res)
|
StopIteration
|
dataset/ETHPy150Open Xion/pyqcy/pyqcy/properties.py/Property.__execute_test
|
8,252
|
def test_run_command_unicode_string(self):
backup_Popen = catkin.builder.subprocess.Popen
class StdOut(object):
def __init__(self, popen):
self.__popen = popen
def readline(self):
self.__popen.returncode = 0
try:
# for Python 2 compatibility only
return unichr(2018)
except __HOLE__:
return chr(2018)
class MockPopen(object):
def __init__(self, *args, **kwargs):
self.returncode = None
self.stdout = StdOut(self)
def wait(self):
return True
try:
catkin.builder.subprocess.Popen = MockPopen
catkin.builder.run_command(['false'], os.getcwd(), True, True)
finally:
catkin.builder.subprocess.Popen = backup_Popen
|
NameError
|
dataset/ETHPy150Open ros/catkin/test/unit_tests/test_builder.py/BuilderTest.test_run_command_unicode_string
|
8,253
|
def test_run_command_unicode_bytes(self):
backup_Popen = catkin.builder.subprocess.Popen
class StdOut(object):
def __init__(self, popen):
self.__popen = popen
def readline(self):
self.__popen.returncode = 0
try:
# for Python 2 compatibility only
s = unichr(2018)
except __HOLE__:
s = chr(2018)
return s.encode('utf8')
class MockPopen(object):
def __init__(self, *args, **kwargs):
self.returncode = None
self.stdout = StdOut(self)
def wait(self):
return True
try:
catkin.builder.subprocess.Popen = MockPopen
catkin.builder.run_command(['false'], os.getcwd(), True, True)
finally:
catkin.builder.subprocess.Popen = backup_Popen
|
NameError
|
dataset/ETHPy150Open ros/catkin/test/unit_tests/test_builder.py/BuilderTest.test_run_command_unicode_bytes
|
8,254
|
def render(self, context, nested=False):
if self.message_context:
message_context = self.message_context.resolve(context)
else:
message_context = None
tmp_context = {}
for var, val in self.extra_context.items():
tmp_context[var] = val.resolve(context)
# Update() works like a push(), so corresponding context.pop() is at
# the end of function
context.update(tmp_context)
singular, vars = self.render_token_list(self.singular)
if self.plural and self.countervar and self.counter:
count = self.counter.resolve(context)
context[self.countervar] = count
plural, plural_vars = self.render_token_list(self.plural)
if message_context:
result = translation.npgettext(message_context, singular,
plural, count)
else:
result = translation.ungettext(singular, plural, count)
vars.extend(plural_vars)
else:
if message_context:
result = translation.pgettext(message_context, singular)
else:
result = translation.ugettext(singular)
data = dict([(v, _render_value_in_context(context.get(v, ''), context)) for v in vars])
context.pop()
try:
result = result % data
except (__HOLE__, ValueError):
if nested:
# Either string is malformed, or it's a bug
raise TemplateSyntaxError("'blocktrans' is unable to format "
"string returned by gettext: %r using %r" % (result, data))
with translation.override(None):
result = self.render(context, nested=True)
return result
|
KeyError
|
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/templatetags/i18n.py/BlockTranslateNode.render
|
8,255
|
def installed(name, target="LocalSystem", dmg=False, store=False, app=False, mpkg=False, user=None, onlyif=None,
unless=None, force=False, allow_untrusted=False, version_check=None):
'''
Install a Mac OS Package from a pkg or dmg file, if given a dmg file it
will first be mounted in a temporary location
name
The pkg or dmg file to install
target
The location in which to install the package. This can be a path or LocalSystem
dmg
Is the given file a dmg file?
store
Should the pkg be installed as if it was from the Mac OS Store?
app
Is the file a .app? If so then we'll just copy that to /Applications/ or the given
target
mpkg
Is the file a .mpkg? If so then we'll check all of the .pkg files found are installed
user
Name of the user performing the unless or onlyif checks
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns true
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns false
force
Force the package to be installed even if its already been found installed
allow_untrusted
Allow the installation of untrusted packages
version_check
The command and version that we want to check against, the version number can use regex.
.. code-block:: yaml
version_check: python --version_check=2.7.[0-9]
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}}
found = []
installing = []
real_pkg = name
# Check onlyif, unless first
run_check_cmd_kwargs = {'runas': user, 'python_shell': True}
if 'shell' in __grains__:
run_check_cmd_kwargs['shell'] = __grains__['shell']
cret = _mod_run_check(run_check_cmd_kwargs, onlyif, unless)
if isinstance(cret, dict):
ret.update(cret)
return ret
# Check version info
if version_check is not None:
split = version_check.split("=")
if len(split) == 2:
version_cmd = split[0]
expected_version = split[1]
try:
version_out = __salt__['cmd.run'](version_cmd, output_loglevel="quiet", ignore_retcode=True)
version_out = version_out.strip()
except CommandExecutionError:
version_out = ""
if re.match(expected_version, version_out) is not None:
ret['comment'] += "Version already matches {0}".format(expected_version)
return ret
else:
ret['comment'] += "Version {0} doesn't match {1}. ".format(version_out, expected_version)
if app and target == "LocalSystem":
target = "/Applications/"
# Mount the dmg first
mount_point = None
if dmg:
out, mount_point = __salt__['macpackage.mount'](name)
if 'attach failed' in out:
ret['result'] = False
ret['comment'] += 'Unable to mount {0}'.format(name)
return ret
if app:
real_pkg = mount_point + "/*.app"
elif mpkg:
real_pkg = mount_point + "/*.mpkg"
else:
real_pkg = mount_point + "/*.pkg"
try:
# Check if we have already installed this
if app:
if dmg:
# Run with python shell due to the wildcard
cmd = 'ls -d *.app'
out = __salt__['cmd.run'](cmd, cwd=mount_point, python_shell=True)
if '.app' not in out:
ret['result'] = False
ret['comment'] += 'Unable to find .app in {0}'.format(mount_point)
return ret
else:
pkg_ids = out.split("\n")
else:
pkg_ids = [os.path.basename(name)]
mount_point = os.path.dirname(name)
if onlyif is None and unless is None and version_check is None:
for p in pkg_ids:
if target[-4:] == ".app":
install_dir = target
else:
install_dir = os.path.join(target, p)
if os.path.exists(install_dir) and force is False:
found.append(p)
else:
installing.append(p)
else:
installing = pkg_ids
else:
installed_pkgs = __salt__['macpackage.installed_pkgs']()
if mpkg:
pkg_ids = __salt__['macpackage.get_mpkg_ids'](real_pkg)
else:
pkg_ids = __salt__['macpackage.get_pkg_id'](real_pkg)
if len(pkg_ids) > 0:
for p in pkg_ids:
if p in installed_pkgs and force is False:
found.append(p)
else:
installing.append(p)
if len(pkg_ids) == len(found):
return ret
if app:
def failed_pkg(f_pkg):
ret['result'] = False
ret['comment'] += '{0} failed to install: {1}'.format(name, out)
if 'failed' in ret['changes']:
ret['changes']['failed'].append(f_pkg)
else:
ret['changes']['failed'] = [f_pkg]
for app in installing:
try:
log.info('Copying {0} to {1}'.format(app, target))
out = __salt__['macpackage.install_app'](os.path.join(mount_point, app), target)
if len(out) != 0:
failed_pkg(app)
else:
ret['comment'] += '{0} installed'.format(app)
if 'installed' in ret['changes']:
ret['changes']['installed'].append(app)
else:
ret['changes']['installed'] = [app]
except __HOLE__:
failed_pkg(app)
else:
out = __salt__['macpackage.install'](real_pkg, target, store, allow_untrusted)
if out['retcode'] != 0:
ret['result'] = False
ret['comment'] += '. {0} failed to install: {1}'.format(name, out)
else:
ret['comment'] += '{0} installed'.format(name)
ret['changes']['installed'] = installing
finally:
if dmg:
# Unmount to be kind
__salt__['macpackage.unmount'](mount_point)
return ret
|
OSError
|
dataset/ETHPy150Open saltstack/salt/salt/states/mac_package.py/installed
|
8,256
|
def test_fail_non_euler_a(self):
p = planning.Euler()
g = build_graph('ab bc bd')
p.forced_plan = lambda *al: None
try:
p(g, EhmNo(), 'a', '<context>')
except __HOLE__ as e:
self.assertEqual(e.args, ("Graph is not Eulerian",))
else:
self.assert_(False, "Expected exception")
|
AssertionError
|
dataset/ETHPy150Open spotify/python-graphwalker/graphwalker/test/planning_test.py/TestEuler.test_fail_non_euler_a
|
8,257
|
def test_fail_non_euler_b(self):
p = planning.Euler()
g = build_graph('ab ba de ed')
p.forced_plan = lambda *al: None
try:
p(g, EhmNo(), 'a', '<context>')
except __HOLE__ as e:
self.assertEqual(e.args, ("Graph is not connected",))
else:
self.assert_(False, "Expected exception")
|
AssertionError
|
dataset/ETHPy150Open spotify/python-graphwalker/graphwalker/test/planning_test.py/TestEuler.test_fail_non_euler_b
|
8,258
|
def textile(value):
try:
import textile
except __HOLE__:
if settings.DEBUG:
raise template.TemplateSyntaxError("Error in {% textile %} filter: The Python textile library isn't installed.")
return force_unicode(value)
else:
return mark_safe(force_unicode(textile.textile(smart_str(value), encoding='utf-8', output='utf-8')))
|
ImportError
|
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/contrib/markup/templatetags/markup.py/textile
|
8,259
|
def markdown(value, arg=''):
"""
Runs Markdown over a given value, optionally using various
extensions python-markdown supports.
Syntax::
{{ value|markdown:"extension1_name,extension2_name..." }}
To enable safe mode, which strips raw HTML and only returns HTML
generated by actual Markdown syntax, pass "safe" as the first
extension in the list.
If the version of Markdown in use does not support extensions,
they will be silently ignored.
"""
try:
import markdown
except __HOLE__:
if settings.DEBUG:
raise template.TemplateSyntaxError("Error in {% markdown %} filter: The Python markdown library isn't installed.")
return force_unicode(value)
else:
# markdown.version was first added in 1.6b. The only version of markdown
# to fully support extensions before 1.6b was the shortlived 1.6a.
if hasattr(markdown, 'version'):
extensions = [e for e in arg.split(",") if e]
if len(extensions) > 0 and extensions[0] == "safe":
extensions = extensions[1:]
safe_mode = True
else:
safe_mode = False
# Unicode support only in markdown v1.7 or above. Version_info
# exist only in markdown v1.6.2rc-2 or above.
if getattr(markdown, "version_info", None) < (1,7):
return mark_safe(force_unicode(markdown.markdown(smart_str(value), extensions, safe_mode=safe_mode)))
else:
return mark_safe(markdown.markdown(force_unicode(value), extensions, safe_mode=safe_mode))
else:
return mark_safe(force_unicode(markdown.markdown(smart_str(value))))
|
ImportError
|
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/contrib/markup/templatetags/markup.py/markdown
|
8,260
|
def restructuredtext(value):
try:
from docutils.core import publish_parts
except __HOLE__:
if settings.DEBUG:
raise template.TemplateSyntaxError("Error in {% restructuredtext %} filter: The Python docutils library isn't installed.")
return force_unicode(value)
else:
docutils_settings = getattr(settings, "RESTRUCTUREDTEXT_FILTER_SETTINGS", {})
parts = publish_parts(source=smart_str(value), writer_name="html4css1", settings_overrides=docutils_settings)
return mark_safe(force_unicode(parts["fragment"]))
|
ImportError
|
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/contrib/markup/templatetags/markup.py/restructuredtext
|
8,261
|
@staticmethod
def get_descriptor(file_input):
try:
# Is it a file like object?
file_input.seek(0)
except __HOLE__:
# If not, try open it.
return open(file_input, 'rb')
else:
return file_input
|
AttributeError
|
dataset/ETHPy150Open mayan-edms/mayan-edms/mayan/apps/django_gpg/api.py/GPG.get_descriptor
|
8,262
|
def __init__(self, binary_path=None, home=None, keyring=None, keyservers=None):
kwargs = {}
if binary_path:
kwargs['gpgbinary'] = binary_path
if home:
kwargs['gnupghome'] = home
if keyring:
kwargs['keyring'] = keyring
self.keyservers = keyservers
try:
self.gpg = gnupg.GPG(**kwargs)
except __HOLE__ as exception:
raise GPGException(
'ERROR: GPG initialization error; Make sure the GPG binary is properly installed; %s' % exception
)
except Exception as exception:
raise GPGException(
'ERROR: GPG initialization error; %s' % exception
)
|
OSError
|
dataset/ETHPy150Open mayan-edms/mayan-edms/mayan/apps/django_gpg/api.py/GPG.__init__
|
8,263
|
def is_int(s):
try:
int(s)
return True
except __HOLE__:
return False
|
ValueError
|
dataset/ETHPy150Open modflowpy/flopy/flopy/utils/formattedfile.py/is_int
|
8,264
|
def is_float(s):
try:
float(s)
return True
except __HOLE__:
return False
|
ValueError
|
dataset/ETHPy150Open modflowpy/flopy/flopy/utils/formattedfile.py/is_float
|
8,265
|
def test_which_set():
"""Test which_set selector."""
skip_if_no_sklearn()
# one label
this_yaml = test_yaml_which_set % {'which_set': 'train'}
trainer = yaml_parse.load(this_yaml)
trainer.main_loop()
# multiple labels
this_yaml = test_yaml_which_set % {'which_set': ['train', 'test']}
trainer = yaml_parse.load(this_yaml)
trainer.main_loop()
# improper label (iterator only returns 'train' and 'test' subsets)
this_yaml = test_yaml_which_set % {'which_set': 'valid'}
try:
trainer = yaml_parse.load(this_yaml)
trainer.main_loop()
raise AssertionError
except ValueError:
pass
# bogus label (not in approved list)
this_yaml = test_yaml_which_set % {'which_set': 'bogus'}
try:
yaml_parse.load(this_yaml)
raise AssertionError
except __HOLE__:
pass
|
ValueError
|
dataset/ETHPy150Open lisa-lab/pylearn2/pylearn2/cross_validation/tests/test_dataset_iterators.py/test_which_set
|
8,266
|
def _get_res(self, profile_name):
log.debug("searching for RES")
res_file = "chrome-extension_kbmfpngjjgdllneeigpgjifpgocmfgmb_0.localstorage"
if self.os == 'linux':
res_folder = self._expand("~/.config/chromium/{}/Local Storage/".format(profile_name))
elif self.os == 'windows':
if platform.release() == "XP":
log.error("Unsupported OS (Windows XP). Returning None")
return None
# todo: Check if it's possible for folder to be in %APPDATA% instead
res_folder = self._expand("%LOCALAPPDATA%\\Chromium\\User Data\\{}\\Local Storage\\".format(profile_name))
elif self.os == "darwin":
res_folder = self._expand("~/Library/Application Support/Chromium/{}/".format(profile_name))
else:
log.error("Unsupported OS. Returning None")
return None
log.debug("res_folder set to : {}".format(res_folder))
if not os.path.exists(res_folder):
log.error("Selected folder does not exist")
return None
try:
full_path = os.path.join(res_folder, res_file)
log.debug("Full path set to {}".format(full_path))
if os.path.exists(full_path):
log.debug("Full path exists")
return full_path
else:
log.warn("Full path does not exist. RES Not installed?")
return None
except __HOLE__:
log.error("Joining failed for {} and {}".format(res_folder, res_file))
return None
except Exception as e:
log.exception(e)
|
AttributeError
|
dataset/ETHPy150Open Nikola-K/RESTool/RESTool/browsers/chromium.py/Chromium._get_res
|
8,267
|
def to_python(self, value):
if isinstance(value, basestring):
try:
return parse_date_string(value, self.precise_reads)
except __HOLE__, e:
raise ValueError('Invalid ISO date/time %r [%s]' %
(value, str(e)))
return value
|
ValueError
|
dataset/ETHPy150Open dimagi/commcare-hq/corehq/ex-submodules/couchexport/properties.py/TimeStampProperty.to_python
|
8,268
|
def tag_sents(self, sentences):
"""
Applies the tag method over a list of sentences. This method will return a
list of dictionaries. Every dictionary will contain a word with its
calculated annotations/tags.
"""
encoding = self._encoding
if not path.isfile(self.executable(self._path)):
raise OSError("Senna executable expected at %s but not found" % self.executable(self._path))
# Build the senna command to run the tagger
_senna_cmd = [self.executable(self._path), '-path', self._path, '-usrtokens', '-iobtags']
_senna_cmd.extend(['-'+op for op in self.operations])
# Serialize the actual sentences to a temporary string
_input = '\n'.join((' '.join(x) for x in sentences))+'\n'
if isinstance(_input, text_type) and encoding:
_input = _input.encode(encoding)
# Run the tagger and get the output
p = Popen(_senna_cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
(stdout, stderr) = p.communicate(input=_input)
senna_output = stdout
# Check the return code.
if p.returncode != 0:
raise RuntimeError('Senna command failed! Details: %s' % stderr)
if encoding:
senna_output = stdout.decode(encoding)
# Output the tagged sentences
map_ = self._map()
tagged_sentences = [[]]
sentence_index = 0
token_index = 0
for tagged_word in senna_output.strip().split("\n"):
if not tagged_word:
tagged_sentences.append([])
sentence_index += 1
token_index = 0
continue
tags = tagged_word.split('\t')
result = {}
for tag in map_:
result[tag] = tags[map_[tag]].strip()
try:
result['word'] = sentences[sentence_index][token_index]
except __HOLE__:
raise IndexError(
"Misalignment error occurred at sentence number %d. Possible reason"
" is that the sentence size exceeded the maximum size. Check the "
"documentation of Senna class for more information."
% sentence_index)
tagged_sentences[-1].append(result)
token_index += 1
return tagged_sentences
# skip doctests if Senna is not installed
|
IndexError
|
dataset/ETHPy150Open nltk/nltk/nltk/classify/senna.py/Senna.tag_sents
|
8,269
|
def setup_module(module):
from nose import SkipTest
try:
tagger = Senna('/usr/share/senna-v2.0', ['pos', 'chk', 'ner'])
except __HOLE__:
raise SkipTest("Senna executable not found")
|
OSError
|
dataset/ETHPy150Open nltk/nltk/nltk/classify/senna.py/setup_module
|
8,270
|
def buildNode(provider, node, source_ref, allow_none = False):
if node is None and allow_none:
return None
try:
kind = getKind(node)
if hasattr(node, "lineno"):
source_ref = source_ref.atLineNumber(node.lineno)
else:
source_ref = source_ref
if kind in build_nodes_args3:
result = build_nodes_args3[kind](
provider = provider,
node = node,
source_ref = source_ref
)
elif kind in build_nodes_args2:
result = build_nodes_args2[kind](
node = node,
source_ref = source_ref
)
elif kind in build_nodes_args1:
result = build_nodes_args1[kind](
source_ref = source_ref
)
elif kind == "Pass":
result = None
else:
assert False, ast.dump(node)
if result is None and allow_none:
return None
assert isinstance(result, NodeBase), result
return result
except SyntaxError:
raise
except __HOLE__:
# Very likely the stack overflow, which we will turn into too complex
# code exception, don't warn about it with a code dump then.
raise
except:
warning("Problem at '%s' with %s." % (source_ref, ast.dump(node)))
raise
|
RuntimeError
|
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/tree/Helpers.py/buildNode
|
8,271
|
def forward(app):
app = TestApp(RecursiveMiddleware(app))
res = app.get('')
assert res.headers['content-type'] == 'text/plain'
assert res.status == '200 OK'
assert 'requested page returned' in res
res = app.get('/error')
assert res.headers['content-type'] == 'text/plain'
assert res.status == '200 OK'
assert 'Page not found' in res
res = app.get('/not_found')
assert res.headers['content-type'] == 'text/plain'
assert res.status == '200 OK'
assert 'Page not found' in res
try:
res = app.get('/recurse')
except __HOLE__ as e:
if str(e).startswith('Forwarding loop detected'):
pass
else:
raise AssertionError('Failed to detect forwarding loop')
|
AssertionError
|
dataset/ETHPy150Open pecan/pecan/pecan/tests/middleware/test_recursive.py/forward
|
8,272
|
def test_ForwardRequest_factory(self):
class TestForwardRequestMiddleware(Middleware):
def __call__(self, environ, start_response):
if environ['PATH_INFO'] != '/not_found':
return self.app(environ, start_response)
environ['PATH_INFO'] = self.url
def factory(app):
class WSGIApp(object):
def __init__(self, app):
self.app = app
def __call__(self, e, start_response):
def keep_status_start_response(status, headers,
exc_info=None):
return start_response(
'404 Not Found', headers, exc_info
)
return self.app(e, keep_status_start_response)
return WSGIApp(app)
raise ForwardRequestException(factory=factory)
app = TestForwardRequestMiddleware(error_docs_app)
app = TestApp(RecursiveMiddleware(app))
res = app.get('')
assert res.headers['content-type'] == 'text/plain'
assert res.status == '200 OK'
assert 'requested page returned' in res
res = app.get('/error')
assert res.headers['content-type'] == 'text/plain'
assert res.status == '200 OK'
assert 'Page not found' in res
res = app.get('/not_found', status=404)
assert res.headers['content-type'] == 'text/plain'
assert res.status == '404 Not Found' # Different status
assert 'Page not found' in res
try:
res = app.get('/recurse')
except __HOLE__ as e:
if str(e).startswith('Forwarding loop detected'):
pass
else:
raise AssertionError('Failed to detect forwarding loop')
|
AssertionError
|
dataset/ETHPy150Open pecan/pecan/pecan/tests/middleware/test_recursive.py/TestRecursiveMiddleware.test_ForwardRequest_factory
|
8,273
|
def _extend_or_set_attribute(self, existing_image, image, attribute_name):
attribute = image.get(attribute_name, [])
if attribute:
try:
existing_image[attribute_name].extend(attribute)
except __HOLE__:
existing_image[attribute_name] = attribute
|
KeyError
|
dataset/ETHPy150Open openstack/tripleo-common/tripleo_common/image/base.py/BaseImageManager._extend_or_set_attribute
|
8,274
|
def request(method, uri, *args, **kwargs):
"""
Handles all the common functionality required for API calls. Returns
the resulting response object.
Formats the request into a dict representing the headers
and body that will be used to make the API call.
"""
req_method = req_methods[method.upper()]
raise_exception = kwargs.pop("raise_exception", True)
raw_content = kwargs.pop("raw_content", False)
kwargs["headers"] = kwargs.get("headers", {})
http_log_req(method, uri, args, kwargs)
data = None
if "data" in kwargs:
# The 'data' kwarg is used when you don't want json encoding.
data = kwargs.pop("data")
elif "body" in kwargs:
if "Content-Type" not in kwargs["headers"]:
kwargs["headers"]["Content-Type"] = "application/json"
data = json.dumps(kwargs.pop("body"))
if data:
resp = req_method(uri, data=data, **kwargs)
else:
resp = req_method(uri, **kwargs)
if raw_content:
body = resp.content
else:
try:
body = resp.json()
except __HOLE__:
# No JSON in response
body = resp.content
http_log_resp(resp, body)
if resp.status_code >= 400 and raise_exception:
raise exc.from_response(resp, body)
return resp, body
|
ValueError
|
dataset/ETHPy150Open rackspace/pyrax/pyrax/http.py/request
|
8,275
|
def __call__(self, wr=None):
'''
Run the callback unless it has already been called or cancelled
'''
try:
del _finalizer_registry[self._key]
except __HOLE__:
sub_debug('finalizer no longer registered')
else:
sub_debug('finalizer calling %s with args %s and kwargs %s',
self._callback, self._args, self._kwargs)
res = self._callback(*self._args, **self._kwargs)
self._weakref = self._callback = self._args = \
self._kwargs = self._key = None
return res
|
KeyError
|
dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/multiprocessing/util.py/Finalize.__call__
|
8,276
|
def cancel(self):
'''
Cancel finalization of the object
'''
try:
del _finalizer_registry[self._key]
except __HOLE__:
pass
else:
self._weakref = self._callback = self._args = \
self._kwargs = self._key = None
|
KeyError
|
dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/multiprocessing/util.py/Finalize.cancel
|
8,277
|
def __repr__(self):
try:
obj = self._weakref()
except (__HOLE__, TypeError):
obj = None
if obj is None:
return '<Finalize object, dead>'
x = '<Finalize object, callback=%s' % \
getattr(self._callback, '__name__', self._callback)
if self._args:
x += ', args=' + str(self._args)
if self._kwargs:
x += ', kwargs=' + str(self._kwargs)
if self._key[0] is not None:
x += ', exitprority=' + str(self._key[0])
return x + '>'
|
AttributeError
|
dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/multiprocessing/util.py/Finalize.__repr__
|
8,278
|
def main():
dh = DHCPHelper()
dhcp_scopes = []
dhcp_scopes = dh.get_scopes_to_generate()
print dhcp_scopes
output_dir = DHCP_CONFIG_OUTPUT_DIRECTORY
for scope in dhcp_scopes:
dhcp_scope = scope.task
try:
dir = dhcp_scope.split("-")[0]
output_file = '-'.join(dhcp_scope.split("-")[1:])
final_destination_file = "%s/%s/%s_generated_hosts.conf" % (output_dir,dir, output_file)
systems = dh.systems_by_scope(dhcp_scope)
adapters = []
for host in systems:
hostname = host['hostname']
adapters.append(dh.adapters_by_system_and_scope(hostname, dhcp_scope))
output_text = DHCPInterface([], adapters).get_hosts()
try:
f = open(final_destination_file,"w")
f.write(output_text)
sregs = StaticReg.objects.filter(
hwadapter_set__keyvalue_set__key='dhcp_scope',
hwadapter_set__keyvalue_set__value=dhcp_scope
)
# Django doesn't allow DISTINCT ON so we must simulate this in
# python. There is probably a better way.
sreg_pks = set()
distinct_sregs = []
for sreg in sregs:
if sreg.pk in sreg_pks:
continue
sreg_pks.add(sreg.pk)
distinct_sregs.append(sreg)
print render_sregs(distinct_sregs)
f.write('\n\n')
f.write(render_sregs(distinct_sregs))
f.close()
print "Wrote config to {0}".format(final_destination_file)
except __HOLE__:
pass
try:
DHCPFile.objects.filter(dhcp_scope=dhcp_scope).delete()
except:
pass
d = DHCPFile(dhcp_scope=dhcp_scope,file_text=output_text)
d.save()
scope.delete()
except IndexError:
scope.delete()
if len(dhcp_scopes) > 0 or always_push_svn:
os.chdir(output_dir)
os.system('/usr/bin/svn update')
os.system('/usr/bin/svn add * --force')
os.system('/usr/bin/svn commit -m "Autogenerated addition from inventory"')
#os.system('/usr/bin/git push origin master')
|
IOError
|
dataset/ETHPy150Open mozilla/inventory/scripts/output_dhcp_config_files_svn.py/main
|
8,279
|
@staticmethod
def _get_plugin(plugin_path):
"""Given a qualified class name (eg. foo.bar.Foo), return the class
:rtype: object
"""
try:
package, class_name = plugin_path.rsplit('.', 1)
except ValueError:
return None
try:
module_handle = importlib.import_module(package)
class_handle = getattr(module_handle, class_name)
return class_handle
except __HOLE__:
LOGGER.exception('Attempting to import %s', plugin_path)
return None
|
ImportError
|
dataset/ETHPy150Open MeetMe/newrelic-plugin-agent/newrelic_plugin_agent/agent.py/NewRelicPluginAgent._get_plugin
|
8,280
|
def process_amqp_msgs(self):
"""Process AMQP queue messages.
It connects to AMQP server and calls callbacks to process DCNM events,
i.e. routing key containing '.cisco.dcnm.', once they arrive in the
queue.
"""
LOG.info(_LI('Starting process_amqp_msgs...'))
while True:
(mtd_fr, hdr_fr, body) = (None, None, None)
try:
if self.consume_channel:
(mtd_fr, hdr_fr, body) = self.consume_channel.basic_get(
self._dcnm_queue_name)
if mtd_fr:
# Queue has messages.
LOG.info(_LI('RX message: %s'), body)
self._cb_dcnm_msg(mtd_fr, body)
self.consume_channel.basic_ack(mtd_fr.delivery_tag)
else:
# Queue is empty.
try:
self._conn.sleep(1)
except __HOLE__:
time.sleep(1)
except Exception:
exc_type, exc_value, exc_tb = sys.exc_info()
tb_str = traceback.format_exception(exc_type,
exc_value, exc_tb)
LOG.exception(_LE("Failed to read from queue: %(queue)s "
"%(exc_type)s, %(exc_value)s, %(exc_tb)s."), {
'queue': self._dcnm_queue_name,
'exc_type': exc_type,
'exc_value': exc_value,
'exc_tb': tb_str})
|
AttributeError
|
dataset/ETHPy150Open openstack/networking-cisco/networking_cisco/apps/saf/server/dfa_listen_dcnm.py/DCNMListener.process_amqp_msgs
|
8,281
|
def _validate_iso_format(self, start_date):
try:
return datetime.datetime.strptime(
start_date, "%Y-%m-%dT%H:%M:%S")
except __HOLE__:
return False
|
ValueError
|
dataset/ETHPy150Open openstack/freezer-web-ui/disaster_recovery/sessions/workflows/create.py/SessionConfigurationAction._validate_iso_format
|
8,282
|
def apply(self, justDatabase = False, noScripts = False,
capsuleChangeSet = None):
if capsuleChangeSet:
# Previous jobs will have moved the pointer in the auxilliary
# changeset, so reset it at the start of each job.
capsuleChangeSet.reset()
tmpDir = os.path.join(self.root, 'var/tmp')
if not os.path.isdir(tmpDir):
# For empty roots or roots that are not systems (e.g. source
# checkouts), just put capsules in the root directory.
tmpDir = self.root
fileDict = {}
for kind, obj in sorted(self.capsuleClasses.items()):
fileDict.update(
dict(((x[0], x[2], x[3]), x[1]) for x in obj._filesNeeded()))
try:
for ((pathId, fileId, sha1), path) in sorted(fileDict.items()):
tmpfd, tmpname = tempfile.mkstemp(dir=tmpDir, prefix=path,
suffix='.conary')
fType, fContents = self.changeSet.getFileContents(pathId,
fileId)
if (fType == changeset.ChangedFileTypes.hldr):
if (capsuleChangeSet):
try:
result = capsuleChangeSet.getFileContents(pathId,
fileId)
fObj = result[1].get()
except __HOLE__:
raise errors.MissingRollbackCapsule('Cannot find '
'RPM %s to perform local rollback' % path)
else:
fObj = fContents.get()
d = digestlib.sha1()
util.copyfileobj(fObj, os.fdopen(tmpfd, "w"), digest = d)
actualSha1 = d.digest()
if actualSha1 != sha1:
raise files.Sha1Exception(path)
# tmpfd is closed when the file object created by os.fdopen
# disappears
fileDict[(pathId, fileId)] = tmpname
for kind, obj in sorted(self.capsuleClasses.items()):
obj.apply(fileDict, justDatabase = justDatabase, noScripts = noScripts)
finally:
for tmpPath in fileDict.values():
try:
os.unlink(tmpPath)
except:
pass
|
KeyError
|
dataset/ETHPy150Open sassoftware/conary/conary/local/capsules.py/MetaCapsuleOperations.apply
|
8,283
|
def loadPlugins(self):
"""
Determine which capsule plugins are relevant to this system, and load
them.
This uses a simple test such as the existence of a directory to
determine whether each plugin is useful. At some point the contents of
the conary database should also be factored in, so that deleting the
capsule target database and running a sync should erase all of those
capsule troves.
"""
db = self._db()
for kind, (module, className, checkFunc
) in self.availablePlugins.iteritems():
if kind in self._loadedPlugins:
continue
if isinstance(checkFunc, basestring):
path = util.joinPaths(db.root, checkFunc)
try:
if not os.stat(path).st_size:
continue
except __HOLE__:
continue
else:
if not checkFunc():
continue
__import__(module)
cls = getattr(sys.modules[module], className)
self._loadedPlugins[kind] = cls(db)
|
OSError
|
dataset/ETHPy150Open sassoftware/conary/conary/local/capsules.py/MetaCapsuleDatabase.loadPlugins
|
8,284
|
@classmethod
@jsonify
def badges_user_list(cls, slug=None):
try:
game = get_game_by_slug(slug)
if game is None:
raise ApiException('No game with that slug')
# get the user from the environment
# get a user model (simulation)
user = get_current_user()
# try to get a user_id from the context
badges_obj = Badges.get_singleton(game)
badges = badges_obj.badges
badges_total_dict = dict((b['key'], b.get('total')) for b in badges)
userbadges = badges_obj.find_userbadges_by_user(user.username)
for key, userbadge in userbadges.iteritems():
del userbadge['username']
try:
total = badges_total_dict[key]
except __HOLE__:
# the badge has been deleted or its key renamed so we just skip it
continue
userbadge['total'] = total
userbadge['achieved'] = (userbadge['current'] >= total)
response.status_int = 200
return {'ok': True, 'data': userbadges.values()}
except BadgesUnsupportedException:
return {'ok': False, 'data': []}
except ApiException as message:
response.status_int = 404
return {'ok': False, 'msg': str(message)}
|
KeyError
|
dataset/ETHPy150Open turbulenz/turbulenz_local/turbulenz_local/controllers/apiv1/badges.py/BadgesController.badges_user_list
|
8,285
|
@classmethod
@badges_service
@secure_post
# add a badge to a user (gets passed
# a badge and a current level over POST,
# the username is taken from the environment)
def badges_user_add(cls, slug, params=None):
try:
session = cls._get_gamesession(params)
game = session.game
if game is None:
raise ApiException('No game with that slug')
badge_key = params['badge_key']
if not badge_key:
raise ApiException('Must specify a badge_key to add.')
# we have a badge_key now try to see if that badge exists
badges_obj = Badges.get_singleton(game)
badge = badges_obj.get_badge(badge_key)
if not badge:
raise ApiException('Badge name %s was not found.' % badge_key)
if not ('image' in badge) or not badge['image']:
badge['image'] = '/static/img/badge-46x46.png'
# Use the badge['key'] property because badge_key is unicode
ub = {'username': session.user.username,
'badge_key': badge['key']}
badge_total = badge.get('total')
total = badge_total or 1.0
current = 0
if 'current' in params:
try:
current = float(int(params['current']))
except (__HOLE__, TypeError):
response.status_int = 400
return {'ok': False, 'msg': '\'current\' must be a integer'}
if not current:
current = total
ub['current'] = current
userbadge = badges_obj.get_userbadge(session.user.username, badge_key)
Badges.get_singleton(game).upsert_badge(ub)
if current >= total and (not userbadge or userbadge.get('current', 0) < total):
achieved = True
else:
achieved = False
response.status_int = 200
return {'ok': True, 'data': {
'current': current,
'total': badge_total,
'badge_key': badge_key,
'achieved': achieved
}}
except BadgesUnsupportedException:
response.status_int = 404
return {'ok': False, 'msg': 'Badges are unsupported for this game'}
except ApiException as message:
response.status_int = 404
return {'ok': False, 'msg': str(message)}
|
ValueError
|
dataset/ETHPy150Open turbulenz/turbulenz_local/turbulenz_local/controllers/apiv1/badges.py/BadgesController.badges_user_add
|
8,286
|
def is_ip(address):
for family in (socket.AF_INET, socket.AF_INET6):
try:
if type(address) != str:
address = address.decode('utf8')
inet_pton(family, address)
return family
except (TypeError, __HOLE__, OSError, IOError):
pass
return False
|
ValueError
|
dataset/ETHPy150Open ziggear/shadowsocks/shadowsocks/common.py/is_ip
|
8,287
|
def pack_addr(address):
address_str = to_str(address)
for family in (socket.AF_INET, socket.AF_INET6):
try:
r = socket.inet_pton(family, address_str)
if family == socket.AF_INET6:
return b'\x04' + r
else:
return b'\x01' + r
except (TypeError, ValueError, __HOLE__, IOError):
pass
if len(address) > 255:
address = address[:255] # TODO
return b'\x03' + chr(len(address)) + address
|
OSError
|
dataset/ETHPy150Open ziggear/shadowsocks/shadowsocks/common.py/pack_addr
|
8,288
|
def generateGlyph(f,gname,glyphList={}):
glyphName, baseName, accentNames, offset = parseComposite(gname)
if baseName.find("_") != -1:
g = f.newGlyph(glyphName)
for componentName in baseName.split("_"):
g.appendComponent(componentName, (g.width, 0))
g.width += f[componentName].width
setUnicodeValue(g, glyphList)
else:
if not f.has_key(glyphName):
try:
f.compileGlyph(glyphName, baseName, accentNames)
except __HOLE__ as e:
print ("KeyError raised for composition rule '%s', likely %s "
"anchor not found in glyph '%s'" % (gname, e, baseName))
return
g = f[glyphName]
setUnicodeValue(g, glyphList)
copyMarkAnchors(f, g, baseName, offset[1] + offset[0])
if len(accentNames) > 0:
alignComponentsToAnchors(f, glyphName, baseName, accentNames)
if offset[0] != 0 or offset[1] != 0:
g.width += offset[1] + offset[0]
g.move((offset[0], 0), anchors=False)
else:
print ("Existing glyph '%s' found in font, ignoring composition "
"rule '%s'" % (glyphName, gname))
|
KeyError
|
dataset/ETHPy150Open google/roboto/scripts/lib/fontbuild/generateGlyph.py/generateGlyph
|
8,289
|
@synchronized('lock')
def channel(self, channel_id=None):
"""Create a new channel, or fetch the channel associated with `channel_id` if specified
:param channel_id: channel ID number
:type channel_id: int or None
:return: Channel
:rtype: amqpy.channel.Channel
"""
try:
return self.channels[channel_id]
except __HOLE__:
return Channel(self, channel_id)
|
KeyError
|
dataset/ETHPy150Open veegee/amqpy/amqpy/connection.py/Connection.channel
|
8,290
|
def _get_free_channel_id(self):
"""Get next free channel ID
:return: next free channel_id
:rtype: int
"""
try:
return self._avail_channel_ids.pop()
except __HOLE__:
raise ResourceError('No free channel ids, current={0}, channel_max={1}'.format(
len(self.channels), self.channel_max), spec.Channel.Open)
|
IndexError
|
dataset/ETHPy150Open veegee/amqpy/amqpy/connection.py/Connection._get_free_channel_id
|
8,291
|
def _claim_channel_id(self, channel_id):
"""Claim channel ID
:param channel_id: channel ID
:type channel_id: int
"""
try:
return self._avail_channel_ids.remove(channel_id)
except __HOLE__:
raise AMQPConnectionError('Channel {} already open'.format(channel_id))
|
ValueError
|
dataset/ETHPy150Open veegee/amqpy/amqpy/connection.py/Connection._claim_channel_id
|
8,292
|
def generate(PMS_uuid, url, authtoken, resolution, blurRadius):
cachepath = sys.path[0]+"/assets/fanartcache"
stylepath = sys.path[0]+"/assets/thumbnails"
# Create cache filename
id = re.search('/library/metadata/(?P<ratingKey>\S+)/art/(?P<fileId>\S+)', url)
if id:
# assumes URL in format "/library/metadata/<ratingKey>/art/fileId>"
id = id.groupdict()
cachefile = urllib.quote_plus(PMS_uuid +"_"+ id['ratingKey'] +"_"+ id['fileId'] +"_"+ resolution +"_"+ blurRadius) + ".jpg"
else:
fileid = posixpath.basename(urlparse.urlparse(url).path)
cachefile = urllib.quote_plus(PMS_uuid +"_"+ fileid +"_"+ resolution +"_"+ blurRadius) + ".jpg" # quote: just to make sure...
# Already created?
dprint(__name__, 1, 'Check for Cachefile.') # Debug
if os.path.isfile(cachepath+"/"+cachefile):
dprint(__name__, 1, 'Cachefile found.') # Debug
return "/fanartcache/"+cachefile
# No! Request Background from PMS
dprint(__name__, 1, 'No Cachefile found. Generating Background.') # Debug
try:
dprint(__name__, 1, 'Getting Remote Image.') # Debug
xargs = {}
if authtoken:
xargs['X-Plex-Token'] = authtoken
request = urllib2.Request(url, None, xargs)
response = urllib2.urlopen(request).read()
background = Image.open(io.BytesIO(response))
except urllib2.URLError as e:
dprint(__name__, 0, 'URLError: {0} // url: {1}', e.reason, url)
return "/thumbnails/Background_blank_" + resolution + ".jpg"
except urllib2.HTTPError as e:
dprint(__name__, 0, 'HTTPError: {0} {1} // url: {2}', str(e.code), e.msg, url)
return "/thumbnails/Background_blank_" + resolution + ".jpg"
except __HOLE__ as e:
dprint(__name__, 0, 'IOError: {0} // url: {1}', str(e), url)
return "/thumbnails/Background_blank_" + resolution + ".jpg"
blurRadius = int(blurRadius)
# Get gradient template
dprint(__name__, 1, 'Merging Layers.') # Debug
if resolution == '1080':
width = 1920
height = 1080
blurRegion = (0, 514, 1920, 1080)
layer = Image.open(stylepath + "/gradient_1080.png")
else:
width = 1280
height = 720
blurRegion = (0, 342, 1280, 720)
blurRadius = int(blurRadius / 1.5)
layer = Image.open(stylepath + "/gradient_720.png")
try:
# Set background resolution and merge layers
bgWidth, bgHeight = background.size
dprint(__name__,1 ,"Background size: {0}, {1}", bgWidth, bgHeight)
dprint(__name__,1 , "aTV Height: {0}, {1}", width, height)
if bgHeight != height:
background = background.resize((width, height), Image.ANTIALIAS)
dprint(__name__,1 , "Resizing background")
if blurRadius != 0:
dprint(__name__,1 , "Blurring Lower Region")
imgBlur = background.crop(blurRegion)
imgBlur = imgBlur.filter(ImageFilter.GaussianBlur(blurRadius))
background.paste(imgBlur, blurRegion)
background.paste(layer, ( 0, 0), layer)
# Save to Cache
background.save(cachepath+"/"+cachefile)
except:
dprint(__name__, 0, 'Error - Failed to generate background image.\n{0}', traceback.format_exc())
return "/thumbnails/Background_blank_" + resolution + ".jpg"
dprint(__name__, 1, 'Cachefile generated.') # Debug
return "/fanartcache/"+cachefile
# HELPERS
|
IOError
|
dataset/ETHPy150Open iBaa/PlexConnect/PILBackgrounds.py/generate
|
8,293
|
def _master_api_request(master, endpoint, post_data=None):
ip, port = master
try:
url = 'http://%s:%s/%s' % (ip, port, endpoint)
if post_data:
return requests.post(url, data=post_data, timeout=MESOS_REQUEST_TIMEOUT_SECS)
return requests.get(url, timeout=MESOS_REQUEST_TIMEOUT_SECS)
except (ConnectionError, __HOLE__, Timeout) as err:
# Potentially transient network errors - don't crash Changes
current_app.logger.warning('Network error during mesos master request (%s): %s', url, err, exc_info=True)
return []
|
HTTPError
|
dataset/ETHPy150Open dropbox/changes/changes/lib/mesos_lib.py/_master_api_request
|
8,294
|
def genes_panel(self, ax, feature):
"""
Plots gene models on an Axes.
Queries the database
:param ax: matplotlib.Axes object
:param feature: pybedtools.Interval
"""
from gffutils.contrib.plotting import Gene
extent = [feature.start, feature.stop]
nearby_genes = self.db.region(
(feature.chrom, feature.start, feature.stop), featuretype='gene')
ybase = 0
ngenes = 0
for nearby_gene in nearby_genes:
# TODO: there should be a better way of identifying which gene is
# the same as the feature requested. Might need to expose an "ID"
# kwarg.
try:
if nearby_gene['ID'][0] == feature['ID']:
color = '0.2'
else:
color = '0.5'
except __HOLE__:
color = '0.5'
ngenes += 1
extent.extend([nearby_gene.start, nearby_gene.stop])
gene_collection = Gene(
self.db,
nearby_gene,
transcripts=None,
cds=['CDS'],
utrs=['exon'],
ybase=ybase,
color=color)
gene_collection.name = nearby_gene.id
gene_collection.add_to_ax(ax)
ybase += gene_collection.max_y
xmin = min(extent)
xmax = max(extent)
ymax = ngenes
# 1% padding seems to work well
padding = (xmax - xmin) * 0.01
ax.axis('tight')
# add lines indicating extent of current feature
# vline_kwargs = dict(color='k', linestyle='--')
# ax.axvline(feature.start, **vline_kwargs)
# ax.axvline(feature.stop, **vline_kwargs)
# Make a new feature to represent the region plus surrounding genes
interval = pybedtools.create_interval_from_list(feature.fields)
interval.strand = '.'
for txt in ax.get_yticklabels():
txt.set_visible(False)
for tick in ax.get_yticklines():
tick.set_visible(False)
ax.set_ylabel('Genes')
ax.spines['right'].set_color('None')
ax.spines['left'].set_color('None')
ax.spines['top'].set_color('None')
ax.yaxis.set_ticks_position('none')
ax.xaxis.set_ticks_position('bottom')
ax.set_ylabel('Genes', rotation=0, horizontalalignment='right',
verticalalignment='center')
return interval
|
KeyError
|
dataset/ETHPy150Open daler/metaseq/metaseq/minibrowser.py/ChIPSeqMiniBrowser.genes_panel
|
8,295
|
def create_volume(name, bricks, stripe=False, replica=False, device_vg=False,
transport='tcp', start=False, force=False):
'''
Create a glusterfs volume.
name
Name of the gluster volume
bricks
Bricks to create volume from, in <peer>:<brick path> format. For \
multiple bricks use list format: '["<peer1>:<brick1>", \
"<peer2>:<brick2>"]'
stripe
Stripe count, the number of bricks should be a multiple of the stripe \
count for a distributed striped volume
replica
Replica count, the number of bricks should be a multiple of the \
replica count for a distributed replicated volume
device_vg
If true, specifies volume should use block backend instead of regular \
posix backend. Block device backend volume does not support multiple \
bricks
transport
Transport protocol to use, can be 'tcp', 'rdma' or 'tcp,rdma'
start
Start the volume after creation
force
Force volume creation, this works even if creating in root FS
CLI Example:
.. code-block:: bash
salt host1 glusterfs.create newvolume host1:/brick
salt gluster1 glusterfs.create vol2 '["gluster1:/export/vol2/brick", \
"gluster2:/export/vol2/brick"]' replica=2 start=True
'''
# If single brick given as a string, accept it
if isinstance(bricks, str):
bricks = [bricks]
# Error for block devices with multiple bricks
if device_vg and len(bricks) > 1:
raise SaltInvocationError('Block device backend volume does not ' +
'support multiple bricks')
# Validate bricks syntax
for brick in bricks:
try:
peer_name, path = brick.split(':')
if not path.startswith('/'):
raise SaltInvocationError(
'Brick paths must start with / in {0}'.format(brick))
except __HOLE__:
raise SaltInvocationError(
'Brick syntax is <peer>:<path> got {0}'.format(brick))
# Format creation call
cmd = 'volume create {0} '.format(name)
if stripe:
cmd += 'stripe {0} '.format(stripe)
if replica:
cmd += 'replica {0} '.format(replica)
if device_vg:
cmd += 'device vg '
if transport != 'tcp':
cmd += 'transport {0} '.format(transport)
cmd += ' '.join(bricks)
if force:
cmd += ' force'
if not _gluster(cmd):
return False
if start:
return start_volume(name)
return True
|
ValueError
|
dataset/ETHPy150Open saltstack/salt/salt/modules/glusterfs.py/create_volume
|
8,296
|
def mkdirp(path):
try:
os.makedirs(path)
except __HOLE__:
if os.path.isdir(path):
return
raise
|
OSError
|
dataset/ETHPy150Open dahlia/libsass-python/sass.py/mkdirp
|
8,297
|
def compile(**kwargs):
"""There are three modes of parameters :func:`compile()` can take:
``string``, ``filename``, and ``dirname``.
The ``string`` parameter is the most basic way to compile SASS.
It simply takes a string of SASS code, and then returns a compiled
CSS string.
:param string: SASS source code to compile. it's exclusive to
``filename`` and ``dirname`` parameters
:type string: :class:`str`
:param output_style: an optional coding style of the compiled result.
choose one of: ``'nested'`` (default), ``'expanded'``,
``'compact'``, ``'compressed'``
:type output_style: :class:`str`
:param source_comments: whether to add comments about source lines.
:const:`False` by default
:type source_comments: :class:`bool`
:param include_paths: an optional list of paths to find ``@import``\ ed
SASS/CSS source files
:type include_paths: :class:`collections.Sequence`, :class:`str`
:param precision: optional precision for numbers. :const:`5` by default.
:type precision: :class:`int`
:param custom_functions: optional mapping of custom functions.
see also below `custom functions
<custom-functions>`_ description
:type custom_functions: :class:`collections.Set`,
:class:`collections.Sequence`,
:class:`collections.Mapping`
:param indented: optional declaration that the string is SASS, not SCSS
formatted. :const:`False` by default
:type indented: :class:`bool`
:returns: the compiled CSS string
:param importers: optional callback functions.
see also below `importer callbacks
<importer-callbacks>`_ description
:type importers: :class:`collections.Callable`
:rtype: :class:`str`
:raises sass.CompileError: when it fails for any reason
(for example the given SASS has broken syntax)
The ``filename`` is the most commonly used way. It takes a string of
SASS filename, and then returns a compiled CSS string.
:param filename: the filename of SASS source code to compile.
it's exclusive to ``string`` and ``dirname`` parameters
:type filename: :class:`str`
:param output_style: an optional coding style of the compiled result.
choose one of: ``'nested'`` (default), ``'expanded'``,
``'compact'``, ``'compressed'``
:type output_style: :class:`str`
:param source_comments: whether to add comments about source lines.
:const:`False` by default
:type source_comments: :class:`bool`
:param source_map_filename: use source maps and indicate the source map
output filename. :const:`None` means not
using source maps. :const:`None` by default.
:type source_map_filename: :class:`str`
:param include_paths: an optional list of paths to find ``@import``\ ed
SASS/CSS source files
:type include_paths: :class:`collections.Sequence`, :class:`str`
:param precision: optional precision for numbers. :const:`5` by default.
:type precision: :class:`int`
:param custom_functions: optional mapping of custom functions.
see also below `custom functions
<custom-functions>`_ description
:type custom_functions: :class:`collections.Set`,
:class:`collections.Sequence`,
:class:`collections.Mapping`
:param importers: optional callback functions.
see also below `importer callbacks
<importer-callbacks>`_ description
:type importers: :class:`collections.Callable`
:returns: the compiled CSS string, or a pair of the compiled CSS string
and the source map string if ``source_map_filename`` is set
:rtype: :class:`str`, :class:`tuple`
:raises sass.CompileError: when it fails for any reason
(for example the given SASS has broken syntax)
:raises exceptions.IOError: when the ``filename`` doesn't exist or
cannot be read
The ``dirname`` is useful for automation. It takes a pair of paths.
The first of the ``dirname`` pair refers the source directory, contains
several SASS source files to compiled. SASS source files can be nested
in directories. The second of the pair refers the output directory
that compiled CSS files would be saved. Directory tree structure of
the source directory will be maintained in the output directory as well.
If ``dirname`` parameter is used the function returns :const:`None`.
:param dirname: a pair of ``(source_dir, output_dir)``.
it's exclusive to ``string`` and ``filename``
parameters
:type dirname: :class:`tuple`
:param output_style: an optional coding style of the compiled result.
choose one of: ``'nested'`` (default), ``'expanded'``,
``'compact'``, ``'compressed'``
:type output_style: :class:`str`
:param source_comments: whether to add comments about source lines.
:const:`False` by default
:type source_comments: :class:`bool`
:param include_paths: an optional list of paths to find ``@import``\ ed
SASS/CSS source files
:type include_paths: :class:`collections.Sequence`, :class:`str`
:param precision: optional precision for numbers. :const:`5` by default.
:type precision: :class:`int`
:param custom_functions: optional mapping of custom functions.
see also below `custom functions
<custom-functions>`_ description
:type custom_functions: :class:`collections.Set`,
:class:`collections.Sequence`,
:class:`collections.Mapping`
:raises sass.CompileError: when it fails for any reason
(for example the given SASS has broken syntax)
.. _custom-functions:
The ``custom_functions`` parameter can take three types of forms:
:class:`~collections.Set`/:class:`~collections.Sequence` of \
:class:`SassFunction`\ s
It is the most general form. Although pretty verbose, it can take
any kind of callables like type objects, unnamed functions,
and user-defined callables.
.. code-block:: python
sass.compile(
...,
custom_functions={
sass.SassFunction('func-name', ('$a', '$b'), some_callable),
...
}
)
:class:`~collections.Mapping` of names to functions
Less general, but easier-to-use form. Although it's not it can take
any kind of callables, it can take any kind of *functions* defined
using :keyword:`def`/:keyword:`lambda` syntax.
It cannot take callables other than them since inspecting arguments
is not always available for every kind of callables.
.. code-block:: python
sass.compile(
...,
custom_functions={
'func-name': lambda a, b: ...,
...
}
)
:class:`~collections.Set`/:class:`~collections.Sequence` of \
named functions
Not general, but the easiest-to-use form for *named* functions.
It can take only named functions, defined using :keyword:`def`.
It cannot take lambdas sinc names are unavailable for them.
.. code-block:: python
def func_name(a, b):
return ...
sass.compile(
...,
custom_functions={func_name}
)
.. _importer-callbacks:
Newer versions of ``libsass`` allow developers to define callbacks to be
called and given a chance to process ``@import`` directives. You can
define yours by passing in a list of callables via the ``importers``
parameter. The callables must be passed as 2-tuples in the form:
.. code-block:: python
(priority_int, callback_fn)
A priority of zero is acceptable; priority determines the order callbacks
are attempted.
These callbacks must accept a single string argument representing the path
passed to the ``@import`` directive, and either return ``None`` to
indicate the path wasn't handled by that callback (to continue with others
or fall back on internal ``libsass`` filesystem behaviour) or a list of
one or more tuples, each in one of three forms:
* A 1-tuple representing an alternate path to handle internally; or,
* A 2-tuple representing an alternate path and the content that path
represents; or,
* A 3-tuple representing the same as the 2-tuple with the addition of a
"sourcemap".
All tuple return values must be strings. As a not overly realistic
example:
.. code-block:: python
def my_importer(path):
return [(path, '#' + path + ' { color: red; }')]
sass.compile(
...,
importers=[(0, my_importer)]
)
Now, within the style source, attempting to ``@import 'button';`` will
instead attach ``color: red`` as a property of an element with the
imported name.
.. versionadded:: 0.4.0
Added ``source_comments`` and ``source_map_filename`` parameters.
.. versionchanged:: 0.6.0
The ``source_comments`` parameter becomes to take only :class:`bool`
instead of :class:`str`.
.. deprecated:: 0.6.0
Values like ``'none'``, ``'line_numbers'``, and ``'map'`` for
the ``source_comments`` parameter are deprecated.
.. versionadded:: 0.7.0
Added ``precision`` parameter.
.. versionadded:: 0.7.0
Added ``custom_functions`` parameter.
.. versionadded:: 0.11.0
``source_map_filename`` no longer implies ``source_comments``.
"""
modes = set()
for mode_name in MODES:
if mode_name in kwargs:
modes.add(mode_name)
if not modes:
raise TypeError('choose one at least in ' + and_join(MODES))
elif len(modes) > 1:
raise TypeError(and_join(modes) + ' are exclusive each other; '
'cannot be used at a time')
precision = kwargs.pop('precision', 5)
output_style = kwargs.pop('output_style', 'nested')
if not isinstance(output_style, string_types):
raise TypeError('output_style must be a string, not ' +
repr(output_style))
try:
output_style = OUTPUT_STYLES[output_style]
except KeyError:
raise CompileError('{0} is unsupported output_style; choose one of {1}'
''.format(output_style, and_join(OUTPUT_STYLES)))
source_comments = kwargs.pop('source_comments', False)
if source_comments in SOURCE_COMMENTS:
if source_comments == 'none':
deprecation_message = ('you can simply pass False to '
"source_comments instead of 'none'")
source_comments = False
elif source_comments in ('line_numbers', 'default'):
deprecation_message = ('you can simply pass True to '
"source_comments instead of " +
repr(source_comments))
source_comments = True
else:
deprecation_message = ("you don't have to pass 'map' to "
'source_comments but just need to '
'specify source_map_filename')
source_comments = False
warnings.warn(
"values like 'none', 'line_numbers', and 'map' for "
'the source_comments parameter are deprecated; ' +
deprecation_message,
DeprecationWarning
)
if not isinstance(source_comments, bool):
raise TypeError('source_comments must be bool, not ' +
repr(source_comments))
fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
source_map_filename = kwargs.pop('source_map_filename', None)
if not (source_map_filename is None or
isinstance(source_map_filename, string_types)):
raise TypeError('source_map_filename must be a string, not ' +
repr(source_map_filename))
elif isinstance(source_map_filename, text_type):
source_map_filename = source_map_filename.encode(fs_encoding)
if not ('filename' in modes or source_map_filename is None):
raise CompileError('source_map_filename is only available with '
'filename= keyword argument since it has to be '
'aware of it')
try:
include_paths = kwargs.pop('include_paths') or b''
except KeyError:
include_paths = b''
else:
if isinstance(include_paths, collections.Sequence):
include_paths = os.pathsep.join(include_paths)
elif not isinstance(include_paths, string_types):
raise TypeError('include_paths must be a sequence of strings, or '
'a colon-separated (or semicolon-separated if '
'Windows) string, not ' + repr(include_paths))
if isinstance(include_paths, text_type):
include_paths = include_paths.encode(fs_encoding)
custom_functions = kwargs.pop('custom_functions', ())
if isinstance(custom_functions, collections.Mapping):
custom_functions = [
SassFunction.from_lambda(name, lambda_)
for name, lambda_ in custom_functions.items()
]
elif isinstance(custom_functions, (collections.Set, collections.Sequence)):
custom_functions = [
func if isinstance(func, SassFunction)
else SassFunction.from_named_function(func)
for func in custom_functions
]
else:
raise TypeError(
'custom_functions must be one of:\n'
'- a set/sequence of {0.__module__}.{0.__name__} objects,\n'
'- a mapping of function name strings to lambda functions,\n'
'- a set/sequence of named functions,\n'
'not {1!r}'.format(SassFunction, custom_functions)
)
importers = _validate_importers(kwargs.pop('importers', None))
if 'string' in modes:
string = kwargs.pop('string')
if isinstance(string, text_type):
string = string.encode('utf-8')
indented = kwargs.pop('indented', False)
if not isinstance(indented, bool):
raise TypeError('indented must be bool, not ' +
repr(source_comments))
_check_no_remaining_kwargs(compile, kwargs)
s, v = _sass.compile_string(
string, output_style, source_comments, include_paths, precision,
custom_functions, indented, importers,
)
if s:
return v.decode('utf-8')
elif 'filename' in modes:
filename = kwargs.pop('filename')
if not isinstance(filename, string_types):
raise TypeError('filename must be a string, not ' + repr(filename))
elif not os.path.isfile(filename):
raise IOError('{0!r} seems not a file'.format(filename))
elif isinstance(filename, text_type):
filename = filename.encode(fs_encoding)
_check_no_remaining_kwargs(compile, kwargs)
s, v, source_map = _sass.compile_filename(
filename, output_style, source_comments, include_paths, precision,
source_map_filename, custom_functions, importers,
)
if s:
v = v.decode('utf-8')
if source_map_filename:
source_map = source_map.decode('utf-8')
v = v, source_map
return v
elif 'dirname' in modes:
try:
search_path, output_path = kwargs.pop('dirname')
except __HOLE__:
raise ValueError('dirname must be a pair of (source_dir, '
'output_dir)')
_check_no_remaining_kwargs(compile, kwargs)
s, v = compile_dirname(
search_path, output_path, output_style, source_comments,
include_paths, precision, custom_functions, importers,
)
if s:
return
else:
raise TypeError('something went wrong')
assert not s
raise CompileError(v)
|
ValueError
|
dataset/ETHPy150Open dahlia/libsass-python/sass.py/compile
|
8,298
|
def get_all_models(app):
try:
app_mod = load_app(app) # First try full path
except __HOLE__:
app_mod = get_app(app) # Then try just app_label
return get_models(app_mod)
|
ImportError
|
dataset/ETHPy150Open zlorf/django-synchro/synchro/settings.py/get_all_models
|
8,299
|
def add_cffi_module(dist, mod_spec):
from cffi.api import FFI
if not isinstance(mod_spec, basestring):
error("argument to 'cffi_modules=...' must be a str or a list of str,"
" not %r" % (type(mod_spec).__name__,))
mod_spec = str(mod_spec)
try:
build_file_name, ffi_var_name = mod_spec.split(':')
except __HOLE__:
error("%r must be of the form 'path/build.py:ffi_variable'" %
(mod_spec,))
if not os.path.exists(build_file_name):
ext = ''
rewritten = build_file_name.replace('.', '/') + '.py'
if os.path.exists(rewritten):
ext = ' (rewrite cffi_modules to [%r])' % (
rewritten + ':' + ffi_var_name,)
error("%r does not name an existing file%s" % (build_file_name, ext))
mod_vars = {'__name__': '__cffi__', '__file__': build_file_name}
execfile(build_file_name, mod_vars)
try:
ffi = mod_vars[ffi_var_name]
except KeyError:
error("%r: object %r not found in module" % (mod_spec,
ffi_var_name))
if not isinstance(ffi, FFI):
ffi = ffi() # maybe it's a function instead of directly an ffi
if not isinstance(ffi, FFI):
error("%r is not an FFI instance (got %r)" % (mod_spec,
type(ffi).__name__))
if not hasattr(ffi, '_assigned_source'):
error("%r: the set_source() method was not called" % (mod_spec,))
module_name, source, source_extension, kwds = ffi._assigned_source
if ffi._windows_unicode:
kwds = kwds.copy()
ffi._apply_windows_unicode(kwds)
if source is None:
_add_py_module(dist, ffi, module_name)
else:
_add_c_module(dist, ffi, module_name, source, source_extension, kwds)
|
ValueError
|
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/cffi-1.5.2/cffi/setuptools_ext.py/add_cffi_module
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.