Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
900 | def loads(self, request, data):
# Short circuit if we've been given an empty set of data
if not data:
return
# Determine what version of the serializer the data was serialized
# with
try:
ver, data = data.split(b",", 1)
except __HOLE__:
... | ValueError | dataset/ETHPy150Open ionrock/cachecontrol/cachecontrol/serialize.py/Serializer.loads |
901 | def prepare_response(self, request, cached):
"""Verify our vary headers match and construct a real urllib3
HTTPResponse object.
"""
# Special case the '*' Vary value as it means we cannot actually
# determine if the cached response is suitable for this request.
if "*" in ... | TypeError | dataset/ETHPy150Open ionrock/cachecontrol/cachecontrol/serialize.py/Serializer.prepare_response |
902 | def _loads_v1(self, request, data):
try:
cached = pickle.loads(data)
except __HOLE__:
return
return self.prepare_response(request, cached) | ValueError | dataset/ETHPy150Open ionrock/cachecontrol/cachecontrol/serialize.py/Serializer._loads_v1 |
903 | def _loads_v2(self, request, data):
try:
cached = json.loads(zlib.decompress(data).decode("utf8"))
except __HOLE__:
return
# We need to decode the items that we've base64 encoded
cached["response"]["body"] = _b64_decode_bytes(
cached["response"]["body... | ValueError | dataset/ETHPy150Open ionrock/cachecontrol/cachecontrol/serialize.py/Serializer._loads_v2 |
904 | def weekly_artists(xml):
soup = BeautifulStoneSoup(xml)
# Check this is the right thing
try:
assert soup.find("weeklyartistchart"), "weekly_artists did not get a Weekly Artist Chart"
except __HOLE__:
print >> sys.stderr, xml
raise AssertionError("weekly_artists did not get a Weekly Artist Chart")
# Get t... | AssertionError | dataset/ETHPy150Open andrewgodwin/lastgraph/lastgui/xml.py/weekly_artists |
905 | @property
def username(self):
try:
return self._thread_local.user
except __HOLE__:
return DEFAULT_USER.get() | AttributeError | dataset/ETHPy150Open cloudera/hue/desktop/libs/hadoop/src/hadoop/yarn/history_server_api.py/HistoryServerApi.username |
906 | def __init__(self, name, filename=None, lognode=None):
self.prefix = name
self.log = None
if filename is not None:
self.log = open("concoord_log_"+name, 'w')
if lognode is not None:
logaddr,logport = lognode.split(':')
try:
self.log = s... | IOError | dataset/ETHPy150Open denizalti/concoord/concoord/utils.py/Logger.__init__ |
907 | def _resize_image(self, filename, size):
"""Resizes the image to specified width, height and force option
- filename: full path of image to resize
- size: dictionary containing:
- width: new width
- height: new height
- force: if True, imag... | IOError | dataset/ETHPy150Open cidadania/ecidadania-ng/src/apps/spaces/fields.py/StdImageField._resize_image |
908 | def test_badpath_notfound(webapp):
try:
url = "%s/../../../../../../etc/passwd" % webapp.server.http.base
urlopen(url)
except __HOLE__ as e:
assert e.code == 404
else:
assert False | HTTPError | dataset/ETHPy150Open circuits/circuits/tests/web/test_security.py/test_badpath_notfound |
909 | def compatible_staticpath(path):
'''
Try to return a path to static the static files compatible all
the way back to Django 1.2. If anyone has a cleaner or better
way to do this let me know!
'''
try:
# >= 1.4
from django.templatetags.static import static
return static(pat... | AttributeError | dataset/ETHPy150Open timmyomahony/django-pagedown/pagedown/utils.py/compatible_staticpath |
910 | def ensure_connected(f):
"""Tries to connect to the player
It *should* be successful if the player is alive
"""
def wrapper(*args, **kwargs):
self = args[0]
try:
self.iface.GetMetadata()
except (dbus.exceptions.DBusException, __HOLE__)... | AttributeError | dataset/ETHPy150Open qtile/qtile/libqtile/widget/mpriswidget.py/Mpris.ensure_connected |
911 | def _execute(self, transforms, *args, **kwargs):
try:
extra = kwargs['extra']
proto_name = kwargs['protocol']
proto_init = kwargs['protocol_init']
session_id = kwargs['session_id']
logging.debug('Incoming session %s(%s) Session ID: %s Extra: %s' % (
... | ValueError | dataset/ETHPy150Open mrjoes/tornadio/tornadio/router.py/SocketRouterBase._execute |
912 | def __init__(self, stream=None):
if stream is None:
stream = sys.stdout
try:
if stream.isatty():
curses.setupterm()
self.terminal_capable = True
except __HOLE__:
pass | AttributeError | dataset/ETHPy150Open google/grr/grr/tools/run_tests.py/Colorizer.__init__ |
913 | def complete(self, text, state):
"""
Complete
"""
response = None
if state == 0:
origline = readline.get_line_buffer()
begin = readline.get_begidx()
end = readline.get_endidx()
being_completed = origline[begin:end]
words... | IndexError | dataset/ETHPy150Open DTVD/rainbowstream/rainbowstream/interactive.py/RainbowCompleter.complete |
914 | def parse_authorization_header(value):
"""Parse an HTTP basic/digest authorization header transmitted by the web
browser. The return value is either `None` if the header was invalid or
not given, otherwise an :class:`Authorization` object.
:param value: the authorization header to parse.
:return: ... | ValueError | dataset/ETHPy150Open IanLewis/kay/kay/lib/werkzeug/http.py/parse_authorization_header |
915 | def parse_www_authenticate_header(value, on_update=None):
"""Parse an HTTP WWW-Authenticate header into a :class:`WWWAuthenticate`
object.
:param value: a WWW-Authenticate header to parse.
:param on_update: an optional callable that is called every time a
value on the :class:`WWWA... | ValueError | dataset/ETHPy150Open IanLewis/kay/kay/lib/werkzeug/http.py/parse_www_authenticate_header |
916 | def parse_date(value):
"""Parse one of the following date formats into a datetime object:
.. sourcecode:: text
Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
Sun Nov 6 08:49:37 1994 ; ANSI C's asctime... | ValueError | dataset/ETHPy150Open IanLewis/kay/kay/lib/werkzeug/http.py/parse_date |
917 | def load_clib(self):
from ctypes import cdll, util
try:
clib = cdll.LoadLibrary(util.find_library('c'))
except __HOLE__ as e:
if 'image not found' in e.message:
clib = cdll.LoadLibrary('libc.dylib') # The mac edge case
else:
rai... | OSError | dataset/ETHPy150Open ooici/pyon/pyon/util/test/test_async.py/TestThreads.load_clib |
918 | def find_all_episodes(self, options):
premium = False
if options.username and options.password:
premium = self._login(options.username, options.password)
if isinstance(premium, Exception):
log.error(premium.message)
return None
jsondata = ... | TypeError | dataset/ETHPy150Open spaam/svtplay-dl/lib/svtplay_dl/service/tv4play.py/Tv4play.find_all_episodes |
919 | def findvid(url, data):
parse = urlparse(url)
if "tv4play.se" in url:
try:
vid = parse_qs(parse.query)["video_id"][0]
except __HOLE__:
return None
else:
match = re.search(r"\"vid\":\"(\d+)\",", data)
if match:
vid = match.group(1)
e... | KeyError | dataset/ETHPy150Open spaam/svtplay-dl/lib/svtplay_dl/service/tv4play.py/findvid |
920 | def run(self, *args, **kwargs):
compile_dir = settings_get('compileDir')
source_file = self.view.file_name()
source_dir = os.path.normcase(os.path.dirname(source_file))
try:
project_file = self.view.window().project_file_name()
except __HOLE__:
project_fil... | AttributeError | dataset/ETHPy150Open billymoon/Stylus/Stylus.py/StyluscompileCommand.run |
921 | def get_executable():
name = get_var('vial_python_executable', 'default')
try:
return get_var('vial_python_executables', {})[name]
except __HOLE__:
pass
path = get_virtualenvwrapper_executable(name)
if path:
return path
if name == 'default':
return sys.executab... | KeyError | dataset/ETHPy150Open baverman/vial-python/vial-plugin/python/env.py/get_executable |
922 | def get():
executable = get_executable()
try:
env = environments[executable]
except __HOLE__:
logfile = join(tempfile.gettempdir(), 'supp.log')
env = environments[executable] = Environment(executable,
get_var('vial_python_executable_env', {}), logfile)
return env | KeyError | dataset/ETHPy150Open baverman/vial-python/vial-plugin/python/env.py/get |
923 | def in_home(*path):
try:
from win32com.shell import shellcon, shell
except __HOLE__:
home = os.path.expanduser("~")
else:
home = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0)
return os.path.join(home, *path) | ImportError | dataset/ETHPy150Open iancmcc/ouimeaux/ouimeaux/config.py/in_home |
924 | @defer.inlineCallbacks
def _downloadMicrodescriptorBlock(self, block, v2dirs):
descs = set()
for d in block:
try:
tmp = b64encode(d.decode('hex')).rstrip('=')
descs.add(tmp)
except __HOLE__:
msg = "Malformed descriptor {}. Disca... | TypeError | dataset/ETHPy150Open nskinkel/oppy/oppy/netstatus/microdescriptormanager.py/MicrodescriptorManager._downloadMicrodescriptorBlock |
925 | def _processMicrodescriptorBlockResult(self, result, requested):
try:
micro_descs = _decompressAndSplitResult(result)
except __HOLE__:
return requested
processed = {}
for m in micro_descs:
hashed = b64encode(sha256(m).digest()).rstrip('=')
... | ValueError | dataset/ETHPy150Open nskinkel/oppy/oppy/netstatus/microdescriptormanager.py/MicrodescriptorManager._processMicrodescriptorBlockResult |
926 | @cacheit
def _inverse_cdf_expression(self):
""" Inverse of the CDF
Used by sample
"""
x, z = symbols('x, z', real=True, positive=True, cls=Dummy)
# Invert CDF
try:
inverse_cdf = list(solveset(self.cdf(x) - z, x))
except __HOLE__:
inver... | NotImplementedError | dataset/ETHPy150Open sympy/sympy/sympy/stats/drv.py/SingleDiscreteDistribution._inverse_cdf_expression |
927 | def shared(value, name=None, strict=False, allow_downcast=None, **kwargs):
"""Return a SharedVariable Variable, initialized with a copy or
reference of `value`.
This function iterates over constructor functions to find a
suitable SharedVariable subclass. The suitable one is the first
constructor t... | TypeError | dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/compile/sharedvalue.py/shared |
928 | def test_load_save_incomplete(self):
self.wk.data = json.loads(wheel_json)
del self.wk.data['signers']
self.wk.data['schema'] = self.wk.SCHEMA+1
self.wk.save()
try:
self.wk.load()
except __HOLE__:
pass
else:
raise Exception("Exp... | ValueError | dataset/ETHPy150Open chalasr/Flask-P2P/venv/lib/python2.7/site-packages/wheel/test/test_keys.py/TestWheelKeys.test_load_save_incomplete |
929 | def _read_to_buffer(self):
"""Reads from the socket and appends the result to the read buffer.
Returns the number of bytes read. Returns 0 if there is nothing
to read (i.e. the read returns EWOULDBLOCK or equivalent). On
error closes the socket and raises an exception.
"""
... | IOError | dataset/ETHPy150Open RobotWebTools/rosbridge_suite/rosbridge_server/src/tornado/iostream.py/BaseIOStream._read_to_buffer |
930 | def _handle_write(self):
while self._write_buffer:
try:
if not self._write_buffer_frozen:
# On windows, socket.send blows up if given a
# write buffer that's too large, instead of just
# returning the number of bytes it was ... | IOError | dataset/ETHPy150Open RobotWebTools/rosbridge_suite/rosbridge_server/src/tornado/iostream.py/BaseIOStream._handle_write |
931 | def _do_ssl_handshake(self):
# Based on code from test_ssl.py in the python stdlib
try:
self._handshake_reading = False
self._handshake_writing = False
self.socket.do_handshake()
except ssl.SSLError as err:
if err.args[0] == ssl.SSL_ERROR_WANT_READ... | AttributeError | dataset/ETHPy150Open RobotWebTools/rosbridge_suite/rosbridge_server/src/tornado/iostream.py/SSLIOStream._do_ssl_handshake |
932 | def read_from_fd(self):
try:
chunk = os.read(self.fd, self.read_chunk_size)
except (IOError, __HOLE__) as e:
if errno_from_exception(e) in _ERRNO_WOULDBLOCK:
return None
elif errno_from_exception(e) == errno.EBADF:
# If the writing half... | OSError | dataset/ETHPy150Open RobotWebTools/rosbridge_suite/rosbridge_server/src/tornado/iostream.py/PipeIOStream.read_from_fd |
933 | def serialize_cache_file(cache_file_path):
"""
Given a cache file, open it and determine whether it's something we can
upload. If it is, serialize it to JSON, then return the serialized JSON.
:param str cache_file_path: The full path to a cache file to read and
potentially serialize.
:rtype... | OSError | dataset/ETHPy150Open gtaylor/EVE-Market-Data-Uploader/emdu/cachefile_serializer.py/serialize_cache_file |
934 | def _repr_svg_(self):
"""SVG representation of a GeometryEntity suitable for IPython"""
from sympy.core.evalf import N
try:
bounds = self.bounds
except (NotImplementedError, TypeError):
# if we have no SVG representation, return None so IPython
# wil... | TypeError | dataset/ETHPy150Open sympy/sympy/sympy/geometry/entity.py/GeometryEntity._repr_svg_ |
935 | def __cmp__(self, other):
"""Comparison of two GeometryEntities."""
n1 = self.__class__.__name__
n2 = other.__class__.__name__
c = (n1 > n2) - (n1 < n2)
if not c:
return 0
i1 = -1
for cls in self.__class__.__mro__:
try:
i1 ... | ValueError | dataset/ETHPy150Open sympy/sympy/sympy/geometry/entity.py/GeometryEntity.__cmp__ |
936 | def _intersect(self, o):
""" Returns a sympy.sets.Set of intersection objects,
if possible. """
from sympy.sets import Set, FiniteSet, Union
from sympy.geometry import Point
try:
inter = self.intersection(o)
except __HOLE__:
# sympy.sets.Set.redu... | NotImplementedError | dataset/ETHPy150Open sympy/sympy/sympy/geometry/entity.py/GeometrySet._intersect |
937 | def parse_message(self, payload, conn_id):
if len(payload) < FRAME_FORMAT_MESSAGE_SIZE:
raise SnakeMQBrokenMessage("message")
try:
ident = self._ident_by_conn[conn_id]
except __HOLE__:
raise SnakeMQNoIdent(conn_id)
muuid, ttl, flags = struct.unpack(F... | KeyError | dataset/ETHPy150Open dsiroky/snakemq/snakemq/messaging.py/Messaging.parse_message |
938 | def _on_packet_sent(self, conn_id, packet_id):
try:
msg_uuid = self._message_by_packet[packet_id]
except __HOLE__:
return
ident = self._ident_by_conn[conn_id]
self.on_message_sent(conn_id, ident, msg_uuid)
#####################################################... | KeyError | dataset/ETHPy150Open dsiroky/snakemq/snakemq/messaging.py/Messaging._on_packet_sent |
939 | def delt(self, *args, **kargs):
"""delt(host|net, gw|dev)"""
self.invalidate_cache()
route = self.make_route(*args,**kargs)
try:
i=self.routes.index(route)
del(self.routes[i])
except __HOLE__:
warning("no matching route found") | ValueError | dataset/ETHPy150Open phaethon/scapy/scapy/route.py/Route.delt |
940 | def start_api_and_rpc_workers(neutron_api):
pool = eventlet.GreenPool()
api_thread = pool.spawn(neutron_api.wait)
try:
neutron_rpc = service.serve_rpc()
except __HOLE__:
LOG.info(_LI("RPC was already started in parent process by "
"plugin."))
else:
rpc_... | NotImplementedError | dataset/ETHPy150Open openstack/neutron/neutron/server/wsgi_eventlet.py/start_api_and_rpc_workers |
941 | def generic_decode_credentials(self, credentials, provider_data, target):
# convenience function for simple creds (rhev-m and vmware currently)
doc = libxml2.parseDoc(credentials)
self.username = None
_usernodes = doc.xpathEval("//provider_credentials/%s_credentials/username" % (target)... | KeyError | dataset/ETHPy150Open redhat-imaging/imagefactory/imagefactory_plugins/RHEVM/RHEVM.py/RHEVM.generic_decode_credentials |
942 | def get_dynamic_provider_data(self, provider):
# Get provider details for RHEV-M or VSphere
# First try to interpret this as an ad-hoc/dynamic provider def
# If this fails, try to find it in one or the other of the config files
# If this all fails return None
# We use this in the... | ValueError | dataset/ETHPy150Open redhat-imaging/imagefactory/imagefactory_plugins/RHEVM/RHEVM.py/RHEVM.get_dynamic_provider_data |
943 | def commit(self, message, author, parents=None, branch=None, date=None,
**kwargs):
"""
Performs in-memory commit (doesn't check workdir in any way) and
returns newly created ``Changeset``. Updates repository's
``revisions``.
:param message: message of the commit
... | KeyError | dataset/ETHPy150Open codeinn/vcs/vcs/backends/git/inmemory.py/GitInMemoryChangeset.commit |
944 | def _is_file_obj(topic):
try:
return isinstance(topic, types.FileType)
except __HOLE__: # pragma: no cover
# FIXME: add comment...
# what is this for?
return isinstance(topic, io.IOBase)
#----------------------------------------------------------------------------------... | AttributeError | dataset/ETHPy150Open heynemann/preggy/preggy/assertions/types/file.py/_is_file_obj |
945 | @assertion
def not_to_be_a_file(topic):
'''Asserts that `topic` is NOT a file.
If `topic` is a string, this asserts that `os.path.isfile()`
returns `False`.
Otherwise, this asserts whether `topic` is NOT an instance of the
built-in `file` type.
'''
try:
to_be_a_file(topic)
exc... | AssertionError | dataset/ETHPy150Open heynemann/preggy/preggy/assertions/types/file.py/not_to_be_a_file |
946 | def warmup(request):
"""
Provides default procedure for handling warmup requests on App
Engine. Just add this view to your main urls.py.
"""
for app in settings.INSTALLED_APPS:
for name in ('urls', 'views', 'models'):
try:
import_module('%s.%s' % (app, nam... | ImportError | dataset/ETHPy150Open potatolondon/djangae/djangae/views.py/warmup |
947 | def init_plugins(plugindir, plugins_to_load=None):
if plugindir and not os.path.isdir(plugindir):
raise InvalidPluginDir(plugindir)
if not plugindir:
plugindir = DIR("plugins")
logger.debug("plugindir: {0}".format(plugindir))
if os.path.isdir(plugindir):
pluginfiles = glob(os.... | OSError | dataset/ETHPy150Open llimllib/limbo/limbo/limbo.py/init_plugins |
948 | def handle_bot_message(event, server):
try:
bot = server.slack.server.bots[event["bot_id"]]
except __HOLE__:
logger.debug("bot_message event {0} has no bot".format(event))
return
return "\n".join(run_hook(server.hooks, "bot_message", event, server)) | KeyError | dataset/ETHPy150Open llimllib/limbo/limbo/limbo.py/handle_bot_message |
949 | def handle_message(event, server):
subtype = event.get("subtype", "")
if subtype == "message_changed":
return
if subtype == "bot_message":
return handle_bot_message(event, server)
try:
msguser = server.slack.server.users[event["user"]]
except __HOLE__:
logger.debug(... | KeyError | dataset/ETHPy150Open llimllib/limbo/limbo/limbo.py/handle_message |
950 | def loop(server, test_loop=None):
"""Run the main loop
server is a limbo Server object
test_loop, if present, is a number of times to run the loop
"""
try:
loops_without_activity = 0
while test_loop is None or test_loop > 0:
start = time.time()
loops_without_... | KeyboardInterrupt | dataset/ETHPy150Open llimllib/limbo/limbo/limbo.py/loop |
951 | def init_server(args, config, Server=LimboServer, Client=SlackClient):
init_log(config)
logger.debug("config: {0}".format(config))
db = init_db(args.database_name)
config_plugins = config.get("plugins")
plugins_to_load = config_plugins.split(",") if config_plugins else []
hooks = init_plugins(... | KeyError | dataset/ETHPy150Open llimllib/limbo/limbo/limbo.py/init_server |
952 | def repl(server, args):
try:
while 1:
cmd = decode(input("limbo> "))
if cmd.lower() == "quit" or cmd.lower() == "exit":
return
print(run_cmd(cmd, server, args.hook, args.pluginpath, None))
except (EOFError, __HOLE__):
print()
pass | KeyboardInterrupt | dataset/ETHPy150Open llimllib/limbo/limbo/limbo.py/repl |
953 | def get_required_setting(setting, value_re, invalid_msg):
"""
Return a constant from ``django.conf.settings``. The `setting`
argument is the constant name, the `value_re` argument is a regular
expression used to validate the setting value and the `invalid_msg`
argument is used as exception message ... | AttributeError | dataset/ETHPy150Open jcassee/django-analytical/analytical/utils.py/get_required_setting |
954 | def get_user_from_context(context):
"""
Get the user instance from the template context, if possible.
If the context does not contain a `request` or `user` attribute,
`None` is returned.
"""
try:
return context['user']
except KeyError:
pass
try:
request = context... | AttributeError | dataset/ETHPy150Open jcassee/django-analytical/analytical/utils.py/get_user_from_context |
955 | def get_identity(context, prefix=None, identity_func=None, user=None):
"""
Get the identity of a logged in user from a template context.
The `prefix` argument is used to provide different identities to
different analytics services. The `identity_func` argument is a
function that returns the identi... | KeyError | dataset/ETHPy150Open jcassee/django-analytical/analytical/utils.py/get_identity |
956 | def is_internal_ip(context, prefix=None):
"""
Return whether the visitor is coming from an internal IP address,
based on information from the template context.
The prefix is used to allow different analytics services to have
different notions of internal addresses.
"""
try:
request ... | KeyError | dataset/ETHPy150Open jcassee/django-analytical/analytical/utils.py/is_internal_ip |
957 | def currentSpeed(self, i3s_output_list, i3s_config):
# parse some configuration parameters
if not isinstance(self.interfaces, list):
self.interfaces = self.interfaces.split(',')
if not isinstance(self.interfaces_blacklist, list):
self.interfaces_blacklist = self.interface... | TypeError | dataset/ETHPy150Open ultrabug/py3status/py3status/modules/net_rate.py/Py3status.currentSpeed |
958 | def _get_stat(self):
"""
Get statistics from devfile in list of lists of words
"""
def dev_filter(x):
# get first word and remove trailing interface number
x = x.strip().split(" ")[0][:-1]
if x in self.interfaces_blacklist:
return Fals... | StopIteration | dataset/ETHPy150Open ultrabug/py3status/py3status/modules/net_rate.py/Py3status._get_stat |
959 | def add(self, *args, **kwargs):
try:
return self[0].new(*args, **kwargs)
except __HOLE__:
o = self._obj()
o._h = self._h
return o.new(*args, **kwargs) | IndexError | dataset/ETHPy150Open kennethreitz-archive/python-github3/github3/structures.py/KeyedListResource.add |
960 | def create_connection(self):
attempts = 0
while True:
attempts += 1
try:
self.connection = Connection('127.0.0.1', 'guest', 'guest')
break
except amqpstorm.AMQPError as why:
LOGGER.exception(why)
if self.... | KeyboardInterrupt | dataset/ETHPy150Open eandersson/amqpstorm/examples/robust_consumer.py/Consumer.create_connection |
961 | def start(self):
if not self.connection:
self.create_connection()
while True:
try:
channel = self.connection.channel()
channel.queue.declare('simple_queue')
channel.basic.consume(self, 'simple_queue', no_ack=False)
c... | KeyboardInterrupt | dataset/ETHPy150Open eandersson/amqpstorm/examples/robust_consumer.py/Consumer.start |
962 | def setup_form_view(view, request, form, *args, **kwargs):
"""Mimic as_view and with forms to skip some of the context"""
view.request = request
try:
view.request.user = request.user
except __HOLE__:
view.request.user = UserFactory()
view.args = args
view.kwargs = kwargs
view... | AttributeError | dataset/ETHPy150Open CenterForOpenScience/osf.io/admin_tests/utilities.py/setup_form_view |
963 | def setup_log_view(view, request, *args, **kwargs):
view.request = request
try:
view.request.user = request.user
except __HOLE__:
view.request.user = UserFactory()
view.args = args
view.kwargs = kwargs
return view | AttributeError | dataset/ETHPy150Open CenterForOpenScience/osf.io/admin_tests/utilities.py/setup_log_view |
964 | def mkdir(path):
""" Creates a dir with the given path.
Args:
path: A str, the name of the dir to create.
Returns:
True on success, False otherwise.
"""
try:
os.mkdir(path)
except __HOLE__:
logging.error("OSError while creating dir '{0}'".format(path))
return False
return True | OSError | dataset/ETHPy150Open AppScale/appscale/AppDB/backup/backup_recovery_helper.py/mkdir |
965 | def makedirs(path):
""" Creates a dir with the given path and all directories in between.
Args:
path: A str, the name of the dir to create.
Returns:
True on success, False otherwise.
"""
try:
os.makedirs(path)
except __HOLE__:
logging.error("OSError while creating dir '{0}'".format(path))
... | OSError | dataset/ETHPy150Open AppScale/appscale/AppDB/backup/backup_recovery_helper.py/makedirs |
966 | def rename(source, destination):
""" Renames source file into destination.
Args:
source: A str, the path of the file to rename.
destination: A str, the destination path.
Returns:
True on success, False otherwise.
"""
try:
os.rename(source, destination)
except __HOLE__:
logging.error("OS... | OSError | dataset/ETHPy150Open AppScale/appscale/AppDB/backup/backup_recovery_helper.py/rename |
967 | def remove(path):
""" Deletes the given file from the filesystem.
Args:
path: A str, the path of the file to delete.
Returns:
True on success, False otherwise.
"""
try:
os.remove(path)
except __HOLE__:
logging.error("OSError while deleting '{0}'".
format(path))
return False
retu... | OSError | dataset/ETHPy150Open AppScale/appscale/AppDB/backup/backup_recovery_helper.py/remove |
968 | def handle(self):
with self._lock:
self.worker.nb_connections +=1
self.worker.refresh_name()
try:
while not self.connected:
data = self.sock.recv(1024)
if not data:
break
self.buf.append(data)
... | KeyboardInterrupt | dataset/ETHPy150Open benoitc/tproxy/tproxy/client.py/ClientConnection.handle |
969 | def send_data(self, sock, data):
if hasattr(data, 'read'):
try:
data.seek(0)
except (__HOLE__, IOError):
pass
while True:
chunk = data.readline()
if not chunk:
break
... | ValueError | dataset/ETHPy150Open benoitc/tproxy/tproxy/client.py/ClientConnection.send_data |
970 | def test_create_file(self):
"""
Test the creation of a simple XlsxWriter file with an autofilter.
This test is the base comparison. It has data but no autofilter.
"""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
# Open a text file ... | ValueError | dataset/ETHPy150Open jmcnamara/XlsxWriter/xlsxwriter/test/comparison/test_autofilter00.py/TestCompareXLSXFiles.test_create_file |
971 | def test_screen(self):
widget = self.create()
self.assertEqual(widget['screen'], '')
try:
display = os.environ['DISPLAY']
except __HOLE__:
self.skipTest('No $DISPLAY set.')
self.checkInvalidParam(widget, 'screen', display,
errmsg="can't mod... | KeyError | dataset/ETHPy150Open francelabs/datafari/windows/python/Lib/lib-tk/test/test_tkinter/test_widgets.py/ToplevelTest.test_screen |
972 | def __iter__(self):
queryset = self.queryset
db = queryset.db
compiler = queryset.query.get_compiler(using=db)
# Execute the query. This will also fill compiler.select, klass_info,
# and annotations.
results = compiler.execute_sql()
select, klass_info, annotation_... | KeyError | dataset/ETHPy150Open django/django/django/db/models/query.py/ModelIterable.__iter__ |
973 | def aggregate(self, *args, **kwargs):
"""
Returns a dictionary containing the calculations (aggregation)
over the current queryset
If args is present the expression is passed as a kwarg using
the Aggregate object's default alias.
"""
if self.query.distinct_fields... | AttributeError | dataset/ETHPy150Open django/django/django/db/models/query.py/QuerySet.aggregate |
974 | def annotate(self, *args, **kwargs):
"""
Return a query set in which the returned objects have been annotated
with extra data or aggregations.
"""
annotations = OrderedDict() # To preserve ordering of args
for arg in args:
# The default_alias property may rai... | AttributeError | dataset/ETHPy150Open django/django/django/db/models/query.py/QuerySet.annotate |
975 | @property
def columns(self):
"""
A list of model field names in the order they'll appear in the
query results.
"""
if not hasattr(self, '_columns'):
self._columns = self.query.get_columns()
# Adjust any column names which don't match field names
... | ValueError | dataset/ETHPy150Open django/django/django/db/models/query.py/RawQuerySet.columns |
976 | def prefetch_related_objects(model_instances, *related_lookups):
"""
Populate prefetched object caches for a list of model instances based on
the lookups/Prefetch instances given.
"""
if len(model_instances) == 0:
return # nothing to do
related_lookups = normalize_prefetch_lookups(rela... | TypeError | dataset/ETHPy150Open django/django/django/db/models/query.py/prefetch_related_objects |
977 | def prefetch_one_level(instances, prefetcher, lookup, level):
"""
Helper function for prefetch_related_objects
Runs prefetches on all instances using the prefetcher object,
assigning results to relevant caches in instance.
The prefetched objects are returned, along with any additional
prefetch... | AttributeError | dataset/ETHPy150Open django/django/django/db/models/query.py/prefetch_one_level |
978 | def test_multiple_instance_error(self):
try:
self.AppClass()
except __HOLE__:
pass
except Exception as e:
raise e
else:
raise AssertionError("Test failed") | RuntimeError | dataset/ETHPy150Open amol-mandhane/htmlPy/tests/base_gui_basics.py/BaseGUIBasics.test_multiple_instance_error |
979 | def delete(self, *args, **kwargs):
permission_name = self.permission_name
super(Queue, self).delete(*args, **kwargs)
# once the Queue is safely deleted, remove the permission (if exists)
if permission_name:
try:
p = Permission.objects.get(codename=permission_... | ObjectDoesNotExist | dataset/ETHPy150Open rossp/django-helpdesk/helpdesk/models.py/Queue.delete |
980 | def _set_settings(self, data):
# data should always be a Python dictionary.
try:
import pickle
except __HOLE__:
import cPickle as pickle
from helpdesk.lib import b64encode
self.settings_pickled = b64encode(pickle.dumps(data)) | ImportError | dataset/ETHPy150Open rossp/django-helpdesk/helpdesk/models.py/UserSettings._set_settings |
981 | def _get_settings(self):
# return a python dictionary representing the pickled data.
try:
import pickle
except __HOLE__:
import cPickle as pickle
from helpdesk.lib import b64decode
try:
return pickle.loads(b64decode(str(self.settings_pickled)))... | ImportError | dataset/ETHPy150Open rossp/django-helpdesk/helpdesk/models.py/UserSettings._get_settings |
982 | def _get_form(response, formname, formid, formnumber, formxpath):
"""Find the form element """
root = create_root_node(response.text, lxml.html.HTMLParser,
base_url=get_base_url(response))
forms = root.xpath('//form')
if not forms:
raise ValueError("No <form> element ... | IndexError | dataset/ETHPy150Open scrapy/scrapy/scrapy/http/request/form.py/_get_form |
983 | def _get_inputs(form, formdata, dont_click, clickdata, response):
try:
formdata = dict(formdata or ())
except (ValueError, __HOLE__):
raise ValueError('formdata should be a dict or iterable of tuples')
inputs = form.xpath('descendant::textarea'
'|descendant::select'
... | TypeError | dataset/ETHPy150Open scrapy/scrapy/scrapy/http/request/form.py/_get_inputs |
984 | def _get_clickable(clickdata, form):
"""
Returns the clickable element specified in clickdata,
if the latter is given. If not, it returns the first
clickable element found
"""
clickables = [
el for el in form.xpath(
'descendant::*[(self::input or self::button)'
' ... | IndexError | dataset/ETHPy150Open scrapy/scrapy/scrapy/http/request/form.py/_get_clickable |
985 | @classmethod
def string_to_date_with_xls_validation(cls, date_str):
date_obj = datetime.strptime(date_str, '%Y-%m-%d').date()
try:
SharedDate().datetime_to_julian(date_obj)
except __HOLE__:
return date_str
else:
return date_obj | ValueError | dataset/ETHPy150Open kobotoolbox/kobocat/onadata/libs/utils/export_tools.py/ExportBuilder.string_to_date_with_xls_validation |
986 | @classmethod
def convert_type(cls, value, data_type):
"""
Convert data to its native type e.g. string '1' to int 1
@param value: the string value to convert
@param data_type: the native data type to convert to
@return: the converted value
"""
func = ExportBuil... | ValueError | dataset/ETHPy150Open kobotoolbox/kobocat/onadata/libs/utils/export_tools.py/ExportBuilder.convert_type |
987 | def _get_server_from_metadata(xform, meta, token):
report_templates = MetaData.external_export(xform)
if meta:
try:
int(meta)
except __HOLE__:
raise Exception(u"Invalid metadata pk {0}".format(meta))
# Get the external server from the metadata
result = r... | ValueError | dataset/ETHPy150Open kobotoolbox/kobocat/onadata/libs/utils/export_tools.py/_get_server_from_metadata |
988 | def tearDown(self):
try:
utils.destroy_test_repository()
utils.destroy_test_project()
except __HOLE__: # not exists
pass
utils.remove_test_user() | OSError | dataset/ETHPy150Open koshinuke/koshinuke.py/tests/core_test.py/CreateTestCase.tearDown |
989 | def _set_log_level_and_params(self, base_log_level, func):
"""Wrap `func` to temporarily set this plugin's logger level to
`base_log_level` + config options (and restore it to its previous
value after the function returns). Also determines which params may not
be sent for backwards-compa... | TypeError | dataset/ETHPy150Open beetbox/beets/beets/plugins.py/BeetsPlugin._set_log_level_and_params |
990 | def load_plugins(names=()):
"""Imports the modules for a sequence of plugin names. Each name
must be the name of a Python module under the "beetsplug" namespace
package in sys.path; the module indicated should contain the
BeetsPlugin subclasses desired.
"""
for name in names:
bname = nam... | ImportError | dataset/ETHPy150Open beetbox/beets/beets/plugins.py/load_plugins |
991 | def test_unary_ops(self):
unary_ops = [str, repr, len, bool, not_]
try:
unary_ops.append(unicode)
except __HOLE__:
pass # unicode no longer exists in Python 3.
for op in unary_ops:
self.assertEqual(
op(self.lazy),
op(s... | NameError | dataset/ETHPy150Open awslabs/lambda-apigateway-twilio-tutorial/pytz/tests/test_lazy.py/LazyListTestCase.test_unary_ops |
992 | def test_binary_ops(self):
binary_ops = [eq, ge, gt, le, lt, ne, add, concat]
try:
binary_ops.append(cmp)
except __HOLE__:
pass # cmp no longer exists in Python 3.
for op in binary_ops:
self.assertEqual(
op(self.lazy, self.lazy),
... | NameError | dataset/ETHPy150Open awslabs/lambda-apigateway-twilio-tutorial/pytz/tests/test_lazy.py/LazyListTestCase.test_binary_ops |
993 | def test_callable(self):
try:
callable
except __HOLE__:
return # No longer exists with Python 3.
self.assertFalse(callable(self.lazy)) | NameError | dataset/ETHPy150Open awslabs/lambda-apigateway-twilio-tutorial/pytz/tests/test_lazy.py/LazyListTestCase.test_callable |
994 | def test_unary_ops(self):
# These ops just need to work.
unary_ops = [str, repr]
try:
unary_ops.append(unicode)
except __HOLE__:
pass # unicode no longer exists in Python 3.
for op in unary_ops:
op(self.lazy) # These ops just need to work.
... | NameError | dataset/ETHPy150Open awslabs/lambda-apigateway-twilio-tutorial/pytz/tests/test_lazy.py/LazySetTestCase.test_unary_ops |
995 | def test_binary_ops(self):
binary_ops = [eq, ge, gt, le, lt, ne, sub, and_, or_, xor]
try:
binary_ops.append(cmp)
except __HOLE__:
pass # cmp no longer exists in Python 3.
for op in binary_ops:
self.assertEqual(
op(self.lazy, self.laz... | NameError | dataset/ETHPy150Open awslabs/lambda-apigateway-twilio-tutorial/pytz/tests/test_lazy.py/LazySetTestCase.test_binary_ops |
996 | def test_iops(self):
try:
iops = [isub, iand, ior, ixor]
except __HOLE__:
return # Don't exist in older Python versions.
for op in iops:
# Mutating operators, so make fresh copies.
lazy = LazySet(self.base)
base = self.base.copy()
... | NameError | dataset/ETHPy150Open awslabs/lambda-apigateway-twilio-tutorial/pytz/tests/test_lazy.py/LazySetTestCase.test_iops |
997 | def test_callable(self):
try:
callable
except __HOLE__:
return # No longer exists with Python 3.
self.assertFalse(callable(self.lazy)) | NameError | dataset/ETHPy150Open awslabs/lambda-apigateway-twilio-tutorial/pytz/tests/test_lazy.py/LazySetTestCase.test_callable |
998 | def makeImportedModule(name, pathname, desc, scope):
""" Returns a ModuleProxy that has access to a closure w/
information about the module to load, but is otherwise
empty. On an attempted access of any member of the module,
the module is loaded.
"""
def _loadModule():
""" ... | AttributeError | dataset/ETHPy150Open sassoftware/conary/conary/lib/importer.py/makeImportedModule |
999 | def find_module(self, fullname, path=None):
origName = fullname
if not path:
mod = sys.modules.get(fullname, False)
if mod is None or mod and isinstance(mod, types.ModuleType):
return mod
frame = sys._getframe(1)
global_scope = frame.f_globals
... | ImportError | dataset/ETHPy150Open sassoftware/conary/conary/lib/importer.py/OnDemandImporter.find_module |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.