Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
4,800 | def __init__(self, env):
self.env = env
self.root_path = os.path.join(self.env.root_path, 'databags')
self._known_bags = {}
self._bags = {}
try:
for filename in os.listdir(self.root_path):
if filename.endswith(('.ini', '.json')):
se... | OSError | dataset/ETHPy150Open lektor/lektor-archive/lektor/databags.py/Databags.__init__ |
4,801 | def init_connection_file(self):
"""find the connection file, and load the info if found.
The current working directory and the current profile's security
directory will be searched for the file if it is not given by
absolute path.
When attempting to connect to a... | IOError | dataset/ETHPy150Open jupyter/jupyter_client/jupyter_client/consoleapp.py/JupyterConsoleApp.init_connection_file |
4,802 | def test_supportsThreads(self):
"""
L{Platform.supportsThreads} returns C{True} if threads can be created in
this runtime, C{False} otherwise.
"""
# It's difficult to test both cases of this without faking the threading
# module. Perhaps an adequate test is to just test ... | ImportError | dataset/ETHPy150Open twisted/twisted/twisted/python/test/test_runtime.py/PlatformTests.test_supportsThreads |
4,803 | def request(host, port, url, method="get", *args, **kwargs):
"""
| General wrapper around the "Request" methods
| Used by Server object when sending request to the main server, can also
| be used by any worker/specific requests.
:param host: hostname to reach
:param port: port to use
:param... | ValueError | dataset/ETHPy150Open mikrosimage/OpenRenderManagement/src/puliclient/server/server.py/request |
4,804 | def __new__(cls, *args, **kwargs):
"""
Initializes class attributes for subsequent constructor calls.
:note: *args and **kwargs are not explicitly used in this function,
but needed for Python 2 compatibility.
"""
if not cls.__initialized__:
cls.__initialized_... | AttributeError | dataset/ETHPy150Open influxdata/influxdb-python/influxdb/helper.py/SeriesHelper.__new__ |
4,805 | def is_series(self):
copy = list(self.items)
for k, _ in enumerate(copy):
try:
if not self.is_successor(copy[k], copy[k + 1]):
yield False
except __HOLE__:
continue
yield True | IndexError | dataset/ETHPy150Open christabor/MoAL/MOAL/maths/set_theory.py/Set.is_series |
4,806 | def __init__(self, obj, name=None, pure=False):
if name is None:
try:
name = obj.__name__ + tokenize(obj, pure=pure)
except __HOLE__:
name = type(obj).__name__ + tokenize(obj, pure=pure)
object.__setattr__(self, '_dasks', [{name: obj}])
obj... | AttributeError | dataset/ETHPy150Open dask/dask/dask/delayed.py/DelayedLeaf.__init__ |
4,807 | def scale_image(img_upload, img_max_size):
"""Crop and scale an image file."""
try:
img = Image.open(img_upload)
except __HOLE__:
return None
src_width, src_height = img.size
src_ratio = float(src_width) / float(src_height)
dst_width, dst_height = img_max_size
dst_ratio = fl... | IOError | dataset/ETHPy150Open mozilla/django-badger/badger/models.py/scale_image |
4,808 | def to_python(self, value):
"""Convert our string value to JSON after we load it from the DB"""
if not value:
return dict()
try:
if (isinstance(value, basestring) or
type(value) is unicode):
return json.loads(value)
except __HOL... | ValueError | dataset/ETHPy150Open mozilla/django-badger/badger/models.py/JSONField.to_python |
4,809 | def bake_obi_image(self, request=None):
"""Bake the OBI JSON badge award assertion into a copy of the original
badge's image, if one exists."""
if request:
base_url = request.build_absolute_uri('/')
else:
base_url = 'http://%s' % (Site.objects.get_current().domai... | ImportError | dataset/ETHPy150Open mozilla/django-badger/badger/models.py/Award.bake_obi_image |
4,810 | def get_value(key):
try:
value = os.environ[key]
except __HOLE__:
msg = u"You must define the {} " \
u"environment variable.".format(key)
raise Exception(msg)
return value | KeyError | dataset/ETHPy150Open tsuru/healthcheck-as-a-service/healthcheck/backends/__init__.py/get_value |
4,811 | @permission_required("core.manage_shop")
def manage_discounts(request):
"""Dispatches to the first discount or to the add discount method
form if there is no discount yet.
"""
try:
discount = Discount.objects.all()[0]
except __HOLE__:
url = reverse("lfs_manage_no_discounts")
else... | IndexError | dataset/ETHPy150Open diefenbach/django-lfs/lfs/manage/discounts/views.py/manage_discounts |
4,812 | @permission_required("core.manage_shop")
def navigation(request, template_name="manage/discounts/navigation.html"):
"""Returns the navigation for the discount view.
"""
try:
current_id = int(request.path.split("/")[-1])
except __HOLE__:
current_id = ""
return render_to_string(templa... | ValueError | dataset/ETHPy150Open diefenbach/django-lfs/lfs/manage/discounts/views.py/navigation |
4,813 | @permission_required("core.manage_shop")
@require_POST
def delete_discount(request, id):
"""Deletes discount with passed id.
"""
try:
discount = Discount.objects.get(pk=id)
except __HOLE__:
pass
else:
discount.delete()
return lfs.core.utils.set_message_cookie(
ur... | ObjectDoesNotExist | dataset/ETHPy150Open diefenbach/django-lfs/lfs/manage/discounts/views.py/delete_discount |
4,814 | def log_error(request, view, action, errors, exc_info=None):
# We only log the first error, send the rest as data; it's simpler this way
error_msg = "Error %s: %s" % (action, format_error(errors[0]))
log_kwargs = {}
if not exc_info:
try:
exc_info = full_exc_info()
except:
... | ImportError | dataset/ETHPy150Open theatlantic/django-cropduster/cropduster/exceptions.py/log_error |
4,815 | def is_valid_ip(ip):
# stackoverflow.com/a/4017219/1707152
def is_valid_ipv4_address(address):
try:
socket.inet_pton(socket.AF_INET, address)
except __HOLE__:
try:
socket.inet_aton(address)
except socket.error:
return False
... | AttributeError | dataset/ETHPy150Open opendns/OpenResolve/resolverapi/util/__init__.py/is_valid_ip |
4,816 | def testInstallHandler(self):
default_handler = signal.getsignal(signal.SIGINT)
unittest.installHandler()
self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler)
try:
pid = os.getpid()
os.kill(pid, signal.SIGINT)
except __HOLE__:
... | KeyboardInterrupt | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/unittest/test/test_break.py/TestBreak.testInstallHandler |
4,817 | def testInterruptCaught(self):
default_handler = signal.getsignal(signal.SIGINT)
result = unittest.TestResult()
unittest.installHandler()
unittest.registerResult(result)
self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler)
def test(result):
... | KeyboardInterrupt | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/unittest/test/test_break.py/TestBreak.testInterruptCaught |
4,818 | def testSecondInterrupt(self):
result = unittest.TestResult()
unittest.installHandler()
unittest.registerResult(result)
def test(result):
pid = os.getpid()
os.kill(pid, signal.SIGINT)
result.breakCaught = True
self.assertTrue(result.should... | KeyboardInterrupt | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/unittest/test/test_break.py/TestBreak.testSecondInterrupt |
4,819 | def testTwoResults(self):
unittest.installHandler()
result = unittest.TestResult()
unittest.registerResult(result)
new_handler = signal.getsignal(signal.SIGINT)
result2 = unittest.TestResult()
unittest.registerResult(result2)
self.assertEqual(signal.getsignal(si... | KeyboardInterrupt | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/unittest/test/test_break.py/TestBreak.testTwoResults |
4,820 | def testHandlerReplacedButCalled(self):
# If our handler has been replaced (is no longer installed) but is
# called by the *new* handler, then it isn't safe to delay the
# SIGINT and we should immediately delegate to the default handler
unittest.installHandler()
handler = signal... | KeyboardInterrupt | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/unittest/test/test_break.py/TestBreak.testHandlerReplacedButCalled |
4,821 | def testRemoveResult(self):
result = unittest.TestResult()
unittest.registerResult(result)
unittest.installHandler()
self.assertTrue(unittest.removeResult(result))
# Should this raise an error instead?
self.assertFalse(unittest.removeResult(unittest.TestResult()))
... | KeyboardInterrupt | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/unittest/test/test_break.py/TestBreak.testRemoveResult |
4,822 | def call_hdevtools_and_wait(arg_list, filename = None, cabal = None):
"""
Calls hdevtools with the given arguments.
Shows a sublime error message if hdevtools is not available.
"""
ghc_opts_args = get_ghc_opts_args(filename, cabal = cabal)
hdevtools_socket = get_setting_async('hdevtools_socket')... | OSError | dataset/ETHPy150Open SublimeHaskell/SublimeHaskell/hdevtools.py/call_hdevtools_and_wait |
4,823 | def admin(cmds, wait = False, **popen_kwargs):
if not hdevtools_enabled():
return None
hdevtools_socket = get_setting_async('hdevtools_socket')
if hdevtools_socket:
cmds.append('--socket={0}'.format(hdevtools_socket))
command = ["hdevtools", "admin"] + cmds
try:
if wait:
... | OSError | dataset/ETHPy150Open SublimeHaskell/SublimeHaskell/hdevtools.py/admin |
4,824 | def resource_from_etree(self, etree, resource_class):
"""Construct a Resource from an etree
Parameters:
etree - the etree to parse
resource_class - class of Resource object to create
The parsing is properly namespace aware but we search just
for the elements wanted a... | ValueError | dataset/ETHPy150Open resync/resync/resync/sitemap.py/Sitemap.resource_from_etree |
4,825 | def md_from_etree(self, md_element, context=''):
"""Parse rs:md attributes returning a dict of the data
Parameters:
md_element - etree element <rs:md>
context - context for error reporting
"""
md = {}
# grab all understood attributes into md dict
... | ValueError | dataset/ETHPy150Open resync/resync/resync/sitemap.py/Sitemap.md_from_etree |
4,826 | def ln_from_etree(self,ln_element,context=''):
"""Parse rs:ln element from an etree, returning a dict of the data
Parameters:
md_element - etree element <rs:md>
context - context string for error reporting
"""
ln = {}
# grab all understood attributes i... | ValueError | dataset/ETHPy150Open resync/resync/resync/sitemap.py/Sitemap.ln_from_etree |
4,827 | def main():
silent = 0
verbose = 0
if sys.argv[1:]:
if sys.argv[1] == '-v':
verbose = 1
elif sys.argv[1] == '-s':
silent = 1
MAGIC = imp.get_magic()
if not silent:
print 'Using MAGIC word', repr(MAGIC)
for dirname in sys.path:
try:
... | IOError | dataset/ETHPy150Open francelabs/datafari/windows/python/Tools/Scripts/checkpyc.py/main |
4,828 | def find_module(module_name, path=None):
""" Returns the filename for the specified module. """
components = module_name.split('.')
try:
# Look up the first component of the module name (of course it could be
# the *only* component).
f, filename, description = imp.find_module(compo... | ImportError | dataset/ETHPy150Open enthought/envisage/envisage/developer/code_browser/enclbr.py/find_module |
4,829 | def get_object(self, name, **args):
try:
return self.resources[name].dataobject()
except __HOLE__:
raise NoSuchObjectError(name) | KeyError | dataset/ETHPy150Open Stiivi/bubbles/bubbles/datapackage.py/DataPackageCollectionStore.get_object |
4,830 | def get_ip(request):
"""
Retrieves the remote IP address from the request data. If the user is
behind a proxy, they may have a comma-separated list of IP addresses, so
we need to account for that. In such a case, only the first IP in the
list will be retrieved. Also, some hosts that use a proxy w... | IndexError | dataset/ETHPy150Open bashu/django-tracking/tracking/utils.py/get_ip |
4,831 | def u_clean(s):
"""A strange attempt at cleaning up unicode"""
uni = ''
try:
# try this first
uni = str(s).decode('iso-8859-1')
except UnicodeDecodeError:
try:
# try utf-8 next
uni = str(s).decode('utf-8')
except UnicodeDecodeError:
# ... | UnicodeDecodeError | dataset/ETHPy150Open bashu/django-tracking/tracking/utils.py/u_clean |
4,832 | def check_path(filename, reporter=modReporter.Default, settings_path=None, **setting_overrides):
"""Check the given path, printing out any warnings detected."""
try:
with open(filename, 'U') as f:
codestr = f.read() + '\n'
except UnicodeError:
reporter.unexpected_error(filename, ... | IOError | dataset/ETHPy150Open timothycrosley/frosted/frosted/api.py/check_path |
4,833 | def getStyleAttribute(elem, attr):
try:
if hasattr(elem.style, 'getProperty'):
return elem.style.getProperty(mash_name_for_glib(attr))
return elem.style.getAttribute(attr)
except __HOLE__:
return getattr(elem.style, attr, None) | AttributeError | dataset/ETHPy150Open anandology/pyjamas/library/gwt/DOM.py/getStyleAttribute |
4,834 | def get_node_version(self):
if not self.project_dir:
return self.default_version
package_file = os.path.join(self.project_dir, 'package.json')
try:
package_json = json.load(open(package_file))
except (__HOLE__, ValueError):
logger.debug(
... | IOError | dataset/ETHPy150Open elbaschid/virtual-node/setup.py/node_build.get_node_version |
4,835 | def run_npm(self, env_dir):
package_file = os.path.join(self.project_dir, 'package.json')
try:
package = json.load(open(package_file))
except __HOLE__:
logger.warning("Could not find 'package.json', ignoring NPM "
"dependencies.")
re... | IOError | dataset/ETHPy150Open elbaschid/virtual-node/setup.py/node_build.run_npm |
4,836 | def install_node(self, env_dir, version=None):
"""
Download source code for node.js, unpack it
and install it in virtual environment.
"""
logger.info(
' * Install node.js (%s' % self.version,
extra={'continued': True}
)
node_name = 'node-v... | IOError | dataset/ETHPy150Open elbaschid/virtual-node/setup.py/node_build.install_node |
4,837 | def _list_all_covered_modules(logger, module_names, modules_exceptions):
modules = []
for module_name in module_names:
if module_name in modules_exceptions:
logger.debug("Module '%s' was excluded", module_name)
continue
try:
module = sys.modules[module_name]
... | KeyError | dataset/ETHPy150Open pybuilder/pybuilder/src/main/python/pybuilder/plugins/python/coverage_plugin.py/_list_all_covered_modules |
4,838 | def _delete_module(module_name, module):
del sys.modules[module_name]
try:
delattr(module, module_name)
except __HOLE__:
pass | AttributeError | dataset/ETHPy150Open pybuilder/pybuilder/src/main/python/pybuilder/plugins/python/coverage_plugin.py/_delete_module |
4,839 | def get_socket(self, force=False):
"""Get a socket from the pool.
Returns a :class:`SocketInfo` object wrapping a connected
:class:`socket.socket`, and a bool saying whether the socket was from
the pool or freshly created.
:Parameters:
- `force`: optional boolean, for... | KeyError | dataset/ETHPy150Open blynch/CloudMemeBackend/pymongo/pool.py/Pool.get_socket |
4,840 | def make_list_of_list(txt):
def make_num(x):
try:
return int(x)
except ValueError:
try:
return float(x)
except __HOLE__:
try:
return complex(x)
except ValueError:
return x
... | ValueError | dataset/ETHPy150Open Ali-Razmjoo/OWASP-ZSC/module/readline_windows/pyreadline/clipboard/__init__.py/make_list_of_list |
4,841 | def __init__(self, backend, algorithm, ctx=None):
self._algorithm = algorithm
self._backend = backend
if ctx is None:
try:
methods = self._backend._hash_mapping[self.algorithm.name]
except __HOLE__:
raise UnsupportedAlgorithm(
... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/cryptography-1.3.1/src/cryptography/hazmat/backends/commoncrypto/hashes.py/_HashContext.__init__ |
4,842 | def main(args):
try:
opts, args = getopt.getopt(args, "hbrdag",
["hash", "btree", "recno", "dbm", "anydbm",
"gdbm"])
except getopt.error:
usage()
return 1
if len(args) == 0 or len(args) > 2:
usa... | AttributeError | dataset/ETHPy150Open Southpaw-TACTIC/TACTIC/src/context/client/tactic-api-python-4.0.api04/Tools/Scripts/pickle2db.py/main |
4,843 | def _(module):
'''
Get inspectlib module for the lazy loader.
:param module:
:return:
'''
mod = None
# pylint: disable=E0598
try:
# importlib is in Python 2.7+ and 3+
import importlib
mod = importlib.import_module("salt.modules.inspectlib.{0}".format(module))
... | ImportError | dataset/ETHPy150Open saltstack/salt/salt/modules/node.py/_ |
4,844 | def _create_hls_streams(self, url):
try:
streams = HLSStream.parse_variant_playlist(self.session, url)
return streams.items()
except __HOLE__ as err:
self.logger.warning("Failed to extract HLS streams: {0}", err) | IOError | dataset/ETHPy150Open chrippa/livestreamer/src/livestreamer/plugins/streamlive.py/StreamLive._create_hls_streams |
4,845 | def _fetch(self, count):
# Try to fill ``self.items`` with at least ``count`` objects.
have = len(self.items)
while self.iterator is not None and have < count:
try:
item = next(self.iterator)
except StopIteration:
self.iterator = None
... | KeyboardInterrupt | dataset/ETHPy150Open ipython/ipython-py3k/IPython/deathrow/igrid.py/IGridTable._fetch |
4,846 | def sort(self, key, reverse=False):
"""
Sort the current list of items using the key function ``key``. If
``reverse`` is true the sort order is reversed.
"""
row = self.GetGridCursorRow()
col = self.GetGridCursorCol()
curitem = self.table.items[row] # Remember whe... | SystemExit | dataset/ETHPy150Open ipython/ipython-py3k/IPython/deathrow/igrid.py/IGridGrid.sort |
4,847 | def sortattrasc(self):
"""
Sort in ascending order; sorting criteria is the current attribute
"""
col = self.GetGridCursorCol()
attr = self.table._displayattrs[col]
frame = self.GetParent().GetParent().GetParent()
if attr is ipipe.noitem:
self.error_ou... | KeyboardInterrupt | dataset/ETHPy150Open ipython/ipython-py3k/IPython/deathrow/igrid.py/IGridGrid.sortattrasc |
4,848 | def sortattrdesc(self):
"""
Sort in descending order; sorting criteria is the current attribute
"""
col = self.GetGridCursorCol()
attr = self.table._displayattrs[col]
frame = self.GetParent().GetParent().GetParent()
if attr is ipipe.noitem:
self.error_... | KeyboardInterrupt | dataset/ETHPy150Open ipython/ipython-py3k/IPython/deathrow/igrid.py/IGridGrid.sortattrdesc |
4,849 | def _getvalue(self, row, col):
"""
Gets the text which is displayed at ``(row, col)``
"""
try:
value = self.table._displayattrs[col].value(self.table.items[row])
(align, width, text) = ipipe.xformat(value, "cell", self.maxchars)
except __HOLE__:
... | IndexError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/deathrow/igrid.py/IGridGrid._getvalue |
4,850 | def searchexpression(self, searchexp, startrow=None, search_forward=True ):
"""
Find by expression
"""
frame = self.GetParent().GetParent().GetParent()
if searchexp:
if search_forward:
if not startrow:
row = self.GetGridCursorRow()+... | KeyboardInterrupt | dataset/ETHPy150Open ipython/ipython-py3k/IPython/deathrow/igrid.py/IGridGrid.searchexpression |
4,851 | def search(self, searchtext, startrow=None, startcol=None, search_forward=True):
"""
search for ``searchtext``, starting in ``(startrow, startcol)``;
if ``search_forward`` is true the direction is "forward"
"""
searchtext = searchtext.lower()
if search_forward:
... | IndexError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/deathrow/igrid.py/IGridGrid.search |
4,852 | def key_pressed(self, event):
"""
Maps pressed keys to functions
"""
frame = self.GetParent().GetParent().GetParent()
frame.SetStatusText("")
sh = event.ShiftDown()
ctrl = event.ControlDown()
keycode = event.GetKeyCode()
if keycode == ord("P"):
... | IndexError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/deathrow/igrid.py/IGridGrid.key_pressed |
4,853 | def _doenter(self, value, *attrs):
"""
"enter" a special item resulting in a new notebook tab
"""
panel = self.GetParent()
nb = panel.GetParent()
frame = nb.GetParent()
current = nb.GetSelection()
count = nb.GetPageCount()
try: # if we want to ente... | TypeError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/deathrow/igrid.py/IGridGrid._doenter |
4,854 | def pickrowsattr(self, rows, col):
""""
pick one column from multiple rows
"""
values = []
try:
attr = self.table._displayattrs[col]
for row in rows:
try:
values.append(attr.value(self.table.items[row]))
... | KeyboardInterrupt | dataset/ETHPy150Open ipython/ipython-py3k/IPython/deathrow/igrid.py/IGridGrid.pickrowsattr |
4,855 | def refresh_interval(self, event):
table = self.notebook.GetPage(self.notebook.GetSelection()).grid.table
dlg = wx.TextEntryDialog(self, "Enter refresh interval (milliseconds):", "Refresh timer:", defaultValue=str(self.refresh_interval))
if dlg.ShowModal() == wx.ID_OK:
try:
... | ValueError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/deathrow/igrid.py/IGridFrame.refresh_interval |
4,856 | def get_user_names(self, fullname='', first_name='', last_name=''):
# Avoid None values
fullname = fullname or ''
first_name = first_name or ''
last_name = last_name or ''
if fullname and not (first_name or last_name):
try:
first_name, last_name = full... | ValueError | dataset/ETHPy150Open omab/python-social-auth/social/backends/base.py/BaseAuth.get_user_names |
4,857 | def merge(args):
"""
%prog merge map1 map2 map3 ...
Convert csv maps to bed format.
Each input map is csv formatted, for example:
ScaffoldID,ScaffoldPosition,LinkageGroup,GeneticPosition
scaffold_2707,11508,1,0
scaffold_2707,11525,1,1.2
scaffold_759,81336,1,9.7
"""
p = OptionP... | IndexError | dataset/ETHPy150Open tanghaibao/jcvi/assembly/allmaps.py/merge |
4,858 | def mergebed(args):
"""
%prog mergebed map1.bed map2.bed map3.bed ...
Combine bed maps to bed format, adding the map name.
"""
p = OptionParser(mergebed.__doc__)
p.add_option("-w", "--weightsfile", default="weights.txt",
help="Write weights to file")
p.set_outfile("out.bed"... | ValueError | dataset/ETHPy150Open tanghaibao/jcvi/assembly/allmaps.py/mergebed |
4,859 | @value.setter
def value(self, value):
if self._invalid:
raise ValueError(
'The value of invalid/unparseable cards cannot set. Either '
'delete this card from the header or replace it.')
if value is None:
value = ''
oldvalue = self._va... | ValueError | dataset/ETHPy150Open spacetelescope/PyFITS/pyfits/card.py/Card.value |
4,860 | def _split(self):
"""
Split the card image between the keyword and the rest of the card.
"""
if self._image is not None:
# If we already have a card image, don't try to rebuild a new card
# image, which self.image would do
image = self._image
... | ValueError | dataset/ETHPy150Open spacetelescope/PyFITS/pyfits/card.py/Card._split |
4,861 | def _fix_value(self):
"""Fix the card image for fixable non-standard compliance."""
value = None
keyword, valuecomment = self._split()
m = self._value_NFSC_RE.match(valuecomment)
# for the unparsable case
if m is None:
try:
value, comment = v... | ValueError | dataset/ETHPy150Open spacetelescope/PyFITS/pyfits/card.py/Card._fix_value |
4,862 | def _int_or_float(s):
"""
Converts an a string to an int if possible, or to a float.
If the string is neither a string or a float a value error is raised.
"""
if isinstance(s, float):
# Already a float so just pass through
return s
try:
return int(s)
except (ValueE... | TypeError | dataset/ETHPy150Open spacetelescope/PyFITS/pyfits/card.py/_int_or_float |
4,863 | def get_page(self, suffix):
"""
A function which will be monkeypatched onto the request to get the current
integer representing the current page.
"""
try:
return int(self.GET['page%s' % suffix])
except (KeyError, ValueError, __HOLE__):
return 1 | TypeError | dataset/ETHPy150Open amarandon/smeuhsocial/apps/pagination/middleware.py/get_page |
4,864 | def paginate(request, queryset, results_per_page=20):
paginator = Paginator(queryset, results_per_page)
try:
page = paginator.page(int(request.GET.get('page', 1)))
except InvalidPage:
raise Http404("Sorry, that page of results does not exist.")
except __HOLE__:
raise PermissionD... | ValueError | dataset/ETHPy150Open mozilla/source/source/base/utils.py/paginate |
4,865 | def _extract_metrics(self, results, metrics, tag_by, wmi, tag_queries, constant_tags):
if len(results) > 1 and tag_by is None:
raise Exception('WMI query returned multiple rows but no `tag_by` value was given. '
'metrics=%s' % metrics)
for res in results:
... | AttributeError | dataset/ETHPy150Open serverdensity/sd-agent/checks.d/wmi_check.py/WMICheck._extract_metrics |
4,866 | def __hash_new(name, string=''):
"""new(name, string='') - Return a new hashing object using the named algorithm;
optionally initialized with a string.
"""
try:
return _hashlib.new(name, string)
except __HOLE__:
# If the _hashlib module (OpenSSL) doesn't support the named
# h... | ValueError | dataset/ETHPy150Open babble/babble/include/jython/Lib/hashlib.py/__hash_new |
4,867 | def save(description, branchname, bugnumber, gitflow=False):
try:
data = json.load(open(os.path.expanduser(config.SAVE_FILE)))
except __HOLE__:
data = {}
repo_name = get_repo_name()
data['%s:%s' % (repo_name, branchname)] = {
'description': description,
'bugnumber': bugnu... | IOError | dataset/ETHPy150Open peterbe/bgg/bgg/lib/start.py/save |
4,868 | @register.filter
def best_selling_products_list(count):
"""Get a list of best selling products"""
try:
ct = int(count)
except __HOLE__:
ct = config_value('PRODUCT','NUM_PAGINATED')
return bestsellers(ct) | ValueError | dataset/ETHPy150Open dokterbob/satchmo/satchmo/apps/product/templatetags/satchmo_product.py/best_selling_products_list |
4,869 | @register.filter
def recent_products_list(count):
"""Get a list of recent products"""
try:
ct = int(count)
except __HOLE__:
ct = config_value('PRODUCT','NUM_PAGINATED')
query = Product.objects.recent_by_site()
return query[:ct] | ValueError | dataset/ETHPy150Open dokterbob/satchmo/satchmo/apps/product/templatetags/satchmo_product.py/recent_products_list |
4,870 | def get_tokens_unprocessed(self, text):
"""
Since ERB doesn't allow "<%" and other tags inside of ruby
blocks we have to use a split approach here that fails for
that too.
"""
tokens = self._block_re.split(text)
tokens.reverse()
state = idx = 0
try... | IndexError | dataset/ETHPy150Open adieu/allbuttonspressed/pygments/lexers/templates.py/ErbLexer.get_tokens_unprocessed |
4,871 | def spider(init, max=-1, ignore_qs=False, post_func=None,
excluded_func=None, hosts=None):
"""
Spider a request by following some links.
init - The initial request(s)
max - The maximum of request to execute
post_func - A hook to be executed after each new page fetched
hosts - A list... | KeyboardInterrupt | dataset/ETHPy150Open tweksteen/burst/burst/spider.py/spider |
4,872 | def test_package_import__semantics(self):
# Generate a couple of broken modules to try importing.
# ...try loading the module when there's a SyntaxError
self.rewrite_file('for')
try: __import__(self.module_name)
except SyntaxError: pass
else: raise RuntimeError, 'Failed... | NameError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_pkgimport.py/TestImport.test_package_import__semantics |
4,873 | def execute(cmd, cmd_timeout, sigterm_timeout, sigkill_timeout,
proc_poll_interval):
start_time = time.time()
returncode = -1
stdout = ''
stderr = ''
try:
proc = subprocess.Popen(u' '.join(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
except Exception:
... | OSError | dataset/ETHPy150Open DataDog/dogapi/src/dogshell/wrap.py/execute |
4,874 | def render(self, context):
try:
obj = template.resolve_variable(self.object_name, context)
template_name = '%s.%s.html' % (obj._meta.app_label, obj._meta.module_name)
template_list = [
'%s/%s' % (self.template_dir, template_name),
'%s/default.h... | AttributeError | dataset/ETHPy150Open hzlf/openbroadcast/website/apps/tools/templatetags/objectutils.py/RenderTemplateNode.render |
4,875 | def process_complex_get(req_dict):
mime_type = "application/json"
# Parse out params into single dict-GET data not in body
param_dict = {}
try:
param_dict = req_dict['body']
except __HOLE__:
pass # no params in the body
param_dict.update(req_dict['params'])
format = param... | KeyError | dataset/ETHPy150Open adlnet/ADL_LRS/lrs/utils/req_process.py/process_complex_get |
4,876 | def build_response(stmt_result):
sha2s = []
mime_type = "application/json"
if isinstance(stmt_result, dict):
statements = stmt_result['statements']
else:
statements = json.loads(stmt_result)['statements']
# Iterate through each attachment in each statement
for stmt in statements... | OSError | dataset/ETHPy150Open adlnet/ADL_LRS/lrs/utils/req_process.py/build_response |
4,877 | def activity_profile_get(req_dict):
# Instantiate ActivityProfile
ap = ActivityProfileManager()
# Get profileId and activityId
profile_id = req_dict['params'].get('profileId', None) if 'params' in req_dict else None
activity_id = req_dict['params'].get('activityId', None) if 'params' in req_dict els... | IOError | dataset/ETHPy150Open adlnet/ADL_LRS/lrs/utils/req_process.py/activity_profile_get |
4,878 | def read_images(path, image_size=None):
"""Reads the images in a given folder, resizes images on the fly if size is given.
Args:
path: Path to a folder with subfolders representing the subjects (persons).
sz: A tuple with the size Resizes
Returns:
A list [X, y, folder_names]
... | IOError | dataset/ETHPy150Open bytefish/facerec/py/apps/videofacerec/simple_videofacerec.py/read_images |
4,879 | @register.tag('experiment')
def experiment(parser, token):
"""
Split Testing experiment tag has the following syntax :
{% experiment <experiment_name> <alternative> %}
experiment content goes here
{% endexperiment %}
If the alternative name is neither 'test' nor 'control' an exception... | ValueError | dataset/ETHPy150Open mixcloud/django-experiments/experiments/templatetags/experiments.py/experiment |
4,880 | def setdefault(self, key, x=None):
key = str(key).title()
try:
return self[key]
except __HOLE__:
self[key] = x
return x | KeyError | dataset/ETHPy150Open zynga/jasy/jasy/core/Types.py/CaseInsensitiveDict.setdefault |
4,881 | def post(self, request, *args, **kwargs):
self.mapper = self.get_mapper(self.model())
self.data = self.get_request_data()
try:
self.object = self.mapper._apply(self.data)
except __HOLE__ as e:
return self.post_invalid(e.error_dict)
return self.post_valid... | ValidationError | dataset/ETHPy150Open funkybob/django-nap/nap/rest/views.py/ListPostMixin.post |
4,882 | def put(self, request, *args, **kwargs):
self.object = self.get_object()
self.mapper = self.get_mapper(self.object)
self.data = self.get_request_data({})
try:
self.mapper._apply(self.data)
except __HOLE__ as e:
return self.put_invalid(e.error_dict)
... | ValidationError | dataset/ETHPy150Open funkybob/django-nap/nap/rest/views.py/ObjectPutMixin.put |
4,883 | def patch(self, request, *args, **kwargs):
self.object = self.get_object()
self.mapper = self.get_mapper(self.object)
self.data = self.get_request_data({})
try:
self.mapper._patch(self.data)
except __HOLE__ as e:
return self.patch_invalid(e.error_dict)
... | ValidationError | dataset/ETHPy150Open funkybob/django-nap/nap/rest/views.py/ObjectPatchMixin.patch |
4,884 | def showmessage(message, mapping):
try:
del (mapping['self'])
except (__HOLE__, ):
pass
items = mapping.items()
items.sort()
print '### %s' % (message, )
for k, v in items:
print ' %s:%s' % (k, v) | KeyError | dataset/ETHPy150Open CarterBain/Medici/ib/client/sync_wrapper.py/showmessage |
4,885 | def can_connect(port):
sock = socket.socket()
sock.settimeout(0.1) # Always localhost, should be wayy faster than this.
try:
sock.connect(('127.0.0.1', port))
return True
except __HOLE__:
return False | OSError | dataset/ETHPy150Open dcos/dcos/pytest/test_ssh_integration.py/can_connect |
4,886 | def lineReceived(self, line):
parts = line.split(',')
if len(parts) != 2:
self.invalidQuery()
else:
try:
portOnServer, portOnClient = map(int, parts)
except __HOLE__:
self.invalidQuery()
else:
if _MIN... | ValueError | dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/protocols/ident.py/IdentServer.lineReceived |
4,887 | def _end(self):
"""End the orchestration play by waiting for all the action threads to
complete."""
for t in self._threads:
try:
while not self._error and t.isAlive():
t.join(1)
except __HOLE__:
self._error = (exceptions... | KeyboardInterrupt | dataset/ETHPy150Open signalfx/maestro-ng/maestro/plays/__init__.py/BaseOrchestrationPlay._end |
4,888 | def _close(self):
"""
Disconnect from Riemann.
"""
try:
self.client.disconnect()
except __HOLE__:
pass | AttributeError | dataset/ETHPy150Open BrightcoveOS/Diamond/src/diamond/handler/riemann.py/RiemannHandler._close |
4,889 | def _process_run_command_output(raw_output):
if raw_output is None:
return raw_output
try:
_output = raw_output.decode('utf-8')
except __HOLE__:
return raw_output
else:
return _output[:-1] | ValueError | dataset/ETHPy150Open sodastsai/taskr/taskr/contrib/system/__init__.py/_process_run_command_output |
4,890 | def get_model_parser(top_rule, comments_model, **kwargs):
"""
Creates model parser for the given language.
"""
class TextXModelParser(Parser):
"""
Parser created from textual textX language description.
Semantic actions for this parser will construct object
graph represe... | AttributeError | dataset/ETHPy150Open igordejanovic/textX/textx/model.py/get_model_parser |
4,891 | def parse_tree_to_objgraph(parser, parse_tree):
"""
Transforms parse_tree to object graph representing model in a
new language.
"""
metamodel = parser.metamodel
def process_match(nt):
"""
Process subtree for match rules.
"""
if isinstance(nt, Terminal):
... | TypeError | dataset/ETHPy150Open igordejanovic/textX/textx/model.py/parse_tree_to_objgraph |
4,892 | def _RegistryQuery(key, value=None):
"""Use reg.exe to read a particular key through _RegistryQueryBase.
First tries to launch from %WinDir%\Sysnative to avoid WoW64 redirection. If
that fails, it falls back to System32. Sysnative is available on Vista and
up and available on Windows Server 2003 and XP throug... | OSError | dataset/ETHPy150Open adobe/brackets-shell/gyp/pylib/gyp/MSVSVersion.py/_RegistryQuery |
4,893 | def _trans_binary(self, value):
""" Given value is expected to be a binary - 0/1 """
try:
conv = int(value)
except __HOLE__:
return 0
if conv not in [0, 1]:
return 0
return conv | ValueError | dataset/ETHPy150Open Yelp/fullerite/src/diamond/collectors/icinga_stats/icinga_stats.py/IcingaStatsCollector._trans_binary |
4,894 | def _trans_dtime(self, value):
""" Translate scheduled downtime """
try:
conv = int(value)
except __HOLE__:
return 0
if conv < 1:
return 0
return conv | ValueError | dataset/ETHPy150Open Yelp/fullerite/src/diamond/collectors/icinga_stats/icinga_stats.py/IcingaStatsCollector._trans_dtime |
4,895 | def get_field(self, field_name, args, kwargs):
try:
return super(PartialFormatter, self).get_field(field_name,
args,
kwargs)
except (KeyError, __HOLE__):
return N... | AttributeError | dataset/ETHPy150Open kwikteam/phy/phy/utils/event.py/PartialFormatter.get_field |
4,896 | def format_field(self, value, spec):
if value is None:
return '?'
try:
return super(PartialFormatter, self).format_field(value, spec)
except __HOLE__:
return '?' | ValueError | dataset/ETHPy150Open kwikteam/phy/phy/utils/event.py/PartialFormatter.format_field |
4,897 | def convert_linkable_to_choice(linkable):
key = get_composite_key(linkable)
try:
value = u'%s (%s)' % (force_text(linkable), linkable.get_absolute_url())
except __HOLE__:
value = force_text(linkable)
return (key, value) | AttributeError | dataset/ETHPy150Open fusionbox/django-widgy/widgy/models/links.py/convert_linkable_to_choice |
4,898 | def _unicodeExpand(s):
try:
return r_unicodeEscape.sub(
lambda m: unichr(int(m.group(0)[2:], 16)), s)
except __HOLE__:
warnings.warn(
'Encountered a unicode char > 0xFFFF in a narrow python build. '
'Trying to degrade gracefully, bu... | ValueError | dataset/ETHPy150Open RDFLib/rdflib/rdflib/py3compat.py/_unicodeExpand |
4,899 | def copyDirectory(src, dest):
try:
shutil.copytree(src, dest)
except shutil.Error as e:
print('Error: %s' % e)
except __HOLE__ as e:
print('Error: %s' % e) | OSError | dataset/ETHPy150Open ActiDoo/gamification-engine/gengine/scripts/quickstart.py/copyDirectory |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.