Unnamed: 0
int64 0
10k
| function
stringlengths 79
138k
| label
stringclasses 20
values | info
stringlengths 42
261
|
---|---|---|---|
3,900 |
def _english_wordlist(self):
try:
wl = self._en_wordlist
except __HOLE__:
from nltk.corpus import words
self._en_wordlist = set(words.words('en-basic'))
wl = self._en_wordlist
return wl
|
AttributeError
|
dataset/ETHPy150Open nltk/nltk/nltk/chunk/named_entity.py/NEChunkParserTagger._english_wordlist
|
3,901 |
def prepare(self):
"""
Read options for uploading, check that they're sane
"""
super(BlazeMeterUploader, self).prepare()
self.client.logger_limit = self.settings.get("request-logging-limit", self.client.logger_limit)
self.client.address = self.settings.get("address", self.client.address)
self.client.data_address = self.settings.get("data-address", self.client.data_address)
self.client.timeout = dehumanize_time(self.settings.get("timeout", self.client.timeout))
self.send_interval = dehumanize_time(self.settings.get("send-interval", self.send_interval))
self.browser_open = self.settings.get("browser-open", self.browser_open)
token = self.settings.get("token", "")
if not token:
self.log.warning("No BlazeMeter API key provided, will upload anonymously")
self.client.token = token
self.client.active_session_id = self.parameters.get("session-id", None)
self.client.test_id = self.parameters.get("test-id", None)
self.client.user_id = self.parameters.get("user-id", None)
self.client.data_signature = self.parameters.get("signature", None)
self.client.kpi_target = self.parameters.get("kpi-target", self.client.kpi_target)
if not self.client.test_id:
try:
self.client.ping() # to check connectivity and auth
except __HOLE__:
self.log.error("Cannot reach online results storage, maybe the address/token is wrong")
raise
if token:
finder = ProjectFinder(self.parameters, self.settings, self.client, self.engine)
self.test_id = finder.resolve_test_id({"type": "external"}, self.engine.config, [])
self.sess_name = self.parameters.get("report-name", self.settings.get("report-name", self.sess_name))
if self.sess_name == 'ask' and sys.stdin.isatty():
self.sess_name = r_input("Please enter report-name: ")
if isinstance(self.engine.aggregator, ResultsProvider):
self.engine.aggregator.add_listener(self)
|
HTTPError
|
dataset/ETHPy150Open Blazemeter/taurus/bzt/modules/blazemeter.py/BlazeMeterUploader.prepare
|
3,902 |
def startup(self):
"""
Initiate online test
"""
super(BlazeMeterUploader, self).startup()
if not self.client.active_session_id:
try:
url = self.client.start_online(self.test_id, self.sess_name)
self.log.info("Started data feeding: %s", url)
if self.browser_open in ('start', 'both'):
open_browser(url)
except __HOLE__:
raise
except BaseException as exc:
self.log.debug("Exception: %s", traceback.format_exc())
self.log.warning("Failed to start feeding: %s", exc)
raise
|
KeyboardInterrupt
|
dataset/ETHPy150Open Blazemeter/taurus/bzt/modules/blazemeter.py/BlazeMeterUploader.startup
|
3,903 |
def _postproc_phase2(self):
try:
self.__upload_artifacts()
except __HOLE__:
self.log.warning("Failed artifact upload: %s", traceback.format_exc())
finally:
self.set_last_status_check(self.parameters.get('forced-last-check', self._last_status_check))
tries = self.send_interval # NOTE: you dirty one...
while not self._last_status_check and tries > 0:
self.log.info("Waiting for ping...")
time.sleep(self.send_interval)
tries -= 1
self._postproc_phase3()
|
IOError
|
dataset/ETHPy150Open Blazemeter/taurus/bzt/modules/blazemeter.py/BlazeMeterUploader._postproc_phase2
|
3,904 |
def _postproc_phase3(self):
try:
self.client.end_online()
if self.engine.stopping_reason:
note = "%s: %s" % (self.engine.stopping_reason.__class__.__name__, str(self.engine.stopping_reason))
sess = self.client.get_session(self.client.active_session_id)
if 'note' in sess:
note += "\n" + sess['note']
self.client.update_session(self.client.active_session_id, {"note": note})
except __HOLE__:
raise
except BaseException as exc:
self.log.warning("Failed to finish online: %s", exc)
|
KeyboardInterrupt
|
dataset/ETHPy150Open Blazemeter/taurus/bzt/modules/blazemeter.py/BlazeMeterUploader._postproc_phase3
|
3,905 |
def __send_data(self, data, do_check=True, is_final=False):
"""
:param data: list[bzt.modules.aggregator.DataPoint]
:return:
"""
if not self.client.active_session_id:
return
try:
self.client.send_kpi_data(data, do_check, is_final)
except __HOLE__ as _:
self.log.debug("Error sending data: %s", traceback.format_exc())
self.log.warning("Failed to send data, will retry in %s sec...", self.client.timeout)
try:
time.sleep(self.client.timeout)
self.client.send_kpi_data(data, do_check, is_final)
self.log.info("Succeeded with retry")
except IOError as _:
self.log.error("Fatal error sending data: %s", traceback.format_exc())
self.log.warning("Will skip failed data and continue running")
if not data:
return
try:
self.client.send_error_summary(data)
except IOError as exc:
self.log.debug("Failed sending error summary: %s", traceback.format_exc())
self.log.warning("Failed to send error summary: %s", exc)
|
IOError
|
dataset/ETHPy150Open Blazemeter/taurus/bzt/modules/blazemeter.py/BlazeMeterUploader.__send_data
|
3,906 |
def _request(self, url, data=None, headers=None, checker=None, method=None):
if not headers:
headers = {}
if self.token:
headers["X-Api-Key"] = self.token
log_method = 'GET' if data is None else 'POST'
if method:
log_method = method
self.log.debug("Request: %s %s %s", log_method, url, data[:self.logger_limit] if data else None)
# .encode("utf-8") is probably better
data = data.encode() if isinstance(data, text_type) else data
req = Request(url, data, headers)
if method:
req.get_method = lambda: method
response = urlopen(req, timeout=self.timeout)
if checker:
checker(response)
resp = response.read()
if not isinstance(resp, str):
resp = resp.decode()
self.log.debug("Response: %s", resp[:self.logger_limit] if resp else None)
try:
return json.loads(resp) if len(resp) else {}
except __HOLE__:
self.log.warning("Non-JSON response from API: %s", resp)
raise
|
ValueError
|
dataset/ETHPy150Open Blazemeter/taurus/bzt/modules/blazemeter.py/BlazeMeterClient._request
|
3,907 |
def update(self):
if not self._sessions:
self._sessions = self.prov.client.get_master_sessions(self.prov.client.active_session_id)
if not self._sessions:
return
mapping = BetterDict()
cnt = 0
for session in self._sessions:
try:
cnt += 1
name_split = session['name'].split('/')
location = session['configuration']['location']
count = session['configuration']['serversCount']
mapping.get(name_split[0]).get(name_split[1])[location] = count
except __HOLE__:
self._sessions = None
txt = "%s #%s\n" % (self.prov.test_name, self.prov.client.active_session_id)
for executor, scenarios in iteritems(mapping):
txt += " %s" % executor
for scenario, locations in iteritems(scenarios):
txt += " %s:\n" % scenario
for location, count in iteritems(locations):
txt += " Agents in %s: %s\n" % (location, count)
self.text.set_text(txt)
|
KeyError
|
dataset/ETHPy150Open Blazemeter/taurus/bzt/modules/blazemeter.py/CloudProvWidget.update
|
3,908 |
def round_trip(o, output=False, list_=False):
""" Performs all eight conversions to verify import/export functionality.
1. cybox.Entity -> dict/list
2. dict/list -> JSON string
3. JSON string -> dict/list
4. dict/list -> cybox.Entity
5. cybox.Entity -> Bindings Object
6. Bindings Object -> XML String
7. XML String -> Bindings Object
8. Bindings object -> cybox.Entity
It returns the final object, so tests which call this function can check to
ensure it was not modified during any of the transforms.
"""
klass = o.__class__
if output:
print "Class: ", klass
print "-" * 40
# 1. cybox.Entity -> dict/list
if list_:
d = o.to_list()
else:
d = o.to_dict()
# 2. dict/list -> JSON string
json_string = json.dumps(d)
if output:
print(json_string)
print "-" * 40
# Before parsing the JSON, make sure the cache is clear
cybox.utils.cache_clear()
# 3. JSON string -> dict/list
d2 = json.loads(json_string)
# 4. dict/list -> cybox.Entity
if list_:
o2 = klass.from_list(d2)
else:
o2 = klass.from_dict(d2)
# 5. Entity -> Bindings Object
ns_info = NamespaceInfo()
xobj = o2.to_obj(ns_info=ns_info)
try:
# 6. Bindings Object -> XML String
xml_string = o2.to_xml(encoding=ExternalEncoding)
if not isinstance(xml_string, unicode):
xml_string = xml_string.decode(ExternalEncoding)
except __HOLE__ as ex:
print str(ex)
ns_info.finalize()
print ns_info.finalized_namespaces
raise ex
if output:
print(xml_string)
print "-" * 40
# Before parsing the XML, make sure the cache is clear
cybox.utils.cache_clear()
#7. XML String -> Bindings Object
xobj2 = klass._binding.parseString(xml_string)
# 8. Bindings object -> cybox.Entity
o3 = klass.from_obj(xobj2)
return o3
|
KeyError
|
dataset/ETHPy150Open STIXProject/python-stix/stix/test/__init__.py/round_trip
|
3,909 |
def symbol_decode(input, errors='strict'):
chars = []
for (i, c) in enumerate(input):
try:
chars.append(decodeTable[ord(c)])
except __HOLE__:
if errors == 'replace':
chars.append(ord(u'?'))
else:
raise UnicodeDecodeError("symbol", input, i, i+1, ERROR_STRING)
return (u"".join(map(unichr, chars)), len(input))
|
KeyError
|
dataset/ETHPy150Open brendonh/pyth/pyth/encodings/symbol.py/symbol_decode
|
3,910 |
def symbol_encode(input, errors='strict'):
chars = []
for (i, c) in enumerate(input):
try:
chars.append(encodeTable[ord(c)])
except __HOLE__:
if errors == 'replace':
chars.append(ord('?'))
else:
raise UnicodeEncodeError("symbol", input, i, i+1, ERROR_STRING)
return ("".join(map(chr, chars)), len(input))
### Codec APIs
|
KeyError
|
dataset/ETHPy150Open brendonh/pyth/pyth/encodings/symbol.py/symbol_encode
|
3,911 |
def decode(self, input, final=False):
try:
return symbol_decode(input)[0]
except __HOLE__:
raise ValueError(ERROR_STRING)
|
UnicodeDecodeError
|
dataset/ETHPy150Open brendonh/pyth/pyth/encodings/symbol.py/IncrementalDecoder.decode
|
3,912 |
def get_glyph_coords(c):
try:
return glyph_coords[c]
except __HOLE__:
return glyph_coords['\x00']
|
KeyError
|
dataset/ETHPy150Open zoofIO/flexx/flexx/lui/widgets.py/get_glyph_coords
|
3,913 |
def __get__(self, inst, owner):
now = time.time()
try:
value, last_update = inst._cache[self.__name__]
if now - last_update > self.ttl > 0:
raise AttributeError
except (KeyError, AttributeError):
value = self.fget(inst)
try:
cache = inst._cache
except __HOLE__:
cache = inst._cache = {}
cache[self.__name__] = (value, now)
return value
|
AttributeError
|
dataset/ETHPy150Open smiley/steamapi/steamapi/decorators.py/cached_property.__get__
|
3,914 |
def __call__(self, *args, **kwargs):
"""
Returns the singleton instance. Upon its first call, it creates a
new instance of the decorated class and calls its `__init__` method.
On all subsequent calls, the already created instance is returned.
"""
with self._lock:
try:
return self._instance
except __HOLE__:
self._instance = self._decorated(*args, **kwargs)
return self._instance
|
AttributeError
|
dataset/ETHPy150Open smiley/steamapi/steamapi/decorators.py/Singleton.__call__
|
3,915 |
def run(self):
"""
each plugin has to implement this method -- it is used to run the plugin actually
response from plugin is kept and used in json result response
"""
try:
shutil.copyfile(self.workflow.builder.df_path, self.path)
except (__HOLE__, OSError) as ex:
msg = "Couldn't copy dockerfile: %r" % ex
self.log.error(msg)
return msg
else:
msg = "Dockerfile successfully copied to '%s'" % self.path
self.log.info(msg)
return msg
|
IOError
|
dataset/ETHPy150Open projectatomic/atomic-reactor/atomic_reactor/plugins/pre_cp_dockerfile.py/CpDockerfilePlugin.run
|
3,916 |
def dashboard(request, mine=True, username=None):
"""
User's HQ is where the user can get updates on the things that interest them
and manage their creations.
Not the same as the user's profile.
"""
is_me = False
if mine:
if request.user.is_authenticated():
the_user = request.user
is_me = True
else:
return HttpResponseRedirect(settings.LOGIN_URL+'?next=%s' % request.path)
else:
the_user = get_object_or_404(User, username=username)
if the_user == request.user:
is_me = True
subscriptions = Subscription.objects.filter(user=the_user)
feeds = [sub.feed for sub in subscriptions]
updates = Update.objects.filter(feed__in=feeds).order_by('-created')
# Paginate the list
paginator = Paginator(updates, 20) # Show 20 updates per page
# Make sure page request is an int. If not, deliver first page.
try:
page = int(request.GET.get('page', '1'))
except __HOLE__:
page = 1
# If page is out of range, deliver last page of results.
try:
updates = paginator.page(page)
except (EmptyPage, InvalidPage):
updates = paginator.page(paginator.num_pages)
return render_to_response('dashboard/dashboard.html', {
'the_user': the_user,
'is_me': is_me,
'subscriptions': subscriptions,
'feeds': feeds,
'updates': updates,
}, context_instance=RequestContext(request)
)
|
ValueError
|
dataset/ETHPy150Open caseywstark/colab/colab/apps/dashboard/views.py/dashboard
|
3,917 |
def votes(request, mine=True, username=None):
is_me = False
if mine:
the_user = request.user
is_me = True
else:
the_user = get_object_or_404(User, username=username)
if the_user == request.user:
is_me = True
the_researcher = request.user.get_profile()
votes = Vote.objects.filter(user=request.user)
# Paginate the list
paginator = Paginator(votes, 20) # Show 20 votes per page
# Make sure page request is an int. If not, deliver first page.
try:
page = int(request.GET.get('page', '1'))
except __HOLE__:
page = 1
# If page is out of range, deliver last page of results.
try:
votes = paginator.page(page)
except (EmptyPage, InvalidPage):
votes = paginator.page(paginator.num_pages)
return render_to_response('dashboard/votes.html', {
'the_user': the_user,
'is_me': is_me,
'votes': votes,
}, context_instance=RequestContext(request)
)
|
ValueError
|
dataset/ETHPy150Open caseywstark/colab/colab/apps/dashboard/views.py/votes
|
3,918 |
def make_msgid(idstring=None):
"""Returns a string suitable for RFC 2822 compliant Message-ID, e.g:
<[email protected]>
Optional idstring if given is a string used to strengthen the
uniqueness of the message id.
"""
timeval = time.time()
utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval))
try:
pid = os.getpid()
except __HOLE__:
# No getpid() in Jython, for example.
pid = 1
randint = random.randrange(100000)
if idstring is None:
idstring = ''
else:
idstring = '.' + idstring
idhost = DNS_NAME
msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, idhost)
return msgid
|
AttributeError
|
dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/core/mail.py/make_msgid
|
3,919 |
def __getattr__(self, name):
try:
return self[name]
except __HOLE__:
raise AttributeError(name)
|
KeyError
|
dataset/ETHPy150Open limodou/uliweb/uliweb/core/template.py/ObjectDict.__getattr__
|
3,920 |
def _convert_entity(m):
if m.group(1) == "#":
try:
return unichr(int(m.group(2)))
except ValueError:
return "&#%s;" % m.group(2)
try:
return _HTML_UNICODE_MAP[m.group(2)]
except __HOLE__:
return "&%s;" % m.group(2)
|
KeyError
|
dataset/ETHPy150Open limodou/uliweb/uliweb/core/template.py/_convert_entity
|
3,921 |
def set(self, key, value, mtime=None):
del self[key]
self.__values[key] = value
try:
pos = self.__access_keys.remove(key)
except __HOLE__:
pass
self.__access_keys.insert(0, key)
if self.check_modified_time:
self.__modified_times[key] = mtime or os.path.getmtime(key)
self.cleanup()
|
ValueError
|
dataset/ETHPy150Open limodou/uliweb/uliweb/core/template.py/LRUTmplatesCacheDict.set
|
3,922 |
def get_all(self, model_query):
"""Returns all model instances of this type matching the given
query."""
if model_query.fetch_offset is not None:
# if possible, attempt to fetch more than we really want so that
# we can determine if we have more results. this trick is only
# possible if fetching w/ offsets
real_fetch_page_size = model_query.fetch_page_size
if(model_query.fetch_page_size < MAX_FETCH_PAGE_SIZE):
model_query.fetch_page_size += 1
if(model_query.query_expr is None):
query = self.model_type.all()
if(model_query.ordering):
query.order(QUERY_ORDER_PREFIXES[model_query.order_type_idx] +
model_query.ordering)
else:
if(model_query.ordering):
model_query.query_expr += (
QUERY_ORDERBY + model_query.ordering +
QUERY_ORDER_SUFFIXES[model_query.order_type_idx])
query = self.model_type.gql(model_query.query_expr,
*model_query.query_params)
if model_query.fetch_offset is None:
if model_query.fetch_cursor:
query.with_cursor(model_query.fetch_cursor)
models = query.fetch(model_query.fetch_page_size)
if(len(models) == model_query.fetch_page_size):
try:
model_query.next_fetch_offset = (QUERY_CURSOR_PREFIX +
query.cursor())
except __HOLE__:
# some queries don't allow cursors, fallback to offsets
model_query.next_fetch_offset = str(
model_query.fetch_page_size)
else:
models = query.fetch(model_query.fetch_page_size,
model_query.fetch_offset)
if(len(models) >= model_query.fetch_page_size):
model_query.next_fetch_offset = str(real_fetch_page_size +
model_query.fetch_offset)
# trim list to the actual size we want
if(len(models) > real_fetch_page_size):
models = models[0:real_fetch_page_size]
return models
|
AssertionError
|
dataset/ETHPy150Open jahlborn/appengine-rest-server/src/main/python/rest/__init__.py/ModelHandler.get_all
|
3,923 |
def get_model_handler(self, model_name, method_name, failure_code=404):
"""Returns the ModelHandler with the given name, or None (and sets
the error code given) if there is no handler with the given name."""
# see if namespace was specified, e.g. "<ns>.<model_name>"
ns_model_name = model_name.rpartition(".")
if(ns_model_name[0]):
# only set namespace if callers are allowed to
if WRITE_EXT_NS not in self.external_namespaces:
raise DispatcherException(404)
namespace_manager.set_namespace(ns_model_name[0])
# remove namespace from model name
model_name = ns_model_name[2]
try:
model_handler = self.model_handlers[model_name]
except __HOLE__:
logging.error("invalid model name %s", model_name, exc_info=1)
raise DispatcherException(failure_code)
if method_name not in model_handler.model_methods:
raise DispatcherException(405)
return model_handler
|
KeyError
|
dataset/ETHPy150Open jahlborn/appengine-rest-server/src/main/python/rest/__init__.py/Dispatcher.get_model_handler
|
3,924 |
def evaluate(self, code):
if not code.strip():
# scheme.scheme_read can't handle empty strings.
return None, ''
log_id = output.new_log()
try:
exp = self.scheme.read_line(code)
result = timer.timed(self.timeout, self.scheme.scheme_eval,
(exp, self._frame))
except __HOLE__ as e:
stacktrace_length = 15
stacktrace = traceback.format_exc().strip().split('\n')
print('Traceback (most recent call last):\n ...')
print('\n'.join(stacktrace[-stacktrace_length:]))
raise interpreter.ConsoleException(e)
except exceptions.Timeout as e:
print('# Error: evaluation exceeded {} seconds.'.format(e.timeout))
raise interpreter.ConsoleException(e)
except self.scheme.SchemeError as e:
print('# Error: {}'.format(e))
raise interpreter.ConsoleException(e, exception_type='SchemeError')
except Exception as e:
stacktrace = traceback.format_exc()
token = '<module>\n'
index = stacktrace.rfind(token) + len(token)
stacktrace = stacktrace[index:].rstrip('\n')
if '\n' in stacktrace:
print('Traceback (most recent call last):')
print(stacktrace)
raise interpreter.ConsoleException(e)
else:
printed_output = ''.join(output.get_log(log_id))
return result, printed_output
finally:
output.remove_log(log_id)
|
RuntimeError
|
dataset/ETHPy150Open Cal-CS-61A-Staff/ok-client/client/sources/ok_test/scheme.py/SchemeConsole.evaluate
|
3,925 |
def _import_scheme(self):
try:
sys.path.insert(0, 'scheme')
self.scheme = importlib.import_module(self.MODULE)
except __HOLE__ as e:
raise exceptions.ProtocolException('Could not import scheme')
|
ImportError
|
dataset/ETHPy150Open Cal-CS-61A-Staff/ok-client/client/sources/ok_test/scheme.py/SchemeConsole._import_scheme
|
3,926 |
def html_generate(env, options, input_js, input_html):
"""
Generate html based on the templates and build mode.
"""
# - dev, canvas_dev:
# render top-level js files into a temporary file
# collect the .js files that need to be included
# setup includes, startup code and the js render result into variables
# render html template
#
# - release, canvas:
# need to know name of output js file
# setup startup code to point to .tzjs or .js file
# render html template
# Load templates (using default html template if not specified)
Profiler.start('load_templates')
template_html = load_html_template(env, input_html)
if template_html is None:
LOG.error("failed to load file %s from template dirs", input_html[0])
exit(1)
# Get context
if len(input_js) > 0:
title = input_js[0]
elif options.codefile:
title = options.codefile
elif len(input_html) > 0:
title = input_html[0]
else:
title = "Unknown"
title = splitext(basename(title))[0]
context = context_from_options(options, title)
Profiler.stop('load_templates')
Profiler.start('code_gen')
# In development modes, render the JS code that needs embedding
rendered_js = ""
inc_js = []
if options.mode in [ 'plugin-debug', 'canvas-debug' ]:
inject_js = inject_js_from_options(options)
Profiler.start('load_js_templates')
templates_js = env_load_templates(env, input_js)
Profiler.stop('load_js_templates')
(rendered_js, inc_js) = render_js(context, options, templates_js,
inject_js)
# Add the HTML and JS code into the tz_* variables
default_add_code(options, context, rendered_js, inc_js)
Profiler.stop('code_gen')
Profiler.start('html_render')
# Render the template and write it out
try:
res = template_html.render(context)
except Exception, e:
raise ToolsException("Error in '%s': %s %s" \
% (input_html, e.__class__.__name__, str(e)))
try:
with open(options.output, "wb") as f:
f.write(res.encode('utf-8'))
except __HOLE__:
raise ToolsException("failed to create file: %s" % options.output)
Profiler.stop('html_render')
return 0
############################################################
|
IOError
|
dataset/ETHPy150Open turbulenz/turbulenz_tools/turbulenz_tools/tools/makehtml.py/html_generate
|
3,927 |
def gvars(app):
@app.before_request
def gdebug():
if app.debug:
g.debug = True
else:
g.debug = False
app.context_processor(backends)
from .models import User
@login_manager.user_loader
def load_user(userid):
try:
return User.query.get(int(userid))
except (TypeError, __HOLE__):
pass
@app.before_request
def guser():
g.user = login.current_user
@app.context_processor
def inject_user():
try:
return {'user': g.user}
except AttributeError:
return {'user': None}
@babel.localeselector
def get_locale():
if g.user:
if hasattr(g.user, 'ui_lang'):
return g.user.ui_lang
accept_languages = app.config.get('ACCEPT_LANGUAGES')
return request.accept_languages.best_match(accept_languages)
|
ValueError
|
dataset/ETHPy150Open xen/flask-project-template/project/app.py/gvars
|
3,928 |
def __init__(self, tasker, workflow,
pulp_registry_name,
docker_registry,
delete_from_registry=False,
pulp_secret_path=None,
username=None, password=None,
dockpulp_loglevel=None):
"""
constructor
:param tasker: DockerTasker instance
:param workflow: DockerBuildWorkflow instance
:param pulp_registry_name: str, name of pulp registry to use,
specified in /etc/dockpulp.conf
:param docker_registry: str, URL of docker registry to sync from
:param delete_from_registry: bool, whether to delete the image
from the docker v2 registry after sync
:param pulp_secret_path: path to pulp.cer and pulp.key
:param username: pulp username, used in preference to
certificate and key
:param password: pulp password, used in preference to
certificate and key
"""
# call parent constructor
super(PulpSyncPlugin, self).__init__(tasker, workflow)
self.pulp_registry_name = pulp_registry_name
self.docker_registry = docker_registry
self.pulp_secret_path = pulp_secret_path
self.username = username
self.password = password
if dockpulp_loglevel is not None:
logger = dockpulp.setup_logger(dockpulp.log)
try:
logger.setLevel(dockpulp_loglevel)
except (__HOLE__, TypeError) as ex:
self.log.error("Can't set provided log level %r: %r",
dockpulp_loglevel, ex)
if delete_from_registry:
self.log.error("will not delete from registry as instructed: "
"not implemented")
|
ValueError
|
dataset/ETHPy150Open projectatomic/atomic-reactor/atomic_reactor/plugins/post_pulp_sync.py/PulpSyncPlugin.__init__
|
3,929 |
def assert_classifier_correct(algorithm):
try:
classifier = classify.MaxentClassifier.train(
TRAIN, algorithm, trace=0, max_iter=1000
)
except (LookupError, __HOLE__) as e:
raise SkipTest(str(e))
for (px, py), featureset in zip(RESULTS, TEST):
pdist = classifier.prob_classify(featureset)
assert abs(pdist.prob('x') - px) < 1e-2, (pdist.prob('x'), px)
assert abs(pdist.prob('y') - py) < 1e-2, (pdist.prob('y'), py)
|
AttributeError
|
dataset/ETHPy150Open nltk/nltk/nltk/test/unit/test_classify.py/assert_classifier_correct
|
3,930 |
def doQuit(self, irc, msg):
# We want to observe netsplits and keep from heralding users rejoining
# after one.
if ircmsgs.isSplit(msg):
self.splitters.enqueue(msg.nick)
try:
id = ircdb.users.getUserId(msg.prefix)
self.splitters.enqueue(id)
except __HOLE__:
pass
|
KeyError
|
dataset/ETHPy150Open ProgVal/Limnoria/plugins/Herald/plugin.py/Herald.doQuit
|
3,931 |
def doJoin(self, irc, msg):
if ircutils.strEqual(irc.nick, msg.nick):
return # It's us.
if msg.nick in self.splitters:
self.log.debug('Not heralding %s, recent split.', msg.nick)
return # Recently split.
channel = msg.args[0]
irc = callbacks.SimpleProxy(irc, msg)
if self.registryValue('heralding', channel):
try:
id = ircdb.users.getUserId(msg.prefix)
if id in self.splitters:
self.log.debug('Not heralding id #%s, recent split.', id)
return
herald = self.db[channel, id]
except __HOLE__:
default = self.registryValue('default', channel)
if default:
default = ircutils.standardSubstitute(irc, msg, default)
msgmaker = ircmsgs.privmsg
if self.registryValue('default.notice', channel):
msgmaker = ircmsgs.notice
target = msg.nick
if self.registryValue('default.public', channel):
target = channel
irc.queueMsg(msgmaker(target, default))
return
now = time.time()
throttle = self.registryValue('throttle', channel)
if now - self.lastHerald.get((channel, id), 0) > throttle:
if (channel, id) in self.lastParts:
i = self.registryValue('throttle.afterPart', channel)
if now - self.lastParts[channel, id] < i:
return
self.lastHerald[channel, id] = now
herald = ircutils.standardSubstitute(irc, msg, herald)
irc.reply(herald, prefixNick=False)
|
KeyError
|
dataset/ETHPy150Open ProgVal/Limnoria/plugins/Herald/plugin.py/Herald.doJoin
|
3,932 |
def doPart(self, irc, msg):
try:
id = self._getId(irc, msg.prefix)
self.lastParts[msg.args[0], id] = time.time()
except __HOLE__:
pass
|
KeyError
|
dataset/ETHPy150Open ProgVal/Limnoria/plugins/Herald/plugin.py/Herald.doPart
|
3,933 |
def _getId(self, irc, userNickHostmask):
try:
id = ircdb.users.getUserId(userNickHostmask)
except __HOLE__:
if not ircutils.isUserHostmask(userNickHostmask):
hostmask = irc.state.nickToHostmask(userNickHostmask)
id = ircdb.users.getUserId(hostmask)
else:
raise KeyError
return id
|
KeyError
|
dataset/ETHPy150Open ProgVal/Limnoria/plugins/Herald/plugin.py/Herald._getId
|
3,934 |
@internationalizeDocstring
def get(self, irc, msg, args, channel, user):
"""[<channel>] [<user|nick>]
Returns the current herald message for <user> (or the user
<nick|hostmask> is currently identified or recognized as). If <user>
is not given, defaults to the user giving the command. <channel>
is only necessary if the message isn't sent in the channel itself.
"""
try:
herald = self.db[channel, user.id]
irc.reply(herald)
except __HOLE__:
irc.error(_('I have no herald for %s.') % user.name)
|
KeyError
|
dataset/ETHPy150Open ProgVal/Limnoria/plugins/Herald/plugin.py/Herald.get
|
3,935 |
def _preCheck(self, irc, msg, user):
capability = self.registryValue('requireCapability')
if capability:
try:
u = ircdb.users.getUser(msg.prefix)
except __HOLE__:
irc.errorNotRegistered(Raise=True)
else:
if u != user:
if not ircdb.checkCapability(msg.prefix, capability):
irc.errorNoCapability(capability, Raise=True)
# I chose not to make <user|nick> optional in this command because
# if it's not a valid username (e.g., if the user tyops and misspells a
# username), it may be nice not to clobber the user's herald.
|
KeyError
|
dataset/ETHPy150Open ProgVal/Limnoria/plugins/Herald/plugin.py/Herald._preCheck
|
3,936 |
@internationalizeDocstring
def remove(self, irc, msg, args, channel, user):
"""[<channel>] [<user|nick>]
Removes the herald message set for <user>, or the user
<nick|hostmask> is currently identified or recognized as. If <user>
is not given, defaults to the user giving the command.
<channel> is only necessary if the message isn't sent in the channel
itself.
"""
self._preCheck(irc, msg, user)
try:
del self.db[channel, user.id]
irc.replySuccess()
except __HOLE__:
irc.error(_('I have no herald for that user.'))
|
KeyError
|
dataset/ETHPy150Open ProgVal/Limnoria/plugins/Herald/plugin.py/Herald.remove
|
3,937 |
def __call__(self, env, start_response):
"""WSGI `app` method.
Makes instances of API callable from a WSGI server. May be used to
host an API or called directly in order to simulate requests when
testing the API.
See also PEP 3333.
Args:
env (dict): A WSGI environment dictionary
start_response (callable): A WSGI helper function for setting
status and headers on a response.
"""
req = self._request_type(env, options=self.req_options)
resp = self._response_type()
resource = None
middleware_stack = [] # Keep track of executed components
params = {}
try:
# NOTE(kgriffs): Using an inner try..except in order to
# address the case when err_handler raises HTTPError.
# NOTE(kgriffs): Coverage is giving false negatives,
# so disabled on relevant lines. All paths are tested
# afaict.
try:
# NOTE(ealogar): The execution of request middleware should be
# before routing. This will allow request mw to modify path.
self._call_req_mw(middleware_stack, req, resp)
# NOTE(warsaw): Moved this to inside the try except because it
# is possible when using object-based traversal for
# _get_responder() to fail. An example is a case where an
# object does not have the requested next-hop child resource.
# In that case, the object being asked to dispatch to its
# child will raise an HTTP exception signalling the problem,
# e.g. a 404.
responder, params, resource = self._get_responder(req)
# NOTE(kgriffs): If the request did not match any route,
# a default responder is returned and the resource is
# None.
if resource is not None:
self._call_rsrc_mw(middleware_stack, req, resp, resource,
params)
responder(req, resp, **params)
self._call_resp_mw(middleware_stack, req, resp, resource)
except Exception as ex:
for err_type, err_handler in self._error_handlers:
if isinstance(ex, err_type):
err_handler(ex, req, resp, params)
self._call_resp_mw(middleware_stack, req, resp,
resource)
break
else:
# PERF(kgriffs): This will propagate HTTPError to
# the handler below. It makes handling HTTPError
# less efficient, but that is OK since error cases
# don't need to be as fast as the happy path, and
# indeed, should perhaps be slower to create
# backpressure on clients that are issuing bad
# requests.
# NOTE(ealogar): This will executed remaining
# process_response when no error_handler is given
# and for whatever exception. If an HTTPError is raised
# remaining process_response will be executed later.
self._call_resp_mw(middleware_stack, req, resp, resource)
raise
except HTTPStatus as ex:
self._compose_status_response(req, resp, ex)
self._call_resp_mw(middleware_stack, req, resp, resource)
except __HOLE__ as ex:
self._compose_error_response(req, resp, ex)
self._call_resp_mw(middleware_stack, req, resp, resource)
#
# Set status and headers
#
if req.method == 'HEAD' or resp.status in self._BODILESS_STATUS_CODES:
body = []
else:
body, length = self._get_body(resp, env.get('wsgi.file_wrapper'))
if length is not None:
resp._headers['content-length'] = str(length)
# NOTE(kgriffs): Based on wsgiref.validate's interpretation of
# RFC 2616, as commented in that module's source code. The
# presence of the Content-Length header is not similarly
# enforced.
if resp.status in (status.HTTP_204, status.HTTP_304):
media_type = None
else:
media_type = self._media_type
headers = resp._wsgi_headers(media_type)
# Return the response per the WSGI spec
start_response(resp.status, headers)
return body
|
HTTPError
|
dataset/ETHPy150Open falconry/falcon/falcon/api.py/API.__call__
|
3,938 |
def add_error_handler(self, exception, handler=None):
"""Registers a handler for a given exception error type.
Args:
exception (type): Whenever an error occurs when handling a request
that is an instance of this exception class, the associated
handler will be called.
handler (callable): A function or callable object taking the form
``func(ex, req, resp, params)``.
If not specified explicitly, the handler will default to
``exception.handle``, where ``exception`` is the error
type specified above, and ``handle`` is a static method
(i.e., decorated with @staticmethod) that accepts
the same params just described. For example::
class CustomException(CustomBaseException):
@staticmethod
def handle(ex, req, resp, params):
# TODO: Log the error
# Convert to an instance of falcon.HTTPError
raise falcon.HTTPError(falcon.HTTP_792)
Note:
A handler can either raise an instance of ``HTTPError``
or modify `resp` manually in order to communicate
information about the issue to the client.
"""
if handler is None:
try:
handler = exception.handle
except __HOLE__:
raise AttributeError('handler must either be specified '
'explicitly or defined as a static'
'method named "handle" that is a '
'member of the given exception class.')
# Insert at the head of the list in case we get duplicate
# adds (will cause the most recently added one to win).
self._error_handlers.insert(0, (exception, handler))
|
AttributeError
|
dataset/ETHPy150Open falconry/falcon/falcon/api.py/API.add_error_handler
|
3,939 |
def _get_responder(self, req):
"""Searches routes for a matching responder.
Args:
req: The request object.
Returns:
A 3-member tuple consisting of a responder callable,
a ``dict`` containing parsed path fields (if any were specified in
the matching route's URI template), and a reference to the
responder's resource instance.
Note:
If a responder was matched to the given URI, but the HTTP
method was not found in the method_map for the responder,
the responder callable element of the returned tuple will be
`falcon.responder.bad_request`.
Likewise, if no responder was matched for the given URI, then
the responder callable element of the returned tuple will be
`falcon.responder.path_not_found`
"""
path = req.path
method = req.method
route = self._router.find(path)
if route is not None:
resource, method_map, params = route
else:
# NOTE(kgriffs): Older routers may indicate that no route
# was found by returning (None, None, None). Therefore, we
# normalize resource as the flag to indicate whether or not
# a route was found, for the sake of backwards-compat.
resource = None
if resource is not None:
try:
responder = method_map[method]
except __HOLE__:
responder = falcon.responders.bad_request
else:
params = {}
for pattern, sink in self._sinks:
m = pattern.match(path)
if m:
params = m.groupdict()
responder = sink
break
else:
responder = falcon.responders.path_not_found
return (responder, params, resource)
|
KeyError
|
dataset/ETHPy150Open falconry/falcon/falcon/api.py/API._get_responder
|
3,940 |
def __add__(self, other):
try:
pairs = itertools.zip_longest(self, other, fillvalue=0.0)
return Vector(a + b for a, b in pairs)
except __HOLE__:
return NotImplemented
|
TypeError
|
dataset/ETHPy150Open fluentpython/example-code/13-op-overloading/vector_v6.py/Vector.__add__
|
3,941 |
def npm(b, r):
logging.info('searching for npm packages')
# Precompile a pattern for parsing the output of `{pear,pecl} list`.
pattern = re.compile(r'^\S+ (\S+)@(\S+)$')
try:
p = subprocess.Popen(['npm', 'ls', '-g'],
close_fds=True,
stdout=subprocess.PIPE)
for line in p.stdout:
match = pattern.match(line.rstrip())
if match is None:
continue
package, version = match.group(1), match.group(2)
if not r.ignore_package('nodejs', package):
b.add_package('nodejs', package, version)
except __HOLE__:
pass
|
OSError
|
dataset/ETHPy150Open devstructure/blueprint/blueprint/backend/npm.py/npm
|
3,942 |
def get(self, poolName):
try:
pool = self.getDispatchTree().pools[poolName]
except __HOLE__:
raise Http404('No such pool')
self.writeCallback({
'pool': pool.to_json()
})
#@queue
|
KeyError
|
dataset/ETHPy150Open mikrosimage/OpenRenderManagement/src/octopus/dispatcher/webservice/pools.py/PoolResource.get
|
3,943 |
def delete(self, poolName):
try:
# remove reference of the pool from all rendernodes
for rn in self.getDispatchTree().renderNodes.values():
if self.getDispatchTree().pools[poolName] in rn.pools:
rn.pools.remove(self.getDispatchTree().pools[poolName])
# try to remove the pool from the dispatch tree
self.getDispatchTree().pools[poolName].archive()
except __HOLE__, e:
logger.warning("No such pool: %r" % e)
raise Http404('No such pool')
|
KeyError
|
dataset/ETHPy150Open mikrosimage/OpenRenderManagement/src/octopus/dispatcher/webservice/pools.py/PoolResource.delete
|
3,944 |
def get_object_or_404(query_or_model, *query):
if not isinstance(query_or_model, SelectQuery):
query_or_model = query_or_model.select()
try:
return query_or_model.where(*query).get()
except __HOLE__:
abort(404)
|
DoesNotExist
|
dataset/ETHPy150Open coleifer/flask-peewee/flask_peewee/utils.py/get_object_or_404
|
3,945 |
def npgettext(self, context, singular, plural, num):
"""Do a plural-forms lookup of a message id. `singular` is used as the
message id for purposes of lookup in the catalog, while `num` is used to
determine which plural form to use. The returned message string is an
8-bit string encoded with the catalog's charset encoding, if known.
If the message id for `context` is not found in the catalog, and a
fallback is specified, the request is forwarded to the fallback's
``npgettext()`` method. Otherwise, when ``num`` is 1 ``singular`` is
returned, and ``plural`` is returned in all other cases.
"""
ctxt_msg_id = self.CONTEXT_ENCODING % (context, singular)
try:
tmsg = self._catalog[(ctxt_msg_id, self.plural(num))]
if self._output_charset:
return text_to_native(tmsg, self._output_charset)
elif self._charset:
return text_to_native(tmsg, self._charset)
return tmsg
except __HOLE__:
if self._fallback:
return self._fallback.npgettext(context, singular, plural, num)
if num == 1:
return singular
else:
return plural
|
KeyError
|
dataset/ETHPy150Open lad1337/XDM/site-packages/babel/support.py/NullTranslations.npgettext
|
3,946 |
def lnpgettext(self, context, singular, plural, num):
"""Equivalent to ``npgettext()``, but the translation is returned in the
preferred system encoding, if no other encoding was explicitly set with
``bind_textdomain_codeset()``.
"""
ctxt_msg_id = self.CONTEXT_ENCODING % (context, singular)
try:
tmsg = self._catalog[(ctxt_msg_id, self.plural(num))]
if self._output_charset:
return tmsg.encode(self._output_charset)
return tmsg.encode(locale.getpreferredencoding())
except __HOLE__:
if self._fallback:
return self._fallback.lnpgettext(context, singular, plural, num)
if num == 1:
return singular
else:
return plural
|
KeyError
|
dataset/ETHPy150Open lad1337/XDM/site-packages/babel/support.py/NullTranslations.lnpgettext
|
3,947 |
def unpgettext(self, context, singular, plural, num):
"""Do a plural-forms lookup of a message id. `singular` is used as the
message id for purposes of lookup in the catalog, while `num` is used to
determine which plural form to use. The returned message string is a
Unicode string.
If the message id for `context` is not found in the catalog, and a
fallback is specified, the request is forwarded to the fallback's
``unpgettext()`` method. Otherwise, when `num` is 1 `singular` is
returned, and `plural` is returned in all other cases.
"""
ctxt_message_id = self.CONTEXT_ENCODING % (context, singular)
try:
tmsg = self._catalog[(ctxt_message_id, self.plural(num))]
except __HOLE__:
if self._fallback:
return self._fallback.unpgettext(context, singular, plural, num)
if num == 1:
tmsg = text_type(singular)
else:
tmsg = text_type(plural)
return tmsg
|
KeyError
|
dataset/ETHPy150Open lad1337/XDM/site-packages/babel/support.py/NullTranslations.unpgettext
|
3,948 |
def _get_helpers(self):
if not hasattr(settings, 'DAGUERRE_PREADJUSTMENTS'):
raise CommandError(NO_ADJUSTMENTS)
dp = settings.DAGUERRE_PREADJUSTMENTS
helpers = []
try:
for (model_or_iterable, adjustments, lookup) in dp:
if isinstance(model_or_iterable, six.string_types):
app_label, model_name = model_or_iterable.split('.')
model_or_iterable = get_model(app_label, model_name)
if (isinstance(model_or_iterable, six.class_types) and
issubclass(model_or_iterable, Model)):
iterable = model_or_iterable.objects.all()
elif isinstance(model_or_iterable, QuerySet):
iterable = model_or_iterable._clone()
else:
iterable = model_or_iterable
helper = AdjustmentHelper(iterable, lookup=lookup, generate=True)
for adjustment in adjustments:
helper.adjust(adjustment)
helper._finalize()
helpers.append(helper)
except (ValueError, __HOLE__, LookupError):
raise CommandError(BAD_STRUCTURE)
return helpers
|
TypeError
|
dataset/ETHPy150Open littleweaver/django-daguerre/daguerre/management/commands/_daguerre_preadjust.py/Command._get_helpers
|
3,949 |
def clone(self, cascade=None, overrides=None, user=None):
"""
Clone this instance and return the new, cloned instance.
``overrides`` should be a dictionary of override values for fields on
the cloned instance.
M2M or reverse FK relations listed in ``cascade`` iterable will be
cascade-cloned. By default, if not listed in ``cascade``, m2m/reverse
FKs will effectively be cleared (as the remote object will still be
pointing to the original instance, not the cloned one.)
If ``cascade`` is a dictionary, keys are m2m/reverse-FK accessor names,
and values are a callable that takes the queryset of all related
objects and returns those that should be cloned.
"""
if cascade is None:
cascade = {}
else:
try:
cascade.iteritems
except __HOLE__:
cascade = dict((i, lambda qs: qs) for i in cascade)
if overrides is None:
overrides = {}
overrides["created_on"] = utcnow()
overrides["created_by"] = user
overrides["modified_by"] = user
clone = self.__class__()
for field in self._meta.fields:
if field.primary_key:
continue
val = overrides.get(field.name, getattr(self, field.name))
setattr(clone, field.name, val)
clone.save(force_insert=True)
for name, filter_func in cascade.items():
mgr = getattr(self, name)
if mgr.__class__.__name__ == "ManyRelatedManager": # M2M
clone_mgr = getattr(clone, name)
existing = set(clone_mgr.all())
new = set(filter_func(mgr.all()))
clone_mgr.add(*new.difference(existing))
clone_mgr.remove(*existing.difference(new))
elif mgr.__class__.__name__ == "RelatedManager": # reverse FK
reverse_name = getattr(self.__class__, name).related.field.name
for obj in filter_func(mgr.all()):
obj.clone(overrides={reverse_name: clone})
else:
raise ValueError(
"Cannot cascade-clone '{0}'; "
"not a many-to-many or reverse foreignkey.".format(name))
return clone
|
AttributeError
|
dataset/ETHPy150Open mozilla/moztrap/moztrap/model/mtmodel.py/MTModel.clone
|
3,950 |
def add_to_query(self, query, alias, col, source, is_summary):
"""
Add the aggregate to the nominated query.
Expects col to be a tuple (which means this can only be used to count
related fields), and transforms it into a NotDeletedCountColumn.
"""
try:
table, field = col
except __HOLE__:
table, field = None, col
col = NotDeletedCountColumn(table, field)
return super(NotDeletedCount, self).add_to_query(
query, alias, col, source, is_summary)
|
ValueError
|
dataset/ETHPy150Open mozilla/moztrap/moztrap/model/mtmodel.py/NotDeletedCount.add_to_query
|
3,951 |
def highest_rated(count=0, site=None):
"""Get the most highly rated products"""
if site is None:
site = Site.objects.get_current()
site_id = site.id
try:
pks = cache_get("BESTRATED", site=site_id, count=count)
pks = [pk for pk in pks.split(',')]
log.debug('retrieved highest rated products from cache')
except NotCachedError, nce:
# here were are going to do just one lookup for all product comments
comments = Comment.objects.filter(content_type__app_label__exact='product',
content_type__model__exact='product',
site__id__exact=site_id,
productrating__rating__gt=0,
is_public__exact=True).order_by('object_pk')
# then make lists of ratings for each
commentdict = {}
for comment in comments:
if hasattr(comment, 'productrating'):
rating = comment.productrating.rating
if rating>0:
commentdict.setdefault(comment.object_pk, []).append(rating)
# now take the average of each, and make a nice list suitable for sorting
ratelist = [(average(ratings), int(pk)) for pk, ratings in commentdict.items()]
ratelist.sort()
#log.debug(ratelist)
# chop off the highest and reverse so highest is the first
ratelist = ratelist[-count:]
ratelist.reverse()
pks = ["%i" % p[1] for p in ratelist]
pkstring = ",".join(pks)
log.debug('calculated highest rated products, set to cache: %s', pkstring)
cache_set(nce.key, value=pkstring)
if pks:
pks = [pk for pk in pks if _int_or_long(pk)]
productdict = Product.objects.in_bulk(pks)
products = []
for pk in pks:
try:
if (int(pk)) in productdict:
key = int(pk)
elif long(pk) in productdict:
key = long(pk)
else:
continue
products.append(productdict[key])
except __HOLE__:
pass
else:
products = []
return products
|
ValueError
|
dataset/ETHPy150Open dokterbob/satchmo/satchmo/apps/satchmo_ext/productratings/queries.py/highest_rated
|
3,952 |
def _int_or_long(v):
try:
v = int(v)
except ValueError:
try:
v = long(v)
except __HOLE__:
return False
return True
|
ValueError
|
dataset/ETHPy150Open dokterbob/satchmo/satchmo/apps/satchmo_ext/productratings/queries.py/_int_or_long
|
3,953 |
def is_valid_ipv4(ip_str):
"""
Check the validity of an IPv4 address
"""
try:
socket.inet_pton(socket.AF_INET, ip_str)
except __HOLE__:
try: # Fall-back on legacy API or False
socket.inet_aton(ip_str)
except (AttributeError, socket.error):
return False
return ip_str.count('.') == 3
except socket.error:
return False
return True
|
AttributeError
|
dataset/ETHPy150Open un33k/django-ipware/ipware/utils.py/is_valid_ipv4
|
3,954 |
def _notify(updated_object, object_type, object_id):
semaphore = '%s-id-%s' % (object_type, object_id)
utility.notify(semaphore)
# TODO: Generalize the block of code with a TODO below here.
# if updated_object is not None and object_type in related_notifications:
# for field, entity in related_notifications[object_type].iteritems():
# if field in updated_object and updated_object[field] is not None:
# semaphore = '%s-id-%s' % (entity, updated_object[field])
# utility.notify(semaphore)
# TODO (wilk or rpedde): Use specific notifications for inheritance
if object_type not in ('attrs', 'facts', 'nodes'):
return
try:
node_id = updated_object['node_id']
node = None
except __HOLE__:
node_id = updated_object['id']
node = updated_object
if object_type != "attrs":
api = api_from_models()
# We're just going to notify every child when containers are updated
if node is None:
try:
node = api._model_get_by_id('nodes', node_id)
except (exceptions.IdNotFound):
return
if 'container' in node['facts'].get('backends', []):
children = utility.get_direct_children(node, api)
for child in children:
semaphore = 'nodes-id-%s' % child['id']
utility.notify(semaphore)
# Update transaction for node and children
id_list = utility.fully_expand_nodelist([node], api)
# TODO(shep): this needs to be better abstracted
# Need a codepath to update transaction for attr modifications
else:
# TODO(shep): this needs to be better abstracted
id_list = [node_id]
_update_transaction_id('nodes', id_list)
|
KeyError
|
dataset/ETHPy150Open rcbops/opencenter/opencenter/webapp/generic.py/_notify
|
3,955 |
@requires_auth()
def list(object_type):
s_obj = singularize(object_type)
api = api_from_models()
if flask.request.method == 'POST':
data = flask.request.json
try:
model_object = api._model_create(object_type, data)
except __HOLE__ as e:
# missing required field
return http_badrequest(msg=str(e))
_notify(model_object, object_type, model_object['id'])
href = flask.request.base_url + str(model_object['id'])
return http_response(201, '%s Created' % s_obj.capitalize(),
ref=href, **{s_obj: model_object})
elif flask.request.method == 'GET':
model_objects = api._model_get_all(object_type)
return http_response(200, 'success', **{object_type: model_objects})
else:
return http_notfound(msg='Unknown method %s' % flask.request.method)
|
KeyError
|
dataset/ETHPy150Open rcbops/opencenter/opencenter/webapp/generic.py/list
|
3,956 |
@classmethod
def setup_class(cls):
global MyBaseClass, MyClass
class MyBaseClass(object):
__sa_instrumentation_manager__ = \
instrumentation.InstrumentationManager
class MyClass(object):
# This proves that a staticmethod will work here; don't
# flatten this back to a class assignment!
def __sa_instrumentation_manager__(cls):
return MyTypesManager(cls)
__sa_instrumentation_manager__ = staticmethod(
__sa_instrumentation_manager__)
# This proves SA can handle a class with non-string dict keys
if not util.pypy and not util.jython:
locals()[42] = 99 # Don't remove this line!
def __init__(self, **kwargs):
for k in kwargs:
setattr(self, k, kwargs[k])
def __getattr__(self, key):
if is_instrumented(self, key):
return get_attribute(self, key)
else:
try:
return self._goofy_dict[key]
except __HOLE__:
raise AttributeError(key)
def __setattr__(self, key, value):
if is_instrumented(self, key):
set_attribute(self, key, value)
else:
self._goofy_dict[key] = value
def __hasattr__(self, key):
if is_instrumented(self, key):
return True
else:
return key in self._goofy_dict
def __delattr__(self, key):
if is_instrumented(self, key):
del_attribute(self, key)
else:
del self._goofy_dict[key]
|
KeyError
|
dataset/ETHPy150Open zzzeek/sqlalchemy/test/ext/test_extendedattr.py/UserDefinedExtensionTest.setup_class
|
3,957 |
def info(self, request):
self._flush()
resp = None
try:
resp = self._protocol.dapInfo(request)
except __HOLE__:
logging.error('request %s not supported', request)
return resp
|
KeyError
|
dataset/ETHPy150Open geky/pyDAPLink/pyDAPLink/daplink/core.py/DAPLinkCore.info
|
3,958 |
@classmethod
def setupClass(cls):
global np, sp, sparse, np_assert_equal
try:
import numpy as np
import scipy as sp
import scipy.sparse as sparse
np_assert_equal=np.testing.assert_equal
except __HOLE__:
raise SkipTest('SciPy sparse library not available.')
|
ImportError
|
dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/tests/test_convert_scipy.py/TestConvertNumpy.setupClass
|
3,959 |
def get_data(feature):
# The third column of the shapefile is the ward number
ward_id = feature.GetField(2)
# Get the correct ward data
try:
ward = ward_data[ward_id]
print 'Processing ward "%s"' % ward_id
except __HOLE__:
print 'No data for ward "%s"' % ward_id
return None
return {
'asian': int(ward['nhasian10']),
'black': int(ward['nhblack10']),
'hispanic': int(ward['hisp10']),
'white': int(ward['nhwhite10']),
}
# Ensure the output path exists
|
KeyError
|
dataset/ETHPy150Open newsapps/englewood/demo.py/get_data
|
3,960 |
def worker(inqueue, outqueue, initializer=None, initargs=()):
put = outqueue.put
get = inqueue.get
if hasattr(inqueue, '_writer'):
inqueue._writer.close()
outqueue._reader.close()
if initializer is not None:
initializer(*initargs)
while 1:
try:
task = get()
except (EOFError, __HOLE__):
debug('worker got EOFError or IOError -- exiting')
break
if task is None:
debug('worker got sentinel -- exiting')
break
job, i, func, args, kwds = task
try:
result = (True, func(*args, **kwds))
except Exception, e:
result = (False, e)
put((job, i, result))
#
# Class representing a process pool
#
|
IOError
|
dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/multiprocessing/pool.py/worker
|
3,961 |
def __init__(self, processes=None, initializer=None, initargs=()):
self._setup_queues()
self._taskqueue = Queue.Queue()
self._cache = {}
self._state = RUN
if processes is None:
try:
processes = cpu_count()
except __HOLE__:
processes = 1
self._pool = []
for i in range(processes):
w = self.Process(
target=worker,
args=(self._inqueue, self._outqueue, initializer, initargs)
)
self._pool.append(w)
w.name = w.name.replace('Process', 'PoolWorker')
w.daemon = True
w.start()
self._task_handler = threading.Thread(
target=Pool._handle_tasks,
args=(self._taskqueue, self._quick_put, self._outqueue, self._pool)
)
self._task_handler.daemon = True
self._task_handler._state = RUN
self._task_handler.start()
self._result_handler = threading.Thread(
target=Pool._handle_results,
args=(self._outqueue, self._quick_get, self._cache)
)
self._result_handler.daemon = True
self._result_handler._state = RUN
self._result_handler.start()
self._terminate = Finalize(
self, self._terminate_pool,
args=(self._taskqueue, self._inqueue, self._outqueue, self._pool,
self._task_handler, self._result_handler, self._cache),
exitpriority=15
)
|
NotImplementedError
|
dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/multiprocessing/pool.py/Pool.__init__
|
3,962 |
@staticmethod
def _handle_tasks(taskqueue, put, outqueue, pool):
thread = threading.current_thread()
for taskseq, set_length in iter(taskqueue.get, None):
i = -1
for i, task in enumerate(taskseq):
if thread._state:
debug('task handler found thread._state != RUN')
break
try:
put(task)
except __HOLE__:
debug('could not put task on queue')
break
else:
if set_length:
debug('doing set_length()')
set_length(i+1)
continue
break
else:
debug('task handler got sentinel')
try:
# tell result handler to finish when cache is empty
debug('task handler sending sentinel to result handler')
outqueue.put(None)
# tell workers there is no more work
debug('task handler sending sentinel to workers')
for p in pool:
put(None)
except IOError:
debug('task handler got IOError when sending sentinels')
debug('task handler exiting')
|
IOError
|
dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/multiprocessing/pool.py/Pool._handle_tasks
|
3,963 |
@staticmethod
def _handle_results(outqueue, get, cache):
thread = threading.current_thread()
while 1:
try:
task = get()
except (IOError, EOFError):
debug('result handler got EOFError/IOError -- exiting')
return
if thread._state:
assert thread._state == TERMINATE
debug('result handler found thread._state=TERMINATE')
break
if task is None:
debug('result handler got sentinel')
break
job, i, obj = task
try:
cache[job]._set(i, obj)
except KeyError:
pass
while cache and thread._state != TERMINATE:
try:
task = get()
except (IOError, EOFError):
debug('result handler got EOFError/IOError -- exiting')
return
if task is None:
debug('result handler ignoring extra sentinel')
continue
job, i, obj = task
try:
cache[job]._set(i, obj)
except KeyError:
pass
if hasattr(outqueue, '_reader'):
debug('ensuring that outqueue is not full')
# If we don't make room available in outqueue then
# attempts to add the sentinel (None) to outqueue may
# block. There is guaranteed to be no more than 2 sentinels.
try:
for i in range(10):
if not outqueue._reader.poll():
break
get()
except (__HOLE__, EOFError):
pass
debug('result handler exiting: len(cache)=%s, thread._state=%s',
len(cache), thread._state)
|
IOError
|
dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/multiprocessing/pool.py/Pool._handle_results
|
3,964 |
def next(self, timeout=None):
self._cond.acquire()
try:
try:
item = self._items.popleft()
except IndexError:
if self._index == self._length:
raise StopIteration
self._cond.wait(timeout)
try:
item = self._items.popleft()
except __HOLE__:
if self._index == self._length:
raise StopIteration
raise TimeoutError
finally:
self._cond.release()
success, value = item
if success:
return value
raise value
|
IndexError
|
dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/multiprocessing/pool.py/IMapIterator.next
|
3,965 |
def _prove(self, goal=None, assumptions=None, verbose=False):
"""
:param goal: Input expression to prove
:type goal: sem.Expression
:param assumptions: Input expressions to use as assumptions in the proof
:type assumptions: list(sem.Expression)
"""
if not assumptions:
assumptions = []
result = None
try:
clauses = []
if goal:
clauses.extend(clausify(-goal))
for a in assumptions:
clauses.extend(clausify(a))
result, clauses = self._attempt_proof(clauses)
if verbose:
print(ResolutionProverCommand._decorate_clauses(clauses))
except __HOLE__ as e:
if self._assume_false and str(e).startswith('maximum recursion depth exceeded'):
result = False
clauses = []
else:
if verbose:
print(e)
else:
raise e
return (result, clauses)
|
RuntimeError
|
dataset/ETHPy150Open nltk/nltk/nltk/inference/resolution.py/ResolutionProver._prove
|
3,966 |
def __setitem__(self, variable, binding):
"""
A binding is consistent with the dict if its variable is not already bound, OR if its
variable is already bound to its argument.
:param variable: ``Variable`` The variable to bind
:param binding: ``Expression`` The atomic to which 'variable' should be bound
:raise BindingException: If the variable cannot be bound in this dictionary
"""
assert isinstance(variable, Variable)
assert isinstance(binding, Expression)
try:
existing = self[variable]
except KeyError:
existing = None
if not existing or binding == existing:
self.d[variable] = binding
elif isinstance(binding, IndividualVariableExpression):
# Since variable is already bound, try to bind binding to variable
try:
existing = self[binding.variable]
except __HOLE__:
existing = None
binding2 = VariableExpression(variable)
if not existing or binding2 == existing:
self.d[binding.variable] = binding2
else:
raise BindingException('Variable %s already bound to another '
'value' % (variable))
else:
raise BindingException('Variable %s already bound to another '
'value' % (variable))
|
KeyError
|
dataset/ETHPy150Open nltk/nltk/nltk/inference/resolution.py/BindingDict.__setitem__
|
3,967 |
def __getitem__(self, variable):
"""
Return the expression to which 'variable' is bound
"""
assert isinstance(variable, Variable)
intermediate = self.d[variable]
while intermediate:
try:
intermediate = self.d[intermediate]
except __HOLE__:
return intermediate
|
KeyError
|
dataset/ETHPy150Open nltk/nltk/nltk/inference/resolution.py/BindingDict.__getitem__
|
3,968 |
def _on_update_progress(self, task, event_type, details):
"""Should be called when task updates its progress."""
try:
progress = details.pop('progress')
except __HOLE__:
pass
else:
try:
self._storage.set_task_progress(task.name, progress,
details=details)
except Exception:
# Update progress callbacks should never fail, so capture and
# log the emitted exception instead of raising it.
LOG.exception("Failed setting task progress for %s to %0.3f",
task, progress)
|
KeyError
|
dataset/ETHPy150Open openstack/taskflow/taskflow/engines/action_engine/actions/task.py/TaskAction._on_update_progress
|
3,969 |
def __get__(self, obj, tp):
result = self._resolve()
setattr(obj, self.name, result) # Invokes __set__.
try:
# This is a bit ugly, but it avoids running this again by
# removing this descriptor.
delattr(obj.__class__, self.name)
except __HOLE__:
pass
return result
|
AttributeError
|
dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/_internal/six/__init__.py/_LazyDescr.__get__
|
3,970 |
def __get_module(self, fullname):
try:
return self.known_modules[fullname]
except __HOLE__:
raise ImportError("This loader does not know module " + fullname)
|
KeyError
|
dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/_internal/six/__init__.py/_SixMetaPathImporter.__get_module
|
3,971 |
def load_module(self, fullname):
try:
# in case of a reload
return sys.modules[fullname]
except __HOLE__:
pass
mod = self.__get_module(fullname)
if isinstance(mod, MovedModule):
mod = mod._resolve()
else:
mod.__loader__ = self
sys.modules[fullname] = mod
return mod
|
KeyError
|
dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/_internal/six/__init__.py/_SixMetaPathImporter.load_module
|
3,972 |
def remove_move(name):
"""Remove item from six.moves."""
try:
delattr(_MovedItems, name)
except AttributeError:
try:
del moves.__dict__[name]
except __HOLE__:
raise AttributeError("no such move, %r" % (name,))
|
KeyError
|
dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/_internal/six/__init__.py/remove_move
|
3,973 |
def get_http_wrapper(library=None, features=[]):
# If we are asked for a specific library, return it.
if library is not None:
try:
return _http_connectors[library]
except KeyError:
raise RuntimeError('%s transport is not available' % (library,))
# If we haven't been asked for a specific feature either, then just return our favourite
# implementation.
if not features:
return _http_connectors.get('httplib2', _http_connectors['urllib2'])
# If we are asked for a connector which supports the given features, then we will
# try that.
current_candidates = _http_connectors.keys()
new_candidates = []
for feature in features:
for candidate in current_candidates:
if candidate in _http_facilities.get(feature, []):
new_candidates.append(candidate)
current_candidates = new_candidates
new_candidates = []
# Return the first candidate in the list.
try:
candidate_name = current_candidates[0]
except __HOLE__:
raise RuntimeError("no transport available which supports these features: %s" % (features,))
else:
return _http_connectors[candidate_name]
|
IndexError
|
dataset/ETHPy150Open uwdata/termite-visualizations/web2py/gluon/contrib/pysimplesoap/transport.py/get_http_wrapper
|
3,974 |
def on_dependent_job_finished(self, job):
with self.lock:
try:
self.deps.remove(job)
except __HOLE__:
ui.debug(ui.red, "Job not in the deps list!", self.deps, job)
pass
|
ValueError
|
dataset/ETHPy150Open aldebaran/qibuild/python/qibuild/parallel_builder.py/BuildJob.on_dependent_job_finished
|
3,975 |
def __call__(self, *args):
try:
return self.cache[args]
except __HOLE__:
self.cache[args] = self.func(*args)
return self.cache[args]
|
KeyError
|
dataset/ETHPy150Open Fluxx/trappist/tests/test_trappist.py/fixture.__call__
|
3,976 |
def run_only_if_beanstalkc_is_available(func):
try:
import beanstalkc
except __HOLE__:
beanstalkc = None
pred = lambda: beanstalkc is not None
return run_only(func, pred)
|
ImportError
|
dataset/ETHPy150Open BrightcoveOS/Diamond/src/collectors/beanstalkd/test/testbeanstalkd.py/run_only_if_beanstalkc_is_available
|
3,977 |
def _dict_path(d, *steps):
"""Traverses throuth a dict of dicts.
Returns always a list. If the object to return is not a list,
it's encapsulated in one.
If any of the path steps does not exist, an empty list is returned.
"""
x = d
for key in steps:
try:
x = x[key]
except __HOLE__:
return []
if not isinstance(x, list):
x = [x]
return x
|
KeyError
|
dataset/ETHPy150Open machinalis/iepy/iepy/preprocess/stanford_preprocess.py/_dict_path
|
3,978 |
@classmethod
def setupClass(cls):
global pyparsing
try:
import pyparsing
except __HOLE__:
try:
import matplotlib.pyparsing as pyparsing
except:
raise SkipTest('gml test: pyparsing not available.')
|
ImportError
|
dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/readwrite/tests/test_gml.py/TestGraph.setupClass
|
3,979 |
def greenify():
"""Patch threading and psycopg2 modules for green threads."""
# don't greenify twice.
if _GREEN:
return
_GREEN[True] = True
from gevent.monkey import patch_all, saved
if ('threading' in sys.modules) and ('threading' not in saved):
import warnings
warnings.warn('threading module loaded before patching!')
patch_all()
try:
# Use psycopg2 by default
import psycopg2
del psycopg2
except __HOLE__:
# Fallback to psycopg2cffi if required (eg: pypy)
from psycopg2cffi import compat
compat.register()
from psycogreen.gevent import patch_psycopg
patch_psycopg()
|
ImportError
|
dataset/ETHPy150Open django-ddp/django-ddp/dddp/__init__.py/greenify
|
3,980 |
def __getattr__(self, name):
"""Create missing attributes using default factories."""
try:
factory = THREAD_LOCAL_FACTORIES[name]
except __HOLE__:
raise AttributeError(name)
return self.get(name, factory)
|
KeyError
|
dataset/ETHPy150Open django-ddp/django-ddp/dddp/__init__.py/ThreadLocal.__getattr__
|
3,981 |
def load(branchname):
data = json.load(open(os.path.expanduser(config.SAVE_FILE)))
repo_name = get_repo_name()
try:
return data['%s:%s' % (repo_name, branchname)]
except __HOLE__:
# possibly one of the old ones
return data[branchname]
|
KeyError
|
dataset/ETHPy150Open peterbe/bgg/bgg/lib/rebase.py/load
|
3,982 |
def test_is_before_failure(self):
try:
d2 = datetime.datetime.today()
assert_that(d2).is_before(self.d1)
fail('should have raised error')
except __HOLE__ as ex:
assert_that(str(ex)).matches('Expected <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}> to be before <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}>, but was not.')
|
AssertionError
|
dataset/ETHPy150Open ActivisionGameScience/assertpy/tests/test_datetime.py/TestDate.test_is_before_failure
|
3,983 |
def test_is_before_bad_val_type_failure(self):
try:
assert_that(123).is_before(123)
fail('should have raised error')
except __HOLE__ as ex:
assert_that(str(ex)).is_equal_to('val must be datetime, but was type <int>')
|
TypeError
|
dataset/ETHPy150Open ActivisionGameScience/assertpy/tests/test_datetime.py/TestDate.test_is_before_bad_val_type_failure
|
3,984 |
def test_is_before_bad_arg_type_failure(self):
try:
assert_that(self.d1).is_before(123)
fail('should have raised error')
except __HOLE__ as ex:
assert_that(str(ex)).is_equal_to('given arg must be datetime, but was type <int>')
|
TypeError
|
dataset/ETHPy150Open ActivisionGameScience/assertpy/tests/test_datetime.py/TestDate.test_is_before_bad_arg_type_failure
|
3,985 |
def test_is_after_failure(self):
try:
d2 = datetime.datetime.today()
assert_that(self.d1).is_after(d2)
fail('should have raised error')
except __HOLE__ as ex:
assert_that(str(ex)).matches('Expected <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}> to be after <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}>, but was not.')
|
AssertionError
|
dataset/ETHPy150Open ActivisionGameScience/assertpy/tests/test_datetime.py/TestDate.test_is_after_failure
|
3,986 |
def test_is_after_bad_val_type_failure(self):
try:
assert_that(123).is_after(123)
fail('should have raised error')
except __HOLE__ as ex:
assert_that(str(ex)).is_equal_to('val must be datetime, but was type <int>')
|
TypeError
|
dataset/ETHPy150Open ActivisionGameScience/assertpy/tests/test_datetime.py/TestDate.test_is_after_bad_val_type_failure
|
3,987 |
def test_is_after_bad_arg_type_failure(self):
try:
assert_that(self.d1).is_after(123)
fail('should have raised error')
except __HOLE__ as ex:
assert_that(str(ex)).is_equal_to('given arg must be datetime, but was type <int>')
|
TypeError
|
dataset/ETHPy150Open ActivisionGameScience/assertpy/tests/test_datetime.py/TestDate.test_is_after_bad_arg_type_failure
|
3,988 |
def test_is_equal_to_ignoring_milliseconds_failure(self):
try:
d2 = datetime.datetime.today() + datetime.timedelta(days=1)
assert_that(self.d1).is_equal_to_ignoring_milliseconds(d2)
fail('should have raised error')
except __HOLE__ as ex:
assert_that(str(ex)).matches('Expected <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}> to be equal to <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}>, but was not.')
|
AssertionError
|
dataset/ETHPy150Open ActivisionGameScience/assertpy/tests/test_datetime.py/TestDate.test_is_equal_to_ignoring_milliseconds_failure
|
3,989 |
def test_is_equal_to_ignoring_milliseconds_bad_val_type_failure(self):
try:
assert_that(123).is_equal_to_ignoring_milliseconds(123)
fail('should have raised error')
except __HOLE__ as ex:
assert_that(str(ex)).is_equal_to('val must be datetime, but was type <int>')
|
TypeError
|
dataset/ETHPy150Open ActivisionGameScience/assertpy/tests/test_datetime.py/TestDate.test_is_equal_to_ignoring_milliseconds_bad_val_type_failure
|
3,990 |
def test_is_equal_to_ignoring_milliseconds_bad_arg_type_failure(self):
try:
assert_that(self.d1).is_equal_to_ignoring_milliseconds(123)
fail('should have raised error')
except __HOLE__ as ex:
assert_that(str(ex)).is_equal_to('given arg must be datetime, but was type <int>')
|
TypeError
|
dataset/ETHPy150Open ActivisionGameScience/assertpy/tests/test_datetime.py/TestDate.test_is_equal_to_ignoring_milliseconds_bad_arg_type_failure
|
3,991 |
def test_is_equal_to_ignoring_seconds_failure(self):
try:
d2 = datetime.datetime.today() + datetime.timedelta(days=1)
assert_that(self.d1).is_equal_to_ignoring_seconds(d2)
fail('should have raised error')
except __HOLE__ as ex:
assert_that(str(ex)).matches('Expected <\d{4}-\d{2}-\d{2} \d{2}:\d{2}> to be equal to <\d{4}-\d{2}-\d{2} \d{2}:\d{2}>, but was not.')
|
AssertionError
|
dataset/ETHPy150Open ActivisionGameScience/assertpy/tests/test_datetime.py/TestDate.test_is_equal_to_ignoring_seconds_failure
|
3,992 |
def test_is_equal_to_ignoring_seconds_bad_val_type_failure(self):
try:
assert_that(123).is_equal_to_ignoring_seconds(123)
fail('should have raised error')
except __HOLE__ as ex:
assert_that(str(ex)).is_equal_to('val must be datetime, but was type <int>')
|
TypeError
|
dataset/ETHPy150Open ActivisionGameScience/assertpy/tests/test_datetime.py/TestDate.test_is_equal_to_ignoring_seconds_bad_val_type_failure
|
3,993 |
def test_is_equal_to_ignoring_seconds_bad_arg_type_failure(self):
try:
assert_that(self.d1).is_equal_to_ignoring_seconds(123)
fail('should have raised error')
except __HOLE__ as ex:
assert_that(str(ex)).is_equal_to('given arg must be datetime, but was type <int>')
|
TypeError
|
dataset/ETHPy150Open ActivisionGameScience/assertpy/tests/test_datetime.py/TestDate.test_is_equal_to_ignoring_seconds_bad_arg_type_failure
|
3,994 |
def test_is_equal_to_ignoring_time_failure(self):
try:
d2 = datetime.datetime.today() + datetime.timedelta(days=1)
assert_that(self.d1).is_equal_to_ignoring_time(d2)
fail('should have raised error')
except __HOLE__ as ex:
assert_that(str(ex)).matches('Expected <\d{4}-\d{2}-\d{2}> to be equal to <\d{4}-\d{2}-\d{2}>, but was not.')
|
AssertionError
|
dataset/ETHPy150Open ActivisionGameScience/assertpy/tests/test_datetime.py/TestDate.test_is_equal_to_ignoring_time_failure
|
3,995 |
def test_is_equal_to_ignoring_time_bad_val_type_failure(self):
try:
assert_that(123).is_equal_to_ignoring_time(123)
fail('should have raised error')
except __HOLE__ as ex:
assert_that(str(ex)).is_equal_to('val must be datetime, but was type <int>')
|
TypeError
|
dataset/ETHPy150Open ActivisionGameScience/assertpy/tests/test_datetime.py/TestDate.test_is_equal_to_ignoring_time_bad_val_type_failure
|
3,996 |
def test_is_equal_to_ignoring_time_bad_arg_type_failure(self):
try:
assert_that(self.d1).is_equal_to_ignoring_time(123)
fail('should have raised error')
except __HOLE__ as ex:
assert_that(str(ex)).is_equal_to('given arg must be datetime, but was type <int>')
|
TypeError
|
dataset/ETHPy150Open ActivisionGameScience/assertpy/tests/test_datetime.py/TestDate.test_is_equal_to_ignoring_time_bad_arg_type_failure
|
3,997 |
def test_is_greater_than_failure(self):
try:
d2 = datetime.datetime.today()
assert_that(self.d1).is_greater_than(d2)
fail('should have raised error')
except __HOLE__ as ex:
assert_that(str(ex)).matches('Expected <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}> to be greater than <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}>, but was not.')
|
AssertionError
|
dataset/ETHPy150Open ActivisionGameScience/assertpy/tests/test_datetime.py/TestDate.test_is_greater_than_failure
|
3,998 |
def test_is_greater_than_bad_arg_type_failure(self):
try:
assert_that(self.d1).is_greater_than(123)
fail('should have raised error')
except __HOLE__ as ex:
assert_that(str(ex)).is_equal_to('given arg must be <datetime>, but was <int>')
|
TypeError
|
dataset/ETHPy150Open ActivisionGameScience/assertpy/tests/test_datetime.py/TestDate.test_is_greater_than_bad_arg_type_failure
|
3,999 |
def test_is_greater_than_or_equal_to_failure(self):
try:
d2 = datetime.datetime.today()
assert_that(self.d1).is_greater_than_or_equal_to(d2)
fail('should have raised error')
except __HOLE__ as ex:
assert_that(str(ex)).matches('Expected <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}> to be greater than or equal to <\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}>, but was not.')
|
AssertionError
|
dataset/ETHPy150Open ActivisionGameScience/assertpy/tests/test_datetime.py/TestDate.test_is_greater_than_or_equal_to_failure
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.