Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
1,700 | @expose("peek-byte", [default(values.W_InputPort, None),
default(values.W_Fixnum, values.W_Fixnum.ZERO)],
simple=False)
def peek_byte(w_port, w_skip, env, cont):
try:
return do_peek(w_port, True, w_skip.value, env, cont)
except __HOLE__:
raise SchemeExce... | UnicodeDecodeError | dataset/ETHPy150Open samth/pycket/pycket/prims/input_output.py/peek_byte |
1,701 | @expose("file-size", [values.W_Object])
def file_size(obj):
if not is_path_string(obj):
raise SchemeException("file-size: expected path string")
path = extract_path(obj)
try:
size = os.path.getsize(path)
except __HOLE__:
raise SchemeException("file-size: file %s does not exists" ... | OSError | dataset/ETHPy150Open samth/pycket/pycket/prims/input_output.py/file_size |
1,702 | def WaitFor(condition, timeout):
"""Waits for up to |timeout| secs for the function |condition| to return True.
Polling frequency is (elapsed_time / 10), with a min of .1s and max of 5s.
Returns:
Result of |condition| function (if present).
"""
min_poll_interval = 0.1
max_poll_interval = 5
output_in... | IOError | dataset/ETHPy150Open chromium/web-page-replay/util.py/WaitFor |
1,703 | def _resolve_refs(self, rule_map, expr, done):
"""Return an expression with all its lazy references recursively
resolved.
Resolve any lazy references in the expression ``expr``, recursing into
all subexpressions.
:arg done: The set of Expressions that have already been or are
... | KeyError | dataset/ETHPy150Open erikrose/parsimonious/parsimonious/grammar.py/RuleVisitor._resolve_refs |
1,704 | def _RemoveV4Ending(addr_string):
"""Replace v4 endings with v6 equivalents."""
match = V4_ENDING.match(addr_string)
if match:
ipv4_addr = ".".join(match.groups()[1:])
try:
socket.inet_aton(ipv4_addr)
except (socket.error, __HOLE__):
raise socket.error("Illegal IPv4 extension: %s" % addr_... | ValueError | dataset/ETHPy150Open google/grr/grr/lib/ipv6_utils.py/_RemoveV4Ending |
1,705 | def InetAtoN(addr_string):
"""Convert ipv6 string to packed bytes.
Args:
addr_string: IPv6 address string
Returns:
bytestring representing address
Raises:
socket.error: on bad IPv6 address format
"""
if not addr_string:
raise socket.error("Empty address string")
if BAD_SINGLE_COLON.match... | TypeError | dataset/ETHPy150Open google/grr/grr/lib/ipv6_utils.py/InetAtoN |
1,706 | def test_fminbound_scalar(self):
try:
optimize.fminbound(self.fun, np.zeros((1, 2)), 1)
self.fail("exception not raised")
except __HOLE__ as e:
assert_('must be scalar' in str(e))
x = optimize.fminbound(self.fun, 1, np.array(5))
assert_allclose(x, sel... | ValueError | dataset/ETHPy150Open scipy/scipy/scipy/optimize/tests/test_optimize.py/TestOptimizeScalar.test_fminbound_scalar |
1,707 | def get_collection(self, request):
"""
Encapsulates collection name.
"""
try:
# If no owner is specified in the request, we use the default from settings for now
# moving forward, we'll want to remove this fallback and require that the owner is specified
... | AttributeError | dataset/ETHPy150Open HumanDynamics/openPDS/openpds/tastypie_mongodb/resources.py/MongoDBResource.get_collection |
1,708 | def undo(self):
"""
Undo the previous command
:raises: IndexError, if there are no objects to undo
"""
try:
c = self._command_stack.pop()
logging.getLogger(__name__).debug("Undo %s", c)
except __HOLE__:
raise IndexError("No commands to... | IndexError | dataset/ETHPy150Open glue-viz/glue/glue/core/command.py/CommandStack.undo |
1,709 | def redo(self):
"""
Redo the previously-undone command
:raises: IndexError, if there are no undone actions
"""
try:
c = self._undo_stack.pop()
logging.getLogger(__name__).debug("Undo %s", c)
except __HOLE__:
raise IndexError("No comman... | IndexError | dataset/ETHPy150Open glue-viz/glue/glue/core/command.py/CommandStack.redo |
1,710 | def get_active_window_id(self):
out = getoutput("xprop -root _NET_ACTIVE_WINDOW")
try:
win_id = out.split('#')[-1].split(',')[0].strip()
except __HOLE__:
return None
return win_id | ValueError | dataset/ETHPy150Open generalov/look-at/look_at/wmctrl.py/WmCtrl.get_active_window_id |
1,711 | @property
def wm_window_role(self):
if not self.window_role:
out = getoutput('xprop -id %s WM_WINDOW_ROLE' % self.id)
try:
_, value = out.split(' = ')
except __HOLE__:
# probably xprop returned an error
return ''
... | ValueError | dataset/ETHPy150Open generalov/look-at/look_at/wmctrl.py/Window.wm_window_role |
1,712 | def run(self):
po_files = []
if not self.output_file:
if self.locale:
po_files.append((self.locale,
os.path.join(self.output_dir, self.locale,
'LC_MESSAGES',
... | OSError | dataset/ETHPy150Open python-babel/babel/babel/messages/frontend.py/update_catalog.run |
1,713 | def is_middleware_class(middleware_class, middleware_path):
try:
middleware_cls = import_string(middleware_path)
except __HOLE__:
return
return issubclass(middleware_cls, middleware_class) | ImportError | dataset/ETHPy150Open django-debug-toolbar/django-debug-toolbar/debug_toolbar/settings.py/is_middleware_class |
1,714 | @classmethod
def from_node(cls, member, data):
blob = json.loads(data)
additional_endpoints = blob.get('additionalEndpoints')
if additional_endpoints is None:
raise ValueError("Expected additionalEndpoints in member data")
service_endpoint = blob.get('serviceEndpoint')
if service_endpoint is... | ValueError | dataset/ETHPy150Open steveniemitz/scales/scales/loadbalancer/zookeeper.py/Member.from_node |
1,715 | def run(self, mapping):
"""
generated_filename will return a filename similar to this:
`20101107__wa__general__precinct.csv`
election will return a filename similar to this:
`20101102__wa__general__precinct`
"""
generated_filename = mapping['generated_f... | IOError | dataset/ETHPy150Open openelections/openelections-core/openelex/us/wa/load.py/LoadResults.run |
1,716 | def normalize_district(header, office, row):
"""
Example of what we had before:
'district': '{0} {1}'.format(
self.district_offices[normalize_races(sh_val)],
"".join(map(str, [int(s) for s in sh_val.strip() if s.isdigit()][:2])
))})
normalize_district now provides a more standa... | IndexError | dataset/ETHPy150Open openelections/openelections-core/openelex/us/wa/load.py/normalize_district |
1,717 | def load(self):
self._common_kwargs = self._build_common_election_kwargs()
self._common_kwargs['reporting_level'] = 'precinct'
results = []
with self._file_handle as csvfile:
party_flag = 0
district_flag = 0
reader = unicodecsv.DictReader(
... | IndexError | dataset/ETHPy150Open openelections/openelections-core/openelex/us/wa/load.py/WALoaderPrecincts.load |
1,718 | def load(self):
with self._file_handle as csvfile:
results = []
reader = unicodecsv.DictReader(csvfile, encoding='latin-1',
delimiter=',')
self.header = [x.replace('"', '') for x in reader.fieldnames]
try:
... | IndexError | dataset/ETHPy150Open openelections/openelections-core/openelex/us/wa/load.py/WALoaderPre2007.load |
1,719 | def _prep_county_results(self, row):
"""
In Washington our general results are reported by county instead
of precinct, although precinct-level vote tallies are available.
"""
kwargs = self._base_kwargs(row)
county = str(row['jurisdiction'])
kwargs.update({
... | KeyError | dataset/ETHPy150Open openelections/openelections-core/openelex/us/wa/load.py/WALoaderPre2007._prep_county_results |
1,720 | def load(self):
self._common_kwargs = self._build_common_election_kwargs()
self._common_kwargs['reporting_level'] = 'county'
results = []
with self._file_handle as csvfile:
district_flag = 0
reader = unicodecsv.DictReader(
csvfile, encoding='lati... | KeyError | dataset/ETHPy150Open openelections/openelections-core/openelex/us/wa/load.py/WALoaderPost2007.load |
1,721 | def _build_contest_kwargs(self, row):
"""
if 'County' in self.reader.fieldnames:
jurisdiction = row['County']
else:
jurisdiction = row['JurisdictionName']
The above is the same as the code below, except a try/catch is quicker
than an if/else statement. Pl... | KeyError | dataset/ETHPy150Open openelections/openelections-core/openelex/us/wa/load.py/WALoaderPost2007._build_contest_kwargs |
1,722 | def load(self):
xlsfile = xlrd.open_workbook(self._xls_file_path)
self._common_kwargs = self._build_common_election_kwargs()
# Set the correct reporting level based on file name
if 'precinct' in self.mapping['generated_filename']:
reporting_level = 'precinct'
else:
... | IndexError | dataset/ETHPy150Open openelections/openelections-core/openelex/us/wa/load.py/WALoaderExcel.load |
1,723 | def distance(self, v1, v2):
""" Returns the cached distance between two vectors.
"""
try:
# Two Vector objects for which the distance was already calculated.
d = self._cache[(v1.id, v2.id)]
except KeyError:
# Two Vector objects for which the distance h... | AttributeError | dataset/ETHPy150Open clips/pattern/pattern/vector/__init__.py/DistanceMap.distance |
1,724 | def hierarchical(vectors, k=1, iterations=1000, distance=COSINE, **kwargs):
""" Returns a Cluster containing k items (vectors or clusters with nested items).
With k=1, the top-level cluster contains a single cluster.
"""
id = sequence()
features = kwargs.get("features", _features(vectors))
... | KeyError | dataset/ETHPy150Open clips/pattern/pattern/vector/__init__.py/hierarchical |
1,725 | def get(self, option):
try:
stdout, stderr = subprocess.Popen(
[self.cmd, option],
stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
except __HOLE__ as ex:
# e.g., [Errno 2] No such file or directory
raise OSError("Could not... | OSError | dataset/ETHPy150Open Toblerity/Shapely/setup.py/GEOSConfig.get |
1,726 | def test_assertEqual_incomparable(self):
apple = MockEquality('apple')
orange = ['orange']
try:
self.assertEqual(apple, orange)
except self.failureException:
self.fail("Fail raised when ValueError ought to have been raised.")
except __HOLE__:
#... | ValueError | dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/trial/test/test_assertions.py/TestSynchronousAssertions.test_assertEqual_incomparable |
1,727 | def test_failUnlessRaises_unexpected(self):
try:
self.failUnlessRaises(ValueError, self._raiseError, TypeError)
except __HOLE__:
self.fail("failUnlessRaises shouldn't re-raise unexpected "
"exceptions")
except self.failureException:
# wha... | TypeError | dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/trial/test/test_assertions.py/TestSynchronousAssertions.test_failUnlessRaises_unexpected |
1,728 | def test_skew(self):
try:
from scipy.stats import skew
except __HOLE__:
raise nose.SkipTest("no scipy.stats.skew")
def this_skew(x):
if len(x) < 3:
return np.nan
return skew(x, bias=False)
self._check_stat_op('skew', this_s... | ImportError | dataset/ETHPy150Open pydata/pandas/pandas/tests/test_panel4d.py/SafeForLongAndSparse.test_skew |
1,729 | def build_file_response(path,
cache_timeout=None,
cached_modify_time=None,
mimetype=None,
default_text_mime=DEFAULT_TEXT_MIME,
default_binary_mime=DEFAULT_BINARY_MIME,
file_wra... | OSError | dataset/ETHPy150Open mahmoud/clastic/clastic/static.py/build_file_response |
1,730 | def get_file_response(self, path, request):
try:
if not isinstance(path, basestring):
path = '/'.join(path)
full_path = find_file(self.search_paths, path)
if full_path is None:
raise NotFound(is_breaking=False)
except (__HOLE__, IOError... | ValueError | dataset/ETHPy150Open mahmoud/clastic/clastic/static.py/StaticApplication.get_file_response |
1,731 | def _get_msg(self, msgid, lc):
"""Get message identified by msgid in a specific locale.
:param: msgid (string) the identifier of a string.
:param: lc (string) the locale.
:return: (string) the message from the .po file.
"""
# obtain the content in the proper language
... | IOError | dataset/ETHPy150Open TheTorProject/gettor/gettor/smtp.py/SMTP._get_msg |
1,732 | def _send_email(self, from_addr, to_addr, subject, msg, attach=None):
"""Send an email.
Take a 'from' and 'to' addresses, a subject and the content, creates
the email and send it.
:param: from_addr (string) the address of the sender.
:param: to_addr (string) the address of the ... | IOError | dataset/ETHPy150Open TheTorProject/gettor/gettor/smtp.py/SMTP._send_email |
1,733 | def getattrd(obj, name, default=sentinel):
"""
Same as getattr(), but allows dot notation lookup
Source: http://stackoverflow.com/a/14324459
"""
try:
return functools.reduce(getattr, name.split("."), obj)
except __HOLE__ as e:
if default is not sentinel:
return defaul... | AttributeError | dataset/ETHPy150Open singingwolfboy/flask-dance/flask_dance/utils.py/getattrd |
1,734 | def main(options, args):
logger = log.get_logger(name="mosaic", options=options)
img_mosaic = mosaic(logger, args, fov_deg=options.fov)
if options.outfile:
outfile = options.outfile
io_fits.use('astropy')
logger.info("Writing output to '%s'..." % (outfile))
try:
... | OSError | dataset/ETHPy150Open ejeschke/ginga/ginga/util/mosaic.py/main |
1,735 | def get_params(config_filename):
params = KeeperParams()
params.config_filename = 'config.json'
if config_filename:
params.config_filename = config_filename
try:
with open(params.config_filename) as config_file:
try:
params.config = json.load(config_file)
... | IOError | dataset/ETHPy150Open Keeper-Security/Commander/keepercommander/cli.py/get_params |
1,736 | def loop(params):
display.welcome()
try:
while not params.user:
params.user = getpass.getpass(prompt='User(Email): ', stream=None)
# only prompt for password when no device token
while not params.password:
params.password = getpass.getpass(prompt='Password... | KeyboardInterrupt | dataset/ETHPy150Open Keeper-Security/Commander/keepercommander/cli.py/loop |
1,737 | def run(self):
_clean.run(self)
import fnmatch
# kill temporary files
patterns = [
# generic tempfiles
'*~', '*.bak', '*.pyc',
# tempfiles generated by ANTLR runs
't[0-9]*Lexer.py', 't[0-9]*Parser.py',
'*.tokens', '*_... | OSError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/antlr3/setup.py/clean.run |
1,738 | def __call__(self, func):
try:
http_methods = getattr(func, "__http_methods__")
except __HOLE__:
http_methods = []
setattr(func, "__http_methods__", http_methods)
http_methods.append((self.method, self.path,))
return func | AttributeError | dataset/ETHPy150Open google/grr/grr/gui/api_call_router.py/Http.__call__ |
1,739 | def prompt(text='choice> '):
try:
# python 2
got = raw_input(text)
except __HOLE__:
# python 3
got = input(text)
return got | NameError | dataset/ETHPy150Open captin411/ofxclient/ofxclient/cli.py/prompt |
1,740 | def predict_proba(self, X):
"""Predict class probabilities for X.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
Raises
------
AttributeError
If the ``loss`` does not support probabilities.
... | AttributeError | dataset/ETHPy150Open scikit-learn/scikit-learn/sklearn/ensemble/gradient_boosting.py/GradientBoostingClassifier.predict_proba |
1,741 | def staged_predict_proba(self, X):
"""Predict class probabilities at each stage for X.
This method allows monitoring (i.e. determine error on testing set)
after each stage.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input sam... | AttributeError | dataset/ETHPy150Open scikit-learn/scikit-learn/sklearn/ensemble/gradient_boosting.py/GradientBoostingClassifier.staged_predict_proba |
1,742 | def get_theme(themeId):
try:
theme = Theme.objects.get(id=themeId)
except __HOLE__:
return None
return {
'id': theme.id,
'name': theme.name,
'downloads': theme.downloads,
'author': theme.author,
'website': theme.website,
'comment': theme.comme... | ObjectDoesNotExist | dataset/ETHPy150Open y-a-r-g/idea-color-themes/backend/logic/themes/themes.py/get_theme |
1,743 | def get_theme_archive(themeId):
try:
theme = Theme.objects.get(id=themeId)
except __HOLE__:
return None, None
theme.downloads = int(theme.downloads) + 1
theme.save()
if theme.archive:
data = theme.archive.read()
else:
data = serialize_to_idea_lines(deserialize_f... | ObjectDoesNotExist | dataset/ETHPy150Open y-a-r-g/idea-color-themes/backend/logic/themes/themes.py/get_theme_archive |
1,744 | def allow_download_all(token_value):
dateLimit = (datetime.now() + timedelta(days=1)).date()
if token_value:
try:
ShoppingToken.objects.get(value=token_value, date__lte=dateLimit, payed=True)
return True
except __HOLE__:
pass
return False | ObjectDoesNotExist | dataset/ETHPy150Open y-a-r-g/idea-color-themes/backend/logic/themes/themes.py/allow_download_all |
1,745 | def import_theme(themeId):
try:
url = 'http://eclipsecolorthemes.org/?view=empty&action=download&theme=%s&type=xml'
response = urllib2.urlopen(url % themeId)
xml = response.read()
descr, elements = deserialize_from_eclipse_color_theme_xml(
xml.replace('\r', '').split('\n'... | ObjectDoesNotExist | dataset/ETHPy150Open y-a-r-g/idea-color-themes/backend/logic/themes/themes.py/import_theme |
1,746 | def json_publish(self, queue_name, body):
try:
return self.publish(queue_name, ujson.dumps(body))
except (__HOLE__, pika.exceptions.AMQPConnectionError):
self.log.warning("Failed to send to rabbitmq, trying to reconnect and send again")
self._reconnect()
... | AttributeError | dataset/ETHPy150Open zulip/zulip/zerver/lib/queue.py/SimpleQueueClient.json_publish |
1,747 | def _get_fullPrice(self):
""" Get price based on parent ConfigurableProduct """
# allow explicit setting of prices.
#qty_discounts = self.price_set.exclude(expires__isnull=False, expires__lt=datetime.date.today()).filter(quantity__lte=1)
try:
qty_discounts = Price.objects.fil... | AttributeError | dataset/ETHPy150Open dokterbob/satchmo/satchmo/apps/product/modules/configurable/models.py/ProductVariation._get_fullPrice |
1,748 | def _repr(self, value, pos):
__traceback_hide__ = True
try:
if value is None:
return ''
if self._unicode:
try:
value = six.text_type(value)
except __HOLE__:
value = str(value)
else... | UnicodeDecodeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Paste-2.0.1/paste/util/template.py/Template._repr |
1,749 | def __getattr__(self, name):
try:
return self[name]
except __HOLE__:
raise AttributeError(name) | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Paste-2.0.1/paste/util/template.py/bunch.__getattr__ |
1,750 | def __getitem__(self, key):
if 'default' in self:
try:
return dict.__getitem__(self, key)
except __HOLE__:
return dict.__getitem__(self, 'default')
else:
return dict.__getitem__(self, key) | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Paste-2.0.1/paste/util/template.py/bunch.__getitem__ |
1,751 | def deploy_index():
"""
Custom module homepage for deploy (=RIT) to display online
documentation for the module
"""
response = current.response
def prep(r):
default_url = URL(f="mission", args="summary", vars={})
return current.s3db.cms_documentation(r, "RIT", default_u... | IOError | dataset/ETHPy150Open sahana/eden/modules/templates/RMSAmericas/controllers.py/deploy_index |
1,752 | def _validate_format(self, parser, format_dict):
"""
Validates the given format dictionary. Each key of this dict refers to a specific BBCode placeholder type.
eg. {TEXT} or {TEXT1} refer to the 'TEXT' BBCode placeholder type.
Each content is validated according to its associated placeho... | KeyError | dataset/ETHPy150Open ellmetha/django-precise-bbcode/precise_bbcode/bbcode/tag.py/BBCodeTag._validate_format |
1,753 | @app.route("/<topic>/", methods=["GET", "POST"])
@app.route("/<topic>/<group_or_key>/", methods=["GET", "POST"])
def flasfka(topic, group_or_key=None):
topic = topic.encode("utf-8")
if group_or_key is not None:
group_or_key = group_or_key.encode("utf-8")
client = get_kafka_client()
client.ensur... | KeyError | dataset/ETHPy150Open travel-intelligence/flasfka/flasfka/api.py/flasfka |
1,754 | def get_env_var(name, default=None):
value = _get_env_var_from_java(name)
if value is not None:
return value
try:
value = os.environ[_encode(name)]
except __HOLE__:
return default
else:
return _decode(value) | KeyError | dataset/ETHPy150Open shellderp/sublime-robot-plugin/lib/robot/utils/robotenv.py/get_env_var |
1,755 | def irm(ip,arg):
""" irm path[s]...
Remove file[s] or dir[s] path. Dirs are deleted recursively.
"""
try:
paths = mglob.expand(arg.split(None,1)[1])
except __HOLE__:
raise UsageError("%irm paths...")
import distutils.dir_util
for p in paths:
print("rm",p)
... | IndexError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/quarantine/ipy_fsops.py/irm |
1,756 | def collect(ip,arg):
""" collect foo/a.txt rec:bar=*.py
Copies foo/a.txt to ~/_ipython/collect/foo/a.txt and *.py from bar,
likewise
Without args, try to open ~/_ipython/collect dir (in win32 at least).
"""
from IPython.external.path import path
basedir = path(ip.ipython_dir + '/co... | IndexError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/quarantine/ipy_fsops.py/collect |
1,757 | def inote(ip,arg):
""" inote Hello world
Adds timestamp and Hello world to ~/_ipython/notes.txt
Without args, opens notes.txt for editing.
"""
import time
fname = ip.ipython_dir + '/notes.txt'
try:
entry = " === " + time.asctime() + ': ===\n' + arg.split(None,1)[1] + '... | IndexError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/quarantine/ipy_fsops.py/inote |
1,758 | def _getMigration(major):
try:
ret = sys.modules[__name__].__dict__['MigrateTo_' + str(major)]
except __HOLE__:
return None
return ret
# return the last major.minor version for a given major | KeyError | dataset/ETHPy150Open sassoftware/conary/conary/server/migrate.py/_getMigration |
1,759 | def __getitem__(self, key):
try:
return getattr(self, key)
except __HOLE__ as exc:
raise KeyError(exc.message) | AttributeError | dataset/ETHPy150Open mozilla/elasticutils/elasticutils/__init__.py/FacetResult.__getitem__ |
1,760 | def to_python(self, obj):
"""Converts strings in a data structure to Python types
It converts datetime-ish things to Python datetimes.
Override if you want something different.
:arg obj: Python datastructure
:returns: Python datastructure with strings converted to
... | ValueError | dataset/ETHPy150Open mozilla/elasticutils/elasticutils/__init__.py/PythonMixin.to_python |
1,761 | def __repr__(self):
try:
return '<S {0}>'.format(repr(self.build_search()))
except __HOLE__:
# This can happen when you're debugging build_search() and
# try to repr the instance you're calling it on. Then that
# calls build_search() and CLOWN SHOES!
... | RuntimeError | dataset/ETHPy150Open mozilla/elasticutils/elasticutils/__init__.py/S.__repr__ |
1,762 | def __init__(self, application_name=None, icon=None, host=None,
password=None, record_limit=None, record_delta=None,
level=NOTSET, filter=None, bubble=False):
NotificationBaseHandler.__init__(self, application_name, record_limit,
record_... | ImportError | dataset/ETHPy150Open getlogbook/logbook/logbook/notifiers.py/GrowlHandler.__init__ |
1,763 | def __init__(self, application_name=None, icon=None, no_init=False,
record_limit=None, record_delta=None, level=NOTSET,
filter=None, bubble=False):
NotificationBaseHandler.__init__(self, application_name, record_limit,
record_delta, leve... | ImportError | dataset/ETHPy150Open getlogbook/logbook/logbook/notifiers.py/LibNotifyHandler.__init__ |
1,764 | def set_notifier_icon(self, notifier, icon):
"""Used to attach an icon on a notifier object."""
try:
from gtk import gdk
except __HOLE__:
# TODO: raise a warning?
raise RuntimeError('The gtk.gdk module is required to set an icon.')
if icon is not None... | ImportError | dataset/ETHPy150Open getlogbook/logbook/logbook/notifiers.py/LibNotifyHandler.set_notifier_icon |
1,765 | def __init__(self, application_name=None, username=None, secret=None,
record_limit=None, record_delta=None, level=NOTSET,
filter=None, bubble=False, hide_level=False):
try:
import notifo
except __HOLE__:
raise RuntimeError(
'The n... | ImportError | dataset/ETHPy150Open getlogbook/logbook/logbook/notifiers.py/NotifoHandler.__init__ |
1,766 | def parse_body(self):
try:
js = json.loads(self.body)
if js[js.keys()[0]]['response_type'] == "ERROR":
raise RimuHostingException(
js[js.keys()[0]]['human_readable_message']
)
return js[js.keys()[0]]
except __HOLE__:... | ValueError | dataset/ETHPy150Open secondstory/dewpoint/libcloud/drivers/rimuhosting.py/RimuHostingResponse.parse_body |
1,767 | def iter_fields(node):
"""
Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
that is present on *node*.
"""
for field in node._fields:
try:
yield field, getattr(node, field)
except __HOLE__:
pass | AttributeError | dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/ast.py/iter_fields |
1,768 | def GetArgsClass(self):
try:
return rdfvalue.RDFValue.GetPlugin(self.type)
except __HOLE__:
raise ValueError("No class found for type %s." % self.type) | KeyError | dataset/ETHPy150Open google/grr/grr/gui/api_call_handler_utils.py/ApiDataObjectKeyValuePair.GetArgsClass |
1,769 | def _qtactor_run(self):
self.process_start()
self.process()
# get gen_process generator
try:
self._qtactor_gen = self.gen_process()
except __HOLE__:
self._qtactor_gen = None
# do first step
if self._qtactor_gen:
self._qtactor_st... | AttributeError | dataset/ETHPy150Open sparkslabs/guild/guild/qtactor.py/QtActorMixin._qtactor_run |
1,770 | def _qtactor_step(self):
try:
self._qtactor_gen.next()
except __HOLE__:
self._qtactor_gen = None
return
# trigger next step
QtCore.QCoreApplication.postEvent(
self, QtCore.QEvent(self._qtactor_step_event),
QtCore.Qt.LowEventPrio... | StopIteration | dataset/ETHPy150Open sparkslabs/guild/guild/qtactor.py/QtActorMixin._qtactor_step |
1,771 | def _set_cloexec(fd):
try:
flags = _fcntl.fcntl(fd, _fcntl.F_GETFD, 0)
except __HOLE__:
pass
else:
# flags read successfully, modify
flags |= _fcntl.FD_CLOEXEC
_fcntl.fcntl(fd, _fcntl.F_SETFD, flags) | IOError | dataset/ETHPy150Open eBay/restcommander/play-1.2.4/python/Lib/tempfile.py/_set_cloexec |
1,772 | def _stat(fn):
try:
f = open(fn)
except __HOLE__:
raise _os.error
f.close() | IOError | dataset/ETHPy150Open eBay/restcommander/play-1.2.4/python/Lib/tempfile.py/_stat |
1,773 | def _candidate_tempdir_list():
"""Generate a list of candidate temporary directories which
_get_default_tempdir will try."""
dirlist = []
# First, try the environment.
for envname in 'TMPDIR', 'TEMP', 'TMP':
dirname = _os.getenv(envname)
if dirname: dirlist.append(dirname)
# F... | AttributeError | dataset/ETHPy150Open eBay/restcommander/play-1.2.4/python/Lib/tempfile.py/_candidate_tempdir_list |
1,774 | def _get_default_tempdir():
"""Calculate the default directory to use for temporary files.
This routine should be called exactly once.
We determine whether or not a candidate temp dir is usable by
trying to create and write to a file in that directory. If this
is successful, the test file is delet... | IOError | dataset/ETHPy150Open eBay/restcommander/play-1.2.4/python/Lib/tempfile.py/_get_default_tempdir |
1,775 | def _mkstemp_inner(dir, pre, suf, flags):
"""Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
names = _get_candidate_names()
for seq in xrange(TMP_MAX):
name = names.next()
file = _os.path.join(dir, pre + name + suf)
try:
fd = _os.open(file, flags, 0600... | OSError | dataset/ETHPy150Open eBay/restcommander/play-1.2.4/python/Lib/tempfile.py/_mkstemp_inner |
1,776 | def mkdtemp(suffix="", prefix=template, dir=None):
"""User-callable function to create and return a unique temporary
directory. The return value is the pathname of the directory.
Arguments are as for mkstemp, except that the 'text' argument is
not accepted.
The directory is readable, writable, an... | OSError | dataset/ETHPy150Open eBay/restcommander/play-1.2.4/python/Lib/tempfile.py/mkdtemp |
1,777 | def __repr__(self):
try:
name = self.Name()
except __HOLE__:
return '<%s at 0x%x>' % (self.__class__.__name__, id(self))
return '<%s %r at 0x%x>' % (self.__class__.__name__, name, id(self)) | NotImplementedError | dataset/ETHPy150Open adblockplus/gyp/pylib/gyp/xcodeproj_file.py/XCObject.__repr__ |
1,778 | def _XCKVPrint(self, file, tabs, key, value):
"""Prints a key and value, members of an XCObject's _properties dictionary,
to file.
tabs is an int identifying the indentation level. If the class'
_should_print_single_line variable is True, tabs is ignored and the
key-value pair will be followed by ... | TypeError | dataset/ETHPy150Open adblockplus/gyp/pylib/gyp/xcodeproj_file.py/XCObject._XCKVPrint |
1,779 | def onVariantPlaylist(self, playlist):
print "Found variant playlist."
masterPlaylist = HlsPlaylist()
masterPlaylist.version = playlist.version
for variant in playlist.variants:
subOutDir = self.outDir + str(variant.bandwidth)
print "Starting a sub hls-proxy for ... | OSError | dataset/ETHPy150Open Viblast/hls-proxy/hlsproxy.py/HlsProxy.onVariantPlaylist |
1,780 | @classmethod
def setupClass(cls):
global numpy
try:
import numpy
except __HOLE__:
raise SkipTest('NumPy not available.') | ImportError | dataset/ETHPy150Open networkx/networkx/networkx/algorithms/link_analysis/tests/test_pagerank.py/TestPageRank.setupClass |
1,781 | @classmethod
def setupClass(cls):
global scipy
try:
import scipy
except __HOLE__:
raise SkipTest('SciPy not available.') | ImportError | dataset/ETHPy150Open networkx/networkx/networkx/algorithms/link_analysis/tests/test_pagerank.py/TestPageRankScipy.setupClass |
1,782 | def resolveEntity(self, publicId, systemId):
source = InputSource()
source.setSystemId(systemId)
try:
dtdPath = self.knownDTDs[systemId]
except __HOLE__:
raise process.ProcessingFailure(
"Invalid DTD system identifier (%r) in %s. Only "
... | KeyError | dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/lore/tree.py/_LocalEntityResolver.resolveEntity |
1,783 | def parseFileAndReport(filename, _open=file):
"""
Parse and return the contents of the given lore XHTML document.
@type filename: C{str}
@param filename: The name of a file containing a lore XHTML document to
load.
@raise process.ProcessingFailure: When the contents of the specified file
c... | IOError | dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/lore/tree.py/parseFileAndReport |
1,784 | def __load():
import imp, os, sys
try:
dirname = os.path.dirname(__loader__.archive)
except __HOLE__:
dirname = sys.prefix
path = os.path.join(dirname, 'PyQt4.QtGui.pyd')
#print "py2exe extension module", __name__, "->", path
mod = imp.load_dynamic(__name__, path)
## mod.froze... | NameError | dataset/ETHPy150Open yasoob/youtube-dl-GUI/build/bdist.win-amd64/winexe/temp/PyQt4.QtGui.py/__load |
1,785 | def convert(self, s):
parts = TokenTranslator._BREAK_ON_RE.split(s)
parts_iter = iter(parts)
converted_parts = []
for part in parts_iter:
if part == '' or TokenTranslator._DELIMITER_RE.match(part):
converted_parts.append(part)
elif TokenTranslator._UPPER_CASE_RE.match(part):
... | StopIteration | dataset/ETHPy150Open pantsbuild/pants/src/python/pants/backend/jvm/tasks/jvm_compile/anonymizer.py/TokenTranslator.convert |
1,786 | def _db_value_for_elem(self, elem):
try:
return self._valid_lookup[elem]
except __HOLE__:
raise LookupError(
'"%s" is not among the defined enum values' % elem) | KeyError | dataset/ETHPy150Open zzzeek/sqlalchemy/lib/sqlalchemy/sql/sqltypes.py/Enum._db_value_for_elem |
1,787 | def _object_value_for_elem(self, elem):
try:
return self._object_lookup[elem]
except __HOLE__:
raise LookupError(
'"%s" is not among the defined enum values' % elem) | KeyError | dataset/ETHPy150Open zzzeek/sqlalchemy/lib/sqlalchemy/sql/sqltypes.py/Enum._object_value_for_elem |
1,788 | def random_image(field):
color1 = random_rgb()
color2 = random_rgb()
color3 = random_rgb()
color4 = random_rgb()
size = (random.randint(300, 900), random.randint(300, 900))
im = Image.new("RGB", size) # create the image
draw = ImageDraw.Draw(im) # create a drawing object that is
dr... | OSError | dataset/ETHPy150Open ccollins/milkman/milkman/generators.py/random_image |
1,789 | def get_volume_connector(self, instance):
"""Return volume connector information."""
if not self._initiator or not self._hypervisor_hostname:
stats = self.host_state.get_host_stats(refresh=True)
try:
self._initiator = stats['host_other-config']['iscsi_iqn']
... | TypeError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/virt/xenapi/driver.py/XenAPIDriver.get_volume_connector |
1,790 | def __init__(self):
self.statefile_path = os.path.join(sys.prefix, "pip-selfcheck.json")
# Load the existing state
try:
with open(self.statefile_path) as statefile:
self.state = json.load(statefile)
except (IOError, __HOLE__):
self.state = {} | ValueError | dataset/ETHPy150Open francelabs/datafari/windows/python/Lib/site-packages/pip/utils/outdated.py/VirtualenvSelfCheckState.__init__ |
1,791 | def __init__(self):
self.statefile_path = os.path.join(USER_CACHE_DIR, "selfcheck.json")
# Load the existing state
try:
with open(self.statefile_path) as statefile:
self.state = json.load(statefile)[sys.prefix]
except (IOError, ValueError, __HOLE__):
... | KeyError | dataset/ETHPy150Open francelabs/datafari/windows/python/Lib/site-packages/pip/utils/outdated.py/GlobalSelfCheckState.__init__ |
1,792 | def __init__(self,
pol,
src='any',
dst='any',
sport='any',
dport='any',
proto='any',
):
self.pol_obj = pol
self.proto = proto
# validate source port
if sport == 'any':
self.sport = sport
e... | ValueError | dataset/ETHPy150Open google/capirca/lib/aclcheck.py/AclCheck.__init__ |
1,793 | def notifyOnDeath(self, cb):
""" Method is used to forward 'notifyOnDeath' calls to the wrapped
object. It is used to register a callback which will be called
when the wrapped object died.
@param cb: Callback which should be registered. The
... | AttributeError | dataset/ETHPy150Open rapyuta/rce/rce-core/rce/core/wrapper.py/_Wrapper.notifyOnDeath |
1,794 | def dontNotifyOnDeath(self, cb):
""" Method is used to forward 'dontNotifyOnDeath' calls to the wrapped
object. It is used to unregister a callback which should have been
called when the wrapped object died.
@param cb: Callback which should be unregistered.
... | AttributeError | dataset/ETHPy150Open rapyuta/rce/rce-core/rce/core/wrapper.py/_Wrapper.dontNotifyOnDeath |
1,795 | def addInterface(self, iTag, iType, clsName):
""" Add an interface to the Robot object.
@param iTag: Tag which is used to identify the interface in
subsequent requests.
@type iTag: str
@param iType: Type of the interface.... | TypeError | dataset/ETHPy150Open rapyuta/rce/rce-core/rce/core/wrapper.py/Robot.addInterface |
1,796 | def removeInterface(self, iTag):
""" Remove an interface from the Robot object.
@param iTag: Tag which is used to identify the interface
which should be removed.
@type iTag: str
"""
try:
self._interfaces.pop(iTag... | KeyError | dataset/ETHPy150Open rapyuta/rce/rce-core/rce/core/wrapper.py/Robot.removeInterface |
1,797 | def getInterface(self, iTag):
""" Return the wrapped interface instance matching the given tag.
@param iTag: Tag which is used to identify the interface
which should be returned.
@type iTag: str
@return: Wrapped inte... | KeyError | dataset/ETHPy150Open rapyuta/rce/rce-core/rce/core/wrapper.py/Robot.getInterface |
1,798 | def removeNode(self, nTag):
""" Remove a node from the ROS environment inside the container.
@param nTag: Tag which is used to identify the ROS node
which should removed.
@type nTag: str
"""
try:
self._nodes.pop(... | KeyError | dataset/ETHPy150Open rapyuta/rce/rce-core/rce/core/wrapper.py/Container.removeNode |
1,799 | def removeParameter(self, name):
""" Remove a parameter from the ROS environment inside the container.
@param name: Name of the parameter which should be removed.
@type name: str
"""
try:
self._parameters.pop(name).destroy()
except __HO... | KeyError | dataset/ETHPy150Open rapyuta/rce/rce-core/rce/core/wrapper.py/Container.removeParameter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.