Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
4,200 | def interact(self):
self.output.write('\n')
while True:
try:
request = self.getline('help> ')
if not request: break
except (__HOLE__, EOFError):
break
request = strip(replace(request, '"', '', "'", ''))
... | KeyboardInterrupt | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/pydoc.py/Helper.interact |
4,201 | def showtopic(self, topic):
try:
import pydoc_topics
except __HOLE__:
self.output.write('''
Sorry, topic and keyword documentation is not available because the
module "pydoc_topics" could not be found.
''')
return
target = self.topics.get(topic, self.... | ImportError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/pydoc.py/Helper.showtopic |
4,202 | def apropos(key):
"""Print all the one-line module summaries that contain a substring."""
def callback(path, modname, desc):
if modname[-9:] == '.__init__':
modname = modname[:-9] + ' (package)'
print modname, desc and '- ' + desc
try: import warnings
except __HOLE__: ... | ImportError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/pydoc.py/apropos |
4,203 | def serve(port, callback=None, completer=None):
import BaseHTTPServer, mimetools, select
# Patch up mimetools.Message so it doesn't break if rfc822 is reloaded.
class Message(mimetools.Message):
def __init__(self, fp, seekable=1):
Message = self.__class__
Message.__ba... | IOError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/pydoc.py/serve |
4,204 | def gui():
"""Graphical interface (starts web server and pops up a control window)."""
class GUI:
def __init__(self, window, port=7464):
self.window = window
self.server = None
self.scanner = None
import Tkinter
self.server_frm = Tkin... | ImportError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/pydoc.py/gui |
4,205 | def cli():
"""Command-line interface (looks at sys.argv to decide what to do)."""
import getopt
class BadUsage: pass
# Scripts don't get the current directory in their path by default.
scriptdir = os.path.dirname(sys.argv[0])
if scriptdir in sys.path:
sys.path.remove(scriptdir)
... | ValueError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/pydoc.py/cli |
4,206 | def testQueryShouldBehaveLikeDict(self):
try:
self.query['zap']
self.fail()
except __HOLE__:
pass
self.query['zap'] = 'x'
self.assert_(self.query['zap'] == 'x') | KeyError | dataset/ETHPy150Open kuri65536/python-for-android/python-build/python-libs/gdata/tests/gdata_tests/service_test.py/QueryTest.testQueryShouldBehaveLikeDict |
4,207 | def __eq__(self, other):
""" Compare the JID to another instance or to string for equality. """
try: other=JID(other)
except __HOLE__: return 0
return self.resource==other.resource and self.__str__(0) == other.__str__(0) | ValueError | dataset/ETHPy150Open CouchPotato/CouchPotatoServer/libs/xmpp/protocol.py/JID.__eq__ |
4,208 | def setRequired(self,req=1):
""" Change the state of the 'required' flag. """
if req: self.setTag('required')
else:
try: self.delChild('required')
except __HOLE__: return | ValueError | dataset/ETHPy150Open CouchPotato/CouchPotatoServer/libs/xmpp/protocol.py/DataField.setRequired |
4,209 | def get_by_name(self, region, container_name, list_objects=False):
"""Get a container by its name.
As two containers with the same name can exist in two
different regions we need to limit the search to one region.
:param container_name: Name of the container to retrieve
:raises ... | AttributeError | dataset/ETHPy150Open runabove/python-runabove/runabove/storage.py/ContainerManager.get_by_name |
4,210 | def _swift_call(self, region, action, *args, **kwargs):
"""Wrap calls to swiftclient to allow retry."""
try:
region_name = region.name
except __HOLE__:
region_name = region
retries = 0
while retries < 3:
if region_name not in self.swifts:
... | AttributeError | dataset/ETHPy150Open runabove/python-runabove/runabove/storage.py/ContainerManager._swift_call |
4,211 | def delete(self, region, container):
"""Delete a container.
:param region: Region where the container will be deleted
:param container: Container to delete
"""
try:
container_name = container.name
except __HOLE__:
container_name = container
... | AttributeError | dataset/ETHPy150Open runabove/python-runabove/runabove/storage.py/ContainerManager.delete |
4,212 | def set_public(self, region, container, public=True):
"""Set a container publicly available.
:param region: Region where the container is
:param container: Container to make public
:param public: Set container private if False
"""
try:
container_name = contai... | AttributeError | dataset/ETHPy150Open runabove/python-runabove/runabove/storage.py/ContainerManager.set_public |
4,213 | def get_region_url(self, region):
"""Get the URL endpoint for storage in a region.
:param region: Region to get the endpoint for
"""
try:
region_name = region.name
except __HOLE__:
region_name = region
try:
return self.swifts[region_na... | AttributeError | dataset/ETHPy150Open runabove/python-runabove/runabove/storage.py/ContainerManager.get_region_url |
4,214 | def copy_object(self, region, from_container, stored_object,
to_container=None, new_object_name=None):
"""Server copy an object from a container to another one.
Containers must be in the same region. Both containers may be
the same. Meta-data is read and copied from the orig... | AttributeError | dataset/ETHPy150Open runabove/python-runabove/runabove/storage.py/ContainerManager.copy_object |
4,215 | def get_object_by_name(self, object_name, download=False):
"""Get an object stored by its name.
Does not download the content of the object by default.
:param object_name: Name of the object to create
:param download: If True download also the object content
"""
if downl... | KeyError | dataset/ETHPy150Open runabove/python-runabove/runabove/storage.py/Container.get_object_by_name |
4,216 | def delete_object(self, object_stored):
"""Delete an object from a container.
:param object_stored: the object to delete
"""
try:
object_name = object_stored.name
except __HOLE__:
object_name = object_stored
self._manager._swift_call(self.region,
... | AttributeError | dataset/ETHPy150Open runabove/python-runabove/runabove/storage.py/Container.delete_object |
4,217 | def execute(self, args=None):
self.logger.debug('Running ' + self.file)
try:
start = time.time()
proc = subprocess.Popen([self.plugin_path + '/' + self.file],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)... | OSError | dataset/ETHPy150Open tiwilliam/syscollect/syscollect/plugin.py/Plugin.execute |
4,218 | def ip_address(x):
try:
x = x.decode('ascii')
except __HOLE__:
pass
return _ip_address(x) | AttributeError | dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/application/healthcheck.py/ip_address |
4,219 | def drop_privileges(user, group):
"""Drop privileges to specified user and group"""
if group is not None:
import grp
gid = grp.getgrnam(group).gr_gid
logger.debug("Dropping privileges to group {0}/{1}".format(group, gid))
try:
os.setresgid(gid, gid, gid)
excep... | AttributeError | dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/application/healthcheck.py/drop_privileges |
4,220 | def categories(collection=None, collections=None, reverse=None, order_by=None,
_pod=None, use_cache=False):
if isinstance(collection, collection_lib.Collection):
collection = collection
elif isinstance(collection, basestring):
collection = _pod.get_collection(collection)
else:... | ValueError | dataset/ETHPy150Open grow/grow/grow/pods/tags.py/categories |
4,221 | def handle(self, *args, **options):
self.stdout.write("Processing products...\n")
products = set()
total = StockState.objects.count()
failed = []
for i, ss in enumerate(StockState.objects.all()):
if i % 500 == 0:
self.stdout.write('done {}/{}'.format(... | AssertionError | dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/commtrack/management/commands/check_product_migration.py/Command.handle |
4,222 | def add_action(self, action, sub_menu='Advanced'):
"""
Adds an action to the editor's context menu.
:param action: QAction to add to the context menu.
:param sub_menu: The name of a sub menu where to put the action.
'Advanced' by default. If None or empty, the action will be... | KeyError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/api/code_edit.py/CodeEdit.add_action |
4,223 | def add_separator(self, sub_menu='Advanced'):
"""
Adds a sepqrator to the editor's context menu.
:return: The sepator that has been added.
:rtype: QtWidgets.QAction
"""
action = QtWidgets.QAction(self)
action.setSeparator(True)
if sub_menu:
tr... | KeyError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/api/code_edit.py/CodeEdit.add_separator |
4,224 | def remove_action(self, action, sub_menu='Advanced'):
"""
Removes an action/separator from the editor's context menu.
:param action: Action/seprator to remove.
:param advanced: True to remove the action from the advanced submenu.
"""
if sub_menu:
try:
... | KeyError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/api/code_edit.py/CodeEdit.remove_action |
4,225 | def setReadOnly(self, read_only):
if read_only != self.isReadOnly():
super().setReadOnly(read_only)
from pyqode.core.panels import ReadOnlyPanel
try:
panel = self.panels.get(ReadOnlyPanel)
except __HOLE__:
self.panels.append(
... | KeyError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/api/code_edit.py/CodeEdit.setReadOnly |
4,226 | def _reset_stylesheet(self):
""" Resets stylesheet"""
self.setFont(QtGui.QFont(self._font_family,
self._font_size + self._zoom_level))
flg_stylesheet = hasattr(self, '_flg_stylesheet')
if QtWidgets.QApplication.instance().styleSheet() or flg_stylesheet:
... | KeyError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/api/code_edit.py/CodeEdit._reset_stylesheet |
4,227 | def compile_messages():
# check if gettext is installed
try:
pipe = subprocess.Popen(['msgfmt', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except __HOLE__ as e:
raise CommandError('Unable to run msgfmt (gettext) command. You probably don\'t have gettext installed. {}'.form... | OSError | dataset/ETHPy150Open divio/django-cms/cms/tests/test_po.py/compile_messages |
4,228 | def copyfile(src, dest, symlink=True):
if not os.path.exists(src):
# Some bad symlink in the src
logger.warn('Cannot find file %s (bad symlink)', src)
return
if os.path.exists(dest):
logger.debug('File %s already exists', dest)
return
if not os.path.exists(os.path.dir... | OSError | dataset/ETHPy150Open femmerling/EmeraldBox/virtualenv.py/copyfile |
4,229 | def file_search_dirs():
here = os.path.dirname(os.path.abspath(__file__))
dirs = ['.', here,
join(here, 'virtualenv_support')]
if os.path.splitext(os.path.dirname(__file__))[0] != 'virtualenv':
# Probably some boot script; just in case virtualenv is installed...
try:
... | ImportError | dataset/ETHPy150Open femmerling/EmeraldBox/virtualenv.py/file_search_dirs |
4,230 | def call_subprocess(cmd, show_stdout=True,
filter_stdout=None, cwd=None,
raise_on_returncode=True, extra_env=None,
remove_from_env=None):
cmd_parts = []
for part in cmd:
if len(part) > 45:
part = part[:20]+"..."+part[-20:]
i... | UnicodeDecodeError | dataset/ETHPy150Open femmerling/EmeraldBox/virtualenv.py/call_subprocess |
4,231 | def path_locations(home_dir):
"""Return the path locations for the environment (where libraries are,
where scripts go, etc)"""
# XXX: We'd use distutils.sysconfig.get_python_inc/lib but its
# prefix arg is broken: http://bugs.python.org/issue3386
if is_win:
# Windows has lots of problems wit... | ImportError | dataset/ETHPy150Open femmerling/EmeraldBox/virtualenv.py/path_locations |
4,232 | def copy_required_modules(dst_prefix):
import imp
# If we are running under -p, we need to remove the current
# directory from sys.path temporarily here, so that we
# definitely get the modules from the site directory of
# the interpreter we are running under, not the one
# virtualenv.py is inst... | ImportError | dataset/ETHPy150Open femmerling/EmeraldBox/virtualenv.py/copy_required_modules |
4,233 | def install_python(home_dir, lib_dir, inc_dir, bin_dir, site_packages, clear):
"""Install just the base environment, no distutils patches etc"""
if sys.executable.startswith(bin_dir):
print('Please use the *system* python to run this script')
return
if clear:
rmtree(lib_dir)
... | OSError | dataset/ETHPy150Open femmerling/EmeraldBox/virtualenv.py/install_python |
4,234 | def fix_local_scheme(home_dir):
"""
Platforms that use the "posix_local" install scheme (like Ubuntu with
Python 2.7) need to be given an additional "local" location, sigh.
"""
try:
import sysconfig
except __HOLE__:
pass
else:
if sysconfig._get_default_scheme() == 'po... | ImportError | dataset/ETHPy150Open femmerling/EmeraldBox/virtualenv.py/fix_local_scheme |
4,235 | def fixup_scripts(home_dir):
# This is what we expect at the top of scripts:
shebang = '#!%s/bin/python' % os.path.normcase(os.path.abspath(home_dir))
# This is what we'll put:
new_shebang = '#!/usr/bin/env python%s' % sys.version[:3]
if is_win:
bin_suffix = 'Scripts'
else:
bin_s... | UnicodeDecodeError | dataset/ETHPy150Open femmerling/EmeraldBox/virtualenv.py/fixup_scripts |
4,236 | def __get__(self, obj, cls=None):
try:
e = SaunterWebDriver.find_element_by_locator(self.locator)
return int(e.text)
except __HOLE__ as e:
if str(e) == "'SeleniumWrapper' object has no attribute 'connection'":
pass
else:
rai... | AttributeError | dataset/ETHPy150Open Element-34/py.saunter/saunter/po/webdriver/number.py/Number.__get__ |
4,237 | def process(self, client_secret, raw_response, x_hub_signature):
if not self._verify_signature(client_secret, raw_response, x_hub_signature):
raise SubscriptionVerifyError("X-Hub-Signature and hmac digest did not match")
try:
response = simplejson.loads(raw_response)
exc... | ValueError | dataset/ETHPy150Open facebookarchive/python-instagram/instagram/subscriptions.py/SubscriptionsReactor.process |
4,238 | 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 alecthomas/importmagic/importmagic/six.py/remove_move |
4,239 | def culaCheckStatus(status):
"""
Raise an exception corresponding to the specified CULA status
code.
Parameters
----------
status : int
CULA status code.
"""
if status != 0:
error = culaGetErrorInfo()
try:
raise culaExceptions[status](error)
... | KeyError | dataset/ETHPy150Open lebedov/scikit-cuda/skcuda/cula.py/culaCheckStatus |
4,240 | def test_mutatingiteration(self):
d = {}
d[1] = 1
try:
for i in d:
d[i+1] = 1
except __HOLE__:
pass
else:
self.fail("changing dict size during iteration doesn't raise Error") | RuntimeError | dataset/ETHPy150Open babble/babble/include/jython/Lib/test/test_dict.py/DictTest.test_mutatingiteration |
4,241 | def test_missing(self):
# Make sure dict doesn't have a __missing__ method
self.assertEqual(hasattr(dict, "__missing__"), False)
self.assertEqual(hasattr({}, "__missing__"), False)
# Test several cases:
# (D) subclass defines __missing__ method returning a value
# (E) sub... | RuntimeError | dataset/ETHPy150Open babble/babble/include/jython/Lib/test/test_dict.py/DictTest.test_missing |
4,242 | def test_tuple_keyerror(self):
# SF #1576657
d = {}
try:
d[(1,)]
except __HOLE__, e:
self.assertEqual(e.args, ((1,),))
else:
self.fail("missing KeyError") | KeyError | dataset/ETHPy150Open babble/babble/include/jython/Lib/test/test_dict.py/DictTest.test_tuple_keyerror |
4,243 | def main():
global REQUIRED, IGNORED
if len(sys.argv) < 2:
print USAGE
# make target folder
target = sys.argv[1]
os.mkdir(target)
# change to os specificsep
REQUIRED = REQUIRED.replace('/', os.sep)
IGNORED = IGNORED.replace('/', os.sep)
# make a list of all files to inclu... | OSError | dataset/ETHPy150Open uwdata/termite-data-server/web2py/scripts/make_min_web2py.py/main |
4,244 | def test_get_debug_values_exc():
"""tests that get_debug_value raises an exception when
debugger is set to raise and a value is missing """
prev_value = config.compute_test_value
try:
config.compute_test_value = 'raise'
x = T.vector()
try:
for x_val in op.get_d... | AttributeError | dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/gof/tests/test_op.py/test_get_debug_values_exc |
4,245 | def test_debug_error_message():
"""tests that debug_error_message raises an
exception when it should."""
prev_value = config.compute_test_value
for mode in ['ignore', 'raise']:
try:
config.compute_test_value = mode
try:
op.debug_error_message('msg')
... | ValueError | dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/gof/tests/test_op.py/test_debug_error_message |
4,246 | def run(self):
try:
while 1:
self.listen()
except __HOLE__:
return | KeyboardInterrupt | dataset/ETHPy150Open kdart/pycopia/net/pycopia/simpleserver.py/GenericServer.run |
4,247 | def run(self):
try:
try:
while 1:
line = raw_input("> ")
self._sock.send(line)
data = self._sock.recv(1024)
if not data:
break
else:
pri... | KeyboardInterrupt | dataset/ETHPy150Open kdart/pycopia/net/pycopia/simpleserver.py/GenericClient.run |
4,248 | def get_homedir():
"""return home directory, or best approximation
On Windows, this returns the Roaming Profile APPDATA
(use CSIDL_LOCAL_APPDATA for Local Profile)
"""
homedir = '.'
if os.name == 'nt':
# For Windows, ask for parent of Roaming 'Application Data' directory
try:
... | ImportError | dataset/ETHPy150Open xraypy/xraylarch/plugins/io/fileutils.py/get_homedir |
4,249 | def getAttributeNames(object, includeMagic=1, includeSingle=1,
includeDouble=1):
"""Return list of unique attributes, including inherited, for object."""
attributes = []
dict = {}
if not introspect.hasattrAlwaysReturnsTrue(object):
# Add some attributes that don't always ge... | TypeError | dataset/ETHPy150Open enthought/pyface/pyface/util/fix_introspect_bug.py/getAttributeNames |
4,250 | def parse_uri(self, uri):
"""
Parse URLs. This method fixes an issue where credentials specified
in the URL are interpreted differently in Python 2.6.1+ than prior
versions of Python.
Note that an Amazon AWS secret key can contain the forward slash,
which is entirely ret... | IndexError | dataset/ETHPy150Open openstack/glance_store/glance_store/_drivers/s3.py/StoreLocation.parse_uri |
4,251 | def add_multipart(self, image_file, image_size, bucket_obj, obj_name, loc,
verifier):
"""
Stores an image file with a multi part upload to S3 backend
:param image_file: The image data to write, as a file-like object
:param bucket_obj: S3 bucket object
:para... | StopIteration | dataset/ETHPy150Open openstack/glance_store/glance_store/_drivers/s3.py/Store.add_multipart |
4,252 | def append_files(in_file1, character, in_file2, out_file):
"""
Created on 24 Oct 2014
Created for use with Wonderware Archestra.
Takes a file1 and appends file2 contents joined by a character, line for line.
USAGE:
%prog in_file1.csv %character in_file2.txt
@author: Roan Fourie
... | IOError | dataset/ETHPy150Open RoanFourie/ArchestrA-Tools/aaTools/aaAppend.py/append_files |
4,253 | def create_job(self, name, user, template_name, **kwargs):
"""
Creates a new job from a JobTemplate.
Args:
name (str): The name of the job.
user (User): A User object for the user who creates the job.
template_name (str): The name of the JobTemplate from whic... | KeyError | dataset/ETHPy150Open tethysplatform/tethys/tethys_compute/job_manager.py/JobManager.create_job |
4,254 | def deserialize(self, cassette_data):
try:
deserialized_data = json.loads(cassette_data)
except __HOLE__:
deserialized_data = {}
return deserialized_data | ValueError | dataset/ETHPy150Open sigmavirus24/betamax/betamax/serializers/json_serializer.py/JSONSerializer.deserialize |
4,255 | def timedelta_total_seconds(delta):
try:
delta.total_seconds
except __HOLE__:
# On Python 2.6, timedelta instances do not have
# a .total_seconds() method.
total_seconds = delta.days * 24 * 60 * 60 + delta.seconds
else:
total_seconds = delta.total_seconds()
retur... | AttributeError | dataset/ETHPy150Open jpadilla/pyjwt/jwt/compat.py/timedelta_total_seconds |
4,256 | def _user_exists(self, username):
try:
pwd.getpwnam(username)[0] # user exists
except __HOLE__:
return False
home_dir = os.path.join('/home', '{0}'.format(username))
auth_key_file = os.path.join(home_dir, '.ssh', 'authorized_keys')
if not os.path.e... | KeyError | dataset/ETHPy150Open koshinuke/koshinuke.py/tests/auth_test.py/AuthTestCase._user_exists |
4,257 | def _load_from_packages(self, packages):
try:
for package in packages:
for module in walk_modules(package):
self._load_module(module)
except __HOLE__ as e:
message = 'Problem loading extensions from package {}: {}'
raise LoaderError... | ImportError | dataset/ETHPy150Open ARM-software/workload-automation/wlauto/core/extension_loader.py/ExtensionLoader._load_from_packages |
4,258 | def _load_from_paths(self, paths, ignore_paths):
self.logger.debug('Loading from paths.')
for path in paths:
self.logger.debug('Checking path %s', path)
for root, _, files in os.walk(path, followlinks=True):
should_skip = False
for igpath in ignore... | SystemExit | dataset/ETHPy150Open ARM-software/workload-automation/wlauto/core/extension_loader.py/ExtensionLoader._load_from_paths |
4,259 | def get_axes_properties(ax):
props = {'axesbg': color_to_hex(ax.patch.get_facecolor()),
'axesbgalpha': ax.patch.get_alpha(),
'bounds': ax.get_position().bounds,
'dynamic': ax.get_navigate(),
'axison': ax.axison,
'frame_on': ax.get_frame_on(),
... | ImportError | dataset/ETHPy150Open plotly/plotly.py/plotly/matplotlylib/mplexporter/utils.py/get_axes_properties |
4,260 | def trigsimp(expr, **opts):
"""
reduces expression by using known trig identities
Notes
=====
method:
- Determine the method to use. Valid choices are 'matching' (default),
'groebner', 'combined', and 'fu'. If 'matching', simplify the
expression recursively by targeting common patterns... | AttributeError | dataset/ETHPy150Open sympy/sympy/sympy/simplify/trigsimp.py/trigsimp |
4,261 | @cacheit
def __trigsimp(expr, deep=False):
"""recursive helper for trigsimp"""
from sympy.simplify.fu import TR10i
if _trigpat is None:
_trigpats()
a, b, c, d, matchers_division, matchers_add, \
matchers_identity, artifacts = _trigpat
if expr.is_Mul:
# do some simplifications l... | TypeError | dataset/ETHPy150Open sympy/sympy/sympy/simplify/trigsimp.py/__trigsimp |
4,262 | @classmethod
def _parse_split(cls, repo, splitmap):
name = splitmap.pop('name')
patterns = splitmap.pop('paths')
try:
return Split(repo, name, patterns)
except __HOLE__:
raise ConfigError("Problem creating split: %s\n%s\n\n%s", name, splitmap,
traceback.format_exc()... | KeyError | dataset/ETHPy150Open jsirois/sapling/saplib/config.py/Config._parse_split |
4,263 | def get_category_lists(init_kwargs=None, additional_parents_aliases=None, obj=None):
"""Returns a list of CategoryList objects, optionally associated with
a given model instance.
:param dict|None init_kwargs:
:param list|None additional_parents_aliases:
:param Model|None obj: Model instance to get ... | KeyError | dataset/ETHPy150Open idlesign/django-sitecats/sitecats/toolbox.py/get_category_lists |
4,264 | def backend_meta_data(self, backend_obj):
"""Query's the database for the object's current values for:
- created_on
- created_by
- modified_on
- modified_by
- deleted_on
- deleted_by
Returns a dictionary of these keys and their values.
... | AttributeError | dataset/ETHPy150Open mozilla/moztrap/tests/case/api/crud.py/ApiCrudCases.backend_meta_data |
4,265 | def do_img(self, attrs):
align = ''
alt = '(image)'
ismap = ''
src = ''
width = 0
height = 0
for attrname, value in attrs:
if attrname == 'align':
align = value
if attrname == 'alt':
alt = value
i... | ValueError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/htmllib.py/HTMLParser.do_img |
4,266 | def test(args = None):
import sys, formatter
if not args:
args = sys.argv[1:]
silent = args and args[0] == '-s'
if silent:
del args[0]
if args:
file = args[0]
else:
file = 'test.html'
if file == '-':
f = sys.stdin
else:
try:
... | IOError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/htmllib.py/test |
4,267 | def briefstr(x):
try:
return getattr(x, 'brief')
except __HOLE__:
if isinstance(x, tuple):
return '(%s)'%(','.join([briefstr(xi) for xi in x]))
return str(x) | AttributeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/guppy-0.1.10/guppy/heapy/Spec.py/briefstr |
4,268 | def func_argnames(self, f, args):
try:
code = f.func_code
return self.getargnames(code) == args
except __HOLE__:
return False | AttributeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/guppy-0.1.10/guppy/heapy/Spec.py/ArgNamesFamily.func_argnames |
4,269 | def meth_argnames(self, m, args):
try:
f = m.im_func
code = f.func_code
return self.getargnames(code)[1:] == args
except __HOLE__:
return False | AttributeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/guppy-0.1.10/guppy/heapy/Spec.py/ArgNamesFamily.meth_argnames |
4,270 | def c_test_contains(self, a, b, env):
try:
func = a.func
except __HOLE__:
expr = a.arg
func = a.func = env.eval('lambda self:%s'%expr)
s = func(self.specmod.Nothing)
try:
tf = env.test_contains(s, b, 'recur with Nothing, ok to fail')
if not tf:
raise TestError
except : # TestError: eg fo... | AttributeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/guppy-0.1.10/guppy/heapy/Spec.py/RecurSelfFamily.c_test_contains |
4,271 | def __init__(self, mod, Spec):
self.mod = mod
self.messages = []
self.examples = {}
if Spec is not None:
self.spec = spec = Spec()
try:
lex = spec.LocalEnvExpr
except __HOLE__:
lex = ''
LE = LocalEnv(mod, lex)
LE._OBJ_ = mod
self.LE = LE
self.topspec = self.eval(spec.GlueType... | AttributeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/guppy-0.1.10/guppy/heapy/Spec.py/TestEnv.__init__ |
4,272 | def eval(self, expr):
mod = self.mod
types = mod._root.types
if isinstance(expr, types.StringTypes):
func = self.mod.eval('lambda LE:(\n%s\n)'%expr)
return func(self.LE)
ls = []
selfset = None
#print 1
names = expr.__dict__.keys()
names.sort()
for name in names:
f = getattr(expr, name)
... | AttributeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/guppy-0.1.10/guppy/heapy/Spec.py/TestEnv.eval |
4,273 | def get_examples(self, collection):
try:
it = iter(collection)
except __HOLE__:
try:
ex = self.examples[collection]
except KeyError:
if isinstance(collection, self.mod.UniSet.UniSet):
ex = collection.get_examples(self)
else:
ex = list(collection)
it = iter(ex)
return it | TypeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/guppy-0.1.10/guppy/heapy/Spec.py/TestEnv.get_examples |
4,274 | @staticmethod
def _is_json(data):
try:
json.loads(data)
except (__HOLE__, ValueError):
return False
return True | TypeError | dataset/ETHPy150Open bulkan/robotframework-requests/src/RequestsLibrary/RequestsKeywords.py/RequestsKeywords._is_json |
4,275 | def invoke(self, cli, args=None, input=None, env=None,
catch_exceptions=True, color=False, **extra):
"""Invokes a command in an isolated environment. The arguments are
forwarded directly to the command line script, the `extra` keyword
arguments are passed to the :meth:`~clickpkg.... | SystemExit | dataset/ETHPy150Open pallets/click/click/testing.py/CliRunner.invoke |
4,276 | @contextlib.contextmanager
def isolated_filesystem(self):
"""A context manager that creates a temporary folder and changes
the current working directory to it for isolated filesystem tests.
"""
cwd = os.getcwd()
t = tempfile.mkdtemp()
os.chdir(t)
try:
... | OSError | dataset/ETHPy150Open pallets/click/click/testing.py/CliRunner.isolated_filesystem |
4,277 | def disable(self):
self._enabled = False
try:
self._client.unschedule(self)
except __HOLE__:
pass | KeyError | dataset/ETHPy150Open dpkp/kafka-python/kafka/coordinator/consumer.py/AutoCommitTask.disable |
4,278 | def readAndGroupTable(infile, options):
"""read table from infile and group.
"""
fields, table = CSV.readTable(
infile, with_header=options.has_headers, as_rows=True)
options.columns = getColumns(fields, options.columns)
assert options.group_column not in options.columns
converter = flo... | ValueError | dataset/ETHPy150Open CGATOxford/cgat/scripts/table2table.py/readAndGroupTable |
4,279 | def main(argv=None):
"""script main.
parses command line options in sys.argv, unless *argv* is given.
"""
if argv is None:
argv = sys.argv
parser = E.OptionParser(version="%prog version: $Id$",
usage=globals()["__doc__"])
parser.add_option(
"-m", "... | ValueError | dataset/ETHPy150Open CGATOxford/cgat/scripts/table2table.py/main |
4,280 | def request_instance(vm_):
'''
Request a single GCE instance from a data dict.
'''
if not GCE_VM_NAME_REGEX.match(vm_['name']):
raise SaltCloudSystemExit(
'VM names must start with a letter, only contain letters, numbers, or dashes '
'and cannot end in a dash.'
)
... | TypeError | dataset/ETHPy150Open saltstack/salt/salt/cloud/clouds/gce.py/request_instance |
4,281 | def get_file_timestamp(fn):
"""
Returns timestamp of the given file
"""
from frappe.utils import cint
try:
return str(cint(os.stat(fn).st_mtime))
except __HOLE__, e:
if e.args[0]!=2:
raise
else:
return None
# to be deprecated | OSError | dataset/ETHPy150Open frappe/frappe/frappe/utils/__init__.py/get_file_timestamp |
4,282 | def watch(path, handler=None, debug=True):
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class Handler(FileSystemEventHandler):
def on_any_event(self, event):
if debug:
print "File {0}: {1}".format(event.event_type, event.src_path)
if not handle... | KeyboardInterrupt | dataset/ETHPy150Open frappe/frappe/frappe/utils/__init__.py/watch |
4,283 | def is_json(text):
try:
json.loads(text)
except __HOLE__:
return False
else:
return True | ValueError | dataset/ETHPy150Open frappe/frappe/frappe/utils/__init__.py/is_json |
4,284 | def env():
""" Returns a simple to use dictionary of common operating system details"""
p = {}
p['platform'] = platform.platform() or None
p['python_version'] = platform.python_version() or None
try:
p['python_major_version'] = p['python_version'][0]
except TypeError:
p['pytho... | NameError | dataset/ETHPy150Open tristanfisher/easyos/easyos/easyos.py/env |
4,285 | def extract_content(self, selector, attr, default):
"""
Method for performing the content extraction for the given XPath expression.
The XPath selector expression can be used to extract content \
from the element tree corresponding to the fetched web page.
If the selector is "url", the URL of the current we... | IndexError | dataset/ETHPy150Open AlexMathew/scrapple/scrapple/selectors/xpath.py/XpathSelector.extract_content |
4,286 | def extract_tabular(self, result={}, table_type="rows", header=[], prefix="", suffix="", selector="", attr="text", default="", verbosity=0):
"""
Method for performing the extraction of tabular data.
:param result:
:param table_type:
:param header:
:param prefix:
:param suffix:
:param selector:
:param... | IndexError | dataset/ETHPy150Open AlexMathew/scrapple/scrapple/selectors/xpath.py/XpathSelector.extract_tabular |
4,287 | @cached_property
def preview_size(self):
# This error checking might be too aggressive...
preview_width, preview_height = PREVIEW_WIDTH, PREVIEW_HEIGHT
preview_size = self.request.GET.get('preview_size', '').split('x')
if len(preview_size) != 2:
preview_size = (PREVIEW_WI... | TypeError | dataset/ETHPy150Open theatlantic/django-cropduster/cropduster/views/__init__.py/CropDusterIndex.preview_size |
4,288 | @cached_property
def db_image(self):
try:
db_image = Image.objects.get(pk=self.request.GET.get('id'))
except (__HOLE__, Image.DoesNotExist):
return None
image_filename = getattr(self.image_file, 'name', None)
if image_filename and image_filename != db_image.i... | ValueError | dataset/ETHPy150Open theatlantic/django-cropduster/cropduster/views/__init__.py/CropDusterIndex.db_image |
4,289 | @cached_property
def thumbs(self):
thumb_ids = filter(None, self.request.GET.get('thumbs', '').split(','))
try:
thumb_ids = map(int, thumb_ids)
except __HOLE__:
thumbs = Thumb.objects.none()
else:
thumbs = Thumb.objects.filter(pk__in=thumb_ids)
... | TypeError | dataset/ETHPy150Open theatlantic/django-cropduster/cropduster/views/__init__.py/CropDusterIndex.thumbs |
4,290 | @csrf_exempt
def crop(request):
if request.method == "GET":
return json_error(request, 'crop', action="cropping image",
errors=["Form submission invalid"])
crop_form = CropForm(request.POST, request.FILES, prefix='crop')
if not crop_form.is_valid():
return json_error(request... | IOError | dataset/ETHPy150Open theatlantic/django-cropduster/cropduster/views/__init__.py/crop |
4,291 | def shortcut(request, content_type_id, object_id):
"Redirect to an object's page based on a content-type ID and an object ID."
# Look up the object, making sure it's got a get_absolute_url() function.
try:
content_type = ContentType.objects.get(pk=content_type_id)
if not content_type.model_c... | IndexError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/contrib/contenttypes/views.py/shortcut |
4,292 | def writing_file(FILENAME, att='a', MESSAGE=""):
try:
with open(FILENAME, att) as f:
f.write(MESSAGE)
f.write('\n')
except __HOLE__ as e:
print "I/O error({0}): {1} for file {2}".format(e.errno, e.strerror, FILENAME) | IOError | dataset/ETHPy150Open bt3gl/Neat-Problems-in-Python-and-Flask/Version-Control/src/system_operations.py/writing_file |
4,293 | def copying_file(SOURCE, DESTINATION):
try:
shutil.copy(SOURCE, DESTINATION)
# could also use
# os.system ("copy %s %s" % (filename1, filename2))
# also, for recursively copy a tree
# shutil.copytree(src, dest)
# source and destination are the same file
except shuti... | IOError | dataset/ETHPy150Open bt3gl/Neat-Problems-in-Python-and-Flask/Version-Control/src/system_operations.py/copying_file |
4,294 | def moving_dir(SOURCE, DESTINATION):
try:
shutil.move(SOURCE, DESTINATION)
# source and destination are the same file
except shutil.Error as e:
print("Error: %s" % e)
# source does not exist
except __HOLE__ as e:
print "I/O error({0}): {1} for file {2}".format(e.errno, e.s... | IOError | dataset/ETHPy150Open bt3gl/Neat-Problems-in-Python-and-Flask/Version-Control/src/system_operations.py/moving_dir |
4,295 | def renaming_file(SOURCE, DESTINATION):
try:
shutil.move(SOURCE, DESTINATION)
# source and destination are the same file
except shutil.Error as e:
print("Error: %s" % e)
# source does not exist
except __HOLE__ as e:
print "I/O error({0}): {1} for file {2}".format(e.errno, ... | IOError | dataset/ETHPy150Open bt3gl/Neat-Problems-in-Python-and-Flask/Version-Control/src/system_operations.py/renaming_file |
4,296 | def creating_file(FILENAME, att='a'):
try:
f = open(FILENAME, att)
f.close()
except __HOLE__ as e:
print "I/O error({0}): {1} for file {2}".format(e.errno, e.strerror, FILENAME) | IOError | dataset/ETHPy150Open bt3gl/Neat-Problems-in-Python-and-Flask/Version-Control/src/system_operations.py/creating_file |
4,297 | def removing_dir_tree(DIR_TO_DELETE):
try:
# we could also use
shutil.rmtree(DIR_TO_DELETE)
#os.rmdir(DIR_TO_DELETE)
except __HOLE__, e:
print ("Error: %s - %s." % (e.filename,e.strerror)) | OSError | dataset/ETHPy150Open bt3gl/Neat-Problems-in-Python-and-Flask/Version-Control/src/system_operations.py/removing_dir_tree |
4,298 | def print_lines(FILENAME):
try:
with open(FILENAME, 'r') as f:
lines = f.readlines()
print("---------- %s ----------" %FILENAME)
for line in lines:
print(line.strip('\n'))
print(" ")
except __HOLE__ as e:
print "I/O error({0}): {1... | IOError | dataset/ETHPy150Open bt3gl/Neat-Problems-in-Python-and-Flask/Version-Control/src/system_operations.py/print_lines |
4,299 | def compressing_file(FILE_TO_COMPRESS):
try:
f_in = open(FILE_TO_COMPRESS)
f_out = gzip.open(FILE_TO_COMPRESS + '.gz', 'wb')
f_out.writelines(f_in)
f_in.close()
f_out.close()
except __HOLE__ as e:
print "I/O error({0}): {1} for file {2}".format(e.errno, e.strerr... | IOError | dataset/ETHPy150Open bt3gl/Neat-Problems-in-Python-and-Flask/Version-Control/src/system_operations.py/compressing_file |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.