Unnamed: 0
int64 0
10k
| function
stringlengths 79
138k
| label
stringclasses 20
values | info
stringlengths 42
261
|
|---|---|---|---|
9,900
|
def test_csv_export_extra_data(self):
"""Ensures exported CSV data matches source data"""
qs_filter = { "pk__in": [x.pk for x in self.snapshots] }
qs = BuildingSnapshot.objects.filter(**qs_filter)
fields = list(_get_fields_from_queryset(qs))
fields.append("canonical_building__id")
fields.append('my new field')
export_filename = export_csv(qs, fields)
export_file = open(export_filename)
reader = csv.reader(export_file)
header = reader.next()
self.assertEqual(header[len(fields)-1], 'my new field')
for i in range(len(self.snapshots)):
row = reader.next()
for j in range(len(fields)):
field = fields[j]
components = field.split("__")
qs_val = qs[i]
for component in components:
try:
qs_val = getattr(qs_val, component)
except __HOLE__:
qs_val = qs_val.extra_data.get(component)
if qs_val == None:
break
if isinstance(qs_val, Manager) or qs_val == None: qs_val = u''
else: qs_val = unicode(qs_val)
csv_val = row[j]
self.assertEqual(qs_val, csv_val)
export_file.close()
os.remove(export_filename)
|
AttributeError
|
dataset/ETHPy150Open buildingenergy/buildingenergy-platform/seed/tests/test_exporters.py/TestExporters.test_csv_export_extra_data
|
9,901
|
def main(self):
"""Main functionality
"""
try:
# Set up logging
log_fmt = '%(asctime)-15s %(levelname)-8s %(message)s'
log_level = logging.INFO
if sys.stdout.isatty():
# Connected to a real terminal - log to stdout
logging.basicConfig(format=log_fmt, level=log_level)
else:
# Background mode - log to file
logging.basicConfig(format=log_fmt, level=log_level, filename=cfg.LOG_FILENAME)
# Banner
self.logger.info("==========================================================")
self.logger.info("Pi Garage Alert starting")
# Use Raspberry Pi board pin numbers
self.logger.info("Configuring global settings")
GPIO.setmode(GPIO.BOARD)
# Configure the sensor pins as inputs with pull up resistors
for door in cfg.GARAGE_DOORS:
self.logger.info("Configuring pin %d for \"%s\"", door['pin'], door['name'])
GPIO.setup(door['pin'], GPIO.IN, pull_up_down=GPIO.PUD_UP)
# Last state of each garage door
door_states = dict()
# time.time() of the last time the garage door changed state
time_of_last_state_change = dict()
# Index of the next alert to send for each garage door
alert_states = dict()
# Create alert sending objects
alert_senders = {
"Jabber": Jabber(door_states, time_of_last_state_change),
"Twitter": Twitter(),
"Twilio": Twilio(),
"Email": Email(),
"Pushbullet": Pushbullet(),
"Gcm": GoogleCloudMessaging()
}
# Read initial states
for door in cfg.GARAGE_DOORS:
name = door['name']
state = get_garage_door_state(door['pin'])
door_states[name] = state
time_of_last_state_change[name] = time.time()
alert_states[name] = 0
self.logger.info("Initial state of \"%s\" is %s", name, state)
status_report_countdown = 5
while True:
for door in cfg.GARAGE_DOORS:
name = door['name']
state = get_garage_door_state(door['pin'])
time_in_state = time.time() - time_of_last_state_change[name]
# Check if the door has changed state
if door_states[name] != state:
door_states[name] = state
time_of_last_state_change[name] = time.time()
self.logger.info("State of \"%s\" changed to %s after %.0f sec", name, state, time_in_state)
# Reset alert when door changes state
if alert_states[name] > 0:
# Use the recipients of the last alert
recipients = door['alerts'][alert_states[name] - 1]['recipients']
send_alerts(self.logger, alert_senders, recipients, name, "%s is now %s" % (name, state), state)
alert_states[name] = 0
# Reset time_in_state
time_in_state = 0
# See if there are more alerts
if len(door['alerts']) > alert_states[name]:
# Get info about alert
alert = door['alerts'][alert_states[name]]
# Has the time elapsed and is this the state to trigger the alert?
if time_in_state > alert['time'] and state == alert['state']:
send_alerts(self.logger, alert_senders, alert['recipients'], name, "%s has been %s for %d seconds!" % (name, state, time_in_state), state)
alert_states[name] += 1
# Periodically log the status for debug and ensuring RPi doesn't get too hot
status_report_countdown -= 1
if status_report_countdown <= 0:
status_msg = rpi_status()
for name in door_states:
status_msg += ", %s: %s/%d/%d" % (name, door_states[name], alert_states[name], (time.time() - time_of_last_state_change[name]))
self.logger.info(status_msg)
status_report_countdown = 600
# Poll every 1 second
time.sleep(1)
except __HOLE__:
logging.critical("Terminating due to keyboard interrupt")
except:
logging.critical("Terminating due to unexpected error: %s", sys.exc_info()[0])
logging.critical("%s", traceback.format_exc())
GPIO.cleanup() # pylint: disable=no-member
alert_senders['Jabber'].terminate()
|
KeyboardInterrupt
|
dataset/ETHPy150Open rllynch/pi_garage_alert/bin/pi_garage_alert.py/PiGarageAlert.main
|
9,902
|
def _escaped_text_from_text(text, escapes="eol"):
r"""Return escaped version of text.
"escapes" is either a mapping of chars in the source text to
replacement text for each such char or one of a set of
strings identifying a particular escape style:
eol
replace EOL chars with '\r' and '\n', maintain the actual
EOLs though too
whitespace
replace EOL chars as above, tabs with '\t' and spaces
with periods ('.')
eol-one-line
replace EOL chars with '\r' and '\n'
whitespace-one-line
replace EOL chars as above, tabs with '\t' and spaces
with periods ('.')
"""
#TODO:
# - Add 'c-string' style.
# - Add _escaped_html_from_text() with a similar call sig.
import re
if isinstance(escapes, base_string_type):
if escapes == "eol":
escapes = {'\r\n': "\\r\\n\r\n", '\n': "\\n\n", '\r': "\\r\r"}
elif escapes == "whitespace":
escapes = {'\r\n': "\\r\\n\r\n", '\n': "\\n\n", '\r': "\\r\r",
'\t': "\\t", ' ': "."}
elif escapes == "eol-one-line":
escapes = {'\n': "\\n", '\r': "\\r"}
elif escapes == "whitespace-one-line":
escapes = {'\n': "\\n", '\r': "\\r", '\t': "\\t", ' ': '.'}
else:
raise ValueError("unknown text escape style: %r" % escapes)
# Sort longer replacements first to allow, e.g. '\r\n' to beat '\r' and
# '\n'.
escapes_keys = list(escapes.keys())
try:
escapes_keys.sort(key=lambda a: len(a), reverse=True)
except __HOLE__:
# Python 2.3 support: sort() takes no keyword arguments
escapes_keys.sort(lambda a,b: cmp(len(a), len(b)))
escapes_keys.reverse()
def repl(match):
val = escapes[match.group(0)]
return val
escaped = re.sub("(%s)" % '|'.join([re.escape(k) for k in escapes_keys]),
repl,
text)
return escaped
|
TypeError
|
dataset/ETHPy150Open an0/Letterpress/code/markdown2/test/test_markdown2.py/_escaped_text_from_text
|
9,903
|
def complete(self, area):
"""
"""
try:
self.seq.next()
except __HOLE__:
pass
|
StopIteration
|
dataset/ETHPy150Open iogf/vy/vyapp/plugins/quick_completion.py/QuickCompletion.complete
|
9,904
|
def import_matches(query, prefix=''):
matches = set(re.findall(r"(%s[a-zA-Z_][a-zA-Z0-9_]*)\.?" % prefix, query))
for raw_module_name in matches:
if re.match('np(\..*)?$', raw_module_name):
module_name = re.sub('^np', 'numpy', raw_module_name)
elif re.match('pd(\..*)?$', raw_module_name):
module_name = re.sub('^pd', 'pandas', raw_module_name)
else:
module_name = raw_module_name
try:
module = __import__(module_name)
globals()[raw_module_name] = module
import_matches(query, prefix='%s.' % module_name)
except __HOLE__ as e:
pass
|
ImportError
|
dataset/ETHPy150Open Russell91/pythonpy/pythonpy/__main__.py/import_matches
|
9,905
|
def test_instance(self):
Point = namedtuple('Point', 'x y')
p = Point(11, 22)
self.assertEqual(p, Point(x=11, y=22))
self.assertEqual(p, Point(11, y=22))
self.assertEqual(p, Point(y=22, x=11))
self.assertEqual(p, Point(*(11, 22)))
self.assertEqual(p, Point(**dict(x=11, y=22)))
self.assertRaises(TypeError, Point, 1) # too few args
self.assertRaises(TypeError, Point, 1, 2, 3) # too many args
self.assertRaises(TypeError, eval, 'Point(XXX=1, y=2)', locals()) # wrong keyword argument
self.assertRaises(TypeError, eval, 'Point(x=1)', locals()) # missing keyword argument
self.assertEqual(repr(p), 'Point(x=11, y=22)')
self.assertNotIn('__weakref__', dir(p))
self.assertEqual(p, Point._make([11, 22])) # test _make classmethod
self.assertEqual(p._fields, ('x', 'y')) # test _fields attribute
self.assertEqual(p._replace(x=1), (1, 22)) # test _replace method
self.assertEqual(p._asdict(), dict(x=11, y=22)) # test _asdict method
self.assertEqual(vars(p), p._asdict()) # verify that vars() works
try:
p._replace(x=1, error=2)
except __HOLE__:
pass
else:
self._fail('Did not detect an incorrect fieldname')
# verify that field string can have commas
Point = namedtuple('Point', 'x, y')
p = Point(x=11, y=22)
self.assertEqual(repr(p), 'Point(x=11, y=22)')
# verify that fieldspec can be a non-string sequence
Point = namedtuple('Point', ('x', 'y'))
p = Point(x=11, y=22)
self.assertEqual(repr(p), 'Point(x=11, y=22)')
|
ValueError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_collections.py/TestNamedTuple.test_instance
|
9,906
|
@classmethod
def from_row(cls, row_dict):
tag = row_dict.get('table_id') or row_dict.get('tag')
if tag is None:
raise ExcelMalformatException(_(FAILURE_MESSAGES['has_no_column']).format(column_name='table_id'))
field_names = row_dict.get('field')
item_attributes = row_dict.get('property')
if field_names is None and item_attributes is None:
raise ExcelMalformatException(_(FAILURE_MESSAGES['neither_fields_nor_attributes']).format(tag=tag))
field_names = [] if field_names is None else field_names
item_attributes = [] if item_attributes is None else item_attributes
def _get_field_properties(prop_key):
if row_dict.has_key(prop_key):
try:
properties = row_dict[prop_key]["property"]
assert isinstance(properties, list)
except (__HOLE__, AssertionError):
error_message = _(FAILURE_MESSAGES["wrong_property_syntax"]).format(
prop_key=prop_key,
)
raise ExcelMalformatException(error_message)
else:
return properties
else:
return []
fields = [
FixtureTypeField(
field_name=field,
properties=_get_field_properties('field {count}'.format(count=i + 1))
) for i, field in enumerate(field_names)
]
return FixtureTableDefinition(
table_id=tag,
fields=fields,
item_attributes=item_attributes,
is_global=row_dict.get('is_global', False),
uid=row_dict.get('UID'),
delete=(row_dict.get(DELETE_HEADER) or '').lower() == 'y',
)
|
KeyError
|
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/fixtures/upload.py/FixtureTableDefinition.from_row
|
9,907
|
def __init__(self, file_or_filename):
try:
self.workbook = WorkbookJSONReader(file_or_filename)
except __HOLE__:
raise FixtureUploadError(_("Error processing your Excel (.xlsx) file"))
except InvalidFileException:
raise FixtureUploadError(_("Invalid file-format. Please upload a valid xlsx file."))
|
AttributeError
|
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/fixtures/upload.py/FixtureWorkbook.__init__
|
9,908
|
def run_upload(domain, workbook, replace=False, task=None):
from corehq.apps.users.bulkupload import GroupMemoizer
return_val = FixtureUploadResult()
group_memoizer = GroupMemoizer(domain)
get_location = get_memoized_location(domain)
def diff_lists(list_a, list_b):
set_a = set(list_a)
set_b = set(list_b)
not_in_b = set_a.difference(set_b)
not_in_a = set_a.difference(set_a)
return list(not_in_a), list(not_in_b)
with CouchTransaction() as transaction:
type_sheets = workbook.get_all_type_sheets()
total_tables = len(type_sheets)
return_val.number_of_fixtures = total_tables
def _update_progress(table_count, item_count, items_in_table):
if task:
processed = table_count * 10 + (10. * item_count / items_in_table)
DownloadBase.set_progress(task, processed, 10 * total_tables)
for table_number, table_def in enumerate(type_sheets):
tag = table_def.table_id
new_data_type = FixtureDataType(
domain=domain,
is_global=table_def.is_global,
tag=table_def.table_id,
fields=table_def.fields,
item_attributes=table_def.item_attributes
)
try:
tagged_fdt = FixtureDataType.fixture_tag_exists(domain, tag)
if tagged_fdt:
data_type = tagged_fdt
# support old usage with 'UID'
elif table_def.uid:
data_type = FixtureDataType.get(table_def.uid)
else:
data_type = new_data_type
if replace and data_type != new_data_type:
data_type.recursive_delete(transaction)
data_type = new_data_type
data_type.fields = table_def.fields
data_type.item_attributes = table_def.item_attributes
data_type.is_global = table_def.is_global
assert data_type.doc_type == FixtureDataType._doc_type
if data_type.domain != domain:
data_type = new_data_type
return_val.errors.append(_("'%(UID)s' is not a valid UID. But the new type is created.") % {'UID': table_def.uid})
if table_def.delete:
data_type.recursive_delete(transaction)
continue
except (ResourceNotFound, KeyError) as e:
data_type = new_data_type
transaction.save(data_type)
data_items = list(workbook.get_data_sheet(data_type))
items_in_table = len(data_items)
for sort_key, di in enumerate(data_items):
_update_progress(table_number, sort_key, items_in_table)
# Check that type definitions in 'types' sheet vs corresponding columns in the item-sheet MATCH
item_fields_list = di['field'].keys() if 'field' in di else []
not_in_sheet, not_in_types = diff_lists(item_fields_list, data_type.fields_without_attributes)
if len(not_in_sheet) > 0:
error_message = _(FAILURE_MESSAGES["has_no_field_column"]).format(tag=tag, field=not_in_sheet[0])
raise ExcelMalformatException(error_message)
if len(not_in_types) > 0:
error_message = _(FAILURE_MESSAGES["has_extra_column"]).format(tag=tag, field=not_in_types[0])
raise ExcelMalformatException(error_message)
# check that this item has all the properties listed in its 'types' definition
item_attributes_list = di['property'].keys() if 'property' in di else []
not_in_sheet, not_in_types = diff_lists(item_attributes_list, data_type.item_attributes)
if len(not_in_sheet) > 0:
error_message = _(FAILURE_MESSAGES["has_no_field_column"]).format(tag=tag, field=not_in_sheet[0])
raise ExcelMalformatException(error_message)
if len(not_in_types) > 0:
error_message = _(FAILURE_MESSAGES["has_extra_column"]).format(tag=tag, field=not_in_types[0])
raise ExcelMalformatException(error_message)
# check that properties in 'types' sheet vs item-sheet MATCH
for field in data_type.fields:
if len(field.properties) > 0:
sheet_props = di.get(field.field_name, {})
sheet_props_list = sheet_props.keys()
type_props = field.properties
not_in_sheet, not_in_types = diff_lists(sheet_props_list, type_props)
if len(not_in_sheet) > 0:
error_message = _(FAILURE_MESSAGES["sheet_has_no_property"]).format(
tag=tag,
property=not_in_sheet[0],
field=field.field_name
)
raise ExcelMalformatException(error_message)
if len(not_in_types) > 0:
error_message = _(FAILURE_MESSAGES["sheet_has_extra_property"]).format(
tag=tag,
property=not_in_types[0],
field=field.field_name
)
raise ExcelMalformatException(error_message)
# check that fields with properties are numbered
if type(di['field'][field.field_name]) != list:
error_message = _(FAILURE_MESSAGES["invalid_field_with_property"]).format(field=field.field_name)
raise ExcelMalformatException(error_message)
field_prop_len = len(di['field'][field.field_name])
for prop in sheet_props:
if type(sheet_props[prop]) != list:
error_message = _(FAILURE_MESSAGES["invalid_property"]).format(
field=field.field_name,
prop=prop
)
raise ExcelMalformatException(error_message)
if len(sheet_props[prop]) != field_prop_len:
error_message = _(FAILURE_MESSAGES["wrong_field_property_combos"]).format(
field=field.field_name,
prop=prop
)
raise ExcelMalformatException(error_message)
# excel format check should have been covered by this line. Can make assumptions about data now
type_fields = data_type.fields
item_fields = {}
for field in type_fields:
# if field doesn't have properties
if len(field.properties) == 0:
item_fields[field.field_name] = FieldList(
field_list=[FixtureItemField(
# using unicode here, to cast ints, and multi-language strings
field_value=unicode(di['field'][field.field_name]),
properties={}
)]
)
else:
field_list = []
field_prop_combos = di['field'][field.field_name]
prop_combo_len = len(field_prop_combos)
prop_dict = di[field.field_name]
for x in range(0, prop_combo_len):
fix_item_field = FixtureItemField(
field_value=unicode(field_prop_combos[x]),
properties={prop: unicode(prop_dict[prop][x]) for prop in prop_dict}
)
field_list.append(fix_item_field)
item_fields[field.field_name] = FieldList(
field_list=field_list
)
item_attributes = di.get('property', {})
new_data_item = FixtureDataItem(
domain=domain,
data_type_id=data_type.get_id,
fields=item_fields,
item_attributes=item_attributes,
sort_key=sort_key
)
try:
if di['UID'] and not replace:
old_data_item = FixtureDataItem.get(di['UID'])
else:
old_data_item = new_data_item
pass
old_data_item.fields = item_fields
old_data_item.item_attributes = item_attributes
if old_data_item.domain != domain or not old_data_item.data_type_id == data_type.get_id:
old_data_item = new_data_item
return_val.errors.append(_("'%(UID)s' is not a valid UID. But the new item is created.") % {'UID': di['UID']})
assert old_data_item.doc_type == FixtureDataItem._doc_type
if di[DELETE_HEADER] == "Y" or di[DELETE_HEADER] == "y":
old_data_item.recursive_delete(transaction)
continue
except (ResourceNotFound, __HOLE__):
old_data_item = new_data_item
transaction.save(old_data_item)
old_groups = old_data_item.groups
for group in old_groups:
old_data_item.remove_group(group)
old_users = old_data_item.users
for user in old_users:
old_data_item.remove_user(user)
old_locations = old_data_item.locations
for location in old_locations:
old_data_item.remove_location(location)
for group_name in di.get('group', []):
group = group_memoizer.by_name(group_name)
if group:
old_data_item.add_group(group, transaction=transaction)
else:
return_val.errors.append(_("Unknown group: '%(name)s'. But the row is successfully added") % {'name': group_name})
for raw_username in di.get('user', []):
try:
username = normalize_username(str(raw_username), domain)
except ValidationError:
return_val.errors.append(_("Invalid username: '%(name)s'. Row is not added") % {'name': raw_username})
continue
user = CommCareUser.get_by_username(username)
if user:
old_data_item.add_user(user)
else:
return_val.errors.append(_("Unknown user: '%(name)s'. But the row is successfully added") % {'name': raw_username})
for name in di.get('location', []):
location_cache = get_location(name)
if location_cache.is_error:
return_val.errors.append(location_cache.message)
else:
old_data_item.add_location(location_cache.location,
transaction=transaction)
return return_val
|
KeyError
|
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/fixtures/upload.py/run_upload
|
9,909
|
def init_database(self):
self.raw_db = create_engine(self.config['url'], echo=False)
self.raw_conn = self.raw_db.connect()
self.operations = Operations(self.raw_conn, self.config)
try:
self.raw_conn.connection.set_isolation_level(0)
except __HOLE__:
logger.info('Could not set isolation level to 0')
self.db = create_engine(self.config['stellar_url'], echo=False)
self.db.session = sessionmaker(bind=self.db)()
self.raw_db.session = sessionmaker(bind=self.raw_db)()
tables_missing = self.create_stellar_database()
self.create_stellar_tables()
# logger.getLogger('sqlalchemy.engine').setLevel(logger.WARN)
|
AttributeError
|
dataset/ETHPy150Open fastmonkeys/stellar/stellar/app.py/Stellar.init_database
|
9,910
|
def _process_response(self, response, message):
"""Process response from remote side."""
LOG.debug("Started processing response message '%s'",
ku.DelayedPretty(message))
try:
request_uuid = message.properties['correlation_id']
except __HOLE__:
LOG.warning("The 'correlation_id' message property is"
" missing in message '%s'",
ku.DelayedPretty(message))
else:
request = self._ongoing_requests.get(request_uuid)
if request is not None:
response = pr.Response.from_dict(response)
LOG.debug("Extracted response '%s' and matched it to"
" request '%s'", response, request)
if response.state == pr.RUNNING:
request.transition_and_log_error(pr.RUNNING, logger=LOG)
elif response.state == pr.EVENT:
# Proxy the event + details to the task notifier so
# that it shows up in the local process (and activates
# any local callbacks...); thus making it look like
# the task is running locally (in some regards).
event_type = response.data['event_type']
details = response.data['details']
request.task.notifier.notify(event_type, details)
elif response.state in (pr.FAILURE, pr.SUCCESS):
if request.transition_and_log_error(response.state,
logger=LOG):
with self._ongoing_requests_lock:
del self._ongoing_requests[request.uuid]
request.set_result(result=response.data['result'])
else:
LOG.warning("Unexpected response status '%s'",
response.state)
else:
LOG.debug("Request with id='%s' not found", request_uuid)
|
KeyError
|
dataset/ETHPy150Open openstack/taskflow/taskflow/engines/worker_based/executor.py/WorkerTaskExecutor._process_response
|
9,911
|
def _clean(self):
if not self._ongoing_requests:
return
with self._ongoing_requests_lock:
ongoing_requests_uuids = set(six.iterkeys(self._ongoing_requests))
waiting_requests = {}
expired_requests = {}
for request_uuid in ongoing_requests_uuids:
try:
request = self._ongoing_requests[request_uuid]
except __HOLE__:
# Guess it got removed before we got to it...
pass
else:
if request.expired:
expired_requests[request_uuid] = request
elif request.current_state == pr.WAITING:
waiting_requests[request_uuid] = request
if expired_requests:
with self._ongoing_requests_lock:
while expired_requests:
request_uuid, request = expired_requests.popitem()
if self._handle_expired_request(request):
del self._ongoing_requests[request_uuid]
if waiting_requests:
finder = self._finder
new_messages_processed = finder.messages_processed
last_messages_processed = self._messages_processed['finder']
if new_messages_processed > last_messages_processed:
# Some new message got to the finder, so we can see
# if any new workers match (if no new messages have been
# processed we might as well not do anything).
while waiting_requests:
_request_uuid, request = waiting_requests.popitem()
worker = finder.get_worker_for_task(request.task)
if (worker is not None and
request.transition_and_log_error(pr.PENDING,
logger=LOG)):
self._publish_request(request, worker)
self._messages_processed['finder'] = new_messages_processed
|
KeyError
|
dataset/ETHPy150Open openstack/taskflow/taskflow/engines/worker_based/executor.py/WorkerTaskExecutor._clean
|
9,912
|
def inlines(value, return_list=False):
try:
from BeautifulSoup import BeautifulSoup
except __HOLE__:
from beautifulsoup import BeautifulSoup
content = BeautifulSoup(value, selfClosingTags=['inline','img','br','input','meta','link','hr'])
inline_list = []
if return_list:
for inline in content.findAll(is_inline):
rendered_inline = render_inline(inline)
inline_list.append(rendered_inline['context'])
return inline_list
else:
for inline in content.findAll(is_inline):
rendered_inline = render_inline(inline)
if rendered_inline:
inline.replaceWith(BeautifulSoup(render_to_string(rendered_inline['template'], rendered_inline['context'])))
else:
inline.replaceWith('')
return mark_safe(content)
|
ImportError
|
dataset/ETHPy150Open issackelly/django-improved-inlines/improved_inlines/parser.py/inlines
|
9,913
|
def render_inline(inline):
"""
Replace inline markup with template markup that matches the
appropriate app and model.
"""
# Look for inline model type, 'app.model'
if inline.name == 'inline':
model_string = inline.get('type', None)
else:
model_string = inline.get('data-inline-type', None)
if not model_string:
if settings.DEBUG:
raise TemplateSyntaxError, "Couldn't find a model attribute in the <%s> tag." % inline.name
else:
return ''
app_label, model_name = model_string.split('.')
# Look for content type
try:
content_type = ContentType.objects.get(app_label=app_label, model=model_name)
model = content_type.model_class()
except ContentType.DoesNotExist:
if settings.DEBUG:
raise TemplateSyntaxError, "Inline ContentType not found for '%s.%s'." % (app_label, model_name)
else:
return ''
# Check for an inline class attribute
inline_class = smart_unicode(inline.get('class', ''))
inline_attr = get_inline_attr(inline)
if not inline_attr:
return ''
if inline_attr.get("ids", None):
# The tag has the 'ids' attribute, process accordingly...
id_list = [int(i) for i in inline_attr["ids"].split(',')]
obj_list = model.objects.in_bulk(id_list)
obj_list = list(obj_list[int(i)] for i in id_list)
context = { 'object_list': obj_list, 'class': inline_class }
elif inline_attr.get("id", None):
# The tag has the 'id' attribute, process accordingly...
try:
obj = model.objects.get(pk=inline_attr["id"])
except model.DoesNotExist:
if settings.DEBUG:
raise model.DoesNotExist, "%s with pk of '%s' does not exist" % (model_name, inline_attr["id"])
else:
return ''
context = { 'content_type':"%s.%s" % (app_label, model_name), 'object': obj, 'class': inline_class, 'settings': settings }
elif inline_attr.get("filter", None):
# The tag has the 'filter' attribute, process accordingly...
try:
l = inline_attr["filter"].split(',')
filterdict = dict()
for item in l:
try:
# This is just here to raise a ValueError if there is no '='
item.index('=')
parts = item.split('=')
## This should work for text, Need to test for all sorts of values
# Note: Potentially dangerous use of eval
filterdict[str(parts[0])] = eval(parts[1])
except __HOLE__:
pass
obj_list = list(model.objects.filter(**filterdict))
context = { 'object_list': obj_list, 'class': inline_class }
except KeyError:
if settings.DEBUG:
raise TemplateSyntaxError, "The <inline> filter attribute is missing or invalid."
else:
return ''
except ValueError:
if settings.DEBUG:
raise TemplateSyntaxError, inline_attr["filter"] + ' is bad, dummy.'
else:
return ''
else:
raise ValueError
# Set Default Template
template = list()
if inline.get('template', None):
template.insert(0, inline.get('template'))
if inline.get('data-inline-template', None):
template.insert(0, inline.get('data-inline-template'))
template.extend(["inlines/%s_%s.html" % (app_label, model_name), "inlines/default.html"])
rendered_inline = {'template': template, 'context': context}
return rendered_inline
|
ValueError
|
dataset/ETHPy150Open issackelly/django-improved-inlines/improved_inlines/parser.py/render_inline
|
9,914
|
def DSQuery(dstype, objectname, attribute=None, node='.'):
"""DirectoryServices query.
Args:
dstype: The type of objects to query. user, group.
objectname: the object to query.
attribute: the optional attribute to query.
node: the node to query.
Returns:
If an attribute is specified, the value of the attribute. Otherwise, the
entire plist.
Raises:
DSException: Cannot query DirectoryServices.
"""
ds_path = '/%ss/%s' % (dstype.capitalize(), objectname)
cmd = [_DSCL, '-plist', node, '-read', ds_path]
if attribute:
cmd.append(attribute)
(stdout, stderr, returncode) = gmacpyutil.RunProcess(cmd)
if returncode:
raise DSException('Cannot query %s for %s: %s' % (ds_path,
attribute,
stderr))
plist = NSString.stringWithString_(stdout).propertyList()
if attribute:
value = None
if 'dsAttrTypeStandard:%s' % attribute in plist:
value = plist['dsAttrTypeStandard:%s' % attribute]
elif attribute in plist:
value = plist[attribute]
try:
# We're copying to a new list to convert from NSCFArray
return value[:]
except __HOLE__:
# ... unless we can't
return value
else:
return plist
|
TypeError
|
dataset/ETHPy150Open google/macops/gmacpyutil/gmacpyutil/ds.py/DSQuery
|
9,915
|
def SyncShadowHash(username, shadow_name):
"""Sync the password hash for the shadow admin account with the user's."""
shadow_guid = UserAttribute(shadow_name, 'GeneratedUID')
user_hash = '/var/db/shadow/hash/%s' % username
if not os.path.exists(user_hash):
user_guid = UserAttribute(username, 'GeneratedUID')[0]
user_hash = '/var/db/shadow/hash/%s' % user_guid
shadow_hash = '/var/db/shadow/hash/%s' % shadow_guid[0]
try:
if (os.path.exists(shadow_hash)
and os.path.isfile(shadow_hash)
and filecmp.cmp(user_hash, shadow_hash, shallow=False)):
# everything is as should be
pass
else:
shutil.copy2(user_hash, shadow_hash)
except (IOError, __HOLE__), err:
raise DSException('Error creating the shadow admin hash for '
'%s-admin: %s' % (username, err))
|
OSError
|
dataset/ETHPy150Open google/macops/gmacpyutil/gmacpyutil/ds.py/SyncShadowHash
|
9,916
|
@classmethod
def default_decoder(cls, value):
try:
return pyrfc3339.parse(value)
except __HOLE__ as error:
raise jose.DeserializationError(error)
|
ValueError
|
dataset/ETHPy150Open letsencrypt/letsencrypt/acme/acme/fields.py/RFC3339Field.default_decoder
|
9,917
|
def main(argv):
if not validate_argv(argv):
print(pysb.export.__doc__, end=' ')
return 1
model_filename = argv[1]
format = argv[2]
# Make sure that the user has supplied an allowable format
if format not in pysb.export.formats.keys():
raise Exception("The format must be one of the following: " +
", ".join(pysb.export.formats.keys()) + ".")
# Sanity checks on filename
if not os.path.exists(model_filename):
raise Exception("File '%s' doesn't exist" % model_filename)
if not re.search(r'\.py$', model_filename):
raise Exception("File '%s' is not a .py file" % model_filename)
sys.path.insert(0, os.path.dirname(model_filename))
model_name = re.sub(r'\.py$', '', os.path.basename(model_filename))
# import it
try:
# FIXME if the model has the same name as some other "real" module
# which we use, there will be trouble (use the imp package and import
# as some safe name?)
model_module = __import__(model_name)
except Exception as e:
print("Error in model script:\n")
raise
# grab the 'model' variable from the module
try:
model = model_module.__dict__['model']
except __HOLE__:
raise Exception("File '%s' isn't a model file" % model_filename)
# Export the model
print(pysb.export.export(model, format, model_module.__doc__))
return 0
|
KeyError
|
dataset/ETHPy150Open pysb/pysb/pysb/export/__main__.py/main
|
9,918
|
def encode_text(text):
if isinstance(text, six.text_type):
return text.encode('utf-8')
try:
return text.decode('utf-8').encode('utf-8')
except (__HOLE__, UnicodeEncodeError):
return text.encode('ascii', 'replace')
|
UnicodeDecodeError
|
dataset/ETHPy150Open pudo/archivekit/archivekit/util.py/encode_text
|
9,919
|
def json_hook(obj):
for k, v in obj.items():
if isinstance(v, basestring):
try:
obj[k] = datetime.strptime(v, "new Date(%Y-%m-%d)").date()
except __HOLE__:
pass
try:
obj[k] = datetime.strptime(v, "%Y-%m-%dT%H:%M:%S")
except ValueError:
pass
return obj
|
ValueError
|
dataset/ETHPy150Open pudo/archivekit/archivekit/util.py/json_hook
|
9,920
|
def _checkCPython(sys=sys, platform=platform):
"""
Checks if this implementation is CPython.
On recent versions of Python, will use C{platform.python_implementation}.
On 2.5, it will try to extract the implementation from sys.subversion. On
older versions (currently the only supported older version is 2.4), checks
if C{__pypy__} is in C{sys.modules}, since PyPy is the implementation we
really care about. If it isn't, assumes CPython.
This takes C{sys} and C{platform} kwargs that by default use the real
modules. You shouldn't care about these -- they are for testing purposes
only.
@return: C{False} if the implementation is definitely not CPython, C{True}
otherwise.
"""
try:
return platform.python_implementation() == "CPython"
except AttributeError:
# For 2.5:
try:
implementation, _, _ = sys.subversion
return implementation == "CPython"
except __HOLE__:
pass
# Are we on Pypy?
if "__pypy__" in sys.modules:
return False
# No? Well, then we're *probably* on CPython.
return True
|
AttributeError
|
dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/python/dist.py/_checkCPython
|
9,921
|
@auth
def _POST(self, *param, **params):
if not validates_icon(self):
self.logger.debug("Create Icon is failed, Invalid input value")
return web.badrequest(add_prefix(self.view.alert, "400"))
icon_filevalue = self.input.multi_icon.value
icon_filename = "%s.%s" % (uniq_filename(), imghdr.what(None, icon_filevalue))
if is_path(icon_filename) is True:
return web.badrequest("Not to include the path.")
icon_realpath = ICON_DIR_TPL % (karesansui.dirname, icon_filename)
icon_webpath = ICON_DIR_TPL % (web.ctx.homepath, icon_filename)
if os.path.exists(icon_realpath):
web.conflict(icon_webpath, add_prefix("icon already exists", "409"))
try:
create_file(icon_realpath, icon_filevalue)
except __HOLE__, ioe:
self.logger.error("Failed to write icon file. - filename=%s" % icon_filename)
return web.internalerror(add_prefix("Failed to create icon file.", "500"))
return web.created(icon_webpath, icon_filename)
|
IOError
|
dataset/ETHPy150Open karesansui/karesansui/karesansui/gadget/icon.py/Icon._POST
|
9,922
|
@auth
def _DELETE(self, *param, **params):
icon_filename = param[0]
if is_path(icon_filename) is True:
return web.badrequest("Not to include the path.")
icon_realpath = ICON_DIR_TPL % (karesansui.dirname, icon_filename)
if not os.path.exists(icon_realpath):
return web.notfound("icon not exists")
try:
remove_file(icon_realpath)
except __HOLE__, ose:
self.logger.error("Failed to remove icon file. - filename=%s" % icon_filename)
raise # return 500(Internal Server Error)
return web.seeother("/")
|
OSError
|
dataset/ETHPy150Open karesansui/karesansui/karesansui/gadget/icon.py/IconBy1._DELETE
|
9,923
|
def relativeairmass(zenith, model='kastenyoung1989'):
'''
Gives the relative (not pressure-corrected) airmass.
Gives the airmass at sea-level when given a sun zenith angle (in
degrees). The ``model`` variable allows selection of different
airmass models (described below). If ``model`` is not included or is
not valid, the default model is 'kastenyoung1989'.
Parameters
----------
zenith : float or Series
Zenith angle of the sun in degrees. Note that some models use
the apparent (refraction corrected) zenith angle, and some
models use the true (not refraction-corrected) zenith angle. See
model descriptions to determine which type of zenith angle is
required. Apparent zenith angles must be calculated at sea level.
model : String
Available models include the following:
* 'simple' - secant(apparent zenith angle) -
Note that this gives -inf at zenith=90
* 'kasten1966' - See reference [1] -
requires apparent sun zenith
* 'youngirvine1967' - See reference [2] -
requires true sun zenith
* 'kastenyoung1989' - See reference [3] -
requires apparent sun zenith
* 'gueymard1993' - See reference [4] -
requires apparent sun zenith
* 'young1994' - See reference [5] -
requries true sun zenith
* 'pickering2002' - See reference [6] -
requires apparent sun zenith
Returns
-------
airmass_relative : float or Series
Relative airmass at sea level. Will return NaN values for any
zenith angle greater than 90 degrees.
References
----------
[1] Fritz Kasten. "A New Table and Approximation Formula for the
Relative Optical Air Mass". Technical Report 136, Hanover, N.H.:
U.S. Army Material Command, CRREL.
[2] A. T. Young and W. M. Irvine, "Multicolor Photoelectric
Photometry of the Brighter Planets," The Astronomical Journal, vol.
72, pp. 945-950, 1967.
[3] Fritz Kasten and Andrew Young. "Revised optical air mass tables
and approximation formula". Applied Optics 28:4735-4738
[4] C. Gueymard, "Critical analysis and performance assessment of
clear sky solar irradiance models using theoretical and measured
data," Solar Energy, vol. 51, pp. 121-138, 1993.
[5] A. T. Young, "AIR-MASS AND REFRACTION," Applied Optics, vol. 33,
pp. 1108-1110, Feb 1994.
[6] Keith A. Pickering. "The Ancient Star Catalog". DIO 12:1, 20,
[7] Matthew J. Reno, Clifford W. Hansen and Joshua S. Stein, "Global
Horizontal Irradiance Clear Sky Models: Implementation and Analysis"
Sandia Report, (2012).
'''
z = zenith
zenith_rad = np.radians(z)
model = model.lower()
if 'kastenyoung1989' == model:
am = (1.0 / (np.cos(zenith_rad) +
0.50572*(((6.07995 + (90 - z)) ** - 1.6364))))
elif 'kasten1966' == model:
am = 1.0 / (np.cos(zenith_rad) + 0.15*((93.885 - z) ** - 1.253))
elif 'simple' == model:
am = 1.0 / np.cos(zenith_rad)
elif 'pickering2002' == model:
am = (1.0 / (np.sin(np.radians(90 - z +
244.0 / (165 + 47.0 * (90 - z) ** 1.1)))))
elif 'youngirvine1967' == model:
am = ((1.0 / np.cos(zenith_rad)) *
(1 - 0.0012*((1.0 / np.cos(zenith_rad)) ** 2) - 1))
elif 'young1994' == model:
am = ((1.002432*((np.cos(zenith_rad)) ** 2) +
0.148386*(np.cos(zenith_rad)) + 0.0096467) /
(np.cos(zenith_rad) ** 3 +
0.149864*(np.cos(zenith_rad) ** 2) +
0.0102963*(np.cos(zenith_rad)) + 0.000303978))
elif 'gueymard1993' == model:
am = (1.0 / (np.cos(zenith_rad) +
0.00176759*(z)*((94.37515 - z) ** - 1.21563)))
else:
raise ValueError('%s is not a valid model for relativeairmass', model)
try:
am[z > 90] = np.nan
except __HOLE__:
am = np.nan if z > 90 else am
return am
|
TypeError
|
dataset/ETHPy150Open pvlib/pvlib-python/pvlib/atmosphere.py/relativeairmass
|
9,924
|
@asyncio.coroutine
def run_as_coroutine(self, stdin, callbacks):
"""
The input 'event loop'.
"""
# Note: We cannot use "yield from", because this package also
# installs on Python 2.
assert isinstance(callbacks, EventLoopCallbacks)
if self.closed:
raise Exception('Event loop already closed.')
timeout = AsyncioTimeout(INPUT_TIMEOUT, callbacks.input_timeout, self.loop)
self.running = True
try:
while self.running:
timeout.reset()
# Get keys
try:
g = iter(self.loop.run_in_executor(None, self._console_input_reader.read))
while True:
yield next(g)
except __HOLE__ as e:
keys = e.args[0]
# Feed keys to input processor.
for k in keys:
callbacks.feed_key(k)
finally:
timeout.stop()
|
StopIteration
|
dataset/ETHPy150Open jonathanslenders/python-prompt-toolkit/prompt_toolkit/eventloop/asyncio_win32.py/Win32AsyncioEventLoop.run_as_coroutine
|
9,925
|
def authn_response(conf, return_addrs, outstanding_queries=None, timeslack=0,
asynchop=True, allow_unsolicited=False,
want_assertions_signed=False):
sec = security_context(conf)
if not timeslack:
try:
timeslack = int(conf.accepted_time_diff)
except __HOLE__:
timeslack = 0
return AuthnResponse(sec, conf.attribute_converters, conf.entityid,
return_addrs, outstanding_queries, timeslack,
asynchop=asynchop, allow_unsolicited=allow_unsolicited,
want_assertions_signed=want_assertions_signed)
# comes in over SOAP so synchronous
|
TypeError
|
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/authn_response
|
9,926
|
def attribute_response(conf, return_addrs, timeslack=0, asynchop=False,
test=False):
sec = security_context(conf)
if not timeslack:
try:
timeslack = int(conf.accepted_time_diff)
except __HOLE__:
timeslack = 0
return AttributeResponse(sec, conf.attribute_converters, conf.entityid,
return_addrs, timeslack, asynchop=asynchop,
test=test)
|
TypeError
|
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/attribute_response
|
9,927
|
def _loads(self, xmldata, decode=True, origxml=None):
# own copy
self.xmlstr = xmldata[:]
logger.debug("xmlstr: %s" % (self.xmlstr,))
if origxml:
self.origxml = origxml
else:
self.origxml = self.xmlstr
try:
self.response = self.signature_check(
xmldata, origdoc=origxml, must=self.require_signature,
require_response_signature=self.require_response_signature)
except __HOLE__:
raise
except SignatureError:
raise
except Exception as excp:
logger.exception("EXCEPTION: %s", excp)
raise
#print "<", self.response
return self._postamble()
|
TypeError
|
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/StatusResponse._loads
|
9,928
|
def _verify(self):
if self.request_id and self.in_response_to and \
self.in_response_to != self.request_id:
logger.error("Not the id I expected: %s != %s" % (
self.in_response_to, self.request_id))
return None
try:
assert self.response.version == "2.0"
except __HOLE__:
_ver = float(self.response.version)
if _ver < 2.0:
raise RequestVersionTooLow()
else:
raise RequestVersionTooHigh()
if self.asynchop:
if self.response.destination and \
self.response.destination not in self.return_addrs:
logger.error("%s not in %s" % (self.response.destination,
self.return_addrs))
return None
assert self.issue_instant_ok()
assert self.status_ok()
return self
|
AssertionError
|
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/StatusResponse._verify
|
9,929
|
def verify(self, key_file=""):
try:
return self._verify()
except __HOLE__:
logger.exception("verify")
return None
|
AssertionError
|
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/StatusResponse.verify
|
9,930
|
def __init__(self, sec_context, attribute_converters, entity_id,
return_addrs=None, outstanding_queries=None,
timeslack=0, asynchop=True, allow_unsolicited=False,
test=False, allow_unknown_attributes=False,
want_assertions_signed=False, want_response_signed=False,
**kwargs):
StatusResponse.__init__(self, sec_context, return_addrs, timeslack,
asynchop=asynchop)
self.entity_id = entity_id
self.attribute_converters = attribute_converters
if outstanding_queries:
self.outstanding_queries = outstanding_queries
else:
self.outstanding_queries = {}
self.context = "AuthnReq"
self.came_from = None
self.ava = None
self.assertion = None
self.assertions = []
self.session_not_on_or_after = 0
self.allow_unsolicited = allow_unsolicited
self.require_signature = want_assertions_signed
self.require_response_signature = want_response_signed
self.test = test
self.allow_unknown_attributes = allow_unknown_attributes
#
try:
self.extension_schema = kwargs["extension_schema"]
except __HOLE__:
self.extension_schema = {}
|
KeyError
|
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/AuthnResponse.__init__
|
9,931
|
def check_subject_confirmation_in_response_to(self, irp):
for assertion in self.response.assertion:
for _sc in assertion.subject.subject_confirmation:
try:
assert _sc.subject_confirmation_data.in_response_to == irp
except __HOLE__:
return False
return True
|
AssertionError
|
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/AuthnResponse.check_subject_confirmation_in_response_to
|
9,932
|
def loads(self, xmldata, decode=True, origxml=None):
self._loads(xmldata, decode, origxml)
if self.asynchop:
if self.in_response_to in self.outstanding_queries:
self.came_from = self.outstanding_queries[self.in_response_to]
#del self.outstanding_queries[self.in_response_to]
try:
if not self.check_subject_confirmation_in_response_to(
self.in_response_to):
logger.exception(
"Unsolicited response %s" % self.in_response_to)
raise UnsolicitedResponse(
"Unsolicited response: %s" % self.in_response_to)
except __HOLE__:
pass
elif self.allow_unsolicited:
pass
else:
logger.exception(
"Unsolicited response %s" % self.in_response_to)
raise UnsolicitedResponse(
"Unsolicited response: %s" % self.in_response_to)
return self
|
AttributeError
|
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/AuthnResponse.loads
|
9,933
|
def authn_statement_ok(self, optional=False):
try:
# the assertion MUST contain one AuthNStatement
assert len(self.assertion.authn_statement) == 1
except __HOLE__:
if optional:
return True
else:
logger.error("No AuthnStatement")
raise
authn_statement = self.assertion.authn_statement[0]
if authn_statement.session_not_on_or_after:
if validate_on_or_after(authn_statement.session_not_on_or_after,
self.timeslack):
self.session_not_on_or_after = calendar.timegm(
time_util.str_to_time(
authn_statement.session_not_on_or_after))
else:
return False
return True
# check authn_statement.session_index
|
AssertionError
|
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/AuthnResponse.authn_statement_ok
|
9,934
|
def condition_ok(self, lax=False):
if self.test:
lax = True
# The Identity Provider MUST include a <saml:Conditions> element
assert self.assertion.conditions
conditions = self.assertion.conditions
logger.debug("conditions: %s" % conditions)
# if no sub-elements or elements are supplied, then the
# assertion is considered to be valid.
if not conditions.keyswv():
return True
# if both are present NotBefore must be earlier than NotOnOrAfter
if conditions.not_before and conditions.not_on_or_after:
if not later_than(conditions.not_on_or_after,
conditions.not_before):
return False
try:
if conditions.not_on_or_after:
self.not_on_or_after = validate_on_or_after(
conditions.not_on_or_after, self.timeslack)
if conditions.not_before:
validate_before(conditions.not_before, self.timeslack)
except Exception as excp:
logger.error("Exception on conditions: %s" % (excp,))
if not lax:
raise
else:
self.not_on_or_after = 0
if not self.allow_unsolicited:
if not for_me(conditions, self.entity_id):
if not lax:
raise Exception("Not for me!!!")
if conditions.condition: # extra conditions
for cond in conditions.condition:
try:
if cond.extension_attributes[
XSI_TYPE] in self.extension_schema:
pass
else:
raise Exception("Unknown condition")
except __HOLE__:
raise Exception("Missing xsi:type specification")
return True
|
KeyError
|
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/AuthnResponse.condition_ok
|
9,935
|
def get_subject(self):
""" The assertion must contain a Subject
"""
assert self.assertion.subject
subject = self.assertion.subject
subjconf = []
for subject_confirmation in subject.subject_confirmation:
_data = subject_confirmation.subject_confirmation_data
if subject_confirmation.method == SCM_BEARER:
if not self._bearer_confirmed(_data):
continue
elif subject_confirmation.method == SCM_HOLDER_OF_KEY:
if not self._holder_of_key_confirmed(_data):
continue
elif subject_confirmation.method == SCM_SENDER_VOUCHES:
pass
else:
raise ValueError("Unknown subject confirmation method: %s" % (
subject_confirmation.method,))
subjconf.append(subject_confirmation)
if not subjconf:
raise VerificationError("No valid subject confirmation")
subject.subject_confirmation = subjconf
# The subject must contain a name_id
try:
assert subject.name_id
self.name_id = subject.name_id
except __HOLE__:
if subject.encrypted_id:
# decrypt encrypted ID
_name_id_str = self.sec.decrypt(
subject.encrypted_id.encrypted_data.to_string())
_name_id = saml.name_id_from_string(_name_id_str)
self.name_id = _name_id
else:
raise VerificationError("Missing NameID")
logger.info("Subject NameID: %s" % self.name_id)
return self.name_id
|
AssertionError
|
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/AuthnResponse.get_subject
|
9,936
|
def parse_assertion(self, key_file=""):
if self.context == "AuthnQuery":
# can contain one or more assertions
pass
else: # This is a saml2int limitation
try:
assert len(self.response.assertion) == 1 or \
len(self.response.encrypted_assertion) == 1
except __HOLE__:
raise Exception("No assertion part")
res = []
if self.response.encrypted_assertion:
logger.debug("***Encrypted assertion/-s***")
decr_text = self.sec.decrypt(self.xmlstr, key_file)
resp = samlp.response_from_string(decr_text)
res = self.decrypt_assertions(resp.encrypted_assertion, decr_text)
if self.response.assertion:
self.response.assertion.extend(res)
else:
self.response.assertion = res
self.response.encrypted_assertion = []
self.xmlstr = decr_text
if self.response.assertion:
logger.debug("***Unencrypted assertion***")
for assertion in self.response.assertion:
if not self._assertion(assertion, assertion in res):
return False
else:
self.assertions.append(assertion)
self.assertion = self.assertions[0]
return True
|
AssertionError
|
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/AuthnResponse.parse_assertion
|
9,937
|
def verify(self, key_file=""):
""" Verify that the assertion is syntactically correct and
the signature is correct if present.
:param key_file: If not the default key file should be used this is it.
"""
try:
res = self._verify()
except __HOLE__ as err:
logger.error("Verification error on the response: %s" % err)
raise
else:
if res is None:
return None
if not isinstance(self.response, samlp.Response):
return self
if self.parse_assertion(key_file):
return self
else:
logger.error("Could not parse the assertion")
return None
|
AssertionError
|
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/AuthnResponse.verify
|
9,938
|
def authn_info(self):
res = []
for astat in self.assertion.authn_statement:
context = astat.authn_context
if context:
try:
aclass = context.authn_context_class_ref.text
except __HOLE__:
aclass = ""
try:
authn_auth = [a.text for a in
context.authenticating_authority]
except AttributeError:
authn_auth = []
res.append((aclass, authn_auth))
return res
|
AttributeError
|
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/AuthnResponse.authn_info
|
9,939
|
def response_factory(xmlstr, conf, return_addrs=None, outstanding_queries=None,
timeslack=0, decode=True, request_id=0, origxml=None,
asynchop=True, allow_unsolicited=False,
want_assertions_signed=False):
sec_context = security_context(conf)
if not timeslack:
try:
timeslack = int(conf.accepted_time_diff)
except __HOLE__:
timeslack = 0
attribute_converters = conf.attribute_converters
entity_id = conf.entityid
extension_schema = conf.extension_schema
response = StatusResponse(sec_context, return_addrs, timeslack, request_id,
asynchop)
try:
response.loads(xmlstr, decode, origxml)
if response.response.assertion or response.response.encrypted_assertion:
authnresp = AuthnResponse(sec_context, attribute_converters,
entity_id, return_addrs,
outstanding_queries, timeslack, asynchop,
allow_unsolicited,
extension_schema=extension_schema,
want_assertions_signed=want_assertions_signed)
authnresp.update(response)
return authnresp
except TypeError:
response.signature_check = sec_context.correctly_signed_logout_response
response.loads(xmlstr, decode, origxml)
logoutresp = LogoutResponse(sec_context, return_addrs, timeslack,
asynchop=asynchop)
logoutresp.update(response)
return logoutresp
return response
# ===========================================================================
# A class of it's own
|
TypeError
|
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/response_factory
|
9,940
|
def loads(self, xmldata, decode=True, origxml=None):
# own copy
self.xmlstr = xmldata[:]
logger.debug("xmlstr: %s" % (self.xmlstr,))
self.origxml = origxml
try:
self.response = self.signature_check(xmldata, origdoc=origxml)
self.assertion = self.response
except __HOLE__:
raise
except SignatureError:
raise
except Exception as excp:
logger.exception("EXCEPTION: %s", excp)
raise
#print "<", self.response
return self._postamble()
|
TypeError
|
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/response.py/AssertionIDResponse.loads
|
9,941
|
def long_description():
"""Return long description from README.rst if it's present
because it doesn't get installed."""
try:
return open(os.path.join(
os.path.dirname(__file__), 'README.rst'
)).read()
except __HOLE__:
return LONG_DESCRIPTION
|
IOError
|
dataset/ETHPy150Open wq/wq/setup.py/long_description
|
9,942
|
def test_can_get_record_values_by_slice_using_getslice(self):
record = Record(["one", "two", "three"], ["eins", "zwei", "drei"])
try:
s = record.__getslice__(0, 2)
except __HOLE__:
assert True
else:
assert s == Record(["one", "two"], ["eins", "zwei"])
|
AttributeError
|
dataset/ETHPy150Open nigelsmall/py2neo/test/test_cursor.py/RecordTestCase.test_can_get_record_values_by_slice_using_getslice
|
9,943
|
def writeWordIDs(featurefile, sep=None):
"""
The wordids are counted directly from the unigrams file.
Filename: location of unigrams.txt
sep: Delimiter. Defaults to None (whitespace), use this for tab- or
comma-delimiting.
"""
output = open(".bookworm/texts/wordlist/wordlist.txt","w")
wordcounts = dict()
for line in featurefile:
(bookid,word,count) = line.split(sep)
count = int(count)
try:
wordcounts[word] += count
except __HOLE__:
wordcounts[word] = count
tuples = [(v,k) for k,v in wordcounts.iteritems()]
tuples.sort()
tuples.reverse()
wordid = 0
for (count,word) in tuples:
wordid += 1
output.write("\t".join([str(wordid),word.replace("\\","\\\\"),str(count)]) + "\n")
|
KeyError
|
dataset/ETHPy150Open Bookworm-project/BookwormDB/bookwormDB/ingestFeatureCounts.py/writeWordIDs
|
9,944
|
def _translate2v2(ip, community, pdu):
"""Translate an SNMPv1 trap to an SNMPv2 trap per RFC2576. This is
done so that the rest of the API only has to deal with V2 traps.
"""
varbinds = pdu.varbinds
# 3.1.(1)
varbinds.insert(0, sysUpTime(pdu.time_stamp).varbind)
# 3.1.(2)
if pdu.generic == 6: # enterpriseSpecific(6)
trapoid = ObjectIdentifier(pdu.enterprise+[0, pdu.specific])
else: # 3.1.(3)
trapoid = _TRAPMAP[pdu.generic]
varbinds.insert(1, snmpTrapOID(trapoid).varbind)
# 3.1.(4)
try:
varbinds.append(snmpTrapAddress(pdu.agent).varbind)
except __HOLE__:
varbinds.append(snmpTrapAddress(ip).varbind)
varbinds.append(snmpTrapCommunity(community).varbind)
varbinds.append(snmpTrapEnterprise(pdu.enterprise).varbind)
return SNMPv2TrapPDU(varbinds=varbinds)
# all trap callbacks should match this signature.
|
AttributeError
|
dataset/ETHPy150Open kdart/pycopia/SNMP/pycopia/SNMP/traps.py/_translate2v2
|
9,945
|
def assert_fp_equal(x, y, err_msg="", nulp=50):
"""Assert two arrays are equal, up to some floating-point rounding error"""
try:
assert_array_almost_equal_nulp(x, y, nulp)
except __HOLE__ as e:
raise AssertionError("%s\n%s" % (e, err_msg))
|
AssertionError
|
dataset/ETHPy150Open scipy/scipy/scipy/optimize/tests/test_linesearch.py/assert_fp_equal
|
9,946
|
def execute_command(self, command_name, **kwargs):
"""Execute an agent command."""
with self.command_lock:
LOG.debug('Executing command: %(name)s with args: %(args)s',
{'name': command_name, 'args': kwargs})
extension_part, command_part = self.split_command(command_name)
if len(self.command_results) > 0:
last_command = list(self.command_results.values())[-1]
if not last_command.is_done():
LOG.error('Tried to execute %(command)s, agent is still '
'executing %(last)s', {'command': command_name,
'last': last_command})
raise errors.CommandExecutionError('agent is busy')
try:
ext = self.get_extension(extension_part)
result = ext.execute(command_part, **kwargs)
except __HOLE__:
# Extension Not found
LOG.exception('Extension %s not found', extension_part)
raise errors.RequestedObjectNotFoundError('Extension',
extension_part)
except errors.InvalidContentError as e:
# Any command may raise a InvalidContentError which will be
# returned to the caller directly.
LOG.exception('Invalid content error: %s', e)
raise e
except Exception as e:
# Other errors are considered command execution errors, and are
# recorded as a failed SyncCommandResult with an error message
LOG.exception('Command execution error: %s', e)
result = SyncCommandResult(command_name, kwargs, False, e)
LOG.info('Command %(name)s completed: %(result)s',
{'name': command_name, 'result': result})
self.command_results[result.id] = result
return result
|
KeyError
|
dataset/ETHPy150Open openstack/ironic-python-agent/ironic_python_agent/extensions/base.py/ExecuteCommandMixin.execute_command
|
9,947
|
def get_user_profile(session_id):
if session_id is None:
return None
try:
djsession = djSession.objects.get(expire_date__gt=timezone.now(),
session_key=session_id)
except djSession.DoesNotExist:
return None
try:
return UserProfile.objects.get(pk=get_session_user(djsession))
except (UserProfile.DoesNotExist, __HOLE__):
return None
|
KeyError
|
dataset/ETHPy150Open zulip/zulip/zerver/lib/socket.py/get_user_profile
|
9,948
|
def on_open(self, info):
log_data = dict(extra='[transport=%s]' % (self.session.transport_name,))
record_request_start_data(log_data)
ioloop = tornado.ioloop.IOLoop.instance()
self.authenticated = False
self.session.user_profile = None
self.close_info = None # type: CloseErrorInfo
self.did_close = False
try:
self.browser_session_id = info.get_cookie(settings.SESSION_COOKIE_NAME).value
self.csrf_token = info.get_cookie(settings.CSRF_COOKIE_NAME).value
except __HOLE__:
# The request didn't contain the necessary cookie values. We can't
# close immediately because sockjs-tornado doesn't expect a close
# inside on_open(), so do it on the next tick.
self.close_info = CloseErrorInfo(403, "Initial cookie lacked required values")
ioloop.add_callback(self.close)
return
def auth_timeout():
self.close_info = CloseErrorInfo(408, "Timeout while waiting for authentication")
self.close()
self.timeout_handle = ioloop.add_timeout(time.time() + 10, auth_timeout)
write_log_line(log_data, path='/socket/open', method='SOCKET',
remote_ip=info.ip, email='unknown', client_name='?')
|
AttributeError
|
dataset/ETHPy150Open zulip/zulip/zerver/lib/socket.py/SocketConnection.on_open
|
9,949
|
def is_in_alphabet(self, uchr, alphabet):
if self.no_memory:
return alphabet in ud.name(uchr)
try:
return self.alphabet_letters[alphabet][uchr]
except __HOLE__:
return self.alphabet_letters[alphabet].setdefault(
uchr, alphabet in ud.name(uchr))
|
KeyError
|
dataset/ETHPy150Open EliFinkelshteyn/alphabet-detector/alphabet_detector/alphabet_detector.py/AlphabetDetector.is_in_alphabet
|
9,950
|
def first(self):
"""
Returns the first object of a query, returns None if no match is found.
"""
qs = self if self.ordered else self.order_by('pk')
try:
return qs[0]
except __HOLE__:
return None
|
IndexError
|
dataset/ETHPy150Open ulule/django-courriers/courriers/core.py/QuerySet.first
|
9,951
|
def last(self):
"""
Returns the last object of a query, returns None if no match is found.
"""
qs = self.reverse() if self.ordered else self.order_by('-pk')
try:
return qs[0]
except __HOLE__:
return None
|
IndexError
|
dataset/ETHPy150Open ulule/django-courriers/courriers/core.py/QuerySet.last
|
9,952
|
def str_to_datetime_processor_factory(regexp, type_):
rmatch = regexp.match
# Even on python2.6 datetime.strptime is both slower than this code
# and it does not support microseconds.
has_named_groups = bool(regexp.groupindex)
def process(value):
if value is None:
return None
else:
try:
m = rmatch(value)
except __HOLE__:
raise ValueError("Couldn't parse %s string '%r' "
"- value is not a string." %
(type_.__name__, value))
if m is None:
raise ValueError("Couldn't parse %s string: "
"'%s'" % (type_.__name__, value))
if has_named_groups:
groups = m.groupdict(0)
return type_(**dict(list(zip(
iter(groups.keys()),
list(map(int, iter(groups.values())))
))))
else:
return type_(*list(map(int, m.groups(0))))
return process
|
TypeError
|
dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/processors.py/str_to_datetime_processor_factory
|
9,953
|
def build_manpages():
# Go into the docs directory and build the manpage.
docdir = os.path.join(os.path.dirname(__file__), 'docs')
curdir = os.getcwd()
os.chdir(docdir)
try:
subprocess.check_call(['make', 'man'])
except __HOLE__:
print("Could not build manpages (make man failed)!", file=sys.stderr)
return
finally:
os.chdir(curdir)
# Copy resulting manpages.
mandir = os.path.join(os.path.dirname(__file__), 'man')
if os.path.exists(mandir):
shutil.rmtree(mandir)
shutil.copytree(os.path.join(docdir, '_build', 'man'), mandir)
# Build manpages if we're making a source distribution tarball.
|
OSError
|
dataset/ETHPy150Open beetbox/beets/setup.py/build_manpages
|
9,954
|
@jsexpose(body_cls=ActionAliasAPI, status_code=http_client.CREATED)
@request_user_has_resource_api_permission(permission_type=PermissionType.ACTION_ALIAS_CREATE)
def post(self, action_alias):
"""
Create a new ActionAlias.
Handles requests:
POST /actionalias/
"""
try:
action_alias_db = ActionAliasAPI.to_model(action_alias)
LOG.debug('/actionalias/ POST verified ActionAliasAPI and formulated ActionAliasDB=%s',
action_alias_db)
action_alias_db = ActionAlias.add_or_update(action_alias_db)
except (ValidationError, __HOLE__, ValueValidationException) as e:
LOG.exception('Validation failed for action alias data=%s.', action_alias)
pecan.abort(http_client.BAD_REQUEST, str(e))
return
extra = {'action_alias_db': action_alias_db}
LOG.audit('Action alias created. ActionAlias.id=%s' % (action_alias_db.id), extra=extra)
action_alias_api = ActionAliasAPI.from_model(action_alias_db)
return action_alias_api
|
ValueError
|
dataset/ETHPy150Open StackStorm/st2/st2api/st2api/controllers/v1/actionalias.py/ActionAliasController.post
|
9,955
|
@request_user_has_resource_db_permission(permission_type=PermissionType.ACTION_MODIFY)
@jsexpose(arg_types=[str], body_cls=ActionAliasAPI)
def put(self, action_alias_ref_or_id, action_alias):
action_alias_db = self._get_by_ref_or_id(ref_or_id=action_alias_ref_or_id)
LOG.debug('PUT /actionalias/ lookup with id=%s found object: %s', action_alias_ref_or_id,
action_alias_db)
try:
if action_alias.id is not None and action_alias.id is not '' and \
action_alias.id != action_alias_ref_or_id:
LOG.warning('Discarding mismatched id=%s found in payload and using uri_id=%s.',
action_alias.id, action_alias_ref_or_id)
old_action_alias_db = action_alias_db
action_alias_db = ActionAliasAPI.to_model(action_alias)
action_alias_db.id = action_alias_ref_or_id
action_alias_db = ActionAlias.add_or_update(action_alias_db)
except (__HOLE__, ValueError) as e:
LOG.exception('Validation failed for action alias data=%s', action_alias)
pecan.abort(http_client.BAD_REQUEST, str(e))
return
extra = {'old_action_alias_db': old_action_alias_db, 'new_action_alias_db': action_alias_db}
LOG.audit('Action alias updated. ActionAlias.id=%s.' % (action_alias_db.id), extra=extra)
action_alias_api = ActionAliasAPI.from_model(action_alias_db)
return action_alias_api
|
ValidationError
|
dataset/ETHPy150Open StackStorm/st2/st2api/st2api/controllers/v1/actionalias.py/ActionAliasController.put
|
9,956
|
def _stop(self, exit_exc=None, caller=None):
if self._stopped:
return
self._stopped = True
self._rloop.kill(block=True)
self._wloop.kill(block=True)
# handle clean disconnection from client
try:
self.sock.shutdown(socket.SHUT_RDWR)
except socket.error:
pass
try:
self.fp.close()
except (socket.error, __HOLE__):
pass
try:
self.sock.close()
except (socket.error, AttributeError):
pass
self.server.remove_client(self)
self.logger.info("Closing connection for client {}".format(self._id))
|
AttributeError
|
dataset/ETHPy150Open simplecrypto/powerpool/powerpool/server.py/GenericClient._stop
|
9,957
|
def visit_Name(self, node):
name = node.id
if name.startswith('__'):
raise ValueError("invalid name %r" % name)
try:
return self.scope[name]
except __HOLE__:
return symbol(name, self.dtypes[name])
|
KeyError
|
dataset/ETHPy150Open blaze/blaze/blaze/expr/parser.py/BlazeParser.visit_Name
|
9,958
|
def run(self, lines):
""" Parse Meta-Data and store in Markdown.Meta. """
meta = {}
key = None
while lines:
line = lines.pop(0)
if line.strip() == '':
break # blank line - done
m1 = META_RE.match(line)
if m1:
key = m1.group('key').lower().strip()
value = m1.group('value').strip()
try:
meta[key].append(value)
except __HOLE__:
meta[key] = [value]
else:
m2 = META_MORE_RE.match(line)
if m2 and key:
# Add another line to existing key
meta[key].append(m2.group('value').strip())
else:
lines.insert(0, line)
break # no meta data - done
self.markdown.Meta = meta
return lines
|
KeyError
|
dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/markdown/extensions/meta.py/MetaPreprocessor.run
|
9,959
|
def __getattr__(self, attr):
if attr.startswith('_'):
raise AttributeError("No such setting: {0}".format(attr))
else:
try:
return self._members[attr]
except __HOLE__:
raise AttributeError("No such setting: {0}".format(attr))
|
KeyError
|
dataset/ETHPy150Open glue-viz/glue/glue/config.py/SettingRegistry.__getattr__
|
9,960
|
def default_members(self):
defaults = {}
for viewer in qt_client.members:
try:
defaults[viewer] = viewer._get_default_tools()
except __HOLE__:
logger.info("could not get default tools for {0}".format(viewer.__name__))
defaults[viewer] = []
return defaults
|
AttributeError
|
dataset/ETHPy150Open glue-viz/glue/glue/config.py/QtToolRegistry.default_members
|
9,961
|
def load_configuration(search_path=None):
''' Find and import a config.py file
Returns:
The module object
Raises:
Exception, if no module was found
'''
search_order = search_path or _default_search_order()
result = imp.new_module('config')
for config_file in search_order:
dir = os.path.dirname(config_file)
try:
sys.path.append(dir)
config = imp.load_source('config', config_file)
result = config
except __HOLE__:
pass
except Exception as e:
raise type(e)("Error loading config file %s:\n%s" % (config_file, e), sys.exc_info()[2])
finally:
sys.path.remove(dir)
return result
|
IOError
|
dataset/ETHPy150Open glue-viz/glue/glue/config.py/load_configuration
|
9,962
|
def get_completions(self, document, complete_event):
"""
Get Python completions.
"""
# Do Path completions
if complete_event.completion_requested or self._complete_path_while_typing(document):
for c in self._path_completer.get_completions(document, complete_event):
yield c
# If we are inside a string, Don't do Jedi completion.
if self._path_completer_grammar.match(document.text_before_cursor):
return
# Do Jedi Python completions.
if complete_event.completion_requested or self._complete_python_while_typing(document):
script = get_jedi_script_from_document(document, self.get_locals(), self.get_globals())
if script:
try:
completions = script.completions()
except TypeError:
# Issue #9: bad syntax causes completions() to fail in jedi.
# https://github.com/jonathanslenders/python-prompt-toolkit/issues/9
pass
except __HOLE__:
# Issue #43: UnicodeDecodeError on OpenBSD
# https://github.com/jonathanslenders/python-prompt-toolkit/issues/43
pass
except AttributeError:
# Jedi issue #513: https://github.com/davidhalter/jedi/issues/513
pass
except ValueError:
# Jedi issue: "ValueError: invalid \x escape"
pass
except KeyError:
# Jedi issue: "KeyError: u'a_lambda'."
# https://github.com/jonathanslenders/ptpython/issues/89
pass
except IOError:
# Jedi issue: "IOError: No such file or directory."
# https://github.com/jonathanslenders/ptpython/issues/71
pass
else:
for c in completions:
yield Completion(c.name_with_symbols, len(c.complete) - len(c.name_with_symbols),
display=c.name_with_symbols)
|
UnicodeDecodeError
|
dataset/ETHPy150Open jonathanslenders/ptpython/ptpython/completer.py/PythonCompleter.get_completions
|
9,963
|
def pid_exists(pid):
"""Check whether pid exists in the current process table."""
if pid == 0:
# According to "man 2 kill" PID 0 has a special meaning:
# it refers to <<every process in the process group of the
# calling process>> so we don't want to go any further.
# If we get here it means this UNIX platform *does* have
# a process with id 0.
return True
try:
os.kill(pid, 0)
except __HOLE__ as err:
if err.errno == errno.ESRCH:
# ESRCH == No such process
return False
elif err.errno == errno.EPERM:
# EPERM clearly means there's a process to deny access to
return True
else:
# According to "man 2 kill" possible error values are
# (EINVAL, EPERM, ESRCH) therefore we should never get
# here. If we do let's be explicit in considering this
# an error.
raise err
else:
return True
|
OSError
|
dataset/ETHPy150Open giampaolo/psutil/psutil/_psposix.py/pid_exists
|
9,964
|
def wait_pid(pid, timeout=None):
"""Wait for process with pid 'pid' to terminate and return its
exit status code as an integer.
If pid is not a children of os.getpid() (current process) just
waits until the process disappears and return None.
If pid does not exist at all return None immediately.
Raise TimeoutExpired on timeout expired.
"""
def check_timeout(delay):
if timeout is not None:
if timer() >= stop_at:
raise TimeoutExpired()
time.sleep(delay)
return min(delay * 2, 0.04)
timer = getattr(time, 'monotonic', time.time)
if timeout is not None:
def waitcall():
return os.waitpid(pid, os.WNOHANG)
stop_at = timer() + timeout
else:
def waitcall():
return os.waitpid(pid, 0)
delay = 0.0001
while True:
try:
retpid, status = waitcall()
except __HOLE__ as err:
if err.errno == errno.EINTR:
delay = check_timeout(delay)
continue
elif err.errno == errno.ECHILD:
# This has two meanings:
# - pid is not a child of os.getpid() in which case
# we keep polling until it's gone
# - pid never existed in the first place
# In both cases we'll eventually return None as we
# can't determine its exit status code.
while True:
if pid_exists(pid):
delay = check_timeout(delay)
else:
return
else:
raise
else:
if retpid == 0:
# WNOHANG was used, pid is still running
delay = check_timeout(delay)
continue
# process exited due to a signal; return the integer of
# that signal
if os.WIFSIGNALED(status):
return os.WTERMSIG(status)
# process exited using exit(2) system call; return the
# integer exit(2) system call has been called with
elif os.WIFEXITED(status):
return os.WEXITSTATUS(status)
else:
# should never happen
raise ValueError("unknown process exit status %r" % status)
|
OSError
|
dataset/ETHPy150Open giampaolo/psutil/psutil/_psposix.py/wait_pid
|
9,965
|
@memoize
def _get_terminal_map():
ret = {}
ls = glob.glob('/dev/tty*') + glob.glob('/dev/pts/*')
for name in ls:
assert name not in ret
try:
ret[os.stat(name).st_rdev] = name
except __HOLE__ as err:
if err.errno != errno.ENOENT:
raise
return ret
|
OSError
|
dataset/ETHPy150Open giampaolo/psutil/psutil/_psposix.py/_get_terminal_map
|
9,966
|
@classmethod
def must_send_stats(cls, master_node_settings_data=None):
"""Checks if stats must be sent
Stats must be sent if user saved the choice and
sending anonymous statistics was selected.
:param master_node_settings_data: dict with master node settings.
If master_node_settings_data is None data from DB will be fetched
:return: bool
"""
try:
if master_node_settings_data is None:
settings = getattr(cls.get_one(), "settings", {})
else:
settings = master_node_settings_data.get("settings")
stat_settings = settings.get("statistics", {})
return stat_settings.get("user_choice_saved", {}).\
get("value", False) and \
stat_settings.get("send_anonymous_statistic", {}). \
get("value", False)
except (__HOLE__, TypeError) as e:
logger.exception(
"Get statistics settings failed: %s", six.text_type(e))
return False
|
AttributeError
|
dataset/ETHPy150Open openstack/fuel-web/nailgun/nailgun/objects/master_node_settings.py/MasterNodeSettings.must_send_stats
|
9,967
|
@classmethod
def run_2to3(cls, path):
from lib2to3.refactor import get_fixers_from_package, RefactoringTool
rt = RefactoringTool(get_fixers_from_package('lib2to3.fixes'))
with TRACER.timed('Translating %s' % path):
for root, dirs, files in os.walk(path):
for fn in files:
full_fn = os.path.join(root, fn)
if full_fn.endswith('.py'):
with TRACER.timed('%s' % fn, V=3):
try:
chmod_plus_w(full_fn)
rt.refactor_file(full_fn, write=True)
except __HOLE__:
TRACER.log('Failed to translate %s' % fn)
TRACER.log(traceback.format_exc())
|
IOError
|
dataset/ETHPy150Open pantsbuild/pex/pex/translator.py/SourceTranslator.run_2to3
|
9,968
|
def paasta_cook_image(args, service=None, soa_dir=None):
"""Build a docker image"""
if service:
service = service
else:
service = args.service
if service and service.startswith('services-'):
service = service.split('services-', 1)[1]
validate_service_name(service, soa_dir)
run_env = os.environ.copy()
default_tag = 'paasta-cook-image-%s-%s' % (service, get_username())
tag = run_env.get('DOCKER_TAG', default_tag)
run_env['DOCKER_TAG'] = tag
if not makefile_responds_to('cook-image'):
sys.stderr.write('ERROR: local-run now requires a cook-image target to be present in the Makefile. See '
'http://paasta.readthedocs.io/en/latest/about/contract.html\n')
return 1
try:
cmd = 'make cook-image'
returncode, output = _run(
cmd,
env=run_env,
log=True,
component='build',
service=service,
loglevel='debug'
)
if returncode != 0:
_log(
service=service,
line='ERROR: make cook-image failed for %s.' % service,
component='build',
level='event',
)
return returncode
except __HOLE__:
sys.stderr.write('\nProcess interrupted by the user. Cancelling.\n')
return 2
|
KeyboardInterrupt
|
dataset/ETHPy150Open Yelp/paasta/paasta_tools/cli/cmds/cook_image.py/paasta_cook_image
|
9,969
|
def addComponent(self, c, index=None):
"""Add a component into this container. The component is added
to the right or under the previous component or into the indexed
position in this container.
@param c:
the component to be added.
@param index:
the Index of the component position. The components
currently in and after the position are shifted
forwards.
"""
if index is None:
self.components.append(c)
else:
self.components.insert(index, c)
try:
super(AbstractOrderedLayout, self).addComponent(c)
self.requestRepaint()
except __HOLE__, e:
if c in self.components:
self.components.remove(c)
raise e
|
ValueError
|
dataset/ETHPy150Open rwl/muntjac/muntjac/ui/abstract_ordered_layout.py/AbstractOrderedLayout.addComponent
|
9,970
|
def addComponentAsFirst(self, c):
"""Adds a component into this container. The component is
added to the left or on top of the other components.
@param c: the component to be added.
"""
self.components.insert(0, c)
try:
super(AbstractOrderedLayout, self).addComponent(c)
self.requestRepaint()
except __HOLE__, e:
self.components.remove(c)
raise e
|
ValueError
|
dataset/ETHPy150Open rwl/muntjac/muntjac/ui/abstract_ordered_layout.py/AbstractOrderedLayout.addComponentAsFirst
|
9,971
|
def getComponentIndex(self, component):
"""Returns the index of the given component.
@param component:
The component to look up.
@return: The index of the component or -1 if the component
is not a child.
"""
try:
return self.components.index(component)
except __HOLE__:
return -1
|
ValueError
|
dataset/ETHPy150Open rwl/muntjac/muntjac/ui/abstract_ordered_layout.py/AbstractOrderedLayout.getComponentIndex
|
9,972
|
def password_reset_confirm(request, uidb36=None, token=None, template_name='registration/password_reset_confirm.html',
token_generator=default_token_generator, set_password_form=SetPasswordForm,
post_reset_redirect=None):
"""
View that checks the hash in a password reset link and presents a
form for entering a new password.
"""
assert uidb36 is not None and token is not None # checked by URLconf
if post_reset_redirect is None:
post_reset_redirect = reverse('django.contrib.auth.views.password_reset_complete')
try:
uid_int = base36_to_int(uidb36)
except __HOLE__:
raise Http404
user = get_object_or_404(User, id=uid_int)
context_instance = RequestContext(request)
if token_generator.check_token(user, token):
context_instance['validlink'] = True
if request.method == 'POST':
form = set_password_form(user, request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(post_reset_redirect)
else:
form = set_password_form(None)
else:
context_instance['validlink'] = False
form = None
context_instance['form'] = form
return render_to_response(template_name, context_instance=context_instance)
|
ValueError
|
dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/contrib/auth/views.py/password_reset_confirm
|
9,973
|
def _community(G, u, community):
"""Get the community of the given node."""
node_u = G.node[u]
try:
return node_u[community]
except __HOLE__:
raise nx.NetworkXAlgorithmError('No community information')
|
KeyError
|
dataset/ETHPy150Open networkx/networkx/networkx/algorithms/link_prediction.py/_community
|
9,974
|
@property
def date(self):
try:
return datetime.date(self.created.year,
self.created.month, self.created.day)
except __HOLE__:
# created may be None
return None
|
AttributeError
|
dataset/ETHPy150Open mozilla/addons-server/src/olympia/stats/models.py/Contribution.date
|
9,975
|
@property
def contributor(self):
try:
return u'%s %s' % (self.post_data['first_name'],
self.post_data['last_name'])
except (TypeError, __HOLE__):
# post_data may be None or missing a key
return None
|
KeyError
|
dataset/ETHPy150Open mozilla/addons-server/src/olympia/stats/models.py/Contribution.contributor
|
9,976
|
@property
def email(self):
try:
return self.post_data['payer_email']
except (__HOLE__, KeyError):
# post_data may be None or missing a key
return None
|
TypeError
|
dataset/ETHPy150Open mozilla/addons-server/src/olympia/stats/models.py/Contribution.email
|
9,977
|
def __init__(self, *args, **kwds):
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
try:
self.__end
except __HOLE__:
self.clear()
self.update(*args, **kwds)
|
AttributeError
|
dataset/ETHPy150Open tanghaibao/jcvi/utils/orderedcollections.py/OrderedDict.__init__
|
9,978
|
def __getitem__(self, key):
try:
return OrderedDict.__getitem__(self, key)
except __HOLE__:
return self.__missing__(key)
|
KeyError
|
dataset/ETHPy150Open tanghaibao/jcvi/utils/orderedcollections.py/DefaultOrderedDict.__getitem__
|
9,979
|
def delete_hosts(hosts):
while True:
list_hosts(hosts)
del_idx = click.prompt('Select host to delete, y/Y to confirm, ' \
'or n/N to add more hosts', default='n')
try:
del_idx = int(del_idx)
hosts.remove(hosts[del_idx])
except IndexError:
click.echo("\"{}\" doesn't match any hosts listed.".format(del_idx))
except __HOLE__:
try:
response = del_idx.lower()
if response in ['y', 'n']:
return hosts, response
click.echo("\"{}\" doesn't coorespond to any valid input.".format(del_idx))
except AttributeError:
click.echo("\"{}\" doesn't coorespond to any valid input.".format(del_idx))
return hosts, None
|
ValueError
|
dataset/ETHPy150Open openshift/openshift-ansible/utils/src/ooinstall/cli_installer.py/delete_hosts
|
9,980
|
def confirm_hosts_facts(oo_cfg, callback_facts):
hosts = oo_cfg.hosts
click.clear()
message = """
A list of the facts gathered from the provided hosts follows. Because it is
often the case that the hostname for a system inside the cluster is different
from the hostname that is resolveable from command line or web clients
these settings cannot be validated automatically.
For some cloud providers the installer is able to gather metadata exposed in
the instance so reasonable defaults will be provided.
Plese confirm that they are correct before moving forward.
"""
notes = """
Format:
connect_to,IP,public IP,hostname,public hostname
Notes:
* The installation host is the hostname from the installer's perspective.
* The IP of the host should be the internal IP of the instance.
* The public IP should be the externally accessible IP associated with the instance
* The hostname should resolve to the internal IP from the instances
themselves.
* The public hostname should resolve to the external ip from hosts outside of
the cloud.
"""
# For testing purposes we need to click.echo only once, so build up
# the message:
output = message
default_facts_lines = []
default_facts = {}
for h in hosts:
if h.preconfigured == True:
continue
try:
default_facts[h.connect_to] = {}
h.ip = callback_facts[h.connect_to]["common"]["ip"]
h.public_ip = callback_facts[h.connect_to]["common"]["public_ip"]
h.hostname = callback_facts[h.connect_to]["common"]["hostname"]
h.public_hostname = callback_facts[h.connect_to]["common"]["public_hostname"]
except __HOLE__:
click.echo("Problem fetching facts from {}".format(h.connect_to))
continue
default_facts_lines.append(",".join([h.connect_to,
h.ip,
h.public_ip,
h.hostname,
h.public_hostname]))
output = "%s\n%s" % (output, ",".join([h.connect_to,
h.ip,
h.public_ip,
h.hostname,
h.public_hostname]))
output = "%s\n%s" % (output, notes)
click.echo(output)
facts_confirmed = click.confirm("Do the above facts look correct?")
if not facts_confirmed:
message = """
Edit %s with the desired values and run `atomic-openshift-installer --unattended install` to restart the install.
""" % oo_cfg.config_path
click.echo(message)
# Make sure we actually write out the config file.
oo_cfg.save_to_disk()
sys.exit(0)
return default_facts
|
KeyError
|
dataset/ETHPy150Open openshift/openshift-ansible/utils/src/ooinstall/cli_installer.py/confirm_hosts_facts
|
9,981
|
def get_installed_hosts(hosts, callback_facts):
installed_hosts = []
# count nativeha lb as an installed host
try:
first_master = next(host for host in hosts if host.master)
lb_hostname = callback_facts[first_master.connect_to]['master'].get('cluster_hostname', '')
lb_host = \
next(host for host in hosts if host.ip == callback_facts[lb_hostname]['common']['ip'])
installed_hosts.append(lb_host)
except (__HOLE__, StopIteration):
pass
for host in hosts:
if host.connect_to in callback_facts.keys() and is_installed_host(host, callback_facts):
installed_hosts.append(host)
return installed_hosts
|
KeyError
|
dataset/ETHPy150Open openshift/openshift-ansible/utils/src/ooinstall/cli_installer.py/get_installed_hosts
|
9,982
|
def get_wallpapers(self):
try:
# get path of all files in the directory
self.images = list(
filter(os.path.isfile,
map(self.get_path,
os.listdir(self.directory))))
except __HOLE__ as e:
logger.exception("I/O error(%s): %s", e.errno, e.strerror)
|
IOError
|
dataset/ETHPy150Open qtile/qtile/libqtile/widget/wallpaper.py/Wallpaper.get_wallpapers
|
9,983
|
def load_vars(path, vars):
"""Load variables from a pickle file.
Arguments:
* path: the path to the pickle file.
* vars: a list of variable names.
Returns:
* cache: a dictionary {var_name: var_value}.
"""
with open(path, 'rb') as f:
# Load the variables from the cache.
try:
cache = pickle.load(f)
except EOFError as e:
cache={}
#raise IOError(str(e))
# Check that all requested variables could be loaded successfully
# from the cache.
missing_vars = sorted(set(vars) - set(cache.keys()))
if missing_vars:
raise ValueError(("The following variables could not be loaded "
"from the cache: {0:s}").format(
', '.join(["'{0:s}'".format(var) for var in missing_vars])))
additional_vars = sorted(set(cache.keys()) - set(vars))
for hidden_variable in '_captured_io', '_cell_md5':
try:
additional_vars.remove(hidden_variable)
except __HOLE__:
pass
if additional_vars:
raise ValueError("The following variables were present in the cache, "
"but removed from the storage request: {0:s}".format(
', '.join(["'{0:s}'".format(var) for var in additional_vars])))
return cache
|
ValueError
|
dataset/ETHPy150Open rossant/ipycache/ipycache.py/load_vars
|
9,984
|
def load_captured_io(captured_io):
try:
return CapturedIO(captured_io.get('stdout', None),
captured_io.get('stderr', None),
outputs=captured_io.get('outputs', []),
)
except __HOLE__:
return CapturedIO(captured_io.get('stdout', None),
captured_io.get('stderr', None),
)
|
TypeError
|
dataset/ETHPy150Open rossant/ipycache/ipycache.py/load_captured_io
|
9,985
|
def cache(cell, path, vars=[],
# HACK: this function implementing the magic's logic is testable
# without IPython, by giving mock functions here instead of IPython
# methods.
ip_user_ns={}, ip_run_cell=None, ip_push=None, ip_clear_output=lambda : None,
force=False, read=False, verbose=True):
if not path:
raise ValueError("The path needs to be specified as a first argument.")
path = os.path.abspath(path)
cell_md5 = hashlib.md5(cell.encode()).hexdigest()
if do_save(path, force=force, read=read):
# Capture the outputs of the cell.
with capture_output_and_print() as io:
try:
ip_run_cell(cell)
except:
# Display input/output.
io()
return
# Create the cache from the namespace.
try:
cached = {var: ip_user_ns[var] for var in vars}
except KeyError:
vars_missing = set(vars) - set(ip_user_ns.keys())
vars_missing_str = ', '.join(["'{0:s}'".format(_)
for _ in vars_missing])
raise ValueError(("Variable(s) {0:s} could not be found in the "
"interactive namespace").format(vars_missing_str))
# Save the outputs in the cache.
cached['_captured_io'] = save_captured_io(io)
cached['_cell_md5'] = cell_md5
# Save the cache in the pickle file.
save_vars(path, cached)
ip_clear_output() # clear away the temporary output and replace with the saved output (ideal?)
if verbose:
print("[Saved variables '{0:s}' to file '{1:s}'.]".format(
', '.join(vars), path))
# If the cache file exists, and no --force mode, load the requested
# variables from the specified file into the interactive namespace.
else:
# Load the variables from cache in inject them in the namespace.
force_recalc = False
try:
cached = load_vars(path, vars)
except __HOLE__ as e:
if 'The following variables' in str(e):
if read:
raise
force_recalc = True
else:
raise
cached = {}
if not '_cell_md5' in cached or cell_md5 != cached['_cell_md5']:
force_recalc = True
if force_recalc and not read:
return cache(cell, path, vars, ip_user_ns, ip_run_cell, ip_push, ip_clear_output, True, read, verbose)
# Handle the outputs separately.
io = load_captured_io(cached.get('_captured_io', {}))
# Push the remaining variables in the namespace.
ip_push(cached)
if verbose:
print(("[Skipped the cell's code and loaded variables {0:s} "
"from file '{1:s}'.]").format(', '.join(vars), path))
# Display the outputs, whether they come from the cell's execution
# or the pickle file.
io() # output is only printed when loading file
|
ValueError
|
dataset/ETHPy150Open rossant/ipycache/ipycache.py/cache
|
9,986
|
def view_detail(request, view):
if not utils.docutils_is_available:
return missing_docutils_page(request)
mod, func = urlresolvers.get_mod_func(view)
try:
view_func = getattr(__import__(mod, {}, {}, ['']), func)
except (ImportError, __HOLE__):
raise Http404
title, body, metadata = utils.parse_docstring(view_func.__doc__)
if title:
title = utils.parse_rst(title, 'view', _('view:') + view)
if body:
body = utils.parse_rst(body, 'view', _('view:') + view)
for key in metadata:
metadata[key] = utils.parse_rst(metadata[key], 'model', _('view:') + view)
return render_to_response('admin_doc/view_detail.html', {
'name': view,
'summary': title,
'body': body,
'meta': metadata,
}, context_instance=RequestContext(request))
|
AttributeError
|
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/contrib/admin/views/doc.py/view_detail
|
9,987
|
def model_detail(request, app_label, model_name):
if not utils.docutils_is_available:
return missing_docutils_page(request)
# Get the model class.
try:
app_mod = models.get_app(app_label)
except ImproperlyConfigured:
raise Http404, _("App %r not found") % app_label
model = None
for m in models.get_models(app_mod):
if m._meta.object_name.lower() == model_name:
model = m
break
if model is None:
raise Http404, _("Model %(name)r not found in app %(label)r") % {'name': model_name, 'label': app_label}
opts = model._meta
# Gather fields/field descriptions.
fields = []
for field in opts.fields:
# ForeignKey is a special case since the field will actually be a
# descriptor that returns the other object
if isinstance(field, models.ForeignKey):
data_type = related_object_name = field.rel.to.__name__
app_label = field.rel.to._meta.app_label
verbose = utils.parse_rst((_("the related `%(label)s.%(type)s` object") % {'label': app_label, 'type': data_type}), 'model', _('model:') + data_type)
else:
data_type = get_readable_field_data_type(field)
verbose = field.verbose_name
fields.append({
'name': field.name,
'data_type': data_type,
'verbose': verbose,
'help_text': field.help_text,
})
# Gather model methods.
for func_name, func in model.__dict__.items():
if (inspect.isfunction(func) and len(inspect.getargspec(func)[0]) == 1):
try:
for exclude in MODEL_METHODS_EXCLUDE:
if func_name.startswith(exclude):
raise StopIteration
except __HOLE__:
continue
verbose = func.__doc__
if verbose:
verbose = utils.parse_rst(utils.trim_docstring(verbose), 'model', _('model:') + opts.module_name)
fields.append({
'name': func_name,
'data_type': get_return_data_type(func_name),
'verbose': verbose,
})
# Gather related objects
for rel in opts.get_all_related_objects():
verbose = _("related `%(label)s.%(name)s` objects") % {'label': rel.opts.app_label, 'name': rel.opts.object_name}
accessor = rel.get_accessor_name()
fields.append({
'name' : "%s.all" % accessor,
'data_type' : 'List',
'verbose' : utils.parse_rst(_("all %s") % verbose , 'model', _('model:') + opts.module_name),
})
fields.append({
'name' : "%s.count" % accessor,
'data_type' : 'Integer',
'verbose' : utils.parse_rst(_("number of %s") % verbose , 'model', _('model:') + opts.module_name),
})
return render_to_response('admin_doc/model_detail.html', {
'name': '%s.%s' % (opts.app_label, opts.object_name),
'summary': _("Fields on %s objects") % opts.object_name,
'description': model.__doc__,
'fields': fields,
}, context_instance=RequestContext(request))
|
StopIteration
|
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/contrib/admin/views/doc.py/model_detail
|
9,988
|
def extract_views_from_urlpatterns(urlpatterns, base=''):
"""
Return a list of views from a list of urlpatterns.
Each object in the returned list is a two-tuple: (view_func, regex)
"""
views = []
for p in urlpatterns:
if hasattr(p, '_get_callback'):
try:
views.append((p._get_callback(), base + p.regex.pattern))
except ViewDoesNotExist:
continue
elif hasattr(p, '_get_url_patterns'):
try:
patterns = p.url_patterns
except __HOLE__:
continue
views.extend(extract_views_from_urlpatterns(patterns, base + p.regex.pattern))
else:
raise TypeError, _("%s does not appear to be a urlpattern object") % p
return views
|
ImportError
|
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/contrib/admin/views/doc.py/extract_views_from_urlpatterns
|
9,989
|
def flush_django_cache(cache_instance=None):
cache_instance = cache_instance
if not cache_instance:
from django.core.cache import cache
cache_instance = cache
try:
cache_instance.clear()
except __HOLE__:
# Django < 1.2, backport
backend_name = cache_instance.__module__.split(".")[-1:][0]
if backend_name not in BACKEND_CLEAR_MAP:
raise ValueError("Don't know how to clear cache for %s backend" % backend_name)
BACKEND_CLEAR_MAP[backend_name](cache_instance)
|
AttributeError
|
dataset/ETHPy150Open Almad/django-sane-testing/djangosanetesting/cache.py/flush_django_cache
|
9,990
|
def get_model(self, name):
try:
return self.models[name]
except __HOLE__:
return None
|
KeyError
|
dataset/ETHPy150Open willhardy/django-seo/rollyourown/seo/options.py/Options.get_model
|
9,991
|
def handle(self, *args, **options):
try:
app, model = args[0].split('.')
except __HOLE__:
raise CommandError('Expected argument <app>.<model>')
self.connection = connections['default']
# XXX: We cant use get_model because its now an abstract model
# model = get_model(app, model)
app = get_app(app)
model = self.get_partitioned_model(app, model)
num_children = options['num_children']
shard_range = range(options['shard'], num_children, options['shards'])
output = self.get_sequences(model, num_children, shard_range)
output.extend(self.get_children_table_sql(model, [model], num_children, shard_range))
return u'\n\n'.join(output) + '\n'
|
ValueError
|
dataset/ETHPy150Open disqus/sharding-example/sqlshards/management/commands/sqlpartition.py/Command.handle
|
9,992
|
def next(self):
if self.tried is not None:
raise Exception("no feedback received on last value generated")
while True:
self.tried = self.data[:] # make a copy
try:
rmd = self.tried.pop(self.i)
if len(rmd) == 1 and rmd[0] == "\n":
self.keep(True)
continue # skip newlines
return self.formatter(sum(self.tried, []))
except __HOLE__:
self.tried = None
if not self.data or (len(self.data[0]) == 1 and not self.found_something):
raise StopIteration
else:
self._reset()
|
IndexError
|
dataset/ETHPy150Open blackberry/ALF/alf/reduce.py/FeedbackIter.next
|
9,993
|
def generate_temp_url(path, seconds, key, method, absolute=False):
"""Generates a temporary URL that gives unauthenticated access to the
Swift object.
:param path: The full path to the Swift object. Example:
/v1/AUTH_account/c/o.
:param seconds: The amount of time in seconds the temporary URL will
be valid for.
:param key: The secret temporary URL key set on the Swift
cluster. To set a key, run 'swift post -m
"Temp-URL-Key: <substitute tempurl key here>"'
:param method: A HTTP method, typically either GET or PUT, to allow
for this temporary URL.
:raises: ValueError if seconds is not a positive integer
:raises: TypeError if seconds is not an integer
:return: the path portion of a temporary URL
"""
if seconds < 0:
raise ValueError('seconds must be a positive integer')
try:
if not absolute:
expiration = int(time.time() + seconds)
else:
expiration = int(seconds)
except __HOLE__:
raise TypeError('seconds must be an integer')
standard_methods = ['GET', 'PUT', 'HEAD', 'POST', 'DELETE']
if method.upper() not in standard_methods:
logger = logging.getLogger("swiftclient")
logger.warning('Non default HTTP method %s for tempurl specified, '
'possibly an error', method.upper())
hmac_body = '\n'.join([method.upper(), str(expiration), path])
# Encode to UTF-8 for py3 compatibility
sig = hmac.new(key.encode(),
hmac_body.encode(),
hashlib.sha1).hexdigest()
return ('{path}?temp_url_sig='
'{sig}&temp_url_expires={exp}'.format(
path=path,
sig=sig,
exp=expiration))
|
TypeError
|
dataset/ETHPy150Open openstack/python-swiftclient/swiftclient/utils.py/generate_temp_url
|
9,994
|
def report_traceback():
"""
Reports a timestamp and full traceback for a given exception.
:return: Full traceback and timestamp.
"""
try:
formatted_lines = traceback.format_exc()
now = time.time()
return formatted_lines, now
except __HOLE__:
return None, None
|
AttributeError
|
dataset/ETHPy150Open openstack/python-swiftclient/swiftclient/utils.py/report_traceback
|
9,995
|
def __next__(self):
"""
Both ``__next__`` and ``next`` are provided to allow compatibility
with python 2 and python 3 and their use of ``iterable.next()``
and ``next(iterable)`` respectively.
"""
chunk = self.content.read(self.chunk_size)
if not chunk:
raise StopIteration
try:
self.md5sum.update(chunk)
except __HOLE__:
self.md5sum.update(chunk.encode())
return chunk
|
TypeError
|
dataset/ETHPy150Open openstack/python-swiftclient/swiftclient/utils.py/ReadableToIterable.__next__
|
9,996
|
def read(self, size=-1):
if self._remaining <= 0:
return ''
to_read = self._remaining if size < 0 else min(size, self._remaining)
chunk = self._readable.read(to_read)
self._remaining -= len(chunk)
try:
self.md5sum.update(chunk)
except __HOLE__:
self.md5sum.update(chunk.encode())
return chunk
|
TypeError
|
dataset/ETHPy150Open openstack/python-swiftclient/swiftclient/utils.py/LengthWrapper.read
|
9,997
|
def add_lazy_relation(cls, field, relation, operation):
"""
Adds a lookup on ``cls`` when a related field is defined using a string,
i.e.::
class MyModel(Model):
fk = ForeignKey("AnotherModel")
This string can be:
* RECURSIVE_RELATIONSHIP_CONSTANT (i.e. "self") to indicate a recursive
relation.
* The name of a model (i.e "AnotherModel") to indicate another model in
the same app.
* An app-label and model name (i.e. "someapp.AnotherModel") to indicate
another model in a different app.
If the other model hasn't yet been loaded -- almost a given if you're using
lazy relationships -- then the relation won't be set up until the
class_prepared signal fires at the end of model initialization.
operation is the work that must be performed once the relation can be resolved.
"""
# Check for recursive relations
if relation == RECURSIVE_RELATIONSHIP_CONSTANT:
app_label = cls._meta.app_label
model_name = cls.__name__
else:
# Look for an "app.Model" relation
try:
app_label, model_name = relation.split(".")
except __HOLE__:
# If we can't split, assume a model in current app
app_label = cls._meta.app_label
model_name = relation
# Try to look up the related model, and if it's already loaded resolve the
# string right away. If get_model returns None, it means that the related
# model isn't loaded yet, so we need to pend the relation until the class
# is prepared.
model = get_model(app_label, model_name, False)
if model:
operation(field, model, cls)
else:
key = (app_label, model_name)
value = (cls, field, operation)
pending_lookups.setdefault(key, []).append(value)
|
ValueError
|
dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/db/models/fields/related.py/add_lazy_relation
|
9,998
|
def get_db_prep_lookup(self, lookup_type, value):
# If we are doing a lookup on a Related Field, we must be
# comparing object instances. The value should be the PK of value,
# not value itself.
def pk_trace(value):
# Value may be a primary key, or an object held in a relation.
# If it is an object, then we need to get the primary key value for
# that object. In certain conditions (especially one-to-one relations),
# the primary key may itself be an object - so we need to keep drilling
# down until we hit a value that can be used for a comparison.
v, field = value, None
try:
while True:
v, field = getattr(v, v._meta.pk.name), v._meta.pk
except __HOLE__:
pass
if field:
if lookup_type in ('range', 'in'):
v = [v]
v = field.get_db_prep_lookup(lookup_type, v)
if isinstance(v, list):
v = v[0]
return v
if hasattr(value, 'as_sql') or hasattr(value, '_as_sql'):
# If the value has a relabel_aliases method, it will need to
# be invoked before the final SQL is evaluated
if hasattr(value, 'relabel_aliases'):
return value
if hasattr(value, 'as_sql'):
sql, params = value.as_sql()
else:
sql, params = value._as_sql()
return QueryWrapper(('(%s)' % sql), params)
# FIXME: lt and gt are explicitally allowed to make
# get_(next/prev)_by_date work; other lookups are not allowed since that
# gets messy pretty quick. This is a good candidate for some refactoring
# in the future.
if lookup_type in ['exact', 'gt', 'lt', 'gte', 'lte']:
return [pk_trace(value)]
if lookup_type in ('range', 'in'):
return [pk_trace(v) for v in value]
elif lookup_type == 'isnull':
return []
raise TypeError, "Related Field has invalid lookup: %s" % lookup_type
|
AttributeError
|
dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/db/models/fields/related.py/RelatedField.get_db_prep_lookup
|
9,999
|
def __get__(self, instance, instance_type=None):
if instance is None:
return self
try:
return getattr(instance, self.cache_name)
except __HOLE__:
params = {'%s__pk' % self.related.field.name: instance._get_pk_val()}
rel_obj = self.related.model._base_manager.get(**params)
setattr(instance, self.cache_name, rel_obj)
return rel_obj
|
AttributeError
|
dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/db/models/fields/related.py/SingleRelatedObjectDescriptor.__get__
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.