Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
6,100 | def __init__(self, message):
try:
self.media_id = message.pop('MediaId')
self.format = message.pop('Format')
self.recognition = message.pop('Recognition', None)
except __HOLE__:
raise ParseError()
super(VoiceMessage, self).__init__(message) | KeyError | dataset/ETHPy150Open wechat-python-sdk/wechat-python-sdk/wechat_sdk/messages.py/VoiceMessage.__init__ |
6,101 | @property
def state(self):
if self._cursor == -1:
raise exceptions.RoboError('No state')
try:
return self._states[self._cursor]
except __HOLE__:
raise exceptions.RoboError('Index out of range') | IndexError | dataset/ETHPy150Open jmcarp/robobrowser/robobrowser/browser.py/RoboBrowser.state |
6,102 | @property
def find(self):
"""See ``BeautifulSoup::find``."""
try:
return self.parsed.find
except __HOLE__:
raise exceptions.RoboError | AttributeError | dataset/ETHPy150Open jmcarp/robobrowser/robobrowser/browser.py/RoboBrowser.find |
6,103 | @property
def find_all(self):
"""See ``BeautifulSoup::find_all``."""
try:
return self.parsed.find_all
except __HOLE__:
raise exceptions.RoboError | AttributeError | dataset/ETHPy150Open jmcarp/robobrowser/robobrowser/browser.py/RoboBrowser.find_all |
6,104 | @property
def select(self):
"""See ``BeautifulSoup::select``."""
try:
return self.parsed.select
except __HOLE__:
raise exceptions.RoboError | AttributeError | dataset/ETHPy150Open jmcarp/robobrowser/robobrowser/browser.py/RoboBrowser.select |
6,105 | def follow_link(self, link, **kwargs):
"""Click a link.
:param Tag link: Link to click
:param kwargs: Keyword arguments to `Session::send`
"""
try:
href = link['href']
except __HOLE__:
raise exceptions.RoboError('Link element must have "href" '
... | KeyError | dataset/ETHPy150Open jmcarp/robobrowser/robobrowser/browser.py/RoboBrowser.follow_link |
6,106 | def _internal_increment(self, namespace, request):
"""Internal function for incrementing from a MemcacheIncrementRequest.
Args:
namespace: A string containing the namespace for the request, if any.
Pass an empty string if there is no namespace.
request: A MemcacheIncrementRequest instance.
... | ValueError | dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/google/appengine/api/memcache/memcache_stub.py/MemcacheServiceStub._internal_increment |
6,107 | def load_resource(res):
try:
f = file(join(dirname(__file__), 'shared', res))
except __HOLE__:
return ''
try:
return f.read()
finally:
f.close() | IOError | dataset/ETHPy150Open limodou/uliweb/uliweb/lib/werkzeug/debug/render.py/load_resource |
6,108 | def color_palette(palette=None, n_colors=None, desat=None):
"""Return a list of colors defining a color palette.
Availible seaborn palette names:
deep, muted, bright, pastel, dark, colorblind
Other options:
hls, husl, any named matplotlib palette, list of colors
Calling this function ... | ValueError | dataset/ETHPy150Open mwaskom/seaborn/seaborn/palettes.py/color_palette |
6,109 | def _curl_process_params(body, content_type, query_params):
extra = None
modifier = None
if query_params:
try:
query_params = urlencode([(k, v.encode('utf8')) for k, v in query_params.items()])
except TypeError:
pass
query_params = '?' + str(query_params)
... | AttributeError | dataset/ETHPy150Open django-silk/silk/silk/code_generation/curl.py/_curl_process_params |
6,110 | def get_conn():
'''
Return a conn object for the passed VM data
'''
driver = get_driver(Provider.CLOUDSTACK)
verify_ssl_cert = config.get_cloud_config_value('verify_ssl_cert',
get_configured_provider(),
__opts__,
default=True,
search_global=False)
... | AttributeError | dataset/ETHPy150Open saltstack/salt/salt/cloud/clouds/cloudstack.py/get_conn |
6,111 | def get_project(conn, vm_):
'''
Return the project to use.
'''
try:
projects = conn.ex_list_projects()
except __HOLE__:
# with versions <0.15 of libcloud this is causing an AttributeError.
log.warning('Cannot get projects, you may need to update libcloud to 0.15 or later')
... | AttributeError | dataset/ETHPy150Open saltstack/salt/salt/cloud/clouds/cloudstack.py/get_project |
6,112 | def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'clo... | AttributeError | dataset/ETHPy150Open saltstack/salt/salt/cloud/clouds/cloudstack.py/create |
6,113 | def filetype(self,fname=None):
""" checks file type of file, returning:
'escan' for Epics Scan
None otherwise
"""
try:
u = open(fname,'r')
t = u.readline()
u.close()
if 'Epics Scan' in t: return 'escan'
except __HOLE_... | IOError | dataset/ETHPy150Open xraypy/xraylarch/plugins/io/gse_escan.py/EscanData.filetype |
6,114 | def _getline(self,lines):
"return mode keyword,"
inp = lines.pop()
is_comment = True
mode = None
if len(inp) > 2:
is_comment = inp[0] in (';','#')
s = inp[1:].strip().lower()
for j in self.mode_names:
if s.startswith(j):
... | ValueError | dataset/ETHPy150Open xraypy/xraylarch/plugins/io/gse_escan.py/EscanData._getline |
6,115 | def read_ascii(self,fname=None):
"""read ascii data file"""
lines = self._open_ascii(fname=fname)
if lines is None: return -1
maxlines = len(lines)
iline = 1
ndata_points = None
tmp_dat = []
tmp_y = []
col_details = []
col_legend = None... | IndexError | dataset/ETHPy150Open xraypy/xraylarch/plugins/io/gse_escan.py/EscanData.read_ascii |
6,116 | def clean_smd(self):
# Check that the SMD is an SMD of the given ANC.
try:
smd = "%02d" % int(self.cleaned_data['smd'])
except __HOLE__:
raise forms.ValidationError("An SMD looks like 01, 02, ...")
anc = self.cleaned_data['anc']
smd_list = anc_data[anc[0]]['ancs'][anc[1]]['smds'].keys()
if smd not in ... | ValueError | dataset/ETHPy150Open codefordc/ancfinder/ancfindersite/backend_views.py/SMDUpdateForm.clean_smd |
6,117 | def wrap_elasticluster(args):
"""Wrap elasticluster commands to avoid need to call separately.
- Uses .bcbio/elasticluster as default configuration location.
- Sets NFS client parameters for elasticluster Ansible playbook. Uses async
clients which provide better throughput on reads/writes:
http... | SystemExit | dataset/ETHPy150Open chapmanb/bcbio-nextgen-vm/bcbiovm/aws/common.py/wrap_elasticluster |
6,118 | def __getattr__(self, name):
path = self._config._normalize_path(".".join((self._name, name)))
try:
return self._config._settings[path]
except __HOLE__:
group_path = path + "."
keys = self._config._settings.keys()
if any(1 for k in keys if k.starts... | KeyError | dataset/ETHPy150Open progrium/ginkgo/ginkgo/config.py/Group.__getattr__ |
6,119 | @property
def nodes_authorized(self):
"""Get authorized, non-deleted nodes. Returns an empty list if the
attached add-on does not include a node model.
"""
try:
schema = self.config.settings_models['node']
except __HOLE__:
return []
return [
... | KeyError | dataset/ETHPy150Open CenterForOpenScience/osf.io/website/addons/base/__init__.py/AddonUserSettingsBase.nodes_authorized |
6,120 | @must_be_logged_in
def revoke_oauth_access(self, external_account, auth, save=True):
"""Revoke all access to an ``ExternalAccount``.
TODO: This should accept node and metadata params in the future, to
allow fine-grained revocation of grants. That's not yet been needed,
so it... | AttributeError | dataset/ETHPy150Open CenterForOpenScience/osf.io/website/addons/base/__init__.py/AddonOAuthUserSettingsBase.revoke_oauth_access |
6,121 | def verify_oauth_access(self, node, external_account, metadata=None):
"""Verify that access has been previously granted.
If metadata is not provided, this checks only if the node can access the
account. This is suitable to check to see if the node's addon settings
is still connected to ... | KeyError | dataset/ETHPy150Open CenterForOpenScience/osf.io/website/addons/base/__init__.py/AddonOAuthUserSettingsBase.verify_oauth_access |
6,122 | def merge(self, user_settings):
"""Merge `user_settings` into this instance"""
if user_settings.__class__ is not self.__class__:
raise TypeError('Cannot merge different addons')
for node_id, data in user_settings.oauth_grants.iteritems():
if node_id not in self.oauth_gra... | KeyError | dataset/ETHPy150Open CenterForOpenScience/osf.io/website/addons/base/__init__.py/AddonOAuthUserSettingsBase.merge |
6,123 | def after_fork(self, node, fork, user, save=True):
"""After forking, copy user settings if the user is the one who authorized
the addon.
:return: A tuple of the form (cloned_settings, message)
"""
clone, _ = super(AddonOAuthNodeSettingsBase, self).after_fork(
node=no... | AttributeError | dataset/ETHPy150Open CenterForOpenScience/osf.io/website/addons/base/__init__.py/AddonOAuthNodeSettingsBase.after_fork |
6,124 | def uriparse(uri, strict=False):
"""Given a valid URI, return a 5-tuple of (scheme, authority, path,
query, fragment). The query part is a URLQuery object, the rest are
strings.
Raises ValueError if URI is malformed.
"""
key = uri, strict
try:
scheme, authority, path, q, fragment = _... | KeyError | dataset/ETHPy150Open kdart/pycopia/aid/pycopia/urlparse.py/uriparse |
6,125 | def queryparse(query, evaluator=lambda x: x):
q = URLQuery()
parts = query.split("&")
for part in parts:
if part:
try:
l, r = part.split("=", 1)
except __HOLE__:
l, r = part, ""
key = unquote_plus(l)
val = evaluator(unqu... | ValueError | dataset/ETHPy150Open kdart/pycopia/aid/pycopia/urlparse.py/queryparse |
6,126 | def getlist(self, key):
try:
val = dict.__getitem__(self, key)
except __HOLE__:
return []
if type(val) is list:
return val
else:
return [val] | KeyError | dataset/ETHPy150Open kdart/pycopia/aid/pycopia/urlparse.py/URLQuery.getlist |
6,127 | def unquote(s):
"""unquote('abc%20def') -> 'abc def'."""
res = s.split('%')
for i in xrange(1, len(res)):
item = res[i]
try:
res[i] = _hextochr[item[:2]] + item[2:]
except __HOLE__:
res[i] = '%' + item
return "".join(res) | KeyError | dataset/ETHPy150Open kdart/pycopia/aid/pycopia/urlparse.py/unquote |
6,128 | def quote(s, safe = '/'):
"""quote('abc def') -> 'abc%20def'
Each part of a URL, e.g. the path info, the query, etc., has a
different set of reserved characters that must be quoted.
RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
the following reserved characters.
reserved ... | KeyError | dataset/ETHPy150Open kdart/pycopia/aid/pycopia/urlparse.py/quote |
6,129 | def urlencode(query, doseq=0):
"""Encode a sequence of two-element tuples or dictionary into a URL
query string.
If any values in the query arg are sequences and doseq is true, each
sequence element is converted to a separate parameter.
If the query arg is a sequence of two-element tuples, the ord... | TypeError | dataset/ETHPy150Open kdart/pycopia/aid/pycopia/urlparse.py/urlencode |
6,130 | def set(self, url, strict=True):
if isinstance(url, basestring):
if isinstance(url, unicode):
# URL's are defined to be in the ASCII character set.
url = quote(url, ";/?:@&=+$,")
self.clear(strict)
try:
self._parse(url, strict)
... | ValueError | dataset/ETHPy150Open kdart/pycopia/aid/pycopia/urlparse.py/UniversalResourceLocator.set |
6,131 | def assign_sizes(data, aes):
"""Assigns size to the given data based on the aes and adds the right legend
Parameters
----------
data : DataFrame
dataframe which should have sizes assigned to
aes : aesthetic
mapping, including a mapping from sizes to variable
Returns
-------... | ValueError | dataset/ETHPy150Open yhat/ggplot/ggplot/components/size.py/assign_sizes |
6,132 | def tearDown(self):
try:
rmtree(self.dir)
except __HOLE__ as e:
# If directory already deleted, keep going
if e.errno not in (errno.ENOENT, errno.EACCES, errno.EPERM):
raise e | OSError | dataset/ETHPy150Open OpenMDAO/OpenMDAO/openmdao/recorders/test/test_dump.py/TestDumpRecorder.tearDown |
6,133 | @c3bottles.route("/create", methods=("GET", "POST"))
@c3bottles.route("/create/<string:lat>/<string:lng>", methods=("GET", "POST"))
@login_required
def create_dp(
number=None, description=None, lat=None,
lng=None, level=None, crates=None, errors=None,
success=None, center_lat=None, center_lng=No... | ValueError | dataset/ETHPy150Open der-michik/c3bottles/view/create.py/create_dp |
6,134 | def _get_next_line_number(self, class_name):
if self.combined or self.streaming:
# This has an obvious side effect. Oh well.
self.combined_line_number += 1
return self.combined_line_number
else:
try:
return len(self._test_cases[class_name])... | KeyError | dataset/ETHPy150Open mblayman/tappy/tap/tracker.py/Tracker._get_next_line_number |
6,135 | def compile(self, func, args, return_type=None, flags=DEFAULT_FLAGS):
"""
Compile the function or retrieve an already compiled result
from the cache.
"""
cache_key = (func, args, return_type, flags)
try:
cr = self.cr_cache[cache_key]
except __HOLE__:
... | KeyError | dataset/ETHPy150Open numba/numba/numba/tests/support.py/CompilationCache.compile |
6,136 | def reset_module_warnings(self, module):
"""
Reset the warnings registry of a module. This can be necessary
as the warnings module is buggy in that regard.
See http://bugs.python.org/issue4180
"""
if isinstance(module, str):
module = sys.modules[module]
... | AttributeError | dataset/ETHPy150Open numba/numba/numba/tests/support.py/TestCase.reset_module_warnings |
6,137 | def assertPreciseEqual(self, first, second, prec='exact', ulps=1,
msg=None, ignore_sign_on_zero=False,
abs_tol=None
):
"""
Versatile equality testing function with more built-in checks than
standard assertEqual().
... | AssertionError | dataset/ETHPy150Open numba/numba/numba/tests/support.py/TestCase.assertPreciseEqual |
6,138 | def _assertPreciseEqual(self, first, second, prec='exact', ulps=1,
msg=None, ignore_sign_on_zero=False,
abs_tol=None):
"""Recursive workhorse for assertPreciseEqual()."""
def _assertNumberEqual(first, second, delta=None):
if (delta is ... | TypeError | dataset/ETHPy150Open numba/numba/numba/tests/support.py/TestCase._assertPreciseEqual |
6,139 | def _create_trashcan_dir():
try:
os.mkdir(_trashcan_dir)
except __HOLE__ as e:
if e.errno != errno.EEXIST:
raise | OSError | dataset/ETHPy150Open numba/numba/numba/tests/support.py/_create_trashcan_dir |
6,140 | def _purge_trashcan_dir():
freshness_threshold = time.time() - _trashcan_timeout
for fn in sorted(os.listdir(_trashcan_dir)):
fn = os.path.join(_trashcan_dir, fn)
try:
st = os.stat(fn)
if st.st_mtime < freshness_threshold:
shutil.rmtree(fn, ignore_errors=T... | OSError | dataset/ETHPy150Open numba/numba/numba/tests/support.py/_purge_trashcan_dir |
6,141 | def handle(self, **options):
address = options.get('address')
# Break address into host:port
if address:
if ':' in address:
host, port = address.split(':', 1)
port = int(port)
else:
host = address
port = Non... | KeyError | dataset/ETHPy150Open dropbox/nsot/nsot/management/commands/start.py/Command.handle |
6,142 | def dump(start=0):
check_for_fields()
try:
lastdump = tyrant["lastdump"]
except __HOLE__:
lastdump = "*"
filecount = 1
itemcount = 1
filename = FILENAME_TEMPLATE % (SLAVE_NAME, now, filecount)
writer = csv.writer(open(filename, "w"))
with solr.pooled_connection(fp._fp_sol... | KeyError | dataset/ETHPy150Open echonest/echoprint-server/replication/slave_dump.py/dump |
6,143 | @authenticated_rest_api_view
@has_request_variables
def api_freshdesk_webhook(request, user_profile, stream=REQ(default='')):
try:
payload = ujson.loads(request.body)
ticket_data = payload["freshdesk_webhook"]
except ValueError:
return json_error("Malformed JSON input")
required_key... | ValueError | dataset/ETHPy150Open zulip/zulip/zerver/views/webhooks/freshdesk.py/api_freshdesk_webhook |
6,144 | def read(self):
"""
Read a simple PNG file, return width, height, pixels and image metadata
This function is a very early prototype with limited flexibility
and excessive use of memory.
"""
signature = self.file.read(8)
if (signature != struct.pack("8B", 137, 80,... | ValueError | dataset/ETHPy150Open ardekantur/pyglet/pyglet/image/codecs/pypng.py/Reader.read |
6,145 | @classmethod
def get(cls, uid, safe=False):
"""
params:
uid - the user id which to fetch
safe - return users without secure fields like salt and hash
db - provide your own instantiated lazydb.Db() connector
"""
if uid is not None:
users... | KeyError | dataset/ETHPy150Open mekarpeles/waltz/waltz/__init__.py/User.get |
6,146 | @classmethod
def delete(cls, uid):
users = cls.db().get(cls.udb, default={}, touch=True)
try:
del users[uid]
return cls.db().put(cls.udb, users)
except __HOLE__:
return False | KeyError | dataset/ETHPy150Open mekarpeles/waltz/waltz/__init__.py/User.delete |
6,147 | def parse():
optParser = getOptParser()
opts,args = optParser.parse_args()
encoding = "utf8"
try:
f = args[-1]
# Try opening from the internet
if f.startswith('http://'):
try:
import urllib.request, urllib.parse, urllib.error, cgi
f = ... | IOError | dataset/ETHPy150Open html5lib/html5lib-python/parse.py/parse |
6,148 | def test_create_tags_invalid_parameters(self):
# NOTE(ft): check tag validity checks
self.assert_execution_error('InvalidParameterValue', 'CreateTags',
{'ResourceId.1': fakes.ID_EC2_VPC_1,
'Tag.1.Value': ''})
self.assert_e... | AttributeError | dataset/ETHPy150Open openstack/ec2-api/ec2api/tests/unit/test_tag.py/TagTestCase.test_create_tags_invalid_parameters |
6,149 | def get_test_data_upload(creator, dataset, filename=TEST_DATA_FILENAME, encoding='utf8'):
# Ensure panda subdir has been created
try:
os.mkdir(settings.MEDIA_ROOT)
except __HOLE__:
pass
src = os.path.join(TEST_DATA_PATH, filename)
dst = os.path.join(settings.MEDIA_ROOT, filename)
... | OSError | dataset/ETHPy150Open pandaproject/panda/panda/tests/utils.py/get_test_data_upload |
6,150 | def get_test_related_upload(creator, dataset, filename=TEST_DATA_FILENAME):
# Ensure panda subdir has been created
try:
os.mkdir(settings.MEDIA_ROOT)
except __HOLE__:
pass
src = os.path.join(TEST_DATA_PATH, filename)
dst = os.path.join(settings.MEDIA_ROOT, filename)
copyfile(src... | OSError | dataset/ETHPy150Open pandaproject/panda/panda/tests/utils.py/get_test_related_upload |
6,151 | def get_first(self, label=None, fs=None, aspace=None):
try:
return next(self.select(label, fs, aspace))
except __HOLE__:
raise ValueError('No annotations match those criteria') | StopIteration | dataset/ETHPy150Open cidles/graf-python/src/graf/annotations.py/AnnotationList.get_first |
6,152 | def remove(self, ann):
"""Remove the given C{Annotation} object.
:param a: Annotation
"""
try:
return self._elements.remove(ann)
except __HOLE__:
print('Error: Annotation not in set') | ValueError | dataset/ETHPy150Open cidles/graf-python/src/graf/annotations.py/AnnotationSpace.remove |
6,153 | def _resolve_fs(self, path, create=False):
"""
Resolves a list of keys to this or a descendent feature structure.
"""
fs = self
for name in path:
try:
fs = fs._elements[name]
except __HOLE__:
if create:
... | KeyError | dataset/ETHPy150Open cidles/graf-python/src/graf/annotations.py/FeatureStructure._resolve_fs |
6,154 | def _parse_key(self, key, create=False):
try:
key = key.strip('/').split('/')
except __HOLE__:
# assume key is already list of path elements
pass
return self._resolve_fs(key[:-1], create), key[-1] | AttributeError | dataset/ETHPy150Open cidles/graf-python/src/graf/annotations.py/FeatureStructure._parse_key |
6,155 | def __contains__(self, key):
try:
fs, key = self._parse_key(key)
except __HOLE__:
return False
return key in fs._elements | KeyError | dataset/ETHPy150Open cidles/graf-python/src/graf/annotations.py/FeatureStructure.__contains__ |
6,156 | def get(self, key, default=None):
try:
return self[key]
except __HOLE__:
return default | KeyError | dataset/ETHPy150Open cidles/graf-python/src/graf/annotations.py/FeatureStructure.get |
6,157 | def pop(self, key, default=None):
try:
fs, key = self._parse_key(key)
return fs._elements.pop(key, default)
except __HOLE__:
return default | KeyError | dataset/ETHPy150Open cidles/graf-python/src/graf/annotations.py/FeatureStructure.pop |
6,158 | def __eq__(self, other):
"""
Equivalence is equivalent types (????)
"""
try:
return self.type == other.type
except __HOLE__:
return False | AttributeError | dataset/ETHPy150Open cidles/graf-python/src/graf/annotations.py/FeatureStructure.__eq__ |
6,159 | def subsumes(self, other):
for key, val in self.items():
try:
oval = other._elements[key]
except __HOLE__:
return False
if isinstance(val, FeatureStructure) and isinstance(oval, FeatureStructure):
if not val.subsumes(oval... | KeyError | dataset/ETHPy150Open cidles/graf-python/src/graf/annotations.py/FeatureStructure.subsumes |
6,160 | def json_request(self, method, url, **kwargs):
kwargs.setdefault('headers', {})
kwargs['headers'].setdefault('Content-Type', 'application/json')
kwargs['headers'].setdefault('Accept', 'application/json')
if 'data' in kwargs:
kwargs['data'] = jsonutils.dumps(kwargs['data'])
... | ValueError | dataset/ETHPy150Open openstack/python-monascaclient/monascaclient/common/http.py/HTTPClient.json_request |
6,161 | def get_woeid(location):
query = urllib.quote(location, '')
values = {
'app_id': YAHOO_APP_ID,
'query': query,
}
url = WHERE_API_QUERY_URL % values
response = requests.get(url)
data = json.loads(response.text)
try:
places = data['places']
if places['count... | KeyError | dataset/ETHPy150Open hacktoolkit/hacktoolkit/apis/yahoo/geo/geoplanet/geoplanet.py/get_woeid |
6,162 | def resolve_woeid(woeid):
values = {
'app_id': YAHOO_APP_ID,
'woeid': woeid
}
url = WHERE_API_RESOLVE_URL % values
response = requests.get(url)
data = json.loads(response.text)
try:
place = data['place']
place_name = place['name']
if place['admin1']:
... | KeyError | dataset/ETHPy150Open hacktoolkit/hacktoolkit/apis/yahoo/geo/geoplanet/geoplanet.py/resolve_woeid |
6,163 | def force_text(s, encoding="utf-8"):
if isinstance(s, six.text_type):
return s
try:
if not isinstance(s, six.string_types):
if six.PY3:
if isinstance(s, bytes):
s = six.text_type(s, encoding)
else:
s = six.text_t... | UnicodeDecodeError | dataset/ETHPy150Open cobrateam/django-htmlmin/htmlmin/util.py/force_text |
6,164 | def removeDuplicates_complicated(self, A):
"""
Two pointers algorithm, open_ptr & closed_ptr
:param A: a list of integers
:return: an integer
"""
length = len(A)
if length<=2:
return length
closed_ptr = 0
duplicate_count = 0... | IndexError | dataset/ETHPy150Open algorhythms/LeetCode/081 Remove Duplicates from Sorted Array II.py/Solution.removeDuplicates_complicated |
6,165 | def __init__(self, language=None):
'''
If a `language` identifier (such as 'en_US') is provided and a matching
language exists, it is selected. If an identifier is provided and no
matching language exists, a NoSuchLangError exception is raised by
self.select_language().
I... | IndexError | dataset/ETHPy150Open kivy/kivy/kivy/core/spelling/__init__.py/SpellingBase.__init__ |
6,166 | def human_to_bytes(hsize, kilo=1024):
'''
This function converts human-readable amounts of bytes to bytes.
It understands the following units :
- I{B} or no unit present for Bytes
- I{k}, I{K}, I{kB}, I{KB} for kB (kilobytes)
- I{m}, I{M}, I{mB}, I{MB} for MB (megabytes)
- I{... | ValueError | dataset/ETHPy150Open agrover/targetcli-fb/targetcli/ui_backstore.py/human_to_bytes |
6,167 | def ui_command_delete(self, name):
'''
Recursively deletes the storage object having the specified I{name}. If
there are LUNs using this storage object, they will be deleted too.
EXAMPLE
=======
B{delete mystorage}
-------------------
Deletes the storage ... | ValueError | dataset/ETHPy150Open agrover/targetcli-fb/targetcli/ui_backstore.py/UIBackstore.ui_command_delete |
6,168 | def _create_file(self, filename, size, sparse=True):
try:
f = open(filename, "w+")
except (OSError, __HOLE__):
raise ExecutionError("Could not open %s" % filename)
try:
if sparse:
try:
os.posix_fallocate(f.fileno(), 0, size)... | IOError | dataset/ETHPy150Open agrover/targetcli-fb/targetcli/ui_backstore.py/UIFileIOBackstore._create_file |
6,169 | def __init__(self, irc=None):
if irc is not None:
assert not irc.getCallback(self.name())
self.__parent = super(Owner, self)
self.__parent.__init__(irc)
# Setup command flood detection.
self.commands = ircutils.FloodQueue(conf.supybot.abuse.flood.interval())
c... | ValueError | dataset/ETHPy150Open ProgVal/Limnoria/plugins/Owner/plugin.py/Owner.__init__ |
6,170 | def _connect(self, network, serverPort=None, password='', ssl=False):
try:
group = conf.supybot.networks.get(network)
(server, port) = group.servers()[0]
except (registry.NonExistentRegistryEntry, __HOLE__):
if serverPort is None:
raise ValueError('con... | IndexError | dataset/ETHPy150Open ProgVal/Limnoria/plugins/Owner/plugin.py/Owner._connect |
6,171 | def _loadPlugins(self, irc):
self.log.debug('Loading plugins (connecting to %s).', irc.network)
alwaysLoadImportant = conf.supybot.plugins.alwaysLoadImportant()
important = conf.supybot.commands.defaultPlugins.importantPlugins()
for (name, value) in conf.supybot.plugins.getValues(fullNam... | ImportError | dataset/ETHPy150Open ProgVal/Limnoria/plugins/Owner/plugin.py/Owner._loadPlugins |
6,172 | def load(self, irc, msg, args, optlist, name):
"""[--deprecated] <plugin>
Loads the plugin <plugin> from any of the directories in
conf.supybot.directories.plugins; usually this includes the main
installed directory and 'plugins' in the current directory.
--deprecated is necessa... | ImportError | dataset/ETHPy150Open ProgVal/Limnoria/plugins/Owner/plugin.py/Owner.load |
6,173 | def reload(self, irc, msg, args, name):
"""<plugin>
Unloads and subsequently reloads the plugin by name; use the 'list'
command to see a list of the currently loaded plugins.
"""
if ircutils.strEqual(name, self.name()):
irc.error('You can\'t reload the %s plugin.' % ... | ImportError | dataset/ETHPy150Open ProgVal/Limnoria/plugins/Owner/plugin.py/Owner.reload |
6,174 | def defaultcapability(self, irc, msg, args, action, capability):
"""{add|remove} <capability>
Adds or removes (according to the first argument) <capability> from the
default capabilities given to users (the configuration variable
supybot.capabilities stores these).
"""
i... | KeyError | dataset/ETHPy150Open ProgVal/Limnoria/plugins/Owner/plugin.py/Owner.defaultcapability |
6,175 | def enable(self, irc, msg, args, plugin, command):
"""[<plugin>] <command>
Enables the command <command> for all users. If <plugin>
if given, only enables the <command> from <plugin>. This command is
the inverse of disable.
"""
try:
if plugin:
... | KeyError | dataset/ETHPy150Open ProgVal/Limnoria/plugins/Owner/plugin.py/Owner.enable |
6,176 | @register.tag(name="render_placeholder")
def do_render_placeholder(parser, token):
try:
tag_name, id_placeholder = token.split_contents()
except __HOLE__:
raise template.TemplateSyntaxError("%r tag requires a single argument" % token.contents.split()[0])
if not (id_placeholder[0] == id_plac... | ValueError | dataset/ETHPy150Open ionyse/ionyweb/ionyweb/website/templatetags/placeholder_tags.py/do_render_placeholder |
6,177 | def setup(self, environ=None):
'''Set up the :class:`.WsgiHandler` the first time this
middleware is accessed.
'''
from django.conf import settings
from django.core.wsgi import get_wsgi_application
#
try:
dotted = settings.WSGI_APPLICATION
exce... | AttributeError | dataset/ETHPy150Open quantmind/pulsar/pulsar/apps/pulse/__init__.py/Wsgi.setup |
6,178 | def bump_nofile_limit():
from twisted.python import log
log.msg("Open files limit: %d" % resource.getrlimit(resource.RLIMIT_NOFILE)[0])
soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
values_to_try = [v for v in [hard, 100000, 10000] if v > soft]
for new_soft in values_to_try:
try:
... | ValueError | dataset/ETHPy150Open scrapinghub/splash/splash/server.py/bump_nofile_limit |
6,179 | def get_algorithm(algorithm):
"""Returns the wire format string and the hash module to use for the
specified TSIG algorithm
@rtype: (string, hash constructor)
@raises NotImplementedError: I{algorithm} is not supported
"""
hashes = {}
try:
import hashlib
hashes[dns.name.from... | ImportError | dataset/ETHPy150Open catap/namebench/nb_third_party/dns/tsig.py/get_algorithm |
6,180 | def __init__(self, request, model, list_display, list_display_links, list_filter, date_hierarchy, search_fields, list_select_related, list_per_page, list_editable, model_admin):
self.model = model
self.opts = model._meta
self.lookup_opts = self.opts
self.root_query_set = model_admin.quer... | ValueError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/contrib/admin/views/main.py/ChangeList.__init__ |
6,181 | def get_ordering(self):
lookup_opts, params = self.lookup_opts, self.params
# For ordering, first check the "ordering" parameter in the admin
# options, then check the object's default ordering. If neither of
# those exist, order descending by ID by default. Finally, look for
# m... | ValueError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/contrib/admin/views/main.py/ChangeList.get_ordering |
6,182 | def __next__(self):
if len(self.urls) == 0:
raise StopIteration
obj = self.load(self.urls.pop(0))
# make sure data is string type
if isinstance(obj, six.binary_type):
obj = obj.decode('utf-8')
elif not isinstance(obj, six.string_types):
raise... | ValueError | dataset/ETHPy150Open mission-liao/pyswagger/pyswagger/getter.py/Getter.__next__ |
6,183 | def _query(self, users, query_continue=None, properties=None):
params = {
'action': "query",
'list': "users"
}
params['ususers'] = self._items(users, type=str)
params['usprop'] = self._items(properties, levels=self.PROPERTIES)
if query_continue is not Non... | KeyError | dataset/ETHPy150Open mediawiki-utilities/python-mediawiki-utilities/mw/api/collections/users.py/Users._query |
6,184 | @register.filter
def get_choice_value(field):
try:
return dict(field.field.choices)[field.value()]
except __HOLE__:
return ', '.join([entry for id, entry in field.field.choices])
except KeyError:
return _('None') | TypeError | dataset/ETHPy150Open mayan-edms/mayan-edms/mayan/apps/appearance/templatetags/appearance_tags.py/get_choice_value |
6,185 | def test_infix_binops(self):
for ia, a in enumerate(candidates):
for ib, b in enumerate(candidates):
results = infix_results[(ia, ib)]
for op, res, ires in zip(infix_binops, results[0], results[1]):
if res is TE:
self.assert... | TypeError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_coercion.py/CoercionTest.test_infix_binops |
6,186 | def test_infinite_rec_classic_classes(self):
# if __coerce__() returns its arguments reversed it causes an infinite
# recursion for classic classes.
class Tester:
def __coerce__(self, other):
return other, self
exc = TestFailed("__coerce__() returning its arg... | RuntimeError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_coercion.py/CoercionTest.test_infinite_rec_classic_classes |
6,187 | def handle(self, project_name=None, target=None, *args, **options):
if project_name is None:
raise CommandError("you must provide a project name")
# Check that the project_name cannot be imported.
try:
import_module(project_name)
except __HOLE__:
pass... | ImportError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/core/management/commands/startproject.py/Command.handle |
6,188 | def __repr__(self):
if isinstance(self.packet, str):
try:
return self.raw()
except __HOLE__:
return str(self.packet)
else:
return str(self.packet) | TypeError | dataset/ETHPy150Open kisom/pypcapfile/pcapfile/structs.py/pcap_packet.__repr__ |
6,189 | def plot_2d_separator(classifier, X, fill=False, ax=None, eps=None):
if eps is None:
eps = X.std() / 2.
x_min, x_max = X[:, 0].min() - eps, X[:, 0].max() + eps
y_min, y_max = X[:, 1].min() - eps, X[:, 1].max() + eps
xx = np.linspace(x_min, x_max, 100)
yy = np.linspace(y_min, y_max, 100)
... | AttributeError | dataset/ETHPy150Open amueller/nyu_ml_lectures/plots/plot_2d_separator.py/plot_2d_separator |
6,190 | def process_response(self, request, response):
"""
If request.secure_session was modified, or if the configuration is to
save the session every time, save the changes and set a session cookie.
"""
if not (request.is_secure() or settings.DEBUG_SECURE):
return ... | AttributeError | dataset/ETHPy150Open mollyproject/mollyproject/molly/auth/middleware.py/SecureSessionMiddleware.process_response |
6,191 | def get(self, url):
"""Return the document contents pointed to by an HTTPS URL.
If something goes wrong (404, timeout, etc.), raise ExpectedError.
"""
try:
return self._opener.open(url).read()
except (__HOLE__, IOError) as exc:
raise ExpectedError("Could... | HTTPError | dataset/ETHPy150Open letsencrypt/letsencrypt/letsencrypt-auto-source/pieces/fetch.py/HttpsGetter.get |
6,192 | def save(filename=None, family='ipv4'):
'''
Save the current in-memory rules to disk
CLI Example:
.. code-block:: bash
salt '*' nftables.save /etc/nftables
'''
if _conf() and not filename:
filename = _conf()
nft_families = ['ip', 'ip6', 'arp', 'bridge']
rules = "#! nf... | OSError | dataset/ETHPy150Open saltstack/salt/salt/modules/nftables.py/save |
6,193 | def getSRegNS(message):
"""Extract the simple registration namespace URI from the given
OpenID message. Handles OpenID 1 and 2, as well as both sreg
namespace URIs found in the wild, as well as missing namespace
definitions (for OpenID 1)
@param message: The OpenID message from which to parse simpl... | KeyError | dataset/ETHPy150Open CollabQ/CollabQ/openid/extensions/sreg.py/getSRegNS |
6,194 | def parseExtensionArgs(self, args, strict=False):
"""Parse the unqualified simple registration request
parameters and add them to this object.
This method is essentially the inverse of
C{L{getExtensionArgs}}. This method restores the serialized simple
registration request fields... | ValueError | dataset/ETHPy150Open CollabQ/CollabQ/openid/extensions/sreg.py/SRegRequest.parseExtensionArgs |
6,195 | def _cast(self, value):
# Many status variables are integers or floats but SHOW GLOBAL STATUS
# returns them as strings
try:
value = int(value)
except ValueError:
try:
value = float(value)
except __HOLE__:
pass
... | ValueError | dataset/ETHPy150Open adamchainz/django-mysql/django_mysql/status.py/BaseStatus._cast |
6,196 | def __init__(self, **kwargs):
try:
self.message = self.msg_fmt % kwargs
except __HOLE__:
exc_info = sys.exc_info()
log.exception(_('Exception in string format operation: %s')
% exc_info[1])
if TOSCAException._FATAL_EXCEPTION_FORM... | KeyError | dataset/ETHPy150Open openstack/tosca-parser/toscaparser/common/exception.py/TOSCAException.__init__ |
6,197 | def __init__(self, name, schema_dict):
self.name = name
if not isinstance(schema_dict, collections.Mapping):
msg = (_('Schema definition of "%(pname)s" must be a dict.')
% dict(pname=name))
ExceptionCollector.appendException(InvalidSchemaError(message=msg))
... | KeyError | dataset/ETHPy150Open openstack/tosca-parser/toscaparser/elements/constraints.py/Schema.__init__ |
6,198 | def __iter__(self):
for k in self.KEYS:
try:
self.schema[k]
except __HOLE__:
pass
else:
yield k | KeyError | dataset/ETHPy150Open openstack/tosca-parser/toscaparser/elements/constraints.py/Schema.__iter__ |
6,199 | def __splitTemplate(value, valueParams):
"""
Split string into plus-expression(s)
- patchParam: string node containing the placeholders
- valueParams: list of params to inject
"""
# Convert list with nodes into Python dict
# [a, b, c] => {0:a, 1:b, 2:c}
mapper = { pos: value for pos,... | KeyError | dataset/ETHPy150Open zynga/jasy/jasy/js/optimize/Translation.py/__splitTemplate |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.